@andares/pi-toolkits 0.12.3 → 0.13.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.
Files changed (65) hide show
  1. package/README.md +100 -15
  2. package/README.zh-CN.md +94 -14
  3. package/package.json +19 -10
  4. package/src/features/ask/index.ts +6 -0
  5. package/src/features/init/apply.ts +32 -12
  6. package/src/features/init/audit-uat.test.ts +103 -0
  7. package/src/features/init/audit.ts +148 -0
  8. package/src/features/init/detect.ts +4 -0
  9. package/src/features/init/index.ts +47 -2
  10. package/src/features/init/plan.ts +11 -0
  11. package/src/features/init/refresh.test.ts +208 -0
  12. package/src/features/init/refresh.ts +255 -0
  13. package/src/features/init/spec.ts +20 -0
  14. package/src/features/init/templates/agents-skeleton.md +2 -0
  15. package/src/features/init/templates/uat-readme.md +53 -0
  16. package/src/features/init/templates/workflow-block.md +21 -0
  17. package/src/features/init/templates.test.ts +3 -1
  18. package/src/features/init/templates.ts +2 -0
  19. package/src/features/init/types.ts +12 -1
  20. package/src/features/permission/index.ts +32 -0
  21. package/src/features/plan/assets/index-C1YLIi4I.js +1 -0
  22. package/src/features/plan/assets/index-DMEpYC3V.css +1 -0
  23. package/src/features/plan/assets/index.html +14 -0
  24. package/src/features/plan/assets.test.ts +64 -0
  25. package/src/features/plan/blocks.test.ts +77 -0
  26. package/src/features/plan/blocks.ts +153 -0
  27. package/src/features/plan/diff.test.ts +144 -0
  28. package/src/features/plan/diff.ts +193 -0
  29. package/src/features/plan/feedback.test.ts +233 -0
  30. package/src/features/plan/feedback.ts +182 -0
  31. package/src/features/plan/index.test.ts +385 -0
  32. package/src/features/plan/index.ts +433 -0
  33. package/src/features/plan/prompt.test.ts +91 -0
  34. package/src/features/plan/prompt.ts +110 -0
  35. package/src/features/plan/render.test.ts +94 -0
  36. package/src/features/plan/render.ts +131 -0
  37. package/src/features/plan/server.test.ts +374 -0
  38. package/src/features/plan/server.ts +272 -0
  39. package/src/features/plan/store.test.ts +145 -0
  40. package/src/features/plan/store.ts +244 -0
  41. package/src/features/review/index.ts +54 -28
  42. package/src/features/review/review.test.ts +46 -1
  43. package/src/features/uat/assets/index-D-W9zj0w.css +1 -0
  44. package/src/features/uat/assets/index-DCBQCsli.js +1 -0
  45. package/src/features/uat/assets/index.html +14 -0
  46. package/src/features/uat/constants.ts +23 -0
  47. package/src/features/uat/index.test.ts +404 -0
  48. package/src/features/uat/index.ts +329 -0
  49. package/src/features/uat/item-tool.ts +280 -0
  50. package/src/features/uat/ledger.test.ts +249 -0
  51. package/src/features/uat/ledger.ts +504 -0
  52. package/src/features/uat/prompt.ts +78 -0
  53. package/src/features/uat/record-tool.ts +167 -0
  54. package/src/features/uat/records.test.ts +145 -0
  55. package/src/features/uat/records.ts +268 -0
  56. package/src/features/uat/server.ts +181 -0
  57. package/src/features/uat/state.test.ts +41 -0
  58. package/src/features/uat/state.ts +67 -0
  59. package/src/index.ts +10 -1
  60. package/src/lib/ask-control.ts +25 -0
  61. package/src/lib/opener.test.ts +72 -0
  62. package/src/lib/opener.ts +121 -0
  63. package/src/lib/permission-control.ts +39 -0
  64. package/src/lib/startup.test.ts +1 -1
  65. package/src/lib/web-review.ts +341 -0
@@ -0,0 +1,255 @@
1
+ /**
2
+ * init feature — `/ask-init refresh`: bring the framework-owned text up to date.
3
+ *
4
+ * Every feature this toolkit ships adds prose to the project: the memory
5
+ * contract, the signpost, the workflow block in `AGENTS.md`, the acceptance
6
+ * ledger contract. Re-running `/ask-init` cannot refresh them (it refuses to
7
+ * overwrite an existing file — that is the rule that keeps it safe), so refresh
8
+ * is the one path allowed to rewrite framework-owned bytes. It earns that with
9
+ * three rules:
10
+ *
11
+ * 1. **Managed files are rewritten only when the disk still equals the anchor**
12
+ * — the hash of the bytes this tool rendered last time. Anything else is a
13
+ * hand edit, and overwriting it would destroy operator work: skip + report.
14
+ * 2. **`AGENTS.md` is touched only between its workflow markers.** If the
15
+ * markers are absent the block is inserted deterministically (before the
16
+ * first appendix, else at the end); outside the block, not one byte moves.
17
+ * 3. **Missing optional pieces are created** (the UAT contract), so a project
18
+ * that adopted the framework before the ledger existed can catch up.
19
+ *
20
+ * The command is idempotent: a second run reports "current" everywhere.
21
+ */
22
+ import { createHash } from "node:crypto";
23
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
24
+ import { dirname, resolve, sep } from "node:path";
25
+ import {
26
+ AGENTS_FILE,
27
+ BUDGETS,
28
+ CONTRACT_FILE,
29
+ FRAMEWORK_VERSION,
30
+ IMPLEMENTATIONS_DIR,
31
+ SIGNPOST_FILE,
32
+ STATE_FILE,
33
+ STATE_GITIGNORE,
34
+ UAT_CONTRACT_FILE,
35
+ WORKFLOW_BLOCK_BEGIN,
36
+ WORKFLOW_BLOCK_END,
37
+ } from "./spec.js";
38
+ import { loadState } from "./detect.js";
39
+ import { iso } from "./plan.js";
40
+ import { stateToToml } from "./apply.js";
41
+ import { renderTemplate } from "./templates.js";
42
+ import type { FrameworkState } from "./types.js";
43
+
44
+ export interface RefreshOptions {
45
+ readonly dryRun?: boolean;
46
+ readonly now?: Date;
47
+ readonly toolVersion?: string;
48
+ }
49
+
50
+ export type BlockStatus = "current" | "updated" | "inserted" | "missing-agents";
51
+
52
+ export interface RefreshResult {
53
+ readonly created: string[];
54
+ readonly updated: string[];
55
+ readonly skipped: Array<{ path: string; reason: string }>;
56
+ readonly block: BlockStatus;
57
+ readonly stateUpdated: boolean;
58
+ readonly dryRun: boolean;
59
+ }
60
+
61
+ const MANAGED_TEMPLATES: ReadonlyArray<{ path: string; template: string; tokens: Record<string, string> }> = [
62
+ { path: CONTRACT_FILE, template: "memory-readme", tokens: {} },
63
+ { path: SIGNPOST_FILE, template: "signpost", tokens: {} },
64
+ { path: UAT_CONTRACT_FILE, template: "uat-readme", tokens: { implementationsDir: IMPLEMENTATIONS_DIR } },
65
+ { path: STATE_GITIGNORE, template: "state-gitignore", tokens: {} },
66
+ ];
67
+
68
+ function sha256(text: string): string {
69
+ return createHash("sha256").update(text).digest("hex");
70
+ }
71
+
72
+ function inside(root: string, rel: string): string {
73
+ const absolute = resolve(root, rel);
74
+ const base = resolve(root);
75
+ if (absolute !== base && !absolute.startsWith(`${base}${sep}`)) {
76
+ throw new Error(`refusing to write outside the repository: ${rel}`);
77
+ }
78
+ return absolute;
79
+ }
80
+
81
+ function baseTokens(): Record<string, string> {
82
+ return {
83
+ frameworkVersion: String(FRAMEWORK_VERSION),
84
+ softBudget: String(BUDGETS.agentsMdSoftChars),
85
+ hardBudget: String(BUDGETS.agentsMdHardChars),
86
+ memoryBudget: String(BUDGETS.memoryFileChars),
87
+ implementationsBudget: String(BUDGETS.implementationsFiles),
88
+ implementationsDir: IMPLEMENTATIONS_DIR,
89
+ statePath: STATE_FILE,
90
+ contractPath: CONTRACT_FILE,
91
+ uatLedger: ".agents/uat/ledger.jsonl",
92
+ };
93
+ }
94
+
95
+ /** Replace or insert the managed workflow block; never touches anything else. */
96
+ export function applyWorkflowBlock(
97
+ text: string,
98
+ block: string,
99
+ ): { text: string; status: Exclude<BlockStatus, "missing-agents"> } {
100
+ const begin = text.indexOf(WORKFLOW_BLOCK_BEGIN);
101
+ const end = text.indexOf(WORKFLOW_BLOCK_END);
102
+ if (begin >= 0 && end > begin) {
103
+ const endLine = text.indexOf("\n", end);
104
+ const stop = endLine === -1 ? text.length : endLine;
105
+ const next = `${text.slice(0, begin)}${block.trimEnd()}${text.slice(stop)}`;
106
+ return { text: next, status: next === text ? "current" : "updated" };
107
+ }
108
+ const appendix = /^##[ \t]+(?:附录|appendix)/im.exec(text);
109
+ if (appendix?.index !== undefined) {
110
+ return {
111
+ text: `${text.slice(0, appendix.index)}${block.trimEnd()}\n\n${text.slice(appendix.index)}`,
112
+ status: "inserted",
113
+ };
114
+ }
115
+ return { text: `${text.trimEnd()}\n\n${block.trimEnd()}\n`, status: "inserted" };
116
+ }
117
+
118
+ export function refreshFramework(root: string, options: RefreshOptions = {}): RefreshResult {
119
+ const loaded = loadState(root);
120
+ if (!loaded.state) {
121
+ throw new Error(
122
+ loaded.error ?? "no agent framework installed (.agents/framework/state.toml is missing) — run /ask-init first",
123
+ );
124
+ }
125
+ const state: FrameworkState = loaded.state;
126
+ const now = options.now ?? new Date();
127
+ const dryRun = options.dryRun === true;
128
+ const created: string[] = [];
129
+ const updated: string[] = [];
130
+ const skipped: RefreshResult["skipped"] = [];
131
+ const previous = new Map(state.managed.map((entry) => [entry.path, entry]));
132
+ const nextManaged = new Map(state.managed.map((entry) => [entry.path, { ...entry }]));
133
+
134
+ for (const spec of MANAGED_TEMPLATES) {
135
+ const absolute = inside(root, spec.path);
136
+ const rendered = renderTemplate(spec.template, { ...baseTokens(), ...spec.tokens }, "en");
137
+ const exists = existsSync(absolute);
138
+ const disk = exists ? readFileSync(absolute, "utf8") : undefined;
139
+ const entry = previous.get(spec.path);
140
+ const diskHash = exists ? sha256(disk ?? "") : undefined;
141
+ // Only a template anchor proves "this is still the text we wrote". Legacy
142
+ // state has none, and its disk hash cannot supply that proof: it is
143
+ // refreshed from disk at the end of a run. We may adopt an anchor only
144
+ // when the legacy file is already byte-identical to the current template.
145
+ const safe = exists
146
+ ? entry?.templateSha256 !== undefined
147
+ ? diskHash === entry.templateSha256
148
+ : diskHash === sha256(rendered)
149
+ : true;
150
+
151
+ if (!exists) {
152
+ if (!dryRun) {
153
+ mkdirSync(dirname(absolute), { recursive: true });
154
+ writeFileSync(absolute, rendered, "utf8");
155
+ }
156
+ created.push(spec.path);
157
+ nextManaged.set(spec.path, {
158
+ path: spec.path,
159
+ sha256: sha256(rendered),
160
+ template: spec.template,
161
+ templateSha256: sha256(rendered),
162
+ });
163
+ continue;
164
+ }
165
+
166
+ if (!safe) {
167
+ skipped.push({
168
+ path: spec.path,
169
+ reason: "edited by hand since the framework last wrote it — left untouched",
170
+ });
171
+ continue;
172
+ }
173
+
174
+ if (disk === rendered) {
175
+ nextManaged.set(spec.path, {
176
+ path: spec.path,
177
+ sha256: sha256(rendered),
178
+ template: spec.template,
179
+ templateSha256: sha256(rendered),
180
+ });
181
+ continue;
182
+ }
183
+
184
+ if (!dryRun) writeFileSync(absolute, rendered, "utf8");
185
+ updated.push(spec.path);
186
+ nextManaged.set(spec.path, {
187
+ path: spec.path,
188
+ sha256: sha256(rendered),
189
+ template: spec.template,
190
+ templateSha256: sha256(rendered),
191
+ });
192
+ }
193
+
194
+ // The one block this tool owns inside a file it does not own.
195
+ let block: BlockStatus = "missing-agents";
196
+ const agentsPath = inside(root, AGENTS_FILE);
197
+ if (existsSync(agentsPath)) {
198
+ const text = readFileSync(agentsPath, "utf8");
199
+ const rendered = renderTemplate("workflow-block", {}, "en");
200
+ const result = applyWorkflowBlock(text, rendered);
201
+ block = result.status;
202
+ if (result.status !== "current" && !dryRun) {
203
+ writeFileSync(agentsPath, result.text, "utf8");
204
+ }
205
+ }
206
+
207
+ const changed = created.length + updated.length > 0 || block === "updated" || block === "inserted";
208
+ const managedChanged =
209
+ state.managed.length !== nextManaged.size ||
210
+ [...nextManaged.values()].some((entry) => {
211
+ const before = previous.get(entry.path);
212
+ return (
213
+ !before ||
214
+ before.sha256 !== entry.sha256 ||
215
+ before.template !== entry.template ||
216
+ before.templateSha256 !== entry.templateSha256
217
+ );
218
+ });
219
+ const toolChanged = state.tool !== (options.toolVersion ?? state.tool);
220
+ const stateChanged = changed || managedChanged || toolChanged;
221
+ if (!dryRun && stateChanged) {
222
+ writeFileSync(
223
+ inside(root, STATE_FILE),
224
+ stateToToml({
225
+ ...state,
226
+ tool: options.toolVersion ?? state.tool,
227
+ updated: iso(now),
228
+ managed: [...nextManaged.values()],
229
+ }),
230
+ "utf8",
231
+ );
232
+ }
233
+
234
+ return {
235
+ created,
236
+ updated,
237
+ skipped,
238
+ block,
239
+ stateUpdated: !dryRun && stateChanged,
240
+ dryRun,
241
+ };
242
+ }
243
+
244
+ /** One-line notice for the command handler. */
245
+ export function describeRefresh(result: RefreshResult): string {
246
+ const parts: string[] = [];
247
+ const verb = result.dryRun ? "would refresh" : "refreshed";
248
+ if (result.created.length > 0) parts.push(`${verb} ${result.created.length} created file(s)`);
249
+ if (result.updated.length > 0) parts.push(`${result.updated.length} framework file(s)`);
250
+ if (result.block === "inserted") parts.push("workflow block inserted into AGENTS.md");
251
+ if (result.block === "updated") parts.push("workflow block updated");
252
+ if (parts.length === 0) parts.push("framework files are already current");
253
+ if (result.skipped.length > 0) parts.push(`${result.skipped.length} left untouched (hand edits)`);
254
+ return parts.join(" · ");
255
+ }
@@ -39,9 +39,20 @@ export const AGENTS_DIR = ".agents";
39
39
  export const MEMORY_DIR = ".agents/memory";
40
40
  export const IMPLEMENTATIONS_DIR = ".agents/implementations";
41
41
  export const PROMPTS_DIR = ".agents/prompts";
42
+ /**
43
+ * Acceptance ledger: the bridge between change records and user-visible
44
+ * behaviour. Optional and additive — a project without it is still a valid v1
45
+ * framework (the audit reports `I-UAT-01`, not an error).
46
+ */
47
+ export const UAT_DIR = ".agents/uat";
48
+ export const UAT_LEDGER_FILE = ".agents/uat/ledger.jsonl";
49
+ export const UAT_CONTRACT_FILE = ".agents/uat/README.md";
42
50
  export const FRAMEWORK_DIR = ".agents/framework";
43
51
 
44
52
  export const STATE_FILE = ".agents/framework/state.toml";
53
+ /** Managed block markers inside AGENTS.md (framework-owned bytes). */
54
+ export const WORKFLOW_BLOCK_BEGIN = "<!-- ask-init:begin workflow";
55
+ export const WORKFLOW_BLOCK_END = "<!-- ask-init:end workflow -->";
45
56
  export const STATE_GITIGNORE = ".agents/framework/.gitignore";
46
57
  export const SNAPSHOTS_DIR = ".agents/framework/snapshots";
47
58
  export const PLANS_DIR = ".agents/framework/plans";
@@ -299,6 +310,15 @@ export const AUDIT_CODES = {
299
310
  agentsSkills: "I-AGENTS-01",
300
311
  notInstalled: "I-INSTALL-01",
301
312
  planSpecDrift: "W-PLAN-01",
313
+ // Acceptance ledger and change-record hygiene.
314
+ uatLedgerBroken: "E-UAT-01",
315
+ uatMissingReport: "W-UAT-01",
316
+ uatStaleCandidate: "W-UAT-02",
317
+ uatStaleItem: "W-UAT-03",
318
+ recordHeader: "W-REC-01",
319
+ // Framework-owned file edited by hand: a refresh will not overwrite it.
320
+ managedEdited: "W-FW-01",
321
+ uatNotInstalled: "I-UAT-01",
302
322
  } as const;
303
323
 
304
324
  export type AuditCode = (typeof AUDIT_CODES)[keyof typeof AUDIT_CODES];
@@ -42,3 +42,5 @@
42
42
  - audit: `/ask-init check`
43
43
  - before writing memory: read `{{contractPath}}`
44
44
  - records: one file per change in `{{implementationsDir}}/`, first line carries the exact time
45
+
46
+ {{workflowBlock}}
@@ -0,0 +1,53 @@
1
+ # Acceptance ledger (UAT)
2
+
3
+ This directory owns one question: **which user-visible behaviours have been
4
+ accepted, and on which evidence?** It is the bridge between
5
+ `{{implementationsDir}}/` (prose records of what changed) and the operator's
6
+ acceptance decisions.
7
+
8
+ `ledger.jsonl` is append-only and committed to git. Nothing here is a task
9
+ list, a plan, or a second copy of a spec.
10
+
11
+ ## Where it lives
12
+
13
+ The ledger belongs to the **main checkout only**. Sessions running in a linked
14
+ git worktree write their change records and ledger events to the main
15
+ checkout, so the acceptance history never splits.
16
+
17
+ ## Events
18
+
19
+ One JSON object per line. Every event carries `v`, `id`, `ts`, `type`; readers
20
+ deduplicate by `id` (two branches may both append, and both sides are kept).
21
+
22
+ | type | written by | meaning |
23
+ | --- | --- | --- |
24
+ | `candidate` | `record_change` / `/ask-uat` fallback | a change record that may need acceptance, plus the one-sentence behaviour it exposes |
25
+ | `batch` | `/ask-uat` | one clustering run: the acceptance items reviewed together |
26
+ | `item` | `uat_item` | one acceptance item: title, 2-3 sentence summary, test steps, evidence records |
27
+ | `link` | `uat_item` | new evidence attached to an existing item (the N:M bridge) |
28
+ | `check` / `uncheck` | the browser page | the operator's acceptance decision, written immediately |
29
+ | `amend` / `merge` / `drop` | `uat_item` | revise an item, merge duplicates, retire abandoned work |
30
+
31
+ ## Rules
32
+
33
+ 1. **One item, many records; one record, many items.** A record is evidence, not
34
+ an acceptance unit. Items are created by clustering on the UAT side, never by
35
+ an implementation session — parallel sessions cannot see each other, so
36
+ item identity must have a single writer.
37
+ 2. **No submit.** Checking an item writes a `check` event immediately. Closing
38
+ the page changes nothing. Unchecking is the same event stream in reverse.
39
+ 3. **New evidence reopens an item.** When a `link` (or a new record in an item)
40
+ is newer than the item's last `check`, the item counts as unchecked again.
41
+ "Checked" therefore means "checked against the current evidence set".
42
+ 4. **Nothing is deleted.** `drop` retires abandoned work; the event stays.
43
+ 5. **Records stay prose.** The ledger stores the behaviour sentence and the
44
+ test hint; the change record keeps the narrative for the agent to read. Do
45
+ not parse prose to reconstruct the ledger.
46
+
47
+ ## Commands
48
+
49
+ - `/ask-uat` — cluster pending change records into acceptance items, then open
50
+ the page
51
+ - `/ask-uat open` — reopen the page without a model turn
52
+ - `/ask-uat off` — stop the page server
53
+ - `/ask-init refresh` — refresh framework-owned files (this contract included)
@@ -0,0 +1,21 @@
1
+ <!-- ask-init:begin workflow v1 -->
2
+ ## Ask workflow
3
+
4
+ This project uses the `@andares/pi-toolkits` ask workflow. The steps run in this order:
5
+
6
+ | step | entry | what it does |
7
+ | --- | --- | --- |
8
+ | discuss | `/ask` | read-only consult; `scratchpad` is the only write channel |
9
+ | plan | `/ask-plan <topic>` | research, ask questions, write `specs/<slug>.md`, review it block by block in the browser, implement only after approval |
10
+ | record | `record_change` | after the work: write the change record and one user-visible behaviour sentence |
11
+ | review | `/ask-review` | optional third-party model cross-check (check + fix); it leaves no state behind |
12
+ | accept | `/ask-uat` | cluster pending change records into acceptance items, verify them on the page, tick them off |
13
+
14
+ Rules that are easy to break:
15
+
16
+ - Change records live in `.agents/implementations/`; new ones carry the minute in the name (`YYYY-MM-DD_HHMM_slug.md`) and repeat it in the first line (`# YYYY-MM-DDTHH:MM±HH:MM — title`).
17
+ - The acceptance ledger is `.agents/uat/ledger.jsonl`, append-only, committed to git, and belongs to the main checkout. Never edit it by hand: the tools and the page write it.
18
+ - Acceptance items are created by clustering on the UAT side, never by an implementation session.
19
+ - Plans go in `specs/`, memory in `.agents/memory/`, evidence in `.agents/implementations/`.
20
+
21
+ <!-- ask-init:end workflow -->
@@ -17,6 +17,8 @@ const TOKENS: Record<string, string> = {
17
17
  statePath: ".agents/framework/state.toml",
18
18
  contractPath: ".agents/memory/README.md",
19
19
  implementationsDir: ".agents/implementations",
20
+ workflowBlock:
21
+ "<!-- ask-init:begin workflow v1 -->\n## Ask workflow\n<!-- ask-init:end workflow -->",
20
22
  h_what: "What this is",
21
23
  h_rules: "Hard rules",
22
24
  h_commands: "Commands",
@@ -44,7 +46,7 @@ describe("templates", () => {
44
46
  });
45
47
 
46
48
  it("keeps the shipped contract free of legacy path references", () => {
47
- for (const name of ["memory-readme", "signpost", "agents-skeleton"]) {
49
+ for (const name of ["memory-readme", "signpost", "agents-skeleton", "uat-readme", "workflow-block"]) {
48
50
  const text = renderTemplate(name, TOKENS, "en");
49
51
  expect(countBareRefs(text, "memory/"), name).toBe(0);
50
52
  expect(countBareRefs(text, "implementations/"), name).toBe(0);
@@ -21,6 +21,8 @@ const FILE_TEMPLATES = new Set([
21
21
  "memory-readme",
22
22
  "signpost",
23
23
  "state-gitignore",
24
+ "uat-readme",
25
+ "workflow-block",
24
26
  ]);
25
27
 
26
28
  /** Templates whose content is not Markdown (written verbatim). */
@@ -66,7 +66,18 @@ export interface FrameworkState {
66
66
  memoryFileChars?: number;
67
67
  };
68
68
  roots: RootInfo[];
69
- managed: Array<{ path: string; sha256: string; template: string }>;
69
+ managed: Array<{
70
+ path: string;
71
+ /** Hash of the file as it was on disk when this run finished. */
72
+ sha256: string;
73
+ template: string;
74
+ /**
75
+ * Hash of the bytes *we* rendered for this file. `refresh` rewrites a file
76
+ * only when the disk still equals this anchor — otherwise the operator
77
+ * edited it and the refresh must not clobber that edit.
78
+ */
79
+ templateSha256?: string;
80
+ }>;
70
81
  migrations: Array<{ at: string; to: string; notes?: string }>;
71
82
  }
72
83
 
@@ -26,6 +26,7 @@ import type { ApprovalLog, ApprovalRecord } from "../../lib/approval-log.js";
26
26
  import { auditBase, auditTool } from "../../lib/approval-log.js";
27
27
  import type { AskRequest, GateHub } from "../../lib/gates.js";
28
28
  import { isJailedTool } from "../../lib/tools.js";
29
+ import { setPermissionControl } from "../../lib/permission-control.js";
29
30
  import { consumeStartupCommand } from "../../lib/startup.js";
30
31
  import {
31
32
  DEFAULT_MODES,
@@ -404,6 +405,37 @@ export function registerPermission(
404
405
  },
405
406
  });
406
407
 
408
+ // ── Control surface for other features ─────────────────────────────────
409
+ // `/ask-plan` needs to switch the checks on for the planning phase and put
410
+ // them back afterwards. It gets a handle, not a copy of the state: the
411
+ // session's own `/ask-perm` command stays authoritative, so an operator who
412
+ // changes the mode mid-plan wins over whatever we restore later.
413
+ setPermissionControl({
414
+ snapshot: () => ({ enabled, modes: { ...modes } }),
415
+ enableDefaults(ctx) {
416
+ if (enabled) return;
417
+ modes = { ...DEFAULT_MODES };
418
+ rules.clear();
419
+ enabled = true;
420
+ syncStatus(ctx);
421
+ recordMode(ctx, { enabled: true, source: "plan", via: "manual" });
422
+ },
423
+ restore(ctx, snapshot) {
424
+ enabled = snapshot.enabled;
425
+ modes = { ...snapshot.modes };
426
+ rules.clear();
427
+ syncStatus(ctx);
428
+ recordMode(ctx, { enabled: snapshot.enabled, source: "plan-restore", via: "manual" });
429
+ },
430
+ disable(ctx) {
431
+ if (!enabled) return;
432
+ enabled = false;
433
+ rules.clear();
434
+ syncStatus(ctx);
435
+ recordMode(ctx, { enabled: false, source: "plan-restore", via: "manual" });
436
+ },
437
+ });
438
+
407
439
  // ── Gate ───────────────────────────────────────────────────────────────
408
440
 
409
441
  gates.register({
@@ -0,0 +1 @@
1
+ (function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var e={context:void 0,registry:void 0,effects:void 0,done:!1,getContextId(){return t(this.context.count)},getNextContextId(){return t(this.context.count++)}};function t(t){let n=String(t),r=n.length-1;return e.context.id+(r?String.fromCharCode(96+r):``)+n}function n(t){e.context=t}var r=(e,t)=>e===t,i=Symbol(`solid-track`),a={equals:r},o=null,s=I,c=1,l=2,u={owned:null,cleanups:null,context:null,owner:null},d=null,f=null,p=null,m=null,h=null,g=0;function _(e,t){let n=p,r=d,i=e.length===0,a=t===void 0?r:t,o=i?u:{owned:null,cleanups:null,context:a?a.context:null,owner:a},s=i?e:()=>e(v(o));d=o,p=null;try{return F(s,!0)}finally{p=n,d=r}}function v(e){return()=>C(()=>B(e))}function y(e,t){t=t?Object.assign({},a,t):a;let n={value:e,observers:null,observerSlots:null,comparator:t.equals||void 0};return[A.bind(n),e=>(typeof e==`function`&&(e=f&&f.running&&f.sources.has(n)?e(n.tValue):e(n.value)),ee(n,e))]}function b(e,t,n){j(N(e,t,!1,c))}function x(e,t,n){s=L;let r=N(e,t,!1,c),i=k&&O(k);i&&(r.suspense=i),(!n||!n.render)&&(r.user=!0),h?h.push(r):j(r)}function S(e,t,n){n=n?Object.assign({},a,n):a;let r=N(e,t,!0,0);return r.observers=null,r.observerSlots=null,r.comparator=n.equals||void 0,j(r),A.bind(r)}function C(e){if(p===null)return e();let t=p;p=null;try{return e()}finally{p=t}}function w(e){x(()=>C(e))}function T(e){return d===null||(d.cleanups===null?d.cleanups=[e]:d.cleanups.push(e)),e}var[E,D]=y(!1);function O(e){let t;return d&&d.context&&(t=d.context[e.id])!==void 0?t:e.defaultValue}var k;function A(){let e=f&&f.running;if(this.sources&&(e?this.tState:this.state)){if((e?this.tState:this.state)===c)j(this);else{let e=m;m=null,F(()=>R(this),!1),m=e}}if(p){let e=this.observers;if(!e||e[e.length-1]!==p){let t=e?e.length:0;p.sources?(p.sources.push(this),p.sourceSlots.push(t)):(p.sources=[this],p.sourceSlots=[t]),e?(e.push(p),this.observerSlots.push(p.sources.length-1)):(this.observers=[p],this.observerSlots=[p.sources.length-1])}}return e&&f.sources.has(this)?this.tValue:this.value}function ee(e,t,n){let r=f&&f.running&&f.sources.has(e)?e.tValue:e.value;if(!e.comparator||!e.comparator(r,t)){if(f){let r=f.running;(r||!n&&f.sources.has(e))&&(f.sources.add(e),e.tValue=t),r||(e.value=t)}else e.value=t;e.observers&&e.observers.length&&F(()=>{for(let t=0;t<e.observers.length;t+=1){let n=e.observers[t],r=f&&f.running;r&&f.disposed.has(n)||((r?!n.tState:!n.state)&&(n.pure?m.push(n):h.push(n),n.observers&&z(n)),r?n.tState=c:n.state=c)}if(m.length>1e6)throw m=[],Error()},!1)}return t}function j(e){if(!e.fn)return;B(e);let t=g;M(e,f&&f.running&&f.sources.has(e)?e.tValue:e.value,t),f&&!f.running&&f.sources.has(e)&&queueMicrotask(()=>{F(()=>{f&&(f.running=!0),p=d=e,M(e,e.tValue,t),p=d=null},!1)})}function M(e,t,n){let r,i=d,a=p;p=d=e;try{r=e.fn(t)}catch(t){return e.pure&&(f&&f.running?(e.tState=c,e.tOwned&&e.tOwned.forEach(B),e.tOwned=void 0):(e.state=c,e.owned&&e.owned.forEach(B),e.owned=null)),e.updatedAt=n+1,U(t)}finally{p=a,d=i}(!e.updatedAt||e.updatedAt<=n)&&(e.updatedAt!=null&&`observers`in e?ee(e,r,!0):f&&f.running&&e.pure?(f.sources.has(e)||(e.value=r),f.sources.add(e),e.tValue=r):e.value=r,e.updatedAt=n)}function N(e,t,n,r=c,i){let a={fn:e,state:r,updatedAt:null,owned:null,sources:null,sourceSlots:null,cleanups:null,value:t,owner:d,context:d?d.context:null,pure:n};return f&&f.running&&(a.state=0,a.tState=r),d===null||d!==u&&(f&&f.running&&d.pure?d.tOwned?d.tOwned.push(a):d.tOwned=[a]:d.owned?d.owned.push(a):d.owned=[a]),a}function P(e){let t=f&&f.running;if((t?e.tState:e.state)===0)return;if((t?e.tState:e.state)===l)return R(e);if(e.suspense&&C(e.suspense.inFallback))return e.suspense.effects.push(e);let n=[e];for(;(e=e.owner)&&(!e.updatedAt||e.updatedAt<g);){if(t&&f.disposed.has(e))return;(t?e.tState:e.state)&&n.push(e)}for(let r=n.length-1;r>=0;r--){if(e=n[r],t){let t=e,i=n[r+1];for(;(t=t.owner)&&t!==i;)if(f.disposed.has(t))return}if((t?e.tState:e.state)===c)j(e);else if((t?e.tState:e.state)===l){let t=m;m=null,F(()=>R(e,n[0]),!1),m=t}}}function F(e,t){if(m)return e();let n=!1;t||(m=[]),h?n=!0:h=[],g++;try{let t=e();return te(n),t}catch(e){n||(h=null),m=null,U(e)}}function te(e){if(m&&=(I(m),null),e)return;let t;if(f){if(!f.promises.size&&!f.queue.size){let e=f.sources,n=f.disposed;h.push.apply(h,f.effects),t=f.resolve;for(let e of h)`tState`in e&&(e.state=e.tState),delete e.tState;f=null,F(()=>{for(let e of n)B(e);for(let t of e){if(t.value=t.tValue,t.owned)for(let e=0,n=t.owned.length;e<n;e++)B(t.owned[e]);t.tOwned&&(t.owned=t.tOwned),delete t.tValue,delete t.tOwned,t.tState=0}D(!1)},!1)}else if(f.running){f.running=!1,f.effects.push.apply(f.effects,h),h=null,D(!0);return}}let n=h;h=null,n.length&&F(()=>s(n),!1),t&&t()}function I(e){for(let t=0;t<e.length;t++)P(e[t])}function L(t){let r,i=0;for(r=0;r<t.length;r++){let e=t[r];e.user?t[i++]=e:P(e)}if(e.context){if(e.count){e.effects||=[],e.effects.push(...t.slice(0,i));return}n()}for(e.effects&&(e.done||!e.count)&&(t=[...e.effects,...t],i+=e.effects.length,delete e.effects),r=0;r<i;r++)P(t[r])}function R(e,t){let n=f&&f.running;n?e.tState=0:e.state=0;for(let r=0;r<e.sources.length;r+=1){let i=e.sources[r];if(i.sources){let e=n?i.tState:i.state;e===c?i!==t&&(!i.updatedAt||i.updatedAt<g)&&P(i):e===l&&R(i,t)}}}function z(e){let t=f&&f.running;for(let n=0;n<e.observers.length;n+=1){let r=e.observers[n];(t?!r.tState:!r.state)&&(t?r.tState=l:r.state=l,r.pure?m.push(r):h.push(r),r.observers&&z(r))}}function B(e){let t;if(e.sources)for(;e.sources.length;){let t=e.sources.pop(),n=e.sourceSlots.pop(),r=t.observers;if(r&&r.length){let e=r.pop(),i=t.observerSlots.pop();n<r.length&&(e.sourceSlots[i]=n,r[n]=e,t.observerSlots[n]=i)}}if(e.tOwned){for(t=e.tOwned.length-1;t>=0;t--)B(e.tOwned[t]);delete e.tOwned}if(f&&f.running&&e.pure)V(e,!0);else if(e.owned){for(t=e.owned.length-1;t>=0;t--)B(e.owned[t]);e.owned=null}if(e.cleanups){for(t=e.cleanups.length-1;t>=0;t--)e.cleanups[t]();e.cleanups=null}f&&f.running?e.tState=0:e.state=0}function V(e,t){if(t||(e.tState=0,f.disposed.add(e)),e.owned)for(let t=0;t<e.owned.length;t++)V(e.owned[t])}function ne(e){return e instanceof Error?e:Error(typeof e==`string`?e:`Unknown error`,{cause:e})}function H(e,t,n){try{for(let n of t)n(e)}catch(e){U(e,n&&n.owner||null)}}function U(e,t=d){let n=o&&t&&t.context&&t.context[o],r=ne(e);if(!n)throw r;h?h.push({fn(){H(r,n,t)},state:c}):H(r,n,t)}var W=Symbol(`fallback`);function G(e){for(let t=0;t<e.length;t++)e[t]()}function re(e,t,n={}){let r=[],a=[],o=[],s=0,c=t.length>1?[]:null;return T(()=>G(o)),()=>{let l=e()||[],u=l.length,d,f;return l[i],C(()=>{let e,t,i,m,h,g,v,y,b;if(u===0)s!==0&&(G(o),o=[],r=[],a=[],s=0,c&&=[]),n.fallback&&(r=[W],a[0]=_(e=>(o[0]=e,n.fallback())),s=1);else if(s===0){for(a=Array(u),f=0;f<u;f++)r[f]=l[f],a[f]=_(p);s=u}else{for(i=Array(u),m=Array(u),c&&(h=Array(u)),g=0,v=Math.min(s,u);g<v&&r[g]===l[g];g++);for(v=s-1,y=u-1;v>=g&&y>=g&&r[v]===l[y];v--,y--)i[y]=a[v],m[y]=o[v],c&&(h[y]=c[v]);for(e=new Map,t=Array(y+1),f=y;f>=g;f--)b=l[f],d=e.get(b),t[f]=d===void 0?-1:d,e.set(b,f);for(d=g;d<=v;d++)b=r[d],f=e.get(b),f!==void 0&&f!==-1?(i[f]=a[d],m[f]=o[d],c&&(h[f]=c[d]),f=t[f],e.set(b,f)):o[d]();for(f=g;f<u;f++)f in i?(a[f]=i[f],o[f]=m[f],c&&(c[f]=h[f],c[f](f))):a[f]=_(p);a=a.slice(0,s=u),r=l.slice(0)}return a});function p(e){if(o[f]=e,c){let[e,n]=y(f);return c[f]=n,t(l[f],e)}return t(l[f])}}}function K(e,t){return C(()=>e(t||{}))}var ie=e=>`Stale read from <${e}>.`;function q(e){let t=`fallback`in e&&{fallback:()=>e.fallback};return S(re(()=>e.each,e.children,t||void 0))}function J(e){let t=e.keyed,n=S(()=>e.when,void 0,void 0),r=t?n:S(n,void 0,{equals:(e,t)=>!e==!t});return S(()=>{let i=r();if(i){let a=e.children;return typeof a==`function`&&a.length>0?C(()=>a(t?i:()=>{if(!C(r))throw ie(`Show`);return n()})):a}return e.fallback},void 0,void 0)}var Y=e=>S(()=>e());function ae(e,t,n){let r=n.length,i=t.length,a=r,o=0,s=0,c=t[i-1].nextSibling,l=null;for(;o<i||s<a;){if(t[o]===n[s]){o++,s++;continue}for(;t[i-1]===n[a-1];)i--,a--;if(i===o){let t=a<r?s?n[s-1].nextSibling:n[a-s]:c;for(;s<a;)e.insertBefore(n[s++],t)}else if(a===s)for(;o<i;)(!l||!l.has(t[o]))&&t[o].remove(),o++;else if(t[o]===n[a-1]&&n[s]===t[i-1]){let r=t[--i].nextSibling;e.insertBefore(n[s++],t[o++].nextSibling),e.insertBefore(n[--a],r),t[i]=n[a]}else{if(!l){l=new Map;let e=s;for(;e<a;)l.set(n[e],e++)}let r=l.get(t[o]);if(r!=null){if(s<r&&r<a){let c=o,u=1,d;for(;++c<i&&c<a&&(d=l.get(t[c]))!=null&&d===r+u;)u++;if(u>r-s){let i=t[o];for(;s<r;)e.insertBefore(n[s++],i)}else e.replaceChild(n[s++],t[o++])}else o++}else t[o++].remove()}}}var oe=`_$DX_DELEGATE`;function se(e,t,n,r={}){let i;return _(r=>{i=r,t===document?e():Z(t,e(),!n&&t.firstChild?null:void 0,n)},r.owner),()=>{i(),t.textContent=``}}function X(e,t,n,r){let i,a=()=>{let t=r?document.createElementNS(`http://www.w3.org/1998/Math/MathML`,`template`):document.createElement(`template`);return t.innerHTML=e,n?t.content.firstChild.firstChild:r?t.firstChild:t.content.firstChild},o=t?()=>C(()=>document.importNode(i||=a(),!0)):()=>(i||=a()).cloneNode(!0);return o.cloneNode=o,o}function ce(e,t=window.document){let n=t[oe]||(t[oe]=new Set);for(let r=0,i=e.length;r<i;r++){let i=e[r];n.has(i)||(n.add(i),t.addEventListener(i,he))}}function le(e,t,n){pe(e)||(n==null?e.removeAttribute(t):e.setAttribute(t,n))}function ue(e,t){pe(e)||(t==null?e.removeAttribute(`class`):e.className=t)}function de(e,t,n,r){if(r)Array.isArray(n)?(e[`$$${t}`]=n[0],e[`$$${t}Data`]=n[1]):e[`$$${t}`]=n;else if(Array.isArray(n)){let r=n[0];e.addEventListener(t,n[0]=t=>r.call(e,n[1],t))}else e.addEventListener(t,n,typeof n!=`function`&&n)}function fe(e,t,n={}){let r=Object.keys(t||{}),i=Object.keys(n),a,o;for(a=0,o=i.length;a<o;a++){let r=i[a];!r||r===`undefined`||t[r]||(me(e,r,!1),delete n[r])}for(a=0,o=r.length;a<o;a++){let i=r[a],o=!!t[i];!i||i===`undefined`||n[i]===o||!o||(me(e,i,!0),n[i]=o)}return n}function Z(e,t,n,r){if(n!==void 0&&!r&&(r=[]),typeof t!=`function`)return Q(e,t,r,n);b(r=>Q(e,t(),r,n),r)}function pe(t){return!!e.context&&!e.done&&(!t||t.isConnected)}function me(e,t,n){let r=t.trim().split(/\s+/);for(let t=0,i=r.length;t<i;t++)e.classList.toggle(r[t],n)}function he(t){if(e.registry&&e.events&&e.events.find(([e,n])=>n===t))return;let n=t.target,r=`$$${t.type}`,i=t.target,a=t.currentTarget,o=e=>Object.defineProperty(t,"target",{configurable:!0,value:e}),s=()=>{let e=n[r];if(e&&!n.disabled){let i=n[`${r}Data`];if(i===void 0?e.call(n,t):e.call(n,i,t),t.cancelBubble)return}return n.host&&typeof n.host!=`string`&&!n.host._$host&&n.contains(t.target)&&o(n.host),!0},c=()=>{for(;s()&&(n=n._$host||n.parentNode||n.host););};Object.defineProperty(t,"currentTarget",{configurable:!0,get(){return n||document}}),e.registry&&!e.done&&(e.done=_$HY.done=!0);try{if(t.composedPath){let e=t.composedPath();o(e[0]);for(let t=0;t<e.length-2&&(n=e[t],s());t++){if(n._$host){n=n._$host,c();break}if(n.parentNode===a)break}}else c();o(i)}finally{t=n=null}}function Q(e,t,n,r,i){let a=pe(e);if(a){!n&&(n=[...e.childNodes]);let t=[];for(let e=0;e<n.length;e++){let r=n[e];r.nodeType===8&&r.data.slice(0,2)===`!$`?r.remove():t.push(r)}n=t}for(;typeof n==`function`;)n=n();if(t===n)return n;let o=typeof t,s=r!==void 0;if(e=s&&n[0]&&n[0].parentNode||e,o===`string`||o===`number`){if(a||o===`number`&&(t=t.toString(),t===n))return n;if(s){let i=n[0];i&&i.nodeType===3?i.data!==t&&(i.data=t):i=document.createTextNode(t),n=$(e,n,r,i)}else n=n!==``&&typeof n==`string`?e.firstChild.data=t:e.textContent=t}else if(t==null||o===`boolean`){if(a)return n;n=$(e,n,r)}else if(o===`function`)return b(()=>{let i=t();for(;typeof i==`function`;)i=i();n=Q(e,i,n,r)}),()=>n;else if(Array.isArray(t)){let o=[],c=n&&Array.isArray(n);if(ge(o,t,n,i))return b(()=>n=Q(e,o,n,r,!0)),()=>n;if(a){if(!o.length)return n;if(r===void 0)return n=[...e.childNodes];let t=o[0];if(t.parentNode!==e)return n;let i=[t];for(;(t=t.nextSibling)!==r;)i.push(t);return n=i}if(o.length===0){if(n=$(e,n,r),s)return n}else c?n.length===0?_e(e,o,r):ae(e,n,o):(n&&$(e),_e(e,o));n=o}else if(t.nodeType){if(a&&t.parentNode)return n=s?[t]:t;if(Array.isArray(n)){if(s)return n=$(e,n,r,t);$(e,n,null,t)}else n==null||n===``||!e.firstChild?e.appendChild(t):e.replaceChild(t,e.firstChild);n=t}return n}function ge(e,t,n,r){let i=!1;for(let a=0,o=t.length;a<o;a++){let o=t[a],s=n&&n[e.length],c;if(o!=null&&o!==!0&&o!==!1){if((c=typeof o)==`object`&&o.nodeType)e.push(o);else if(Array.isArray(o))i=ge(e,o,s)||i;else if(c===`function`){if(r){for(;typeof o==`function`;)o=o();i=ge(e,Array.isArray(o)?o:[o],Array.isArray(s)?s:[s])||i}else e.push(o),i=!0}else{let t=String(o);s&&s.nodeType===3&&s.data===t?e.push(s):e.push(document.createTextNode(t))}}}return i}function _e(e,t,n=null){for(let r=0,i=t.length;r<i;r++)e.insertBefore(t[r],n)}function $(e,t,n,r){if(n===void 0)return e.textContent=``;let i=r||document.createTextNode(``);if(t.length){let r=!1;for(let a=t.length-1;a>=0;a--){let o=t[a];if(i!==o){let t=o.parentNode===e;!r&&!a?t?e.replaceChild(i,o):e.insertBefore(i,n):t&&o.remove()}else r=!0}}else e.insertBefore(i,n);return[i]}var ve=new URLSearchParams(window.location.search).get(`t`)??``;async function ye(e,t={}){let n=await fetch(e,{...t,headers:{...t.body?{"content-type":`application/json`}:{},"x-plan-token":ve,...t.headers??{}}});if(!n.ok)throw Error(`${t.method??`GET`} ${e} → HTTP ${n.status}`);return await n.json()}function be(e){return ye(e===void 0?`/api/state`:`/api/state?version=${e}`)}function xe(e,t){return ye(`/api/annotate`,{method:`POST`,body:JSON.stringify({version:e,annotations:t})})}function Se(e,t){return ye(`/api/decide`,{method:`POST`,body:JSON.stringify({action:e,version:t})})}function Ce(e){try{return JSON.parse(e.data)}catch{return}}function we(e){let t=new EventSource(`/api/events?t=${encodeURIComponent(ve)}`);return t.addEventListener(`revision`,t=>{let n=Ce(t);n&&e.onRevision(n.version)}),t.addEventListener(`annotations`,()=>e.onAnnotations()),t.addEventListener(`decided`,t=>{let n=Ce(t);n&&e.onDecided(n)}),()=>t.close()}var Te=`plan:lang`;function Ee(){let e=localStorage.getItem(Te);return e===`en`||e===`zh`?e:navigator.language.toLowerCase().startsWith(`zh`)?`zh`:`en`}function De(e){localStorage.setItem(Te,e)}var Oe={en:{title:`Plan review`,version:`v{version} of {total}`,changed:`{count} changed`,noChange:`no changes`,expanded:`collapsed unchanged`,showAll:`show unchanged`,onlyChanged:`only changed`,approve:`Approve`,deny:`Send feedback`,globalNotes:`Global notes`,notePlaceholder:`What should change here?`,addNote:`Add note`,save:`Save`,cancel:`Cancel`,remove:`Remove`,verdictChange:`must change`,verdictSuggest:`suggest`,verdictQuestion:`question`,history:`History`,back:`Back to latest`,viewingOld:`Read-only: you are viewing v{v}`,readOnly:`Read-only`,approved:`Approved`,denied:`Feedback sent`,closing:`Closing this tab…`,closeHint:`You can close this tab now.`,waiting:`Waiting for the agent…`,status_unchanged:`unchanged`,status_moved:`moved`,status_modified:`modified`,status_added:`new`,status_removed:`removed`,unchangedHidden:`{count} unchanged blocks hidden`,error:`Something went wrong: {message}`,emptyPlan:`This plan is empty.`,notesHint:`Notes are sent with either decision — approve just means “start implementing”.`,noteCount:`{count} notes`},zh:{title:`计划评审`,version:`第 {version} / {total} 版`,changed:`{count} 处改动`,noChange:`无改动`,expanded:`已折叠未变块`,showAll:`显示未变块`,onlyChanged:`只看改动`,approve:`批准`,deny:`提交意见`,globalNotes:`全局批注`,notePlaceholder:`这里应该怎么改?`,addNote:`添加批注`,save:`保存`,cancel:`取消`,remove:`删除`,verdictChange:`必须改`,verdictSuggest:`建议`,verdictQuestion:`疑问`,history:`历史`,back:`回到最新版`,viewingOld:`只读:正在查看第 {v} 版`,readOnly:`只读`,approved:`已批准`,denied:`意见已提交`,closing:`正在关闭标签页…`,closeHint:`现在可以关闭这个标签页了。`,waiting:`等待模型继续…`,status_unchanged:`未变`,status_moved:`位置移动`,status_modified:`已修改`,status_added:`新增`,status_removed:`已删除`,unchangedHidden:`隐藏了 {count} 个未变块`,error:`出错了:{message}`,emptyPlan:`计划是空的。`,notesHint:`批注无论批准还是提意见都会送达;批准只是让模型开始实施。`,noteCount:`{count} 条批注`}};function ke(e,t,n={}){return(Oe[e][t]??t).replace(/\{(\w+)\}/g,(e,t)=>String(n[t]??`{${t}}`))}var Ae=X(`<span class=readonly>`),je=X(`<div class=error>`),Me=X(`<div class=banner><button class=link>`),Ne=X(`<div class=done><div class=done-title></div><div class=done-hint>`),Pe=X(`<p class=empty>`),Fe=X(`<div class=hidden-note><button class=link>`),Ie=X(`<div class=global-panel>`),Le=X(`<div class=page><header class=topbar><div class=topbar-left><span class=slug></span><span class=version></span><span class=changed></span></div><div class=topbar-right><button class=ghost></button><button class=ghost> (<!>)</button><button class=lang></button></div></header><div class=history><span class=history-label></span></div><main class=blocks></main><footer class=footer><div class=hint> · </div><div class=actions><button class=deny></button><button class=approve>`),Re=X(`<span class=chip-changed>+`),ze=X(`<button class=chip>v`),Be=X(`<button class=add>+ `),Ve=X(`<article class=block><div class=block-head><span></span><span class=block-id></span></div><div class=block-body>`),He=X(`<button class=remove>`),Ue=X(`<div class=note><span class=note-verdict></span><span class=note-text>`),We=X(`<div class=note><span class=note-verdict></span><span class=note-text></span><button class=remove>`),Ge=X(`<div class=editor><div class=verdicts></div><textarea></textarea><div class=editor-actions><button class=ghost></button><button class=primary>`),Ke=X(`<label><input type=radio name=verdict>`);function qe(){let[e,t]=y(Ee()),[n,r]=y(),[i,a]=y(),[o,s]=y(),[c,l]=y(),[u,d]=y(!1),[f,p]=y(),[m,h]=y(``),[g,_]=y(`change`),[v,x]=y(!1),C=(t,n)=>ke(e(),t,n);async function E(e){try{let t=await be(e);r(t),s(void 0),l(t.decided&&t.decision?t.decision.action:void 0)}catch(e){s(e instanceof Error?e.message:String(e))}}w(()=>{E(),T(we({onRevision:()=>{i()===void 0&&E()},onAnnotations:()=>{i()===void 0&&E()},onDecided:e=>l(e.action)}))});let D=S(()=>n()?.items??[]),O=S(()=>D().filter(e=>e.status!==`unchanged`).length),k=S(()=>!u()&&O()>0),A=S(()=>k()?D().filter(e=>e.status===`unchanged`).length:0),ee=S(()=>k()?D().filter(e=>e.status!==`unchanged`):D()),j=S(()=>n()?.history[0]?.n??n()?.version),M=S(()=>{let e=n();return e!==void 0&&e.version!==j()}),N=e=>n()?.annotations.blocks.find(t=>t.blockId===e)?.annotations??[],P=S(()=>{let e=n()?.annotations;if(!e)return 0;let t=e.blocks.reduce((e,t)=>e+t.annotations.length,0);return e.global.length+t});async function F(e){let t=n();if(!t)return;let i={...t,annotations:e};r(i);try{await xe(t.version,e)}catch(e){s(e instanceof Error?e.message:String(e)),await E(t.version)}}async function te(e){let t=m().trim();if(t===``)return;let r=n();if(!r)return;let i={verdict:g(),comment:t},a;if(e===void 0)a={...r.annotations,global:[...r.annotations.global,i]};else{let t=r.annotations.blocks.slice(),n=t.findIndex(t=>t.blockId===e);n===-1?t.push({blockId:e,annotations:[i]}):t[n]={...t[n],annotations:[...t[n].annotations,i]},a={...r.annotations,blocks:t}}p(void 0),h(``),await F(a)}async function I(e,t){let r=n();if(!r)return;let i;i=e===void 0?{...r.annotations,global:r.annotations.global.filter((e,n)=>n!==t)}:{...r.annotations,blocks:r.annotations.blocks.map(n=>n.blockId===e?{...n,annotations:n.annotations.filter((e,n)=>n!==t)}:n).filter(e=>e.annotations.length>0)},await F(i)}async function L(e){let t=n();if(t)try{await Se(e,t.version),l(e),window.close(),setTimeout(()=>x(!0),300)}catch(e){s(e instanceof Error?e.message:String(e))}}let R=e=>`badge badge-${e}`;return(()=>{var r=Le(),s=r.firstChild,l=s.firstChild,y=l.firstChild,x=y.nextSibling,S=x.nextSibling,w=l.nextSibling.firstChild,T=w.nextSibling,D=T.firstChild,k=D.nextSibling;k.nextSibling;var F=T.nextSibling,z=s.nextSibling,B=z.firstChild,V=z.nextSibling,ne=V.nextSibling,H=ne.firstChild,U=H.firstChild,W=H.nextSibling.firstChild,G=W.nextSibling;return Z(y,()=>n()?.slug),Z(x,()=>C(`version`,{version:n()?.version??0,total:n()?.totalVersions??0})),Z(S,(()=>{var e=Y(()=>O()>0);return()=>e()?C(`changed`,{count:O()}):C(`noChange`)})()),Z(l,K(J,{get when(){return M()},get children(){var e=Ae();return Z(e,()=>C(`readOnly`)),e}}),null),w.$$click=()=>d(!u()),Z(w,(()=>{var e=Y(()=>!!u());return()=>e()?C(`onlyChanged`):C(`showAll`)})()),T.$$click=()=>p({blockId:void 0}),Z(T,()=>C(`globalNotes`),D),Z(T,()=>n()?.annotations.global.length??0,k),F.$$click=()=>{let n=e()===`en`?`zh`:`en`;t(n),De(n)},Z(F,()=>e()===`en`?`中文`:`EN`),Z(r,K(J,{get when(){return o()},get children(){var e=je();return Z(e,()=>C(`error`,{message:o()??``})),e}}),z),Z(r,K(J,{get when(){return M()},get children(){var e=Me(),t=e.firstChild;return Z(e,()=>C(`viewingOld`,{v:i()??0}),t),t.$$click=()=>{a(void 0),E()},Z(t,()=>C(`back`)),e}}),z),Z(r,K(J,{get when(){return c()},get children(){var e=Ne(),t=e.firstChild,n=t.nextSibling;return Z(t,(()=>{var e=Y(()=>c()===`approve`);return()=>e()?C(`approved`):C(`denied`)})()),Z(n,(()=>{var e=Y(()=>!!v());return()=>e()?C(`closeHint`):C(`closing`)})()),e}}),z),Z(B,()=>C(`history`)),Z(z,K(q,{get each(){return n()?.history??[]},children:e=>(()=>{var t=ze();return t.firstChild,t.$$click=()=>{e.n===j()?(a(void 0),E()):(a(e.n),E(e.n))},Z(t,()=>e.n,null),Z(t,K(J,{get when(){return e.changed>0},get children(){var t=Re();return t.firstChild,Z(t,()=>e.changed,null),t}}),null),b(()=>t.classList.toggle(`active`,e.n===n()?.version)),t})()}),null),Z(r,K(J,{get when(){return Y(()=>!!n())()&&n().items.length===0},get children(){var e=Pe();return Z(e,()=>C(`emptyPlan`)),e}}),V),Z(V,K(J,{get when(){return A()>0},get children(){var e=Fe(),t=e.firstChild;return Z(e,()=>C(`unchangedHidden`,{count:A()}),t),t.$$click=()=>d(!0),Z(t,()=>C(`showAll`)),e}}),null),Z(V,K(q,{get each(){return ee()},children:e=>(()=>{var t=Ve(),n=t.firstChild,r=n.firstChild,i=r.nextSibling,a=n.nextSibling;return Z(r,()=>C(`status_${e.status}`)),Z(i,()=>e.id),Z(n,K(J,{get when(){return!M()},get children(){var t=Be();return t.firstChild,t.$$click=()=>{p({blockId:e.id}),h(``),_(`change`)},Z(t,()=>C(`addNote`),null),t}}),null),Z(t,K(q,{get each(){return N(e.id)},children:(t,n)=>(()=>{var r=Ue(),i=r.firstChild,a=i.nextSibling;return Z(i,()=>C(`verdict${t.verdict[0].toUpperCase()}${t.verdict.slice(1)}`)),Z(a,()=>t.comment),Z(r,K(J,{get when(){return!M()},get children(){var t=He();return t.$$click=()=>void I(e.id,n()),Z(t,()=>C(`remove`)),t}}),null),b(e=>fe(r,{[t.verdict]:!0},e)),r})()}),null),Z(t,K(J,{get when(){return Y(()=>f()?.blockId===e.id)()&&!M()},get children(){return K(Je,{draft:m,setDraft:h,verdict:g,setVerdict:_,onSave:()=>void te(e.id),onCancel:()=>p(void 0),t:C})}}),null),b(n=>{var i={[`is-`+e.status]:!0},o=R(e.status),s=e.html;return n.e=fe(t,i,n.e),o!==n.t&&ue(r,n.t=o),s!==n.a&&(a.innerHTML=n.a=s),n},{e:void 0,t:void 0,a:void 0}),t})()}),null),Z(r,K(J,{get when(){return Y(()=>!!(f()&&f().blockId===void 0))()&&!M()},get children(){var e=Ie();return Z(e,K(q,{get each(){return n()?.annotations.global??[]},children:(e,t)=>(()=>{var n=We(),r=n.firstChild,i=r.nextSibling,a=i.nextSibling;return Z(r,()=>e.verdict),Z(i,()=>e.comment),a.$$click=()=>void I(void 0,t()),Z(a,()=>C(`remove`)),b(t=>fe(n,{[e.verdict]:!0},t)),n})()}),null),Z(e,K(Je,{draft:m,setDraft:h,verdict:g,setVerdict:_,onSave:()=>void te(void 0),onCancel:()=>p(void 0),t:C}),null),e}}),ne),Z(H,()=>C(`notesHint`),U),Z(H,()=>C(`noteCount`,{count:P()}),null),W.$$click=()=>void L(`deny`),Z(W,()=>C(`deny`)),G.$$click=()=>void L(`approve`),Z(G,()=>C(`approve`)),b(e=>{var t=M()||c()!==void 0,n=M()||c()!==void 0;return t!==e.e&&(W.disabled=e.e=t),n!==e.t&&(G.disabled=e.t=n),e},{e:void 0,t:void 0}),r})()}function Je(e){return(()=>{var t=Ge(),n=t.firstChild,r=n.nextSibling,i=r.nextSibling.firstChild,a=i.nextSibling;return Z(n,K(q,{each:[`change`,`suggest`,`question`],children:t=>(()=>{var n=Ke(),r=n.firstChild;return r.addEventListener(`change`,()=>e.setVerdict(t)),Z(n,()=>e.t(`verdict${t[0].toUpperCase()}${t.slice(1)}`),null),b(()=>n.classList.toggle(`active`,e.verdict()===t)),b(()=>r.checked=e.verdict()===t),n})()})),r.$$input=t=>e.setDraft(t.currentTarget.value),de(i,`click`,e.onCancel,!0),Z(i,()=>e.t(`cancel`)),de(a,`click`,e.onSave,!0),Z(a,()=>e.t(`save`)),b(t=>{var n=e.t(`notePlaceholder`),i=e.draft().trim()===``;return n!==t.e&&le(r,`placeholder`,t.e=n),i!==t.t&&(a.disabled=t.t=i),t},{e:void 0,t:void 0}),b(()=>r.value=e.draft()),t})()}ce([`click`,`input`]);var Ye=document.getElementById(`root`);Ye&&se(()=>K(qe,{}),Ye);
@@ -0,0 +1 @@
1
+ :root{--bg:#14171d;--panel:#1b1f27;--panel-2:#20252f;--line:#2b323d;--text:#d7dce4;--dim:#8b94a3;--green:#3fb950;--amber:#d29922;--blue:#58a6ff;--red:#f85149;--radius:8px;--lightningcss-light: ;--lightningcss-dark:initial;color-scheme:dark}*{box-sizing:border-box}body{background:var(--bg);color:var(--text);margin:0;font:14px/1.65 ui-sans-serif,system-ui,-apple-system,Segoe UI,Roboto,Noto Sans CJK SC,sans-serif}.page{max-width:980px;margin:0 auto;padding:0 20px 120px}.topbar{z-index:10;background:linear-gradient(var(--bg) 78%, transparent);flex-wrap:wrap;justify-content:space-between;align-items:center;gap:12px;padding:14px 0 12px;display:flex;position:sticky;top:0}.topbar-left,.topbar-right{flex-wrap:wrap;align-items:center;gap:10px;display:flex}.slug{font-weight:600}.version,.changed,.readonly{color:var(--dim);font-variant-numeric:tabular-nums}.readonly{color:var(--amber);border:1px solid var(--amber);border-radius:999px;padding:0 8px}button{font:inherit;cursor:pointer;border-radius:var(--radius);border:1px solid var(--line);background:var(--panel);color:var(--text);padding:6px 12px}button:hover:not(:disabled){background:var(--panel-2);border-color:#3a4350}button:disabled{opacity:.45;cursor:not-allowed}button.primary{color:#fff;background:#1f6feb;border-color:#1f6feb}button.approve{color:#fff;background:#1a7f37;border-color:#1a7f37}button.deny{background:#3d1f22;border-color:#6e2a2f}button.link{color:var(--blue);background:0 0;border:none;padding:0 4px;text-decoration:underline}.lang{min-width:52px}.error{border:1px solid var(--red);color:#ffb4ad;border-radius:var(--radius);margin:8px 0;padding:8px 12px}.banner{border:1px solid var(--amber);border-radius:var(--radius);color:#f0d08a;margin:8px 0;padding:8px 12px}.done{border:1px solid var(--line);border-radius:var(--radius);background:var(--panel);margin:12px 0;padding:16px}.done-title{font-size:18px;font-weight:600}.done-hint{color:var(--dim)}.history{border-bottom:1px solid var(--line);flex-wrap:wrap;align-items:center;gap:8px;padding:10px 0 16px;display:flex}.history-label{color:var(--dim)}.chip{font-variant-numeric:tabular-nums;border-radius:999px;padding:2px 10px}.chip.active{border-color:var(--blue);color:var(--blue)}.chip-changed{color:var(--amber);margin-left:6px}.blocks{flex-direction:column;gap:14px;padding-top:18px;display:flex}.hidden-note{color:var(--dim);text-align:center;border:1px dashed var(--line);border-radius:var(--radius);padding:6px}.block{border:1px solid var(--line);border-left:4px solid var(--line);border-radius:var(--radius);background:var(--panel);padding:10px 14px}.block.is-added{border-left-color:var(--green)}.block.is-modified{border-left-color:var(--amber)}.block.is-moved{border-left-color:var(--blue)}.block.is-removed{border-left-color:var(--red);opacity:.75}.block.is-removed .block-body{color:var(--dim);text-decoration:line-through}.block-head{align-items:center;gap:8px;margin-bottom:6px;display:flex}.block-id{color:var(--dim);opacity:.6;font:11px/1 ui-monospace,monospace}.add{margin-left:auto;padding:2px 8px;font-size:12px}.block-body>:first-child{margin-top:0}.block-body>:last-child{margin-bottom:0}.block-body pre,.block-body code{font-family:ui-monospace,SFMono-Regular,Menlo,monospace}.block-body pre{border:1px solid var(--line);border-radius:var(--radius);background:#0f1217;padding:10px 12px;overflow:auto}.block-body :not(pre)>code{background:#262c36;border-radius:4px;padding:1px 5px;font-size:.92em}.block-body a{color:var(--blue)}.block-body table{border-collapse:collapse}.block-body th,.block-body td{border:1px solid var(--line);padding:4px 8px}.block-body blockquote{border-left:3px solid var(--line);color:var(--dim);margin:0;padding-left:12px}.badge{border:1px solid var(--line);color:var(--dim);text-transform:uppercase;letter-spacing:.04em;border-radius:999px;padding:1px 8px;font-size:11px}.badge-unchanged{display:none}.badge-added{border-color:var(--green);color:var(--green)}.badge-modified{border-color:var(--amber);color:var(--amber)}.badge-moved{border-color:var(--blue);color:var(--blue)}.badge-removed{border-color:var(--red);color:var(--red)}.note{border-radius:var(--radius);background:var(--panel-2);border-left:3px solid var(--line);align-items:baseline;gap:8px;margin-top:8px;padding:6px 10px;display:flex}.note.change{border-left-color:var(--red)}.note.suggest{border-left-color:var(--blue)}.note.question{border-left-color:var(--dim)}.note-verdict{text-transform:uppercase;color:var(--dim);letter-spacing:.04em;font-size:11px}.note-text{white-space:pre-wrap;flex:1}.remove{padding:0 8px;font-size:12px}.editor,.global-panel{border:1px dashed var(--line);border-radius:var(--radius);background:var(--panel-2);margin-top:10px;padding:10px}.global-panel{margin:16px 0}.verdicts{color:var(--dim);gap:14px;margin-bottom:8px;display:flex}.verdicts label{cursor:pointer}.verdicts label.active{color:var(--text)}.verdicts input{margin-right:4px}.editor textarea{resize:vertical;width:100%;min-height:70px;color:var(--text);border:1px solid var(--line);border-radius:var(--radius);font:inherit;background:#0f1217;padding:8px}.editor-actions{justify-content:flex-end;gap:8px;margin-top:8px;display:flex}.footer{border-top:1px solid var(--line);-webkit-backdrop-filter:blur(6px);backdrop-filter:blur(6px);background:#14171df0;justify-content:space-between;align-items:center;gap:16px;padding:12px 24px;display:flex;position:fixed;bottom:0;left:0;right:0}.hint{color:var(--dim);font-size:12px}.actions{gap:10px;display:flex}.empty{color:var(--dim)}
@@ -0,0 +1,14 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <meta name="robots" content="noindex" />
7
+ <title>ask-plan</title>
8
+ <script type="module" crossorigin src="/index-C1YLIi4I.js"></script>
9
+ <link rel="stylesheet" crossorigin href="/index-DMEpYC3V.css">
10
+ </head>
11
+ <body>
12
+ <div id="root"></div>
13
+ </body>
14
+ </html>
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Wiring between the built UI and the review server.
3
+ *
4
+ * The UI is a separate Vite app whose output is committed to
5
+ * `src/features/plan/assets/` (see `pnpm ui:check`). These assertions catch the
6
+ * failure that would otherwise only show up in a browser: the page shipping a
7
+ * bundle path the server cannot resolve (Vite's `assetsDir` and the server's
8
+ * `/assets/<file>` route have to agree).
9
+ */
10
+ import { existsSync } from "node:fs";
11
+ import { mkdtempSync, rmSync } from "node:fs";
12
+ import { tmpdir } from "node:os";
13
+ import { join } from "node:path";
14
+ import { afterAll, beforeAll, describe, expect, it } from "vitest";
15
+ import { startPlanServer } from "./server.js";
16
+ import { createPlanSession } from "./store.js";
17
+
18
+ const assetsDir = new URL("./assets/", import.meta.url).pathname;
19
+ const built = existsSync(join(assetsDir, "index.html"));
20
+ let agentDir: string;
21
+
22
+ beforeAll(() => {
23
+ agentDir = mkdtempSync(join(tmpdir(), "pi-plan-assets-"));
24
+ });
25
+
26
+ afterAll(() => {
27
+ rmSync(agentDir, { recursive: true, force: true });
28
+ });
29
+
30
+ describe.skipIf(!built)("built UI assets", () => {
31
+ it("serves the built page and the bundle it references", async () => {
32
+ const session = createPlanSession({ agentDir, slug: "assets", text: "## Plan\n\nbody" });
33
+ const server = await startPlanServer({
34
+ session,
35
+ portStart: 44_000 + Math.floor(Math.random() * 1000),
36
+ portAttempts: 20,
37
+ bindHost: "127.0.0.1",
38
+ urlHost: "127.0.0.1",
39
+ closeDelayMs: 0,
40
+ });
41
+ try {
42
+ const page = await fetch(`http://127.0.0.1:${server.port}/?t=${server.token}`);
43
+ expect(page.status).toBe(200);
44
+ const html = await page.text();
45
+ expect(html).toContain('<div id="root">');
46
+
47
+ const assetPath = /src="([^"]+\.js)"/.exec(html)?.[1];
48
+ expect(assetPath, "the built page must reference its bundle").toBeTruthy();
49
+ const bundle = await fetch(`http://127.0.0.1:${server.port}${assetPath}`);
50
+ expect(bundle.status).toBe(200);
51
+ expect(bundle.headers.get("content-type")).toContain("javascript");
52
+ expect((await bundle.text()).length).toBeGreaterThan(1000);
53
+
54
+ const stylePath = /href="([^"]+\.css)"/.exec(html)?.[1];
55
+ if (stylePath) {
56
+ const style = await fetch(`http://127.0.0.1:${server.port}${stylePath}`);
57
+ expect(style.status).toBe(200);
58
+ expect(style.headers.get("content-type")).toContain("text/css");
59
+ }
60
+ } finally {
61
+ await server.close();
62
+ }
63
+ });
64
+ });