@punks/cli 4.0.3 → 5.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 (116) hide show
  1. package/dist/BASELINE_CHANGELOG.md +25 -1
  2. package/dist/CHANGELOG.md +41 -0
  3. package/dist/baseline/scaffold-baseline/baseline.json +563 -5
  4. package/dist/baseline/scaffold-baseline/data/scripts/harness-projection/authoring.d.mts +23 -0
  5. package/dist/baseline/scaffold-baseline/data/scripts/harness-projection/authoring.mjs +84 -0
  6. package/dist/baseline/scaffold-baseline/data/scripts/harness-projection/authoring.test.ts +79 -0
  7. package/dist/baseline/scaffold-baseline/data/scripts/harness-projection/lint-feedback.test.ts +60 -28
  8. package/dist/baseline/scaffold-baseline/data/scripts/sync-subagents-validator.test.ts +59 -0
  9. package/dist/baseline/scaffold-baseline/data/scripts/sync-subagents.d.mts +1 -0
  10. package/dist/baseline/scaffold-baseline/data/scripts/sync-subagents.mjs +192 -16
  11. package/dist/baseline/scaffold-baseline/data/shared-agents.md +55 -0
  12. package/dist/baseline/scaffold-baseline/skills/agnostic/cli/hi-cli/references/post-command-flow.md +12 -0
  13. package/dist/baseline/scaffold-baseline/skills/agnostic/generic/handoff/SKILL.md +18 -5
  14. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/create-plan/SKILL.md +10 -2
  15. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/create-plan/references/plan-schema.md +28 -8
  16. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/create-plan/references/planner-task-graph.md +7 -3
  17. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/create-verification-skill/SKILL.md +66 -0
  18. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/create-verification-skill/references/upstream.md +20 -0
  19. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/implement-spec/SKILL.md +16 -41
  20. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/implement-spec/assets/IMPLEMENTATION-NOTES-TEMPLATE.md +14 -0
  21. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/implement-spec/references/architecture-conformance.md +10 -6
  22. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/implement-spec/references/lifecycle.md +47 -7
  23. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/implement-spec/references/parallel-orchestration.md +102 -134
  24. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/implement-spec/references/parallel-worker-brief.md +77 -67
  25. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/implement-spec/references/parallel.md +19 -39
  26. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/implement-spec/references/runtime-product-validation.md +27 -0
  27. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/swarm-planner/SKILL.md +27 -2
  28. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/update-verification-skill/SKILL.md +81 -0
  29. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/verify-behavior/SKILL.md +105 -65
  30. package/dist/baseline/scaffold-baseline/skills/agnostic/quality/autoreview/SKILL.md +17 -4
  31. package/dist/baseline/scaffold-baseline/skills/agnostic/quality/autoreview/scripts/autoreview +102 -5
  32. package/dist/baseline/scaffold-baseline/skills/agnostic/requirements/brainstorm/SKILL.md +11 -5
  33. package/dist/baseline/scaffold-baseline/skills/agnostic/subagents/swarm-planner/SKILL.md +27 -2
  34. package/dist/baseline/scaffold-baseline/skills/phases/delivery-phase/SKILL.md +12 -14
  35. package/dist/baseline/scaffold-baseline/skills/phases/delivery-phase/phases/backlog.md +4 -0
  36. package/dist/baseline/scaffold-baseline/skills/phases/delivery-phase/phases/closeout.md +12 -4
  37. package/dist/baseline/scaffold-baseline/skills/phases/delivery-phase/phases/debug.md +11 -5
  38. package/dist/baseline/scaffold-baseline/skills/phases/delivery-phase/phases/docs-ingest.md +4 -0
  39. package/dist/baseline/scaffold-baseline/skills/phases/delivery-phase/phases/handback.md +6 -2
  40. package/dist/baseline/scaffold-baseline/skills/phases/delivery-phase/phases/implement.md +12 -7
  41. package/dist/baseline/scaffold-baseline/skills/phases/delivery-phase/phases/plan.md +7 -1
  42. package/dist/baseline/scaffold-baseline/skills/phases/delivery-phase/phases/review.md +61 -22
  43. package/dist/baseline/scaffold-baseline/skills/phases/delivery-phase/phases/router.md +45 -91
  44. package/dist/baseline/scaffold-baseline/skills/phases/delivery-phase/phases/spec.md +4 -0
  45. package/dist/baseline/scaffold-baseline/skills/phases/delivery-phase/references/artifact-state.md +21 -9
  46. package/dist/baseline/scaffold-baseline/skills/phases/delivery-phase/references/context-continuity.md +109 -0
  47. package/dist/baseline/scaffold-baseline/skills/phases/delivery-phase/references/failure-continuity.md +27 -0
  48. package/dist/baseline/scaffold-baseline/skills/phases/delivery-phase/references/phase-handoff.md +32 -20
  49. package/dist/baseline/scaffold-baseline/skills/phases/docs-ingest-phase/SKILL.md +4 -0
  50. package/dist/baseline/scaffold-baseline/skills/phases/docs-ingest-phase/references/wiki-ingest.md +4 -0
  51. package/dist/baseline/scaffold-baseline/skills/phases/review-phase/phases/prepare-review.md +41 -8
  52. package/dist/baseline/scaffold-baseline/skills/phases/review-phase/phases/retain-report.md +13 -4
  53. package/dist/baseline/scaffold-baseline/skills/phases/review-phase/phases/router.md +1 -1
  54. package/dist/baseline/scaffold-baseline/skills/phases/review-phase/phases/run-review.md +24 -18
  55. package/dist/baseline/scaffold-baseline/skills/phases/review-phase/references/durable-report.md +40 -6
  56. package/dist/baseline/scaffold-baseline/skills/phases/review-phase/references/review-packet.md +72 -0
  57. package/dist/baseline/scaffold-baseline/skills/phases/review-phase/references/runtime-handoff.md +3 -0
  58. package/dist/baseline/scaffold-baseline/skills/phases/review-phase/references/state-graph.md +51 -42
  59. package/dist/baseline/scaffold-baseline/skills/phases/review-phase/scripts/review-contract.mjs +239 -4
  60. package/dist/baseline/scaffold-baseline.json +5 -5
  61. package/dist/baseline/scaffold-baseline.tgz +0 -0
  62. package/dist/data/scripts/harness-projection/authoring.d.mts +23 -0
  63. package/dist/data/scripts/harness-projection/authoring.mjs +84 -0
  64. package/dist/data/scripts/sync-subagents.d.mts +1 -0
  65. package/dist/data/scripts/sync-subagents.mjs +158 -15
  66. package/dist/data/shared-agents.md +2 -60
  67. package/dist/index.js +1417 -1407
  68. package/dist/skills/agnostic/cli/hi-cli/references/post-command-flow.md +12 -0
  69. package/dist/skills/agnostic/generic/handoff/SKILL.md +18 -5
  70. package/dist/skills/agnostic/planning/create-plan/SKILL.md +10 -2
  71. package/dist/skills/agnostic/planning/create-plan/references/plan-schema.md +28 -8
  72. package/dist/skills/agnostic/planning/create-plan/references/planner-task-graph.md +7 -3
  73. package/dist/skills/agnostic/planning/create-verification-skill/SKILL.md +66 -0
  74. package/dist/skills/agnostic/planning/create-verification-skill/references/upstream.md +20 -0
  75. package/dist/skills/agnostic/planning/implement-spec/SKILL.md +16 -41
  76. package/dist/skills/agnostic/planning/implement-spec/assets/IMPLEMENTATION-NOTES-TEMPLATE.md +14 -0
  77. package/dist/skills/agnostic/planning/implement-spec/references/architecture-conformance.md +10 -6
  78. package/dist/skills/agnostic/planning/implement-spec/references/lifecycle.md +47 -7
  79. package/dist/skills/agnostic/planning/implement-spec/references/parallel-orchestration.md +102 -134
  80. package/dist/skills/agnostic/planning/implement-spec/references/parallel-worker-brief.md +77 -67
  81. package/dist/skills/agnostic/planning/implement-spec/references/parallel.md +19 -39
  82. package/dist/skills/agnostic/planning/implement-spec/references/runtime-product-validation.md +27 -0
  83. package/dist/skills/agnostic/planning/swarm-planner/SKILL.md +27 -2
  84. package/dist/skills/agnostic/planning/update-verification-skill/SKILL.md +81 -0
  85. package/dist/skills/agnostic/planning/verify-behavior/SKILL.md +105 -65
  86. package/dist/skills/agnostic/quality/autoreview/SKILL.md +17 -4
  87. package/dist/skills/agnostic/quality/autoreview/scripts/autoreview +102 -5
  88. package/dist/skills/agnostic/requirements/brainstorm/SKILL.md +11 -5
  89. package/dist/skills/agnostic/subagents/swarm-planner/SKILL.md +27 -2
  90. package/dist/skills/phases/delivery-phase/SKILL.md +12 -14
  91. package/dist/skills/phases/delivery-phase/phases/backlog.md +4 -0
  92. package/dist/skills/phases/delivery-phase/phases/closeout.md +12 -4
  93. package/dist/skills/phases/delivery-phase/phases/debug.md +11 -5
  94. package/dist/skills/phases/delivery-phase/phases/docs-ingest.md +4 -0
  95. package/dist/skills/phases/delivery-phase/phases/handback.md +6 -2
  96. package/dist/skills/phases/delivery-phase/phases/implement.md +12 -7
  97. package/dist/skills/phases/delivery-phase/phases/plan.md +7 -1
  98. package/dist/skills/phases/delivery-phase/phases/review.md +61 -22
  99. package/dist/skills/phases/delivery-phase/phases/router.md +45 -91
  100. package/dist/skills/phases/delivery-phase/phases/spec.md +4 -0
  101. package/dist/skills/phases/delivery-phase/references/artifact-state.md +21 -9
  102. package/dist/skills/phases/delivery-phase/references/context-continuity.md +109 -0
  103. package/dist/skills/phases/delivery-phase/references/failure-continuity.md +27 -0
  104. package/dist/skills/phases/delivery-phase/references/phase-handoff.md +32 -20
  105. package/dist/skills/phases/docs-ingest-phase/SKILL.md +4 -0
  106. package/dist/skills/phases/docs-ingest-phase/references/wiki-ingest.md +4 -0
  107. package/dist/skills/phases/review-phase/phases/prepare-review.md +40 -8
  108. package/dist/skills/phases/review-phase/phases/retain-report.md +13 -4
  109. package/dist/skills/phases/review-phase/phases/router.md +1 -1
  110. package/dist/skills/phases/review-phase/phases/run-review.md +24 -18
  111. package/dist/skills/phases/review-phase/references/durable-report.md +40 -6
  112. package/dist/skills/phases/review-phase/references/review-packet.md +72 -0
  113. package/dist/skills/phases/review-phase/references/runtime-handoff.md +3 -0
  114. package/dist/skills/phases/review-phase/references/state-graph.md +21 -12
  115. package/dist/skills/phases/review-phase/scripts/review-contract.mjs +137 -4
  116. package/package.json +4 -1
@@ -0,0 +1,84 @@
1
+ import { createHash } from "node:crypto";
2
+
3
+ export const readScopedAuthoringProofs = (receipt) => {
4
+ const proofs = receipt?.scopedAuthoring;
5
+ if (!Array.isArray(proofs)) {
6
+ return [];
7
+ }
8
+ const scopes = new Set();
9
+ for (const proof of proofs) {
10
+ if (
11
+ proof === null ||
12
+ typeof proof !== "object" ||
13
+ typeof proof.scopeId !== "string" ||
14
+ proof.scopeId.length === 0 ||
15
+ typeof proof.inputIdentity !== "string" ||
16
+ !/^[a-f0-9]{64}$/u.test(proof.inputIdentity) ||
17
+ proof.status !== "verified" ||
18
+ scopes.has(proof.scopeId)
19
+ ) {
20
+ return [];
21
+ }
22
+ scopes.add(proof.scopeId);
23
+ }
24
+ return proofs;
25
+ };
26
+
27
+ export const scopeAuthoringIdentity = (scope) =>
28
+ JSON.stringify(
29
+ scope.authoring === undefined
30
+ ? { compatibility: "unknown", scopeId: scope.id }
31
+ : {
32
+ contracts: [...scope.authoring.contracts]
33
+ .toSorted((left, right) => left.id.localeCompare(right.id))
34
+ .map(({ id, authoringRevision, activationRevision }) => ({
35
+ activationRevision,
36
+ authoringRevision,
37
+ id,
38
+ })),
39
+ kind: scope.authoring.kind,
40
+ missingContracts: [...new Set(scope.authoring.missingContracts)].toSorted(),
41
+ path: scope.authoring.path,
42
+ },
43
+ );
44
+
45
+ export const assessScopedAuthoring = ({ contextPlan, proofs }) =>
46
+ contextPlan.scopes.flatMap((scope) => {
47
+ if (
48
+ scope.id === "shared" ||
49
+ scope.id === ".agents" ||
50
+ !scope.contributions.some(({ kind }) => kind === "scoped-prompt")
51
+ ) {
52
+ return [];
53
+ }
54
+ const inputIdentity = createHash("sha256").update(scopeAuthoringIdentity(scope)).digest("hex");
55
+ const proof = proofs.find((entry) => entry.scopeId === scope.id);
56
+ const compatible =
57
+ scope.authoring !== undefined && scope.authoring.missingContracts.length === 0;
58
+ if (compatible && proof?.status === "verified" && proof.inputIdentity === inputIdentity) {
59
+ return [];
60
+ }
61
+ let trigger;
62
+ if (compatible) {
63
+ trigger = proof === undefined ? "unverified" : "inputs-changed";
64
+ } else {
65
+ trigger = "compatibility-unknown";
66
+ }
67
+ const allowedAgentIds = scope.contributions
68
+ .filter(({ kind }) => kind === "subagent-template")
69
+ .map(({ identity }) => identity.id)
70
+ .toSorted();
71
+ return [
72
+ {
73
+ allowedAgentIds,
74
+ allowedOutputs: [
75
+ scope.id === "root" ? "AGENTS.md" : `${scope.id}/AGENTS.md`,
76
+ ...(allowedAgentIds.length === 0 ? [] : [".agents/subagents/manifest.mjs"]),
77
+ ],
78
+ completionEvidence: "validated-authored-output-and-native-projection",
79
+ inputIdentity,
80
+ scopeId: scope.id,
81
+ trigger,
82
+ },
83
+ ];
84
+ });
@@ -0,0 +1,79 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import type { ContextPlan } from "@punks/scaffold/context-plan";
3
+ import { assessScopedAuthoring } from "./authoring.mjs";
4
+
5
+ const plan: ContextPlan = {
6
+ scopes: [
7
+ {
8
+ authoring: {
9
+ contracts: [{ activationRevision: "1", authoringRevision: "1", id: "generated-authoring" }],
10
+ kind: "workspace",
11
+ missingContracts: [],
12
+ path: "apps/api",
13
+ },
14
+ contributions: [
15
+ {
16
+ compatibility: [],
17
+ identity: { id: "apps/api:workspace", version: "1" },
18
+ kind: "scoped-prompt",
19
+ order: 0,
20
+ provenance: { revision: "1", source: "project" },
21
+ references: [],
22
+ },
23
+ ],
24
+ id: "apps/api",
25
+ packs: [],
26
+ },
27
+ ],
28
+ version: "1",
29
+ };
30
+
31
+ describe("bounded scoped authoring", () => {
32
+ it("emits one input-bound action and suppresses it only after current validated proof", () => {
33
+ const pending = assessScopedAuthoring({ contextPlan: plan, proofs: [] });
34
+ expect(pending).toHaveLength(1);
35
+ expect(pending[0]).toMatchObject({
36
+ allowedOutputs: ["apps/api/AGENTS.md"],
37
+ completionEvidence: "validated-authored-output-and-native-projection",
38
+ scopeId: "apps/api",
39
+ trigger: "unverified",
40
+ });
41
+ expect(pending[0]?.inputIdentity).toMatch(/^[a-f0-9]{64}$/u);
42
+ expect(
43
+ assessScopedAuthoring({
44
+ contextPlan: plan,
45
+ proofs: [
46
+ {
47
+ inputIdentity: pending[0]?.inputIdentity ?? "",
48
+ scopeId: "apps/api",
49
+ status: "verified",
50
+ },
51
+ ],
52
+ }),
53
+ ).toStrictEqual([]);
54
+ });
55
+
56
+ it("bounds agent authoring to the planned roles while preserving custom roles", () => {
57
+ const agentPlan: ContextPlan = {
58
+ ...plan,
59
+ scopes: plan.scopes.map((scope) => ({
60
+ ...scope,
61
+ contributions: [
62
+ ...scope.contributions,
63
+ {
64
+ compatibility: [],
65
+ identity: { id: "api-owner", version: "1" },
66
+ kind: "subagent-template",
67
+ order: 1,
68
+ provenance: { revision: "1", source: "project" },
69
+ references: [],
70
+ },
71
+ ],
72
+ })),
73
+ };
74
+ expect(assessScopedAuthoring({ contextPlan: agentPlan, proofs: [] })[0]).toMatchObject({
75
+ allowedAgentIds: ["api-owner"],
76
+ allowedOutputs: ["apps/api/AGENTS.md", ".agents/subagents/manifest.mjs"],
77
+ });
78
+ });
79
+ });
@@ -1,4 +1,5 @@
1
1
  import { describe, expect, it } from "vitest";
2
+ import * as Schema from "effect/Schema";
2
3
 
3
4
  import { testHooks } from "../../hooks/format-edited-file.mjs";
4
5
  import { claudeAdapter } from "./adapters/claude.mjs";
@@ -6,6 +7,30 @@ import { codexAdapter } from "./adapters/codex.mjs";
6
7
  import { cursorAdapter } from "./adapters/cursor.mjs";
7
8
  import { openCodeAdapter } from "./adapters/opencode.mjs";
8
9
 
10
+ type JsonRecord = Readonly<Record<string, unknown>>;
11
+ type ProviderLintSummary = Parameters<typeof testHooks.renderProviderFeedback>[1];
12
+
13
+ const isRecord = (value: unknown): value is JsonRecord =>
14
+ typeof value === "object" && value !== null && !Array.isArray(value);
15
+
16
+ const record = (value: unknown): JsonRecord => {
17
+ if (!isRecord(value)) {
18
+ throw new TypeError("Expected JSON object");
19
+ }
20
+ return value;
21
+ };
22
+
23
+ const stringField = (value: JsonRecord, field: string): string => {
24
+ const fieldValue = value[field];
25
+ if (typeof fieldValue !== "string") {
26
+ throw new TypeError(`Expected ${field} to be a string`);
27
+ }
28
+ return fieldValue;
29
+ };
30
+
31
+ const renderProviderFeedback = (provider: string, summary: ProviderLintSummary): unknown =>
32
+ Schema.decodeUnknownSync(Schema.Unknown)(testHooks.renderProviderFeedback(provider, summary));
33
+
9
34
  const finding = {
10
35
  column: 1,
11
36
  documentation: "https://oxc.rs/docs/guide/usage/linter/rules/no-console",
@@ -52,35 +77,41 @@ const hookAction = (adapter: typeof codexAdapter) => {
52
77
  throw new Error("lifecycle-hook capability is missing");
53
78
  }
54
79
  const projected = adapter.project({ capability, contribution, scopeId: "root" });
55
- if (!Array.isArray(projected)) {
56
- throw new TypeError("formatter hook was not projected");
80
+ if (!Array.isArray(projected) || projected.some((entry) => !isRecord(entry))) {
81
+ throw new TypeError("formatter hook was not projected as an array of records");
57
82
  }
58
- return projected;
83
+ return projected.filter(isRecord);
59
84
  };
60
85
 
61
86
  describe("provider-native lint feedback", () => {
62
87
  it("projects actionable findings through each provider's response contract", () => {
63
- const codex = testHooks.renderProviderFeedback("codex", summary);
64
- expect(codex).toMatchObject({
88
+ const codex = record(renderProviderFeedback("codex", summary));
89
+ const codexHookSpecificOutput = record(codex.hookSpecificOutput);
90
+ expect({
91
+ contextIncludesLocation: stringField(codexHookSpecificOutput, "additionalContext").includes(
92
+ "apps/demo/src/bad.ts:2:1",
93
+ ),
94
+ decision: codex.decision,
95
+ hookEventName: stringField(codexHookSpecificOutput, "hookEventName"),
96
+ }).toStrictEqual({
97
+ contextIncludesLocation: true,
65
98
  decision: "block",
66
- hookSpecificOutput: {
67
- additionalContext: expect.stringContaining("apps/demo/src/bad.ts:2:1"),
68
- hookEventName: "PostToolUse",
69
- },
99
+ hookEventName: "PostToolUse",
70
100
  });
71
101
 
72
- const claude = testHooks.renderProviderFeedback("claude", summary);
73
- expect(claude).toMatchObject({
74
- hookSpecificOutput: {
75
- additionalContext: expect.stringContaining("(error) [no-console]"),
76
- hookEventName: "PostToolUse",
77
- },
78
- });
102
+ const claude = record(renderProviderFeedback("claude", summary));
103
+ const claudeHookSpecificOutput = record(claude.hookSpecificOutput);
104
+ expect({
105
+ contextIncludesRule: stringField(claudeHookSpecificOutput, "additionalContext").includes(
106
+ "(error) [no-console]",
107
+ ),
108
+ hookEventName: stringField(claudeHookSpecificOutput, "hookEventName"),
109
+ }).toStrictEqual({ contextIncludesRule: true, hookEventName: "PostToolUse" });
79
110
 
80
- const cursor = testHooks.renderProviderFeedback("cursor", summary);
81
- expect(cursor).toMatchObject({ user_message: expect.stringContaining("Unexpected console") });
111
+ const cursor = record(renderProviderFeedback("cursor", summary));
112
+ expect(stringField(cursor, "user_message")).toContain("Unexpected console");
82
113
 
83
- const opencode = testHooks.renderProviderFeedback("opencode", summary);
114
+ const opencode = record(renderProviderFeedback("opencode", summary));
84
115
  expect(opencode).toMatchObject({
85
116
  diagnostics: [expect.objectContaining({ file: finding.file, rule: finding.rule })],
86
117
  event: "lint-feedback",
@@ -89,17 +120,18 @@ describe("provider-native lint feedback", () => {
89
120
  });
90
121
 
91
122
  it("stays silent for clean verification and reports exhaustion without a repair request", () => {
92
- expect(testHooks.renderProviderFeedback("codex", cleanSummary)).toBeNull();
123
+ expect(renderProviderFeedback("codex", cleanSummary)).toBeNull();
93
124
 
94
- const exhausted = testHooks.renderProviderFeedback("codex", {
95
- ...summary,
96
- exhausted: true,
97
- });
98
- expect(exhausted).toMatchObject({
99
- hookSpecificOutput: { additionalContext: expect.stringContaining("exhausted") },
100
- });
125
+ const exhausted = record(
126
+ renderProviderFeedback("codex", {
127
+ ...summary,
128
+ exhausted: true,
129
+ }),
130
+ );
131
+ const hookSpecificOutput = record(exhausted.hookSpecificOutput);
132
+ expect(stringField(hookSpecificOutput, "additionalContext")).toContain("exhausted");
101
133
  expect("decision" in exhausted).toBeFalsy();
102
- expect(String(exhausted.hookSpecificOutput.additionalContext).toLowerCase()).not.toContain(
134
+ expect(stringField(hookSpecificOutput, "additionalContext").toLowerCase()).not.toContain(
103
135
  "fix these",
104
136
  );
105
137
  });
@@ -0,0 +1,59 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { validateCanonicalContextPlan } from "./sync-subagents.mjs";
3
+
4
+ interface CommitGateContribution {
5
+ compatibility: readonly unknown[];
6
+ contract: { formatCheck: string; lint: string };
7
+ identity: { id: string; version: string };
8
+ kind: "commit-gate";
9
+ order: number;
10
+ provenance: { revision: string; source: string };
11
+ references: readonly string[];
12
+ }
13
+
14
+ const contribution: CommitGateContribution = {
15
+ compatibility: [],
16
+ contract: { formatCheck: "bun run check:format", lint: "bun run lint" },
17
+ identity: { id: "verification", version: "1" },
18
+ kind: "commit-gate",
19
+ order: 0,
20
+ provenance: { revision: "1", source: "project" },
21
+ references: [],
22
+ };
23
+
24
+ const plan = (entry: object = contribution) => ({
25
+ scopes: [{ contributions: [entry], id: "root", packs: [] }],
26
+ version: "1",
27
+ });
28
+
29
+ type MutateContribution = (entry: CommitGateContribution) => Record<string, unknown>;
30
+
31
+ const invalidCases: readonly [string, MutateContribution][] = [
32
+ [
33
+ "missing contract",
34
+ (entry) => {
35
+ const { contract: _contract, ...invalid } = entry;
36
+ return invalid;
37
+ },
38
+ ],
39
+ ["empty lint", (entry) => ({ ...entry, contract: { ...entry.contract, lint: "" } })],
40
+ [
41
+ "empty formatCheck",
42
+ (entry) => ({ ...entry, contract: { ...entry.contract, formatCheck: "" } }),
43
+ ],
44
+ [
45
+ "extra contract field",
46
+ (entry) => ({ ...entry, contract: { ...entry.contract, extra: "unexpected" } }),
47
+ ],
48
+ ];
49
+
50
+ describe("sync-subagents context-plan validator", () => {
51
+ it("accepts commit-gate contracts with both command strings", () => {
52
+ expect(validateCanonicalContextPlan(plan())).toBeUndefined();
53
+ });
54
+
55
+ it.each(invalidCases)("rejects %s", (_label, mutate) => {
56
+ const invalid = mutate(contribution);
57
+ expect(validateCanonicalContextPlan(plan(invalid))).toMatch(/contract|fields/iu);
58
+ });
59
+ });
@@ -0,0 +1 @@
1
+ export declare const validateCanonicalContextPlan: (contextPlan: unknown) => string | undefined;
@@ -12,6 +12,10 @@ import { cursorAdapter } from "./harness-projection/adapters/cursor.mjs";
12
12
  import { openCodeAdapter } from "./harness-projection/adapters/opencode.mjs";
13
13
  import { applyProjection } from "./harness-projection/apply.mjs";
14
14
  import { project } from "./harness-projection/core.mjs";
15
+ import {
16
+ assessScopedAuthoring,
17
+ readScopedAuthoringProofs,
18
+ } from "./harness-projection/authoring.mjs";
15
19
 
16
20
  const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
17
21
  const sharedAgentsPath = path.join(repoRoot, ".agents/AGENTS.md");
@@ -2878,6 +2882,7 @@ const contributionKinds = new Set([
2878
2882
  "lifecycle-hook",
2879
2883
  "tool-configuration",
2880
2884
  "subagent-template",
2885
+ "commit-gate",
2881
2886
  ]);
2882
2887
 
2883
2888
  const identityIssue = (identity) =>
@@ -2905,17 +2910,19 @@ const compatibilityIssue = (compatibility) =>
2905
2910
  ? undefined
2906
2911
  : "Context contribution compatibility is invalid";
2907
2912
 
2913
+ const commitGateContractIssue = (contract) =>
2914
+ exactKeys(contract, ["lint", "formatCheck"]) &&
2915
+ isNonEmptyString(contract.lint) &&
2916
+ isNonEmptyString(contract.formatCheck)
2917
+ ? undefined
2918
+ : "Commit-gate contract must contain non-empty lint and formatCheck strings";
2919
+
2908
2920
  const contributionIssue = (contribution) => {
2909
- if (
2910
- !exactKeys(contribution, [
2911
- "kind",
2912
- "identity",
2913
- "provenance",
2914
- "compatibility",
2915
- "references",
2916
- "order",
2917
- ])
2918
- ) {
2921
+ const expectedKeys =
2922
+ contribution?.kind === "commit-gate"
2923
+ ? ["kind", "identity", "provenance", "compatibility", "references", "order", "contract"]
2924
+ : ["kind", "identity", "provenance", "compatibility", "references", "order"];
2925
+ if (!exactKeys(contribution, expectedKeys)) {
2919
2926
  return "Context contribution fields are invalid";
2920
2927
  }
2921
2928
  return (
@@ -2925,6 +2932,9 @@ const contributionIssue = (contribution) => {
2925
2932
  identityIssue(contribution.identity) ??
2926
2933
  provenanceIssue(contribution.provenance) ??
2927
2934
  compatibilityIssue(contribution.compatibility) ??
2935
+ (contribution.kind === "commit-gate"
2936
+ ? commitGateContractIssue(contribution.contract)
2937
+ : undefined) ??
2928
2938
  (!Array.isArray(contribution.references) || !contribution.references.every(isNonEmptyString)
2929
2939
  ? "Context contribution references are invalid"
2930
2940
  : undefined) ??
@@ -2933,9 +2943,33 @@ const contributionIssue = (contribution) => {
2933
2943
  };
2934
2944
 
2935
2945
  const scopeIssue = (scope) => {
2936
- if (!exactKeys(scope, ["id", "packs", "contributions"]) || !isNonEmptyString(scope.id)) {
2946
+ const expectedKeys =
2947
+ scope?.authoring === undefined
2948
+ ? ["id", "packs", "contributions"]
2949
+ : ["id", "packs", "contributions", "authoring"];
2950
+ if (!exactKeys(scope, expectedKeys) || !isNonEmptyString(scope.id)) {
2937
2951
  return "Context scope fields are invalid";
2938
2952
  }
2953
+ if (scope.authoring !== undefined) {
2954
+ const identity = scope.authoring;
2955
+ if (
2956
+ !exactKeys(identity, ["path", "kind", "contracts", "missingContracts"]) ||
2957
+ !isNonEmptyString(identity.path) ||
2958
+ !isNonEmptyString(identity.kind) ||
2959
+ !Array.isArray(identity.contracts) ||
2960
+ !identity.contracts.every(
2961
+ (contract) =>
2962
+ exactKeys(contract, ["id", "authoringRevision", "activationRevision"]) &&
2963
+ isNonEmptyString(contract.id) &&
2964
+ isNonEmptyString(contract.authoringRevision) &&
2965
+ isNonEmptyString(contract.activationRevision),
2966
+ ) ||
2967
+ !Array.isArray(identity.missingContracts) ||
2968
+ !identity.missingContracts.every(isNonEmptyString)
2969
+ ) {
2970
+ return `Context scope ${scope.id} authoring identity is invalid`;
2971
+ }
2972
+ }
2939
2973
  if (
2940
2974
  !Array.isArray(scope.packs) ||
2941
2975
  !scope.packs.every(
@@ -3002,18 +3036,80 @@ function subagentManifestIssue(contextPlan) {
3002
3036
  const canonicalContextIssue = (contextPlan) =>
3003
3037
  contextPlanIssue(contextPlan) ?? subagentManifestIssue(contextPlan);
3004
3038
 
3039
+ export const validateCanonicalContextPlan = (contextPlan) => canonicalContextIssue(contextPlan);
3040
+
3005
3041
  const contextPlanVersion = (contextPlan) =>
3006
3042
  isObject(contextPlan) && typeof contextPlan.version === "string"
3007
3043
  ? contextPlan.version
3008
3044
  : "unknown";
3009
3045
 
3010
- async function main({ publicationLock } = {}) {
3046
+ const parseAuthoringCompletion = (args) => {
3047
+ if (args.length === 0) return undefined;
3048
+ if (args.length !== 3 || args[0] !== "--complete-authoring" || !/^[a-f0-9]{64}$/.test(args[2])) {
3049
+ throw new Error("Expected --complete-authoring <scope> <current input identity>.");
3050
+ }
3051
+ return { scopeId: args[1], inputIdentity: args[2] };
3052
+ };
3053
+
3054
+ async function readAuthoredScope(action) {
3055
+ const promptFile = action.allowedOutputs[0];
3056
+ const bytes = await readConfinedRegularFile(resolveActionPath(promptFile, "authored output"));
3057
+ if (bytes === null || bytes.toString("utf8").trim().length === 0) {
3058
+ throw new Error(`Authored output is missing or empty: ${promptFile}`);
3059
+ }
3060
+ return bytes;
3061
+ }
3062
+
3063
+ async function verifyAuthoredProjection(action, projections, application) {
3064
+ await readAuthoredScope(action);
3065
+ for (const projection of projections) {
3066
+ const relevant = (entry) =>
3067
+ entry.trace?.scopeId === action.scopeId &&
3068
+ ["scoped-prompt", "subagent-template"].includes(entry.trace?.kind);
3069
+ if ([...projection.failures, ...projection.omissions].some(relevant)) {
3070
+ throw new Error(`Scoped authoring projection is incomplete: ${action.scopeId}`);
3071
+ }
3072
+ for (const mirror of projection.actions.filter(
3073
+ (entry) => relevant(entry) && entry.operation === "mirror" && entry.source !== entry.target,
3074
+ )) {
3075
+ const sourcePath = resolveActionPath(mirror.source, "source");
3076
+ const targetPath = resolveActionPath(mirror.target, "target");
3077
+ const stat = await lstat(targetPath);
3078
+ if (stat.isSymbolicLink()) {
3079
+ if ((await readlink(targetPath)) !== path.relative(path.dirname(targetPath), sourcePath)) {
3080
+ throw new Error(`Scoped authoring mirror diverges: ${mirror.target}`);
3081
+ }
3082
+ } else {
3083
+ const source = await readConfinedRegularFile(sourcePath);
3084
+ const target = await readConfinedRegularFile(targetPath);
3085
+ if (source === null || target === null || !source.equals(target)) {
3086
+ throw new Error(`Scoped authoring mirror diverges: ${mirror.target}`);
3087
+ }
3088
+ }
3089
+ }
3090
+ }
3091
+ for (const agentId of action.allowedAgentIds) {
3092
+ for (const [adapterId, surface] of Object.entries(harnessAgentSurface)) {
3093
+ const expected = application.rendered[adapterId]?.[agentId];
3094
+ const actual = await readConfinedRegularFile(
3095
+ path.join(surface.directory, `${agentId}.${surface.extension}`),
3096
+ );
3097
+ if (typeof expected !== "string" || actual?.toString("utf8") !== expected) {
3098
+ throw new Error(`Scoped authoring native agent diverges: ${adapterId}:${agentId}`);
3099
+ }
3100
+ }
3101
+ }
3102
+ }
3103
+
3104
+ async function main({ publicationLock, authoringCompletion } = {}) {
3011
3105
  operationRepoRootIdentity = await captureRepoRootIdentity("synchronize scaffold output");
3012
3106
  const manifestPreflight = await preflightScaffoldManifest();
3013
3107
  await assertConfinedRegularFile(projectionReceiptPath);
3014
3108
  const previousReceiptBytes = await readConfinedRegularFile(projectionReceiptPath);
3109
+ let previousAuthoringProofs = [];
3015
3110
  try {
3016
3111
  const previousReceipt = JSON.parse(previousReceiptBytes?.toString("utf8") ?? "null");
3112
+ previousAuthoringProofs = readScopedAuthoringProofs(previousReceipt);
3017
3113
  previousCopyFallbacks = Array.isArray(previousReceipt.copyFallbacks)
3018
3114
  ? previousReceipt.copyFallbacks.filter(
3019
3115
  (copy) =>
@@ -3028,6 +3124,8 @@ async function main({ publicationLock } = {}) {
3028
3124
  }
3029
3125
  const loadedContextPlan = await readContextPlan();
3030
3126
  const loadedProjectionPlan = await readProjectionPlan();
3127
+ const authoringManifestPath = path.join(repoRoot, ".agents/subagents/manifest.mjs");
3128
+ const authoringManifestBytes = await readConfinedRegularFile(authoringManifestPath);
3031
3129
  const application = await prepareHarnessApplication();
3032
3130
  const renderedOutputSha256 = semanticJsonHash({
3033
3131
  availableHooks: application.availableHooks,
@@ -3037,10 +3135,33 @@ async function main({ publicationLock } = {}) {
3037
3135
  try {
3038
3136
  await assertScaffoldManifestPreflight(manifestPreflight);
3039
3137
  if (!loadedContextPlan.exists && !loadedProjectionPlan.exists) {
3138
+ if (authoringCompletion !== undefined) {
3139
+ throw new Error("Scoped authoring completion requires a canonical context plan.");
3140
+ }
3040
3141
  await materializeLegacyHarnesses(application);
3041
3142
  return;
3042
3143
  }
3043
3144
  const contextPlan = loadedContextPlan.value;
3145
+ const authoringActions =
3146
+ contextPlanIssue(contextPlan) === undefined
3147
+ ? assessScopedAuthoring({ contextPlan, proofs: [] })
3148
+ : [];
3149
+ const completionAction =
3150
+ authoringCompletion === undefined
3151
+ ? undefined
3152
+ : authoringActions.find(
3153
+ (action) =>
3154
+ action.scopeId === authoringCompletion.scopeId &&
3155
+ action.inputIdentity === authoringCompletion.inputIdentity,
3156
+ );
3157
+ if (authoringCompletion !== undefined) {
3158
+ if (completionAction === undefined || completionAction.trigger === "compatibility-unknown") {
3159
+ throw new Error("Scoped authoring completion does not match a supported current input.");
3160
+ }
3161
+ const issue = canonicalContextIssue(contextPlan);
3162
+ if (issue !== undefined) throw new Error(issue);
3163
+ await readAuthoredScope(completionAction);
3164
+ }
3044
3165
  const suppliedProjectionPlan = loadedProjectionPlan.exists
3045
3166
  ? validateProjectionPlan({ plan: loadedProjectionPlan.value, contextPlan })
3046
3167
  : undefined;
@@ -3088,12 +3209,62 @@ async function main({ publicationLock } = {}) {
3088
3209
  );
3089
3210
  }
3090
3211
 
3212
+ const scopedAuthoring = previousAuthoringProofs.filter(
3213
+ (proof) =>
3214
+ !authoringActions.some(
3215
+ (action) =>
3216
+ action.scopeId === proof.scopeId &&
3217
+ (action === completionAction || action.inputIdentity === proof.inputIdentity),
3218
+ ),
3219
+ );
3220
+ for (const action of authoringActions) {
3221
+ if (action.trigger === "compatibility-unknown") continue;
3222
+ const prior = previousAuthoringProofs.find(
3223
+ (proof) => proof.scopeId === action.scopeId && proof.inputIdentity === action.inputIdentity,
3224
+ );
3225
+ if (action !== completionAction && prior === undefined) continue;
3226
+ try {
3227
+ await verifyAuthoredProjection(action, applied, application);
3228
+ scopedAuthoring.push({
3229
+ scopeId: action.scopeId,
3230
+ inputIdentity: action.inputIdentity,
3231
+ status: "verified",
3232
+ });
3233
+ } catch (error) {
3234
+ if (action === completionAction) throw error;
3235
+ }
3236
+ }
3237
+ if (scopedAuthoring.length > 0) {
3238
+ const currentApplication = await prepareHarnessApplication();
3239
+ const currentManifest = await readConfinedRegularFile(authoringManifestPath);
3240
+ if (
3241
+ authoringManifestBytes === null ||
3242
+ currentManifest === null ||
3243
+ !authoringManifestBytes.equals(currentManifest) ||
3244
+ semanticJsonHash({
3245
+ availableHooks: currentApplication.availableHooks,
3246
+ rendered: currentApplication.rendered,
3247
+ }) !== renderedOutputSha256
3248
+ ) {
3249
+ throw new Error("Scoped authoring inputs changed during projection; retry completion.");
3250
+ }
3251
+ }
3252
+ const currentContext = await readContextPlan();
3253
+ if (
3254
+ !currentContext.exists ||
3255
+ semanticJsonHash(currentContext.value) !== semanticJsonHash(contextPlan)
3256
+ ) {
3257
+ throw new Error("Scoped authoring inputs changed during projection; retry completion.");
3258
+ }
3091
3259
  const receipt = {
3092
3260
  version: "1",
3093
3261
  contextPlanVersion: contextPlanVersion(contextPlan),
3094
3262
  renderedOutputSha256,
3095
3263
  status: receiptStatus(applied),
3096
3264
  projections: applied,
3265
+ scopedAuthoring: scopedAuthoring.toSorted((left, right) =>
3266
+ left.scopeId.localeCompare(right.scopeId),
3267
+ ),
3097
3268
  copyFallbacks: [...currentCopyFallbacks.values()].toSorted((left, right) =>
3098
3269
  copyFallbackKey(left).localeCompare(copyFallbackKey(right)),
3099
3270
  ),
@@ -3109,8 +3280,13 @@ async function main({ publicationLock } = {}) {
3109
3280
  }
3110
3281
  }
3111
3282
 
3112
- try {
3113
- await main();
3114
- } finally {
3115
- await closeMutationWorkers();
3283
+ const entrypointPath = process.argv[1] === undefined ? null : await realpath(process.argv[1]);
3284
+ const modulePath = await realpath(fileURLToPath(import.meta.url));
3285
+
3286
+ if (entrypointPath === modulePath) {
3287
+ try {
3288
+ await main({ authoringCompletion: parseAuthoringCompletion(process.argv.slice(2)) });
3289
+ } finally {
3290
+ await closeMutationWorkers();
3291
+ }
3116
3292
  }