@andares/pi-toolkits 0.13.0 → 1.0.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 (44) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/README.md +123 -25
  3. package/README.zh-CN.md +75 -21
  4. package/package.json +14 -4
  5. package/src/features/ask/index.test.ts +15 -0
  6. package/src/features/ask/index.ts +17 -0
  7. package/src/features/init/audit.test.ts +19 -2
  8. package/src/features/init/audit.ts +117 -15
  9. package/src/features/init/index.test.ts +123 -1
  10. package/src/features/init/index.ts +156 -46
  11. package/src/features/init/parity.test.ts +176 -0
  12. package/src/features/init/parity.ts +229 -0
  13. package/src/features/init/plan.ts +25 -3
  14. package/src/features/init/refresh.test.ts +88 -1
  15. package/src/features/init/refresh.ts +43 -64
  16. package/src/features/init/spec.ts +11 -0
  17. package/src/features/init/templates/memory-readme.md +9 -2
  18. package/src/features/init/test-helpers.ts +1 -0
  19. package/src/features/init/workflow.ts +159 -0
  20. package/src/features/permission/policy.test.ts +10 -0
  21. package/src/features/permission/units.test.ts +157 -0
  22. package/src/features/permission/units.ts +317 -15
  23. package/src/features/plan/index.test.ts +51 -0
  24. package/src/features/plan/index.ts +24 -4
  25. package/src/features/quit-guard/constants.ts +18 -5
  26. package/src/features/quit-guard/index.ts +75 -29
  27. package/src/features/quit-guard/killer.test.ts +77 -0
  28. package/src/features/quit-guard/killer.ts +215 -0
  29. package/src/features/review/index.ts +14 -0
  30. package/src/features/review/review.test.ts +34 -2
  31. package/src/features/uat/index.test.ts +15 -0
  32. package/src/features/uat/index.ts +10 -7
  33. package/src/features/uat/record-tool.ts +3 -2
  34. package/src/features/uat/state.ts +13 -5
  35. package/src/features/whats-new/changelog.ts +104 -0
  36. package/src/features/whats-new/constants.ts +35 -0
  37. package/src/features/whats-new/index.ts +146 -0
  38. package/src/features/whats-new/notice.ts +68 -0
  39. package/src/features/whats-new/paths.ts +29 -0
  40. package/src/features/whats-new/store.ts +114 -0
  41. package/src/features/whats-new/version.ts +43 -0
  42. package/src/features/whats-new/whats-new.test.ts +460 -0
  43. package/src/index.ts +3 -0
  44. package/src/lib/phases.ts +37 -0
@@ -0,0 +1,229 @@
1
+ /**
2
+ * init feature — framework-owned text versus the installed tool.
3
+ *
4
+ * `/ask-init` must answer one question on a repeated run: *is the project's
5
+ * framework text on par with the version of this tool, and if not, what can be
6
+ * repaired without judgement?* This module is the read-only half of that
7
+ * answer. It compares each managed file with the bytes this version renders,
8
+ * distinguishes a hand edit from an older template, and reports required files
9
+ * that are simply missing.
10
+ *
11
+ * It never writes. The operator's files are theirs: a managed file is rewritten
12
+ * only when `refresh` has an anchor proving the disk still holds our bytes.
13
+ */
14
+ import { createHash } from "node:crypto";
15
+ import { existsSync, readFileSync, statSync } from "node:fs";
16
+ import { join } from "node:path";
17
+ import { inspectWorkflowBlock, type WorkflowStatus } from "./workflow.js";
18
+ import {
19
+ AGENTS_FILE,
20
+ BUDGETS,
21
+ CONTRACT_FILE,
22
+ FRAMEWORK_VERSION,
23
+ IMPLEMENTATIONS_DIR,
24
+ MEMORY_DIR,
25
+ MEMORY_FILES,
26
+ PLAN_FILE,
27
+ SIGNPOST_FILE,
28
+ STATE_FILE,
29
+ STATE_GITIGNORE,
30
+ UAT_CONTRACT_FILE,
31
+ } from "./spec.js";
32
+ import { renderTemplate } from "./templates.js";
33
+ import type { FrameworkState } from "./types.js";
34
+
35
+ export interface ManagedSpec {
36
+ readonly path: string;
37
+ readonly template: string;
38
+ readonly tokens: Record<string, string>;
39
+ }
40
+
41
+ /** Files `refresh` owns. The set is also what state.toml anchors. */
42
+ export const MANAGED_SPECS: readonly ManagedSpec[] = [
43
+ { path: CONTRACT_FILE, template: "memory-readme", tokens: {} },
44
+ { path: SIGNPOST_FILE, template: "signpost", tokens: {} },
45
+ {
46
+ path: UAT_CONTRACT_FILE,
47
+ template: "uat-readme",
48
+ tokens: { implementationsDir: IMPLEMENTATIONS_DIR },
49
+ },
50
+ { path: STATE_GITIGNORE, template: "state-gitignore", tokens: {} },
51
+ ];
52
+
53
+ export function baseTokens(): Record<string, string> {
54
+ return {
55
+ frameworkVersion: String(FRAMEWORK_VERSION),
56
+ softBudget: String(BUDGETS.agentsMdSoftChars),
57
+ hardBudget: String(BUDGETS.agentsMdHardChars),
58
+ memoryBudget: String(BUDGETS.memoryFileChars),
59
+ implementationsBudget: String(BUDGETS.implementationsFiles),
60
+ implementationsDir: IMPLEMENTATIONS_DIR,
61
+ statePath: STATE_FILE,
62
+ contractPath: CONTRACT_FILE,
63
+ uatLedger: ".agents/uat/ledger.jsonl",
64
+ };
65
+ }
66
+
67
+ /** The exact Markdown for the ask workflow block. */
68
+ export function workflowBlockText(): string {
69
+ return renderTemplate("workflow-block", {}, "en");
70
+ }
71
+
72
+ export function renderManaged(spec: ManagedSpec): string {
73
+ return renderTemplate(spec.template, { ...baseTokens(), ...spec.tokens }, "en");
74
+ }
75
+
76
+ function sha256(text: string): string {
77
+ return createHash("sha256").update(text).digest("hex");
78
+ }
79
+
80
+ export type ManagedStatus = "current" | "stale" | "missing" | "hand-edited" | "unverifiable";
81
+
82
+ export interface ManagedParity {
83
+ readonly path: string;
84
+ readonly status: ManagedStatus;
85
+ readonly reason?: string;
86
+ }
87
+
88
+ /**
89
+ * Compare every managed file with the current template. `state` may be absent:
90
+ * without anchors every differing file is `unverifiable`, never a hand edit.
91
+ */
92
+ export function inspectManaged(
93
+ root: string,
94
+ state?: FrameworkState,
95
+ ): ManagedParity[] {
96
+ const byPath = new Map((state?.managed ?? []).map((entry) => [entry.path, entry]));
97
+ return MANAGED_SPECS.map((spec) => {
98
+ const absolute = join(root, spec.path);
99
+ if (!existsSync(absolute)) return { path: spec.path, status: "missing" };
100
+ let disk: string;
101
+ try {
102
+ disk = readFileSync(absolute, "utf8");
103
+ } catch (error) {
104
+ return {
105
+ path: spec.path,
106
+ status: "unverifiable",
107
+ reason: `could not read the file (${error instanceof Error ? error.message : String(error)})`,
108
+ };
109
+ }
110
+ const rendered = renderManaged(spec);
111
+ const anchor = byPath.get(spec.path)?.templateSha256;
112
+ if (anchor === undefined) {
113
+ return disk === rendered
114
+ ? { path: spec.path, status: "current" }
115
+ : {
116
+ path: spec.path,
117
+ status: "unverifiable",
118
+ reason: "no template anchor: cannot tell a hand edit from an older template",
119
+ };
120
+ }
121
+ if (sha256(disk) !== anchor) {
122
+ return {
123
+ path: spec.path,
124
+ status: "hand-edited",
125
+ reason: "the file no longer matches the bytes this tool last rendered",
126
+ };
127
+ }
128
+ return disk === rendered
129
+ ? { path: spec.path, status: "current" }
130
+ : { path: spec.path, status: "stale" };
131
+ });
132
+ }
133
+
134
+ /**
135
+ * Files the framework contract requires for a usable loop. Managed files are
136
+ * reported separately (they have their own refresh path); this list is what
137
+ * `/ask-init` can recreate mechanically from seeds.
138
+ */
139
+ export function requiredFrameworkFiles(): string[] {
140
+ return [
141
+ AGENTS_FILE,
142
+ ...MEMORY_FILES.filter((file) => file.core).map((file) => `${MEMORY_DIR}/${file.file}`),
143
+ PLAN_FILE,
144
+ ];
145
+ }
146
+
147
+ export function missingRequired(root: string): string[] {
148
+ return requiredFrameworkFiles().filter((rel) => !isFile(join(root, rel)));
149
+ }
150
+
151
+ /** A directory named `AGENTS.md` is not an entry file; readiness checks types. */
152
+ function isFile(absolute: string): boolean {
153
+ try {
154
+ return statSync(absolute).isFile();
155
+ } catch {
156
+ return false;
157
+ }
158
+ }
159
+
160
+ function isDirectory(absolute: string): boolean {
161
+ try {
162
+ return statSync(absolute).isDirectory();
163
+ } catch {
164
+ return false;
165
+ }
166
+ }
167
+
168
+ /** The workflow block in AGENTS.md, or a reason it cannot be judged. */
169
+ export function inspectWorkflow(root: string): WorkflowStatus {
170
+ const absolute = join(root, AGENTS_FILE);
171
+ if (!existsSync(absolute)) return "missing-agents";
172
+ try {
173
+ const text = readFileSync(absolute, "utf8");
174
+ return inspectWorkflowBlock(text, workflowBlockText()).status;
175
+ } catch {
176
+ return "malformed";
177
+ }
178
+ }
179
+
180
+ export interface FrameworkParity {
181
+ readonly managed: ManagedParity[];
182
+ readonly requiredMissing: string[];
183
+ readonly workflow: WorkflowStatus;
184
+ }
185
+
186
+ export function inspectFramework(root: string, state?: FrameworkState): FrameworkParity {
187
+ return {
188
+ managed: inspectManaged(root, state),
189
+ requiredMissing: missingRequired(root),
190
+ workflow: inspectWorkflow(root),
191
+ };
192
+ }
193
+
194
+ /** Compact lines for the plan preview, the audit report and a no-op notice. */
195
+ export function describeParity(parity: FrameworkParity): string[] {
196
+ const lines: string[] = [];
197
+ const drift = parity.managed.filter((entry) => entry.status !== "current");
198
+ if (drift.length === 0) {
199
+ lines.push("- framework files: current");
200
+ } else {
201
+ for (const entry of drift) {
202
+ lines.push(`- ${entry.status}: ${entry.path}${entry.reason ? ` (${entry.reason})` : ""}`);
203
+ }
204
+ }
205
+ lines.push(`- workflow block: ${parity.workflow}`);
206
+ if (parity.requiredMissing.length > 0) {
207
+ lines.push(`- required files missing: ${parity.requiredMissing.join(", ")}`);
208
+ }
209
+ return lines;
210
+ }
211
+
212
+ /**
213
+ * The tolerant "can the ask loop run here?" predicate.
214
+ *
215
+ * Deliberately feature-based, not byte-based: small edits to a memory file do
216
+ * not break the loop, so they must not block `/ask-uat` or `record_change`.
217
+ */
218
+ export interface FrameworkReadiness {
219
+ readonly ready: boolean;
220
+ readonly missing: string[];
221
+ }
222
+
223
+ export function frameworkReadiness(root: string): FrameworkReadiness {
224
+ const missing = [STATE_FILE, AGENTS_FILE, CONTRACT_FILE].filter(
225
+ (rel) => !isFile(join(root, rel)),
226
+ );
227
+ if (!isDirectory(join(root, IMPLEMENTATIONS_DIR))) missing.push(IMPLEMENTATIONS_DIR);
228
+ return { ready: missing.length === 0, missing };
229
+ }
@@ -41,6 +41,7 @@ import {
41
41
  } from "./spec.js";
42
42
  import { duplicateHeadings, largestSections, sectionsAfterAppendix, tombstones } from "./analyze.js";
43
43
  import { countBareRefs } from "./detect.js";
44
+ import { missingRequired } from "./parity.js";
44
45
  import { indexBlock, rootsBlock } from "./render.js";
45
46
  import { renderTemplate } from "./templates.js";
46
47
  import type {
@@ -181,7 +182,10 @@ function selectMode(facts: Facts): PlanMode {
181
182
  !facts.retiredTodos &&
182
183
  // A PLAN.md left in memory is pre-v1 layout, not an installed plan home.
183
184
  !existsSync(join(facts.root, MEMORY_DIR, "PLAN.md")) &&
184
- existsSync(join(facts.root, CONTRACT_FILE));
185
+ existsSync(join(facts.root, CONTRACT_FILE)) &&
186
+ // AGENTS.md and the core memory seeds are what make the loop readable;
187
+ // missing ones are mechanical repairs, not a reason to audit only.
188
+ missingRequired(facts.root).length === 0;
185
189
  return layoutOk ? "audit-only" : "reconcile";
186
190
  }
187
191
  const anyContent =
@@ -329,6 +333,7 @@ function editAgentsTask(facts: Facts, deep: boolean): Task | undefined {
329
333
  acceptance: [
330
334
  "no fact was dropped: every removed sentence is either still present verbatim in the destination or listed in the coverage table",
331
335
  `AGENTS.md stays under ${BUDGETS.agentsMdHardChars} characters (soft: ${BUDGETS.agentsMdSoftChars})`,
336
+ "the ask workflow markers (`<!-- ask-init:begin workflow … -->` … `<!-- ask-init:end workflow -->`) stay intact; the block inside them is framework-owned",
332
337
  ],
333
338
  };
334
339
  }
@@ -566,6 +571,10 @@ export function buildPlan(facts: Facts, options: PlanOptions): Plan {
566
571
  const snapshotPaths = [
567
572
  AGENTS_FILE,
568
573
  CLAUDE_FILE,
574
+ CONTRACT_FILE,
575
+ SIGNPOST_FILE,
576
+ UAT_CONTRACT_FILE,
577
+ STATE_GITIGNORE,
569
578
  facts.deprecated.memory ? "memory" : "",
570
579
  facts.deprecated.implementations ? "implementations" : "",
571
580
  facts.deprecated.prompts ? "prompts" : "",
@@ -738,7 +747,6 @@ export function buildPlan(facts: Facts, options: PlanOptions): Plan {
738
747
  }
739
748
 
740
749
  /* Tasks. */
741
- if (mode !== "upgrade") tasks.push(surveyTask(facts));
742
750
  const edit = editAgentsTask(facts, deep);
743
751
  if (edit) tasks.push(edit);
744
752
  else if (!facts.context.agents) {
@@ -808,9 +816,20 @@ export function buildPlan(facts: Facts, options: PlanOptions): Plan {
808
816
  if (roots) tasks.push(roots);
809
817
  const budget = budgetTask(facts);
810
818
  if (budget) tasks.push(budget);
811
- const coverage = coverageTask(facts, now);
819
+ const needsCoverage =
820
+ mode === "adopt" ||
821
+ facts.legacyMemory.length > 0 ||
822
+ facts.legacyDocs.length > 0 ||
823
+ facts.todos.length > 0;
824
+ const coverage = needsCoverage ? coverageTask(facts, now) : undefined;
812
825
  if (coverage) tasks.push(coverage);
813
826
 
827
+ // A reconcile caused only by missing files/directories is mechanical: no
828
+ // survey and no model turn. A survey is only worth paying for when there is
829
+ // prose work to decide; fresh/adopt always need it.
830
+ const mechanicalOnly = mode === "reconcile" && tasks.length === 0;
831
+ if (!mechanicalOnly) tasks.unshift(surveyTask(facts));
832
+
814
833
  /* State last: it records what this run created and moved. */
815
834
  actions.push({ kind: "write-state", state: buildState(facts, now, options.toolVersion, mode) });
816
835
 
@@ -837,6 +856,9 @@ export function buildPlan(facts: Facts, options: PlanOptions): Plan {
837
856
  if (creates.length > 0) {
838
857
  summary.push(`create ${creates.length} files (contract, signpost, seeds, state)`);
839
858
  }
859
+ if (mechanicalOnly) {
860
+ summary.push("mechanical repair only — no model tasks");
861
+ }
840
862
  if (tasks.length > 0) {
841
863
  summary.push(`hand ${tasks.length} tasks to the model: ${tasks.map((task) => task.id).join(", ")}`);
842
864
  }
@@ -4,7 +4,7 @@ import { join } from "node:path";
4
4
  import { afterEach, describe, expect, it } from "vitest";
5
5
  import { stateToToml } from "./apply.js";
6
6
  import { loadState } from "./detect.js";
7
- import { applyWorkflowBlock, refreshFramework } from "./refresh.js";
7
+ import { applyWorkflowBlock, describeRefresh, refreshFramework } from "./refresh.js";
8
8
  import { CONTRACT_FILE, UAT_CONTRACT_FILE, UAT_DIR, WORKFLOW_BLOCK_BEGIN, WORKFLOW_BLOCK_END } from "./spec.js";
9
9
  import { installedProject, remove } from "./test-helpers.js";
10
10
 
@@ -80,6 +80,62 @@ describe("workflow block", () => {
80
80
  const appended = applyWorkflowBlock("# demo\n\n## Body\n\ntext\n", block);
81
81
  expect(appended.text.trimEnd().endsWith(WORKFLOW_BLOCK_END)).toBe(true);
82
82
  });
83
+
84
+ it("never treats inline marker examples as the managed block", () => {
85
+ const text = [
86
+ "# demo",
87
+ "",
88
+ "- docs: `<!-- ask-init:begin workflow v1 -->`",
89
+ " `<!-- ask-init:end workflow -->`,块外文字保持原样",
90
+ "",
91
+ "## Body",
92
+ "",
93
+ "tail",
94
+ ].join("\n");
95
+ const block = `${WORKFLOW_BLOCK_BEGIN} v1 -->\n## Ask workflow\n${WORKFLOW_BLOCK_END}`;
96
+ const result = applyWorkflowBlock(text, block);
97
+ expect(result.status).toBe("inserted");
98
+ expect(result.text).toContain("`<!-- ask-init:begin workflow v1 -->`");
99
+ expect(result.text).toContain("块外文字保持原样");
100
+ });
101
+
102
+ it("ignores markers inside fenced code blocks", () => {
103
+ const text = [
104
+ "# demo",
105
+ "",
106
+ "```md",
107
+ "<!-- ask-init:begin workflow v1 -->",
108
+ "## example",
109
+ "<!-- ask-init:end workflow -->",
110
+ "```",
111
+ "",
112
+ ].join("\n");
113
+ const block = `${WORKFLOW_BLOCK_BEGIN} v1 -->\n## Ask workflow\n${WORKFLOW_BLOCK_END}`;
114
+ const result = applyWorkflowBlock(text, block);
115
+ expect(result.status).toBe("inserted");
116
+ expect(result.text).toContain("## example");
117
+ });
118
+
119
+ it("does not add a second block when a hand-written Ask workflow section exists", () => {
120
+ const text = "# demo\n\n## Ask workflow\n\nDo it by hand.\n";
121
+ const block = `${WORKFLOW_BLOCK_BEGIN} v1 -->\n## Ask workflow\n${WORKFLOW_BLOCK_END}`;
122
+ const result = applyWorkflowBlock(text, block);
123
+ expect(result.status).toBe("hand-written");
124
+ expect(result.text).toBe(text);
125
+ });
126
+
127
+ it("reports malformed marker layouts without touching the file", () => {
128
+ const block = `${WORKFLOW_BLOCK_BEGIN} v1 -->\n## Ask workflow\n${WORKFLOW_BLOCK_END}`;
129
+ const beginOnly = `# demo\n\n${WORKFLOW_BLOCK_BEGIN} v1 -->\n## old\n`;
130
+ const first = applyWorkflowBlock(beginOnly, block);
131
+ expect(first.status).toBe("malformed");
132
+ expect(first.text).toBe(beginOnly);
133
+
134
+ const endFirst = `# demo\n\n${WORKFLOW_BLOCK_END}\n## old\n${WORKFLOW_BLOCK_BEGIN} v1 -->\n`;
135
+ const second = applyWorkflowBlock(endFirst, block);
136
+ expect(second.status).toBe("malformed");
137
+ expect(second.text).toBe(endFirst);
138
+ });
83
139
  });
84
140
 
85
141
  describe("refreshFramework", () => {
@@ -142,9 +198,18 @@ describe("refreshFramework", () => {
142
198
  const result = refreshFramework(root);
143
199
  expect(result.updated).not.toContain(CONTRACT_FILE);
144
200
  expect(result.skipped.map((entry) => entry.path)).toContain(CONTRACT_FILE);
201
+ expect(result.skipped.find((entry) => entry.path === CONTRACT_FILE)?.reason).toMatch(/edited by hand/);
145
202
  expect(readFileSync(join(root, CONTRACT_FILE), "utf8")).toBe("my own contract\n");
146
203
  });
147
204
 
205
+ it("reports a missing AGENTS.md instead of calling the framework current", () => {
206
+ const root = installed();
207
+ remove(join(root, "AGENTS.md"));
208
+ const result = refreshFramework(root, { dryRun: true });
209
+ expect(result.block).toBe("missing-agents");
210
+ expect(describeRefresh(result)).toContain("AGENTS.md is missing");
211
+ });
212
+
148
213
  it("writes nothing in a dry run", () => {
149
214
  const root = installed();
150
215
  const before = readFileSync(join(root, "AGENTS.md"), "utf8");
@@ -175,6 +240,28 @@ describe("refreshFramework", () => {
175
240
  expect(readFileSync(join(root, CONTRACT_FILE), "utf8")).toBe(edited);
176
241
  });
177
242
 
243
+ it("adopts a legacy file only when --adopt is explicit", () => {
244
+ const root = installed();
245
+ const legacy = "legacy contract from an older version\n";
246
+ writeFileSync(join(root, CONTRACT_FILE), legacy, "utf8");
247
+ writeState(root, [
248
+ {
249
+ path: CONTRACT_FILE,
250
+ sha256: sha256(legacy),
251
+ template: "memory-readme",
252
+ templateSha256: undefined,
253
+ },
254
+ ]);
255
+ const skipped = refreshFramework(root);
256
+ expect(skipped.updated).not.toContain(CONTRACT_FILE);
257
+ expect(skipped.skipped.map((entry) => entry.path)).toContain(CONTRACT_FILE);
258
+
259
+ const adopted = refreshFramework(root, { adoptLegacy: true });
260
+ expect(adopted.adopted).toContain(CONTRACT_FILE);
261
+ expect(adopted.updated).toContain(CONTRACT_FILE);
262
+ expect(readFileSync(join(root, CONTRACT_FILE), "utf8")).not.toBe(legacy);
263
+ });
264
+
178
265
  it("persists missing template anchors even when no file content changes", () => {
179
266
  const root = installed();
180
267
  refreshFramework(root, { toolVersion: "test" });
@@ -17,6 +17,11 @@
17
17
  * 3. **Missing optional pieces are created** (the UAT contract), so a project
18
18
  * that adopted the framework before the ledger existed can catch up.
19
19
  *
20
+ * `/ask-init` runs this on every invocation: on an installed project the first
21
+ * step is now the same comparison, so a repeat run either reports "current" or
22
+ * repairs what is safe before the audit. Marker matching lives in `workflow.ts`
23
+ * and refuses to touch ambiguous layouts.
24
+ *
20
25
  * The command is idempotent: a second run reports "current" everywhere.
21
26
  */
22
27
  import { createHash } from "node:crypto";
@@ -24,47 +29,39 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
24
29
  import { dirname, resolve, sep } from "node:path";
25
30
  import {
26
31
  AGENTS_FILE,
27
- BUDGETS,
28
- CONTRACT_FILE,
29
- FRAMEWORK_VERSION,
30
- IMPLEMENTATIONS_DIR,
31
- SIGNPOST_FILE,
32
32
  STATE_FILE,
33
- STATE_GITIGNORE,
34
- UAT_CONTRACT_FILE,
35
- WORKFLOW_BLOCK_BEGIN,
36
- WORKFLOW_BLOCK_END,
37
33
  } from "./spec.js";
38
34
  import { loadState } from "./detect.js";
39
35
  import { iso } from "./plan.js";
40
36
  import { stateToToml } from "./apply.js";
41
- import { renderTemplate } from "./templates.js";
37
+ import { MANAGED_SPECS, renderManaged, workflowBlockText } from "./parity.js";
42
38
  import type { FrameworkState } from "./types.js";
39
+ import {
40
+ applyWorkflowBlock,
41
+ type BlockStatus,
42
+ } from "./workflow.js";
43
+
44
+ export { applyWorkflowBlock } from "./workflow.js";
43
45
 
44
46
  export interface RefreshOptions {
45
47
  readonly dryRun?: boolean;
46
48
  readonly now?: Date;
47
49
  readonly toolVersion?: string;
50
+ /** Treat a legacy managed file with no anchor as ours and update it. */
51
+ readonly adoptLegacy?: boolean;
48
52
  }
49
53
 
50
- export type BlockStatus = "current" | "updated" | "inserted" | "missing-agents";
51
-
52
54
  export interface RefreshResult {
53
55
  readonly created: string[];
54
56
  readonly updated: string[];
57
+ /** Legacy files taken over because `--adopt` was explicit. */
58
+ readonly adopted: string[];
55
59
  readonly skipped: Array<{ path: string; reason: string }>;
56
60
  readonly block: BlockStatus;
57
61
  readonly stateUpdated: boolean;
58
62
  readonly dryRun: boolean;
59
63
  }
60
64
 
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
65
  function sha256(text: string): string {
69
66
  return createHash("sha256").update(text).digest("hex");
70
67
  }
@@ -78,43 +75,6 @@ function inside(root: string, rel: string): string {
78
75
  return absolute;
79
76
  }
80
77
 
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
78
  export function refreshFramework(root: string, options: RefreshOptions = {}): RefreshResult {
119
79
  const loaded = loadState(root);
120
80
  if (!loaded.state) {
@@ -127,13 +87,14 @@ export function refreshFramework(root: string, options: RefreshOptions = {}): Re
127
87
  const dryRun = options.dryRun === true;
128
88
  const created: string[] = [];
129
89
  const updated: string[] = [];
90
+ const adopted: string[] = [];
130
91
  const skipped: RefreshResult["skipped"] = [];
131
92
  const previous = new Map(state.managed.map((entry) => [entry.path, entry]));
132
93
  const nextManaged = new Map(state.managed.map((entry) => [entry.path, { ...entry }]));
133
94
 
134
- for (const spec of MANAGED_TEMPLATES) {
95
+ for (const spec of MANAGED_SPECS) {
135
96
  const absolute = inside(root, spec.path);
136
- const rendered = renderTemplate(spec.template, { ...baseTokens(), ...spec.tokens }, "en");
97
+ const rendered = renderManaged(spec);
137
98
  const exists = existsSync(absolute);
138
99
  const disk = exists ? readFileSync(absolute, "utf8") : undefined;
139
100
  const entry = previous.get(spec.path);
@@ -145,7 +106,7 @@ export function refreshFramework(root: string, options: RefreshOptions = {}): Re
145
106
  const safe = exists
146
107
  ? entry?.templateSha256 !== undefined
147
108
  ? diskHash === entry.templateSha256
148
- : diskHash === sha256(rendered)
109
+ : diskHash === sha256(rendered) || options.adoptLegacy === true
149
110
  : true;
150
111
 
151
112
  if (!exists) {
@@ -166,7 +127,10 @@ export function refreshFramework(root: string, options: RefreshOptions = {}): Re
166
127
  if (!safe) {
167
128
  skipped.push({
168
129
  path: spec.path,
169
- reason: "edited by hand since the framework last wrote it — left untouched",
130
+ reason:
131
+ entry?.templateSha256 !== undefined
132
+ ? "edited by hand since the framework last wrote it — left untouched"
133
+ : "no template anchor and the bytes differ from the current template — cannot tell a hand edit from an older template; left untouched",
170
134
  });
171
135
  continue;
172
136
  }
@@ -181,6 +145,9 @@ export function refreshFramework(root: string, options: RefreshOptions = {}): Re
181
145
  continue;
182
146
  }
183
147
 
148
+ if (entry?.templateSha256 === undefined && options.adoptLegacy === true) {
149
+ adopted.push(spec.path);
150
+ }
184
151
  if (!dryRun) writeFileSync(absolute, rendered, "utf8");
185
152
  updated.push(spec.path);
186
153
  nextManaged.set(spec.path, {
@@ -191,15 +158,16 @@ export function refreshFramework(root: string, options: RefreshOptions = {}): Re
191
158
  });
192
159
  }
193
160
 
194
- // The one block this tool owns inside a file it does not own.
161
+ // The one block this tool owns inside a file it does not own. A malformed
162
+ // marker layout is reported, never rewritten.
195
163
  let block: BlockStatus = "missing-agents";
196
164
  const agentsPath = inside(root, AGENTS_FILE);
197
165
  if (existsSync(agentsPath)) {
198
166
  const text = readFileSync(agentsPath, "utf8");
199
- const rendered = renderTemplate("workflow-block", {}, "en");
167
+ const rendered = workflowBlockText();
200
168
  const result = applyWorkflowBlock(text, rendered);
201
169
  block = result.status;
202
- if (result.status !== "current" && !dryRun) {
170
+ if ((result.status === "inserted" || result.status === "updated") && !dryRun) {
203
171
  writeFileSync(agentsPath, result.text, "utf8");
204
172
  }
205
173
  }
@@ -234,6 +202,7 @@ export function refreshFramework(root: string, options: RefreshOptions = {}): Re
234
202
  return {
235
203
  created,
236
204
  updated,
205
+ adopted,
237
206
  skipped,
238
207
  block,
239
208
  stateUpdated: !dryRun && stateChanged,
@@ -247,9 +216,19 @@ export function describeRefresh(result: RefreshResult): string {
247
216
  const verb = result.dryRun ? "would refresh" : "refreshed";
248
217
  if (result.created.length > 0) parts.push(`${verb} ${result.created.length} created file(s)`);
249
218
  if (result.updated.length > 0) parts.push(`${result.updated.length} framework file(s)`);
219
+ if (result.adopted.length > 0) parts.push(`${result.adopted.length} legacy file(s) adopted`);
250
220
  if (result.block === "inserted") parts.push("workflow block inserted into AGENTS.md");
251
221
  if (result.block === "updated") parts.push("workflow block updated");
222
+ if (result.block === "malformed") {
223
+ parts.push("workflow markers in AGENTS.md are inconsistent — left untouched");
224
+ }
225
+ if (result.block === "hand-written") {
226
+ parts.push("a hand-written Ask workflow section exists without markers — left untouched");
227
+ }
228
+ if (result.block === "missing-agents") {
229
+ parts.push("AGENTS.md is missing — run /ask-init to rebuild it");
230
+ }
252
231
  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)`);
232
+ if (result.skipped.length > 0) parts.push(`${result.skipped.length} left untouched (hand edits or no anchor)`);
254
233
  return parts.join(" · ");
255
234
  }
@@ -287,6 +287,9 @@ export const SCAN = {
287
287
 
288
288
  export const AUDIT_CODES = {
289
289
  pathBareRef: "E-PATH-01",
290
+ // Bare legacy references while no legacy directory exists: nothing a move
291
+ // would break, so this is stale documentation, not a migration blocker.
292
+ pathBareRefStale: "W-PATH-01",
290
293
  stateUntracked: "E-STATE-01",
291
294
  stateUncommitted: "W-STATE-01",
292
295
  stateVersion: "E-STATE-02",
@@ -318,6 +321,14 @@ export const AUDIT_CODES = {
318
321
  recordHeader: "W-REC-01",
319
322
  // Framework-owned file edited by hand: a refresh will not overwrite it.
320
323
  managedEdited: "W-FW-01",
324
+ // Managed file is missing or behind the installed template: refresh fixes it.
325
+ managedStale: "W-FW-02",
326
+ // The AGENTS.md workflow block is absent, behind, hand-written or malformed.
327
+ workflowBlock: "W-FW-03",
328
+ // A required framework file is missing: /ask-init can rebuild it mechanically.
329
+ frameworkFileMissing: "W-FW-04",
330
+ // Legacy state has no template anchor: cannot tell a hand edit from old bytes.
331
+ legacyAnchor: "I-FW-01",
321
332
  uatNotInstalled: "I-UAT-01",
322
333
  } as const;
323
334
 
@@ -80,8 +80,9 @@ compaction plan is.
80
80
 
81
81
  `/ask-init check` (or the `framework_audit` tool during an init run) reports:
82
82
 
83
- - structure: missing files, index ↔ file mismatches, `AGENTS.override.md` shadowing
84
- - paths: references to `memory` or `implementations` without the `.agents/` prefix (a move would break them)
83
+ - structure: missing required files, index ↔ file mismatches, `AGENTS.override.md` shadowing
84
+ - framework files: managed text that is missing or behind the installed template, a missing or malformed `AGENTS.md` workflow block, and hand edits (`/ask-init` refreshes only what is safe)
85
+ - paths: references to `memory` or `implementations` without the `.agents/` prefix; an error while a legacy directory still exists (`E-PATH-01`), a warning once it is gone (`W-PATH-01`)
85
86
  - duplication: the same section heading in two files (one fact, two homes)
86
87
  - order: sections appended after the historical appendix
87
88
  - budgets: `AGENTS.md` and memory-file sizes
@@ -97,3 +98,9 @@ version is newer than the state file, `/ask-init` plans an upgrade: deterministi
97
98
  steps run in code, prose changes are handed to the model as tasks. A project whose
98
99
  state version is newer than the installed tool is never migrated — upgrade the
99
100
  tool instead.
101
+
102
+ Text-only changes (the workflow block, the signpost, this contract) do not bump
103
+ the framework version. Run `/ask-init` (or `/ask-init refresh`) after upgrading
104
+ the package to bring them up to date, then `/reload` if `AGENTS.md` changed.
105
+ Re-running `/ask-init` is safe: it reports `current` when nothing drifted and
106
+ leaves files you edited by hand alone.