@andares/pi-toolkits 0.12.4 → 0.14.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 (77) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/README.md +134 -17
  3. package/README.zh-CN.md +115 -16
  4. package/package.json +24 -11
  5. package/src/features/ask/index.ts +6 -0
  6. package/src/features/init/apply.ts +32 -12
  7. package/src/features/init/audit-uat.test.ts +103 -0
  8. package/src/features/init/audit.ts +148 -0
  9. package/src/features/init/detect.ts +4 -0
  10. package/src/features/init/index.ts +47 -2
  11. package/src/features/init/plan.ts +11 -0
  12. package/src/features/init/refresh.test.ts +208 -0
  13. package/src/features/init/refresh.ts +255 -0
  14. package/src/features/init/spec.ts +20 -0
  15. package/src/features/init/templates/agents-skeleton.md +2 -0
  16. package/src/features/init/templates/uat-readme.md +53 -0
  17. package/src/features/init/templates/workflow-block.md +21 -0
  18. package/src/features/init/templates.test.ts +3 -1
  19. package/src/features/init/templates.ts +2 -0
  20. package/src/features/init/types.ts +12 -1
  21. package/src/features/permission/index.ts +32 -0
  22. package/src/features/permission/policy.test.ts +10 -0
  23. package/src/features/permission/units.test.ts +157 -0
  24. package/src/features/permission/units.ts +317 -15
  25. package/src/features/plan/assets/index-C1YLIi4I.js +1 -0
  26. package/src/features/plan/assets/index-DMEpYC3V.css +1 -0
  27. package/src/features/plan/assets/index.html +14 -0
  28. package/src/features/plan/assets.test.ts +64 -0
  29. package/src/features/plan/blocks.test.ts +77 -0
  30. package/src/features/plan/blocks.ts +153 -0
  31. package/src/features/plan/diff.test.ts +144 -0
  32. package/src/features/plan/diff.ts +193 -0
  33. package/src/features/plan/feedback.test.ts +233 -0
  34. package/src/features/plan/feedback.ts +182 -0
  35. package/src/features/plan/index.test.ts +385 -0
  36. package/src/features/plan/index.ts +433 -0
  37. package/src/features/plan/prompt.test.ts +91 -0
  38. package/src/features/plan/prompt.ts +110 -0
  39. package/src/features/plan/render.test.ts +94 -0
  40. package/src/features/plan/render.ts +131 -0
  41. package/src/features/plan/server.test.ts +374 -0
  42. package/src/features/plan/server.ts +272 -0
  43. package/src/features/plan/store.test.ts +145 -0
  44. package/src/features/plan/store.ts +244 -0
  45. package/src/features/review/index.ts +54 -28
  46. package/src/features/review/review.test.ts +46 -1
  47. package/src/features/uat/assets/index-D-W9zj0w.css +1 -0
  48. package/src/features/uat/assets/index-DCBQCsli.js +1 -0
  49. package/src/features/uat/assets/index.html +14 -0
  50. package/src/features/uat/constants.ts +23 -0
  51. package/src/features/uat/index.test.ts +404 -0
  52. package/src/features/uat/index.ts +329 -0
  53. package/src/features/uat/item-tool.ts +280 -0
  54. package/src/features/uat/ledger.test.ts +249 -0
  55. package/src/features/uat/ledger.ts +504 -0
  56. package/src/features/uat/prompt.ts +78 -0
  57. package/src/features/uat/record-tool.ts +167 -0
  58. package/src/features/uat/records.test.ts +145 -0
  59. package/src/features/uat/records.ts +268 -0
  60. package/src/features/uat/server.ts +181 -0
  61. package/src/features/uat/state.test.ts +41 -0
  62. package/src/features/uat/state.ts +67 -0
  63. package/src/features/whats-new/changelog.ts +104 -0
  64. package/src/features/whats-new/constants.ts +35 -0
  65. package/src/features/whats-new/index.ts +146 -0
  66. package/src/features/whats-new/notice.ts +68 -0
  67. package/src/features/whats-new/paths.ts +29 -0
  68. package/src/features/whats-new/store.ts +114 -0
  69. package/src/features/whats-new/version.ts +43 -0
  70. package/src/features/whats-new/whats-new.test.ts +460 -0
  71. package/src/index.ts +13 -1
  72. package/src/lib/ask-control.ts +25 -0
  73. package/src/lib/opener.test.ts +72 -0
  74. package/src/lib/opener.ts +121 -0
  75. package/src/lib/permission-control.ts +39 -0
  76. package/src/lib/startup.test.ts +1 -1
  77. package/src/lib/web-review.ts +341 -0
@@ -0,0 +1,208 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { afterEach, describe, expect, it } from "vitest";
5
+ import { stateToToml } from "./apply.js";
6
+ import { loadState } from "./detect.js";
7
+ import { applyWorkflowBlock, refreshFramework } from "./refresh.js";
8
+ import { CONTRACT_FILE, UAT_CONTRACT_FILE, UAT_DIR, WORKFLOW_BLOCK_BEGIN, WORKFLOW_BLOCK_END } from "./spec.js";
9
+ import { installedProject, remove } from "./test-helpers.js";
10
+
11
+ const roots: string[] = [];
12
+
13
+ function sha256(text: string): string {
14
+ return createHash("sha256").update(text).digest("hex");
15
+ }
16
+
17
+ function installed(): string {
18
+ const root = installedProject();
19
+ roots.push(root);
20
+ return root;
21
+ }
22
+
23
+ function writeState(
24
+ root: string,
25
+ managed: Array<{ path: string; sha256: string; template: string; templateSha256?: string }>,
26
+ ): void {
27
+ writeFileSync(
28
+ join(root, ".agents/framework/state.toml"),
29
+ stateToToml({
30
+ version: 1,
31
+ tool: "0.0.0-test",
32
+ created: "2026-01-01T00:00:00+08:00",
33
+ updated: "2026-01-01T00:00:00+08:00",
34
+ profile: "core",
35
+ modules: [],
36
+ roots: [],
37
+ managed,
38
+ migrations: [],
39
+ }),
40
+ "utf8",
41
+ );
42
+ }
43
+
44
+ afterEach(() => {
45
+ for (const root of roots.splice(0)) remove(root);
46
+ });
47
+
48
+ describe("workflow block", () => {
49
+ it("replaces the block between its markers and leaves the rest alone", () => {
50
+ const text = [
51
+ "# demo",
52
+ "",
53
+ "intro",
54
+ "",
55
+ "<!-- ask-init:begin workflow v1 -->",
56
+ "## old block",
57
+ "<!-- ask-init:end workflow -->",
58
+ "",
59
+ "## After",
60
+ "",
61
+ "tail",
62
+ "",
63
+ ].join("\n");
64
+ const result = applyWorkflowBlock(text, `${WORKFLOW_BLOCK_BEGIN} v2 -->\n## new block\n${WORKFLOW_BLOCK_END}`);
65
+ expect(result.status).toBe("updated");
66
+ expect(result.text).toContain("## new block");
67
+ expect(result.text).not.toContain("## old block");
68
+ expect(result.text).toContain("intro");
69
+ expect(result.text).toContain("## After");
70
+ expect(result.text).toContain("tail");
71
+ });
72
+
73
+ it("inserts before the appendix, else at the end", () => {
74
+ const block = `${WORKFLOW_BLOCK_BEGIN} v1 -->\n## Ask workflow\n${WORKFLOW_BLOCK_END}`;
75
+ const withAppendix = applyWorkflowBlock("# demo\n\n## Body\n\ntext\n\n## 附录\n\nold\n", block);
76
+ expect(withAppendix.status).toBe("inserted");
77
+ expect(withAppendix.text.indexOf("## Ask workflow")).toBeLessThan(
78
+ withAppendix.text.indexOf("## 附录"),
79
+ );
80
+ const appended = applyWorkflowBlock("# demo\n\n## Body\n\ntext\n", block);
81
+ expect(appended.text.trimEnd().endsWith(WORKFLOW_BLOCK_END)).toBe(true);
82
+ });
83
+ });
84
+
85
+ describe("refreshFramework", () => {
86
+ it("creates the acceptance contract and inserts the workflow block", () => {
87
+ const root = installed();
88
+ const result = refreshFramework(root, { now: new Date("2026-11-13T21:07:00+08:00") });
89
+ expect(result.created).toContain(UAT_CONTRACT_FILE);
90
+ expect(existsSync(join(root, UAT_DIR))).toBe(true);
91
+ expect(result.block).toBe("inserted");
92
+ const agents = readFileSync(join(root, "AGENTS.md"), "utf8");
93
+ expect(agents).toContain(WORKFLOW_BLOCK_BEGIN);
94
+ expect(agents).toContain(WORKFLOW_BLOCK_END);
95
+ expect(agents).toContain("## Ask workflow");
96
+ // The operator's own text is untouched.
97
+ expect(agents).toContain("A demo project.");
98
+ });
99
+
100
+ it("is idempotent", () => {
101
+ const root = installed();
102
+ const first = refreshFramework(root);
103
+ expect(first.created.length + first.updated.length).toBeGreaterThan(0);
104
+ const second = refreshFramework(root);
105
+ expect(second.created).toEqual([]);
106
+ expect(second.updated).toEqual([]);
107
+ expect(second.block).toBe("current");
108
+ });
109
+
110
+ it("rewrites a managed file whose disk still equals the anchor", () => {
111
+ const root = installed();
112
+ writeFileSync(join(root, CONTRACT_FILE), "stale contract\n", "utf8");
113
+ writeState(root, [
114
+ {
115
+ path: CONTRACT_FILE,
116
+ sha256: sha256("stale contract\n"),
117
+ template: "memory-readme",
118
+ templateSha256: sha256("stale contract\n"),
119
+ },
120
+ ]);
121
+ const result = refreshFramework(root);
122
+ expect(result.updated).toContain(CONTRACT_FILE);
123
+ const text = readFileSync(join(root, CONTRACT_FILE), "utf8");
124
+ expect(text).toContain("Agent memory framework");
125
+ expect(text).not.toBe("stale contract\n");
126
+ const state = loadState(root).state;
127
+ const entry = state?.managed.find((item) => item.path === CONTRACT_FILE);
128
+ expect(entry?.templateSha256).toBe(sha256(text));
129
+ });
130
+
131
+ it("never overwrites a hand-edited framework file", () => {
132
+ const root = installed();
133
+ writeFileSync(join(root, CONTRACT_FILE), "my own contract\n", "utf8");
134
+ writeState(root, [
135
+ {
136
+ path: CONTRACT_FILE,
137
+ sha256: sha256("original contract\n"),
138
+ template: "memory-readme",
139
+ templateSha256: sha256("original contract\n"),
140
+ },
141
+ ]);
142
+ const result = refreshFramework(root);
143
+ expect(result.updated).not.toContain(CONTRACT_FILE);
144
+ expect(result.skipped.map((entry) => entry.path)).toContain(CONTRACT_FILE);
145
+ expect(readFileSync(join(root, CONTRACT_FILE), "utf8")).toBe("my own contract\n");
146
+ });
147
+
148
+ it("writes nothing in a dry run", () => {
149
+ const root = installed();
150
+ const before = readFileSync(join(root, "AGENTS.md"), "utf8");
151
+ const result = refreshFramework(root, { dryRun: true });
152
+ expect(result.dryRun).toBe(true);
153
+ expect(result.created).toContain(UAT_CONTRACT_FILE);
154
+ expect(existsSync(join(root, UAT_CONTRACT_FILE))).toBe(false);
155
+ expect(readFileSync(join(root, "AGENTS.md"), "utf8")).toBe(before);
156
+ });
157
+
158
+ it("does not trust a legacy disk hash as proof that a file was not hand-edited", () => {
159
+ const root = installed();
160
+ const edited = "operator edited this contract\n";
161
+ writeFileSync(join(root, CONTRACT_FILE), edited, "utf8");
162
+ writeState(root, [
163
+ {
164
+ path: CONTRACT_FILE,
165
+ sha256: sha256(edited),
166
+ template: "memory-readme",
167
+ // Legacy state has no template anchor. The disk hash only says what
168
+ // the last run saw, not what the framework originally rendered.
169
+ templateSha256: undefined,
170
+ },
171
+ ]);
172
+ const result = refreshFramework(root);
173
+ expect(result.updated).not.toContain(CONTRACT_FILE);
174
+ expect(result.skipped.map((entry) => entry.path)).toContain(CONTRACT_FILE);
175
+ expect(readFileSync(join(root, CONTRACT_FILE), "utf8")).toBe(edited);
176
+ });
177
+
178
+ it("persists missing template anchors even when no file content changes", () => {
179
+ const root = installed();
180
+ refreshFramework(root, { toolVersion: "test" });
181
+ const statePath = join(root, ".agents/framework/state.toml");
182
+ const state = loadState(root).state!;
183
+ writeFileSync(
184
+ statePath,
185
+ stateToToml({
186
+ ...state,
187
+ managed: state.managed.map((entry) => ({ ...entry, templateSha256: undefined })),
188
+ }),
189
+ "utf8",
190
+ );
191
+ const result = refreshFramework(root, { toolVersion: "test" });
192
+ expect(result.created).toEqual([]);
193
+ expect(result.updated).toEqual([]);
194
+ expect(result.stateUpdated).toBe(true);
195
+ expect(
196
+ loadState(root).state?.managed
197
+ .filter((entry) => existsSync(join(root, entry.path)))
198
+ .every((entry) => entry.templateSha256 !== undefined),
199
+ ).toBe(true);
200
+ });
201
+
202
+ it("refuses a project without the framework", () => {
203
+ const root = installed();
204
+ remove(root);
205
+ roots.splice(roots.indexOf(root), 1);
206
+ expect(() => refreshFramework(root)).toThrow(/\/ask-init first/);
207
+ });
208
+ });
@@ -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({