diff --git a/ACCEPTANCE.md b/ACCEPTANCE.md new file mode 100644 index 0000000..1a7ffbd --- /dev/null +++ b/ACCEPTANCE.md @@ -0,0 +1,82 @@ +# 1353 / P4 双向会话验收 + +**复验结论:宿主 `b0656f8` 通过两条主链、fork 隐藏卡片编辑和隔离环境串行全量测试(2053/2053)。** 默认并行全量仍有失败;人工未覆盖项见下文。未发布、未建立 CI。 + +## 版本与入口 + +macOS;Goldfish/gf 18.11.70,Python 3.14.7,Node v26.5.0。开工时三个工作副本均干净。插件从 `pigmagicfly/1353/plan-mode-core` 的 `7e4f645` 起步;插件 origin 无 main 引用。宿主 `../gfcode2` 的 `edb7ccf` 与 fetch 后的 `origin/main` 一致。Pi 源码基准 `fb0fe823539f6d04850f6e34748c01f01f212e1f`,实际运行安装包 v1.7.0 的 `dist/bundle/cli.js`,显式加载包内 `examples/extensions/plan-mode/index.ts` 和 `examples/extensions/questionnaire.ts`。RPC 模式可驱动选择/编辑,但不能展示 questionnaire 自定义 TUI。 + +安装复演从插件根的 bash 开始(均在临时 HOME/工作目录操作): + +```bash +plugin=$PWD; host=$(cd ../gfcode2 && pwd); d=$(mktemp -d); chmod 700 "$d" +mkdir -p "$d"/{home,work,empty,config} +printf '%s\n' '(import (scheme process-context) (liii pi app cli))' \ + '(exit (run-pi (command-line)))' > "$d/entry.scm" +includes=(); for x in app code agent ai gfsh bash highlight; do includes+=(-I "$host/$x"); done +gfpi() { HOME="$d/home" PI_BUILTIN_EXTENSIONS_DIR="$d/empty" PI_CODING_AGENT_DIR="$d/config" \ + gf "${includes[@]}" "$d/entry.scm" pi "$@"; } +cd "$d/work"; gfpi --help # 首行应显示 gfcode2,不能是 site-lisp 的旧版 +``` + +如需真实模型,仅在本机向 `$d/config` 放入所选 provider 的配置与凭据(本次只取 Google 的 `zai-org/glm-5.2-maas`,权限限制在当前用户,验证后删除)。先在无插件 TUI 运行,再 link;不要将该目录、日志或真实会话用作 fixture。 + +```bash +model=(--provider google --model zai-org/glm-5.2-maas --no-skills) +gfpi "${model[@]}" --session-dir "$d/host-session" '请用 questionnaire 询问颜色和尺寸,收到回答再总结。' +gfpi link --local "$plugin" +gfpi "${model[@]}" --plan --session-dir "$d/plan-session" '先用 questionnaire 询问选 A 还是 B,再给出三步计划。' +``` + +## 自动回放(不读用户配置) + +```bash +# 插件根;pkg 指向已安装的 v1.7.0 包,不需要安装 Python 依赖 +pkg="$(npm root -g)/@earendil-works/pi-coding-agent" +gf test; gf fmt --check; gf check +python3 tests/interop/replay.py ../gfcode2 "$pkg" +# 含 fork、压缩、隐藏卡片编辑;edb7ccf 可复现失败,b0656f8 通过 +python3 tests/interop/replay.py --check-fork ../gfcode2 "$pkg" +``` + +`replay.py` 依次启动真实客户端,模型由回环 HTTP 服务扮演。切换时保留前一端的条目列表,比较不变前缀、新条目 `parentId`、状态、线上工具定义和消息。`pi-1.7.0-one-of-three.jsonl` 是第一链中 Pi 写出的 19 行原始结构,含模型/thinking、标准问答、隐藏提示与 1/3 快照。仅替换临时 cwd 和包安装根为 `/project`、`/pi`;id、时间戳、类型和树边未改。输入是测试专用短句,无用户目录、凭据或私人会话。 + +| 场景 / 客户端 | 期望与实测 | 证据 | +|---|---|---| +| Pi → gf → Pi | Pi 真正调用 questionnaire,无 UI 返回 cancelled;三步 Execute 到 1/3。gf 请求含 1 个已勾选、2 个待办,恢复 write,问答文本与原 ID 匹配且无 details;追加第二步后 Pi status 为 2/3。 | 默认回放第一链 | +| gf → Pi → gf | gf 保存规划态,Pi 显示 plan,Refine 产生标准 user 并进入请求,两张清单、一次 Execute;三步完成后 gf 有 write、无旧 todo。 | 默认回放第二链 | +| 无插件读写 → 重装 | gf 卸下临时 link 后能续写且不产生 plan 快照;重装后接续 golden 的原进度,Pi 重开 2/3。 | 默认回放第三链 | +| 物理末行为旁支 / fork / compaction / context_edit | Pi SessionManager 从指定活动叶 fork;gf 保留 summary、完成第三步、原文件字节不变。`edb7ccf` 的请求仍是 `before amendment`;`b0656f8` 的请求与 Pi 均为 `after amendment`,旧文本不再投影。 | `--check-fork` 最后断言 | +| 隐藏和未知条目 | custom 状态不作为对话;custom_message 隐藏只控制显示。gf 执行态的请求仍含 Pi 较早的 `[PLAN MODE ACTIVE]`,同时有当前执行提示;勿假定所有旧约束都被过滤。未知条目等基础投影另见宿主窄回归,不推断所有扩展互通。 | 第一链、`session-projection`、`pi-extension-fixture-round-trip` | +| Execute/Stay/Refine、工具限制 | gf 队列在 `agent_end` 后按序处理 `send-message!`、`send-user-message!`,空编辑/取消不执行。规划只保留允许且原来可用的工具,退出恢复工具;不注册问卷、私有提问框或平行队列。 | 插件四项测试、宿主 `extension-end-follow-up` | + +## 人工 TUI(与回放分开) + +- **无 Plan 的 gf + GLM 5.2:**模型发起双题,Color 选第二项 Green,Size 选 Type something 输入 Medium,再提交。原 toolCallId 与结果相同,`answers` 分别为选项 index=2 和 `wasCustom:true`,`cancelled:false`;下一条助手消息总结了两项答案。 +- **link 后 gf + 同一模型:**`⏸ plan` 下选择 Sample B。标准 toolResult 匹配原调用,模型继续生成三步;选 Stay 后 `/todos` 显示三条未完成,`/plan` 清空并离开。关闭 gf 后,用 Pi TUI 离线打开同一会话副本,看到 `questionnaire 1 question (Sample)`、`✓ sample: 2. Sample B` 和后续计划。此步只验证**历史展示**,不是 Pi 发起新在线提问的证据。 +- **边界:**Pi RPC 无 UI 的真实 toolCall 不等于 Pi 产生悬而未决的调用、退出后由 gf TUI 接管。两端交接未验证进行中的问卷;没有把历史工具结果再执行一次。人工中断/取消后重开、无 session 的跨端恢复(本身无文件)、全平台快捷键、同一个多人/多进程会话并写都不列为已通过。 + +宿主问卷不依赖插件:worker 的 `questionnaire-port` 发送带 id、reply channel 和问题的事件给 TUI;TUI 交还答案或取消,worker 写普通 assistant/toolCall 与 toolResult,详情在 `message.details` 而不在模型请求。非交互用 `--tools +questionnaire` 显式打开,缺 UI 立即返回。Pi 读取历史是会话能力,新提问则需要已加载工具及 TUI。Plan 仅通过宿主扩展运行时的活动分支、状态追加、活动工具、UI 和消息调度接口工作。 + +## 参考宿主回归与工作量 + +```bash +cd ../gfcode2 +for t in extension-runtime extension-end-follow-up questionnaire-e2e questionnaire-branches; do + gf test "code/tests/e2e/$t-test.scm" || break +done +for t in session-manager session-projection custom-message-projection pi-extension-fixture-round-trip \ + append-session-entry-at-leaf parse-tools-selection-test.scm handle-questionnaire; do gf test "$t" || break; done +node code/tests/e2e/pi-session-extension-interop.mjs "$pkg" +gf fmt --check; gf check +gf test # 默认并行 +# 复验:不读个人技能和菜单,不受 /var 与 /private/var 的路径别名影响 +scratch=$(mktemp -d); scratch=$(cd "$scratch" && pwd -P); mkdir "$scratch/home" "$scratch/tmp" +HOME="$scratch/home" TMPDIR="$scratch/tmp" gf test --force -j 1 +``` + +以上窄测试、Node 互通、格式和静态检查均退出 0。插件四个测试逐个及 `gf test --force` 4/4,格式与静态检查退出 0。原始 `edb7ccf` 宿主全量:默认 **2009/2053,44 失败**;串行 **2043/2053,10 失败**(均退出 255)。串行剩余:skills/extension discovery、injected-chan、interactive-agent、pi-cli-e2e、app-thinking、app-queue、app-run-ctrl-d、app-resume-integration、app-menu。隔离 HOME 单跑 `pi-cli-e2e-test.scm` 仍有两项断言失败(退出码及项目上下文提示)。不将所有失败归因于并发,也不以窄回归代替完整通过。 + +宿主修正后,原失败投影测试由 6 个断言失败变为通过;五个修正入口的 e2e 逐个通过,隔离 HOME、物理 TMPDIR、`--force -j 1` 全量 **2053/2053**。另起隔离目录复验默认并行 `gf test --force` 仍为 **2026/2053,27 失败**(含间歇性库加载错误);不据此修改未涉及的运行时代码。 + +排除测试与 fixture 的独立非测试 A/D/N:P0 `c761750..51b1d1a` 124/34/+90;P1 `c0d080f..f71d765` 517/98/+419;P2 `920bacb..8ca9efb` 527/39/+488(不含中间无关主干改动);结束回调补充 `8ca9efb..edb7ccf` 86/34/+52。逐文件复核:将对应两个提交代入 `git diff --numstat BASE HEAD -- . ':(exclude,glob)**/tests/**' ':(exclude,glob)tests/**'`。本次宿主修复独立范围 `edb7ccf..b0656f8` 非测试 18/7/+11,全部在 `code/liii/pi/code/core/session-projection/context-edit.scm`。 diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..b87bf21 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,5 @@ +# 插件开发约定 + +- 运行时只通过 gfcode 扩展事件、活动工具、分支写入与 UI 接口操作;不复制宿主问卷或自行调度模型。 +- 改状态转换、解析或交互分支时,在 `tests/gfcode/plan-mode/` 先写可失败的用例。宿主依赖与命令见 `README.md`。 +- 测试不读用户配置、不联网。提交前运行 `gf fmt`、`gf fmt --check`、`gf check` 和 `gf test`。真实模型冒烟与单元测试分开,密钥和会话不入库。 diff --git a/README.md b/README.md new file mode 100644 index 0000000..e9753f1 --- /dev/null +++ b/README.md @@ -0,0 +1,41 @@ +# gfcode-plan-mode + +把“先讨论、确认后再修改”作为 gf pi 的一个会话模式。对照 Pi **v1.7.0** 的 `examples/extensions/plan-mode`;需要含结束回调续轮修正的 gfcode **`edb7ccf`**(两条基本交接链的最低验收基线);fork 后编辑隐藏卡片需要宿主修正 **`b0656f8`**。只安装同版本号的 Goldfish 并不保证 `gf pi` 加载了这份宿主代码。Plan Mode 只在会话内切换规划和执行,不实现 Blueprint 的阶段、依赖或验证门。当前未发布。 + +## 安装与使用 + +确认 `gf pi --help` 首行括号里的宿主路径指向上述版本;本地源码启动方式见[验收记录](ACCEPTANCE.md)。从需要规划的项目运行: + +```sh +gf pi link --local ~/git/gfcode-plan-mode +gf pi --plan +``` + +不加 `--local` 为用户级安装。`--plan` 从规划态开始;已有会话以当前活动分支最近的快照为准。`/plan` 手动切换并清空清单;`/todos` 查看进度。gf 没有扩展快捷键注册接口,请使用命令;Pi 原扩展支持 Ctrl+Alt+P。开发验证平台为 macOS,未验证 Windows/Linux TUI。 + +规划时只向模型暴露原工具中的已知只读工具、受限 bash 和内置 `questionnaire`。模型通过宿主问卷澄清需求:问题、取消、`toolResult.details` 和交互窗口均由 gfcode 提供。TUI 默认启用宿主问卷;非交互模式默认没有问卷,可显式 `--tools +questionnaire`;没有 UI 时不会等待用户。原本排除的工具不会被补回。Bash 只识别有限的命令和参数,组合命令各段都必须通过;这不是操作系统沙箱。 + +助手用 `Plan:` 和编号条目输出计划。**Execute** 恢复工具并自动启动执行;**Stay** 保留规划态等待下一条输入;**Refine** 以用户消息发送编辑后的非空补充。无 UI、取消、空编辑和无有效步骤均不自动执行。使用含 TUI 续轮结算修复的宿主时,Execute 期间输入框上方会显示与普通模式相同的 `Working` 动画,同时保留待办清单。完成或中止后动画消失,即使还有未完成的步骤。执行提示要求用 `[DONE:n]` 更新完成状态,最后一轮结算完成卡。 + +## 会话格式 + +沿活动叶使用 Pi v3 JSONL,不定义新 entry type。`custom/plan-mode` 不进入模型历史。下面是三个快照的 `data` 示例(不含会话 ID、路径、消息内容): + +```jsonl +{"enabled":false,"executing":false,"toolsBeforePlanMode":[],"todos":[]} +{"enabled":true,"executing":false,"toolsBeforePlanMode":["read","write"],"todos":[]} +{"enabled":false,"executing":true,"toolsBeforePlanMode":["read","write"],"todos":[{"step":1,"text":"Inspect README","completed":false}]} +``` + +`custom_message` 中的 `plan-todo-list` 是清单,`plan-mode-execute` 是执行边界,`plan-complete` 是完成卡。Refine 补充是 `message` / `role:user`,不是扩展卡片。gf 插件按当前状态注入系统提示,不把自身的提示存入历史。Pi 原扩展会保存隐藏的 `plan-mode-context`;gf 也会将它投影给模型,`display:false` **不**表示排除上下文。两条交接链及修正后的 fork 隐藏卡片投影均已实跑,详见[兼容矩阵与复现命令](ACCEPTANCE.md)。 + +## 本地验证 + +```sh +cd ~/git/gfcode-plan-mode +gf test +gf fmt --check +gf check +``` + +测试仅在需要宿主库时从同级 `../gfcode2` 加载,使用假模型和临时会话,不读真实凭据。问卷集成用例让模型调用宿主工具、检查相同 toolCallId 的回答、产生计划并执行到完成。另在临时 HOME 和临时工作目录中实测 `gf pi link --local` 与 Google `zai-org/glm-5.2-maas` 非交互生成计划;真实模型不属于测试依赖。 diff --git a/gf_fmt.json b/gf_fmt.json new file mode 100644 index 0000000..a02d1f8 --- /dev/null +++ b/gf_fmt.json @@ -0,0 +1 @@ +{"scheme":{"suffix":["scm"],"path":["gfcode/","tests/"]}} diff --git a/gfcode/plan-mode/index.scm b/gfcode/plan-mode/index.scm new file mode 100644 index 0000000..0a5606e --- /dev/null +++ b/gfcode/plan-mode/index.scm @@ -0,0 +1,50 @@ +(define-library (gfcode plan-mode index) + (export extension) + (import (scheme base) + (liii pi code core extensions) + (liii pi code cli args query) + (gfcode plan-mode lifecycle) + ) ;import + (begin + (define (extension api . ignored) + (let ((flag #f) (sessions '())) + (define (session ctx) + (cdr (assq ctx sessions)) + ) ;define + (define (command name description event) + (let ((handler + (lambda (args command-ctx) + ((session (cdr (assq 'extension-context command-ctx))) event args) + ) ;lambda + ) ;handler + ) ; + (for-each (lambda (n) + (register-command! api (make-extension-command-def n description handler)) + ) ;lambda + (list name (string-append "/" name)) + ) ;for-each + ) ;let + ) ;define + (register-flag! api + (make-extension-flag-def "--plan" "Start in read-only plan mode" :key 'plan) + ) ;register-flag! + (register-config-augmenter! api + (lambda (cfg parsed) (when parsed (set! flag (pi-args-ref parsed 'plan))) cfg) + ) ;register-config-augmenter! + (pi-on! api + 'session_start + (lambda (p ctx) + (set! sessions (cons (cons ctx (make-plan-session ctx flag)) sessions)) + ) ;lambda + ) ;pi-on! + (for-each + (lambda (event) (pi-on! api event (lambda (p ctx) ((session ctx) event p)))) + '(before_agent_start tool_call turn_end agent_end) + ) ;for-each + (command "plan" "Toggle planning mode" 'toggle) + (command "todos" "Show plan steps" 'todos) + "plan-mode-loaded" + ) ;let + ) ;define + ) ;begin +) ;define-library diff --git a/gfcode/plan-mode/lifecycle.scm b/gfcode/plan-mode/lifecycle.scm new file mode 100644 index 0000000..3b138c9 --- /dev/null +++ b/gfcode/plan-mode/lifecycle.scm @@ -0,0 +1,195 @@ +(define-library (gfcode plan-mode lifecycle) + (export make-plan-session) + (import (scheme base) + (liii list) + (liii string) + (liii json) + (liii pi code core extensions) + (gfcode plan-mode rules) + (gfcode plan-mode state) + ) ;import + (begin + (define (make-plan-session ctx flag) + (define (call key . args) + (apply (cdr (assq key (extension-context-extra ctx))) args) + ) ;define + (define (ui key . args) + (apply call 'ui key args) + ) ;define + (define (tools) + (call 'get-active-tools) + ) ;define + (define entries (call 'branch-entries)) + (define state (restore-state entries (tools) flag)) + (define (render!) + (ui 'status + "plan-mode" + (cond ((planning? state) "⏸ plan") + ((executing? state) + (format #f "📋 ~D/~D" (count cdr (todos state)) (length (todos state))) + ) ; + (else #f) + ) ;cond + ) ;ui + (ui 'widget "plan-mode" (and (executing? state) (todo-lines state))) + ) ;define + (define (commit! next) + (set! state next) + (call 'append-state! "plan-mode" (snapshot state)) + (render!) + ) ;define + (define (toggle!) + (let ((next (toggle-plan state (tools)))) + (call 'set-active-tools! + (if (planning? next) (planning-tools (saved-tools next)) (saved-tools state)) + ) ;call + (commit! next) + #t + ) ;let + ) ;define + (define (prompt base) + (cond + ((planning? state) + (string-append base + "\nPlan mode: investigate only; never modify files. " + (if (member "questionnaire" (tools)) + "Use questionnaire to clarify requirements. " + "Ask for clarification in text if needed. " + ) ;if + "Finish with Plan: on its own line and numbered steps." + ) ;string-append + ) ; + ((executing? state) + (string-append base + "\nExecute the plan; report [DONE:n] when step n is complete.\n" + (string-join (todo-lines state) "\n") + ) ;string-append + ) ; + (else base) + ) ;cond + ) ;define + (define (card!) + (call 'send-message! + "plan-todo-list" + (string-join (todo-lines state) "\n") + #t + 'follow-up + #f + ) ;call + ) ;define + (define (choose! lines) + (commit! (accept-plan state lines)) + (let* ((execute "Execute the plan (track progress)") + (refine "Refine the plan") + (choice (ui 'select "Plan mode - what next?" (list execute "Stay in plan mode" refine)) + ) ;choice + ) ; + (cond ((equal? choice execute) + (call 'set-active-tools! (saved-tools state)) + (commit! (start-execution state)) + (card!) + (call 'send-message! + "plan-mode-execute" + "Execute the listed steps. Report [DONE:n] after completing each step." + #t + 'follow-up + #t + ) ;call + ) ; + ((equal? choice refine) + (let ((text (ui 'editor "Refine the plan:" ""))) + (when + (and (string? text) (not (string-null? (string-trim-both text)))) + (card!) + (call 'send-user-message! (string-trim-both text) 'follow-up #t) + ) ;when + ) ;let + ) ; + ) ;cond + ) ;let* + ) ;define + (define (progress! text final?) + (let ((next (mark-progress state text final?))) + (cond + ((and final? (finished? next)) + (call 'send-message! + "plan-complete" + (string-append "Plan complete!\n" (string-join (todo-lines next) "\n")) + #t + 'next-turn + #f + ) ;call + (commit! initial-state) + ) ; + ((not (equal? (todos state) (todos next))) (commit! next)) + ) ;cond + ) ;let + ) ;define + (when (planning? state) + (call 'set-active-tools! (planning-tools (saved-tools state))) + ) ;when + (when + (and flag + (planning? state) + (not + (any (lambda (e) (equal? (json-ref e "customType") "plan-mode")) entries) + ) ;not + ) ;and + (call 'append-state! "plan-mode" (snapshot state)) + ) ;when + (when (or flag (planning? state) (executing? state)) + (render!) + ) ;when + (lambda (event payload) + (case event + ((toggle) (toggle!)) + ((todos) + (ui 'notify + (if (null? (todos state)) "No todos." (string-join (todo-lines state) "\n")) + ) ;ui + #t + ) ; + ((before_agent_start) + (list + (cons 'system-prompt (prompt (cdr (assq 'system-prompt payload)))) + ) ;list + ) ; + ((tool_call) + (and (planning? state) + (equal? "bash" (cdr (assq 'name payload))) + (not + (let ((input (cdr (or (assq 'input payload) '(input))))) + (and (json-object? input) (safe-command? (json-ref input "command"))) + ) ;let + ) ;not + '(block "Plan mode: command is not read-only") + ) ;and + ) ; + ((turn_end) + (when (executing? state) + (progress! (assistant-text (cdr (assq 'message payload))) #f) + ) ;when + ) ; + ((agent_end) + (let* ((msgs (cdr (assq 'messages payload))) + (text + (if (pair? msgs) (assistant-text (car (reverse msgs))) "") + ) ;text + ) ; + (cond + ((planning? state) + (let ((lines (plan-lines text))) + (when (pair? lines) + (choose! lines) + ) ;when + ) ;let + ) ; + ((executing? state) (progress! text #t)) + ) ;cond + ) ;let* + ) ; + ) ;case + ) ;lambda + ) ;define + ) ;begin +) ;define-library diff --git a/gfcode/plan-mode/rules.scm b/gfcode/plan-mode/rules.scm new file mode 100644 index 0000000..63e4f21 --- /dev/null +++ b/gfcode/plan-mode/rules.scm @@ -0,0 +1,179 @@ +(define-library (gfcode plan-mode rules) + (export safe-command? plan-lines step-done? plan-complete? planning-tools) + (import (scheme base) + (scheme char) + (only (srfi srfi-13) string-prefix?) + (liii string) + (liii list) + ) ;import + (begin + ;; A small shell grammar, not a blacklist. Unknown programs, switches and + ;; expansions are rejected. Quote delimiters never start a new command. + (define (read-only? argv) + (and (pair? argv) + (let ((cmd (car argv)) (args (cdr argv))) + (cond ((member cmd '("pwd" "whoami")) (null? args)) + ((member cmd '("ls" "cat" "wc" "head" "tail")) + (every + (lambda (a) + (or (not (string-prefix? "-" a)) (member a '("-l" "-a" + "-la" "-n"))) + ) ;lambda + args + ) ;every + ) ; + ((equal? cmd "git") + (member args + '(("status") + ("status" "--short") + ("diff") + ("diff" "--stat") + ("log") + ("log" "--oneline") + ("branch") + ("remote" "-v") + ("ls-files")) + ) ;member + ) ; + (else #f) + ) ;cond + ) ;let + ) ;and + ) ;define + (define (safe-command? input) + (define (push-word chars words) + (if (null? chars) words (cons (list->string (reverse chars)) words)) + ) ;define + (define (plain? ch) + (or (char-alphabetic? ch) (char-numeric? ch) (memv ch '(#\/ #\. #\- #\_ + #\:))) + ) ;define + (define (scan cs quote-char word words) + (let ((argv (lambda () (reverse (push-word word words))))) + (cond + ((null? cs) (and (not quote-char) (read-only? (argv)) #t)) + ((plain? (car cs)) (scan (cdr cs) quote-char (cons (car cs) word) words)) + ((and quote-char (eqv? quote-char (car cs))) (scan (cdr cs) #f word words)) + ((and (not quote-char) (memv (car cs) '(#\' #\"))) + (scan (cdr cs) (car cs) word words) + ) ; + ((eqv? (car cs) #\space) + (if quote-char + (scan (cdr cs) quote-char (cons #\space word) words) + (scan (cdr cs) #f '() (push-word word words)) + ) ;if + ) ; + ((and (not quote-char) (memv (car cs) '(#\| #\&)) (read-only? (argv))) + (cond + ((and (pair? (cdr cs)) (eqv? (car cs) (cadr cs))) (scan (cddr cs) #f '() '())) + ((eqv? (car cs) #\|) (scan (cdr cs) #f '() '())) + (else #f) + ) ;cond + ) ; + (else #f) + ) ;cond + ) ;let + ) ;define + (and (string? input) (scan (string->list input) #f '() '())) + ) ;define + (define (planning-tools tools) + (filter (lambda (n) + (member n '("read" "ls" "find" "grep" "bash" "questionnaire" + "web_search")) + ) ;lambda + tools + ) ;filter + ) ;define + (define (numbered-step line) + (let ((i (string-skip line char-numeric?)) (n (string-length line))) + (and i + (> i 0) + (< (+ i 2) n) + (memv (string-ref line i) '(#\. #\))) + (char-whitespace? (string-ref line (+ i 1))) + (string-trim-both (substring line (+ i 2) n)) + ) ;and + ) ;let + ) ;define + (define (plan-lines text) + (let loop + ((ls (if (string? text) (string-split text "\n") '())) + (previous '()) + (current #f) + ) ; + (if (null? ls) + (if (pair? current) (reverse current) previous) + (let* ((line (string-trim-both (car ls))) (step (and current (numbered-step line)))) + (cond + ((member (string-downcase line) '("plan:" "**plan:**" "**plan**:")) + (loop (cdr ls) (if (pair? current) (reverse current) previous) '()) + ) ; + (step (loop (cdr ls) previous (cons step current))) + (else (loop (cdr ls) previous current)) + ) ;cond + ) ;let* + ) ;if + ) ;let + ) ;define + (define (words text) + (string-tokenize + (list->string + (map (lambda (c) (if (char-alphanumeric? c) (char-downcase c) #\space)) + (string->list text) + ) ;map + ) ;list->string + ) ;string-tokenize + ) ;define + (define (char-alphanumeric? c) + (or (char-alphabetic? c) (char-numeric? c)) + ) ;define + (define (starts-with-words? xs prefix) + (or (null? prefix) + (and (pair? xs) + (equal? (car xs) (car prefix)) + (starts-with-words? (cdr xs) (cdr prefix)) + ) ;and + ) ;or + ) ;define + (define (contains-phrase? xs phrases) + (and (pair? xs) + (or (any (lambda (p) (starts-with-words? xs p)) phrases) + (contains-phrase? (cdr xs) phrases) + ) ;or + ) ;and + ) ;define + (define (step-done? text n) + (and (string? text) + (let ((num (number->string n))) + (contains-phrase? (words text) + (cons (list "done" num) + (apply append + (map (lambda (word) (list (list "step" num word) (list "step" num "is" word))) + '("done" "complete" "completed" "finished") + ) ;map + ) ;apply + ) ;cons + ) ;contains-phrase? + ) ;let + ) ;and + ) ;define + (define (plan-complete? text) + (and (string? text) + (contains-phrase? (words text) + (apply append + (map (lambda (word) + (list (list "plan" "is" word) + (list "plan" word) + (list "all" "steps" "are" word) + (list "all" "steps" word) + (list "every" "step" "is" word) + ) ;list + ) ;lambda + '("done" "complete" "completed" "finished") + ) ;map + ) ;apply + ) ;contains-phrase? + ) ;and + ) ;define + ) ;begin +) ;define-library diff --git a/gfcode/plan-mode/state.scm b/gfcode/plan-mode/state.scm new file mode 100644 index 0000000..ef5af73 --- /dev/null +++ b/gfcode/plan-mode/state.scm @@ -0,0 +1,176 @@ +(define-library (gfcode plan-mode state) + (export initial-state planning? executing? todos saved-tools toggle-plan + accept-plan start-execution mark-progress finished? snapshot restore-state + assistant-text todo-lines + ) ;export + (import (scheme base) + (liii string) + (liii list) + (liii json) + (liii pi ai message) + (gfcode plan-mode rules) + ) ;import + (begin + (define (filter-map proc xs) + (filter (lambda (x) x) (map proc xs)) + ) ;define + (define-record-type + (make-state mode tools todos) + plan-state? + (mode state-mode) + (tools saved-tools) + (todos todos) + ) ;define-record-type + (define initial-state (make-state 'normal '() '())) + (define (planning? s) + (eq? (state-mode s) 'planning) + ) ;define + (define (executing? s) + (eq? (state-mode s) 'executing) + ) ;define + (define (toggle-plan s tools) + (if (planning? s) initial-state (make-state 'planning tools '())) + ) ;define + (define (accept-plan s lines) + (make-state 'planning (saved-tools s) (map (lambda (v) (cons v #f)) lines)) + ) ;define + (define (start-execution s) + (make-state 'executing (saved-tools s) (todos s)) + ) ;define + (define (mark-progress s text final?) + (let ((all? (and final? (plan-complete? text)))) + (make-state (state-mode s) + (saved-tools s) + (map + (lambda (item n) (cons (car item) (or (cdr item) all? (step-done? text n)))) + (todos s) + (iota (length (todos s)) 1) + ) ;map + ) ;make-state + ) ;let + ) ;define + (define (finished? s) + (and (executing? s) (pair? (todos s)) (every cdr (todos s))) + ) ;define + (define (todo-lines s) + (map + (lambda (item n) + (string-append (number->string n) (if (cdr item) ". ✓ " ". ☐ ") (car item)) + ) ;lambda + (todos s) + (iota (length (todos s)) 1) + ) ;map + ) ;define + (define (bool b) + (if b 'true 'false) + ) ;define + (define (snapshot s) + (list (cons "enabled" (bool (planning? s))) + (cons "executing" (bool (executing? s))) + (cons "toolsBeforePlanMode" (list->vector (saved-tools s))) + (cons "todos" + (list->vector + (map + (lambda (i n) + (list (cons "step" n) (cons "text" (car i)) (cons "completed" (bool (cdr i)))) + ) ;lambda + (todos s) + (iota (length (todos s)) 1) + ) ;map + ) ;list->vector + ) ;cons + ) ;list + ) ;define + (define (assistant-text msg) + (let* ((obj (if (pi-assistant-message? msg) (pi-message->json msg) msg)) + (blocks (and (json-object? obj) + (equal? "assistant" (json-ref obj "role")) + (json-ref obj "content") + ) ;and + ) ;blocks + ) ; + (if (vector? blocks) + (string-join + (filter-map + (lambda (b) + (let ((k (and (json-object? b) (json-ref b "type")))) + (and (member k '("text" "thinking")) (string? (json-ref b k)) (json-ref b k)) + ) ;let + ) ;lambda + (vector->list blocks) + ) ;filter-map + "\n" + ) ;string-join + "" + ) ;if + ) ;let* + ) ;define + (define (decode data tools flag) + (let* ((raw (json-ref data "toolsBeforePlanMode")) + (items (json-ref data "todos")) + (mode + (cond ((json-ref-boolean data "executing" #f) 'executing) + ((or (json-ref-boolean data "enabled" #f) + (and flag (null? (json-ref data "enabled"))) + ) ;or + 'planning + ) ; + (else 'normal) + ) ;cond + ) ;mode + (saved + (if (vector? raw) + (filter (lambda (n) (member n tools)) (vector->list raw)) + tools + ) ;if + ) ;saved + (steps + (if (vector? items) + (filter-map + (lambda (i) + (and (json-object? i) + (string? (json-ref i "text")) + (cons (json-ref i "text") (json-ref-boolean i "completed" #f)) + ) ;and + ) ;lambda + (vector->list items) + ) ;filter-map + '() + ) ;if + ) ;steps + ) ; + (if (eq? mode 'normal) initial-state (make-state mode saved steps)) + ) ;let* + ) ;define + (define (restore-state entries tools flag) + (let loop + ((ls entries) + (s (if flag (toggle-plan initial-state tools) initial-state)) + (boundary? #f) + ) ; + (if (null? ls) + s + (let* ((e (car ls)) (kind (json-ref e "type")) (type (json-ref e "customType"))) + (cond + ((and (equal? kind "custom") + (equal? type "plan-mode") + (json-object? (json-ref e "data")) + ) ;and + (let ((next (decode (json-ref e "data") tools flag))) + (loop (cdr ls) next (and boundary? (executing? next) (executing? s))) + ) ;let + ) ; + ((and (equal? kind "custom_message") (equal? type "plan-mode-execute")) + (loop (cdr ls) s #t) + ) ; + ((and boundary? (executing? s) (equal? kind "message")) + (loop (cdr ls) (mark-progress s (assistant-text (json-ref e "message")) #f) #t) + ) ; + (else (loop (cdr ls) s boundary?)) + ) ;cond + ) ;let* + ) ;if + ) ;let + ) ;define + ) ;begin +) ;define-library diff --git a/gfproject.json b/gfproject.json new file mode 100644 index 0000000..ac45743 --- /dev/null +++ b/gfproject.json @@ -0,0 +1,9 @@ +{ + "package": { + "name": "gfcode-plan-mode", + "organization": "gfcode", + "version": "0.1.0", + "description": "Plan mode for gfcode" + }, + "domains": {"plan-mode": {"root": ".", "mode": "r7rs"}} +} diff --git a/tests/gfcode/plan-mode/README.md b/tests/gfcode/plan-mode/README.md new file mode 100644 index 0000000..c074ac7 --- /dev/null +++ b/tests/gfcode/plan-mode/README.md @@ -0,0 +1,10 @@ +# Plan Mode 测试导览 + +从插件根运行 `gf test tests/gfcode/plan-mode/`。这组测试不启动 Pi,也不需要凭据。 + +- `rules-test.scm`:命令白名单、计划提取和完成标记。 +- `restore-test.scm`:快照、活动分支与执行边界。 +- `lifecycle-test.scm`:模拟 UI 选择、取消和 Refine 调度。 +- `questionnaire-test.scm`:宿主工具调用、答案回传及 Execute 续轮。 + +真实客户端回放独立于单元测试,见[验收记录](../../../ACCEPTANCE.md)。 diff --git a/tests/gfcode/plan-mode/lifecycle-test.scm b/tests/gfcode/plan-mode/lifecycle-test.scm new file mode 100644 index 0000000..0c3b085 --- /dev/null +++ b/tests/gfcode/plan-mode/lifecycle-test.scm @@ -0,0 +1,85 @@ +;; lifecycle +;; 验证规划选择菜单及其消息调度。 +;; +;; 语法 +;; ---- +;; (exercise choice refinement) +;; +;; 参数 +;; ---- +;; choice 为模拟菜单选择,refinement 为编辑器结果。 +;; +;; 返回值 +;; ---- +;; 收集到的后续消息;取消或空编辑不发送补充。 + +(set! *load-path* + (append '("../gfcode2/code" "../gfcode2/agent" "../gfcode2/ai") *load-path*) +) ;set! +(import (scheme base) + (liii check) + (liii pi code core extensions) + (liii pi ai message) + (gfcode plan-mode lifecycle) +) ;import +(check-set-mode! 'report-failed) + +(define (exercise choice edit) + (let* ((active '("edit" "read" "extra")) + (sends '()) + (menus 0) + (notice #f) + (extra + (list (cons 'branch-entries (lambda () '())) + (cons 'get-active-tools (lambda () active)) + (cons 'set-active-tools! (lambda (names) (set! active names))) + (cons 'append-state! (lambda args #t)) + (cons 'send-message! + (lambda args (set! sends (append sends (list (car args))))) + ) ;cons + (cons 'send-user-message! + (lambda (text mode trigger) (set! sends (append sends (list text)))) + ) ;cons + (cons 'ui + (lambda (key . args) + (case key + ((select) (set! menus (+ menus 1)) choice) + ((editor) edit) + ((notify) (set! notice (car args))) + (else #f) + ) ;case + ) ;lambda + ) ;cons + ) ;list + ) ;extra + (handler (make-plan-session (make-extension-context :extra extra) #t)) + ) ; + (define (end text) + (handler 'agent_end + (list + (cons 'messages (list (pi-assistant-message (list (pi-text-block text))))) + ) ;list + ) ;handler + ) ;define + (check active => '("read")) + (end "Plan:\n1. Examine README") + (end "No new plan") + (check menus => 1) + (check active => '("read")) + (handler 'toggle '()) + (check active => '("edit" "read" "extra")) + (handler 'todos '()) + (check notice => "No todos.") + sends + ) ;let* +) ;define +(check (exercise "Refine the plan" " use blue ") + => + '("plan-todo-list" "use blue") +) ;check +(check (exercise "Refine the plan" " ") => '()) +(check (exercise "Refine the plan" #f) => '()) +(check (exercise "Stay in plan mode" #f) => '()) +(check (exercise #f #f) => '()) + +(check-report) diff --git a/tests/gfcode/plan-mode/questionnaire-test.scm b/tests/gfcode/plan-mode/questionnaire-test.scm new file mode 100644 index 0000000..b7ee56f --- /dev/null +++ b/tests/gfcode/plan-mode/questionnaire-test.scm @@ -0,0 +1,133 @@ +;; questionnaire +;; 在真实宿主队列中验证问卷与 Execute 续轮。 +;; +;; 语法 +;; ---- +;; (run-session-flow parsed deps prompt initial emit file) +;; +;; 参数 +;; ---- +;; deps 注入本地模型与选择回调,file 指向临时会话。 +;; +;; 返回值 +;; ---- +;; 从会话检查匹配的问答、执行提示及完成卡。 + +(set! *load-path* + (append '("../gfcode2/code" "../gfcode2/agent" "../gfcode2/ai" + "../gfcode2/gfsh" "../gfcode2/bash") + *load-path* + ) ;append +) ;set! +(import (scheme base) + (liii path) + (liii uuid) + (liii json) + (liii check) + (liii list) + (liii string) + (liii pi code modes flow) + (liii pi code core tools) + (liii pi code core extensions) + (liii pi code core compaction session) + (liii pi ai message) +) ;import +(check-set-mode! 'report-failed) +(let ((reg (make-extension-registry)) + (file (path->string (path-join (path-temp-dir) (uuid4)))) + (original '("write" "questionnaire" "read" "extra")) + (calls 0) + (menus 0) + ) ; + (define (request p c msgs sp tools emit timeout) + (set! calls (+ calls 1)) + (case calls + ((1) + (check tools => '("questionnaire" "read")) + (check (string-contains? sp "Use questionnaire") => #t) + (pi-assistant-message (list (pi-tool-call-block "q1" + "questionnaire" + (string->json "{\"questions\":[{\"id\":\"x\",\"prompt\":\"Pick\",\"options\":[{\"value\":\"yes\",\"label\":\"Yes\"}]}]}" + ) ;string->json + ) ;pi-tool-call-block + ) ;list + :stop-reason "toolUse" + ) ;pi-assistant-message + ) ; + ((2) + (let ((r (car (reverse msgs)))) + (check (pi-tool-result-message-tool-call-id r) => "q1") + (check (json-ref (pi-tool-result-message-details r) "answers" 0 "value") + => + "yes" + ) ;check + ) ;let + (pi-assistant-message (list (pi-thinking-block "Plan:\n1. Wrong draft") + (pi-text-block "Plan:\n1. Inspect file") + ) ;list + :stop-reason "stop" + ) ;pi-assistant-message + ) ; + (else (check tools => original) + (check (string-contains? sp "Inspect file") => #t) + (pi-assistant-message (list (pi-text-block "[DONE:1]")) :stop-reason "stop") + ) ;else + ) ;case + ) ;define + (dynamic-wind (lambda () #t) + (lambda () + (check (cdr (assq 'status (pi-load-extension "gfcode/plan-mode/index.scm" reg))) + => + 'ok + ) ;check + (for-each + (lambda (augment) (augment '() '((plan . #t)))) + (extension-registry-augmenters-list reg) + ) ;for-each + (run-session-flow '((no-skills . #t) (no-auto-compact . #t)) + (list (cons 'registry reg) + (cons 'config-dir (path-temp-dir)) + (cons 'tools original) + (cons 'request-fn request) + (cons 'execute-tool-call execute-tool-call) + (cons 'questionnaire-port (lambda args #(0))) + (cons 'extension-ui + (list + (cons 'select + (lambda (title options) + (check title => "Plan mode - what next?") + (check options + => + '("Execute the plan (track progress)" + "Stay in plan mode" + "Refine the plan") + ) ;check + (set! menus (+ menus 1)) + (car options) + ) ;lambda + ) ;cons + ) ;list + ) ;cons + ) ;list + "plan" + #f + (lambda (msgs) #t) + file + ) ;run-session-flow + (check calls => 3) + (check menus => 1) + (let ((entries (pi-read-session-entries file))) + (check + (map (lambda (e) (json-ref e "customType")) + (filter (lambda (e) (equal? "custom_message" (json-ref e "type"))) entries) + ) ;map + => + '("plan-todo-list" "plan-mode-execute" "plan-complete") + ) ;check + ) ;let + ) ;lambda + (lambda () (when (file-exists? file) (delete-file file))) + ) ;dynamic-wind +) ;let + +(check-report) diff --git a/tests/gfcode/plan-mode/restore-test.scm b/tests/gfcode/plan-mode/restore-test.scm new file mode 100644 index 0000000..f3c4133 --- /dev/null +++ b/tests/gfcode/plan-mode/restore-test.scm @@ -0,0 +1,75 @@ +;; restore +;; 从活动分支的快照与助手消息恢复清单。 +;; +;; 语法 +;; ---- +;; (restore-state entries tools) +;; +;; 参数 +;; ---- +;; entries 是分支上有序条目,tools 是当前工具名列表。 +;; +;; 返回值 +;; ---- +;; 最近规划状态;执行边界之前的完成标记不影响新清单。 + +(set! *load-path* (append '("../gfcode2/ai") *load-path*)) +(import (scheme base) (liii check) (liii json) (gfcode plan-mode state)) +(check-set-mode! 'report-failed) + +(define tools '("bash" "read" "write")) + +(define plan + (accept-plan (toggle-plan initial-state tools) '("Inspect README" "Run tests")) +) ;define + +(define exec (start-execution plan)) + +(define (entry state) + (list '("type" . "custom") + '("customType" . "plan-mode") + (cons "data" (snapshot state)) + ) ;list +) ;define + +(define boundary + '(("type" . "custom_message") ("customType" . "plan-mode-execute")) +) ;define + +(define msg + (string->json "{\"type\":\"message\",\"message\":{\"role\":\"assistant\",\"content\":[{\"type\":\"text\",\"text\":\"[DONE:1]\"}]}}" + ) ;string->json +) ;define +(let ((s (restore-state (list (entry exec) boundary msg (entry plan) (entry exec) boundary) + '("read") + #f + ) ;restore-state + ) ;s + ) ; + (check (saved-tools s) => '("read")) + (check (map cdr (todos s)) => '(#f #f)) + (check (map cdr (todos (mark-progress s "[DONE:1] [DONE:1] [DONE:9]" #f))) + => + '(#t #f) + ) ;check +) ;let +(check + (map cdr (todos (restore-state (list (entry exec) boundary msg) tools #f))) + => + '(#t #f) +) ;check +(check (finished? (mark-progress exec "All steps are done." #t)) => #t) +(let ((s (restore-state (list (string->json "{\"type\":\"custom\",\"customType\":\"plan-mode\",\"data\":{\"enabled\":true}}" + ) ;string->json + ) ;list + tools + #f + ) ;restore-state + ) ;s + ) ; + (check (planning? s) => #t) + (check (saved-tools s) => tools) + (check (todos s) => '()) +) ;let + +(check-report) diff --git a/tests/gfcode/plan-mode/rules-test.scm b/tests/gfcode/plan-mode/rules-test.scm new file mode 100644 index 0000000..b28c1cb --- /dev/null +++ b/tests/gfcode/plan-mode/rules-test.scm @@ -0,0 +1,36 @@ +;; rules +;; 检查规划态命令及计划文本解析。 +;; +;; 语法 +;; ---- +;; (safe-command? command) / (plan-lines text) +;; +;; 参数 +;; ---- +;; command 为命令字符串,text 为助手输出。 +;; +;; 返回值 +;; ---- +;; 命令是否允许,或最后有效计划的步骤列表;无计划返回空列表。 + +(import (scheme base) (liii check) (gfcode plan-mode rules)) +(check-set-mode! 'report-failed) +(check (map safe-command? + '("git status" "git diff --stat" "ls | pwd" "git log && git add ." + "git branch -D main" "ls > out" "cat 'file name'" "cat \"$(date)\"" + "git diff --output=x") + ) ;map + => + '(#t #t #t #f #f #f #t #f #f) +) ;check +(check (plan-lines "Plan:\n1. Old draft\n**Plan:**\n1. Inspect the file\n2) Run the tests\nPlan:" + ) ;plan-lines + => + '("Inspect the file" "Run the tests") +) ;check +(check (plan-lines #f) => '()) +(check (step-done? "[DONE:1] [DONE:11]" 1) => #t) +(check (step-done? "[DONE:11]" 1) => #f) +(check (plan-complete? "The plan is not complete") => #f) + +(check-report) diff --git a/tests/gfcode/plan-mode/working-test.scm b/tests/gfcode/plan-mode/working-test.scm new file mode 100644 index 0000000..9500067 --- /dev/null +++ b/tests/gfcode/plan-mode/working-test.scm @@ -0,0 +1,112 @@ +;; working +;; 在虚拟终端检查 Plan 菜单后的 Working 边框与待办清单。 +;; +;; 语法 +;; ---- +;; (check-plan-ui choice stop-reason) +;; +;; 参数 +;; ---- +;; choice 为菜单选项下标;stop-reason 为执行请求的停止原因。 +;; +;; 返回值 +;; ---- +;; Execute 工作期间显示 Working,完成、中止或 Stay 后恢复空闲。 +(set! *load-path* + (append '("../gfcode2/app" "../gfcode2/code" "../gfcode2/agent" + "../gfcode2/ai" "../gfcode2/gfsh" "../gfcode2/bash" + "../gfcode2/highlight") + *load-path* + ) ;append +) ;set! +(import (scheme base) + (liii check) + (liii list) + (liii string) + (liii tui) + (liii path) + (liii uuid) + (liii pi ai message) + (liii pi agent queue) + (liii pi code core extensions) + (liii pi app interactive app) + (liii pi app interactive extension-ui) + (liii pi app interactive worker) +) ;import +(check-set-mode! 'report-failed) + +(define (check-plan-ui choice stop-reason) + (let* ((reg (make-extension-registry)) + (calls 0) + (app (make-pi-app :terminal (make-virtual-terminal :width 90 :height 32))) + (events (pi-app-event-chan app)) + (file (path->string (path-join (path-temp-dir) (uuid4)))) + ) ; + (define (visible? text) + (any (lambda (line) (string-contains? line text)) + (alt-screen-lines (pi-app-screen app)) + ) ;any + ) ;define + (define (request p c msgs sp tools emit timeout) + (set! calls (+ calls 1)) + (cond + ((= calls 1) + (pi-assistant-message (list (pi-text-block "Plan:\n1. Inspect file")) + :stop-reason "stop" + ) ;pi-assistant-message + ) ; + (else (pi-app-poll-events! app) + (check (visible? "1. ☐ Inspect file") => #t) + (check (visible? "Working") => #t) + (pi-assistant-message + (list (pi-text-block (if (equal? stop-reason "stop") "[DONE:1]" ""))) + :stop-reason stop-reason + ) ;pi-assistant-message + ) ;else + ) ;cond + ) ;define + (dynamic-wind (lambda () #t) + (lambda () + (check (cdr (assq 'status (pi-load-extension "gfcode/plan-mode/index.scm" reg))) + => + 'ok + ) ;check + (for-each + (lambda (fn) (fn '() '((plan . #t)))) + (extension-registry-augmenters-list reg) + ) ;for-each + (pi-queue-set-busy! (pi-app-queue app)) + (pi-tui-run-worker '((no-skills . #t) (no-auto-compact . #t)) + (list '(provider . "deepseek") + '(api-key . "test") + '(tools "read") + (cons 'registry reg) + (cons 'config-dir (path-temp-dir)) + (cons 'request-fn request) + (cons 'extension-ui + (cons (cons 'select (lambda (title options) (list-ref options choice))) + (make-extension-ui events #f) + ) ;cons + ) ;cons + ) ;list + "plan" + events + file + ) ;pi-tui-run-worker + (pi-app-poll-events! app) + (check calls => (if (= choice 0) 2 1)) + (check (visible? "Working") => #f) + (when (equal? stop-reason "aborted") + (check (visible? "Aborted") => #t) + (check (visible? "1. ☐ Inspect file") => #t) + ) ;when + ) ;lambda + (lambda () (when (file-exists? file) (delete-file file))) + ) ;dynamic-wind + ) ;let* +) ;define +(check-plan-ui 0 "stop") +(check-plan-ui 0 "aborted") +(check-plan-ui 1 "stop") + +(check-report) diff --git a/tests/interop/fork.mjs b/tests/interop/fork.mjs new file mode 100644 index 0000000..1d4f58e --- /dev/null +++ b/tests/interop/fork.mjs @@ -0,0 +1,24 @@ +// replay.py supplies a temporary golden copy and a separate fork directory. +import assert from 'node:assert/strict'; +import {readFileSync} from 'node:fs'; +import {join} from 'node:path'; +import {pathToFileURL} from 'node:url'; + +const [pkg, source, dir] = process.argv.slice(2); +const {SessionManager} = await import(pathToFileURL(join(pkg, 'dist/core/session-manager.js'))); +const manager = SessionManager.open(source, dir); +const kept = manager.getLeafId(); +manager.appendCompaction('The sample plan is executing.', kept, 100); +const note = manager.appendCustomMessageEntry('sample-note', 'before amendment', false); +const active = manager.appendContextEdit(note, {content: 'after amendment'}); +manager.branch(kept); +const sibling = manager.appendCustomEntry('plan-mode', {enabled: false, executing: false, todos: []}); +const original = readFileSync(source, 'utf8'); +assert.equal(JSON.parse(original.trimEnd().split('\n').at(-1)).id, sibling); +const fork = manager.createBranchedSession(active); +const reopened = SessionManager.open(fork); +assert.equal(reopened.getLeafId(), active); +assert.equal(reopened.getEntry(sibling), undefined); +const projected = reopened.buildSessionContext().messages; +assert.equal(projected.find(m => m.customType === 'sample-note')?.content, 'after amendment'); +assert.equal(readFileSync(source, 'utf8'), original); diff --git a/tests/interop/pi-1.7.0-one-of-three.jsonl b/tests/interop/pi-1.7.0-one-of-three.jsonl new file mode 100644 index 0000000..926c6bc --- /dev/null +++ b/tests/interop/pi-1.7.0-one-of-three.jsonl @@ -0,0 +1,19 @@ +{"type":"session","version":3,"id":"01a22c4e-dbe0-771d-a679-9805acb93826","timestamp":"2026-11-30T11:54:55.329Z","cwd":"/project"} +{"type":"model_change","id":"63f2e105","parentId":null,"timestamp":"2026-11-30T11:54:55.355Z","provider":"loop","modelId":"probe"} +{"type":"thinking_level_change","id":"6b05f271","parentId":"63f2e105","timestamp":"2026-11-30T11:54:55.355Z","thinkingLevel":"off"} +{"type":"message","id":"38030a43","parentId":"6b05f271","timestamp":"2026-11-30T11:54:55.360Z","message":{"role":"system","content":"","sections":{"preamble":"You are a coding assistant running inside pi, a coding agent harness. Help users inspect files, run commands, and modify code.","tools":"\n- read: Read file contents\n- bash: Execute bash commands (ls, grep, find, etc.)\n- grep: Search file contents for patterns (respects .gitignore)\n- find: Find files by glob pattern (respects .gitignore)\n- ls: List directory contents\n\nAdditional tools may be available.\n","rules":"\n- Use read to examine files instead of cat or sed.\n- You can inspect PI_* environment variables for current model and session details.\n- Be concise in your responses\n- Show file paths clearly when working with files\n","docs":"\nPi documentation (read only when the user asks about the harness itself, its SDK, extensions, themes, skills, or TUI):\n- Main documentation: /pi/README.md\n- Additional docs: /pi/docs\n- Examples: /pi/examples (extensions, custom tools, SDK)\n- When reading pi docs or examples, resolve docs/... under Additional docs and examples/... under Examples, not the current working directory\n- When asked about: extensions (docs/extensions.md, examples/extensions/), themes (docs/themes.md), skills (docs/skills.md), prompt templates (docs/prompt-templates.md), TUI components (docs/tui.md), keybindings (docs/keybindings.md), SDK integrations (docs/sdk.md), custom providers (docs/custom-provider.md), adding models (docs/models.md), packages (docs/packages.md), environment variables (docs/environment-variables.md), MCP servers (docs/mcp.md), codemode scripts and non-LLM models such as classifiers and image models (docs/codemode.md)\n- Before implementing harness changes, read the relevant docs and examples in full, following related cross-references.\n","cwd":"\n/project\n"},"timestamp":1796039695359,"toolsAdded":[{"name":"read","description":"Read the contents of a file. Supports text files and images (jpg, png, gif, webp, bmp). Images are sent as attachments. For text files, output is truncated to 2000 lines or 50KB (whichever is hit first). Use offset/limit for large files. When you need the full file, continue with offset until complete.","parameters":{"type":"object","required":["path"],"properties":{"path":{"type":"string","description":"Path to the file to read (relative or absolute)"},"offset":{"type":"number","description":"Line number to start reading from (1-indexed)"},"limit":{"type":"number","description":"Maximum number of lines to read"}}},"constrainedSampling":{"type":"json_schema","strict":"prefer"}},{"name":"bash","description":"Execute a bash command in the current working directory. Returns stdout and stderr. Output is truncated to last 2000 lines or 50KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.","parameters":{"type":"object","required":["command"],"properties":{"command":{"type":"string","description":"Shell command to execute"},"timeout":{"type":"number","description":"Timeout in seconds (optional, no default timeout)"}}},"constrainedSampling":{"type":"json_schema","strict":"prefer"}},{"name":"questionnaire","description":"Ask the user one or more questions. Use for clarifying requirements, getting preferences, or confirming decisions. For single questions, shows a simple option list. For multiple questions, shows a tab-based interface.","parameters":{"type":"object","required":["questions"],"properties":{"questions":{"type":"array","items":{"type":"object","required":["id","prompt","options"],"properties":{"id":{"type":"string","description":"Unique identifier for this question"},"label":{"type":"string","description":"Short contextual label for tab bar, e.g. 'Scope', 'Priority' (defaults to Q1, Q2)"},"prompt":{"type":"string","description":"The full question text to display"},"options":{"type":"array","items":{"type":"object","required":["value","label"],"properties":{"value":{"type":"string","description":"The value returned when selected"},"label":{"type":"string","description":"Display label for the option"},"description":{"type":"string","description":"Optional description shown below label"}}},"description":"Available options to choose from"},"allowOther":{"type":"boolean","description":"Allow 'Type something' option (default: true)"}}},"description":"Questions to ask the user"}}}},{"name":"grep","description":"Search file contents for a pattern. Returns matching lines with file paths and line numbers. Respects .gitignore. Output is truncated to 100 matches or 50KB (whichever is hit first). Long lines are truncated to 500 chars.","parameters":{"type":"object","required":["pattern"],"properties":{"pattern":{"type":"string","description":"Search pattern (regex or literal string)"},"path":{"type":"string","description":"Directory or file to search (default: current directory)"},"glob":{"type":"string","description":"Filter files by glob pattern relative to path, e.g. 'src/**/*.ts'. Without '/', e.g. '*.ts', it matches file names at any depth"},"ignoreCase":{"type":"boolean","description":"Case-insensitive search (default: false)"},"literal":{"type":"boolean","description":"Treat pattern as literal string instead of regex (default: false)"},"context":{"type":"number","description":"Number of lines to show before and after each match (default: 0)"},"limit":{"type":"number","description":"Maximum number of matches to return (default: 100)"}}}},{"name":"find","description":"Search for files by glob pattern. Returns matching file paths relative to the search directory. Respects .gitignore. Output is truncated to 1000 results or 50KB (whichever is hit first).","parameters":{"type":"object","required":["pattern"],"properties":{"pattern":{"type":"string","description":"Glob pattern relative to the search directory, e.g. 'src/**/*.ts'. Without '/', e.g. '*.ts', it matches file names at any depth"},"path":{"type":"string","description":"Directory to search in (default: current directory)"},"limit":{"type":"number","description":"Maximum number of results (default: 1000)"}}}},{"name":"ls","description":"List directory contents. Returns entries sorted alphabetically, with '/' suffix for directories. Includes dotfiles. Output is truncated to 500 entries or 50KB (whichever is hit first).","parameters":{"type":"object","properties":{"path":{"type":"string","description":"Directory to list (default: current directory)"},"limit":{"type":"number","description":"Maximum number of entries to return (default: 500)"}}}}]}} +{"type":"message","id":"3e06b38b","parentId":"38030a43","timestamp":"2026-11-30T11:54:55.360Z","message":{"role":"user","content":[{"type":"text","text":"Plan the sample."}],"timestamp":1796039695359}} +{"type":"custom_message","customType":"plan-mode-context","content":"[PLAN MODE ACTIVE]\nYou are in plan mode - a read-only exploration mode for safe code analysis.\n\nRestrictions:\n- Built-in edit and write tools are disabled\n- Other currently active tools remain available\n- Bash is restricted to an allowlist of read-only commands\n\nAsk clarifying questions using the questionnaire tool.\nUse brave-search skill via bash for web research.\n\nCreate a detailed numbered plan under a \"Plan:\" header:\n\nPlan:\n1. First step description\n2. Second step description\n...\n\nDo NOT attempt to make changes - just describe what you would do.","display":false,"id":"c1d3ccb7","parentId":"3e06b38b","timestamp":"2026-11-30T11:54:55.360Z"} +{"type":"message","id":"c2f8483c","parentId":"c1d3ccb7","timestamp":"2026-11-30T11:54:55.382Z","message":{"role":"assistant","content":[{"type":"toolCall","id":"probe-question","name":"questionnaire","arguments":{"questions":[{"id":"scope","prompt":"Which sample?","options":[{"label":"Small","value":"small"}]}]}}],"api":"openai-completions","provider":"loop","model":"probe","usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"totalTokens":0,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"stopReason":"toolUse","timestamp":1796039695365,"responseId":"sample","rawStopReason":"tool_calls","durationMs":17,"thinkingLevel":"off"}} +{"type":"message","id":"adbbddf8","parentId":"c2f8483c","timestamp":"2026-11-30T11:54:55.384Z","message":{"role":"toolResult","toolCallId":"probe-question","toolName":"questionnaire","content":[{"type":"text","text":"Error: UI not available (running in non-interactive mode)"}],"details":{"questions":[],"answers":[],"cancelled":true},"isError":false,"durationMs":0,"timestamp":1796039695384}} +{"type":"message","id":"4cd89400","parentId":"adbbddf8","timestamp":"2026-11-30T11:54:55.387Z","message":{"role":"assistant","content":[{"type":"text","text":"Plan:\n1. Inspect sample\n2. Compare sample\n3. Report findings"}],"api":"openai-completions","provider":"loop","model":"probe","usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"totalTokens":0,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"stopReason":"stop","timestamp":1796039695385,"responseId":"sample","rawStopReason":"stop","durationMs":2,"thinkingLevel":"off"}} +{"type":"custom","customType":"plan-mode","data":{"enabled":true,"todos":[{"step":1,"text":"Inspect sample","completed":false},{"step":2,"text":"Compare sample","completed":false},{"step":3,"text":"Report findings","completed":false}],"executing":false,"toolsBeforePlanMode":["read","bash","edit","write","questionnaire"]},"id":"e40a6208","parentId":"4cd89400","timestamp":"2026-11-30T11:54:55.388Z"} +{"type":"custom","customType":"plan-mode","data":{"enabled":false,"todos":[{"step":1,"text":"Inspect sample","completed":false},{"step":2,"text":"Compare sample","completed":false},{"step":3,"text":"Report findings","completed":false}],"executing":true},"id":"c6a97b28","parentId":"e40a6208","timestamp":"2026-11-30T11:54:55.388Z"} +{"type":"message","id":"ddf5f642","parentId":"c6a97b28","timestamp":"2026-11-30T11:54:55.389Z","message":{"role":"system","content":"","timestamp":1796039695389,"toolsAdded":[{"name":"edit","description":"Edit a single file using exact text replacement. Every edits[].oldText must match a unique, non-overlapping region of the original file. If two changes affect the same block or nearby lines, merge them into one edit instead of emitting overlapping edits. Do not include large unchanged regions just to connect distant changes.","parameters":{"type":"object","required":["path","edits"],"properties":{"path":{"type":"string","description":"Path to the file to edit (relative or absolute)"},"edits":{"type":"array","items":{"type":"object","required":["oldText","newText"],"properties":{"oldText":{"type":"string","description":"Exact text for one targeted replacement. It must be unique in the original file and must not overlap with any other edits[].oldText in the same call."},"newText":{"type":"string","description":"Replacement text for this targeted edit."}}},"description":"One or more targeted replacements. Each edit is matched against the original file, not incrementally. Do not include overlapping or nested edits. If two changes touch the same block or nearby lines, merge them into one edit instead."}}},"constrainedSampling":{"type":"json_schema","strict":"prefer"}},{"name":"write","description":"Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories.","parameters":{"type":"object","required":["path","content"],"properties":{"path":{"type":"string","description":"Path to the file to write (relative or absolute)"},"content":{"type":"string","description":"Content to write to the file"}}},"constrainedSampling":{"type":"json_schema","strict":"prefer"}}],"toolsRemoved":[{"name":"grep"},{"name":"find"},{"name":"ls"}]}} +{"type":"custom_message","customType":"plan-todo-list","content":"**Plan Steps (3):**\n\n1. ☐ Inspect sample\n2. ☐ Compare sample\n3. ☐ Report findings","display":true,"id":"8805fa68","parentId":"ddf5f642","timestamp":"2026-11-30T11:54:55.389Z"} +{"type":"message","id":"d4e75988","parentId":"8805fa68","timestamp":"2026-11-30T11:54:55.392Z","message":{"role":"assistant","content":[{"type":"text","text":"Noted."}],"api":"openai-completions","provider":"loop","model":"probe","usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"totalTokens":0,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"stopReason":"stop","timestamp":1796039695390,"responseId":"sample","rawStopReason":"stop","durationMs":2,"thinkingLevel":"off"}} +{"type":"custom","customType":"plan-mode","data":{"enabled":false,"todos":[{"step":1,"text":"Inspect sample","completed":false},{"step":2,"text":"Compare sample","completed":false},{"step":3,"text":"Report findings","completed":false}],"executing":true},"id":"7d900240","parentId":"d4e75988","timestamp":"2026-11-30T11:54:55.392Z"} +{"type":"message","id":"2c0ca0dc","parentId":"7d900240","timestamp":"2026-11-30T11:54:55.392Z","message":{"role":"system","content":"","sections":{"tools":"\n- read: Read file contents\n- bash: Execute bash commands (ls, grep, find, etc.)\n- edit: Make precise file edits with exact text replacement, including multiple disjoint edits in one call\n- write: Create or overwrite files\n\nAdditional tools may be available.\n","rules":"\n- Use bash for file operations like ls, rg, find\n- Use read to examine files instead of cat or sed.\n- You can inspect PI_* environment variables for current model and session details.\n- Use edit for targeted changes. Batch changes to one file in a single call.\n- Each edits[].oldText must exactly and uniquely match the original file. Keep matches short and non-overlapping; merge nearby changes without including large unchanged regions.\n- Use write only for new files or complete rewrites.\n- Be concise in your responses\n- Show file paths clearly when working with files\n"},"timestamp":1796039695392}} +{"type":"custom_message","customType":"plan-mode-execute","content":"Execute the plan.\n\nRemaining steps:\n1. Inspect sample\n2. Compare sample\n3. Report findings\n\nStart with: Inspect sample\nAfter completing a step, include a [DONE:n] tag in your response.","display":true,"id":"a65f3599","parentId":"2c0ca0dc","timestamp":"2026-11-30T11:54:55.392Z"} +{"type":"message","id":"e08989be","parentId":"a65f3599","timestamp":"2026-11-30T11:54:55.394Z","message":{"role":"assistant","content":[{"type":"text","text":"[DONE:1]"}],"api":"openai-completions","provider":"loop","model":"probe","usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"totalTokens":0,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"stopReason":"stop","timestamp":1796039695393,"responseId":"sample","rawStopReason":"stop","durationMs":2,"thinkingLevel":"off"}} +{"type":"custom","customType":"plan-mode","data":{"enabled":false,"todos":[{"step":1,"text":"Inspect sample","completed":true},{"step":2,"text":"Compare sample","completed":false},{"step":3,"text":"Report findings","completed":false}],"executing":true},"id":"f8be676e","parentId":"e08989be","timestamp":"2026-11-30T11:54:55.395Z"} diff --git a/tests/interop/replay.py b/tests/interop/replay.py new file mode 100644 index 0000000..a528e69 --- /dev/null +++ b/tests/interop/replay.py @@ -0,0 +1,292 @@ +"""Run from plugin root: python3 tests/interop/replay.py GF_HOST PI_PACKAGE. +Uses both clients, an isolated HOME and a scripted loopback chat endpoint. +""" +import json +import os +from pathlib import Path +import queue +import subprocess +import sys +import tempfile +import threading +from collections.abc import Callable, Iterable +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from typing import Any + +Row = dict[str, Any] + +ROOT = Path(__file__).resolve().parents[2] +PLAN = 'Plan:\n1. Inspect sample\n2. Compare sample\n3. Report findings' +REFINE = 'Use the smaller sample.' + + +def write(path: Path, data: object) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(data)) + + +class ProbeServer(ThreadingHTTPServer): + def __init__(self) -> None: + super().__init__(('127.0.0.1', 0), Model) + self.requests: list[Row] = [] + self.replies: queue.Queue[str | Row] = queue.Queue() + + +class Model(BaseHTTPRequestHandler): + server: ProbeServer + + def log_message(self, fmt: str, *args: object) -> None: + pass # No access log: assertions inspect the captured requests. + + def do_POST(self) -> None: + if self.path != '/v1/chat/completions': + self.send_error(404) + return + try: + length = int(self.headers.get('Content-Length', '0')) + if not 0 < length <= 2**20: + raise ValueError('invalid request length') + request = json.loads(self.rfile.read(length)) + if not isinstance(request, dict) or not isinstance(request.get('messages'), list): + raise ValueError('missing messages') + except ValueError: + self.send_error(400, 'Invalid chat request') + return + self.server.requests.append(request) + try: + reply = self.server.replies.get_nowait() + except queue.Empty: + self.send_error(400, 'Unexpected extra model turn') + return + self.send_response(200) + self.send_header('Content-Type', 'text/event-stream') + self.end_headers() + if isinstance(reply, dict): + delta = {'role': 'assistant', 'tool_calls': [reply]} + finish = 'tool_calls' + else: + delta, finish = {'role': 'assistant', 'content': reply}, 'stop' + for delta, stop in [(delta, None), ({}, finish)]: + chunk = dict(id='sample', object='chat.completion.chunk', created=1, model='probe', + choices=[dict(index=0, delta=delta, finish_reason=stop)]) + self.wfile.write(('data: ' + json.dumps(chunk) + '\n\n').encode()) + self.wfile.write(b'data: [DONE]\n\n') + + +def session(directory: Path) -> tuple[Path, list[Row]]: + file, = directory.rglob('*.jsonl') + return file, [json.loads(line) for line in file.read_text().splitlines()] + + +def state(rows: list[Row]) -> Row: + return next(r['data'] for r in reversed(rows) if r.get('customType') == 'plan-mode') + + +def progress(rows: list[Row]) -> list[bool]: + return [t['completed'] for t in state(rows)['todos']] + + +def descendant(before: list[Row], after: list[Row]) -> None: + assert after[:len(before)] == before + for a, b in zip(after[len(before)-1:], after[len(before):]): + assert b['parentId'] == a['id'], b + + +def rpc(cmd: list[str], env: dict[str, str], cwd: Path, *, status: str, + prompt: str | None = None, choices: Iterable[str] = (), + done: Callable[[], bool] | None = None) -> None: + """Observe actual status on startup. For prompts, wait for persisted target state.""" + with subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True, + env=env, cwd=cwd) as proc: + assert proc.stdin is not None and proc.stdout is not None + events: queue.Queue[str] = queue.Queue() + + def read() -> None: + for line in proc.stdout: + events.put(line) + events.put('') + + reader = threading.Thread(target=read, daemon=True) + reader.start() + + def send(**obj: str) -> None: + proc.stdin.write(json.dumps(obj) + '\n') + proc.stdin.flush() + choices = iter(choices) + try: + while True: + try: + line = events.get(timeout=30) + except queue.Empty as exc: + raise TimeoutError(f'Pi RPC stalled waiting for {status!r} or agent_end') from exc + assert line, 'Pi RPC exited before expected status' + event = json.loads(line) + method = event.get('method') + if method == 'setStatus' and status in event.get('statusText', ''): + if prompt is None: + break + send(type='prompt', message=prompt) + prompt, status = None, '__unreachable__' + elif method in ('select', 'editor'): + send(type='extension_ui_response', id=event['id'], value=next(choices)) + elif event['type'] == 'agent_end' and done and done(): + break + finally: + proc.terminate() + try: + proc.wait(timeout=5) + except subprocess.TimeoutExpired: + proc.kill() + proc.wait() + reader.join() + + +def run(tmp: Path, host: Path, pkg: Path, server: ProbeServer, check_fork: bool) -> None: + assert json.loads((pkg/'package.json').read_text())['version'] == '1.7.0' + work = tmp/'work' + work.mkdir() + for name in ['home', 'empty']: + (tmp/name).mkdir() + env = {k: os.environ[k] for k in ('PATH', 'LANG', 'TMPDIR') if k in os.environ} + env.update(HOME=str(tmp/'home'), PI_BUILTIN_EXTENSIONS_DIR=str(tmp/'empty'), PI_OFFLINE='1') + base = f'http://127.0.0.1:{server.server_port}/v1' + model = dict(id='probe', name='Probe', reasoning=False, input=['text'], contextWindow=65536, maxTokens=1024) + provider = dict(api='openai-completions', baseUrl=base) + write(tmp/'gf/models/providers.json', ['loop']) + write(tmp/'gf/models/loop.json', dict(provider, models=['probe'])) + write(tmp/'gf/models/loop/probe.json', dict(model, **provider)) + write(tmp/'gf/auth.json', {'loop': dict(type='api_key', key='local-test')}) + write(tmp/'pi/models.json', {'providers': {'loop': dict(provider, apiKey='local-test', models=[model])}}) + entry = tmp/'entry.scm' + entry.write_text('(import (scheme process-context) (liii pi app cli))\n(exit (run-pi (command-line)))\n') + gf = ['gf'] + for domain in ['app', 'code', 'agent', 'ai', 'gfsh', 'bash', 'highlight']: + gf += ['-I', str(host/domain)] + gf += [str(entry), 'pi'] + def gold(*args: str) -> None: + subprocess.run(gf + list(args), env=dict(env, PI_CODING_AGENT_DIR=str(tmp/'gf')), cwd=work, + check=True, timeout=45) + gold('link', '--local', str(ROOT)) + common = ['--provider', 'loop', '--model', 'probe', '--no-skills'] + pi = ['node', str(pkg/'dist/bundle/cli.js'), '--mode', 'rpc', '--agent-dir', str(tmp/'pi'), + '--no-extensions', '--no-mcp', '-e', str(pkg/'examples/extensions/plan-mode/index.ts'), + '-e', str(pkg/'examples/extensions/questionnaire.ts'), *common] + def replies(*items: str | Row) -> None: + for item in items: + server.replies.put(item) + a = tmp/'a' + ask = dict(index=0, id='probe-question', type='function', function=dict(name='questionnaire', + arguments=json.dumps({'questions': [{'id': 'scope', 'prompt': 'Which sample?', + 'options': [{'label': 'Small', 'value': 'small'}]}]}))) + replies(ask, PLAN, 'Noted.', '[DONE:1]') + rpc(pi + ['--plan', '--session-dir', str(a)], env, work, status='plan', prompt='Plan the sample.', + choices=['Execute the plan (track progress)'], done=lambda: progress(session(a)[1]) == [True, False, False]) + f, first = session(a) + result, = [r['message'] for r in first if r.get('message', {}).get('role') == 'toolResult'] + assert result['toolCallId'] == 'probe-question' and result['details']['cancelled'] is True + assert progress(first) == [True, False, False] + replies('[DONE:2]') + gold(*common, '--session-dir', str(a), '-c', '-p', 'Continue the sample.') + _, second = session(a) + descendant(first, second) + assert progress(second) == [True, True, False] + req = server.requests[-1] + tool, = [m for m in req['messages'] if m['role'] == 'tool'] + assert tool['tool_call_id'] == 'probe-question' and 'UI not available' in str(tool['content']) + assert 'details' not in tool and 'cancelled' not in str(tool['content']) + system = '\n'.join(str(m['content']) for m in req['messages'] if m['role'] == 'system') + assert '1. ✓ Inspect sample' in system and '2. ☐ Compare sample' in system + # Pi persists a hidden plan-mode context; gf projects it even in execution. + assert any('PLAN MODE ACTIVE' in str(m['content']) for m in req['messages']) + assert 'write' in [t['function']['name'] for t in req['tools']] + rpc(pi + ['--session', str(f)], env, work, status='2/3') + print('PASS Pi 1/3 → gf 2/3 → Pi status 2/3') + + b = tmp/'b' + replies(PLAN) + gold(*common, '--plan', '--session-dir', str(b), '-p', 'Plan another sample.') + f, first = session(b) + assert state(first)['enabled'] + replies(PLAN, 'Noted.', PLAN, 'Noted.', '[DONE:1] [DONE:2] [DONE:3]') + rpc(pi + ['--session', str(f)], env, work, status='plan', prompt='Review the sample.', + choices=['Refine the plan', REFINE, 'Execute the plan (track progress)'], + done=lambda: state(session(b)[1])['todos'] == [] and not state(session(b)[1])['enabled']) + _, second = session(b) + descendant(first, second) + assert any(r.get('message', {}).get('role') == 'user' and REFINE in str(r['message']['content']) for r in second) + kinds = [r.get('customType') for r in second[len(first):]] + cards = [k for k in kinds if k in ('plan-todo-list', 'plan-mode-execute')] + assert cards == ['plan-todo-list', 'plan-todo-list', 'plan-mode-execute'] + assert not server.replies.qsize() + assert any(REFINE in str(r['messages'][-1]['content']) for r in server.requests) + replies('Finished.') + gold(*common, '--session-dir', str(b), '-c', '-p', 'Confirm status.') + _, last = session(b) + descendant(second, last) + assert not progress(last) and not state(last)['executing'] + assert 'write' in [t['function']['name'] for t in server.requests[-1]['tools']] + print('PASS gf plan → Pi Refine/Execute → gf normal') + + # Reopen the checked-in Pi sample without Plan, then restore the same leaf. + golden = tmp/'golden' + golden.mkdir() + file = golden/'sample.jsonl' + fixture = (ROOT/'tests/interop/pi-1.7.0-one-of-three.jsonl').read_text().splitlines() + # Pi requires the header cwd to exist; relocate only this field in the copy. + header = dict(json.loads(fixture[0]), cwd=str(work.resolve())) + file.write_text('\n'.join([json.dumps(header), *fixture[1:]]) + '\n') + _, original = session(golden) + assert progress(original) == [True, False, False] + link = work/'.gf/gfcode/plan-mode' + assert link.is_symlink() + link.unlink() + replies('History is readable.') + gold(*common, '--session-dir', str(golden), '-c', '-p', 'Read the history.') + _, without = session(golden) + descendant(original, without) + assert all(r.get('customType') != 'plan-mode' for r in without[len(original):]) + gold('link', '--local', str(ROOT)) + replies('[DONE:2]') + gold(*common, '--session-dir', str(golden), '-c', '-p', 'Continue the plan.') + _, restored = session(golden) + descendant(without, restored) + assert progress(restored) == [True, True, False] + rpc(pi + ['--session', str(file)], env, work, status='2/3') + print('PASS Pi golden → gf without Plan → relink → Pi status 2/3') + + if not check_fork: + return + fork_dir = tmp/'fork' + fork_dir.mkdir() + subprocess.run(['node', str(ROOT/'tests/interop/fork.mjs'), str(pkg), str(file), str(fork_dir)], + env=env, cwd=work, check=True, timeout=15) + source = file.read_bytes() + fork, before = session(fork_dir) + replies('[DONE:3]') + gold(*common, '--session-dir', str(fork_dir), '-c', '-p', 'Finish the plan.') + _, after = session(fork_dir) + descendant(before, after) + assert not progress(after) and not state(after)['executing'] + assert file.read_bytes() == source + messages = str(server.requests[-1]['messages']) + assert 'The sample plan is executing.' in messages + assert 'after amendment' in messages and 'before amendment' not in messages, ( + f'custom_message edit lost: original={"before amendment" in messages}, ' + f'replacement={"after amendment" in messages}') + print('PASS Pi active-leaf fork + compaction/context_edit → gf completion; sibling unchanged') + + +if __name__ == '__main__': + args = sys.argv[1:] + check_fork = args[:1] == ['--check-fork'] + if check_fork: + args = args[1:] + if len(args) != 2 or not __debug__: + sys.exit('Usage: python3 tests/interop/replay.py [--check-fork] GF_HOST PI_PACKAGE (without -O)') + host, pkg = [Path(arg).resolve() for arg in args] + with tempfile.TemporaryDirectory() as d, ProbeServer() as server: + threading.Thread(target=server.serve_forever, daemon=True).start() + try: + run(Path(d), host, pkg, server, check_fork) + finally: + server.shutdown()