@punks/cli 2.6.1 → 3.0.0-beta.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 (102) hide show
  1. package/AGENTS.md +1 -1
  2. package/README.md +42 -24
  3. package/dist/BASELINE_CHANGELOG.md +57 -0
  4. package/dist/CHANGELOG.md +80 -0
  5. package/dist/data/scripts/harness-projection/adapters/claude.d.mts +3 -0
  6. package/dist/data/scripts/harness-projection/adapters/claude.mjs +124 -0
  7. package/dist/data/scripts/harness-projection/adapters/codex.d.mts +3 -0
  8. package/dist/data/scripts/harness-projection/adapters/codex.mjs +137 -0
  9. package/dist/data/scripts/harness-projection/adapters/cursor.d.mts +5 -0
  10. package/dist/data/scripts/harness-projection/adapters/cursor.mjs +106 -0
  11. package/dist/data/scripts/harness-projection/adapters/opencode.d.mts +5 -0
  12. package/dist/data/scripts/harness-projection/adapters/opencode.mjs +100 -0
  13. package/dist/data/scripts/harness-projection/apply.d.mts +12 -0
  14. package/dist/data/scripts/harness-projection/apply.mjs +96 -0
  15. package/dist/data/scripts/harness-projection/core.d.mts +8 -0
  16. package/dist/data/scripts/harness-projection/core.mjs +239 -0
  17. package/dist/data/scripts/harness-projection/test-fixtures/application-context-plan.json +27 -0
  18. package/dist/data/scripts/harness-projection/test-fixtures/claude/actions.json +109 -0
  19. package/dist/data/scripts/harness-projection/test-fixtures/claude/context-plan.json +150 -0
  20. package/dist/data/scripts/harness-projection/test-fixtures/claude/matrix.json +23 -0
  21. package/dist/data/scripts/harness-projection/test-fixtures/claude/traces.json +15 -0
  22. package/dist/data/scripts/harness-projection/test-fixtures/codex/actions.json +124 -0
  23. package/dist/data/scripts/harness-projection/test-fixtures/codex/context-plan.json +150 -0
  24. package/dist/data/scripts/harness-projection/test-fixtures/codex/matrix.json +23 -0
  25. package/dist/data/scripts/harness-projection/test-fixtures/codex/traces.json +15 -0
  26. package/dist/data/scripts/harness-projection/test-fixtures/cursor/compiler-input.json +93 -0
  27. package/dist/data/scripts/harness-projection/test-fixtures/cursor/context-plan.json +108 -0
  28. package/dist/data/scripts/harness-projection/test-fixtures/cursor/matrix.json +19 -0
  29. package/dist/data/scripts/harness-projection/test-fixtures/cursor/projection.json +54 -0
  30. package/dist/data/scripts/harness-projection/test-fixtures/mixed-context-plan.json +35 -0
  31. package/dist/data/scripts/harness-projection/test-fixtures/opencode/compiler-input.json +93 -0
  32. package/dist/data/scripts/harness-projection/test-fixtures/opencode/context-plan.json +108 -0
  33. package/dist/data/scripts/harness-projection/test-fixtures/opencode/matrix.json +19 -0
  34. package/dist/data/scripts/harness-projection/test-fixtures/opencode/projection.json +51 -0
  35. package/dist/data/scripts/sync-subagents.mjs +1113 -33
  36. package/dist/data/subagents/manifest.mjs +5 -6
  37. package/dist/index.js +1373 -62672
  38. package/dist/skills/agnostic/docs/docs-onboarding/SKILL.md +1 -1
  39. package/dist/skills/agnostic/docs/docs-onboarding/references/artifact-contract.md +2 -2
  40. package/dist/skills/agnostic/planning/create-plan/SKILL.md +11 -10
  41. package/dist/skills/agnostic/planning/create-plan/references/grill-ambiguity.md +10 -31
  42. package/dist/skills/agnostic/planning/create-plan/references/plan-schema.md +2 -2
  43. package/dist/skills/agnostic/planning/create-spec/SKILL.md +3 -5
  44. package/dist/skills/agnostic/planning/create-spec/assets/SPEC-TEMPLATE.md +1 -0
  45. package/dist/skills/agnostic/planning/create-spec/references/backlog-sync.md +2 -2
  46. package/dist/skills/agnostic/planning/create-spec/references/grill-phase.md +4 -9
  47. package/dist/skills/agnostic/planning/create-spec/references/spec-quality-bar.md +1 -0
  48. package/dist/skills/agnostic/planning/implement-spec/references/lifecycle.md +1 -1
  49. package/dist/skills/agnostic/requirements/grilling/LICENSE +21 -0
  50. package/dist/skills/agnostic/requirements/grilling/SKILL.md +6 -30
  51. package/dist/skills/agnostic/requirements/grilling/UPSTREAM.md +16 -0
  52. package/dist/skills/agnostic/requirements/requirements-grill/SKILL.md +3 -5
  53. package/dist/skills/agnostic/requirements/requirements-grill/references/artifact-output.md +40 -16
  54. package/dist/skills/agnostic/requirements/requirements-grill/references/grilling-flow.md +3 -16
  55. package/dist/skills/agnostic/requirements/write-backlog/REFERENCE.md +21 -15
  56. package/dist/skills/agnostic/requirements/write-backlog/SKILL.md +14 -14
  57. package/dist/skills/agnostic/requirements/write-backlog/assets/concepts/backlog-model.md +28 -9
  58. package/dist/skills/agnostic/requirements/write-backlog/assets/providers/azure-devops-create-payload.md +45 -5
  59. package/dist/skills/agnostic/requirements/write-backlog/assets/providers/github-projects-create-payload.md +48 -28
  60. package/dist/skills/agnostic/requirements/write-backlog/assets/providers/linear-create-payload.md +22 -6
  61. package/dist/skills/agnostic/requirements/write-backlog/assets/providers/monday-create-payload.md +47 -22
  62. package/dist/skills/frameworks/effect/effect/LICENSE +21 -0
  63. package/dist/skills/frameworks/effect/effect/SKILL.md +100 -0
  64. package/dist/skills/frameworks/effect/effect/UPSTREAM.md +11 -0
  65. package/dist/skills/frameworks/effect/effect/references/CACHING.md +76 -0
  66. package/dist/skills/frameworks/effect/effect/references/CONFIG.md +67 -0
  67. package/dist/skills/frameworks/effect/effect/references/HTTP_CLIENTS.md +101 -0
  68. package/dist/skills/frameworks/effect/{effect-authoring/references/otel-patterns.md → effect/references/OBSERVABILITY.md} +4 -29
  69. package/dist/skills/frameworks/effect/effect/references/SCHEDULING.md +135 -0
  70. package/dist/skills/frameworks/effect/effect/references/SCHEMA.md +130 -0
  71. package/dist/skills/frameworks/effect/effect/references/SERVICES_LAYERS.md +168 -0
  72. package/dist/skills/frameworks/effect/effect/references/STREAMS.md +135 -0
  73. package/dist/skills/frameworks/effect/effect/references/TESTING.md +118 -0
  74. package/dist/skills/frameworks/effect/effect-backend-structure/SKILL.md +7 -8
  75. package/dist/skills/frameworks/effect/effect-recoverable-actions/SKILL.md +1 -1
  76. package/dist/skills/frameworks/nestjs/nestjs-best-practices/.gitignore +29 -0
  77. package/dist/skills/misc/secrets-cli/SKILL.md +54 -0
  78. package/dist/skills/misc/secrets-cli/references/command-reference.md +107 -0
  79. package/dist/skills/misc/secrets-cli/references/safety-and-errors.md +54 -0
  80. package/dist/skills/misc/secrets-cli/references/workflows.md +106 -0
  81. package/dist/skills/phases/design-phase/phases/grill.md +1 -1
  82. package/dist/skills/phases/requirements-phase/SKILL.md +2 -4
  83. package/dist/skills/phases/review-phase/REFERENCE.md +13 -5
  84. package/dist/skills/phases/review-phase/SKILL.md +3 -2
  85. package/package.json +1 -1
  86. package/dist/skills/agnostic/planning/create-spec/references/handoff.md +0 -47
  87. package/dist/skills/frameworks/effect/effect-authoring/SKILL.md +0 -116
  88. package/dist/skills/frameworks/effect/effect-authoring/references/branded-types.md +0 -98
  89. package/dist/skills/frameworks/effect/effect-authoring/references/effect-primitives.md +0 -144
  90. package/dist/skills/frameworks/effect/effect-authoring/references/error-patterns.md +0 -156
  91. package/dist/skills/frameworks/effect/effect-authoring/references/test-patterns.md +0 -146
  92. package/dist/skills/frameworks/effect/effect-best-practices/SKILL.md +0 -517
  93. package/dist/skills/frameworks/effect/effect-best-practices/references/anti-patterns.md +0 -392
  94. package/dist/skills/frameworks/effect/effect-best-practices/references/effect-atom-patterns.md +0 -653
  95. package/dist/skills/frameworks/effect/effect-best-practices/references/error-patterns.md +0 -464
  96. package/dist/skills/frameworks/effect/effect-best-practices/references/language-server.md +0 -287
  97. package/dist/skills/frameworks/effect/effect-best-practices/references/layer-patterns.md +0 -495
  98. package/dist/skills/frameworks/effect/effect-best-practices/references/observability-patterns.md +0 -342
  99. package/dist/skills/frameworks/effect/effect-best-practices/references/rpc-cluster-patterns.md +0 -418
  100. package/dist/skills/frameworks/effect/effect-best-practices/references/schema-patterns.md +0 -353
  101. package/dist/skills/frameworks/effect/effect-best-practices/references/service-patterns.md +0 -299
  102. /package/dist/skills/frameworks/effect/{effect-authoring/references/effect-atom-patterns.md → effect/references/EFFECT_ATOM.md} +0 -0
@@ -3,21 +3,34 @@ import {
3
3
  lstat,
4
4
  mkdir,
5
5
  readFile,
6
+ realpath,
6
7
  readdir,
7
8
  readlink,
8
9
  rm,
9
10
  symlink,
10
11
  writeFile,
11
12
  } from "node:fs/promises";
13
+ import { createHash } from "node:crypto";
12
14
  import path from "node:path";
13
15
  import { fileURLToPath } from "node:url";
14
16
 
15
17
  import { agents, capabilityPacks } from "../subagents/manifest.mjs";
18
+ import { claudeAdapter } from "./harness-projection/adapters/claude.mjs";
19
+ import { codexAdapter } from "./harness-projection/adapters/codex.mjs";
20
+ import { cursorAdapter } from "./harness-projection/adapters/cursor.mjs";
21
+ import { openCodeAdapter } from "./harness-projection/adapters/opencode.mjs";
22
+ import { applyProjection } from "./harness-projection/apply.mjs";
23
+ import { project } from "./harness-projection/core.mjs";
16
24
 
17
25
  const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
18
26
  const sharedAgentsPath = path.join(repoRoot, ".agents/AGENTS.md");
19
27
  const sharedSkillsPath = path.join(repoRoot, ".agents/skills");
20
28
  const sharedHooksPath = path.join(repoRoot, ".agents/hooks");
29
+ const contextPlanPath = path.join(repoRoot, ".devpunks/context-plan.json");
30
+ const projectionReceiptPath = path.join(repoRoot, ".devpunks/harness-projection-receipt.json");
31
+ const adapters = [claudeAdapter, codexAdapter, cursorAdapter, openCodeAdapter];
32
+ let previousCopyFallbacks = [];
33
+ const currentCopyFallbacks = new Map();
21
34
 
22
35
  const codexDir = path.join(repoRoot, ".codex");
23
36
  const codexAgentsDir = path.join(codexDir, "agents");
@@ -210,18 +223,23 @@ function buildCursorHooksConfig({ hasFormatHook, hasUpdateCheckHook }) {
210
223
 
211
224
  function buildOpenCodeConfig(existingConfig, { hasFormatHook }) {
212
225
  const config = { ...existingConfig };
226
+ const formatter =
227
+ typeof config.formatter === "object" && config.formatter !== null
228
+ ? { ...config.formatter }
229
+ : {};
230
+ delete formatter["harness-format-edited-file"];
213
231
 
214
232
  if (hasFormatHook) {
215
- config.formatter = {
216
- ...(typeof config.formatter === "object" && config.formatter !== null
217
- ? config.formatter
218
- : {}),
219
- "harness-format-edited-file": {
220
- command: ["node", ".agents/hooks/format-edited-file.mjs", "files", "$FILE"],
221
- extensions: [".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs", ".json", ".py"],
222
- },
233
+ formatter["harness-format-edited-file"] = {
234
+ command: ["node", ".agents/hooks/format-edited-file.mjs", "files", "$FILE"],
235
+ extensions: [".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs", ".json", ".py"],
223
236
  };
224
237
  }
238
+ if (Object.keys(formatter).length > 0) {
239
+ config.formatter = formatter;
240
+ } else {
241
+ delete config.formatter;
242
+ }
225
243
 
226
244
  return {
227
245
  $schema: "https://opencode.ai/config.json",
@@ -418,7 +436,12 @@ function buildOpenCodeAgent(agent, prompt) {
418
436
  return `${frontmatter}${opencodeManagedComment}\n\n${prompt}\n`;
419
437
  }
420
438
 
421
- async function ensureSymlink(linkPath, targetPath) {
439
+ const fileDigest = async (filePath) =>
440
+ createHash("sha256").update(await readFile(filePath)).digest("hex");
441
+
442
+ const copyFallbackKey = ({ source, target }) => `${source}\0${target}`;
443
+
444
+ async function ensureSymlink(linkPath, targetPath, fallbackIdentity) {
422
445
  const relativeTarget = path.relative(path.dirname(linkPath), targetPath);
423
446
  await mkdir(path.dirname(linkPath), { recursive: true });
424
447
 
@@ -451,6 +474,12 @@ async function ensureSymlink(linkPath, targetPath) {
451
474
  force: true,
452
475
  errorOnExist: false,
453
476
  });
477
+ if (fallbackIdentity !== undefined && !copyTargetStat.isDirectory()) {
478
+ currentCopyFallbacks.set(copyFallbackKey(fallbackIdentity), {
479
+ ...fallbackIdentity,
480
+ digest: await fileDigest(linkPath),
481
+ });
482
+ }
454
483
  }
455
484
  }
456
485
 
@@ -466,7 +495,7 @@ async function pathExists(filePath) {
466
495
  }
467
496
  }
468
497
 
469
- async function writeManagedFiles(directory, extension, renderedByName) {
498
+ async function writeManagedFiles(directory, extension, renderedByName, writeCurrent = true) {
470
499
  await mkdir(directory, { recursive: true });
471
500
 
472
501
  const managedNames = new Set(Object.keys(renderedByName).map((name) => `${name}.${extension}`));
@@ -488,8 +517,10 @@ async function writeManagedFiles(directory, extension, renderedByName) {
488
517
  }
489
518
  }
490
519
 
491
- for (const [name, content] of Object.entries(renderedByName)) {
492
- await writeFile(path.join(directory, `${name}.${extension}`), content, "utf8");
520
+ if (writeCurrent) {
521
+ for (const [name, content] of Object.entries(renderedByName)) {
522
+ await writeFile(path.join(directory, `${name}.${extension}`), content, "utf8");
523
+ }
493
524
  }
494
525
  }
495
526
 
@@ -513,11 +544,10 @@ async function syncHookSurface() {
513
544
  for (const targetPath of targetPaths) {
514
545
  await ensureSymlink(targetPath, sourcePath);
515
546
  }
516
- continue;
517
- }
518
-
519
- for (const targetPath of targetPaths) {
520
- await rm(targetPath, { force: true, recursive: true });
547
+ } else {
548
+ for (const targetPath of targetPaths) {
549
+ await rm(targetPath, { force: true, recursive: true });
550
+ }
521
551
  }
522
552
  }
523
553
  }
@@ -532,7 +562,7 @@ async function syncPromptMirrors() {
532
562
  await ensureSymlink(opencodeAgentsMirrorPath, sharedAgentsPath);
533
563
  }
534
564
 
535
- async function main() {
565
+ async function prepareHarnessApplication() {
536
566
  const claudeFiles = {};
537
567
  const codexFiles = {};
538
568
  const cursorFiles = {};
@@ -549,22 +579,177 @@ async function main() {
549
579
  opencodeFiles[agent.name] = buildOpenCodeAgent(agent, prompt);
550
580
  }
551
581
 
552
- await mkdir(path.dirname(codexConfigPath), { recursive: true });
553
- await mkdir(path.dirname(claudeSettingsPath), { recursive: true });
554
- await mkdir(path.dirname(cursorHooksJsonPath), { recursive: true });
555
582
  const availableHooks = {
556
583
  hasFormatHook: await pathExists(path.join(sharedHooksPath, "format-edited-file.mjs")),
557
584
  hasUpdateCheckHook: await pathExists(path.join(sharedHooksPath, "scaffold-update-check.mjs")),
558
585
  };
559
- await writeFile(codexConfigPath, buildCodexAgentConfig(availableHooks), "utf8");
560
- await rm(path.join(codexDir, "hooks.json"), { force: true });
561
- await writeFile(
562
- claudeSettingsPath,
563
- encodeJson(buildClaudeSettingsConfig(await readJsonFile(claudeSettingsPath), availableHooks)),
564
- "utf8",
586
+ return {
587
+ availableHooks,
588
+ rendered: {
589
+ claude: claudeFiles,
590
+ codex: codexFiles,
591
+ cursor: cursorFiles,
592
+ opencode: opencodeFiles,
593
+ },
594
+ };
595
+ }
596
+
597
+ const harnessAgentSurface = {
598
+ claude: { directory: claudeAgentsDir, extension: "md" },
599
+ codex: { directory: codexAgentsDir, extension: "toml" },
600
+ cursor: { directory: cursorAgentsDir, extension: "md" },
601
+ opencode: { directory: opencodeAgentsDir, extension: "md" },
602
+ };
603
+
604
+ const harnessConfigPath = {
605
+ claude: claudeSettingsPath,
606
+ codex: codexConfigPath,
607
+ cursor: cursorHooksJsonPath,
608
+ opencode: opencodeConfigPath,
609
+ };
610
+
611
+ const harnessHookSurface = {
612
+ claude: claudeHooksDir,
613
+ codex: codexHooksDir,
614
+ cursor: cursorHooksDir,
615
+ opencode: opencodePluginsDir,
616
+ };
617
+
618
+ const actionTargetPath = (action) => {
619
+ const target = action.file ?? action.target ?? action.nativePath;
620
+ return typeof target === "string" ? target.split("#", 1)[0] : undefined;
621
+ };
622
+
623
+ const actionPathFields = [
624
+ "source",
625
+ "target",
626
+ "file",
627
+ "nativePath",
628
+ "canonicalPath",
629
+ "directory",
630
+ "config.path",
631
+ ];
632
+ const harnessActionOperations = new Set([
633
+ "cleanup-managed-agents",
634
+ "merge-json",
635
+ "merge-toml",
636
+ "mirror",
637
+ "native",
638
+ "reconcile-lifecycle-hooks",
639
+ "render",
640
+ "render-template",
641
+ "use-native-mirror",
642
+ "use-native-prompt",
643
+ "use-native-skill",
644
+ ]);
645
+
646
+ const actionPathValue = (action, field) =>
647
+ field === "config.path" ? action.config?.path : action[field];
648
+
649
+ const isPathWithin = (root, candidate) => {
650
+ const relative = path.relative(root, candidate);
651
+ return (
652
+ relative === "" ||
653
+ (!relative.startsWith(`..${path.sep}`) && relative !== ".." && !path.isAbsolute(relative))
565
654
  );
566
- await writeFile(cursorHooksJsonPath, encodeJson(buildCursorHooksConfig(availableHooks)), "utf8");
567
- if (availableHooks.hasFormatHook || (await pathExists(opencodeConfigPath))) {
655
+ };
656
+
657
+ const resolveActionPath = (value, field) => {
658
+ if (typeof value !== "string") {
659
+ throw new Error(`Harness action ${field} path must be a string`);
660
+ }
661
+ const candidate = value.split("#", 1)[0];
662
+ const portableCandidate = candidate.replaceAll("\\", "/");
663
+ if (
664
+ candidate.length === 0 ||
665
+ path.isAbsolute(candidate) ||
666
+ path.win32.isAbsolute(candidate) ||
667
+ portableCandidate.split("/").includes("..")
668
+ ) {
669
+ throw new Error(`Harness action ${field} path escapes the repository: ${value}`);
670
+ }
671
+ const resolved = path.resolve(repoRoot, portableCandidate);
672
+ const relative = path.relative(repoRoot, resolved);
673
+ if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
674
+ throw new Error(`Harness action ${field} path escapes the repository: ${value}`);
675
+ }
676
+ return resolved;
677
+ };
678
+
679
+ const resolveActionPaths = (action) =>
680
+ Object.fromEntries(
681
+ [
682
+ ...actionPathFields.flatMap((field) => {
683
+ const value = actionPathValue(action, field);
684
+ return value === undefined ? [] : [[field, value]];
685
+ }),
686
+ ...(action.managedHookFiles ?? []).map((value, index) => [
687
+ `managedHookFiles[${index}]`,
688
+ value,
689
+ ]),
690
+ ].map(([field, value]) => [field, resolveActionPath(value, field)]),
691
+ );
692
+
693
+ const hasInvalidActionPaths = (action) => {
694
+ try {
695
+ resolveActionPaths(action);
696
+ return false;
697
+ } catch {
698
+ return true;
699
+ }
700
+ };
701
+
702
+ async function nearestExistingPath(candidate) {
703
+ let current = candidate;
704
+ while (!(await pathExists(current))) {
705
+ const parent = path.dirname(current);
706
+ if (parent === current) {
707
+ break;
708
+ }
709
+ current = parent;
710
+ }
711
+ return current;
712
+ }
713
+
714
+ async function assertRealPathContainment(action, actionPaths) {
715
+ const realRepoRoot = await realpath(repoRoot);
716
+ for (const [field, candidate] of Object.entries(actionPaths)) {
717
+ const ancestor = await nearestExistingPath(candidate);
718
+ const realAncestor = await realpath(ancestor);
719
+ if (!isPathWithin(realRepoRoot, realAncestor)) {
720
+ throw new Error(
721
+ `Harness action ${field} path escapes the repository: ${actionPathValue(action, field)}`,
722
+ );
723
+ }
724
+ }
725
+ }
726
+
727
+ async function writeAdapterConfig(adapterId, availableHooks) {
728
+ if (adapterId === "codex") {
729
+ await mkdir(path.dirname(codexConfigPath), { recursive: true });
730
+ await writeFile(codexConfigPath, buildCodexAgentConfig(availableHooks), "utf8");
731
+ await rm(path.join(codexDir, "hooks.json"), { force: true });
732
+ return;
733
+ }
734
+ if (adapterId === "claude") {
735
+ await mkdir(path.dirname(claudeSettingsPath), { recursive: true });
736
+ await writeFile(
737
+ claudeSettingsPath,
738
+ encodeJson(buildClaudeSettingsConfig(await readJsonFile(claudeSettingsPath), availableHooks)),
739
+ "utf8",
740
+ );
741
+ return;
742
+ }
743
+ if (adapterId === "cursor") {
744
+ await mkdir(path.dirname(cursorHooksJsonPath), { recursive: true });
745
+ await writeFile(
746
+ cursorHooksJsonPath,
747
+ encodeJson(buildCursorHooksConfig(availableHooks)),
748
+ "utf8",
749
+ );
750
+ return;
751
+ }
752
+ if (adapterId === "opencode") {
568
753
  await writeFile(
569
754
  opencodeConfigPath,
570
755
  encodeOpenCodeConfig(
@@ -573,13 +758,908 @@ async function main() {
573
758
  "utf8",
574
759
  );
575
760
  }
576
- await writeManagedFiles(claudeAgentsDir, "md", claudeFiles);
577
- await writeManagedFiles(codexAgentsDir, "toml", codexFiles);
578
- await writeManagedFiles(cursorAgentsDir, "md", cursorFiles);
579
- await writeManagedFiles(opencodeAgentsDir, "md", opencodeFiles);
761
+ }
762
+
763
+ const hookIdForAction = (action) =>
764
+ action.id.includes(":lifecycle-hook:") ? action.trace?.contribution?.id : undefined;
765
+
766
+ async function reconcileLifecycleHooks(action, adapterId, actionPaths) {
767
+ const activeHookIds = new Set();
768
+ for (const hookId of action.hookIds) {
769
+ if (await pathExists(path.join(sharedHooksPath, `${hookId}.mjs`))) {
770
+ activeHookIds.add(hookId);
771
+ }
772
+ }
773
+ for (const [index, managedHookFile] of action.managedHookFiles.entries()) {
774
+ const hookId = path.basename(managedHookFile, ".mjs");
775
+ if (!activeHookIds.has(hookId)) {
776
+ await rm(actionPaths[`managedHookFiles[${index}]`], { force: true, recursive: true });
777
+ }
778
+ }
779
+ const projectedHooks = {
780
+ hasFormatHook: action.configurations.some(
781
+ (configuration) =>
782
+ hookIdForAction(configuration) === "format-edited-file" &&
783
+ activeHookIds.has("format-edited-file"),
784
+ ),
785
+ hasUpdateCheckHook: action.configurations.some(
786
+ (configuration) =>
787
+ hookIdForAction(configuration) === "scaffold-update-check" &&
788
+ activeHookIds.has("scaffold-update-check"),
789
+ ),
790
+ };
791
+ if (
792
+ adapterId !== "opencode" ||
793
+ projectedHooks.hasFormatHook ||
794
+ (await pathExists(opencodeConfigPath))
795
+ ) {
796
+ await writeAdapterConfig(adapterId, projectedHooks);
797
+ }
798
+ }
799
+
800
+ async function applyHarnessAction(action, application) {
801
+ const actionPaths = resolveActionPaths(action);
802
+ await assertRealPathContainment(action, actionPaths);
803
+ const adapterId = action.trace.adapter.id;
804
+
805
+ if (action.operation === "cleanup-managed-agents") {
806
+ await writeManagedFiles(
807
+ actionPaths.directory,
808
+ action.extension,
809
+ application.rendered[adapterId],
810
+ false,
811
+ );
812
+ return;
813
+ }
814
+ if (action.operation === "reconcile-lifecycle-hooks") {
815
+ await reconcileLifecycleHooks(action, adapterId, actionPaths);
816
+ return;
817
+ }
818
+ if (action.operation === "use-native-mirror") {
819
+ await syncSkillMirrors();
820
+ return;
821
+ }
822
+ if (
823
+ action.operation === "use-native-skill" ||
824
+ action.operation === "use-native-prompt" ||
825
+ action.operation === "native"
826
+ ) {
827
+ return;
828
+ }
829
+ if (action.operation === "mirror") {
830
+ if (action.source !== action.target) {
831
+ const sourcePath = actionPaths.source;
832
+ const targetPath = actionPaths.target;
833
+ if (!(await pathExists(sourcePath))) {
834
+ throw new Error(`Missing canonical source: ${action.source}`);
835
+ }
836
+ if (await pathExists(targetPath)) {
837
+ const targetStat = await lstat(targetPath);
838
+ const previousCopy = previousCopyFallbacks.find(
839
+ (copy) => copy.source === action.source && copy.target === action.target,
840
+ );
841
+ const isManagedCopy =
842
+ targetStat.isFile() &&
843
+ previousCopy !== undefined &&
844
+ (await fileDigest(targetPath)) === previousCopy.digest;
845
+ if (
846
+ !targetStat.isSymbolicLink() &&
847
+ !isManagedCopy &&
848
+ action.id.includes(":scoped-prompt:")
849
+ ) {
850
+ throw new Error(
851
+ `Consumer prompt target requires explicit preservation: ${action.target}`,
852
+ );
853
+ }
854
+ }
855
+ await ensureSymlink(targetPath, sourcePath, {
856
+ source: action.source,
857
+ target: action.target,
858
+ });
859
+ }
860
+ return;
861
+ }
862
+ if (action.operation === "merge-json" || action.operation === "merge-toml") {
863
+ return;
864
+ }
865
+ if (action.operation === "render-template" || action.operation === "render") {
866
+ const name = action.templateId ?? action.contributionId;
867
+ const content = application.rendered[adapterId]?.[name];
868
+ const target = actionTargetPath(action);
869
+ if (typeof content !== "string" || target === undefined) {
870
+ throw new Error(`Missing ${adapterId} render input for ${name ?? "unknown template"}`);
871
+ }
872
+ const targetPath = resolveActionPath(target, "target");
873
+ await mkdir(path.dirname(targetPath), { recursive: true });
874
+ await writeFile(targetPath, content, "utf8");
875
+ return;
876
+ }
877
+
878
+ throw new Error(`Unknown harness application operation: ${action.operation}`);
879
+ }
880
+
881
+ async function cleanupManagedAgents(application, writeCurrent = false) {
882
+ for (const [adapterId, surface] of Object.entries(harnessAgentSurface)) {
883
+ const rendered = application.rendered[adapterId];
884
+ await writeManagedFiles(surface.directory, surface.extension, rendered, writeCurrent);
885
+ }
886
+ }
887
+
888
+ async function materializeLegacyHarnesses(application) {
889
+ await writeAdapterConfig("codex", application.availableHooks);
890
+ await writeAdapterConfig("claude", application.availableHooks);
891
+ await writeAdapterConfig("cursor", application.availableHooks);
892
+ if (application.availableHooks.hasFormatHook || (await pathExists(opencodeConfigPath))) {
893
+ await writeAdapterConfig("opencode", application.availableHooks);
894
+ }
895
+ await cleanupManagedAgents(application, true);
580
896
  await syncPromptMirrors();
581
897
  await syncSkillMirrors();
582
898
  await syncHookSurface();
583
899
  }
584
900
 
901
+ const summaryState = (summary) =>
902
+ summary._tag === "HarnessProjectionFailure"
903
+ ? {
904
+ applied: summary.completed,
905
+ omissions: summary.omissions,
906
+ failures: summary.errors,
907
+ }
908
+ : {
909
+ applied: summary.applied,
910
+ omissions: summary._tag === "HarnessProjectionPartial" ? summary.omissions : [],
911
+ failures: [],
912
+ };
913
+
914
+ const projectionEvidence = ({ adapter, projection, summary }) => {
915
+ const state = summaryState(summary);
916
+ return {
917
+ adapter: adapter.matrix.adapter,
918
+ matrixVersion: adapter.matrix.matrixVersion,
919
+ actions: projection.actions,
920
+ warnings: [
921
+ ...state.applied
922
+ .filter(({ support }) => support === "degraded")
923
+ .map(({ reason, trace }) => ({
924
+ _tag: "DegradedHarnessCapabilityWarning",
925
+ reason,
926
+ trace,
927
+ })),
928
+ ...state.omissions.map(({ warning, trace }) => ({ ...warning, trace })),
929
+ ],
930
+ omissions: state.omissions,
931
+ failures: state.failures,
932
+ };
933
+ };
934
+
935
+ const receiptStatus = (projections) =>
936
+ projections.some(({ failures }) => failures.length > 0)
937
+ ? "failure"
938
+ : projections.some(({ warnings, omissions }) => warnings.length > 0 || omissions.length > 0)
939
+ ? "partial"
940
+ : "success";
941
+
942
+ const projectSafely = (adapter, contextPlan) => {
943
+ try {
944
+ const issue = canonicalContextIssue(contextPlan);
945
+ if (issue !== undefined) {
946
+ throw new Error(issue);
947
+ }
948
+ return project({ adapter, contextPlan });
949
+ } catch (error) {
950
+ return {
951
+ actions: [],
952
+ summary: {
953
+ _tag: "HarnessProjectionFailure",
954
+ completed: [],
955
+ omissions: [],
956
+ errors: [
957
+ {
958
+ _tag: "InvalidHarnessProjectionError",
959
+ trace: {
960
+ contextPlanVersion: contextPlanVersion(contextPlan),
961
+ scopeId: "unknown",
962
+ kind: "skill",
963
+ contribution: { id: "context-plan", version: "unknown" },
964
+ adapter: adapter.matrix.adapter,
965
+ matrixVersion: adapter.matrix.matrixVersion,
966
+ },
967
+ message: error instanceof Error ? error.message : "Invalid canonical context plan",
968
+ },
969
+ ],
970
+ },
971
+ };
972
+ }
973
+ };
974
+
975
+ const structuralIdentity = (value) => {
976
+ if (Array.isArray(value)) return `[${value.map(structuralIdentity).join(",")}]`;
977
+ if (isObject(value)) {
978
+ return `{${Object.entries(value)
979
+ .toSorted(([left], [right]) => (left === right ? 0 : left < right ? -1 : 1))
980
+ .map(([key, entry]) => `${JSON.stringify(key)}:${structuralIdentity(entry)}`)
981
+ .join(",")}}`;
982
+ }
983
+ return JSON.stringify(value) ?? String(value);
984
+ };
985
+
986
+ const normalizeProjectionSummary = (summary) => {
987
+ const sort = (values) =>
988
+ [...values].toSorted((left, right) => {
989
+ const leftIdentity = structuralIdentity(left);
990
+ const rightIdentity = structuralIdentity(right);
991
+ return leftIdentity === rightIdentity ? 0 : leftIdentity < rightIdentity ? -1 : 1;
992
+ });
993
+ if (summary._tag === "HarnessProjectionSuccess") {
994
+ return { ...summary, applied: sort(summary.applied) };
995
+ }
996
+ if (summary._tag === "HarnessProjectionPartial") {
997
+ return { ...summary, applied: sort(summary.applied), omissions: sort(summary.omissions) };
998
+ }
999
+ return {
1000
+ ...summary,
1001
+ completed: sort(summary.completed),
1002
+ errors: sort(summary.errors),
1003
+ omissions: sort(summary.omissions),
1004
+ };
1005
+ };
1006
+
1007
+ const normalizeProjection = (projection) => ({
1008
+ actions: [...projection.actions].toSorted((left, right) =>
1009
+ left.id === right.id ? 0 : left.id < right.id ? -1 : 1,
1010
+ ),
1011
+ summary: normalizeProjectionSummary(projection.summary),
1012
+ });
1013
+
1014
+ const withManagedAgentCleanup = (adapter, contextPlan, projection) => {
1015
+ const surface = harnessAgentSurface[adapter.matrix.adapter.id];
1016
+ if (canonicalContextIssue(contextPlan) !== undefined || surface === undefined) {
1017
+ return projection;
1018
+ }
1019
+
1020
+ return {
1021
+ ...projection,
1022
+ actions: [
1023
+ {
1024
+ id: `${adapter.matrix.adapter.id}:cleanup-managed-agents`,
1025
+ operation: "cleanup-managed-agents",
1026
+ directory: path.relative(repoRoot, surface.directory),
1027
+ extension: surface.extension,
1028
+ trace: {
1029
+ contextPlanVersion: contextPlan.version,
1030
+ operation: "managed-agent-cleanup",
1031
+ adapter: adapter.matrix.adapter,
1032
+ matrixVersion: adapter.matrix.matrixVersion,
1033
+ },
1034
+ },
1035
+ ...projection.actions,
1036
+ ],
1037
+ };
1038
+ };
1039
+
1040
+ const withLifecycleHookReconciliation = (adapter, contextPlan, projection) => {
1041
+ if (canonicalContextIssue(contextPlan) !== undefined) {
1042
+ return projection;
1043
+ }
1044
+ const configPath = harnessConfigPath[adapter.matrix.adapter.id];
1045
+ const hookDirectory = harnessHookSurface[adapter.matrix.adapter.id];
1046
+ const lifecycleActions = projection.actions.filter((action) =>
1047
+ action.id.includes(":lifecycle-hook:"),
1048
+ );
1049
+ return {
1050
+ ...projection,
1051
+ actions: [
1052
+ ...projection.actions,
1053
+ {
1054
+ id: `${adapter.matrix.adapter.id}:reconcile-lifecycle-hooks`,
1055
+ operation: "reconcile-lifecycle-hooks",
1056
+ file: path.relative(repoRoot, configPath),
1057
+ managedHookFiles: ["format-edited-file", "scaffold-update-check"].map((hookId) =>
1058
+ path.relative(repoRoot, path.join(hookDirectory, `${hookId}.mjs`)),
1059
+ ),
1060
+ hookIds: [
1061
+ ...new Set(
1062
+ lifecycleActions.map(hookIdForAction).filter((hookId) => hookId !== undefined),
1063
+ ),
1064
+ ].toSorted(),
1065
+ configurations: lifecycleActions.filter(
1066
+ (action) =>
1067
+ action.operation === "merge-json" ||
1068
+ action.operation === "merge-toml" ||
1069
+ action.config !== undefined,
1070
+ ),
1071
+ trace: {
1072
+ contextPlanVersion: contextPlan.version,
1073
+ operation: "lifecycle-hook-reconciliation",
1074
+ adapter: adapter.matrix.adapter,
1075
+ matrixVersion: adapter.matrix.matrixVersion,
1076
+ },
1077
+ },
1078
+ ],
1079
+ };
1080
+ };
1081
+
1082
+ const sameTrace = (left, right) =>
1083
+ left.contextPlanVersion === right.contextPlanVersion &&
1084
+ left.scopeId === right.scopeId &&
1085
+ left.kind === right.kind &&
1086
+ left.contribution.id === right.contribution.id &&
1087
+ left.contribution.version === right.contribution.version &&
1088
+ left.adapter.id === right.adapter.id &&
1089
+ left.adapter.version === right.adapter.version &&
1090
+ left.matrixVersion === right.matrixVersion;
1091
+
1092
+ const withApplicationOmissions = (summary, omissions) => {
1093
+ if (omissions.length === 0) {
1094
+ return summary;
1095
+ }
1096
+ const omittedTraces = omissions.map(({ trace }) => trace);
1097
+ const keepApplied = ({ trace }) => !omittedTraces.some((omitted) => sameTrace(trace, omitted));
1098
+
1099
+ if (summary._tag === "HarnessProjectionFailure") {
1100
+ return {
1101
+ ...summary,
1102
+ completed: summary.completed.filter(keepApplied),
1103
+ omissions: [...summary.omissions, ...omissions],
1104
+ };
1105
+ }
1106
+
1107
+ const applied = summary.applied.filter(keepApplied);
1108
+ return {
1109
+ _tag: "HarnessProjectionPartial",
1110
+ applied,
1111
+ omissions: [
1112
+ ...(summary._tag === "HarnessProjectionPartial" ? summary.omissions : []),
1113
+ ...omissions,
1114
+ ],
1115
+ };
1116
+ };
1117
+
1118
+ async function prepareProjectionApplication(projection) {
1119
+ const actions = [];
1120
+ const omissions = [];
1121
+
1122
+ for (const action of projection.actions) {
1123
+ let canonicalSourcePath;
1124
+ if (action.id.includes(":scoped-prompt:")) {
1125
+ const canonicalSource = action.source ?? action.canonicalPath;
1126
+ try {
1127
+ canonicalSourcePath =
1128
+ typeof canonicalSource === "string"
1129
+ ? resolveActionPath(canonicalSource, "source")
1130
+ : undefined;
1131
+ } catch {
1132
+ actions.push(action);
1133
+ continue;
1134
+ }
1135
+ if (canonicalSourcePath !== undefined && !(await pathExists(canonicalSourcePath))) {
1136
+ omissions.push({
1137
+ _tag: "HarnessApplicationOmission",
1138
+ support: "missing",
1139
+ trace: action.trace,
1140
+ warning: {
1141
+ _tag: "MissingCanonicalPromptWarning",
1142
+ family: "scoped-prompt",
1143
+ reason: `Missing canonical prompt source at ${canonicalSource}`,
1144
+ },
1145
+ });
1146
+ continue;
1147
+ }
1148
+ }
1149
+ let targetPath;
1150
+ try {
1151
+ targetPath = resolveActionPaths(action).target;
1152
+ } catch {
1153
+ actions.push(action);
1154
+ continue;
1155
+ }
1156
+ if (
1157
+ action.operation === "mirror" &&
1158
+ action.id.includes(":scoped-prompt:") &&
1159
+ action.source !== action.target &&
1160
+ (await pathExists(targetPath))
1161
+ ) {
1162
+ const targetStat = await lstat(targetPath);
1163
+ const isManagedSymlink =
1164
+ targetStat.isSymbolicLink() &&
1165
+ canonicalSourcePath !== undefined &&
1166
+ (await readlink(targetPath)) ===
1167
+ path.relative(path.dirname(targetPath), canonicalSourcePath);
1168
+ const previousCopy = previousCopyFallbacks.find(
1169
+ (copy) => copy.source === action.source && copy.target === action.target,
1170
+ );
1171
+ const isManagedCopy =
1172
+ !targetStat.isSymbolicLink() &&
1173
+ targetStat.isFile() &&
1174
+ previousCopy !== undefined &&
1175
+ (await fileDigest(targetPath)) === previousCopy.digest;
1176
+ if (!isManagedSymlink && !isManagedCopy) {
1177
+ omissions.push({
1178
+ _tag: "HarnessApplicationOmission",
1179
+ support: "preserved",
1180
+ trace: action.trace,
1181
+ warning: {
1182
+ _tag: "PreservedConsumerPromptWarning",
1183
+ family: "scoped-prompt",
1184
+ reason: `Preserved consumer-owned prompt at ${action.target}`,
1185
+ },
1186
+ });
1187
+ continue;
1188
+ }
1189
+ }
1190
+ actions.push(action);
1191
+ }
1192
+
1193
+ return {
1194
+ actions,
1195
+ summary: withApplicationOmissions(projection.summary, omissions),
1196
+ };
1197
+ }
1198
+
1199
+ async function readContextPlan() {
1200
+ try {
1201
+ return {
1202
+ exists: true,
1203
+ value: JSON.parse(await readFile(contextPlanPath, "utf8")),
1204
+ };
1205
+ } catch (error) {
1206
+ if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") {
1207
+ return { exists: false, value: undefined };
1208
+ }
1209
+ return {
1210
+ exists: true,
1211
+ value: {
1212
+ version: "unknown",
1213
+ scopes: null,
1214
+ parseError: error instanceof Error ? error.message : "Malformed canonical context plan",
1215
+ },
1216
+ };
1217
+ }
1218
+ }
1219
+
1220
+ async function readProjectionPlan() {
1221
+ const projectionPlanPath = process.env.DP_HARNESS_PROJECTION_PLAN;
1222
+ if (projectionPlanPath === undefined) {
1223
+ return { exists: false, value: undefined };
1224
+ }
1225
+ try {
1226
+ const value = JSON.parse(await readFile(projectionPlanPath, "utf8"));
1227
+ if (
1228
+ !isObject(value) ||
1229
+ value.version !== "1" ||
1230
+ typeof value.contextPlanVersion !== "string" ||
1231
+ !Array.isArray(value.projections)
1232
+ ) {
1233
+ throw new Error("Invalid supplied harness projection plan");
1234
+ }
1235
+ return { exists: true, value };
1236
+ } catch (error) {
1237
+ throw new Error("Invalid supplied harness projection plan", { cause: error });
1238
+ }
1239
+ }
1240
+
1241
+ const projectionSummaryShapeIssue = (summary) => {
1242
+ if (!isObject(summary)) return "Projection summary must be an object";
1243
+ if (summary._tag === "HarnessProjectionSuccess") {
1244
+ return Array.isArray(summary.applied) ? undefined : "Success summary must contain applied";
1245
+ }
1246
+ if (summary._tag === "HarnessProjectionPartial") {
1247
+ return Array.isArray(summary.applied) && Array.isArray(summary.omissions)
1248
+ ? undefined
1249
+ : "Partial summary must contain applied and omissions";
1250
+ }
1251
+ if (summary._tag === "HarnessProjectionFailure") {
1252
+ return Array.isArray(summary.completed) &&
1253
+ Array.isArray(summary.omissions) &&
1254
+ Array.isArray(summary.errors)
1255
+ ? undefined
1256
+ : "Failure summary must contain completed, omissions, and errors";
1257
+ }
1258
+ return "Projection summary tag is invalid";
1259
+ };
1260
+
1261
+ const actionTraceMatches = ({ trace, plan, projection, contextPlan }) =>
1262
+ exactKeys(trace, [
1263
+ "contextPlanVersion",
1264
+ "scopeId",
1265
+ "kind",
1266
+ "contribution",
1267
+ "adapter",
1268
+ "matrixVersion",
1269
+ ]) &&
1270
+ trace.contextPlanVersion === plan.contextPlanVersion &&
1271
+ isNonEmptyString(trace.scopeId) &&
1272
+ contributionKinds.has(trace.kind) &&
1273
+ exactKeys(trace.contribution, ["id", "version"]) &&
1274
+ isNonEmptyString(trace.contribution.id) &&
1275
+ isNonEmptyString(trace.contribution.version) &&
1276
+ exactKeys(trace.adapter, ["id", "version"]) &&
1277
+ trace.adapter.id === projection.matrix.adapter.id &&
1278
+ trace.adapter.version === projection.matrix.adapter.version &&
1279
+ trace.matrixVersion === projection.matrix.matrixVersion &&
1280
+ Array.isArray(contextPlan?.scopes) &&
1281
+ contextPlan.scopes.some(
1282
+ (scope) =>
1283
+ scope?.id === trace.scopeId &&
1284
+ Array.isArray(scope.contributions) &&
1285
+ scope.contributions.some(
1286
+ (contribution) =>
1287
+ contribution?.kind === trace.kind &&
1288
+ contribution?.identity?.id === trace.contribution.id &&
1289
+ contribution.identity.version === trace.contribution.version,
1290
+ ),
1291
+ );
1292
+
1293
+ const contributionTraceKey = (trace) =>
1294
+ [
1295
+ trace.contextPlanVersion,
1296
+ trace.scopeId,
1297
+ trace.kind,
1298
+ trace.contribution.id,
1299
+ trace.contribution.version,
1300
+ trace.adapter.id,
1301
+ trace.adapter.version,
1302
+ trace.matrixVersion,
1303
+ ].join("\u0000");
1304
+
1305
+ const projectionSummaryIssue = ({ summary, plan, projection, contextPlan }) => {
1306
+ const shapeIssue = projectionSummaryShapeIssue(summary);
1307
+ if (shapeIssue !== undefined) return shapeIssue;
1308
+ const applied = summary._tag === "HarnessProjectionFailure" ? summary.completed : summary.applied;
1309
+ const omissions = summary._tag === "HarnessProjectionSuccess" ? [] : summary.omissions;
1310
+ const errors = summary._tag === "HarnessProjectionFailure" ? summary.errors : [];
1311
+ if (
1312
+ applied.some(
1313
+ (outcome) =>
1314
+ !isObject(outcome) ||
1315
+ outcome._tag !== "HarnessProjectionApplied" ||
1316
+ (outcome.support !== "supported" && outcome.support !== "degraded") ||
1317
+ (outcome.support === "degraded" && !isNonEmptyString(outcome.reason)),
1318
+ )
1319
+ ) {
1320
+ return "Projection summary contains an invalid applied outcome";
1321
+ }
1322
+ if (
1323
+ omissions.some(
1324
+ (outcome) =>
1325
+ !isObject(outcome) ||
1326
+ outcome._tag !== "HarnessProjectionOmission" ||
1327
+ outcome.support !== "unsupported" ||
1328
+ !isObject(outcome.warning) ||
1329
+ outcome.warning._tag !== "UnsupportedHarnessCapabilityWarning" ||
1330
+ !contributionKinds.has(outcome.warning.family) ||
1331
+ !isNonEmptyString(outcome.warning.reason),
1332
+ )
1333
+ ) {
1334
+ return "Projection summary contains an invalid omission";
1335
+ }
1336
+ if (
1337
+ errors.some(
1338
+ (outcome) =>
1339
+ !isObject(outcome) ||
1340
+ (outcome._tag !== "HarnessAdapterDefectError" &&
1341
+ outcome._tag !== "InvalidHarnessProjectionError") ||
1342
+ !isNonEmptyString(outcome.message),
1343
+ )
1344
+ ) {
1345
+ return "Projection summary contains an invalid error";
1346
+ }
1347
+ const outcomes = [...applied, ...omissions, ...errors];
1348
+ return outcomes.some(
1349
+ (outcome) =>
1350
+ !isObject(outcome) ||
1351
+ !isObject(outcome.trace) ||
1352
+ !actionTraceMatches({ trace: outcome.trace, plan, projection, contextPlan }),
1353
+ )
1354
+ ? "Projection summary contains an invalid trace"
1355
+ : (() => {
1356
+ const actionTraces = new Set(
1357
+ projection.actions.map(({ trace }) => contributionTraceKey(trace)),
1358
+ );
1359
+ const appliedTraces = new Set(applied.map(({ trace }) => contributionTraceKey(trace)));
1360
+ return actionTraces.size !== appliedTraces.size ||
1361
+ [...actionTraces].some((trace) => !appliedTraces.has(trace))
1362
+ ? "Projection summary traces do not match projection actions"
1363
+ : undefined;
1364
+ })();
1365
+ };
1366
+
1367
+ const validateProjectionPlan = ({ plan, contextPlan }) => {
1368
+ const contextIssue = canonicalContextIssue(contextPlan);
1369
+ if (contextIssue !== undefined) {
1370
+ throw new Error(`Supplied harness projection plan requires canonical context: ${contextIssue}`);
1371
+ }
1372
+ if (plan.contextPlanVersion !== contextPlanVersion(contextPlan)) {
1373
+ throw new Error("Supplied harness projection plan context version does not match");
1374
+ }
1375
+ const adaptersById = new Map(adapters.map((adapter) => [adapter.matrix.adapter.id, adapter]));
1376
+ const ids = plan.projections.map((projection) => projection?.matrix?.adapter?.id);
1377
+ if (
1378
+ ids.length !== adapters.length ||
1379
+ new Set(ids).size !== ids.length ||
1380
+ ids.some((id) => !adaptersById.has(id))
1381
+ ) {
1382
+ throw new Error(
1383
+ "Supplied harness projection plan must contain each known adapter exactly once",
1384
+ );
1385
+ }
1386
+ for (const projection of plan.projections) {
1387
+ const expected = adaptersById.get(projection.matrix.adapter.id);
1388
+ if (
1389
+ projection.matrix.adapter.version !== expected.matrix.adapter.version ||
1390
+ projection.matrix.matrixVersion !== expected.matrix.matrixVersion
1391
+ ) {
1392
+ throw new Error(
1393
+ `Supplied harness projection matrix mismatch: ${projection.matrix.adapter.id}`,
1394
+ );
1395
+ }
1396
+ if (
1397
+ !Array.isArray(projection.actions) ||
1398
+ new Set(projection.actions.map((action) => action?.id)).size !== projection.actions.length ||
1399
+ projection.actions.some(
1400
+ (action) =>
1401
+ !isObject(action) ||
1402
+ !isNonEmptyString(action.id) ||
1403
+ !harnessActionOperations.has(action.operation) ||
1404
+ hasInvalidActionPaths(action) ||
1405
+ !isObject(action.trace) ||
1406
+ !actionTraceMatches({ trace: action.trace, plan, projection, contextPlan }),
1407
+ )
1408
+ ) {
1409
+ throw new Error(
1410
+ `Supplied harness projection actions are invalid: ${projection.matrix.adapter.id}`,
1411
+ );
1412
+ }
1413
+ const summaryIssue = projectionSummaryIssue({
1414
+ summary: projection.summary,
1415
+ plan,
1416
+ projection,
1417
+ contextPlan,
1418
+ });
1419
+ if (summaryIssue !== undefined) {
1420
+ throw new Error(`${summaryIssue}: ${projection.matrix.adapter.id}`);
1421
+ }
1422
+ const canonical = normalizeProjection(projectSafely(expected, contextPlan));
1423
+ if (
1424
+ JSON.stringify(projection.actions) !== JSON.stringify(canonical.actions) ||
1425
+ JSON.stringify(projection.summary) !== JSON.stringify(canonical.summary)
1426
+ ) {
1427
+ throw new Error(
1428
+ `Supplied harness projection is noncanonical: ${projection.matrix.adapter.id}`,
1429
+ );
1430
+ }
1431
+ }
1432
+ return plan;
1433
+ };
1434
+
1435
+ const exactKeys = (value, keys) =>
1436
+ isObject(value) &&
1437
+ Object.keys(value).length === keys.length &&
1438
+ Object.keys(value).every((key) => keys.includes(key));
1439
+
1440
+ const isNonEmptyString = (value) => typeof value === "string" && value.length > 0;
1441
+ const isOrder = (value) => Number.isInteger(value) && value >= 0;
1442
+ const contributionKinds = new Set([
1443
+ "skill",
1444
+ "scoped-prompt",
1445
+ "lifecycle-hook",
1446
+ "tool-configuration",
1447
+ "subagent-template",
1448
+ ]);
1449
+
1450
+ const identityIssue = (identity) =>
1451
+ exactKeys(identity, ["id", "version"]) &&
1452
+ isNonEmptyString(identity.id) &&
1453
+ isNonEmptyString(identity.version)
1454
+ ? undefined
1455
+ : "Context contribution identity is invalid";
1456
+
1457
+ const provenanceIssue = (provenance) =>
1458
+ exactKeys(provenance, ["source", "revision"]) &&
1459
+ isNonEmptyString(provenance.source) &&
1460
+ isNonEmptyString(provenance.revision)
1461
+ ? undefined
1462
+ : "Context contribution provenance is invalid";
1463
+
1464
+ const compatibilityIssue = (compatibility) =>
1465
+ Array.isArray(compatibility) &&
1466
+ compatibility.every(
1467
+ (entry) =>
1468
+ exactKeys(entry, ["id", "versionRange"]) &&
1469
+ isNonEmptyString(entry.id) &&
1470
+ isNonEmptyString(entry.versionRange),
1471
+ )
1472
+ ? undefined
1473
+ : "Context contribution compatibility is invalid";
1474
+
1475
+ const contributionIssue = (contribution) => {
1476
+ if (
1477
+ !exactKeys(contribution, [
1478
+ "kind",
1479
+ "identity",
1480
+ "provenance",
1481
+ "compatibility",
1482
+ "references",
1483
+ "order",
1484
+ ])
1485
+ ) {
1486
+ return "Context contribution fields are invalid";
1487
+ }
1488
+ return (
1489
+ (!contributionKinds.has(contribution.kind)
1490
+ ? "Context contribution kind is invalid"
1491
+ : undefined) ??
1492
+ identityIssue(contribution.identity) ??
1493
+ provenanceIssue(contribution.provenance) ??
1494
+ compatibilityIssue(contribution.compatibility) ??
1495
+ (!Array.isArray(contribution.references) || !contribution.references.every(isNonEmptyString)
1496
+ ? "Context contribution references are invalid"
1497
+ : undefined) ??
1498
+ (!isOrder(contribution.order) ? "Context contribution order is invalid" : undefined)
1499
+ );
1500
+ };
1501
+
1502
+ const scopeIssue = (scope) => {
1503
+ if (!exactKeys(scope, ["id", "packs", "contributions"]) || !isNonEmptyString(scope.id)) {
1504
+ return "Context scope fields are invalid";
1505
+ }
1506
+ if (
1507
+ !Array.isArray(scope.packs) ||
1508
+ !scope.packs.every(
1509
+ (pack) =>
1510
+ exactKeys(pack, ["id", "order"]) && isNonEmptyString(pack.id) && isOrder(pack.order),
1511
+ )
1512
+ ) {
1513
+ return `Context scope ${scope.id} packs are invalid`;
1514
+ }
1515
+ if (!Array.isArray(scope.contributions)) {
1516
+ return `Context scope ${scope.id} contributions must be an array`;
1517
+ }
1518
+ for (const contribution of scope.contributions) {
1519
+ const issue = contributionIssue(contribution);
1520
+ if (issue !== undefined) {
1521
+ return `${issue} in scope ${scope.id}`;
1522
+ }
1523
+ }
1524
+ return undefined;
1525
+ };
1526
+
1527
+ function contextPlanIssue(contextPlan) {
1528
+ if (!exactKeys(contextPlan, ["version", "scopes"])) {
1529
+ return "Canonical context plan fields are invalid";
1530
+ }
1531
+ if (contextPlan.version !== "1" || !Array.isArray(contextPlan.scopes)) {
1532
+ return "Canonical context plan version or scopes are invalid";
1533
+ }
1534
+ for (const scope of contextPlan.scopes) {
1535
+ const issue = scopeIssue(scope);
1536
+ if (issue !== undefined) {
1537
+ return issue;
1538
+ }
1539
+ }
1540
+ return undefined;
1541
+ }
1542
+
1543
+ function subagentManifestIssue(contextPlan) {
1544
+ if (!Array.isArray(contextPlan?.scopes)) {
1545
+ return undefined;
1546
+ }
1547
+ const planned = contextPlan.scopes
1548
+ .flatMap((scope) => scope.contributions ?? [])
1549
+ .filter((contribution) => contribution.kind === "subagent-template")
1550
+ .map((contribution) => ({
1551
+ id: contribution.identity.id,
1552
+ references: [...new Set(contribution.references)].toSorted(),
1553
+ }))
1554
+ .toSorted((left, right) => left.id.localeCompare(right.id));
1555
+ if (planned.length === 0) {
1556
+ return undefined;
1557
+ }
1558
+ const authored = agents
1559
+ .map((agent) => ({
1560
+ id: agent.name,
1561
+ references: getSkillNames(agent).toSorted(),
1562
+ }))
1563
+ .toSorted((left, right) => left.id.localeCompare(right.id));
1564
+ return JSON.stringify(planned) === JSON.stringify(authored)
1565
+ ? undefined
1566
+ : "Subagent manifest diverges from canonical context plan; run scaffold update to reconcile it";
1567
+ }
1568
+
1569
+ const canonicalContextIssue = (contextPlan) =>
1570
+ contextPlanIssue(contextPlan) ?? subagentManifestIssue(contextPlan);
1571
+
1572
+ const contextPlanVersion = (contextPlan) =>
1573
+ isObject(contextPlan) && typeof contextPlan.version === "string"
1574
+ ? contextPlan.version
1575
+ : "unknown";
1576
+
1577
+ async function main() {
1578
+ try {
1579
+ const previousReceipt = JSON.parse(await readFile(projectionReceiptPath, "utf8"));
1580
+ previousCopyFallbacks = Array.isArray(previousReceipt.copyFallbacks)
1581
+ ? previousReceipt.copyFallbacks.filter(
1582
+ (copy) =>
1583
+ isObject(copy) &&
1584
+ typeof copy.source === "string" &&
1585
+ typeof copy.target === "string" &&
1586
+ typeof copy.digest === "string",
1587
+ )
1588
+ : [];
1589
+ } catch {
1590
+ previousCopyFallbacks = [];
1591
+ }
1592
+ const loadedContextPlan = await readContextPlan();
1593
+ const loadedProjectionPlan = await readProjectionPlan();
1594
+ const application = await prepareHarnessApplication();
1595
+ if (!loadedContextPlan.exists && !loadedProjectionPlan.exists) {
1596
+ await materializeLegacyHarnesses(application);
1597
+ return;
1598
+ }
1599
+ const contextPlan = loadedContextPlan.value;
1600
+ const suppliedProjectionPlan = loadedProjectionPlan.exists
1601
+ ? validateProjectionPlan({ plan: loadedProjectionPlan.value, contextPlan })
1602
+ : undefined;
1603
+ const projected =
1604
+ suppliedProjectionPlan !== undefined
1605
+ ? suppliedProjectionPlan.projections.map((projection) => {
1606
+ const adapter = adapters.find(
1607
+ ({ matrix }) => matrix.adapter.id === projection.matrix.adapter.id,
1608
+ );
1609
+ if (adapter === undefined) throw new Error("Validated projection adapter is missing");
1610
+ return {
1611
+ adapter,
1612
+ projection: withLifecycleHookReconciliation(
1613
+ adapter,
1614
+ contextPlan,
1615
+ withManagedAgentCleanup(adapter, contextPlan, {
1616
+ actions: projection.actions,
1617
+ summary: projection.summary,
1618
+ }),
1619
+ ),
1620
+ };
1621
+ })
1622
+ : adapters.map((adapter) => ({
1623
+ adapter,
1624
+ projection: withLifecycleHookReconciliation(
1625
+ adapter,
1626
+ contextPlan,
1627
+ withManagedAgentCleanup(adapter, contextPlan, projectSafely(adapter, contextPlan)),
1628
+ ),
1629
+ }));
1630
+ const applied = [];
1631
+
1632
+ for (const entry of projected) {
1633
+ const applicationProjection = await prepareProjectionApplication(entry.projection);
1634
+ const summary = await applyProjection({
1635
+ projection: applicationProjection,
1636
+ filesystem: { apply: (action) => applyHarnessAction(action, application) },
1637
+ });
1638
+ applied.push(
1639
+ projectionEvidence({
1640
+ adapter: entry.adapter,
1641
+ projection: applicationProjection,
1642
+ summary,
1643
+ }),
1644
+ );
1645
+ }
1646
+
1647
+ const receipt = {
1648
+ version: "1",
1649
+ contextPlanVersion: contextPlanVersion(contextPlan),
1650
+ status: receiptStatus(applied),
1651
+ projections: applied,
1652
+ copyFallbacks: [...currentCopyFallbacks.values()].toSorted((left, right) =>
1653
+ copyFallbackKey(left).localeCompare(copyFallbackKey(right)),
1654
+ ),
1655
+ };
1656
+ await mkdir(path.dirname(projectionReceiptPath), { recursive: true });
1657
+ await writeFile(projectionReceiptPath, encodeJson(receipt), "utf8");
1658
+ if (receipt.status === "failure") {
1659
+ throw new Error(
1660
+ `Harness projection failed; inspect ${path.relative(repoRoot, projectionReceiptPath)}`,
1661
+ );
1662
+ }
1663
+ }
1664
+
585
1665
  await main();