@andares/pi-toolkits 0.12.4 → 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,103 @@
1
+ import { createHash } from "node:crypto";
2
+ import { mkdirSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { afterEach, describe, expect, it } from "vitest";
5
+ import { audit } from "./audit.js";
6
+ import { stateToToml } from "./apply.js";
7
+ import { detect } from "./detect.js";
8
+ import { AUDIT_CODES, CONTRACT_FILE, UAT_CONTRACT_FILE } from "./spec.js";
9
+ import { installedProject, remove } from "./test-helpers.js";
10
+
11
+ const roots: string[] = [];
12
+
13
+ function installed(extra: Record<string, string> = {}): string {
14
+ const root = installedProject(extra);
15
+ roots.push(root);
16
+ return root;
17
+ }
18
+
19
+ function codes(root: string): string[] {
20
+ return audit(detect(root)).map((finding) => finding.code);
21
+ }
22
+
23
+ function writeLedger(root: string, lines: string[]): void {
24
+ mkdirSync(join(root, ".agents/uat"), { recursive: true });
25
+ writeFileSync(join(root, ".agents/uat/ledger.jsonl"), `${lines.join("\n")}\n`, "utf8");
26
+ }
27
+
28
+ function ledgerEvent(body: Record<string, unknown>): string {
29
+ return JSON.stringify({ v: 1, id: `e-${Math.random().toString(36).slice(2)}`, ts: "2026-11-13T21:00+08:00", ...body });
30
+ }
31
+
32
+ afterEach(() => {
33
+ for (const root of roots.splice(0)) remove(root);
34
+ });
35
+
36
+ describe("UAT audit findings", () => {
37
+ it("reports a missing acceptance ledger as info", () => {
38
+ const root = installed();
39
+ expect(codes(root)).toContain(AUDIT_CODES.uatNotInstalled);
40
+ });
41
+
42
+ it("stays quiet once the contract exists", () => {
43
+ const root = installed({ [UAT_CONTRACT_FILE]: "# ledger\n" });
44
+ writeLedger(root, []);
45
+ expect(codes(root)).not.toContain(AUDIT_CODES.uatNotInstalled);
46
+ });
47
+
48
+ it("fails on an unparsable ledger line", () => {
49
+ const root = installed({ [UAT_CONTRACT_FILE]: "# ledger\n" });
50
+ writeLedger(root, ["{not json"]);
51
+ const findings = audit(detect(root));
52
+ const finding = findings.find((entry) => entry.code === AUDIT_CODES.uatLedgerBroken);
53
+ expect(finding?.severity).toBe("error");
54
+ });
55
+
56
+ it("warns when an item points at a missing record", () => {
57
+ const root = installed({ [UAT_CONTRACT_FILE]: "# ledger\n" });
58
+ writeLedger(root, [
59
+ ledgerEvent({ type: "item", item: "U-1", title: "t", summary: "s", reports: ["gone"] }),
60
+ ]);
61
+ const findings = audit(detect(root));
62
+ expect(findings.some((entry) => entry.code === AUDIT_CODES.uatMissingReport)).toBe(true);
63
+ });
64
+
65
+ it("warns about a recent non-canonical change record", () => {
66
+ const root = installed();
67
+ writeFileSync(
68
+ join(root, ".agents/implementations/2026-11-13_handwritten.md"),
69
+ "# Handwritten\n\nno time\n",
70
+ "utf8",
71
+ );
72
+ expect(codes(root)).toContain(AUDIT_CODES.recordHeader);
73
+ });
74
+
75
+ it("warns when a framework file was edited by hand", () => {
76
+ const root = installed();
77
+ const text = "# my own contract\n";
78
+ writeFileSync(join(root, CONTRACT_FILE), text, "utf8");
79
+ writeFileSync(
80
+ join(root, ".agents/framework/state.toml"),
81
+ stateToToml({
82
+ version: 1,
83
+ tool: "test",
84
+ created: "2026-01-01T00:00:00+08:00",
85
+ updated: "2026-01-01T00:00:00+08:00",
86
+ profile: "core",
87
+ modules: [],
88
+ roots: [],
89
+ managed: [
90
+ {
91
+ path: CONTRACT_FILE,
92
+ sha256: createHash("sha256").update(text).digest("hex"),
93
+ template: "memory-readme",
94
+ templateSha256: createHash("sha256").update("rendered once\n").digest("hex"),
95
+ },
96
+ ],
97
+ migrations: [],
98
+ }),
99
+ "utf8",
100
+ );
101
+ expect(codes(root)).toContain(AUDIT_CODES.managedEdited);
102
+ });
103
+ });
@@ -9,6 +9,7 @@
9
9
  * It is read-only and never "fixes" anything itself.
10
10
  */
11
11
  import { execFileSync } from "node:child_process";
12
+ import { createHash } from "node:crypto";
12
13
  import { existsSync, readFileSync, readdirSync } from "node:fs";
13
14
  import { join, posix } from "node:path";
14
15
  import {
@@ -22,6 +23,9 @@ import {
22
23
  PLAN_FILE,
23
24
  REPORTS_DIR,
24
25
  SPECS_DIR,
26
+ UAT_CONTRACT_FILE,
27
+ UAT_DIR,
28
+ UAT_LEDGER_FILE,
25
29
  } from "./spec.js";
26
30
  import {
27
31
  duplicateHeadings,
@@ -30,6 +34,8 @@ import {
30
34
  sectionsAfterAppendix,
31
35
  } from "./analyze.js";
32
36
  import { parseCoverage } from "./coverage.js";
37
+ import { deriveState, ledgerPath, readEvents } from "../uat/ledger.js";
38
+ import { listRecords } from "../uat/records.js";
33
39
  import { staleRoots } from "./plan.js";
34
40
  import type { DocInfo, Facts, Finding, Severity } from "./types.js";
35
41
 
@@ -523,6 +529,146 @@ function checkScaffold(facts: Facts): Finding[] {
523
529
  /* Entry points */
524
530
  /* -------------------------------------------------------------------------- */
525
531
 
532
+ const DAY_MS = 86_400_000;
533
+
534
+ /**
535
+ * Framework-owned files: a refresh may rewrite one only while the disk still
536
+ * equals the bytes this tool rendered. Anything else is a hand edit, and
537
+ * silently overwriting it would destroy operator work — so the audit reports it
538
+ * instead.
539
+ */
540
+ function checkFrameworkFiles(facts: Facts): Finding[] {
541
+ const state = facts.state;
542
+ if (!state) return [];
543
+ const out: Finding[] = [];
544
+ for (const entry of state.managed) {
545
+ if (entry.path === "" || entry.templateSha256 === undefined) continue;
546
+ const absolute = join(facts.root, entry.path);
547
+ if (!existsSync(absolute)) continue;
548
+ const hash = createHash("sha256").update(readFileSync(absolute)).digest("hex");
549
+ if (hash === entry.templateSha256) continue;
550
+ out.push(
551
+ finding(
552
+ AUDIT_CODES.managedEdited,
553
+ "warning",
554
+ "framework file was edited by hand: /ask-init refresh will not overwrite it — keep your additions outside the framework-owned text, or re-apply them after a refresh",
555
+ entry.path,
556
+ ),
557
+ );
558
+ }
559
+ return out;
560
+ }
561
+
562
+ /**
563
+ * Acceptance ledger hygiene. All of these are warnings except a corrupt stream:
564
+ * a ledger line that cannot be parsed means a lost event, which is an error.
565
+ */
566
+ function checkUat(facts: Facts): Finding[] {
567
+ if (!facts.state) return [];
568
+ const out: Finding[] = [];
569
+ const now = Date.now();
570
+ const records = listRecords(facts.root);
571
+
572
+ // Record hygiene is independent of the ledger: the canonical frame is what
573
+ // the tool writes, and the ledger is the only consumer either way.
574
+ const recentNonCanonical = records.filter(
575
+ (record) => !record.canonical && record.epochMs >= now - 14 * DAY_MS,
576
+ );
577
+ if (recentNonCanonical.length > 0) {
578
+ const first = recentNonCanonical[0];
579
+ out.push(
580
+ finding(
581
+ AUDIT_CODES.recordHeader,
582
+ "warning",
583
+ `${recentNonCanonical.length} recent change record(s) do not use the canonical minute header/name (first: ${first?.id}); write new ones with record_change`,
584
+ first?.path,
585
+ ),
586
+ );
587
+ }
588
+
589
+ if (!existsSync(join(facts.root, UAT_DIR))) {
590
+ out.push(
591
+ finding(
592
+ AUDIT_CODES.uatNotInstalled,
593
+ "info",
594
+ "acceptance ledger not installed (.agents/uat/): run /ask-init refresh",
595
+ UAT_DIR,
596
+ ),
597
+ );
598
+ return out;
599
+ }
600
+ if (!existsSync(join(facts.root, UAT_CONTRACT_FILE))) {
601
+ out.push(
602
+ finding(
603
+ AUDIT_CODES.uatNotInstalled,
604
+ "info",
605
+ "acceptance ledger contract is missing: run /ask-init refresh",
606
+ UAT_CONTRACT_FILE,
607
+ ),
608
+ );
609
+ }
610
+
611
+ const { events, skipped } = readEvents(ledgerPath(facts.root));
612
+ if (skipped > 0) {
613
+ out.push(
614
+ finding(
615
+ AUDIT_CODES.uatLedgerBroken,
616
+ "error",
617
+ `${skipped} line(s) in the acceptance ledger could not be parsed: fix or remove them (${UAT_LEDGER_FILE})`,
618
+ UAT_LEDGER_FILE,
619
+ ),
620
+ );
621
+ }
622
+
623
+ const state = deriveState(records, events);
624
+ const missing = state.items.flatMap((item) =>
625
+ item.missingReports.map((report) => `${item.id} → ${report}`),
626
+ );
627
+ if (missing.length > 0) {
628
+ out.push(
629
+ finding(
630
+ AUDIT_CODES.uatMissingReport,
631
+ "warning",
632
+ `acceptance item(s) point at change records that no longer exist: ${missing.slice(0, 5).join(", ")}${
633
+ missing.length > 5 ? " …" : ""
634
+ }`,
635
+ UAT_LEDGER_FILE,
636
+ ),
637
+ );
638
+ }
639
+
640
+ const stalePending = state.pending.filter(
641
+ (record) => record.epochMs > 0 && now - record.epochMs > 14 * DAY_MS,
642
+ );
643
+ if (stalePending.length > 0) {
644
+ out.push(
645
+ finding(
646
+ AUDIT_CODES.uatStaleCandidate,
647
+ "warning",
648
+ `${stalePending.length} change record(s) have been waiting for acceptance for over 14 days: run /ask-uat`,
649
+ UAT_LEDGER_FILE,
650
+ ),
651
+ );
652
+ }
653
+
654
+ const staleOpen = state.open.filter((item) => {
655
+ const created = Date.parse(item.createdAt);
656
+ return Number.isFinite(created) && now - created > 30 * DAY_MS;
657
+ });
658
+ if (staleOpen.length > 0) {
659
+ out.push(
660
+ finding(
661
+ AUDIT_CODES.uatStaleItem,
662
+ "warning",
663
+ `${staleOpen.length} acceptance item(s) have been open for over 30 days: verify or drop them`,
664
+ UAT_LEDGER_FILE,
665
+ ),
666
+ );
667
+ }
668
+
669
+ return out;
670
+ }
671
+
526
672
  export function audit(facts: Facts, options: AuditOptions = {}): Finding[] {
527
673
  const findings = [
528
674
  ...checkStructure(facts),
@@ -538,6 +684,8 @@ export function audit(facts: Facts, options: AuditOptions = {}): Finding[] {
538
684
  ...checkPlanDrift(facts),
539
685
  ...checkCoverage(facts, options.coveragePath),
540
686
  ...checkScaffold(facts),
687
+ ...checkFrameworkFiles(facts),
688
+ ...checkUat(facts),
541
689
  ];
542
690
  const rank: Record<Severity, number> = { error: 0, warning: 1, info: 2 };
543
691
  return findings.sort((a, b) => rank[a.severity] - rank[b.severity] || a.code.localeCompare(b.code));
@@ -412,6 +412,10 @@ export function parseState(raw: string): FrameworkState {
412
412
  path: String(entry.path ?? ""),
413
413
  sha256: String(entry.sha256 ?? ""),
414
414
  template: String(entry.template ?? ""),
415
+ templateSha256:
416
+ entry.template_sha256 === undefined
417
+ ? undefined
418
+ : String(entry.template_sha256),
415
419
  }))
416
420
  : [];
417
421
  const migrations = Array.isArray(data.migrations)
@@ -46,6 +46,7 @@ import {
46
46
  } from "./spec.js";
47
47
  import { FRAMEWORK_AUDIT_TOOL } from "./tool.js";
48
48
  import { confirmPlan, showReport } from "./ui.js";
49
+ import { describeRefresh, refreshFramework } from "./refresh.js";
49
50
  import type { ApplyResult, Plan } from "./types.js";
50
51
  import { registerAuditTool } from "./tool.js";
51
52
 
@@ -60,7 +61,7 @@ export interface InitOptions {
60
61
  }
61
62
 
62
63
  export interface ParsedInitArgs {
63
- readonly sub: "run" | "plan" | "check" | "roots" | "scrub" | "help";
64
+ readonly sub: "run" | "plan" | "check" | "roots" | "refresh" | "scrub" | "help";
64
65
  readonly dryRun: boolean;
65
66
  readonly deep: boolean;
66
67
  readonly yes: boolean;
@@ -74,6 +75,7 @@ const USAGE = [
74
75
  "/ask-init plan [--deep] show the plan only (writes nothing)",
75
76
  "/ask-init check audit the installed framework (read-only)",
76
77
  "/ask-init roots sync pi-add-dir roots into the framework state",
78
+ "/ask-init refresh refresh framework-owned files and the AGENTS.md workflow block",
77
79
  "/ask-init --dry-run report only, write nothing (same as plan)",
78
80
  "/ask-init --yes skip the confirmation panel",
79
81
  "/ask-init --lang zh|en rendering language for framework-generated files",
@@ -89,7 +91,14 @@ export function parseInitArgs(input: string): ParsedInitArgs {
89
91
  const unknown: string[] = [];
90
92
  for (let index = 0; index < tokens.length; index += 1) {
91
93
  const token = tokens[index];
92
- if (token === "plan" || token === "check" || token === "roots" || token === "scrub" || token === "help") {
94
+ if (
95
+ token === "plan" ||
96
+ token === "check" ||
97
+ token === "roots" ||
98
+ token === "refresh" ||
99
+ token === "scrub" ||
100
+ token === "help"
101
+ ) {
93
102
  sub = token;
94
103
  continue;
95
104
  }
@@ -466,6 +475,41 @@ function createRunHandler(
466
475
 
467
476
  const toolVersion = options.toolVersion ?? packageVersion();
468
477
  const now = options.now ?? new Date();
478
+
479
+ // Framework-owned text is refreshable without an upgrade recipe: managed
480
+ // files are rewritten only while the disk still equals the bytes we wrote,
481
+ // and AGENTS.md is touched only between the workflow markers.
482
+ if (parsed.sub === "refresh") {
483
+ try {
484
+ const result = refreshFramework(root, {
485
+ dryRun: parsed.dryRun,
486
+ now,
487
+ toolVersion,
488
+ });
489
+ ctx.ui.notify(
490
+ `ask-init refresh: ${describeRefresh(result)}${parsed.dryRun ? " — nothing was written." : ""}`,
491
+ result.skipped.length > 0 ? "warning" : "info",
492
+ );
493
+ if (result.skipped.length > 0) {
494
+ await showReport(
495
+ ctx,
496
+ "ask-init refresh — left untouched",
497
+ [
498
+ "These framework files were edited by hand, so refresh did not overwrite them.",
499
+ "Move your additions out of the managed file, or re-apply them after refreshing.",
500
+ "",
501
+ ...result.skipped.map((entry) => `- ${entry.path}: ${entry.reason}`),
502
+ ].join("\n"),
503
+ );
504
+ }
505
+ } catch (error) {
506
+ ctx.ui.notify(
507
+ `ask-init refresh: ${error instanceof Error ? error.message : String(error)}`,
508
+ "error",
509
+ );
510
+ }
511
+ return;
512
+ }
469
513
  const addedRoots = options.addedRoots ?? addedRootsFromBranch(ctx);
470
514
  const facts = detect(root, { addedRoots, lang: parsed.lang });
471
515
 
@@ -579,6 +623,7 @@ export function registerInit(pi0: ExtensionAPI, options: InitOptions = {}): void
579
623
  { value: "plan", label: "plan", description: "show the plan only (writes nothing)" },
580
624
  { value: "check", label: "check", description: "audit the installed framework" },
581
625
  { value: "roots", label: "roots", description: "sync pi-add-dir roots into state" },
626
+ { value: "refresh", label: "refresh", description: "refresh framework-owned files (safe, idempotent)" },
582
627
  { value: "--dry-run", label: "--dry-run", description: "report only, write nothing" },
583
628
  { value: "--deep", label: "--deep", description: "allow structural rewrites" },
584
629
  { value: "--yes", label: "--yes", description: "skip the confirmation panel" },
@@ -36,11 +36,13 @@ import {
36
36
  SPECS_DIR,
37
37
  STATE_FILE,
38
38
  STATE_GITIGNORE,
39
+ UAT_CONTRACT_FILE,
39
40
  type ProjectLanguage,
40
41
  } from "./spec.js";
41
42
  import { duplicateHeadings, largestSections, sectionsAfterAppendix, tombstones } from "./analyze.js";
42
43
  import { countBareRefs } from "./detect.js";
43
44
  import { indexBlock, rootsBlock } from "./render.js";
45
+ import { renderTemplate } from "./templates.js";
44
46
  import type {
45
47
  Action,
46
48
  CreateFileAction,
@@ -152,6 +154,7 @@ function buildTokens(facts: Facts, now: Date, created: ReadonlySet<string>): Tok
152
154
  ),
153
155
  index: indexBlock(facts, language, created),
154
156
  roots: rootsBlock(facts.roots, language),
157
+ workflowBlock: renderTemplate("workflow-block", {}, language),
155
158
  };
156
159
  }
157
160
 
@@ -692,6 +695,14 @@ export function buildPlan(facts: Facts, options: PlanOptions): Plan {
692
695
  "signpost for the hidden agent directory",
693
696
  );
694
697
  add(CONTRACT_FILE, "memory-readme", { frameworkVersion: String(FRAMEWORK_VERSION) }, "framework contract");
698
+ // The acceptance ledger is additive: a project without it is still a valid
699
+ // v1 framework (the audit reports I-UAT-01, not an error).
700
+ add(
701
+ UAT_CONTRACT_FILE,
702
+ "uat-readme",
703
+ { implementationsDir: IMPLEMENTATIONS_DIR },
704
+ "acceptance ledger contract",
705
+ );
695
706
  add(STATE_GITIGNORE, "state-gitignore", {}, "ignore runtime state");
696
707
  for (const spec of MEMORY_FILES) {
697
708
  if (!spec.core) continue;
@@ -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
+ });