pi-anchorloop 2.6.0 → 2.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/README.zh-TW.md +1 -1
- package/package.json +1 -1
- package/pi/book.ts +46 -5
- package/pi/support/book.ts +75 -4
- package/skills/anchorloop/SKILL.md +1 -1
package/README.md
CHANGED
|
@@ -25,7 +25,7 @@ shared grilling · domain-modeling · human-feedback · agent-terse
|
|
|
25
25
|
|
|
26
26
|
| File | What it does |
|
|
27
27
|
| --- | --- |
|
|
28
|
-
| `pi/book.ts` | The loop book. The first `todo` create opens an `inline` loop (intent from the first todo's subject, anchor from a `Reality anchor:` line or the todo's `metadata.anchor`), and a `kind` call opens or changes one; task records need the `todo` tool of [`@juicesharp/rpiv-todo`](https://github.com/juicesharp/rpiv-mono/tree/main/packages/rpiv-todo#readme) (its `tool_result` details `{tasks, nextId}` and `rpiv-todo-state` entries). The agent declares only what the extension cannot observe with `anchorloop_stage`: `kind` (to choose `quick`, `reviewed`, or `durable`, with an intent and the anchor command; changing a kind the agent chose takes a `reason`), `verify` (a check not run in bash), `fresh-read`, `friction` (`tried`, `found`, `led_by`), `reflect`, `skip`, `back`, `close`, and the query `read`. Everything else is read from evidence: production edits (a write or edit in any git repo, outside its `scratch/` and `docs/specs/`; a linked child's edits and a successful `git merge`, `cherry-pick`, or `pull` count too), the exit code of the bash call that ran the anchor command (an anchor that passed, failed, and passed again records its own friction entry, already reflected as `resolved`: the rerun command and the failed run's key line, at most 120 characters and never a stack trace; the agent is told nothing), reviewer `Blocking: P0=<n> P1=<m>` counts, summaries of `docs/specs/*/` artifacts as they are edited, and a returned subagent that Jev judges to have been a fresh-context read of the spec. A phase machine over that evidence gives each kind a fixed sequence (`quick` act → check; `inline` anchor → act → verify; `reviewed` adds review; `durable` adds decide → grill → spec → read → approve → design; every kind ends with reflect → close), and `read` shows `<kind> · phase <current> ✓ → <next> (missing: …) · skipped: …`. A widget below the editor shows `⚓ <kind> · <current> ✓ → <next>`, with `· N friction` while friction waits for a `reflect`, after every tool call, on `session_start`, and when a `Reality anchor:` line is stated, and clears when the loop closes. An anchor run or declared verify of a `quick` or `inline` loop also measures the diff's reach: source files (not tests, lockfiles, specs, or prose), the top-level directories they sit in, and a README, changelog, or `*.schema.json` changed beside them. Files already changed when a repo joined the loop count only once their content changes, and a file at a repository root counts as a file, not a directory. At 3 source files, 2 directories, or one such file, the result carries one line asking to re-classify, and verify waits for a `kind` call with `reason` that answers each threshold crossed; a later threshold asks again. A phase that starts before an earlier one is complete warns once in one line; phases regress when evidence changes or on `back`. The book also records each todo with its `anchor`, `ref` (`<path>#<heading>`, resolved to line ranges), and `followup` metadata. One YAML book per open loop lives under `~/.pi/agent/anchorloop/books/` (`ANCHORLOOP_BOOKS_DIR` overrides it; empty project and `agents/` directories are removed), subagent books under `agents/` (a child that closes keeps its book for the main session); `session_start` sweeps books whose session is gone or that have not changed in 7 days. `close` answers `closed (landed). Clear the todo list.`, adding only the phases not shown complete and the unreflected friction, and never refuses over phases or friction, only while a pending or in-progress todo lacks `metadata.followup` (a ticket id, `memory`, or `drop — <reason>`). |
|
|
28
|
+
| `pi/book.ts` | The loop book. The first `todo` create opens an `inline` loop (intent from the first todo's subject, anchor from a `Reality anchor:` line or the todo's `metadata.anchor`), and a `kind` call opens or changes one; task records need the `todo` tool of [`@juicesharp/rpiv-todo`](https://github.com/juicesharp/rpiv-mono/tree/main/packages/rpiv-todo#readme) (its `tool_result` details `{tasks, nextId}` and `rpiv-todo-state` entries). The agent declares only what the extension cannot observe with `anchorloop_stage`: `kind` (to choose `quick`, `reviewed`, or `durable`, with an intent and the anchor command; changing a kind the agent chose takes a `reason`), `verify` (a check not run in bash), `fresh-read`, `friction` (`tried`, `found`, `led_by`), `reflect`, `skip`, `back`, `close`, and the query `read`. Everything else is read from evidence: production edits (a write or edit in any git repo, outside its `scratch/` and `docs/specs/`; a linked child's edits and a successful `git merge`, `cherry-pick`, or `pull` count too), the exit code of the bash call that ran the anchor command (an anchor that passed, failed, and passed again records its own friction entry, already reflected as `resolved`: the rerun command and the failed run's key line, at most 120 characters and never a stack trace; the agent is told nothing), reviewer `Blocking: P0=<n> P1=<m>` counts, summaries of `docs/specs/*/` artifacts as they are edited, and a returned subagent that Jev judges to have been a fresh-context read of the spec. A phase machine over that evidence gives each kind a fixed sequence (`quick` act → check; `inline` anchor → act → verify; `reviewed` adds review; `durable` adds decide → grill → spec → read → approve → design; every kind ends with reflect → close), and `read` shows `<kind> · phase <current> ✓ → <next> (missing: …) · skipped: …`. A widget below the editor shows `⚓ <kind> · <current> ✓ → <next>`, with `· N friction` while friction waits for a `reflect`, after every tool call, on `session_start`, and when a `Reality anchor:` line is stated, and clears when the loop closes. An anchor run or declared verify of a `quick` or `inline` loop also measures the diff's reach: source files (not tests, lockfiles, specs, or prose), the top-level directories they sit in, and a README, changelog, or `*.schema.json` changed beside them. Files already changed when a repo joined the loop count only once their content changes, and a file at a repository root counts as a file, not a directory. At 3 source files, 2 directories, or one such file, the result carries one line asking to re-classify, and verify waits for a `kind` call with `reason` that answers each threshold crossed; a later threshold asks again. A phase that starts before an earlier one is complete warns once in one line; phases regress when evidence changes or on `back`. The book also records each todo with its `anchor`, `ref` (`<path>#<heading>`, resolved to line ranges), and `followup` metadata. One YAML book per open loop lives under `~/.pi/agent/anchorloop/books/` (`ANCHORLOOP_BOOKS_DIR` overrides it; empty project and `agents/` directories are removed), subagent books under `agents/` (a child that closes keeps its book for the main session). A child is linked only through [pi-herdr-agents](https://github.com/wayne930242/pi-herdr-agents) (`PI_SUBAGENT_ID` in the child, `details.id` on the parent's `subagent` result; pi itself has no subagents): a linked child's edits are the parent's act, and its anchor runs, recorded as `check`, carry the working-state tree of each repo it works in (tracked and untracked files, ignored files and `scratch/` left out). When a parent's `git merge`, `cherry-pick` or `pull` succeeds, or a subagent result returns, and the parent's working-state trees are exactly the trees of a child's latest run of the same anchor (a leading `cd` into a repo root aside), and that run passed, the parent records it as its own verify (`adopted`): a fast-forward of a worker's branch, or a child that worked in the parent's checkout, needs no second run, while a merge onto a base that moved, a parent edit or repo the child never saw, or a file the child ran with but did not commit does; `session_start` sweeps books whose session is gone or that have not changed in 7 days. `close` answers `closed (landed). Clear the todo list.`, adding only the phases not shown complete and the unreflected friction, and never refuses over phases or friction, only while a pending or in-progress todo lacks `metadata.followup` (a ticket id, `memory`, or `drop — <reason>`). |
|
|
29
29
|
| `pi/anchor-gate.ts` | Inside an open loop, appends one warning line to the edit's tool result (where the agent reads it) when `write` or `edit` starts the `act` phase while an earlier phase of the loop kind is incomplete: no anchor (`anchor` on the `kind` call, a `Reality anchor:` line, or a skip), and in a `durable` loop a missing decision, spec, fresh read, approval, or design, read from the `docs/specs/<folder>/` files (found from the book, the intent, or a todo `ref`). It warns again only when a new phase goes missing; the call still goes through. Outside a loop and in `quick` loops it stays silent. `.md`, `.txt`, and `.html` files, `scratch/`, `docs/specs/`, and temp files outside the project pass silently. Edits made through `bash` are not checked. |
|
|
30
30
|
| `pi/decision-tool.ts` | The `anchorloop_decision` tool appends single-line, spreadsheet-safe rows to a decision trail TSV for forks, pivots, and blockers (completed units come from `git log`), or a `start` row when a run picks up another run's trail. |
|
|
31
31
|
| `pi/second-thought.ts` | Inside an open loop, asks Jev (TypeSafe's typed-decision model, through pi's classifier registry) to check the phase machine when a run settles and the loop book gained an entry since the last judgment, and at a `close` declaration. The program computes the next phase from the book; Jev sees the kind, intent, anchor, diff summary (≤1200 chars), `phase` (current, next, missing), verify state, the open todos by id and subject, the task list, and friction (a child's under its name), and judges only whether to `advance`, go `back`, or `ask-user`, plus `done`, the review tier still needed, and quality; phase completion comes from the program's evidence alone. The advisory is `next: <phase> (<missing>)` plus Jev's concerns, with no scores. It is sent only when Jev has a concern, todos are open without a followup, or the run continues, and stays silent when Jev agrees with nothing to add (the verdict is still recorded in the session); at close it carries concerns only. Away from close it also names the loop's open todos that have no valid `metadata.followup` (the first three, subjects cut to 60 characters, then `+N more`) and asks the agent to continue each, complete it, or set that followup. The run continues once, when Jev agrees to advance and the next phase is a verify, review, or fix, or when such todos are open and Jev's move is not `ask-user` (then the advisory tells the agent to ask the user instead); an advisory with the same next phase, concerns, and open todo ids as the last one is not repeated, and a `full` rating after a clean review that follows the last change is not a concern. A run that called `MonitorCreate`, `LoopCreate`, `goal_wait`, or a `subagent` tool is waiting and is not judged. Without a TypeSafe key it does nothing, and outside a loop it never runs. In a subagent session (`PI_SUBAGENT_ID` from pi-herdr-agents, or `PI_SUBAGENT_CHILD` from pi-subagents) it registers nothing, since the agent that spawned it judges the result. |
|
package/README.zh-TW.md
CHANGED
|
@@ -25,7 +25,7 @@ anchorloop 核心循環 · 原則 · playbook:autonomous-run、paus
|
|
|
25
25
|
|
|
26
26
|
| 檔案 | 作用 |
|
|
27
27
|
| --- | --- |
|
|
28
|
-
| `pi/book.ts` | Loop book。第一次 `todo` create 會以 `inline` 開啟 loop(intent 取第一個 todo 的標題,anchor 取 `Reality anchor:` 這一行或該 todo 的 `metadata.anchor`),`kind` 呼叫也能開啟或更改 loop;任務紀錄需要 [`@juicesharp/rpiv-todo`](https://github.com/juicesharp/rpiv-mono/tree/main/packages/rpiv-todo#readme) 的 `todo` 工具(它的 `tool_result` details `{tasks, nextId}` 和 `rpiv-todo-state` 條目)。agent 只用 `anchorloop_stage` 宣告 extension 看不到的事:`kind`(用來選 `quick`、`reviewed` 或 `durable`,附 intent 和 anchor 指令;改掉 agent 自己選的種類時,必須附 `reason`)、`verify`(不是指令的檢查)、`fresh-read`、`friction`(`tried`、`found`、`led_by`)、`reflect`、`skip`、`back`、`close`,以及查詢用的 `read`。其餘都從證據讀出:production 的修改(任何 git repo 內、`scratch/` 與 `docs/specs/` 以外的 write 或 edit;已連結 child 的修改,以及成功的 `git merge`、`cherry-pick`、`pull` 也算)、執行過 anchor 指令的那次 bash 的 exit code(anchor 通過後失敗、又再通過時,extension 會自己記一筆 friction,並直接 reflect 為 `resolved`:重跑的指令,加上失敗那次最關鍵的一行輸出,最多 120 字元,不放 stack trace;不會通知 agent)、reviewer 的 `Blocking: P0=<n> P1=<m>` 數字、`docs/specs/*/` 產出物每次編輯後的摘要,以及 Jev 判定為「全新 context 讀過 spec」的 subagent 回報。階段機依這些證據給每種 loop 固定的階段順序(`quick` 為 act → check;`inline` 為 anchor → act → verify;`reviewed` 加 review;`durable` 再加 decide → grill → spec → read → approve → design;每一種都以 reflect → close 結尾),`read` 顯示 `<種類> · phase <目前> ✓ → <下一個>(缺:…)· 已跳過:…`。編輯器下方的 widget 會顯示 `⚓ <種類> · <目前> ✓ → <下一個>`,還有 friction 等著 `reflect` 時附 `· N friction`;每次工具呼叫後、`session_start` 時,以及 agent 寫出 `Reality anchor:` 這一行時更新,loop 結案後清掉。`quick` 或 `inline` loop 跑 anchor 或宣告 verify 時,也會量 diff 的影響範圍:原始碼檔案(不含測試、lockfile、spec 與文字檔)、它們所在的頂層目錄,以及跟原始碼一起改的 README、changelog 或 `*.schema.json`。repo 加入 loop 時就已經改過的檔案,要等內容再變動才算;repo 根目錄的檔案只算檔案數,不算一個目錄。達到 3 個原始碼檔案、2 個目錄或 1 個這類檔案時,結果會附一行請 agent 重新分類;verify 要等到以 `reason` 呼叫 `kind`、回應每一個跨過的門檻才算完成,之後再跨過新的門檻會再問一次。前一個階段還沒完成就開始下一個階段,會用一行警告一次;證據改變或用 `back` 時階段會退回。book 也記錄每個 todo 的 `anchor`、`ref`(`<path>#<heading>`,解析成行號範圍)和 `followup` metadata。每個開啟中的 loop 有一份 YAML book,放在 `~/.pi/agent/anchorloop/books/`(可用 `ANCHORLOOP_BOOKS_DIR` 覆寫),subagent 的 book 放在 `agents/`(subagent 自己 close 時 book 留給主 session
|
|
28
|
+
| `pi/book.ts` | Loop book。第一次 `todo` create 會以 `inline` 開啟 loop(intent 取第一個 todo 的標題,anchor 取 `Reality anchor:` 這一行或該 todo 的 `metadata.anchor`),`kind` 呼叫也能開啟或更改 loop;任務紀錄需要 [`@juicesharp/rpiv-todo`](https://github.com/juicesharp/rpiv-mono/tree/main/packages/rpiv-todo#readme) 的 `todo` 工具(它的 `tool_result` details `{tasks, nextId}` 和 `rpiv-todo-state` 條目)。agent 只用 `anchorloop_stage` 宣告 extension 看不到的事:`kind`(用來選 `quick`、`reviewed` 或 `durable`,附 intent 和 anchor 指令;改掉 agent 自己選的種類時,必須附 `reason`)、`verify`(不是指令的檢查)、`fresh-read`、`friction`(`tried`、`found`、`led_by`)、`reflect`、`skip`、`back`、`close`,以及查詢用的 `read`。其餘都從證據讀出:production 的修改(任何 git repo 內、`scratch/` 與 `docs/specs/` 以外的 write 或 edit;已連結 child 的修改,以及成功的 `git merge`、`cherry-pick`、`pull` 也算)、執行過 anchor 指令的那次 bash 的 exit code(anchor 通過後失敗、又再通過時,extension 會自己記一筆 friction,並直接 reflect 為 `resolved`:重跑的指令,加上失敗那次最關鍵的一行輸出,最多 120 字元,不放 stack trace;不會通知 agent)、reviewer 的 `Blocking: P0=<n> P1=<m>` 數字、`docs/specs/*/` 產出物每次編輯後的摘要,以及 Jev 判定為「全新 context 讀過 spec」的 subagent 回報。階段機依這些證據給每種 loop 固定的階段順序(`quick` 為 act → check;`inline` 為 anchor → act → verify;`reviewed` 加 review;`durable` 再加 decide → grill → spec → read → approve → design;每一種都以 reflect → close 結尾),`read` 顯示 `<種類> · phase <目前> ✓ → <下一個>(缺:…)· 已跳過:…`。編輯器下方的 widget 會顯示 `⚓ <種類> · <目前> ✓ → <下一個>`,還有 friction 等著 `reflect` 時附 `· N friction`;每次工具呼叫後、`session_start` 時,以及 agent 寫出 `Reality anchor:` 這一行時更新,loop 結案後清掉。`quick` 或 `inline` loop 跑 anchor 或宣告 verify 時,也會量 diff 的影響範圍:原始碼檔案(不含測試、lockfile、spec 與文字檔)、它們所在的頂層目錄,以及跟原始碼一起改的 README、changelog 或 `*.schema.json`。repo 加入 loop 時就已經改過的檔案,要等內容再變動才算;repo 根目錄的檔案只算檔案數,不算一個目錄。達到 3 個原始碼檔案、2 個目錄或 1 個這類檔案時,結果會附一行請 agent 重新分類;verify 要等到以 `reason` 呼叫 `kind`、回應每一個跨過的門檻才算完成,之後再跨過新的門檻會再問一次。前一個階段還沒完成就開始下一個階段,會用一行警告一次;證據改變或用 `back` 時階段會退回。book 也記錄每個 todo 的 `anchor`、`ref`(`<path>#<heading>`,解析成行號範圍)和 `followup` metadata。每個開啟中的 loop 有一份 YAML book,放在 `~/.pi/agent/anchorloop/books/`(可用 `ANCHORLOOP_BOOKS_DIR` 覆寫),subagent 的 book 放在 `agents/`(subagent 自己 close 時 book 留給主 session)。子代理只透過 [pi-herdr-agents](https://github.com/wayne930242/pi-herdr-agents) 關聯(子行程的 `PI_SUBAGENT_ID`、父 session `subagent` 結果的 `details.id`;pi 本身沒有 subagent):關聯的子代理,其改動算父 loop 的 act;其 anchor 執行記為 `check`,並附上它所在各 repo 的工作狀態 tree(含已追蹤與未追蹤檔案,不含 ignored 檔案與 `scratch/`)。父 session 的 `git merge`、`cherry-pick`、`pull` 成功時,或收到子代理結果時,若父 session 的工作狀態 tree 正好等於子代理最近一次同一 anchor 執行(忽略開頭切到 repo 根目錄的 `cd`)的 tree,且那次通過,就把它記為父 loop 自己的 verify(`adopted`):fast-forward 合入 worker 分支、或子代理直接在父 checkout 裡工作,都不必再跑一次;合到已前進的 base、父 session 有子代理沒看過的改動或 repo、或子代理跑測試時有沒 commit 的檔案,則要自己跑;`session_start` 會清掉 session 已不存在或 7 天沒有更新的 book。`close` 回覆 `closed (landed). Clear the todo list.`,只多列沒有完成的階段和還沒 reflect 的 friction;它不會因為階段或 friction 而拒絕,只在還有 pending 或 in-progress 的 todo 沒有 `metadata.followup`(票號、`memory` 或 `drop — <原因>`)時拒絕。 |
|
|
29
29
|
| `pi/anchor-gate.ts` | 只在開啟的 loop 內:`write` 或 `edit` 開始 `act` 階段、而這種 loop 前面的階段還沒完成時,把一行警告附在該次編輯的 tool result 後面(agent 在那裡讀到它):沒有 anchor(kind 呼叫的 `anchor`、`Reality anchor:` 這一行,或已跳過),`durable` loop 則還缺決策、spec、全新 context 的閱讀、核准或設計(從 `docs/specs/<資料夾>/` 的檔案判斷,資料夾由 book、intent 或 todo 的 `ref` 找出)。只有新缺了一個階段時才會再警告;呼叫仍會放行。沒有 loop 或是 `quick` loop 時保持安靜。`.md`、`.txt`、`.html` 檔、`scratch/`、`docs/specs/` 和專案外的暫存檔不會觸發。透過 `bash` 做的修改不檢查。 |
|
|
30
30
|
| `pi/decision-tool.ts` | `anchorloop_decision` 工具把一筆決策寫進 TSV 決策軌跡(記岔路、轉向與卡點;完成的工作單元看 `git log`),每筆只佔一行,用試算表開啟也安全;接手別人的軌跡時寫一筆 `start`。 |
|
|
31
31
|
| `pi/second-thought.ts` | 只在開啟的 loop 內:一次執行結束且 book 自上次判斷後多了條目時,以及宣告 `close` 時,透過 pi 的 classifier registry 請 Jev(TypeSafe 的型別化決策模型)複核階段機。下一個階段由程式從 book 算出;Jev 看到種類、intent、anchor、diff 摘要(≤1200 字元)、`phase`(目前、下一個、缺什麼)、verify 狀態、未完成 todo(id 與標題)、任務清單和 friction(子 agent 的以它的名字列出),只判斷要 `advance`、退回(`back`)還是 `ask-user`,另外還問 `done`、還需要哪一級 review 與品質;階段是否完成只由程式依證據判定。提醒是 `next: <階段>(<缺什麼>)` 加上 Jev 的疑慮,不附分數;只在 Jev 有疑慮、有 todo 未完成而沒有 followup、或這次會讓 agent 多跑一輪時才送出,Jev 同意且沒有補充時保持安靜(判斷結果仍記在 session 裡);結案時只附疑慮。離開 close 時,提醒也會點名 loop 中還沒有有效 `metadata.followup` 的未完成 todo(前三個,標題截成 60 字元,其餘以 `+N more` 帶過),請 agent 逐一繼續、完成,或設定該 followup。Jev 同意前進、而下一個階段是 verify、review 或 fix,或有這類 todo 未完成且 Jev 的判斷不是 `ask-user`(此時提醒改請 agent 去問使用者)時,才讓 agent 多跑一輪;下一個階段、疑慮和未完成 todo 的 id 都與上一則相同的提醒不重複;最後一次修改之後已有無 blocking 發現的 review 時,`full` 評等不算疑慮。呼叫過 `MonitorCreate`、`LoopCreate`、`goal_wait` 或 `subagent` 工具的執行在等待中,不被判斷。沒有 TypeSafe key 時什麼都不做,沒有 loop 時不會執行。subagent session(pi-herdr-agents 的 `PI_SUBAGENT_ID`,或 pi-subagents 的 `PI_SUBAGENT_CHILD`)不註冊任何東西,因為由派它的 agent 判斷結果。 |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-anchorloop",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.7.0",
|
|
4
4
|
"description": "Agent workflow skills for pi: one entry skill per task type, each with playbooks, over a shared Align → Anchor → Act → Verify loop, plus loop extensions (loop book, anchor gate, decision trail tool, Jev second thought, skill validator, stream rules).",
|
|
5
5
|
"author": "Wei Hung",
|
|
6
6
|
"license": "MIT",
|
package/pi/book.ts
CHANGED
|
@@ -20,6 +20,7 @@ import {
|
|
|
20
20
|
anchorCommand,
|
|
21
21
|
appendEntry,
|
|
22
22
|
artifactKind,
|
|
23
|
+
bases,
|
|
23
24
|
childId,
|
|
24
25
|
childIds,
|
|
25
26
|
childLines,
|
|
@@ -36,6 +37,7 @@ import {
|
|
|
36
37
|
openLoop,
|
|
37
38
|
replayTodos,
|
|
38
39
|
refsOf,
|
|
40
|
+
repoRootOf,
|
|
39
41
|
retryPairs,
|
|
40
42
|
resolveRef,
|
|
41
43
|
reviewTrend,
|
|
@@ -51,6 +53,8 @@ import {
|
|
|
51
53
|
touchRepoBeforeMerge,
|
|
52
54
|
validFollowup,
|
|
53
55
|
verifyAfterLastAct,
|
|
56
|
+
workingTrees,
|
|
57
|
+
adoptableRun,
|
|
54
58
|
} from "./support/book.ts";
|
|
55
59
|
import { classify } from "./support/jev.ts";
|
|
56
60
|
import { REVIEWLESS, SEQUENCES, computePhases, describe, incompleteBefore, outsideWork, reachLine, reachOf, unansweredReach } from "./support/phases.ts";
|
|
@@ -616,6 +620,38 @@ export default function (pi: ExtensionAPI) {
|
|
|
616
620
|
return reach && unansweredReach(book.entries, reach).length > 0 ? `anchorloop: ${reachLine(reach, currentKind(book.entries))}.` : undefined;
|
|
617
621
|
}
|
|
618
622
|
|
|
623
|
+
/** The repos the loop works in: the repos it changed and the one it runs in. */
|
|
624
|
+
function loopRepos(book: Book, cwd: string): string[] {
|
|
625
|
+
const here = repoRootOf(join(cwd, "_"));
|
|
626
|
+
return [...new Set([...bases(book.entries).map((base) => base.repo), ...(here ? [here] : [])])];
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
function loopTrees(book: Book, cwd: string): string[] {
|
|
630
|
+
return workingTrees(loopRepos(book, cwd));
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
/** A child's anchor run carries the trees it ran on, so the coordinator can tell whether it holds that same state. */
|
|
634
|
+
function treesField(book: Book, cwd: string): { trees?: string[] } {
|
|
635
|
+
const trees = loopTrees(book, cwd);
|
|
636
|
+
return trees.length ? { trees } : {};
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
/**
|
|
640
|
+
* Records a linked child's passing run of the loop anchor as this loop's verify when the loop now holds exactly the state
|
|
641
|
+
* that run checked (after a merge lands a worker's branch, or when a child that worked in this checkout returns), so the
|
|
642
|
+
* coordinator does not run the anchor a second time. Any other state, or another command, leaves verify to its own run.
|
|
643
|
+
*/
|
|
644
|
+
function adoptChildRun(book: Book, cwd: string): void {
|
|
645
|
+
const anchor = anchorCommand(book.entries);
|
|
646
|
+
if (!anchor || verifyAfterLastAct(book.entries) || !book.entries.some((entry) => entry.stage === "link")) return;
|
|
647
|
+
const repos = loopRepos(book, cwd);
|
|
648
|
+
const trees = workingTrees(repos);
|
|
649
|
+
const found = adoptableRun(book.entries, anchor, trees, repos, cwd);
|
|
650
|
+
if (!found) return;
|
|
651
|
+
const last = `adopted from ${found.name}${found.run.last ? `: ${String(found.run.last)}` : ""}`.slice(0, 200);
|
|
652
|
+
book.entries.push(appendEntry(book.path, "verify", { command: anchor.slice(0, 200), exit: 0, last, adopted: found.name, trees, ...reachField(book, cwd) }));
|
|
653
|
+
}
|
|
654
|
+
|
|
619
655
|
/**
|
|
620
656
|
* Records what a finished bash call shows: runs of the loop anchor, of task anchors, and a first commit as the change.
|
|
621
657
|
* Returns the re-classification line when an anchor run of an unreviewed loop measured a reach no `kind` answer covers.
|
|
@@ -631,9 +667,10 @@ export default function (pi: ExtensionAPI) {
|
|
|
631
667
|
// A failed run keeps its key line, so a rerun that passes can name what failed without the whole output.
|
|
632
668
|
const keyOf = (code: unknown) => (typeof code === "number" && code !== 0 ? { key: keyLine(output) } : {});
|
|
633
669
|
if (anchor && anchorRun(command, anchor)) {
|
|
634
|
-
const
|
|
670
|
+
const child = childId() !== undefined;
|
|
671
|
+
const recorded = child || currentKind(book.entries) === "quick" ? "check" : "verify";
|
|
635
672
|
const code = anchorExit(command, anchor, exit);
|
|
636
|
-
const entry = appendEntry(book.path, recorded, { command: anchor.slice(0, 200), exit: code, last, ...keyOf(code), ...reachField(book, cwd) });
|
|
673
|
+
const entry = appendEntry(book.path, recorded, { command: anchor.slice(0, 200), exit: code, last, ...keyOf(code), ...reachField(book, cwd), ...(child ? treesField(book, cwd) : {}) });
|
|
637
674
|
book.entries.push(entry);
|
|
638
675
|
const reach = reachNotice(book, entry);
|
|
639
676
|
if (reach) notices.push(reach);
|
|
@@ -645,9 +682,12 @@ export default function (pi: ExtensionAPI) {
|
|
|
645
682
|
}
|
|
646
683
|
autoFriction(book);
|
|
647
684
|
const merged = mergeRun(command);
|
|
648
|
-
if (exit === 0 && merged && !/Already up[ -]to[ -]date/i.test(last ?? "")
|
|
649
|
-
|
|
650
|
-
|
|
685
|
+
if (exit === 0 && merged && !/Already up[ -]to[ -]date/i.test(last ?? "")) {
|
|
686
|
+
if (book.entries.at(-1)?.stage !== "edit") {
|
|
687
|
+
touchRepoBeforeMerge(book, resolve(String(book.header.cwd ?? process.cwd()), merged.dir), merged.verb);
|
|
688
|
+
book.entries.push(appendEntry(book.path, "edit", { via: "merge" }));
|
|
689
|
+
}
|
|
690
|
+
adoptChildRun(book, cwd);
|
|
651
691
|
}
|
|
652
692
|
if (exit === 0 && /\bgit\b[^|;&]*\bcommit\b/.test(command) && !book.entries.some((entry) => entry.stage === "edit")) {
|
|
653
693
|
const cwd = String(book.header.cwd ?? "");
|
|
@@ -828,6 +868,7 @@ function headAndTail(text: string): string {
|
|
|
828
868
|
showStatus(ctx);
|
|
829
869
|
}
|
|
830
870
|
if (message.role !== "custom" || message.customType !== "subagent_result" || subagent) return;
|
|
871
|
+
adoptChildRun(book, ctx.cwd);
|
|
831
872
|
const agent = String(message.details?.agent ?? "");
|
|
832
873
|
if (REVIEWERS.has(agent)) {
|
|
833
874
|
const d = message.details ?? {};
|
package/pi/support/book.ts
CHANGED
|
@@ -7,8 +7,8 @@
|
|
|
7
7
|
|
|
8
8
|
import { createHash, randomUUID } from "node:crypto";
|
|
9
9
|
import { execFileSync } from "node:child_process";
|
|
10
|
-
import { closeSync, constants, existsSync, mkdirSync, openSync, readdirSync, readFileSync, realpathSync, renameSync, rmdirSync, statSync, unlinkSync, writeSync } from "node:fs";
|
|
11
|
-
import { homedir } from "node:os";
|
|
10
|
+
import { closeSync, constants, copyFileSync, existsSync, mkdirSync, mkdtempSync, openSync, readdirSync, readFileSync, realpathSync, renameSync, rmdirSync, rmSync, statSync, unlinkSync, utimesSync, writeSync } from "node:fs";
|
|
11
|
+
import { homedir, tmpdir } from "node:os";
|
|
12
12
|
import { basename, dirname, join, resolve } from "node:path";
|
|
13
13
|
|
|
14
14
|
export const KINDS = ["quick", "inline", "reviewed", "durable"] as const;
|
|
@@ -541,14 +541,85 @@ export function validFollowup(followup: unknown): boolean {
|
|
|
541
541
|
|
|
542
542
|
// --- git -----------------------------------------------------------------------------------------
|
|
543
543
|
|
|
544
|
-
function git(cwd: string, args: string[]): string | undefined {
|
|
544
|
+
function git(cwd: string, args: string[], env?: NodeJS.ProcessEnv): string | undefined {
|
|
545
545
|
try {
|
|
546
|
-
return execFileSync("git", ["-C", cwd, ...args], { encoding: "utf-8", timeout: 5000, stdio: ["ignore", "pipe", "ignore"] }).trim();
|
|
546
|
+
return execFileSync("git", ["-C", cwd, ...args], { encoding: "utf-8", timeout: 5000, stdio: ["ignore", "pipe", "ignore"], env: env ?? process.env }).trim();
|
|
547
547
|
} catch {
|
|
548
548
|
return undefined;
|
|
549
549
|
}
|
|
550
550
|
}
|
|
551
551
|
|
|
552
|
+
/**
|
|
553
|
+
* The tree a commit of everything in `repo`'s working state would have (tracked and untracked, ignored files and `scratch/`
|
|
554
|
+
* left out), built in a copy of the index so the repo's own index is untouched; undefined when git cannot build it.
|
|
555
|
+
*/
|
|
556
|
+
export function workingTree(repo: string): string | undefined {
|
|
557
|
+
const index = git(repo, ["rev-parse", "--path-format=absolute", "--git-path", "index"]);
|
|
558
|
+
if (!index) return undefined;
|
|
559
|
+
const dir = mkdtempSync(join(tmpdir(), "anchorloop-tree-"));
|
|
560
|
+
try {
|
|
561
|
+
const env = { ...process.env, GIT_INDEX_FILE: join(dir, "index") };
|
|
562
|
+
if (existsSync(index)) {
|
|
563
|
+
// The copy keeps the index's mtime: git trusts an entry's stat only when it is older than the index, and a file
|
|
564
|
+
// changed in the second the index was written but kept its size would otherwise be taken as unchanged.
|
|
565
|
+
copyFileSync(index, env.GIT_INDEX_FILE);
|
|
566
|
+
const { atime, mtime } = statSync(index);
|
|
567
|
+
utimesSync(env.GIT_INDEX_FILE, atime, mtime);
|
|
568
|
+
}
|
|
569
|
+
if (git(repo, ["add", "-A", "--", ".", ":(exclude)scratch"], env) === undefined) return undefined;
|
|
570
|
+
return git(repo, ["write-tree"], env);
|
|
571
|
+
} finally {
|
|
572
|
+
rmSync(dir, { recursive: true, force: true });
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
/** The working-state tree of each repo in `repos`, leaving out a repo git cannot build one for. */
|
|
577
|
+
export function workingTrees(repos: Iterable<string>): string[] {
|
|
578
|
+
return [...new Set(repos)].map(workingTree).filter((tree): tree is string => tree !== undefined);
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
const CD_STEP = /^cd\s+("[^"]*"|'[^']*'|\S+)\s*(?:&&|;)\s*/;
|
|
582
|
+
|
|
583
|
+
/**
|
|
584
|
+
* The command without the leading `cd <dir> &&` (or `;`) steps whose directory is one of `roots`, the roots of the loop's
|
|
585
|
+
* repos, so one anchor run from two checkouts reads the same; a `cd` into a subdirectory stays, since it runs other tests.
|
|
586
|
+
*/
|
|
587
|
+
function anchorBody(command: string, roots: string[], cwd: string): string {
|
|
588
|
+
let rest = command.trim();
|
|
589
|
+
for (let step = CD_STEP.exec(rest); step; step = CD_STEP.exec(rest)) {
|
|
590
|
+
const target = step[1].replace(/^(["'])(.*)\1$/, "$2").replace(/^~(?=\/|$)/, homedir());
|
|
591
|
+
if (!roots.includes(real(resolve(cwd, target)))) break;
|
|
592
|
+
rest = rest.slice(step[0].length);
|
|
593
|
+
}
|
|
594
|
+
return rest.replace(/\s+/g, " ");
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
/**
|
|
598
|
+
* The linked child whose latest run of `anchor` passed on exactly the state the coordinator holds: the trees that run
|
|
599
|
+
* recorded are the coordinator's `trees`, no more and no fewer, so a repo only one side worked in is never taken as checked.
|
|
600
|
+
* `roots` and `cwd` are the coordinator's repo roots and directory. Only a pi-herdr-agents child is linked
|
|
601
|
+
* (`PI_SUBAGENT_ID`); pi itself has no subagents.
|
|
602
|
+
*/
|
|
603
|
+
export function adoptableRun(entries: Entry[], anchor: string, trees: string[], roots: string[], cwd: string, env: NodeJS.ProcessEnv = process.env): { name: string; run: Entry } | undefined {
|
|
604
|
+
const body = anchorBody(anchor, roots, cwd);
|
|
605
|
+
const held = new Set(trees);
|
|
606
|
+
for (const id of childIds(entries)) {
|
|
607
|
+
const runs = findChildBooks(id, env).flatMap(({ book }) => {
|
|
608
|
+
const home = String(book.header.cwd ?? "");
|
|
609
|
+
const here = home ? repoRootOf(join(home, "_")) : undefined;
|
|
610
|
+
const childRoots = [...bases(book.entries).map((base) => base.repo), ...(here ? [here] : [])];
|
|
611
|
+
return book.entries.filter((entry) => entry.stage === "check" && typeof entry.command === "string" && anchorBody(entry.command, childRoots, home) === body);
|
|
612
|
+
});
|
|
613
|
+
const run = runs.sort((a, b) => a.ts.localeCompare(b.ts)).at(-1);
|
|
614
|
+
const checked = new Set(Array.isArray(run?.trees) ? (run.trees as unknown[]).map(String) : []);
|
|
615
|
+
if (run && run.exit === 0 && checked.size === held.size && [...checked].every((tree) => held.has(tree))) {
|
|
616
|
+
const link = entries.find((entry) => entry.stage === "link" && entry.child === id);
|
|
617
|
+
return { name: String(link?.name ?? id), run };
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
return undefined;
|
|
621
|
+
}
|
|
622
|
+
|
|
552
623
|
function existingDir(path: string): string {
|
|
553
624
|
let dir = path;
|
|
554
625
|
while (!existsSync(dir) && dirname(dir) !== dir) dir = dirname(dir);
|
|
@@ -15,7 +15,7 @@ Pick the entry's playbook from its index; with none fitting, run the loop bare.
|
|
|
15
15
|
|
|
16
16
|
Before the first change the loop has an anchor: a `Reality anchor: <the exact check that observes the result, and its checkpoint>` line, `metadata.anchor` on the first todo, or `anchor` on a `kind` call. The first edit without one gets a one-line reminder in its result.
|
|
17
17
|
|
|
18
|
-
Size the anchor to the change's reach and pick one method: an executable check, a user operation, human judgment, or a focused review. A coordinator's anchor governs. Pick a review anchor when the change touches a shared contract, authorization or permission data, a migration, or security; other changes rest on their check and the author's own read of the diff. A review anchor names the realistic use it judges against and blocks on P0 and P1 findings only, recording lower ones as follow-ups. Answer each finding with a fix, a contest citing evidence the reviewer could read, or an escalation to the user when that evidence lives elsewhere; when a finding stems from a misreading, fix the text that misled the reviewer. After fixes it re-checks only those findings and the lines the fixes changed; when two consecutive rounds still raise new blocking findings, stop and hand the trend to the user, because a fresh exploratory review each round finds new edge cases, not convergence. The checkpoint is normally once, after the last increment.
|
|
18
|
+
Size the anchor to the change's reach and pick one method: an executable check, a user operation, human judgment, or a focused review. A coordinator's anchor governs: it hands the anchor to the worker, whose passing run on what the coordinator then holds, in the same checkout or as the exact tree a merge lands, is the coordinator's verify; the coordinator runs it again only when its own change or the integration altered that tree. Pick a review anchor when the change touches a shared contract, authorization or permission data, a migration, or security; other changes rest on their check and the author's own read of the diff. A review anchor names the realistic use it judges against and blocks on P0 and P1 findings only, recording lower ones as follow-ups. Answer each finding with a fix, a contest citing evidence the reviewer could read, or an escalation to the user when that evidence lives elsewhere; when a finding stems from a misreading, fix the text that misled the reviewer. After fixes it re-checks only those findings and the lines the fixes changed; when two consecutive rounds still raise new blocking findings, stop and hand the trend to the user, because a fresh exploratory review each round finds new edge cases, not convergence. The checkpoint is normally once, after the last increment.
|
|
19
19
|
|
|
20
20
|
## Act
|
|
21
21
|
|