cc-codeconductor 1.6.0 → 1.7.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 (126) hide show
  1. package/README.md +22 -7
  2. package/dist/core/compilation/compile-checker.d.ts +3 -2
  3. package/dist/core/goal/goal-state.d.ts +1 -0
  4. package/dist/core/orchestrator/runtime-orchestrator.d.ts +1 -0
  5. package/dist/core/queue/lock.d.ts +3 -0
  6. package/dist/core/verification/rdd-receipt.d.ts +25 -0
  7. package/dist/core/verification/verification-runner.d.ts +27 -2
  8. package/dist/index.js +1501 -782
  9. package/dist/library.js +420 -142
  10. package/dist/validation/schemas.d.ts +65 -26
  11. package/docs/generated/cli.md +8 -0
  12. package/package.json +2 -1
  13. package/presets/agy/AGENTS.md +1 -1
  14. package/presets/agy/scripts/invoke-hook.cjs +43 -24
  15. package/presets/agy/skills/backlog/SKILL.md +1 -1
  16. package/presets/agy/skills/cc-feature/SKILL.md +17 -16
  17. package/presets/agy/skills/cc-fix/SKILL.md +28 -34
  18. package/presets/agy/skills/cc-spec-mutation/SKILL.md +1 -1
  19. package/presets/agy/skills/cc-tdd-cycle/SKILL.md +1 -1
  20. package/presets/agy/skills/evaluation/SKILL.md +1 -1
  21. package/presets/agy/skills/openspec/SKILL.md +10 -6
  22. package/presets/agy/skills/testing-tdd/SKILL.md +3 -3
  23. package/presets/agy/workflows/cc-api-contract.md +1 -1
  24. package/presets/agy/workflows/cc-ask.md +2 -2
  25. package/presets/agy/workflows/cc-council.md +2 -0
  26. package/presets/agy/workflows/cc-db-migration.md +1 -1
  27. package/presets/agy/workflows/cc-feature.md +1 -1
  28. package/presets/agy/workflows/cc-fix.md +1 -1
  29. package/presets/agy/workflows/cc-iterative.md +1 -1
  30. package/presets/agy/workflows/cc-odd.md +2 -2
  31. package/presets/agy/workflows/cc-openspec.md +1 -1
  32. package/presets/agy/workflows/cc-spec-mutation.md +2 -2
  33. package/presets/agy/workflows/cc-tdd-cycle.md +2 -2
  34. package/presets/claude/CLAUDE.md +1 -1
  35. package/presets/claude/commands/cc/api-contract.md +1 -1
  36. package/presets/claude/commands/cc/ask.md +2 -2
  37. package/presets/claude/commands/cc/council.md +2 -83
  38. package/presets/claude/commands/cc/db-migration.md +1 -1
  39. package/presets/claude/commands/cc/feature.md +1 -1
  40. package/presets/claude/commands/cc/fix.md +1 -1
  41. package/presets/claude/commands/cc/iterative.md +1 -1
  42. package/presets/claude/commands/cc/odd.md +2 -2
  43. package/presets/claude/commands/cc/openspec.md +5 -5
  44. package/presets/claude/commands/cc/spec-mutation.md +2 -2
  45. package/presets/claude/commands/cc/tdd-cycle.md +3 -3
  46. package/presets/claude/settings.json +6 -101
  47. package/presets/claude/skills/backlog/SKILL.md +1 -1
  48. package/presets/claude/skills/evaluation/SKILL.md +1 -1
  49. package/presets/claude/skills/openspec/SKILL.md +10 -6
  50. package/presets/claude/skills/testing-tdd/SKILL.md +3 -3
  51. package/presets/codex/AGENTS.md +1 -1
  52. package/presets/codex/commands/cc-ask.md +2 -2
  53. package/presets/codex/skills/backlog/SKILL.md +1 -1
  54. package/presets/codex/skills/cc-api-contract/SKILL.md +1 -1
  55. package/presets/codex/skills/cc-council/SKILL.md +2 -93
  56. package/presets/codex/skills/cc-db-migration/SKILL.md +1 -1
  57. package/presets/codex/skills/cc-feature/SKILL.md +1 -1
  58. package/presets/codex/skills/cc-fix/SKILL.md +1 -1
  59. package/presets/codex/skills/cc-iterative/SKILL.md +1 -1
  60. package/presets/codex/skills/cc-odd/SKILL.md +2 -2
  61. package/presets/codex/skills/cc-openspec/SKILL.md +10 -8
  62. package/presets/codex/skills/cc-spec-mutation/SKILL.md +2 -2
  63. package/presets/codex/skills/cc-tdd-cycle/SKILL.md +2 -2
  64. package/presets/codex/skills/django-testing/SKILL.md +1 -1
  65. package/presets/codex/skills/evaluation/SKILL.md +1 -1
  66. package/presets/codex/skills/openspec/SKILL.md +10 -6
  67. package/presets/codex/skills/python-django-stack/SKILL.md +1 -1
  68. package/presets/codex/skills/testing-tdd/SKILL.md +3 -3
  69. package/presets/cursor/AGENTS.md +1 -1
  70. package/presets/cursor/commands/cc/api-contract.md +1 -1
  71. package/presets/cursor/commands/cc/ask.md +2 -2
  72. package/presets/cursor/commands/cc/council.md +2 -83
  73. package/presets/cursor/commands/cc/db-migration.md +1 -1
  74. package/presets/cursor/commands/cc/feature.md +1 -1
  75. package/presets/cursor/commands/cc/fix.md +1 -1
  76. package/presets/cursor/commands/cc/iterative.md +1 -1
  77. package/presets/cursor/commands/cc/odd.md +2 -2
  78. package/presets/cursor/commands/cc/openspec.md +10 -8
  79. package/presets/cursor/commands/cc/spec-mutation.md +2 -2
  80. package/presets/cursor/commands/cc/tdd-cycle.md +2 -2
  81. package/presets/cursor/skills/backlog/SKILL.md +1 -1
  82. package/presets/cursor/skills/evaluation/SKILL.md +1 -1
  83. package/presets/cursor/skills/openspec/SKILL.md +10 -6
  84. package/presets/cursor/skills/testing-tdd/SKILL.md +3 -3
  85. package/presets/gemini/GEMINI.md +1 -1
  86. package/presets/gemini/commands/cc/api-contract.toml +1 -1
  87. package/presets/gemini/commands/cc/ask.toml +2 -2
  88. package/presets/gemini/commands/cc/council.toml +2 -83
  89. package/presets/gemini/commands/cc/db-migration.toml +1 -1
  90. package/presets/gemini/commands/cc/feature.toml +1 -1
  91. package/presets/gemini/commands/cc/fix.toml +1 -1
  92. package/presets/gemini/commands/cc/iterative.toml +1 -1
  93. package/presets/gemini/commands/cc/odd.toml +2 -2
  94. package/presets/gemini/commands/cc/openspec.toml +10 -8
  95. package/presets/gemini/commands/cc/spec-mutation.toml +2 -2
  96. package/presets/gemini/commands/cc/tdd-cycle.toml +2 -2
  97. package/presets/muse/AGENTS.md +1 -1
  98. package/presets/opencode/agents/implementer.md +1 -1
  99. package/presets/opencode/agents/tester.md +1 -1
  100. package/presets/opencode/commands/cc-api-contract.md +1 -1
  101. package/presets/opencode/commands/cc-ask.md +2 -2
  102. package/presets/opencode/commands/cc-council.md +2 -83
  103. package/presets/opencode/commands/cc-db-migration.md +1 -1
  104. package/presets/opencode/commands/cc-feature.md +1 -1
  105. package/presets/opencode/commands/cc-fix.md +1 -1
  106. package/presets/opencode/commands/cc-iterative.md +1 -1
  107. package/presets/opencode/commands/cc-odd.md +2 -2
  108. package/presets/opencode/commands/cc-openspec.md +2 -2
  109. package/presets/opencode/commands/cc-spec-mutation.md +2 -2
  110. package/presets/opencode/commands/cc-tdd-cycle.md +2 -2
  111. package/presets/opencode/prompts/v1.0.0/implementer.md +1 -1
  112. package/presets/opencode/prompts/v1.0.0/tester.md +1 -1
  113. package/presets/opencode/skills/backlog/SKILL.md +1 -1
  114. package/presets/opencode/skills/django-testing/SKILL.md +1 -0
  115. package/presets/opencode/skills/evaluation/SKILL.md +1 -1
  116. package/presets/opencode/skills/openspec/SKILL.md +10 -6
  117. package/presets/opencode/skills/python-django-stack/SKILL.md +1 -0
  118. package/presets/opencode/skills/python-fastapi-stack/SKILL.md +1 -0
  119. package/presets/opencode/skills/spring-boot-kotlin/SKILL.md +1 -0
  120. package/presets/opencode/skills/sqlalchemy/SKILL.md +1 -0
  121. package/presets/opencode/skills/testing-tdd/SKILL.md +3 -3
  122. package/presets/pi/AGENTS.md +1 -1
  123. package/presets/shared/invoke-hook.cjs +43 -24
  124. package/src/presets/manifests/claude.yml +1 -1
  125. package/src/presets/shared-skills.yml +30 -0
  126. package/src/presets/targets/pi.yml +1 -1
package/dist/index.js CHANGED
@@ -72,7 +72,7 @@ var package_default;
72
72
  var init_package = __esm(() => {
73
73
  package_default = {
74
74
  name: "cc-codeconductor",
75
- version: "1.6.0",
75
+ version: "1.7.0",
76
76
  description: "A multi-agent orchestration framework for AI-assisted software engineering workflows.",
77
77
  keywords: [
78
78
  "ai",
@@ -126,6 +126,7 @@ var init_package = __esm(() => {
126
126
  "test:fast": "bun run scripts/test-fast.ts",
127
127
  typecheck: "tsc --noEmit",
128
128
  lint: "bun run scripts/lint.ts",
129
+ "check:council-redirect": "bun run scripts/check-council-redirect.ts",
129
130
  "check:coverage": "bun run scripts/check-coverage.ts",
130
131
  "check:prompt-changelog": "bun run scripts/check-prompt-changelog.ts",
131
132
  "check:drift": "bun run scripts/check-drift.ts",
@@ -4178,6 +4179,27 @@ function formatUsage(usage, bin = resolveCliBin()) {
4178
4179
  }
4179
4180
  var init_cli_bin = () => {};
4180
4181
 
4182
+ // src/core/presets/package-paths.ts
4183
+ var exports_package_paths = {};
4184
+ __export(exports_package_paths, {
4185
+ PACKAGE_ROOT: () => PACKAGE_ROOT,
4186
+ POLICY_PATH: () => POLICY_PATH,
4187
+ ROOT_PRESETS_DIR: () => ROOT_PRESETS_DIR,
4188
+ SKILLS_REGISTRY_PATH: () => SKILLS_REGISTRY_PATH,
4189
+ SRC_PRESETS_DIR: () => SRC_PRESETS_DIR
4190
+ });
4191
+ import { dirname, resolve, sep } from "node:path";
4192
+ import { fileURLToPath } from "node:url";
4193
+ var moduleDir, PACKAGE_ROOT, SRC_PRESETS_DIR, ROOT_PRESETS_DIR, POLICY_PATH, SKILLS_REGISTRY_PATH;
4194
+ var init_package_paths = __esm(() => {
4195
+ moduleDir = dirname(fileURLToPath(import.meta.url));
4196
+ PACKAGE_ROOT = moduleDir.endsWith(`${sep}dist`) ? resolve(moduleDir, "..") : resolve(moduleDir, "..", "..", "..");
4197
+ SRC_PRESETS_DIR = resolve(PACKAGE_ROOT, "src", "presets");
4198
+ ROOT_PRESETS_DIR = resolve(PACKAGE_ROOT, "presets");
4199
+ POLICY_PATH = resolve(PACKAGE_ROOT, "policy.yml");
4200
+ SKILLS_REGISTRY_PATH = resolve(PACKAGE_ROOT, "skills-registry.json");
4201
+ });
4202
+
4181
4203
  // node_modules/yaml/dist/nodes/identity.js
4182
4204
  var require_identity = __commonJS(function(exports) {
4183
4205
  var ALIAS = Symbol.for("yaml.alias");
@@ -7856,10 +7878,10 @@ var require_resolve_block_map = __commonJS(function(exports) {
7856
7878
  let offset = bm.offset;
7857
7879
  let commentEnd = null;
7858
7880
  for (const collItem of bm.items) {
7859
- const { start, key, sep, value } = collItem;
7881
+ const { start, key, sep: sep2, value } = collItem;
7860
7882
  const keyProps = resolveProps.resolveProps(start, {
7861
7883
  indicator: "explicit-key-ind",
7862
- next: key ?? sep?.[0],
7884
+ next: key ?? sep2?.[0],
7863
7885
  offset,
7864
7886
  onError,
7865
7887
  parentIndent: bm.indent,
@@ -7873,7 +7895,7 @@ var require_resolve_block_map = __commonJS(function(exports) {
7873
7895
  else if ("indent" in key && key.indent !== bm.indent)
7874
7896
  onError(offset, "BAD_INDENT", startColMsg);
7875
7897
  }
7876
- if (!keyProps.anchor && !keyProps.tag && !sep) {
7898
+ if (!keyProps.anchor && !keyProps.tag && !sep2) {
7877
7899
  commentEnd = keyProps.end;
7878
7900
  if (keyProps.comment) {
7879
7901
  if (map.comment)
@@ -7898,7 +7920,7 @@ var require_resolve_block_map = __commonJS(function(exports) {
7898
7920
  ctx.atKey = false;
7899
7921
  if (utilMapIncludes.mapIncludes(ctx, map.items, keyNode))
7900
7922
  onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique");
7901
- const valueProps = resolveProps.resolveProps(sep ?? [], {
7923
+ const valueProps = resolveProps.resolveProps(sep2 ?? [], {
7902
7924
  indicator: "map-value-ind",
7903
7925
  next: value,
7904
7926
  offset: keyNode.range[2],
@@ -7914,7 +7936,7 @@ var require_resolve_block_map = __commonJS(function(exports) {
7914
7936
  if (ctx.options.strict && keyProps.start < valueProps.found.offset - 1024)
7915
7937
  onError(keyNode.range, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit block mapping key");
7916
7938
  }
7917
- const valueNode = value ? composeNode(ctx, value, valueProps, onError) : composeEmptyNode(ctx, offset, sep, null, valueProps, onError);
7939
+ const valueNode = value ? composeNode(ctx, value, valueProps, onError) : composeEmptyNode(ctx, offset, sep2, null, valueProps, onError);
7918
7940
  if (ctx.schema.compat)
7919
7941
  utilFlowIndentCheck.flowIndentCheck(bm.indent, value, onError);
7920
7942
  offset = valueNode.range[2];
@@ -8000,7 +8022,7 @@ var require_resolve_end = __commonJS(function(exports) {
8000
8022
  let comment = "";
8001
8023
  if (end) {
8002
8024
  let hasSpace = false;
8003
- let sep = "";
8025
+ let sep2 = "";
8004
8026
  for (const token of end) {
8005
8027
  const { source, type } = token;
8006
8028
  switch (type) {
@@ -8014,13 +8036,13 @@ var require_resolve_end = __commonJS(function(exports) {
8014
8036
  if (!comment)
8015
8037
  comment = cb;
8016
8038
  else
8017
- comment += sep + cb;
8018
- sep = "";
8039
+ comment += sep2 + cb;
8040
+ sep2 = "";
8019
8041
  break;
8020
8042
  }
8021
8043
  case "newline":
8022
8044
  if (comment)
8023
- sep += source;
8045
+ sep2 += source;
8024
8046
  hasSpace = true;
8025
8047
  break;
8026
8048
  default:
@@ -8060,18 +8082,18 @@ var require_resolve_flow_collection = __commonJS(function(exports) {
8060
8082
  let offset = fc.offset + fc.start.source.length;
8061
8083
  for (let i = 0;i < fc.items.length; ++i) {
8062
8084
  const collItem = fc.items[i];
8063
- const { start, key, sep, value } = collItem;
8085
+ const { start, key, sep: sep2, value } = collItem;
8064
8086
  const props = resolveProps.resolveProps(start, {
8065
8087
  flow: fcName,
8066
8088
  indicator: "explicit-key-ind",
8067
- next: key ?? sep?.[0],
8089
+ next: key ?? sep2?.[0],
8068
8090
  offset,
8069
8091
  onError,
8070
8092
  parentIndent: fc.indent,
8071
8093
  startOnNewline: false
8072
8094
  });
8073
8095
  if (!props.found) {
8074
- if (!props.anchor && !props.tag && !sep && !value) {
8096
+ if (!props.anchor && !props.tag && !sep2 && !value) {
8075
8097
  if (i === 0 && props.comma)
8076
8098
  onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`);
8077
8099
  else if (i < fc.items.length - 1)
@@ -8123,8 +8145,8 @@ var require_resolve_flow_collection = __commonJS(function(exports) {
8123
8145
  }
8124
8146
  }
8125
8147
  }
8126
- if (!isMap && !sep && !props.found) {
8127
- const valueNode = value ? composeNode(ctx, value, props, onError) : composeEmptyNode(ctx, props.end, sep, null, props, onError);
8148
+ if (!isMap && !sep2 && !props.found) {
8149
+ const valueNode = value ? composeNode(ctx, value, props, onError) : composeEmptyNode(ctx, props.end, sep2, null, props, onError);
8128
8150
  coll.items.push(valueNode);
8129
8151
  offset = valueNode.range[2];
8130
8152
  if (isBlock(value))
@@ -8136,7 +8158,7 @@ var require_resolve_flow_collection = __commonJS(function(exports) {
8136
8158
  if (isBlock(key))
8137
8159
  onError(keyNode.range, "BLOCK_IN_FLOW", blockMsg);
8138
8160
  ctx.atKey = false;
8139
- const valueProps = resolveProps.resolveProps(sep ?? [], {
8161
+ const valueProps = resolveProps.resolveProps(sep2 ?? [], {
8140
8162
  flow: fcName,
8141
8163
  indicator: "map-value-ind",
8142
8164
  next: value,
@@ -8147,8 +8169,8 @@ var require_resolve_flow_collection = __commonJS(function(exports) {
8147
8169
  });
8148
8170
  if (valueProps.found) {
8149
8171
  if (!isMap && !props.found && ctx.options.strict) {
8150
- if (sep)
8151
- for (const st of sep) {
8172
+ if (sep2)
8173
+ for (const st of sep2) {
8152
8174
  if (st === valueProps.found)
8153
8175
  break;
8154
8176
  if (st.type === "newline") {
@@ -8165,7 +8187,7 @@ var require_resolve_flow_collection = __commonJS(function(exports) {
8165
8187
  else
8166
8188
  onError(valueProps.start, "MISSING_CHAR", `Missing , or : between ${fcName} items`);
8167
8189
  }
8168
- const valueNode = value ? composeNode(ctx, value, valueProps, onError) : valueProps.found ? composeEmptyNode(ctx, valueProps.end, sep, null, valueProps, onError) : null;
8190
+ const valueNode = value ? composeNode(ctx, value, valueProps, onError) : valueProps.found ? composeEmptyNode(ctx, valueProps.end, sep2, null, valueProps, onError) : null;
8169
8191
  if (valueNode) {
8170
8192
  if (isBlock(value))
8171
8193
  onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg);
@@ -8342,7 +8364,7 @@ var require_resolve_block_scalar = __commonJS(function(exports) {
8342
8364
  chompStart = i + 1;
8343
8365
  }
8344
8366
  let value = "";
8345
- let sep = "";
8367
+ let sep2 = "";
8346
8368
  let prevMoreIndented = false;
8347
8369
  for (let i = 0;i < contentStart; ++i)
8348
8370
  value += lines[i][0].slice(trimIndent) + `
@@ -8360,33 +8382,33 @@ var require_resolve_block_scalar = __commonJS(function(exports) {
8360
8382
  indent = "";
8361
8383
  }
8362
8384
  if (type === Scalar.Scalar.BLOCK_LITERAL) {
8363
- value += sep + indent.slice(trimIndent) + content;
8364
- sep = `
8385
+ value += sep2 + indent.slice(trimIndent) + content;
8386
+ sep2 = `
8365
8387
  `;
8366
8388
  } else if (indent.length > trimIndent || content[0] === "\t") {
8367
- if (sep === " ")
8368
- sep = `
8389
+ if (sep2 === " ")
8390
+ sep2 = `
8369
8391
  `;
8370
- else if (!prevMoreIndented && sep === `
8392
+ else if (!prevMoreIndented && sep2 === `
8371
8393
  `)
8372
- sep = `
8394
+ sep2 = `
8373
8395
 
8374
8396
  `;
8375
- value += sep + indent.slice(trimIndent) + content;
8376
- sep = `
8397
+ value += sep2 + indent.slice(trimIndent) + content;
8398
+ sep2 = `
8377
8399
  `;
8378
8400
  prevMoreIndented = true;
8379
8401
  } else if (content === "") {
8380
- if (sep === `
8402
+ if (sep2 === `
8381
8403
  `)
8382
8404
  value += `
8383
8405
  `;
8384
8406
  else
8385
- sep = `
8407
+ sep2 = `
8386
8408
  `;
8387
8409
  } else {
8388
- value += sep + content;
8389
- sep = " ";
8410
+ value += sep2 + content;
8411
+ sep2 = " ";
8390
8412
  prevMoreIndented = false;
8391
8413
  }
8392
8414
  }
@@ -8567,27 +8589,27 @@ var require_resolve_flow_scalar = __commonJS(function(exports) {
8567
8589
  if (!match)
8568
8590
  return source;
8569
8591
  let res = match[1];
8570
- let sep = " ";
8592
+ let sep2 = " ";
8571
8593
  let pos = first.lastIndex;
8572
8594
  line.lastIndex = pos;
8573
8595
  while (match = line.exec(source)) {
8574
8596
  if (match[1] === "") {
8575
- if (sep === `
8597
+ if (sep2 === `
8576
8598
  `)
8577
- res += sep;
8599
+ res += sep2;
8578
8600
  else
8579
- sep = `
8601
+ sep2 = `
8580
8602
  `;
8581
8603
  } else {
8582
- res += sep + match[1];
8583
- sep = " ";
8604
+ res += sep2 + match[1];
8605
+ sep2 = " ";
8584
8606
  }
8585
8607
  pos = line.lastIndex;
8586
8608
  }
8587
8609
  const last = /[ \t]*(.*)/sy;
8588
8610
  last.lastIndex = pos;
8589
8611
  match = last.exec(source);
8590
- return res + sep + (match?.[1] ?? "");
8612
+ return res + sep2 + (match?.[1] ?? "");
8591
8613
  }
8592
8614
  function doubleQuotedValue(source, onError) {
8593
8615
  let res = "";
@@ -9368,14 +9390,14 @@ var require_cst_stringify = __commonJS(function(exports) {
9368
9390
  }
9369
9391
  }
9370
9392
  }
9371
- function stringifyItem({ start, key, sep, value }) {
9393
+ function stringifyItem({ start, key, sep: sep2, value }) {
9372
9394
  let res = "";
9373
9395
  for (const st of start)
9374
9396
  res += st.source;
9375
9397
  if (key)
9376
9398
  res += stringifyToken(key);
9377
- if (sep)
9378
- for (const st of sep)
9399
+ if (sep2)
9400
+ for (const st of sep2)
9379
9401
  res += st.source;
9380
9402
  if (value)
9381
9403
  res += stringifyToken(value);
@@ -10523,18 +10545,18 @@ var require_parser = __commonJS(function(exports) {
10523
10545
  if (this.type === "map-value-ind") {
10524
10546
  const prev = getPrevProps(this.peek(2));
10525
10547
  const start = getFirstKeyStartProps(prev);
10526
- let sep;
10548
+ let sep2;
10527
10549
  if (scalar.end) {
10528
- sep = scalar.end;
10529
- sep.push(this.sourceToken);
10550
+ sep2 = scalar.end;
10551
+ sep2.push(this.sourceToken);
10530
10552
  delete scalar.end;
10531
10553
  } else
10532
- sep = [this.sourceToken];
10554
+ sep2 = [this.sourceToken];
10533
10555
  const map = {
10534
10556
  type: "block-map",
10535
10557
  offset: scalar.offset,
10536
10558
  indent: scalar.indent,
10537
- items: [{ start, key: scalar, sep }]
10559
+ items: [{ start, key: scalar, sep: sep2 }]
10538
10560
  };
10539
10561
  this.onKeyLine = true;
10540
10562
  this.stack[this.stack.length - 1] = map;
@@ -10688,15 +10710,15 @@ var require_parser = __commonJS(function(exports) {
10688
10710
  } else if (isFlowToken(it.key) && !includesToken(it.sep, "newline")) {
10689
10711
  const start2 = getFirstKeyStartProps(it.start);
10690
10712
  const key = it.key;
10691
- const sep = it.sep;
10692
- sep.push(this.sourceToken);
10713
+ const sep2 = it.sep;
10714
+ sep2.push(this.sourceToken);
10693
10715
  delete it.key;
10694
10716
  delete it.sep;
10695
10717
  this.stack.push({
10696
10718
  type: "block-map",
10697
10719
  offset: this.offset,
10698
10720
  indent: this.indent,
10699
- items: [{ start: start2, key, sep }]
10721
+ items: [{ start: start2, key, sep: sep2 }]
10700
10722
  });
10701
10723
  } else if (start.length > 0) {
10702
10724
  it.sep = it.sep.concat(start, this.sourceToken);
@@ -10890,13 +10912,13 @@ var require_parser = __commonJS(function(exports) {
10890
10912
  const prev = getPrevProps(parent);
10891
10913
  const start = getFirstKeyStartProps(prev);
10892
10914
  fixFlowSeqItems(fc);
10893
- const sep = fc.end.splice(1, fc.end.length);
10894
- sep.push(this.sourceToken);
10915
+ const sep2 = fc.end.splice(1, fc.end.length);
10916
+ sep2.push(this.sourceToken);
10895
10917
  const map = {
10896
10918
  type: "block-map",
10897
10919
  offset: fc.offset,
10898
10920
  indent: fc.indent,
10899
- items: [{ start, key: fc, sep }]
10921
+ items: [{ start, key: fc, sep: sep2 }]
10900
10922
  };
10901
10923
  this.onKeyLine = true;
10902
10924
  this.stack[this.stack.length - 1] = map;
@@ -11277,6 +11299,7 @@ __export(exports_schemas, {
11277
11299
  TaskOutcomeSchema: () => TaskOutcomeSchema,
11278
11300
  TaskOutcomeSourceSchema: () => TaskOutcomeSourceSchema,
11279
11301
  TaskOutcomeStatusSchema: () => TaskOutcomeStatusSchema,
11302
+ TddValidationRecordSchema: () => TddValidationRecordSchema,
11280
11303
  TechnicalPlanOutputSchema: () => TechnicalPlanOutputSchema,
11281
11304
  TokenUsageSchema: () => TokenUsageSchema,
11282
11305
  ToolProviderNamesSchema: () => ToolProviderNamesSchema,
@@ -11448,7 +11471,7 @@ function validateProductEvent(data) {
11448
11471
  function validateSkillsRegistry(data) {
11449
11472
  return SkillsRegistrySchema.parse(data);
11450
11473
  }
11451
- var CouncilAgentSpecSchema, CouncilSpecSchema, ProjectProfileSchema, CompileCheckConfigSchema, LoopConfigSchema, CodeConductorConfigSchema, RunnerTargetSchema, InstallStrategySchema, ContainedRelativePathSchema, ManifestEntrySchema, InstallManifestSchema, ToolProviderNamesSchema, PermissionProviderNamesSchema, ModelConfigSchema, SkillFrontmatterSchema, CommandFrontmatterSchema, TargetCapabilitiesSchema, ContractTargetSchema, ContractFormatSchema, AgentContractSchema, CouncilFindingSchema, CouncilVerdictInputSchema, ConsensusConfigSchema, CouncilVerdictSchema, ClaudeAgentFileSchema, OpenCodeAgentFileSchema, SentryStackFrameSchema, SentryWebhookSchema, MemoryPointerSchema, MemoryIndexSchema, GoalTaskSchema, GoalGraphSchema, ConfidenceLevelSchema, ProductNodeTypeSchema, GraphRelationSchema, KnowledgeEntitySchema, DecisionSchema, EvidenceSchema, CanonicalTaskCardStatusSchema, CanonicalTaskCardSchema, ProductGraphNodeSchema, ProductGraphEdgeSchema, ProductGraphSchema, ProductMetaSchema, ProductEventTypeSchema, ProductEventSchema, OperationalStateSchema, StrategicMemorySchema, ImpactReportSchema, BusinessReviewOutputSchema, VerificationReportSchema, BacklogStatusSchema, BacklogTypeSchema, BacklogPrioritySchema, BacklogGlobalSchema, BacklogItemSchema, BacklogDocumentSchema, OpenspecTaskCardPhaseSchema, OpenspecTaskCardStatusSchema, OpenspecTaskCardSchema, OpenspecStateSchema, SpecAnalyzeFindingSchema, SpecAnalyzeReportSchema, WorkflowCommandSchema, CcepOutputFormatSchema, CommandEnvelopeSchema, WorkflowPhaseSchema, WorkflowRiskRuleSchema, WorkflowProfileSchema, ExecutionContextSchema, PlannerOutputSchema, AgentArtifactSchema, AgentOutputSchema, ImplementerTestsSchema, ImplementerOutputSchema, ReviewAxisSchema, ReviewFindingSchema, ReviewerOutputSchema, TechnicalPlanOutputSchema, FixIntakeOutputSchema, ScorecardVerdictSchema, ScorecardCriterionIdSchema, ScorecardCriterionSchema, ScorecardRecordSchema, TaskOutcomeSourceSchema, TaskOutcomeStatusSchema, DeliveryRouteSchema, TokenUsageSchema, DeliveryTelemetrySchema, DeliveryLedgerTaskSchema, DeliveryLedgerSchema, HandoffEnvelopeSchema, RepoRelativePathSchema, DeliveryLedgerRequestSchema, TaskOutcomeSchema, HarnessComponentIdSchema, HarnessComponentLayerSchema, HarnessToggleKindSchema, HarnessCatalogEntrySchema, HarnessCatalogSchema, HarnessOverlaySchema, HarnessExperimentSchema, HarnessSuiteTaskSchema, HarnessSuiteSchema, EvaluationIndexSchema, ExecutionProfileNameSchema, ExecutionProfileSchema, SkillsRegistrySchema;
11474
+ var CouncilAgentSpecSchema, CouncilSpecSchema, ProjectProfileSchema, CompileCheckConfigSchema, LoopConfigSchema, CodeConductorConfigSchema, RunnerTargetSchema, InstallStrategySchema, ContainedRelativePathSchema, ManifestEntrySchema, InstallManifestSchema, ToolProviderNamesSchema, PermissionProviderNamesSchema, ModelConfigSchema, SkillFrontmatterSchema, CommandFrontmatterSchema, TargetCapabilitiesSchema, ContractTargetSchema, ContractFormatSchema, AgentContractSchema, CouncilFindingSchema, CouncilVerdictInputSchema, ConsensusConfigSchema, CouncilVerdictSchema, ClaudeAgentFileSchema, OpenCodeAgentFileSchema, SentryStackFrameSchema, SentryWebhookSchema, MemoryPointerSchema, MemoryIndexSchema, GoalTaskSchema, GoalGraphSchema, ConfidenceLevelSchema, ProductNodeTypeSchema, GraphRelationSchema, KnowledgeEntitySchema, DecisionSchema, EvidenceSchema, TddValidationRecordSchema, CanonicalTaskCardStatusSchema, CanonicalTaskCardSchema, ProductGraphNodeSchema, ProductGraphEdgeSchema, ProductGraphSchema, ProductMetaSchema, ProductEventTypeSchema, ProductEventSchema, OperationalStateSchema, StrategicMemorySchema, ImpactReportSchema, BusinessReviewOutputSchema, VerificationReportSchema, BacklogStatusSchema, BacklogTypeSchema, BacklogPrioritySchema, BacklogGlobalSchema, BacklogItemSchema, BacklogDocumentSchema, OpenspecTaskCardPhaseSchema, OpenspecTaskCardStatusSchema, OpenspecTaskCardSchema, OpenspecStateSchema, SpecAnalyzeFindingSchema, SpecAnalyzeReportSchema, WorkflowCommandSchema, CcepOutputFormatSchema, CommandEnvelopeSchema, WorkflowPhaseSchema, WorkflowRiskRuleSchema, WorkflowProfileSchema, ExecutionContextSchema, PlannerOutputSchema, AgentArtifactSchema, AgentOutputSchema, ImplementerTestsSchema, ImplementerOutputSchema, ReviewAxisSchema, ReviewFindingSchema, ReviewerOutputSchema, TechnicalPlanOutputSchema, FixIntakeOutputSchema, ScorecardVerdictSchema, ScorecardCriterionIdSchema, ScorecardCriterionSchema, ScorecardRecordSchema, TaskOutcomeSourceSchema, TaskOutcomeStatusSchema, DeliveryRouteSchema, TokenUsageSchema, DeliveryTelemetrySchema, DeliveryLedgerTaskSchema, DeliveryLedgerSchema, HandoffEnvelopeSchema, RepoRelativePathSchema, DeliveryLedgerRequestSchema, TaskOutcomeSchema, HarnessComponentIdSchema, HarnessComponentLayerSchema, HarnessToggleKindSchema, HarnessCatalogEntrySchema, HarnessCatalogSchema, HarnessOverlaySchema, HarnessExperimentSchema, HarnessSuiteTaskSchema, HarnessSuiteSchema, EvaluationIndexSchema, ExecutionProfileNameSchema, ExecutionProfileSchema, SkillsRegistrySchema;
11452
11475
  var init_schemas = __esm(() => {
11453
11476
  init_zod();
11454
11477
  init_runner_target();
@@ -11693,6 +11716,7 @@ var init_schemas = __esm(() => {
11693
11716
  title: exports_external.string(),
11694
11717
  type: exports_external.enum(["feature", "fix", "refactor", "test", "docs"]),
11695
11718
  risk: exports_external.enum(["low", "medium", "high"]),
11719
+ priority: exports_external.enum(["P0", "P1", "P2", "P3"]).optional(),
11696
11720
  status: exports_external.enum(["pending", "in-progress", "done", "blocked"]),
11697
11721
  depends_on: exports_external.array(exports_external.string()).optional().default([]),
11698
11722
  acceptance_criteria: exports_external.array(exports_external.string()),
@@ -11765,6 +11789,13 @@ var init_schemas = __esm(() => {
11765
11789
  summary: exports_external.string().optional(),
11766
11790
  data: exports_external.record(exports_external.string(), exports_external.unknown()).optional()
11767
11791
  });
11792
+ TddValidationRecordSchema = exports_external.object({
11793
+ taskId: exports_external.string().min(1),
11794
+ evidenceId: exports_external.string().min(1),
11795
+ receiptNonce: exports_external.string().regex(/^[0-9a-f]{32}$/),
11796
+ manifestHash: exports_external.string().regex(/^[0-9a-f]{64}$/),
11797
+ validatedAt: exports_external.string().datetime()
11798
+ }).strict();
11768
11799
  CanonicalTaskCardStatusSchema = exports_external.enum([
11769
11800
  "draft",
11770
11801
  "ready",
@@ -11829,6 +11860,7 @@ var init_schemas = __esm(() => {
11829
11860
  ProductEventTypeSchema = exports_external.enum([
11830
11861
  "task.started",
11831
11862
  "task.completed",
11863
+ "lock.recovered",
11832
11864
  "decision.recorded",
11833
11865
  "evidence.added",
11834
11866
  "ingest.completed",
@@ -11965,7 +11997,8 @@ var init_schemas = __esm(() => {
11965
11997
  lastScanHash: exports_external.string().optional(),
11966
11998
  lastScanAt: exports_external.string().optional(),
11967
11999
  changePaths: exports_external.record(exports_external.string(), exports_external.string()).optional().default({}),
11968
- itemSnapshots: exports_external.record(exports_external.string(), exports_external.string()).optional().default({})
12000
+ itemSnapshots: exports_external.record(exports_external.string(), exports_external.string()).optional().default({}),
12001
+ itemBaseCommits: exports_external.record(exports_external.string(), exports_external.string()).optional()
11969
12002
  });
11970
12003
  SpecAnalyzeFindingSchema = exports_external.object({
11971
12004
  severity: exports_external.enum(["CRITICAL", "HIGH", "MEDIUM", "LOW"]),
@@ -12201,7 +12234,8 @@ var init_schemas = __esm(() => {
12201
12234
  id: ScorecardCriterionIdSchema,
12202
12235
  label: exports_external.string(),
12203
12236
  weight: exports_external.number().min(0).max(1),
12204
- score: exports_external.number().int().min(0).max(3),
12237
+ score: exports_external.number().int().min(0).max(3).nullable(),
12238
+ unmeasured: exports_external.boolean().optional(),
12205
12239
  notes: exports_external.string().optional(),
12206
12240
  autoSuggested: exports_external.boolean().optional()
12207
12241
  });
@@ -12427,10 +12461,10 @@ var init_schemas = __esm(() => {
12427
12461
 
12428
12462
  // src/core/config/config-loader.ts
12429
12463
  import { readFile } from "node:fs/promises";
12430
- import { resolve } from "node:path";
12464
+ import { resolve as resolve2 } from "node:path";
12431
12465
  async function loadConfig(projectRoot) {
12432
12466
  try {
12433
- const configPath = resolve(projectRoot, CONFIG_FILE);
12467
+ const configPath = resolve2(projectRoot, CONFIG_FILE);
12434
12468
  const content = await readFile(configPath, "utf-8");
12435
12469
  const data = $parse(content);
12436
12470
  if (!data) {
@@ -12450,7 +12484,7 @@ async function loadConfig(projectRoot) {
12450
12484
  }
12451
12485
  async function configExists(projectRoot) {
12452
12486
  try {
12453
- const configPath = resolve(projectRoot, CONFIG_FILE);
12487
+ const configPath = resolve2(projectRoot, CONFIG_FILE);
12454
12488
  await readFile(configPath, "utf-8");
12455
12489
  return true;
12456
12490
  } catch {
@@ -12464,27 +12498,6 @@ var init_config_loader = __esm(() => {
12464
12498
  init_schemas();
12465
12499
  });
12466
12500
 
12467
- // src/core/presets/package-paths.ts
12468
- var exports_package_paths = {};
12469
- __export(exports_package_paths, {
12470
- PACKAGE_ROOT: () => PACKAGE_ROOT,
12471
- POLICY_PATH: () => POLICY_PATH,
12472
- ROOT_PRESETS_DIR: () => ROOT_PRESETS_DIR,
12473
- SKILLS_REGISTRY_PATH: () => SKILLS_REGISTRY_PATH,
12474
- SRC_PRESETS_DIR: () => SRC_PRESETS_DIR
12475
- });
12476
- import { dirname, resolve as resolve2, sep } from "node:path";
12477
- import { fileURLToPath } from "node:url";
12478
- var moduleDir, PACKAGE_ROOT, SRC_PRESETS_DIR, ROOT_PRESETS_DIR, POLICY_PATH, SKILLS_REGISTRY_PATH;
12479
- var init_package_paths = __esm(() => {
12480
- moduleDir = dirname(fileURLToPath(import.meta.url));
12481
- PACKAGE_ROOT = moduleDir.endsWith(`${sep}dist`) ? resolve2(moduleDir, "..") : resolve2(moduleDir, "..", "..", "..");
12482
- SRC_PRESETS_DIR = resolve2(PACKAGE_ROOT, "src", "presets");
12483
- ROOT_PRESETS_DIR = resolve2(PACKAGE_ROOT, "presets");
12484
- POLICY_PATH = resolve2(PACKAGE_ROOT, "policy.yml");
12485
- SKILLS_REGISTRY_PATH = resolve2(PACKAGE_ROOT, "skills-registry.json");
12486
- });
12487
-
12488
12501
  // src/core/security/target-compatibility.ts
12489
12502
  import { readFile as readFile2 } from "node:fs/promises";
12490
12503
  async function loadTargetSecurityCompatibility() {
@@ -13130,6 +13143,7 @@ var init_complementary_detector = __esm(() => {
13130
13143
  import { lstat as lstat2, readdir, readFile as readFile4, stat } from "node:fs/promises";
13131
13144
  import { homedir as homedir2 } from "node:os";
13132
13145
  import { join as join4, relative as relative2, resolve as resolve4 } from "node:path";
13146
+ import { isDeepStrictEqual } from "node:util";
13133
13147
  function isMaintainerReservedDest(baseDir, destPath) {
13134
13148
  const rel = relative2(baseDir, destPath).replace(/\\/g, "/");
13135
13149
  if (MAINTAINER_RESERVED_EXACT.has(rel))
@@ -13186,7 +13200,12 @@ function mergeDeep(target, source) {
13186
13200
  const srcVal = source[key];
13187
13201
  const tgtVal = target[key];
13188
13202
  if (Array.isArray(srcVal) && Array.isArray(tgtVal)) {
13189
- result[key] = [...new Set([...tgtVal, ...srcVal])];
13203
+ const values = [...tgtVal];
13204
+ for (const value of srcVal) {
13205
+ if (!values.some((existing) => isDeepStrictEqual(existing, value)))
13206
+ values.push(value);
13207
+ }
13208
+ result[key] = values;
13190
13209
  } else if (srcVal && typeof srcVal === "object" && !Array.isArray(srcVal) && tgtVal && typeof tgtVal === "object" && !Array.isArray(tgtVal)) {
13191
13210
  result[key] = mergeDeep(tgtVal, srcVal);
13192
13211
  } else {
@@ -13453,6 +13472,7 @@ async function applySingleFile(srcPath, destPath, strategy, force, dryRun, isTem
13453
13472
  incomingContent = await injectMcpServers(incomingContent, destPath);
13454
13473
  let finalContent = incomingContent;
13455
13474
  let action = "written";
13475
+ const warnings = [];
13456
13476
  if (strategy === "append") {
13457
13477
  let existing = "";
13458
13478
  try {
@@ -13470,9 +13490,30 @@ async function applySingleFile(srcPath, destPath, strategy, force, dryRun, isTem
13470
13490
  let existing = {};
13471
13491
  try {
13472
13492
  existing = JSON.parse(await readFile4(destPath, "utf-8"));
13473
- } catch {}
13493
+ if (!existing || typeof existing !== "object" || Array.isArray(existing)) {
13494
+ throw new Error("Existing JSON must be an object");
13495
+ }
13496
+ } catch (error) {
13497
+ if (error.code !== "ENOENT") {
13498
+ return { src: srcPath, dest: destPath, action: "error", error: `Cannot merge existing JSON: ${error}` };
13499
+ }
13500
+ }
13474
13501
  try {
13475
13502
  const incoming = JSON.parse(incomingContent);
13503
+ if (!incoming || typeof incoming !== "object" || Array.isArray(incoming)) {
13504
+ throw new Error("Incoming JSON must be an object");
13505
+ }
13506
+ if (srcPath.replace(/\\/g, "/").endsWith("/claude/settings.json")) {
13507
+ const permissions = existing.permissions;
13508
+ const allow = permissions?.allow;
13509
+ if (Array.isArray(allow)) {
13510
+ for (const rule of allow) {
13511
+ if (typeof rule === "string" && /^(?:Bash\([^)]*\*[^)]*\)|WebFetch(?:\([^)]*\*[^)]*\))?)$/.test(rule)) {
13512
+ warnings.push(`${destPath}: preserved user permission ${rule}; review this broad permission.`);
13513
+ }
13514
+ }
13515
+ }
13516
+ }
13476
13517
  finalContent = JSON.stringify(mergeDeep(existing, incoming), null, 2);
13477
13518
  } catch (e) {
13478
13519
  return { src: srcPath, dest: destPath, action: "error", error: `JSON merge failed: ${e}` };
@@ -13496,7 +13537,7 @@ async function applySingleFile(srcPath, destPath, strategy, force, dryRun, isTem
13496
13537
  }
13497
13538
  }
13498
13539
  if (dryRun) {
13499
- return { src: srcPath, dest: destPath, action, dryRun: true, renderedContent: finalContent };
13540
+ return { src: srcPath, dest: destPath, action, dryRun: true, renderedContent: finalContent, ...warnings.length ? { warnings } : {} };
13500
13541
  }
13501
13542
  if (baseDir === undefined) {
13502
13543
  return {
@@ -13510,7 +13551,7 @@ async function applySingleFile(srcPath, destPath, strategy, force, dryRun, isTem
13510
13551
  await writeContainedFile(baseDir, relative2(baseDir, destPath), finalContent, {
13511
13552
  force: true
13512
13553
  });
13513
- return { src: srcPath, dest: destPath, action, renderedContent: finalContent };
13554
+ return { src: srcPath, dest: destPath, action, renderedContent: finalContent, ...warnings.length ? { warnings } : {} };
13514
13555
  } catch (e) {
13515
13556
  return { src: srcPath, dest: destPath, action: "error", error: String(e) };
13516
13557
  }
@@ -13733,6 +13774,12 @@ function profileFor(agentId) {
13733
13774
  function checklistFor(agentId) {
13734
13775
  return profileFor(agentId).checklist;
13735
13776
  }
13777
+ function responsibilitiesFor(agentId) {
13778
+ return profileFor(agentId).responsibilities;
13779
+ }
13780
+ function vetoNoteFor(agentId) {
13781
+ return profileFor(agentId).vetoNote;
13782
+ }
13736
13783
  function generateAgentContent(agent) {
13737
13784
  const profile = profileFor(agent.id);
13738
13785
  const vetoSection = profile.vetoNote ? `
@@ -14256,13 +14303,16 @@ ${agentTables}
14256
14303
  }
14257
14304
  function generateCodexAgent(agent) {
14258
14305
  const focusAreas = agent.focus.join(", ");
14306
+ const responsibilities = responsibilitiesFor(agent.id).join("; ");
14259
14307
  const checklist = checklistFor(agent.id).join("; ");
14308
+ const veto = vetoNoteFor(agent.id);
14309
+ const vetoSentence = veto ? ` ${veto}` : "";
14260
14310
  return `model = "gpt-6.1-sol"
14261
14311
  model_reasoning_effort = "medium"
14262
14312
  name = "${agent.role}"
14263
14313
  description = "${agent.role} council agent. Focus: ${focusAreas}. Context: ${agent.context}. Model hint: ${agent.modelHint}."
14264
14314
  nickname_candidates = ["${agent.role}", "Council ${agent.role}"]
14265
- developer_instructions = "You are the ${agent.role} council agent. Your focus areas are: ${focusAreas}. Context: ${agent.context}. Apply ${agent.modelHint} reasoning to your analysis. Review checklist: ${checklist}. Categorize findings as CRITICAL (blocks the verdict), WARNING, or SUGGESTION."
14315
+ developer_instructions = "You are the ${agent.role} council agent. Your focus areas are: ${focusAreas}. Context: ${agent.context}. Apply ${agent.modelHint} reasoning to your analysis. Responsibilities: ${responsibilities}. Review checklist: ${checklist}.${vetoSentence} Categorize findings as CRITICAL (blocks the verdict), WARNING, or SUGGESTION."
14266
14316
  `;
14267
14317
  }
14268
14318
  function generateCodexSkill(spec) {
@@ -14916,6 +14966,7 @@ __export(exports_doctor_command, {
14916
14966
  });
14917
14967
  import { join as join6 } from "node:path";
14918
14968
  import { homedir as homedir4 } from "node:os";
14969
+ import { spawnSync } from "node:child_process";
14919
14970
  async function doctorCommand(options) {
14920
14971
  const { projectRoot, output } = options;
14921
14972
  const checks = [];
@@ -14964,6 +15015,22 @@ async function doctorCommand(options) {
14964
15015
  }
14965
15016
  };
14966
15017
  }
15018
+ const hookProbe = spawnSync(process.execPath, [join6(ROOT_PRESETS_DIR, "shared", "invoke-hook.cjs"), "--check"], {
15019
+ cwd: projectRoot,
15020
+ input: "",
15021
+ encoding: "utf8",
15022
+ timeout: 12000,
15023
+ env: { ...process.env, PROJECT_ROOT: projectRoot }
15024
+ });
15025
+ let hookOperational = false;
15026
+ try {
15027
+ hookOperational = hookProbe.status === 0 && JSON.parse(hookProbe.stdout).operational === true;
15028
+ } catch {}
15029
+ checks.push({
15030
+ name: "hook-runner",
15031
+ status: hookOperational ? "pass" : "warn",
15032
+ message: hookOperational ? "CodeConductor hook runner is operational." : "Hook guard unavailable. Install cc-codeconductor locally; CC_DEV=1 is reserved for trusted development. CC_HOOK_FAIL_CLOSED=1 denies pre-tool when unavailable."
15033
+ });
14967
15034
  const runnerDirs = [".opencode", ".claude", ".codex"];
14968
15035
  for (const dir of runnerDirs) {
14969
15036
  try {
@@ -15273,6 +15340,7 @@ async function doctorCommand(options) {
15273
15340
  }
15274
15341
  }
15275
15342
  var init_doctor_command = __esm(() => {
15343
+ init_package_paths();
15276
15344
  init_config_loader();
15277
15345
  init_target_compatibility();
15278
15346
  init_update_checker();
@@ -15408,10 +15476,90 @@ var init_config_writer = __esm(() => {
15408
15476
  init_codeconductor_config();
15409
15477
  });
15410
15478
 
15479
+ // src/core/ccep/council-fallback.generated.ts
15480
+ var COUNCIL_FALLBACK_PROFILE;
15481
+ var init_council_fallback_generated = __esm(() => {
15482
+ COUNCIL_FALLBACK_PROFILE = {
15483
+ id: "council",
15484
+ version: 1,
15485
+ command: "council",
15486
+ phases: [
15487
+ {
15488
+ id: "wayfinding",
15489
+ agent: "repo-explorer",
15490
+ outputSchema: "agent-output"
15491
+ },
15492
+ {
15493
+ id: "deliberation",
15494
+ agents: [
15495
+ "task-coach",
15496
+ "architect",
15497
+ "devil"
15498
+ ],
15499
+ skill: "council",
15500
+ outputSchema: "planner-output",
15501
+ stopGate: "confirmation"
15502
+ },
15503
+ {
15504
+ id: "tdd",
15505
+ agent: "tester",
15506
+ requires: "red-state"
15507
+ },
15508
+ {
15509
+ id: "implement",
15510
+ agent: "implementer"
15511
+ },
15512
+ {
15513
+ id: "council-review",
15514
+ agents: [
15515
+ "architect",
15516
+ "product",
15517
+ "delivery",
15518
+ "data-ops",
15519
+ "security-reviewer",
15520
+ "devil"
15521
+ ],
15522
+ skill: "council",
15523
+ outputSchema: "council-verdict"
15524
+ }
15525
+ ],
15526
+ routing: {
15527
+ default: [
15528
+ "wayfinding",
15529
+ "deliberation",
15530
+ "tdd",
15531
+ "implement",
15532
+ "council-review"
15533
+ ]
15534
+ },
15535
+ confirmationGate: {
15536
+ stopOnHighRisk: true,
15537
+ stopOnQuestions: true
15538
+ }
15539
+ };
15540
+ });
15541
+
15411
15542
  // src/core/ccep/profiles.ts
15412
- var baseGate, WORKFLOW_PROFILES;
15543
+ import { readFileSync as readFileSync2 } from "node:fs";
15544
+ import { dirname as dirname5, join as join7 } from "node:path";
15545
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
15546
+ function loadCouncilMirror() {
15547
+ try {
15548
+ const raw = readFileSync2(join7(dirname5(fileURLToPath2(import.meta.url)), "workflows", "council.yml"), "utf-8");
15549
+ return validateWorkflowProfile($parse(raw));
15550
+ } catch (error) {
15551
+ if (error?.code !== "ENOENT")
15552
+ throw error;
15553
+ return COUNCIL_FALLBACK_PROFILE;
15554
+ }
15555
+ }
15556
+ var baseGate, councilMirror, WORKFLOW_PROFILES;
15413
15557
  var init_profiles = __esm(() => {
15558
+ init_dist();
15559
+ init_schemas();
15560
+ init_council_fallback_generated();
15414
15561
  baseGate = { stopOnHighRisk: true, stopOnQuestions: true };
15562
+ councilMirror = loadCouncilMirror();
15415
15563
  WORKFLOW_PROFILES = {
15416
15564
  feature: {
15417
15565
  id: "feature",
@@ -15645,31 +15793,7 @@ var init_profiles = __esm(() => {
15645
15793
  routing: { default: ["analyze", "create", "evaluate"] },
15646
15794
  confirmationGate: { stopOnHighRisk: false, stopOnQuestions: false }
15647
15795
  },
15648
- council: {
15649
- id: "council",
15650
- version: 1,
15651
- command: "council",
15652
- phases: [
15653
- { id: "wayfinding", agent: "repo-explorer", outputSchema: "agent-output" },
15654
- {
15655
- id: "deliberation",
15656
- agents: ["task-coach", "architect", "devil"],
15657
- skill: "council",
15658
- outputSchema: "planner-output",
15659
- stopGate: "confirmation"
15660
- },
15661
- { id: "tdd", agent: "tester", requires: "red-state" },
15662
- { id: "implement", agent: "implementer" },
15663
- {
15664
- id: "council-review",
15665
- agents: ["architect", "product", "delivery", "data-ops", "security-reviewer", "devil"],
15666
- skill: "council",
15667
- outputSchema: "council-verdict"
15668
- }
15669
- ],
15670
- routing: { default: ["wayfinding", "deliberation", "tdd", "implement", "council-review"] },
15671
- confirmationGate: baseGate
15672
- },
15796
+ council: councilMirror,
15673
15797
  iterative: {
15674
15798
  id: "iterative",
15675
15799
  version: 1,
@@ -15797,17 +15921,17 @@ var init_profiles = __esm(() => {
15797
15921
  });
15798
15922
 
15799
15923
  // src/core/ccep/profile-yaml.ts
15800
- import { existsSync as existsSync2, readFileSync as readFileSync2 } from "node:fs";
15801
- import { dirname as dirname5, join as join7 } from "node:path";
15802
- import { fileURLToPath as fileURLToPath2 } from "node:url";
15924
+ import { existsSync as existsSync2, readFileSync as readFileSync3 } from "node:fs";
15925
+ import { dirname as dirname6, join as join8 } from "node:path";
15926
+ import { fileURLToPath as fileURLToPath3 } from "node:url";
15803
15927
  function workflowYamlPath(command, projectRoot) {
15804
15928
  if (projectRoot) {
15805
- const projectPath = join7(projectRoot, ".codeconductor", "workflows", `${command}.yml`);
15929
+ const projectPath = join8(projectRoot, ".codeconductor", "workflows", `${command}.yml`);
15806
15930
  if (existsSync2(projectPath)) {
15807
15931
  return projectPath;
15808
15932
  }
15809
15933
  }
15810
- const bundledPath = join7(BUNDLED_WORKFLOWS_DIR, `${command}.yml`);
15934
+ const bundledPath = join8(BUNDLED_WORKFLOWS_DIR, `${command}.yml`);
15811
15935
  if (existsSync2(bundledPath)) {
15812
15936
  return bundledPath;
15813
15937
  }
@@ -15822,7 +15946,7 @@ function loadWorkflowProfileFromYaml(command, projectRoot) {
15822
15946
  if (!path) {
15823
15947
  return null;
15824
15948
  }
15825
- const content = readFileSync2(path, "utf-8");
15949
+ const content = readFileSync3(path, "utf-8");
15826
15950
  return parseWorkflowYaml(content);
15827
15951
  }
15828
15952
  function loadWorkflowProfileFallback(command) {
@@ -15837,12 +15961,12 @@ var init_profile_yaml = __esm(() => {
15837
15961
  init_dist();
15838
15962
  init_schemas();
15839
15963
  init_profiles();
15840
- BUNDLED_WORKFLOWS_DIR = join7(dirname5(fileURLToPath2(import.meta.url)), "workflows");
15964
+ BUNDLED_WORKFLOWS_DIR = join8(dirname6(fileURLToPath3(import.meta.url)), "workflows");
15841
15965
  });
15842
15966
 
15843
15967
  // src/core/ccep/workflow-init.ts
15844
15968
  import { access as access3, copyFile, mkdir as mkdir4, readdir as readdir2 } from "node:fs/promises";
15845
- import { join as join8, resolve as resolve9 } from "node:path";
15969
+ import { join as join9, resolve as resolve9 } from "node:path";
15846
15970
  async function fileExists4(path) {
15847
15971
  try {
15848
15972
  await access3(path);
@@ -15862,11 +15986,11 @@ async function initWorkflowArtifacts(baseDir, force) {
15862
15986
  for (const file of files) {
15863
15987
  if (!file.endsWith(".yml"))
15864
15988
  continue;
15865
- const destPath = join8(destDir, file);
15989
+ const destPath = join9(destDir, file);
15866
15990
  if (!force && await fileExists4(destPath)) {
15867
15991
  continue;
15868
15992
  }
15869
- await copyFile(join8(BUNDLED_WORKFLOWS_DIR, file), destPath);
15993
+ await copyFile(join9(BUNDLED_WORKFLOWS_DIR, file), destPath);
15870
15994
  created.push(`.codeconductor/workflows/${file}`);
15871
15995
  }
15872
15996
  return created;
@@ -15924,12 +16048,12 @@ async function detectDjango(rootDir) {
15924
16048
  }
15925
16049
  async function detectFastApi(rootDir) {
15926
16050
  const { fileExists: fileExists5 } = await Promise.resolve().then(() => (init_safety(), exports_safety));
15927
- const { join: join9 } = await import("node:path");
16051
+ const { join: join10 } = await import("node:path");
15928
16052
  const { readFile: readFile9 } = await import("node:fs/promises");
15929
16053
  const signals = [];
15930
16054
  if (await fileExists5(rootDir, "requirements.txt")) {
15931
16055
  try {
15932
- const content = await readFile9(join9(rootDir, "requirements.txt"), "utf-8");
16056
+ const content = await readFile9(join10(rootDir, "requirements.txt"), "utf-8");
15933
16057
  if (content.includes("fastapi")) {
15934
16058
  signals.push("fastapi-requirements");
15935
16059
  }
@@ -15937,7 +16061,7 @@ async function detectFastApi(rootDir) {
15937
16061
  }
15938
16062
  if (await fileExists5(rootDir, "pyproject.toml")) {
15939
16063
  try {
15940
- const content = await readFile9(join9(rootDir, "pyproject.toml"), "utf-8");
16064
+ const content = await readFile9(join10(rootDir, "pyproject.toml"), "utf-8");
15941
16065
  if (content.includes("fastapi")) {
15942
16066
  signals.push("fastapi-pyproject");
15943
16067
  }
@@ -15946,7 +16070,7 @@ async function detectFastApi(rootDir) {
15946
16070
  for (const filename of ["main.py", "app.py", "app/main.py", "app/app.py"]) {
15947
16071
  if (await fileExists5(rootDir, filename)) {
15948
16072
  try {
15949
- const content = await readFile9(join9(rootDir, filename), "utf-8");
16073
+ const content = await readFile9(join10(rootDir, filename), "utf-8");
15950
16074
  if (content.includes("FastAPI") && content.includes("fastapi")) {
15951
16075
  signals.push(`${filename}-fastapi`);
15952
16076
  }
@@ -16008,7 +16132,7 @@ async function detectAstro(rootDir) {
16008
16132
  }
16009
16133
  async function detectNext(rootDir) {
16010
16134
  const { fileExists: fileExists5 } = await Promise.resolve().then(() => (init_safety(), exports_safety));
16011
- const { join: join9 } = await import("node:path");
16135
+ const { join: join10 } = await import("node:path");
16012
16136
  const { readFile: readFile9 } = await import("node:fs/promises");
16013
16137
  const signals = [];
16014
16138
  if (await fileExists5(rootDir, "next.config.js") || await fileExists5(rootDir, "next.config.mjs") || await fileExists5(rootDir, "next.config.ts")) {
@@ -16016,7 +16140,7 @@ async function detectNext(rootDir) {
16016
16140
  }
16017
16141
  if (await fileExists5(rootDir, "package.json")) {
16018
16142
  try {
16019
- const content = await readFile9(join9(rootDir, "package.json"), "utf-8");
16143
+ const content = await readFile9(join10(rootDir, "package.json"), "utf-8");
16020
16144
  const pkg = JSON.parse(content);
16021
16145
  if (pkg.dependencies?.next || pkg.devDependencies?.next) {
16022
16146
  signals.push("package.json-next");
@@ -16027,7 +16151,7 @@ async function detectNext(rootDir) {
16027
16151
  }
16028
16152
  async function detectGenericFrontend(rootDir) {
16029
16153
  const { fileExists: fileExists5 } = await Promise.resolve().then(() => (init_safety(), exports_safety));
16030
- const { join: join9 } = await import("node:path");
16154
+ const { join: join10 } = await import("node:path");
16031
16155
  const { readFile: readFile9 } = await import("node:fs/promises");
16032
16156
  const signals = [];
16033
16157
  if (await fileExists5(rootDir, "index.html")) {
@@ -16041,7 +16165,7 @@ async function detectGenericFrontend(rootDir) {
16041
16165
  }
16042
16166
  if (await fileExists5(rootDir, "package.json")) {
16043
16167
  try {
16044
- const content = await readFile9(join9(rootDir, "package.json"), "utf-8");
16168
+ const content = await readFile9(join10(rootDir, "package.json"), "utf-8");
16045
16169
  const pkg = JSON.parse(content);
16046
16170
  const frontendDeps = ["react", "vue", "svelte", "solid-js", "angular", "@angular/core"];
16047
16171
  const hasFrontendDep = frontendDeps.some((dep) => pkg.dependencies?.[dep] || pkg.devDependencies?.[dep]);
@@ -16056,7 +16180,7 @@ async function detectGenericFrontend(rootDir) {
16056
16180
  // src/core/detection/detectors/monorepo.ts
16057
16181
  async function detectMonorepo(rootDir) {
16058
16182
  const { fileExists: fileExists5 } = await Promise.resolve().then(() => (init_safety(), exports_safety));
16059
- const { join: join9 } = await import("node:path");
16183
+ const { join: join10 } = await import("node:path");
16060
16184
  const { readFile: readFile9 } = await import("node:fs/promises");
16061
16185
  const signals = [];
16062
16186
  if (await fileExists5(rootDir, "pnpm-workspace.yaml")) {
@@ -16070,7 +16194,7 @@ async function detectMonorepo(rootDir) {
16070
16194
  }
16071
16195
  if (await fileExists5(rootDir, "package.json")) {
16072
16196
  try {
16073
- const content = await readFile9(join9(rootDir, "package.json"), "utf-8");
16197
+ const content = await readFile9(join10(rootDir, "package.json"), "utf-8");
16074
16198
  const pkg = JSON.parse(content);
16075
16199
  if (pkg.workspaces) {
16076
16200
  signals.push("package.json-workspaces");
@@ -16079,7 +16203,7 @@ async function detectMonorepo(rootDir) {
16079
16203
  }
16080
16204
  if (await fileExists5(rootDir, "Cargo.toml")) {
16081
16205
  try {
16082
- const content = await readFile9(join9(rootDir, "Cargo.toml"), "utf-8");
16206
+ const content = await readFile9(join10(rootDir, "Cargo.toml"), "utf-8");
16083
16207
  if (content.includes("[workspace]")) {
16084
16208
  signals.push("Cargo.toml-workspace");
16085
16209
  }
@@ -17125,7 +17249,7 @@ __export(exports_install_command, {
17125
17249
  });
17126
17250
  import { readFile as readFile12 } from "node:fs/promises";
17127
17251
  import { homedir as homedir7 } from "node:os";
17128
- import { basename as basename5, dirname as dirname6, resolve as resolve12, sep as sep3 } from "node:path";
17252
+ import { basename as basename5, dirname as dirname7, resolve as resolve12, sep as sep3 } from "node:path";
17129
17253
  async function installCommand(options) {
17130
17254
  const { target, dryRun, force, global: isGlobal, output, projectRoot } = options;
17131
17255
  const baseDir = isGlobal ? homedir7() : projectRoot;
@@ -17271,7 +17395,7 @@ async function verifyRenderedFiles(manifest, baseDir, results) {
17271
17395
  if (!parsed.ok) {
17272
17396
  warnings.push(`${r.dest}: ${parsed.error.kind} — ${parsed.error.message}`);
17273
17397
  } else {
17274
- const dir = basename5(dirname6(r.dest));
17398
+ const dir = basename5(dirname7(r.dest));
17275
17399
  const ident = skillIdentifier(parsed.frontmatter);
17276
17400
  if (ident !== dir) {
17277
17401
  warnings.push(`${r.dest}: identifier "${ident}" does not match its directory "${dir}"`);
@@ -17304,6 +17428,7 @@ async function installPresetCommand(options) {
17304
17428
  const results = await copyFromManifest(manifest, PRESETS_DIR, baseDir, isGlobal, dryRun, force, modelConfig, locale);
17305
17429
  for (const r of results) {
17306
17430
  allFileResults.push({ target: t, ...r });
17431
+ postInstallWarnings.push(...r.warnings ?? []);
17307
17432
  }
17308
17433
  if (!dryRun) {
17309
17434
  postInstallWarnings.push(...await verifyRenderedFiles(manifest, baseDir, results));
@@ -18515,7 +18640,7 @@ var init_binary_downloader = __esm(() => {
18515
18640
  import { execFile as execFile2 } from "node:child_process";
18516
18641
  import { access as access6, mkdir as mkdir6, mkdtemp, rename as rename2, rm, writeFile as writeFile5 } from "node:fs/promises";
18517
18642
  import { homedir as homedir8, tmpdir } from "node:os";
18518
- import { join as join9 } from "node:path";
18643
+ import { join as join10 } from "node:path";
18519
18644
  import { promisify as promisify2 } from "node:util";
18520
18645
  async function assertTarArchiveSafe(archivePath, destRoot) {
18521
18646
  const { stdout } = await execFileAsync2("tar", ["-tzf", archivePath], {
@@ -18536,7 +18661,7 @@ async function extractHardenedTar(archivePath, destRoot) {
18536
18661
  class LspInstaller {
18537
18662
  lspBinDir;
18538
18663
  constructor() {
18539
- this.lspBinDir = join9(homedir8(), ".codeconductor", "lsp", "bin");
18664
+ this.lspBinDir = join10(homedir8(), ".codeconductor", "lsp", "bin");
18540
18665
  }
18541
18666
  async checkInstalled(def) {
18542
18667
  try {
@@ -18664,7 +18789,7 @@ class LspInstaller {
18664
18789
  }
18665
18790
  assertBinaryArtifact(binary);
18666
18791
  await mkdir6(this.lspBinDir, { recursive: true });
18667
- const destPath = join9(this.lspBinDir, def.binaryName);
18792
+ const destPath = join10(this.lspBinDir, def.binaryName);
18668
18793
  try {
18669
18794
  await access6(destPath);
18670
18795
  return;
@@ -18676,16 +18801,16 @@ class LspInstaller {
18676
18801
  throw new Error(`Failed to download ${def.serverName}: ${error instanceof Error ? error.message : String(error)}`);
18677
18802
  }
18678
18803
  assertSha256Hex(bytes, binary.sha256);
18679
- const workDir = await mkdtemp(join9(tmpdir(), "cc-lsp-"));
18804
+ const workDir = await mkdtemp(join10(tmpdir(), "cc-lsp-"));
18680
18805
  try {
18681
18806
  const archiveName = binary.url.endsWith(".zip") ? "server.zip" : "server.tar.gz";
18682
- const archivePath = join9(workDir, archiveName);
18807
+ const archivePath = join10(workDir, archiveName);
18683
18808
  await writeFile5(archivePath, bytes);
18684
18809
  if (archiveName.endsWith(".zip")) {
18685
18810
  throw new Error(`Zip binary installs are not supported yet for ${def.serverName}; use a .tar.gz artifact`);
18686
18811
  }
18687
18812
  await extractHardenedTar(archivePath, workDir);
18688
- const candidate = join9(workDir, def.binaryName);
18813
+ const candidate = join10(workDir, def.binaryName);
18689
18814
  try {
18690
18815
  await access6(candidate);
18691
18816
  await rename2(candidate, destPath);
@@ -18964,7 +19089,7 @@ var init_install_lsp_command = __esm(() => {
18964
19089
 
18965
19090
  // src/core/install/update-transaction.ts
18966
19091
  import { mkdir as mkdir7, readFile as readFile13, rm as rm2, unlink, writeFile as writeFile6 } from "node:fs/promises";
18967
- import { dirname as dirname7, isAbsolute as isAbsolute4, join as join10, relative as relative5, resolve as resolve16, sep as sep5 } from "node:path";
19092
+ import { dirname as dirname8, isAbsolute as isAbsolute4, join as join11, relative as relative5, resolve as resolve16, sep as sep5 } from "node:path";
18968
19093
  function assertInsideBase(basePath, destination) {
18969
19094
  const base = resolve16(basePath);
18970
19095
  const absolute = resolve16(base, destination);
@@ -18996,8 +19121,8 @@ class UpdateTransaction {
18996
19121
  try {
18997
19122
  const content = await readFile13(destination);
18998
19123
  snapshots.push({ path: destination, existed: true, content });
18999
- const backupPath = join10(backupDir, relative5(resolve16(basePath), resolve16(destination)));
19000
- await mkdir7(dirname7(backupPath), { recursive: true });
19124
+ const backupPath = join11(backupDir, relative5(resolve16(basePath), resolve16(destination)));
19125
+ await mkdir7(dirname8(backupPath), { recursive: true });
19001
19126
  await writeFile6(backupPath, content);
19002
19127
  } catch (error) {
19003
19128
  if (error.code === "ENOENT") {
@@ -19017,7 +19142,7 @@ class UpdateTransaction {
19017
19142
  throw new Error(`Rollback destination is no longer contained: ${snapshot.path}`);
19018
19143
  }
19019
19144
  if (snapshot.existed) {
19020
- await mkdir7(dirname7(gated), { recursive: true });
19145
+ await mkdir7(dirname8(gated), { recursive: true });
19021
19146
  await writeFile6(gated, snapshot.content);
19022
19147
  } else {
19023
19148
  await unlink(gated).catch((error) => {
@@ -19042,7 +19167,7 @@ __export(exports_update_command, {
19042
19167
  updateCommand: () => updateCommand
19043
19168
  });
19044
19169
  import { homedir as homedir10 } from "node:os";
19045
- import { join as join11, resolve as resolve17 } from "node:path";
19170
+ import { join as join12, resolve as resolve17 } from "node:path";
19046
19171
  import { readFile as readFile14, stat as stat3 } from "node:fs/promises";
19047
19172
  async function updateCommand(options) {
19048
19173
  const { dryRun, force, global: isGlobal, output, projectRoot, check = false } = options;
@@ -19152,7 +19277,7 @@ async function updateCommand(options) {
19152
19277
  const bundledCouncil = resolve17(SRC_PRESETS_DIR, "council", "council.yml");
19153
19278
  try {
19154
19279
  const content = await readFile14(bundledCouncil, "utf-8");
19155
- const written = await writeContainedFile(basePath, join11(".codeconductor", "presets", "council.yml"), content, { force: true });
19280
+ const written = await writeContainedFile(basePath, join12(".codeconductor", "presets", "council.yml"), content, { force: true });
19156
19281
  updated.push(written);
19157
19282
  } catch (e) {
19158
19283
  throw new Error(`Failed to update council.yml: ${e}`);
@@ -19161,7 +19286,7 @@ async function updateCommand(options) {
19161
19286
  if (updateResults.policy) {
19162
19287
  try {
19163
19288
  const content = await readFile14(POLICY_PATH, "utf-8");
19164
- const written = await writeContainedFile(basePath, join11(".codeconductor", "presets", "policy.yml"), content, { force: true });
19289
+ const written = await writeContainedFile(basePath, join12(".codeconductor", "presets", "policy.yml"), content, { force: true });
19165
19290
  updated.push(written);
19166
19291
  } catch (e) {
19167
19292
  throw new Error(`Failed to update policy.yml: ${e}`);
@@ -19240,13 +19365,13 @@ async function updateCommand(options) {
19240
19365
  for (const s of updateResults.skills) {
19241
19366
  newSkillsLock[s.id] = s.latestVersion;
19242
19367
  }
19243
- let lockRel = join11(".codeconductor", "skills-lock.json");
19368
+ let lockRel = join12(".codeconductor", "skills-lock.json");
19244
19369
  try {
19245
19370
  const statAgents = await stat3(resolve17(basePath, ".agents"));
19246
19371
  if (statAgents.isDirectory()) {
19247
19372
  const statCodeConductor = await stat3(resolve17(basePath, ".codeconductor")).catch(() => null);
19248
19373
  if (!statCodeConductor) {
19249
- lockRel = join11(".agents", "skills-lock.json");
19374
+ lockRel = join12(".agents", "skills-lock.json");
19250
19375
  }
19251
19376
  }
19252
19377
  } catch {}
@@ -19319,7 +19444,7 @@ __export(exports_migrate_command, {
19319
19444
  });
19320
19445
  import { readFile as readFile15, readdir as readdir3, rm as rm3, writeFile as writeFile7 } from "node:fs/promises";
19321
19446
  import { homedir as homedir11 } from "node:os";
19322
- import { join as join12, resolve as resolve18 } from "node:path";
19447
+ import { join as join13, resolve as resolve18 } from "node:path";
19323
19448
  function migratePermissionRules(settings) {
19324
19449
  const permissions = settings.permissions;
19325
19450
  if (typeof permissions !== "object" || permissions === null) {
@@ -19366,7 +19491,7 @@ function resolveSettingsPath(options) {
19366
19491
  if (options.file)
19367
19492
  return resolve18(options.projectRoot, options.file);
19368
19493
  const base = options.global ? homedir11() : options.projectRoot;
19369
- return join12(base, ".claude", "settings.json");
19494
+ return join13(base, ".claude", "settings.json");
19370
19495
  }
19371
19496
  async function findOrphanedPromptVersions(basePath, isGlobal) {
19372
19497
  const found = [];
@@ -19376,7 +19501,7 @@ async function findOrphanedPromptVersions(basePath, isGlobal) {
19376
19501
  if (!installed)
19377
19502
  continue;
19378
19503
  const installPath = getTargetInstallationPath(target, basePath, isGlobal);
19379
- const promptsDir = join12(installPath, "prompts");
19504
+ const promptsDir = join13(installPath, "prompts");
19380
19505
  if (seenDirs.has(promptsDir))
19381
19506
  continue;
19382
19507
  seenDirs.add(promptsDir);
@@ -19391,7 +19516,7 @@ async function findOrphanedPromptVersions(basePath, isGlobal) {
19391
19516
  continue;
19392
19517
  if (entry.name === CURRENT_PRESET_VERSION)
19393
19518
  continue;
19394
- found.push({ target, path: join12(promptsDir, entry.name), version: entry.name });
19519
+ found.push({ target, path: join13(promptsDir, entry.name), version: entry.name });
19395
19520
  }
19396
19521
  }
19397
19522
  return found;
@@ -19673,7 +19798,7 @@ __export(exports_help_command, {
19673
19798
  helpCommand: () => helpCommand
19674
19799
  });
19675
19800
  import { readdir as readdir4 } from "node:fs/promises";
19676
- import { join as join13 } from "node:path";
19801
+ import { join as join14 } from "node:path";
19677
19802
  async function scanPresetDir(projectRoot, target) {
19678
19803
  const inventory = {
19679
19804
  target,
@@ -19682,12 +19807,12 @@ async function scanPresetDir(projectRoot, target) {
19682
19807
  agents: [],
19683
19808
  workflows: []
19684
19809
  };
19685
- const presetDir = join13(projectRoot, "presets", target);
19810
+ const presetDir = join14(projectRoot, "presets", target);
19686
19811
  try {
19687
19812
  const entries = await readdir4(presetDir, { withFileTypes: true });
19688
19813
  for (const entry of entries) {
19689
19814
  if (entry.isDirectory()) {
19690
- const subDir = join13(presetDir, entry.name);
19815
+ const subDir = join14(presetDir, entry.name);
19691
19816
  const subEntries = await readdir4(subDir, { withFileTypes: true });
19692
19817
  for (const sub of subEntries) {
19693
19818
  if (sub.isFile()) {
@@ -19814,13 +19939,13 @@ __export(exports_debt_harvest_command, {
19814
19939
  debtHarvestCommand: () => debtHarvestCommand
19815
19940
  });
19816
19941
  import { readdir as readdir5, readFile as readFile16, writeFile as writeFile8, mkdir as mkdir8 } from "node:fs/promises";
19817
- import { join as join14, relative as relative6, extname } from "node:path";
19942
+ import { join as join15, relative as relative6, extname } from "node:path";
19818
19943
  async function walkDir(dir, extensions) {
19819
19944
  const results = [];
19820
19945
  try {
19821
19946
  const entries = await readdir5(dir, { withFileTypes: true });
19822
19947
  for (const entry of entries) {
19823
- const fullPath = join14(dir, entry.name);
19948
+ const fullPath = join15(dir, entry.name);
19824
19949
  if (entry.isDirectory()) {
19825
19950
  if (entry.name.startsWith(".") || entry.name === "node_modules")
19826
19951
  continue;
@@ -19887,7 +20012,7 @@ function renderLedger(entries) {
19887
20012
  async function debtHarvestCommand(options) {
19888
20013
  const { projectRoot, dir = "src", output } = options;
19889
20014
  try {
19890
- const targetDir = join14(projectRoot, dir);
20015
+ const targetDir = join15(projectRoot, dir);
19891
20016
  const files = await walkDir(targetDir, SOURCE_EXTENSIONS);
19892
20017
  const allEntries = [];
19893
20018
  for (const file of files) {
@@ -19895,9 +20020,9 @@ async function debtHarvestCommand(options) {
19895
20020
  const entries = extractDefers(content, relative6(projectRoot, file));
19896
20021
  allEntries.push(...entries);
19897
20022
  }
19898
- const ledgerDir = join14(projectRoot, ".codeconductor");
20023
+ const ledgerDir = join15(projectRoot, ".codeconductor");
19899
20024
  await mkdir8(ledgerDir, { recursive: true });
19900
- const ledgerPath = join14(ledgerDir, "debt-ledger.md");
20025
+ const ledgerPath = join15(ledgerDir, "debt-ledger.md");
19901
20026
  const ledgerContent = renderLedger(allEntries);
19902
20027
  await writeFile8(ledgerPath, ledgerContent, "utf-8");
19903
20028
  if (output === "json") {
@@ -20332,27 +20457,27 @@ var init_goal_planner = __esm(() => {
20332
20457
  });
20333
20458
 
20334
20459
  // src/core/product-graph/paths.ts
20335
- import { join as join15 } from "node:path";
20460
+ import { join as join16 } from "node:path";
20336
20461
  function productGraphPath(projectRoot) {
20337
- return join15(projectRoot, PRODUCT_DIR, PRODUCT_GRAPH_FILE);
20462
+ return join16(projectRoot, PRODUCT_DIR, PRODUCT_GRAPH_FILE);
20338
20463
  }
20339
20464
  function productMetaPath(projectRoot) {
20340
- return join15(projectRoot, PRODUCT_DIR, PRODUCT_META_FILE);
20465
+ return join16(projectRoot, PRODUCT_DIR, PRODUCT_META_FILE);
20341
20466
  }
20342
20467
  function eventsPath(projectRoot) {
20343
- return join15(projectRoot, PRODUCT_DIR, EVENTS_FILE);
20468
+ return join16(projectRoot, PRODUCT_DIR, EVENTS_FILE);
20344
20469
  }
20345
20470
  function operationalStatePath(projectRoot) {
20346
- return join15(projectRoot, PRODUCT_DIR, OPERATIONAL_STATE_FILE);
20471
+ return join16(projectRoot, PRODUCT_DIR, OPERATIONAL_STATE_FILE);
20347
20472
  }
20348
20473
  function strategicPath(projectRoot) {
20349
- return join15(projectRoot, PRODUCT_DIR, STRATEGIC_FILE);
20474
+ return join16(projectRoot, PRODUCT_DIR, STRATEGIC_FILE);
20350
20475
  }
20351
20476
  function productReportPath(projectRoot) {
20352
- return join15(projectRoot, PRODUCT_DIR, PRODUCT_REPORT_FILE);
20477
+ return join16(projectRoot, PRODUCT_DIR, PRODUCT_REPORT_FILE);
20353
20478
  }
20354
20479
  function evidenceDir(projectRoot) {
20355
- return join15(projectRoot, PRODUCT_DIR, EVIDENCE_DIR);
20480
+ return join16(projectRoot, PRODUCT_DIR, EVIDENCE_DIR);
20356
20481
  }
20357
20482
  var PRODUCT_DIR = ".codeconductor", PRODUCT_GRAPH_FILE = "product-graph.json", PRODUCT_META_FILE = "product-meta.json", EVENTS_FILE = "events.jsonl", OPERATIONAL_STATE_FILE = "operational-state.json", STRATEGIC_FILE = "strategic.json", PRODUCT_REPORT_FILE = "product-report.md", EVIDENCE_DIR = "evidence";
20358
20483
  var init_paths = () => {};
@@ -20370,7 +20495,7 @@ __export(exports_graph_store, {
20370
20495
  upsertNode: () => upsertNode
20371
20496
  });
20372
20497
  import { mkdir as mkdir9, readFile as readFile17, writeFile as writeFile9 } from "node:fs/promises";
20373
- import { dirname as dirname8 } from "node:path";
20498
+ import { dirname as dirname9 } from "node:path";
20374
20499
  async function loadGraph(projectRoot) {
20375
20500
  try {
20376
20501
  const raw = await readFile17(productGraphPath(projectRoot), "utf-8");
@@ -20386,7 +20511,7 @@ async function saveGraph(projectRoot, graph) {
20386
20511
  try {
20387
20512
  const validated = ProductGraphSchema.parse(graph);
20388
20513
  const path = productGraphPath(projectRoot);
20389
- await mkdir9(dirname8(path), { recursive: true });
20514
+ await mkdir9(dirname9(path), { recursive: true });
20390
20515
  await writeFile9(path, JSON.stringify(validated, null, 2), "utf-8");
20391
20516
  return ok(undefined);
20392
20517
  } catch (e) {
@@ -20548,15 +20673,233 @@ var init_product_planner = __esm(() => {
20548
20673
  };
20549
20674
  });
20550
20675
 
20676
+ // src/core/memory/episodic-store.ts
20677
+ import { appendFile, mkdir as mkdir10, readFile as readFile18 } from "node:fs/promises";
20678
+ import { resolve as resolve19 } from "node:path";
20679
+ async function appendEvent(projectRoot, event) {
20680
+ try {
20681
+ const full = ProductEventSchema.parse({
20682
+ ...event,
20683
+ id: event.id ?? `evt-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
20684
+ });
20685
+ const path = eventsPath(projectRoot);
20686
+ await mkdir10(resolve19(projectRoot, ".codeconductor"), { recursive: true });
20687
+ await appendFile(path, JSON.stringify(full) + `
20688
+ `, "utf-8");
20689
+ return ok(full);
20690
+ } catch (e) {
20691
+ return err(e instanceof Error ? e : new Error(String(e)));
20692
+ }
20693
+ }
20694
+ async function listEvents(projectRoot, since, type) {
20695
+ try {
20696
+ const content = await readFile18(eventsPath(projectRoot), "utf-8");
20697
+ const events = [];
20698
+ for (const line of content.split(`
20699
+ `)) {
20700
+ if (!line.trim())
20701
+ continue;
20702
+ const parsed = ProductEventSchema.parse(JSON.parse(line));
20703
+ if (since && parsed.timestamp < since)
20704
+ continue;
20705
+ if (type && parsed.type !== type)
20706
+ continue;
20707
+ events.push(parsed);
20708
+ }
20709
+ return ok(events);
20710
+ } catch (e) {
20711
+ if (e.code === "ENOENT") {
20712
+ return ok([]);
20713
+ }
20714
+ return err(e instanceof Error ? e : new Error(String(e)));
20715
+ }
20716
+ }
20717
+ var init_episodic_store = __esm(() => {
20718
+ init_schemas();
20719
+ init_paths();
20720
+ });
20721
+
20722
+ // src/core/queue/lock.ts
20723
+ import { createHash as createHash3, randomUUID } from "node:crypto";
20724
+ import { AsyncLocalStorage } from "node:async_hooks";
20725
+ import { mkdir as mkdir11, open as open2, readFile as readFile19, unlink as unlink2 } from "node:fs/promises";
20726
+ import { hostname } from "node:os";
20727
+ import { resolve as resolve20 } from "node:path";
20728
+ async function readOwner(path) {
20729
+ const owner = JSON.parse(await readFile19(path, "utf8"));
20730
+ if (!Number.isInteger(owner.pid) || owner.pid <= 0 || typeof owner.hostname !== "string" || typeof owner.token !== "string" || !owner.token || !Number.isFinite(Date.parse(owner.timestamp))) {
20731
+ throw new Error("Invalid queue lock metadata");
20732
+ }
20733
+ return owner;
20734
+ }
20735
+ function isOrphan(owner) {
20736
+ if (owner.hostname !== hostname() || Date.now() - Date.parse(owner.timestamp) < STALE_MS)
20737
+ return false;
20738
+ try {
20739
+ process.kill(owner.pid, 0);
20740
+ return false;
20741
+ } catch (e) {
20742
+ return e.code === "ESRCH";
20743
+ }
20744
+ }
20745
+ async function removeOwned(path, token) {
20746
+ try {
20747
+ if ((await readOwner(path)).token === token)
20748
+ await unlink2(path);
20749
+ } catch (e) {
20750
+ if (e.code !== "ENOENT")
20751
+ throw e;
20752
+ }
20753
+ }
20754
+ async function electRecovery(dir, token, owner) {
20755
+ const registry = resolve20(dir, "recoveries");
20756
+ await mkdir11(registry, { recursive: true });
20757
+ const seen = new Set;
20758
+ while (!seen.has(token)) {
20759
+ seen.add(token);
20760
+ const path = resolve20(registry, `${createHash3("sha256").update(token).digest("hex")}.json`);
20761
+ try {
20762
+ const file = await open2(path, "wx");
20763
+ try {
20764
+ await file.writeFile(JSON.stringify(owner));
20765
+ } finally {
20766
+ await file.close();
20767
+ }
20768
+ return true;
20769
+ } catch (e) {
20770
+ if (e.code !== "EEXIST")
20771
+ throw e;
20772
+ }
20773
+ const elected = await readOwner(path);
20774
+ if (elected.token === owner.token)
20775
+ return true;
20776
+ if (!isOrphan(elected))
20777
+ return false;
20778
+ token = elected.token;
20779
+ }
20780
+ throw new Error("Invalid queue lock recovery chain");
20781
+ }
20782
+ async function withQueueLock(projectRoot, action) {
20783
+ const root = resolve20(projectRoot);
20784
+ const held = heldLocks.getStore();
20785
+ if (held?.has(root))
20786
+ return action();
20787
+ const dir = resolve20(projectRoot, ".codeconductor/queue");
20788
+ const path = resolve20(dir, ".lock");
20789
+ const recoveryPath = resolve20(dir, ".lock.recovery");
20790
+ const owner = {
20791
+ pid: process.pid,
20792
+ hostname: hostname(),
20793
+ timestamp: new Date().toISOString(),
20794
+ token: randomUUID()
20795
+ };
20796
+ let acquired = false;
20797
+ try {
20798
+ await mkdir11(dir, { recursive: true });
20799
+ for (let attempt = 0;attempt < 40; attempt++) {
20800
+ try {
20801
+ const recoveryOwner = await readOwner(recoveryPath);
20802
+ if (isOrphan(recoveryOwner) && await electRecovery(dir, recoveryOwner.token, owner)) {
20803
+ await removeOwned(recoveryPath, recoveryOwner.token);
20804
+ continue;
20805
+ }
20806
+ } catch (e) {
20807
+ if (e instanceof SyntaxError || e instanceof Error && e.message === "Invalid queue lock metadata") {
20808
+ await new Promise((resolveWait) => setTimeout(resolveWait, 25));
20809
+ continue;
20810
+ }
20811
+ if (e.code !== "ENOENT")
20812
+ throw e;
20813
+ try {
20814
+ const file = await open2(path, "wx");
20815
+ try {
20816
+ await file.writeFile(JSON.stringify(owner));
20817
+ } finally {
20818
+ await file.close();
20819
+ }
20820
+ acquired = true;
20821
+ break;
20822
+ } catch (e2) {
20823
+ if (e2.code !== "EEXIST")
20824
+ throw e2;
20825
+ }
20826
+ try {
20827
+ const existing = await readOwner(path);
20828
+ if (isOrphan(existing) && await electRecovery(dir, existing.token, owner)) {
20829
+ const current = await readOwner(path);
20830
+ if (current.token === existing.token && isOrphan(current)) {
20831
+ await unlink2(path);
20832
+ const recovered = await appendEvent(projectRoot, {
20833
+ type: "lock.recovered",
20834
+ timestamp: new Date().toISOString(),
20835
+ payload: { owner: current }
20836
+ });
20837
+ if (!recovered.success)
20838
+ return recovered;
20839
+ }
20840
+ continue;
20841
+ }
20842
+ } catch (e2) {
20843
+ if (!(e2 instanceof SyntaxError) && !(e2 instanceof Error && e2.message === "Invalid queue lock metadata") && !["ENOENT", "EEXIST"].includes(e2.code ?? ""))
20844
+ throw e2;
20845
+ }
20846
+ }
20847
+ await new Promise((resolveWait) => setTimeout(resolveWait, 25));
20848
+ }
20849
+ if (!acquired)
20850
+ return err(new Error("Queue lock is held by another process; retry after it finishes"));
20851
+ return await heldLocks.run(new Set([...held ?? [], root]), action);
20852
+ } catch (e) {
20853
+ return err(e instanceof Error ? e : new Error(String(e)));
20854
+ } finally {
20855
+ if (acquired) {
20856
+ try {
20857
+ await removeOwned(path, owner.token);
20858
+ } catch (e) {
20859
+ return err(e instanceof Error ? e : new Error(String(e)));
20860
+ }
20861
+ }
20862
+ }
20863
+ }
20864
+ var STALE_MS, heldLocks;
20865
+ var init_lock = __esm(() => {
20866
+ init_episodic_store();
20867
+ STALE_MS = 5 * 60 * 1000;
20868
+ heldLocks = new AsyncLocalStorage;
20869
+ });
20870
+
20551
20871
  // src/core/goal/goal-state.ts
20552
20872
  var exports_goal_state = {};
20553
20873
  __export(exports_goal_state, {
20554
20874
  loadGoal: () => loadGoal,
20555
20875
  markTaskBlocked: () => markTaskBlocked,
20876
+ propagateBlockedTasks: () => propagateBlockedTasks,
20556
20877
  writeGoal: () => writeGoal
20557
20878
  });
20558
- import { mkdir as mkdir10, readFile as readFile18, writeFile as writeFile10 } from "node:fs/promises";
20559
- import { resolve as resolve19 } from "node:path";
20879
+ import { randomUUID as randomUUID2 } from "node:crypto";
20880
+ import { mkdir as mkdir12, readFile as readFile20, rename as rename3, unlink as unlink3, writeFile as writeFile10 } from "node:fs/promises";
20881
+ import { resolve as resolve21 } from "node:path";
20882
+ function propagateBlockedTasks(graph) {
20883
+ const blocked = new Set(graph.tasks.filter((task) => task.status === "blocked").map((task) => task.id));
20884
+ let changed = false;
20885
+ let progressed;
20886
+ do {
20887
+ progressed = false;
20888
+ for (const task of graph.tasks) {
20889
+ if (task.status !== "pending")
20890
+ continue;
20891
+ const dependency = (task.depends_on ?? []).find((id) => blocked.has(id));
20892
+ if (!dependency)
20893
+ continue;
20894
+ task.status = "blocked";
20895
+ task.blocked_reason = `Blocked by dependency "${dependency}"`;
20896
+ blocked.add(task.id);
20897
+ progressed = true;
20898
+ changed = true;
20899
+ }
20900
+ } while (progressed);
20901
+ return changed;
20902
+ }
20560
20903
  function validateGoalGraph2(graph) {
20561
20904
  const ids = new Set(graph.tasks.map((t) => t.id));
20562
20905
  if (ids.size !== graph.tasks.length) {
@@ -20571,14 +20914,20 @@ function validateGoalGraph2(graph) {
20571
20914
  }
20572
20915
  const visited = new Set;
20573
20916
  const inStack = new Set;
20917
+ const path = [];
20918
+ let cycle = [];
20919
+ const tasksById = new Map(graph.tasks.map((task) => [task.id, task]));
20574
20920
  function dfs(taskId) {
20575
- if (inStack.has(taskId))
20921
+ if (inStack.has(taskId)) {
20922
+ cycle = [...path.slice(path.indexOf(taskId)), taskId];
20576
20923
  return true;
20924
+ }
20577
20925
  if (visited.has(taskId))
20578
20926
  return false;
20579
20927
  visited.add(taskId);
20580
20928
  inStack.add(taskId);
20581
- const task = graph.tasks.find((t) => t.id === taskId);
20929
+ path.push(taskId);
20930
+ const task = tasksById.get(taskId);
20582
20931
  if (task) {
20583
20932
  for (const dep of task.depends_on ?? []) {
20584
20933
  if (dfs(dep))
@@ -20586,29 +20935,43 @@ function validateGoalGraph2(graph) {
20586
20935
  }
20587
20936
  }
20588
20937
  inStack.delete(taskId);
20938
+ path.pop();
20589
20939
  return false;
20590
20940
  }
20591
20941
  for (const task of graph.tasks) {
20592
20942
  if (dfs(task.id)) {
20593
- return err(new Error(`Cycle detected involving task "${task.id}"`));
20943
+ return err(new Error(`Cycle detected: ${cycle.join(" -> ")}`));
20594
20944
  }
20595
20945
  }
20596
20946
  return ok(graph);
20597
20947
  }
20598
20948
  async function writeGoal(projectRoot, graph) {
20949
+ return withQueueLock(projectRoot, () => writeGoalUnlocked(projectRoot, graph));
20950
+ }
20951
+ async function writeGoalUnlocked(projectRoot, graph) {
20599
20952
  const validation = validateGoalGraph2(graph);
20600
20953
  if (!validation.success)
20601
20954
  return validation;
20602
- const dir = resolve19(projectRoot, ".codeconductor");
20603
- await mkdir10(dir, { recursive: true });
20604
- const yaml = $stringify(graph);
20605
- await writeFile10(resolve19(dir, "current-goal.yml"), yaml, "utf-8");
20606
- return ok(undefined);
20955
+ const dir = resolve21(projectRoot, ".codeconductor");
20956
+ const temporary = resolve21(dir, `current-goal.${process.pid}.${randomUUID2()}.tmp`);
20957
+ try {
20958
+ await mkdir12(dir, { recursive: true });
20959
+ await writeFile10(temporary, $stringify(graph), { encoding: "utf-8", flag: "wx" });
20960
+ await rename3(temporary, resolve21(dir, "current-goal.yml"));
20961
+ return ok(undefined);
20962
+ } catch (e) {
20963
+ return err(e instanceof Error ? e : new Error(String(e)));
20964
+ } finally {
20965
+ await unlink3(temporary).catch((e) => {
20966
+ if (e.code !== "ENOENT")
20967
+ throw e;
20968
+ });
20969
+ }
20607
20970
  }
20608
20971
  async function loadGoal(projectRoot) {
20609
20972
  try {
20610
- const filePath = resolve19(projectRoot, GOAL_FILE);
20611
- const content = await readFile18(filePath, "utf-8");
20973
+ const filePath = resolve21(projectRoot, GOAL_FILE);
20974
+ const content = await readFile20(filePath, "utf-8");
20612
20975
  const data = $parse(content);
20613
20976
  const validated = GoalGraphSchema.parse(data);
20614
20977
  return validateGoalGraph2(validated);
@@ -20617,6 +20980,9 @@ async function loadGoal(projectRoot) {
20617
20980
  }
20618
20981
  }
20619
20982
  async function markTaskBlocked(projectRoot, taskId, reason) {
20983
+ return withQueueLock(projectRoot, () => markTaskBlockedUnlocked(projectRoot, taskId, reason));
20984
+ }
20985
+ async function markTaskBlockedUnlocked(projectRoot, taskId, reason) {
20620
20986
  const loadResult = await loadGoal(projectRoot);
20621
20987
  if (!loadResult.success)
20622
20988
  return loadResult;
@@ -20627,12 +20993,14 @@ async function markTaskBlocked(projectRoot, taskId, reason) {
20627
20993
  }
20628
20994
  task.status = "blocked";
20629
20995
  task.blocked_reason = reason;
20996
+ propagateBlockedTasks(graph);
20630
20997
  return writeGoal(projectRoot, graph);
20631
20998
  }
20632
20999
  var GOAL_FILE = ".codeconductor/current-goal.yml";
20633
21000
  var init_goal_state = __esm(() => {
20634
21001
  init_dist();
20635
21002
  init_schemas();
21003
+ init_lock();
20636
21004
  });
20637
21005
 
20638
21006
  // src/commands/goal.command.ts
@@ -20770,8 +21138,8 @@ var init_goal_command = __esm(() => {
20770
21138
  });
20771
21139
 
20772
21140
  // src/core/openspec/backlog-parser.ts
20773
- import { readFile as readFile19 } from "node:fs/promises";
20774
- import { resolve as resolve20 } from "node:path";
21141
+ import { readFile as readFile21 } from "node:fs/promises";
21142
+ import { resolve as resolve22 } from "node:path";
20775
21143
  function parseBool(value) {
20776
21144
  const v = value.trim().toLowerCase();
20777
21145
  return v === "yes" || v === "true";
@@ -20945,8 +21313,8 @@ function parseBacklogMarkdown(content) {
20945
21313
  }
20946
21314
  async function loadBacklog(projectRoot) {
20947
21315
  try {
20948
- const filePath = resolve20(projectRoot, BACKLOG_FILE);
20949
- const content = await readFile19(filePath, "utf-8");
21316
+ const filePath = resolve22(projectRoot, BACKLOG_FILE);
21317
+ const content = await readFile21(filePath, "utf-8");
20950
21318
  return parseBacklogMarkdown(content);
20951
21319
  } catch (e) {
20952
21320
  return err(e instanceof Error ? e : new Error(String(e)));
@@ -20995,11 +21363,11 @@ function slugify(text) {
20995
21363
  }
20996
21364
 
20997
21365
  // src/core/knowledge/source-parsers.ts
20998
- import { readFile as readFile20 } from "node:fs/promises";
20999
- import { basename as basename6, join as join16, relative as relative7, sep as sep6 } from "node:path";
21366
+ import { readFile as readFile22 } from "node:fs/promises";
21367
+ import { basename as basename6, join as join17, relative as relative7, sep as sep6 } from "node:path";
21000
21368
  async function parseAdrFile(filePath) {
21001
21369
  try {
21002
- const content = await readFile20(filePath, "utf-8");
21370
+ const content = await readFile22(filePath, "utf-8");
21003
21371
  const base = basename6(filePath);
21004
21372
  const idMatch = base.match(/adr-(\d+)/i);
21005
21373
  const id = idMatch ? `adr-${idMatch[1]}` : slugify(base);
@@ -21048,7 +21416,7 @@ function adrToEntities(adr, source) {
21048
21416
  }
21049
21417
  async function parseReadmeEntities(projectRoot, productName) {
21050
21418
  try {
21051
- const content = await readFile20(join16(projectRoot, "README.md"), "utf-8");
21419
+ const content = await readFile22(join17(projectRoot, "README.md"), "utf-8");
21052
21420
  const firstPara = content.split(`
21053
21421
 
21054
21422
  `).find((p) => p.trim() && !p.startsWith("#") && !p.startsWith(">")) ?? "";
@@ -21069,7 +21437,7 @@ async function parseReadmeEntities(projectRoot, productName) {
21069
21437
  }
21070
21438
  async function parseGraphifyEntities(projectRoot) {
21071
21439
  try {
21072
- const raw = await readFile20(join16(projectRoot, "graphify-out", "graph.json"), "utf-8");
21440
+ const raw = await readFile22(join17(projectRoot, "graphify-out", "graph.json"), "utf-8");
21073
21441
  const graph = JSON.parse(raw);
21074
21442
  const entities = [];
21075
21443
  for (const node2 of graph.nodes ?? []) {
@@ -21093,14 +21461,14 @@ async function parseGraphifyEntities(projectRoot) {
21093
21461
  async function scanSrcComponents(projectRoot) {
21094
21462
  const { readdir: readdir6 } = await import("node:fs/promises");
21095
21463
  const entities = [];
21096
- const srcDir = join16(projectRoot, "src");
21464
+ const srcDir = join17(projectRoot, "src");
21097
21465
  async function walk(dir, prefix) {
21098
21466
  try {
21099
21467
  const entries = await readdir6(dir, { withFileTypes: true });
21100
21468
  for (const entry of entries) {
21101
21469
  if (entry.name.startsWith("."))
21102
21470
  continue;
21103
- const full = join16(dir, entry.name);
21471
+ const full = join17(dir, entry.name);
21104
21472
  if (entry.isDirectory()) {
21105
21473
  if (entry.name === "node_modules")
21106
21474
  continue;
@@ -21124,78 +21492,32 @@ async function scanSrcComponents(projectRoot) {
21124
21492
  }
21125
21493
  var init_source_parsers = () => {};
21126
21494
 
21127
- // src/core/memory/episodic-store.ts
21128
- import { appendFile, mkdir as mkdir11, readFile as readFile21 } from "node:fs/promises";
21129
- import { resolve as resolve21 } from "node:path";
21130
- async function appendEvent(projectRoot, event) {
21131
- try {
21132
- const full = ProductEventSchema.parse({
21133
- ...event,
21134
- id: event.id ?? `evt-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
21135
- });
21136
- const path = eventsPath(projectRoot);
21137
- await mkdir11(resolve21(projectRoot, ".codeconductor"), { recursive: true });
21138
- await appendFile(path, JSON.stringify(full) + `
21139
- `, "utf-8");
21140
- return ok(full);
21141
- } catch (e) {
21142
- return err(e instanceof Error ? e : new Error(String(e)));
21495
+ // src/core/knowledge/ingest-pipeline.ts
21496
+ import { createHash as createHash4 } from "node:crypto";
21497
+ import { readFile as readFile23 } from "node:fs/promises";
21498
+ import { join as join18, relative as relative8, sep as sep7 } from "node:path";
21499
+ import { mkdir as mkdir13, writeFile as writeFile11 } from "node:fs/promises";
21500
+ async function mapLimit(items, limit, fn) {
21501
+ if (items.length === 0)
21502
+ return [];
21503
+ const out = new Array(items.length);
21504
+ let next = 0;
21505
+ async function worker() {
21506
+ while (true) {
21507
+ const index = next++;
21508
+ if (index >= items.length)
21509
+ return;
21510
+ out[index] = await fn(items[index], index);
21511
+ }
21143
21512
  }
21513
+ const workers = Math.min(limit, items.length);
21514
+ await Promise.all(Array.from({ length: workers }, () => worker()));
21515
+ return out;
21144
21516
  }
21145
- async function listEvents(projectRoot, since, type) {
21517
+ async function hashFile(path) {
21146
21518
  try {
21147
- const content = await readFile21(eventsPath(projectRoot), "utf-8");
21148
- const events = [];
21149
- for (const line of content.split(`
21150
- `)) {
21151
- if (!line.trim())
21152
- continue;
21153
- const parsed = ProductEventSchema.parse(JSON.parse(line));
21154
- if (since && parsed.timestamp < since)
21155
- continue;
21156
- if (type && parsed.type !== type)
21157
- continue;
21158
- events.push(parsed);
21159
- }
21160
- return ok(events);
21161
- } catch (e) {
21162
- if (e.code === "ENOENT") {
21163
- return ok([]);
21164
- }
21165
- return err(e instanceof Error ? e : new Error(String(e)));
21166
- }
21167
- }
21168
- var init_episodic_store = __esm(() => {
21169
- init_schemas();
21170
- init_paths();
21171
- });
21172
-
21173
- // src/core/knowledge/ingest-pipeline.ts
21174
- import { createHash as createHash3 } from "node:crypto";
21175
- import { readFile as readFile22 } from "node:fs/promises";
21176
- import { join as join17, relative as relative8, sep as sep7 } from "node:path";
21177
- import { mkdir as mkdir12, writeFile as writeFile11 } from "node:fs/promises";
21178
- async function mapLimit(items, limit, fn) {
21179
- if (items.length === 0)
21180
- return [];
21181
- const out = new Array(items.length);
21182
- let next = 0;
21183
- async function worker() {
21184
- while (true) {
21185
- const index = next++;
21186
- if (index >= items.length)
21187
- return;
21188
- out[index] = await fn(items[index], index);
21189
- }
21190
- }
21191
- const workers = Math.min(limit, items.length);
21192
- await Promise.all(Array.from({ length: workers }, () => worker()));
21193
- return out;
21194
- }
21195
- async function hashFile(path) {
21196
- try {
21197
- const content = await readFile22(path, "utf-8");
21198
- return createHash3("sha256").update(content).digest("hex").slice(0, 16);
21519
+ const content = await readFile23(path, "utf-8");
21520
+ return createHash4("sha256").update(content).digest("hex").slice(0, 16);
21199
21521
  } catch {
21200
21522
  return null;
21201
21523
  }
@@ -21209,7 +21531,7 @@ async function collectDeferRisks(projectRoot) {
21209
21531
  for (const entry of entries) {
21210
21532
  if (entry.name.startsWith(".") || entry.name === "node_modules")
21211
21533
  continue;
21212
- const full = join17(dir, entry.name);
21534
+ const full = join18(dir, entry.name);
21213
21535
  if (entry.isDirectory()) {
21214
21536
  await walk(full);
21215
21537
  } else if (entry.name.endsWith(".ts")) {
@@ -21218,10 +21540,10 @@ async function collectDeferRisks(projectRoot) {
21218
21540
  }
21219
21541
  } catch {}
21220
21542
  }
21221
- await walk(join17(projectRoot, "src"));
21543
+ await walk(join18(projectRoot, "src"));
21222
21544
  const perFile = await mapLimit(files, WALK_READ_CONCURRENCY, async (full) => {
21223
21545
  const entities = [];
21224
- const content = await readFile22(full, "utf-8");
21546
+ const content = await readFile23(full, "utf-8");
21225
21547
  const rel = relative8(projectRoot, full).split(sep7).join("/");
21226
21548
  const deferRe = new RegExp(DEFER_REGEX_SOURCE, "gm");
21227
21549
  let match;
@@ -21281,12 +21603,12 @@ async function parseBacklogEntities(projectRoot) {
21281
21603
  }
21282
21604
  async function parseAdrEntities(projectRoot) {
21283
21605
  const { readdir: readdir6 } = await import("node:fs/promises");
21284
- const adrDir = join17(projectRoot, "docs", "adr");
21606
+ const adrDir = join18(projectRoot, "docs", "adr");
21285
21607
  const entities = [];
21286
21608
  try {
21287
21609
  const files = (await readdir6(adrDir)).filter((file) => file.endsWith(".md"));
21288
21610
  const parsed = await Promise.all(files.map(async (file) => {
21289
- const adr = await parseAdrFile(join17(adrDir, file));
21611
+ const adr = await parseAdrFile(join18(adrDir, file));
21290
21612
  return adr ? adrToEntities(adr, `docs/adr/${file}`) : [];
21291
21613
  }));
21292
21614
  entities.push(...parsed.flat());
@@ -21378,7 +21700,7 @@ async function runIngest(projectRoot, productName) {
21378
21700
  await saveGraph2(projectRoot, graph);
21379
21701
  const sourceHashes = {};
21380
21702
  for (const src of ["README.md", "BACKLOG.md", "ROADMAP.md"]) {
21381
- const h = await hashFile(join17(projectRoot, src));
21703
+ const h = await hashFile(join18(projectRoot, src));
21382
21704
  if (h)
21383
21705
  sourceHashes[src] = h;
21384
21706
  }
@@ -21388,7 +21710,7 @@ async function runIngest(projectRoot, productName) {
21388
21710
  lastIngestAt: new Date().toISOString(),
21389
21711
  sourceHashes
21390
21712
  };
21391
- await mkdir12(join17(projectRoot, ".codeconductor"), { recursive: true });
21713
+ await mkdir13(join18(projectRoot, ".codeconductor"), { recursive: true });
21392
21714
  await writeFile11(productMetaPath(projectRoot), JSON.stringify(ProductMetaSchema.parse(meta), null, 2), "utf-8");
21393
21715
  await appendEvent(projectRoot, {
21394
21716
  type: "ingest.completed",
@@ -21470,11 +21792,11 @@ var init_ingest_command = __esm(() => {
21470
21792
  });
21471
21793
 
21472
21794
  // src/core/memory/operational-state.ts
21473
- import { mkdir as mkdir13, readFile as readFile23, writeFile as writeFile12 } from "node:fs/promises";
21474
- import { resolve as resolve22 } from "node:path";
21795
+ import { mkdir as mkdir14, readFile as readFile24, writeFile as writeFile12 } from "node:fs/promises";
21796
+ import { resolve as resolve23 } from "node:path";
21475
21797
  async function loadOperationalState(projectRoot) {
21476
21798
  try {
21477
- const raw = await readFile23(operationalStatePath(projectRoot), "utf-8");
21799
+ const raw = await readFile24(operationalStatePath(projectRoot), "utf-8");
21478
21800
  return ok(OperationalStateSchema.parse(JSON.parse(raw)));
21479
21801
  } catch (e) {
21480
21802
  if (e.code === "ENOENT") {
@@ -21496,7 +21818,7 @@ async function saveOperationalState(projectRoot, state) {
21496
21818
  updatedAt: new Date().toISOString()
21497
21819
  });
21498
21820
  const path = operationalStatePath(projectRoot);
21499
- await mkdir13(resolve22(projectRoot, ".codeconductor"), { recursive: true });
21821
+ await mkdir14(resolve23(projectRoot, ".codeconductor"), { recursive: true });
21500
21822
  await writeFile12(path, JSON.stringify(validated, null, 2), "utf-8");
21501
21823
  return ok(undefined);
21502
21824
  } catch (e) {
@@ -21531,11 +21853,11 @@ var init_operational_state = __esm(() => {
21531
21853
  });
21532
21854
 
21533
21855
  // src/core/memory/strategic-memory.ts
21534
- import { mkdir as mkdir14, readFile as readFile24, writeFile as writeFile13 } from "node:fs/promises";
21535
- import { resolve as resolve23 } from "node:path";
21856
+ import { mkdir as mkdir15, readFile as readFile25, writeFile as writeFile13 } from "node:fs/promises";
21857
+ import { resolve as resolve24 } from "node:path";
21536
21858
  async function loadStrategicMemory(projectRoot) {
21537
21859
  try {
21538
- const raw = await readFile24(strategicPath(projectRoot), "utf-8");
21860
+ const raw = await readFile25(strategicPath(projectRoot), "utf-8");
21539
21861
  return ok(StrategicMemorySchema.parse(JSON.parse(raw)));
21540
21862
  } catch (e) {
21541
21863
  if (e.code === "ENOENT") {
@@ -21556,7 +21878,7 @@ async function saveStrategicMemory(projectRoot, memory) {
21556
21878
  updatedAt: new Date().toISOString()
21557
21879
  });
21558
21880
  const path = strategicPath(projectRoot);
21559
- await mkdir14(resolve23(projectRoot, ".codeconductor"), { recursive: true });
21881
+ await mkdir15(resolve24(projectRoot, ".codeconductor"), { recursive: true });
21560
21882
  await writeFile13(path, JSON.stringify(validated, null, 2), "utf-8");
21561
21883
  return ok(undefined);
21562
21884
  } catch (e) {
@@ -21569,8 +21891,8 @@ var init_strategic_memory = __esm(() => {
21569
21891
  });
21570
21892
 
21571
21893
  // src/core/memory/memory-index.ts
21572
- import { mkdir as mkdir15, readFile as readFile25, writeFile as writeFile14 } from "node:fs/promises";
21573
- import { resolve as resolve24 } from "node:path";
21894
+ import { mkdir as mkdir16, readFile as readFile26, writeFile as writeFile14 } from "node:fs/promises";
21895
+ import { resolve as resolve25 } from "node:path";
21574
21896
  function parseMarkdown(content) {
21575
21897
  const startIdx = content.indexOf(SENTINEL_START);
21576
21898
  const endIdx = content.indexOf(SENTINEL_END);
@@ -21589,8 +21911,8 @@ function parseMarkdown(content) {
21589
21911
  }
21590
21912
  async function loadMemoryIndex(projectRoot) {
21591
21913
  try {
21592
- const filePath = resolve24(projectRoot, MEMORY_FILE);
21593
- const content = await readFile25(filePath, "utf-8");
21914
+ const filePath = resolve25(projectRoot, MEMORY_FILE);
21915
+ const content = await readFile26(filePath, "utf-8");
21594
21916
  const parsed = parseMarkdown(content);
21595
21917
  if (!parsed) {
21596
21918
  return err(new Error("Failed to parse memory index from memory.md"));
@@ -21607,24 +21929,24 @@ var init_memory_index = __esm(() => {
21607
21929
  });
21608
21930
 
21609
21931
  // src/core/evaluation/outcome-store.ts
21610
- import { appendFile as appendFile2, mkdir as mkdir16, readFile as readFile26, readdir as readdir6, writeFile as writeFile15 } from "node:fs/promises";
21611
- import { resolve as resolve25 } from "node:path";
21932
+ import { appendFile as appendFile2, mkdir as mkdir17, readFile as readFile27, readdir as readdir6, writeFile as writeFile15 } from "node:fs/promises";
21933
+ import { resolve as resolve26 } from "node:path";
21612
21934
  async function ensureEvaluationDir(projectRoot) {
21613
- const dir = resolve25(projectRoot, EVAL_DIR);
21614
- await mkdir16(dir, { recursive: true });
21615
- await mkdir16(resolve25(dir, SCORECARDS_DIR), { recursive: true });
21935
+ const dir = resolve26(projectRoot, EVAL_DIR);
21936
+ await mkdir17(dir, { recursive: true });
21937
+ await mkdir17(resolve26(dir, SCORECARDS_DIR), { recursive: true });
21616
21938
  return dir;
21617
21939
  }
21618
21940
  async function appendOutcome(projectRoot, outcome) {
21619
21941
  try {
21620
21942
  const dir = await ensureEvaluationDir(projectRoot);
21621
21943
  const validated = TaskOutcomeSchema.parse(outcome);
21622
- await appendFile2(resolve25(dir, OUTCOMES_FILE), JSON.stringify(validated) + `
21944
+ await appendFile2(resolve26(dir, OUTCOMES_FILE), JSON.stringify(validated) + `
21623
21945
  `, "utf-8");
21624
- const indexPath = resolve25(dir, INDEX_FILE);
21946
+ const indexPath = resolve26(dir, INDEX_FILE);
21625
21947
  let index = { version: 1, lastOutcomeId: validated.id };
21626
21948
  try {
21627
- const raw = await readFile26(indexPath, "utf-8");
21949
+ const raw = await readFile27(indexPath, "utf-8");
21628
21950
  index = EvaluationIndexSchema.parse(JSON.parse(raw));
21629
21951
  index.lastOutcomeId = validated.id;
21630
21952
  } catch {}
@@ -21636,8 +21958,8 @@ async function appendOutcome(projectRoot, outcome) {
21636
21958
  }
21637
21959
  async function listOutcomes(projectRoot, filter = {}) {
21638
21960
  try {
21639
- const path = resolve25(projectRoot, EVAL_DIR, OUTCOMES_FILE);
21640
- const content = await readFile26(path, "utf-8");
21961
+ const path = resolve26(projectRoot, EVAL_DIR, OUTCOMES_FILE);
21962
+ const content = await readFile27(path, "utf-8");
21641
21963
  const lines = content.split(`
21642
21964
  `).filter((l) => l.trim().length > 0);
21643
21965
  const outcomes = [];
@@ -21675,7 +21997,7 @@ async function saveScorecard(projectRoot, record) {
21675
21997
  try {
21676
21998
  const dir = await ensureEvaluationDir(projectRoot);
21677
21999
  const validated = ScorecardRecordSchema.parse(record);
21678
- const filePath = resolve25(dir, SCORECARDS_DIR, `${validated.id}.json`);
22000
+ const filePath = resolve26(dir, SCORECARDS_DIR, `${validated.id}.json`);
21679
22001
  await writeFile15(filePath, JSON.stringify(validated, null, 2), "utf-8");
21680
22002
  return ok(filePath);
21681
22003
  } catch (e) {
@@ -21684,7 +22006,7 @@ async function saveScorecard(projectRoot, record) {
21684
22006
  }
21685
22007
  async function listScorecards(projectRoot, filter = {}) {
21686
22008
  try {
21687
- const dir = resolve25(projectRoot, EVAL_DIR, SCORECARDS_DIR);
22009
+ const dir = resolve26(projectRoot, EVAL_DIR, SCORECARDS_DIR);
21688
22010
  let files;
21689
22011
  try {
21690
22012
  files = await readdir6(dir);
@@ -21697,7 +22019,7 @@ async function listScorecards(projectRoot, filter = {}) {
21697
22019
  for (const file of files) {
21698
22020
  if (!file.endsWith(".json"))
21699
22021
  continue;
21700
- const parsed = ScorecardRecordSchema.parse(JSON.parse(await readFile26(resolve25(dir, file), "utf-8")));
22022
+ const parsed = ScorecardRecordSchema.parse(JSON.parse(await readFile27(resolve26(dir, file), "utf-8")));
21701
22023
  if (filter.backlogId && parsed.backlogId !== filter.backlogId)
21702
22024
  continue;
21703
22025
  if (filter.verdict && parsed.verdict !== filter.verdict)
@@ -21719,8 +22041,8 @@ async function hasPassingScorecard(projectRoot, backlogId) {
21719
22041
  }
21720
22042
  async function loadScorecard(projectRoot, id) {
21721
22043
  try {
21722
- const filePath = resolve25(projectRoot, EVAL_DIR, SCORECARDS_DIR, `${id}.json`);
21723
- const content = await readFile26(filePath, "utf-8");
22044
+ const filePath = resolve26(projectRoot, EVAL_DIR, SCORECARDS_DIR, `${id}.json`);
22045
+ const content = await readFile27(filePath, "utf-8");
21724
22046
  return ok(ScorecardRecordSchema.parse(JSON.parse(content)));
21725
22047
  } catch (e) {
21726
22048
  return err(e instanceof Error ? e : new Error(String(e)));
@@ -21812,11 +22134,11 @@ var init_outcome_store = __esm(() => {
21812
22134
  });
21813
22135
 
21814
22136
  // src/core/feedback/feedback-ingestor.ts
21815
- import { readFile as readFile27 } from "node:fs/promises";
21816
- import { join as join18 } from "node:path";
22137
+ import { readFile as readFile28 } from "node:fs/promises";
22138
+ import { join as join19 } from "node:path";
21817
22139
  async function parseChangelogLearnings(projectRoot) {
21818
22140
  try {
21819
- const content = await readFile27(join18(projectRoot, "CHANGELOG.md"), "utf-8");
22141
+ const content = await readFile28(join19(projectRoot, "CHANGELOG.md"), "utf-8");
21820
22142
  const unreleased = content.match(/## \[Unreleased\]([\s\S]*?)(?=## \[|\n## )/i);
21821
22143
  if (!unreleased)
21822
22144
  return [];
@@ -22160,6 +22482,7 @@ var init_product_command = __esm(() => {
22160
22482
  });
22161
22483
 
22162
22484
  // src/core/compilation/compile-checker.ts
22485
+ import { spawn } from "node:child_process";
22163
22486
  function tokenizeCommand(cmd) {
22164
22487
  const tokens = [];
22165
22488
  let current = "";
@@ -22205,6 +22528,12 @@ function isAllowlistedCompileCommand(command) {
22205
22528
  return false;
22206
22529
  return ALLOWLISTED_ARGV_PREFIXES.some((prefix) => parts.length >= prefix.length && prefix.every((token, i) => parts[i] === token));
22207
22530
  }
22531
+ function isAllowlistedTestCommand(command) {
22532
+ if (!isAllowlistedCompileCommand(command))
22533
+ return false;
22534
+ const parts = Array.isArray(command) ? command : tokenizeCommand(command);
22535
+ return parts.some((token) => token === "test" || token.startsWith("test:"));
22536
+ }
22208
22537
  function minimalChildEnv() {
22209
22538
  const env = {
22210
22539
  PATH: process.env.PATH ?? "",
@@ -22310,40 +22639,37 @@ async function runCompileCheck(options) {
22310
22639
  const startTime = performance.now();
22311
22640
  let timedOut = false;
22312
22641
  const parts = Array.isArray(command) ? command : tokenizeCommand(command);
22642
+ const failure = (stderr) => ({
22643
+ success: false,
22644
+ exitCode: -1,
22645
+ stdout: "",
22646
+ stderr,
22647
+ errors: [],
22648
+ durationMs: performance.now() - startTime,
22649
+ timedOut: false
22650
+ });
22313
22651
  let proc;
22314
22652
  try {
22315
- proc = Bun.spawn(parts, {
22653
+ proc = spawn(parts[0], parts.slice(1), {
22316
22654
  cwd,
22317
- stdout: "pipe",
22318
- stderr: "pipe",
22655
+ stdio: ["ignore", "pipe", "pipe"],
22319
22656
  env: minimalChildEnv(),
22320
22657
  detached: process.platform !== "win32"
22321
22658
  });
22322
22659
  } catch (err2) {
22323
- const durationMs = performance.now() - startTime;
22324
- return {
22325
- success: false,
22326
- exitCode: -1,
22327
- stdout: "",
22328
- stderr: String(err2),
22329
- errors: [],
22330
- durationMs,
22331
- timedOut: false
22332
- };
22333
- }
22334
- const collectOutput = (async () => {
22335
- const stdoutStream = proc.stdout;
22336
- const stderrStream = proc.stderr;
22337
- const [stdout, stderr] = await Promise.all([
22338
- new Response(stdoutStream).text(),
22339
- new Response(stderrStream).text()
22340
- ]);
22341
- return { stdout, stderr, exitCode: await proc.exited };
22342
- })();
22343
- collectOutput.catch(() => {});
22660
+ return failure(String(err2));
22661
+ }
22662
+ const collectOutput = new Promise((resolvePromise) => {
22663
+ let stdout = "";
22664
+ let stderr = "";
22665
+ proc.stdout.setEncoding("utf-8").on("data", (chunk) => stdout += chunk);
22666
+ proc.stderr.setEncoding("utf-8").on("data", (chunk) => stderr += chunk);
22667
+ proc.on("error", (err2) => resolvePromise({ stdout: "", stderr: String(err2), exitCode: -1 }));
22668
+ proc.on("close", (code) => resolvePromise({ stdout, stderr, exitCode: code ?? -1 }));
22669
+ });
22344
22670
  let timeoutId;
22345
- const timeout = new Promise((resolve26) => {
22346
- timeoutId = setTimeout(() => resolve26("timeout"), timeoutMs);
22671
+ const timeout = new Promise((resolvePromise) => {
22672
+ timeoutId = setTimeout(() => resolvePromise("timeout"), timeoutMs);
22347
22673
  });
22348
22674
  try {
22349
22675
  const outcome = await Promise.race([collectOutput, timeout]);
@@ -22351,8 +22677,7 @@ async function runCompileCheck(options) {
22351
22677
  timedOut = true;
22352
22678
  try {
22353
22679
  if (process.platform === "win32") {
22354
- const taskkill = Bun.spawn(["taskkill", "/PID", String(proc.pid), "/T", "/F"], { stdout: "ignore", stderr: "ignore" });
22355
- await taskkill.exited;
22680
+ spawn("taskkill", ["/PID", String(proc.pid), "/T", "/F"], { stdio: "ignore" }).on("error", () => proc.kill("SIGKILL"));
22356
22681
  } else {
22357
22682
  process.kill(-proc.pid, "SIGKILL");
22358
22683
  }
@@ -22361,7 +22686,6 @@ async function runCompileCheck(options) {
22361
22686
  proc.kill("SIGKILL");
22362
22687
  } catch {}
22363
22688
  }
22364
- await proc.exited;
22365
22689
  return {
22366
22690
  success: false,
22367
22691
  exitCode: proc.exitCode ?? -1,
@@ -22382,15 +22706,7 @@ async function runCompileCheck(options) {
22382
22706
  timedOut
22383
22707
  };
22384
22708
  } catch (err2) {
22385
- return {
22386
- success: false,
22387
- exitCode: -1,
22388
- stdout: "",
22389
- stderr: String(err2),
22390
- errors: [],
22391
- durationMs: performance.now() - startTime,
22392
- timedOut
22393
- };
22709
+ return { ...failure(String(err2)), timedOut };
22394
22710
  } finally {
22395
22711
  clearTimeout(timeoutId);
22396
22712
  }
@@ -22417,17 +22733,19 @@ __export(exports_rdd_receipt, {
22417
22733
  captureReceipt: () => captureReceipt,
22418
22734
  collectReceiptPaths: () => collectReceiptPaths,
22419
22735
  isRddReceipt: () => isRddReceipt,
22420
- verifyReceipt: () => verifyReceipt
22736
+ isRegisteredReceipt: () => isRegisteredReceipt,
22737
+ verifyReceipt: () => verifyReceipt,
22738
+ verifyReceiptLock: () => verifyReceiptLock
22421
22739
  });
22422
- import { createHash as createHash4 } from "node:crypto";
22423
- import { readdir as readdir7, readFile as readFile28 } from "node:fs/promises";
22424
- import { join as join19, relative as relative9, resolve as resolve26, sep as sep8 } from "node:path";
22740
+ import { createHash as createHash5, randomBytes } from "node:crypto";
22741
+ import { mkdir as mkdir18, readdir as readdir7, readFile as readFile29, writeFile as writeFile17 } from "node:fs/promises";
22742
+ import { join as join20, relative as relative9, resolve as resolve27, sep as sep8 } from "node:path";
22425
22743
  function sha2562(content) {
22426
- return createHash4("sha256").update(content).digest("hex");
22744
+ return createHash5("sha256").update(content).digest("hex");
22427
22745
  }
22428
22746
  function canonicalPath(projectRoot, input) {
22429
- const root = resolve26(projectRoot);
22430
- const absolute = resolve26(root, input);
22747
+ const root = resolve27(projectRoot);
22748
+ const absolute = resolve27(root, input);
22431
22749
  if (absolute !== root && !absolute.startsWith(`${root}${sep8}`)) {
22432
22750
  throw new Error(`RDD receipt path "${input}" is outside the project root`);
22433
22751
  }
@@ -22445,7 +22763,7 @@ async function fingerprint(projectRoot, paths) {
22445
22763
  }
22446
22764
  const result = [];
22447
22765
  for (const [path, absolute] of [...deduplicated.entries()].sort(([left], [right]) => left.localeCompare(right))) {
22448
- result.push({ path, hash: sha2562(await readFile28(absolute)) });
22766
+ result.push({ path, hash: sha2562(await readFile29(absolute)) });
22449
22767
  }
22450
22768
  return result;
22451
22769
  }
@@ -22453,6 +22771,23 @@ function manifestHash(paths) {
22453
22771
  return sha2562(paths.map((entry) => `${entry.path}\x00${entry.hash}`).join(`
22454
22772
  `));
22455
22773
  }
22774
+ function receiptRegistryDir(projectRoot) {
22775
+ return join20(resolve27(projectRoot), ".codeconductor", "rdd-receipts");
22776
+ }
22777
+ function isWellFormedNonce(nonce) {
22778
+ return typeof nonce === "string" && /^[0-9a-f]{32}$/.test(nonce);
22779
+ }
22780
+ async function isRegisteredReceipt(projectRoot, receipt) {
22781
+ if (!isWellFormedNonce(receipt.nonce))
22782
+ return false;
22783
+ try {
22784
+ const raw = await readFile29(join20(receiptRegistryDir(projectRoot), `${receipt.nonce}.json`), "utf-8");
22785
+ const entry = JSON.parse(raw);
22786
+ return entry.manifestHash === receipt.manifestHash;
22787
+ } catch {
22788
+ return false;
22789
+ }
22790
+ }
22456
22791
  function isRddReceipt(value) {
22457
22792
  if (!value || typeof value !== "object")
22458
22793
  return false;
@@ -22466,37 +22801,47 @@ async function captureReceipt(projectRoot, input) {
22466
22801
  throw new Error("RDD receipts require at least one protected path");
22467
22802
  }
22468
22803
  const paths = await fingerprint(projectRoot, input.paths);
22469
- return {
22804
+ const hashed = manifestHash(paths);
22805
+ const nonce = randomBytes(16).toString("hex");
22806
+ const capturedAt = new Date().toISOString();
22807
+ const receipt = {
22470
22808
  version: 1,
22471
22809
  taskId: input.taskId,
22472
22810
  phase: input.phase,
22473
22811
  paths,
22474
22812
  coverage: input.coverage ?? "paths",
22475
- manifestHash: manifestHash(paths),
22813
+ manifestHash: hashed,
22476
22814
  command: input.command,
22477
22815
  outcome: input.outcome,
22478
- capturedAt: new Date().toISOString()
22816
+ capturedAt,
22817
+ nonce
22479
22818
  };
22819
+ const directory = receiptRegistryDir(projectRoot);
22820
+ await mkdir18(directory, { recursive: true });
22821
+ const entry = { manifestHash: hashed, taskId: input.taskId, capturedAt };
22822
+ await writeFile17(join20(directory, `${nonce}.json`), JSON.stringify(entry, null, 2), "utf-8");
22823
+ return receipt;
22480
22824
  }
22481
22825
  async function collectReceiptPaths(projectRoot) {
22482
- const root = resolve26(projectRoot);
22826
+ const root = resolve27(projectRoot);
22483
22827
  const paths = [];
22484
22828
  async function visit2(current) {
22485
22829
  const entries = await readdir7(current, { withFileTypes: true });
22486
22830
  for (const entry of entries) {
22487
22831
  if (entry.isDirectory()) {
22488
22832
  if (!EXCLUDED_DIRECTORIES.has(entry.name))
22489
- await visit2(join19(current, entry.name));
22833
+ await visit2(join20(current, entry.name));
22490
22834
  continue;
22491
22835
  }
22492
22836
  if (entry.isFile())
22493
- paths.push(relative9(root, join19(current, entry.name)).split(sep8).join("/"));
22837
+ paths.push(relative9(root, join20(current, entry.name)).split(sep8).join("/"));
22494
22838
  }
22495
22839
  }
22496
22840
  await visit2(root);
22497
22841
  return paths.sort();
22498
22842
  }
22499
22843
  async function verifyReceipt(projectRoot, receipt) {
22844
+ const registered = await isRegisteredReceipt(projectRoot, receipt);
22500
22845
  const expected = new Map(receipt.paths.map((entry) => [entry.path, entry.hash]));
22501
22846
  const changedPaths = [];
22502
22847
  const current = [];
@@ -22505,7 +22850,7 @@ async function verifyReceipt(projectRoot, receipt) {
22505
22850
  for (const path of pathsToCheck) {
22506
22851
  try {
22507
22852
  const canonical = canonicalPath(projectRoot, path);
22508
- const hash = sha2562(await readFile28(canonical.absolute));
22853
+ const hash = sha2562(await readFile29(canonical.absolute));
22509
22854
  const currentEntry = { path: canonical.relative, hash };
22510
22855
  current.push(currentEntry);
22511
22856
  currentByPath.set(currentEntry.path, currentEntry);
@@ -22522,12 +22867,24 @@ async function verifyReceipt(projectRoot, receipt) {
22522
22867
  changedPaths.sort();
22523
22868
  const actualHash = manifestHash(current.sort((left, right) => left.path.localeCompare(right.path)));
22524
22869
  return {
22525
- valid: changedPaths.length === 0 && actualHash === receipt.manifestHash,
22870
+ valid: registered && changedPaths.length === 0 && actualHash === receipt.manifestHash,
22526
22871
  expectedHash: receipt.manifestHash,
22527
22872
  actualHash,
22528
22873
  changedPaths
22529
22874
  };
22530
22875
  }
22876
+ async function verifyReceiptLock(projectRoot, lockPath) {
22877
+ let parsed;
22878
+ try {
22879
+ parsed = JSON.parse(await readFile29(resolve27(projectRoot, lockPath), "utf-8"));
22880
+ } catch {
22881
+ return { valid: false, changedPaths: [] };
22882
+ }
22883
+ if (!isRddReceipt(parsed))
22884
+ return { valid: false, changedPaths: [] };
22885
+ const verification = await verifyReceipt(projectRoot, parsed);
22886
+ return { valid: verification.valid, changedPaths: verification.changedPaths };
22887
+ }
22531
22888
  var EXCLUDED_DIRECTORIES;
22532
22889
  var init_rdd_receipt = __esm(() => {
22533
22890
  EXCLUDED_DIRECTORIES = new Set([
@@ -22542,9 +22899,9 @@ var init_rdd_receipt = __esm(() => {
22542
22899
 
22543
22900
  // src/core/verification/verification-runner.ts
22544
22901
  import { existsSync as existsSync3 } from "node:fs";
22545
- import { readFile as readFile29 } from "node:fs/promises";
22546
- import { dirname as dirname9, join as join20, resolve as resolve27 } from "node:path";
22547
- import { mkdir as mkdir17, readdir as readdir8, writeFile as writeFile17 } from "node:fs/promises";
22902
+ import { readFile as readFile30 } from "node:fs/promises";
22903
+ import { dirname as dirname10, join as join21, resolve as resolve28 } from "node:path";
22904
+ import { mkdir as mkdir19, readdir as readdir8, writeFile as writeFile18 } from "node:fs/promises";
22548
22905
  function isPassingEvidence(ev) {
22549
22906
  switch (ev.type) {
22550
22907
  case "verification":
@@ -22570,8 +22927,8 @@ async function isCurrentPassingEvidence(projectRoot, ev) {
22570
22927
  return (await verifyReceipt(projectRoot, receipt)).valid;
22571
22928
  }
22572
22929
  function evidenceFilePath(evDir, id) {
22573
- const path = resolve27(evDir, `${id.replace(/[^A-Za-z0-9_-]/g, "_")}.json`);
22574
- if (dirname9(path) !== resolve27(evDir)) {
22930
+ const path = resolve28(evDir, `${id.replace(/[^A-Za-z0-9_-]/g, "_")}.json`);
22931
+ if (dirname10(path) !== resolve28(evDir)) {
22575
22932
  return err(new Error(`Refusing to write evidence for "${id}" outside ${evDir}`));
22576
22933
  }
22577
22934
  return ok(path);
@@ -22582,8 +22939,8 @@ async function persistEvidence(projectRoot, evidence) {
22582
22939
  if (!evidencePath.success)
22583
22940
  return evidencePath;
22584
22941
  try {
22585
- await mkdir17(evDir, { recursive: true });
22586
- await writeFile17(evidencePath.data, JSON.stringify(evidence, null, 2), "utf-8");
22942
+ await mkdir19(evDir, { recursive: true });
22943
+ await writeFile18(evidencePath.data, JSON.stringify(evidence, null, 2), "utf-8");
22587
22944
  } catch (e) {
22588
22945
  return err(e instanceof Error ? e : new Error(String(e)));
22589
22946
  }
@@ -22605,7 +22962,7 @@ async function collectTaskEvidence(projectRoot, taskId) {
22605
22962
  if (!file.endsWith(".json"))
22606
22963
  continue;
22607
22964
  try {
22608
- const raw = await readFile29(join20(evDir, file), "utf-8");
22965
+ const raw = await readFile30(join21(evDir, file), "utf-8");
22609
22966
  const ev = EvidenceSchema.parse(JSON.parse(raw));
22610
22967
  if (ev.relatedTask === taskId)
22611
22968
  records.push(ev);
@@ -22785,14 +23142,79 @@ async function gateTaskCompletion(projectRoot, taskId, evidenceRequired, evidenc
22785
23142
  }
22786
23143
  return ok(true);
22787
23144
  }
22788
- async function loadTddSuiteEvidence(projectRoot, taskId, evidenceId) {
23145
+ async function captureTddSuiteEvidence(projectRoot, taskId, options) {
23146
+ if (!options.allowCompileCheck && !isAllowlistedTestCommand(options.command)) {
23147
+ return err(new Error("TDD suite command is not on the test allowlist. Re-run with --allow-compile-check to trust it."));
23148
+ }
23149
+ const paths = await collectReceiptPaths(projectRoot);
23150
+ const before = await captureReceipt(projectRoot, {
23151
+ taskId,
23152
+ phase: options.phase ?? "verification",
23153
+ paths,
23154
+ command: options.command,
23155
+ outcome: "failed",
23156
+ coverage: "project"
23157
+ });
23158
+ const result = await runCompileCheck({
23159
+ command: options.command,
23160
+ cwd: projectRoot
23161
+ });
23162
+ const suitePassed = result.success && !result.timedOut && result.exitCode === 0;
23163
+ const suiteFailed = !result.timedOut && result.exitCode > 0;
23164
+ const receipt = { ...before, outcome: suitePassed ? "passed" : "failed" };
23165
+ const receiptResult = await verifyReceipt(projectRoot, receipt);
23166
+ if (!receiptResult.valid) {
23167
+ return err(new Error(`RDD candidate changed while the TDD suite ran: ${receiptResult.changedPaths.join(", ")}`));
23168
+ }
23169
+ const evidence = {
23170
+ id: `ev-tdd-${taskId}-${Date.now()}`,
23171
+ source: TDD_EVIDENCE_SOURCE,
23172
+ type: "tdd",
23173
+ timestamp: new Date().toISOString(),
23174
+ relatedTask: taskId,
23175
+ confidence: suitePassed || suiteFailed ? 0.9 : 0.3,
23176
+ summary: suitePassed ? "TDD suite passed" : suiteFailed ? "TDD suite failed" : "TDD suite inconclusive",
23177
+ data: {
23178
+ capturedBy: TDD_CAPTURED_BY,
23179
+ suiteFailed,
23180
+ suitePassed,
23181
+ exitCode: result.exitCode,
23182
+ timedOut: result.timedOut,
23183
+ command: options.command,
23184
+ rddReceipt: receipt
23185
+ }
23186
+ };
23187
+ const persisted = await persistEvidence(projectRoot, evidence);
23188
+ if (!persisted.success)
23189
+ return persisted;
23190
+ const event = await appendEvent(projectRoot, {
23191
+ type: "verification.completed",
23192
+ timestamp: new Date().toISOString(),
23193
+ payload: {
23194
+ taskId,
23195
+ tdd: true,
23196
+ suiteFailed,
23197
+ suitePassed,
23198
+ evidenceId: evidence.id
23199
+ }
23200
+ });
23201
+ if (!event.success)
23202
+ return event;
23203
+ return ok({
23204
+ evidenceId: evidence.id,
23205
+ suiteFailed,
23206
+ suitePassed,
23207
+ receipt
23208
+ });
23209
+ }
23210
+ async function readRunnerTddEvidence(projectRoot, taskId, evidenceId) {
22789
23211
  const evDir = evidenceDir(projectRoot);
22790
23212
  const path = evidenceFilePath(evDir, evidenceId);
22791
23213
  if (!path.success)
22792
23214
  return path;
22793
23215
  let raw;
22794
23216
  try {
22795
- raw = await readFile29(path.data, "utf-8");
23217
+ raw = await readFile30(path.data, "utf-8");
22796
23218
  } catch (e) {
22797
23219
  return err(e instanceof Error ? e : new Error(String(e)));
22798
23220
  }
@@ -22821,24 +23243,83 @@ async function loadTddSuiteEvidence(projectRoot, taskId, evidenceId) {
22821
23243
  if (receipt.taskId !== taskId) {
22822
23244
  return err(new Error(`Evidence "${evidenceId}" receipt belongs to another task`));
22823
23245
  }
22824
- const verified = await verifyReceipt(projectRoot, receipt);
23246
+ return ok({ capturedBy, suiteFailed, suitePassed, receipt });
23247
+ }
23248
+ async function loadTddSuiteEvidence(projectRoot, taskId, evidenceId) {
23249
+ const read = await readRunnerTddEvidence(projectRoot, taskId, evidenceId);
23250
+ if (!read.success)
23251
+ return read;
23252
+ const verified = await verifyReceipt(projectRoot, read.data.receipt);
22825
23253
  if (!verified.valid) {
22826
23254
  return err(new Error(`Evidence "${evidenceId}" RDD receipt is stale: ${verified.changedPaths.join(", ")}`));
22827
23255
  }
22828
- return ok({ capturedBy, suiteFailed, suitePassed, receipt });
23256
+ return read;
22829
23257
  }
22830
- async function hasTddRunnerEvidence(projectRoot, taskId, expectedPhase) {
23258
+ async function listRunnerTddRecords(projectRoot, taskId) {
22831
23259
  const collected = await collectTaskEvidence(projectRoot, taskId);
22832
23260
  if (!collected.success)
22833
- return false;
22834
- for (const ev of collected.data.records) {
22835
- if (ev.type !== "tdd" || ev.source !== TDD_EVIDENCE_SOURCE || ev.data?.capturedBy !== TDD_CAPTURED_BY) {
23261
+ return [];
23262
+ return collected.data.records.filter((ev) => ev.type === "tdd" && ev.source === TDD_EVIDENCE_SOURCE && ev.data?.capturedBy === TDD_CAPTURED_BY);
23263
+ }
23264
+ function tddValidationFilePath(projectRoot, taskId) {
23265
+ return evidenceFilePath(join21(resolve28(projectRoot), ".codeconductor", "tdd-validations"), taskId);
23266
+ }
23267
+ async function loadTddValidation(projectRoot, taskId) {
23268
+ const path = tddValidationFilePath(projectRoot, taskId);
23269
+ if (!path.success)
23270
+ return;
23271
+ try {
23272
+ const record = TddValidationRecordSchema.parse(JSON.parse(await readFile30(path.data, "utf-8")));
23273
+ return record.taskId === taskId ? record : undefined;
23274
+ } catch {
23275
+ return;
23276
+ }
23277
+ }
23278
+ async function recordRedValidation(projectRoot, taskId) {
23279
+ let best;
23280
+ for (const ev of await listRunnerTddRecords(projectRoot, taskId)) {
23281
+ const loaded = await loadTddSuiteEvidence(projectRoot, taskId, ev.id);
23282
+ if (!loaded.success || !isRedSuite(loaded.data) || loaded.data.receipt.outcome !== "failed")
22836
23283
  continue;
23284
+ const { receipt } = loaded.data;
23285
+ if (!best || receipt.capturedAt > best.receipt.capturedAt || receipt.capturedAt === best.receipt.capturedAt && ev.id > best.id) {
23286
+ best = { id: ev.id, receipt };
23287
+ }
23288
+ }
23289
+ if (!best || !best.receipt.nonce) {
23290
+ return err(new Error(`Task ${taskId} has no fresh RED verification-runner TDD evidence`));
23291
+ }
23292
+ const record = TddValidationRecordSchema.parse({
23293
+ taskId,
23294
+ evidenceId: best.id,
23295
+ receiptNonce: best.receipt.nonce,
23296
+ manifestHash: best.receipt.manifestHash,
23297
+ validatedAt: new Date().toISOString()
23298
+ });
23299
+ const path = tddValidationFilePath(projectRoot, taskId);
23300
+ if (!path.success)
23301
+ return path;
23302
+ try {
23303
+ await mkdir19(dirname10(path.data), { recursive: true });
23304
+ await writeFile18(path.data, JSON.stringify(record, null, 2), "utf-8");
23305
+ } catch (e) {
23306
+ return err(e instanceof Error ? e : new Error(String(e)));
23307
+ }
23308
+ return ok(record);
23309
+ }
23310
+ async function hasTddRunnerEvidence(projectRoot, taskId, expectedPhase) {
23311
+ const validation = expectedPhase === "red" ? await loadTddValidation(projectRoot, taskId) : undefined;
23312
+ for (const ev of await listRunnerTddRecords(projectRoot, taskId)) {
23313
+ if (expectedPhase === "red" && validation?.evidenceId === ev.id) {
23314
+ const read = await readRunnerTddEvidence(projectRoot, taskId, ev.id);
23315
+ if (read.success && isRedSuite(read.data) && read.data.receipt.outcome === "failed" && read.data.receipt.nonce === validation.receiptNonce && read.data.receipt.manifestHash === validation.manifestHash && await isRegisteredReceipt(projectRoot, read.data.receipt)) {
23316
+ return true;
23317
+ }
22837
23318
  }
22838
23319
  const loaded = await loadTddSuiteEvidence(projectRoot, taskId, ev.id);
22839
23320
  if (!loaded.success)
22840
23321
  continue;
22841
- if (expectedPhase === "red" && (!loaded.data.suiteFailed || loaded.data.suitePassed))
23322
+ if (expectedPhase === "red" && !isRedSuite(loaded.data))
22842
23323
  continue;
22843
23324
  if (expectedPhase === "green" && (!loaded.data.suitePassed || loaded.data.suiteFailed))
22844
23325
  continue;
@@ -22846,7 +23327,7 @@ async function hasTddRunnerEvidence(projectRoot, taskId, expectedPhase) {
22846
23327
  }
22847
23328
  return false;
22848
23329
  }
22849
- var TDD_EVIDENCE_SOURCE = "cc verify", TDD_CAPTURED_BY = "verification-runner";
23330
+ var TDD_EVIDENCE_SOURCE = "cc verify", TDD_CAPTURED_BY = "verification-runner", isRedSuite = (e) => e.suiteFailed && !e.suitePassed;
22850
23331
  var init_verification_runner = __esm(() => {
22851
23332
  init_schemas();
22852
23333
  init_config_loader();
@@ -22858,22 +23339,23 @@ var init_verification_runner = __esm(() => {
22858
23339
 
22859
23340
  // src/core/orchestrator/runtime-orchestrator.ts
22860
23341
  async function rollbackTaskStatus(projectRoot, graph, task, previousStatus, previousState, cause) {
22861
- task.status = previousStatus;
22862
- const write = await writeGoal(projectRoot, graph);
22863
- const restored = write.success ? await saveOperationalState(projectRoot, previousState) : write;
22864
- return restored.success ? err(cause) : err(new Error(`${cause.message} (rollback failed: ${restored.error.message})`));
23342
+ return withQueueLock(projectRoot, async () => {
23343
+ task.status = previousStatus;
23344
+ const write = await writeGoal(projectRoot, graph);
23345
+ const restored = write.success ? await saveOperationalState(projectRoot, previousState) : write;
23346
+ return restored.success ? err(cause) : err(new Error(`${cause.message} (rollback failed: ${restored.error.message})`));
23347
+ });
22865
23348
  }
22866
23349
  function getReadyTasks(graph) {
23350
+ propagateBlockedTasks(graph);
22867
23351
  const done = new Set(graph.tasks.filter((t) => t.status === "done").map((t) => t.id));
22868
- const blocked = new Set(graph.tasks.filter((t) => t.status === "blocked").map((t) => t.id));
23352
+ const order = new Map(graph.tasks.map((task, index) => [task.id, index]));
22869
23353
  return graph.tasks.filter((task) => {
22870
23354
  if (task.status !== "pending")
22871
23355
  return false;
22872
- if (blocked.has(task.id))
22873
- return false;
22874
23356
  const deps = task.depends_on ?? [];
22875
23357
  return deps.every((d) => done.has(d));
22876
- });
23358
+ }).sort((a, b) => (a.priority ?? "P2").localeCompare(b.priority ?? "P2") || order.get(a.id) - order.get(b.id) || a.id.localeCompare(b.id));
22877
23359
  }
22878
23360
  function goalTaskToCanonicalCard(task, objective) {
22879
23361
  return {
@@ -22918,9 +23400,29 @@ function buildTaskEnvelope(card, projectRoot, projectName) {
22918
23400
  };
22919
23401
  }
22920
23402
  async function getNextTask(projectRoot, projectName) {
23403
+ return withQueueLock(projectRoot, () => getNextTaskUnlocked(projectRoot, projectName));
23404
+ }
23405
+ async function claimNextTask(projectRoot, projectName) {
23406
+ return withQueueLock(projectRoot, async () => {
23407
+ const next = await getNextTaskUnlocked(projectRoot, projectName);
23408
+ if (!next.success)
23409
+ return next;
23410
+ const started = await startTaskUnlocked(projectRoot, next.data.task.id, next.data.task.agentType);
23411
+ return started.success ? next : started;
23412
+ });
23413
+ }
23414
+ async function completeTask(projectRoot, taskId, evidenceIds) {
23415
+ return withQueueLock(projectRoot, () => completeTaskUnlocked(projectRoot, taskId, evidenceIds));
23416
+ }
23417
+ async function getNextTaskUnlocked(projectRoot, projectName) {
22921
23418
  const goalResult = await loadGoal(projectRoot);
22922
23419
  if (!goalResult.success)
22923
23420
  return goalResult;
23421
+ if (propagateBlockedTasks(goalResult.data)) {
23422
+ const write = await writeGoal(projectRoot, goalResult.data);
23423
+ if (!write.success)
23424
+ return write;
23425
+ }
22924
23426
  const graphResult = await loadGraph(projectRoot);
22925
23427
  const productGraph = graphResult.success ? graphResult.data : undefined;
22926
23428
  const enriched = enrichGoalWithProduct(goalResult.data, productGraph);
@@ -22938,7 +23440,7 @@ async function getNextTask(projectRoot, projectName) {
22938
23440
  readyCount: ready.length
22939
23441
  });
22940
23442
  }
22941
- async function startTask(projectRoot, taskId, agent) {
23443
+ async function startTaskUnlocked(projectRoot, taskId, agent) {
22942
23444
  const goalResult = await loadGoal(projectRoot);
22943
23445
  if (!goalResult.success)
22944
23446
  return goalResult;
@@ -22948,6 +23450,10 @@ async function startTask(projectRoot, taskId, agent) {
22948
23450
  if (task.status !== "pending") {
22949
23451
  return err(new Error(`Task ${taskId} is ${task.status}, expected pending`));
22950
23452
  }
23453
+ const done = new Set(goalResult.data.tasks.filter((t) => t.status === "done").map((t) => t.id));
23454
+ const unmet = (task.depends_on ?? []).filter((id) => !done.has(id));
23455
+ if (unmet.length > 0)
23456
+ return err(new Error(`Task ${taskId} has unmet dependencies: ${unmet.join(", ")}`));
22951
23457
  const stateBefore = await loadOperationalState(projectRoot);
22952
23458
  if (!stateBefore.success)
22953
23459
  return stateBefore;
@@ -22971,7 +23477,7 @@ async function startTask(projectRoot, taskId, agent) {
22971
23477
  }
22972
23478
  return ok(undefined);
22973
23479
  }
22974
- async function completeTask(projectRoot, taskId, evidenceIds) {
23480
+ async function completeTaskUnlocked(projectRoot, taskId, evidenceIds) {
22975
23481
  const goalResult = await loadGoal(projectRoot);
22976
23482
  if (!goalResult.success)
22977
23483
  return goalResult;
@@ -23037,6 +23543,7 @@ function formatGoalStatus(graph) {
23037
23543
  var init_runtime_orchestrator = __esm(() => {
23038
23544
  init_product_planner();
23039
23545
  init_goal_state();
23546
+ init_lock();
23040
23547
  init_graph_store();
23041
23548
  init_episodic_store();
23042
23549
  init_operational_state();
@@ -23611,14 +24118,10 @@ async function handleStatus(projectRoot, output) {
23611
24118
  }
23612
24119
  async function handleNext(projectRoot, output) {
23613
24120
  const projectName = await getProjectName(projectRoot);
23614
- const next = await getNextTask(projectRoot, projectName);
24121
+ const next = await claimNextTask(projectRoot, projectName);
23615
24122
  if (!next.success) {
23616
24123
  return { code: 1, data: { success: false, command: "orchestrate", errors: [next.error.message] } };
23617
24124
  }
23618
- const started = await startTask(projectRoot, next.data.task.id, next.data.task.agentType);
23619
- if (!started.success) {
23620
- return { code: 1, data: { success: false, command: "orchestrate", errors: [started.error.message] } };
23621
- }
23622
24125
  if (output === "json") {
23623
24126
  return {
23624
24127
  code: 0,
@@ -23976,6 +24479,54 @@ var init_verify_command = __esm(() => {
23976
24479
  init_verification_runner();
23977
24480
  });
23978
24481
 
24482
+ // src/commands/tdd.command.ts
24483
+ var exports_tdd_command = {};
24484
+ __export(exports_tdd_command, {
24485
+ tddCommand: () => tddCommand
24486
+ });
24487
+ function fail(errors3) {
24488
+ return { code: 1, data: { success: false, command: "tdd", errors: errors3 } };
24489
+ }
24490
+ async function tddCommand(options) {
24491
+ const { subcommand, projectRoot, taskId, phase, command } = options;
24492
+ if (subcommand !== "capture") {
24493
+ return fail([`Unknown subcommand: ${subcommand}. ${USAGE}`]);
24494
+ }
24495
+ if (!taskId || !command || phase !== "red" && phase !== "green") {
24496
+ return fail([USAGE]);
24497
+ }
24498
+ const captured = await captureTddSuiteEvidence(projectRoot, taskId, {
24499
+ command,
24500
+ phase,
24501
+ allowCompileCheck: options.allowCompileCheck === true
24502
+ });
24503
+ if (!captured.success)
24504
+ return fail([captured.error.message]);
24505
+ const { evidenceId, suiteFailed, suitePassed } = captured.data;
24506
+ const matches = phase === "red" ? suiteFailed : suitePassed;
24507
+ return {
24508
+ code: matches ? 0 : 1,
24509
+ data: {
24510
+ success: matches,
24511
+ command: "tdd capture",
24512
+ taskId,
24513
+ phase,
24514
+ evidenceId,
24515
+ suiteFailed,
24516
+ suitePassed,
24517
+ ...matches ? {} : {
24518
+ errors: [
24519
+ phase === "red" ? "RED requires a failing suite, but the suite passed: the test proves nothing." : "GREEN requires a passing suite, but the suite failed."
24520
+ ]
24521
+ }
24522
+ }
24523
+ };
24524
+ }
24525
+ var USAGE = 'Usage: tdd capture --task <cardId> --phase red|green --command "<test command>" [--allow-compile-check]';
24526
+ var init_tdd_command = __esm(() => {
24527
+ init_verification_runner();
24528
+ });
24529
+
23979
24530
  // src/commands/rdd.command.ts
23980
24531
  var exports_rdd_command = {};
23981
24532
  __export(exports_rdd_command, {
@@ -23984,18 +24535,18 @@ __export(exports_rdd_command, {
23984
24535
  });
23985
24536
  import { execFile as execFile4 } from "node:child_process";
23986
24537
  import { existsSync as existsSync4 } from "node:fs";
23987
- import { mkdir as mkdir18, readFile as readFile30, readdir as readdir9, rename as rename3, writeFile as writeFile18, chmod } from "node:fs/promises";
23988
- import { dirname as dirname10, resolve as resolve28 } from "node:path";
24538
+ import { mkdir as mkdir20, readFile as readFile31, readdir as readdir9, rename as rename4, writeFile as writeFile19, chmod } from "node:fs/promises";
24539
+ import { dirname as dirname11, resolve as resolve29 } from "node:path";
23989
24540
  import { promisify as promisify4 } from "node:util";
23990
24541
  function receiptPath(projectRoot, id) {
23991
- const directory = resolve28(evidenceDir(projectRoot));
23992
- const path = resolve28(directory, `${id.replace(/[^A-Za-z0-9_-]/g, "_")}.json`);
23993
- if (dirname10(path) !== directory)
24542
+ const directory = resolve29(evidenceDir(projectRoot));
24543
+ const path = resolve29(directory, `${id.replace(/[^A-Za-z0-9_-]/g, "_")}.json`);
24544
+ if (dirname11(path) !== directory)
23994
24545
  throw new Error(`Invalid RDD receipt id: ${id}`);
23995
24546
  return path;
23996
24547
  }
23997
24548
  async function loadReceipt(projectRoot, id) {
23998
- const raw = await readFile30(receiptPath(projectRoot, id), "utf-8");
24549
+ const raw = await readFile31(receiptPath(projectRoot, id), "utf-8");
23999
24550
  const evidence = EvidenceSchema.parse(JSON.parse(raw));
24000
24551
  if (evidence.type !== "rdd")
24001
24552
  throw new Error(`Evidence "${id}" is not an RDD receipt`);
@@ -24037,16 +24588,16 @@ async function installHooks(projectRoot) {
24037
24588
  cwd: projectRoot,
24038
24589
  encoding: "utf8"
24039
24590
  });
24040
- const hooksDir = resolve28(projectRoot, stdout.trim());
24041
- await mkdir18(hooksDir, { recursive: true });
24591
+ const hooksDir = resolve29(projectRoot, stdout.trim());
24592
+ await mkdir20(hooksDir, { recursive: true });
24042
24593
  const installed = [];
24043
24594
  const skipped = [];
24044
24595
  for (const hook of ["pre-commit", "pre-push"]) {
24045
- const path = resolve28(hooksDir, hook);
24046
- const backup = resolve28(hooksDir, `${hook}.rdd-original`);
24596
+ const path = resolve29(hooksDir, hook);
24597
+ const backup = resolve29(hooksDir, `${hook}.rdd-original`);
24047
24598
  const marker = "# codeconductor-rdd-hook";
24048
24599
  if (existsSync4(path)) {
24049
- const existing = await readFile30(path, "utf8");
24600
+ const existing = await readFile31(path, "utf8");
24050
24601
  if (existing.includes(marker)) {
24051
24602
  skipped.push(hook);
24052
24603
  continue;
@@ -24054,7 +24605,7 @@ async function installHooks(projectRoot) {
24054
24605
  if (existsSync4(backup)) {
24055
24606
  throw new Error(`Cannot preserve ${hook}: ${backup} already exists`);
24056
24607
  }
24057
- await rename3(path, backup);
24608
+ await rename4(path, backup);
24058
24609
  }
24059
24610
  const script = `#!/bin/sh
24060
24611
  ${marker}
@@ -24065,7 +24616,7 @@ if [ -x "$HOOK_DIR/${hook}.rdd-original" ]; then
24065
24616
  fi
24066
24617
  cc-codeconductor rdd git-check
24067
24618
  `;
24068
- await writeFile18(path, script, "utf8");
24619
+ await writeFile19(path, script, "utf8");
24069
24620
  await chmod(path, 493);
24070
24621
  installed.push(hook);
24071
24622
  }
@@ -24097,8 +24648,8 @@ async function rddCommand(options) {
24097
24648
  data: { rddReceipt: receipt }
24098
24649
  };
24099
24650
  const directory = evidenceDir(options.projectRoot);
24100
- await mkdir18(directory, { recursive: true });
24101
- await writeFile18(receiptPath(options.projectRoot, id), JSON.stringify(evidence, null, 2), "utf-8");
24651
+ await mkdir20(directory, { recursive: true });
24652
+ await writeFile19(receiptPath(options.projectRoot, id), JSON.stringify(evidence, null, 2), "utf-8");
24102
24653
  return { code: 0, data: { success: true, receiptId: id, receipt } };
24103
24654
  }
24104
24655
  if (options.subcommand === "verify") {
@@ -24324,15 +24875,7 @@ var init_output_validator = __esm(() => {
24324
24875
 
24325
24876
  // src/core/ccep/prompt-compiler.ts
24326
24877
  function buildSystemLayer() {
24327
- return [
24328
- "You are a CodeConductor agent operating under CCEP-1.",
24329
- "Rules:",
24330
- "- Do not invent context.",
24331
- "- If critical data is missing, return questions in structured output.",
24332
- "- Produce valid JSON only — no free-form prose as the final answer.",
24333
- "- Match the output schema exactly."
24334
- ].join(`
24335
- `);
24878
+ return "You are a CodeConductor agent (CCEP-1): never invent context; missing critical data goes to structured output as questions; the final answer is valid JSON only, matching the output schema exactly.";
24336
24879
  }
24337
24880
  function buildAgentLayer(role, phase, outputSchema) {
24338
24881
  const label = ROLE_LABELS[role] ?? role;
@@ -24342,11 +24885,11 @@ function buildAgentLayer(role, phase, outputSchema) {
24342
24885
  Convert product intent into a structured plan without writing code.`;
24343
24886
  } else if (role === "implementer") {
24344
24887
  instruction = `You are the ${label}.
24345
- Execute only your assigned phase: ${phase}.
24888
+ Work only on phase ${phase}.
24346
24889
  Write the minimal diff.`;
24347
24890
  } else {
24348
24891
  instruction = `You are the ${label}.
24349
- Execute only your assigned phase: ${phase}.`;
24892
+ Work only on phase ${phase}.`;
24350
24893
  }
24351
24894
  return `${instruction}
24352
24895
  Return ${outputSchema} JSON only.`;
@@ -24511,13 +25054,13 @@ var init_prompt_compiler = __esm(() => {
24511
25054
  });
24512
25055
 
24513
25056
  // src/core/ccep/command-parser.ts
24514
- import { existsSync as existsSync5, readFileSync as readFileSync3 } from "node:fs";
24515
- import { basename as basename7, join as join21 } from "node:path";
25057
+ import { existsSync as existsSync5, readFileSync as readFileSync4 } from "node:fs";
25058
+ import { basename as basename7, join as join22 } from "node:path";
24516
25059
  function readProjectId(projectRoot) {
24517
- const packageJsonPath = join21(projectRoot, "package.json");
25060
+ const packageJsonPath = join22(projectRoot, "package.json");
24518
25061
  if (existsSync5(packageJsonPath)) {
24519
25062
  try {
24520
- const pkg = JSON.parse(readFileSync3(packageJsonPath, "utf-8"));
25063
+ const pkg = JSON.parse(readFileSync4(packageJsonPath, "utf-8"));
24521
25064
  if (pkg.name) {
24522
25065
  return pkg.name;
24523
25066
  }
@@ -24544,10 +25087,10 @@ function parseCommand(command, userRequest, projectRoot) {
24544
25087
  maxVariance: "low"
24545
25088
  }
24546
25089
  };
24547
- const packageJsonPath = join21(projectRoot, "package.json");
25090
+ const packageJsonPath = join22(projectRoot, "package.json");
24548
25091
  if (existsSync5(packageJsonPath)) {
24549
25092
  try {
24550
- const pkg = JSON.parse(readFileSync3(packageJsonPath, "utf-8"));
25093
+ const pkg = JSON.parse(readFileSync4(packageJsonPath, "utf-8"));
24551
25094
  const deps = { ...pkg.dependencies, ...pkg.devDependencies };
24552
25095
  const stack = ["typescript"];
24553
25096
  if (deps?.next)
@@ -24617,10 +25160,10 @@ var init_workflow_profile_loader = __esm(() => {
24617
25160
  });
24618
25161
 
24619
25162
  // src/core/evaluation/harness-catalog.ts
24620
- import { createHash as createHash5 } from "node:crypto";
24621
- import { existsSync as existsSync6, readFileSync as readFileSync4 } from "node:fs";
24622
- import { copyFile as copyFile2, mkdir as mkdir19, readFile as readFile31, readdir as readdir10, rm as rm4, writeFile as writeFile19 } from "node:fs/promises";
24623
- import { dirname as dirname11, join as join22, resolve as resolve29 } from "node:path";
25163
+ import { createHash as createHash6 } from "node:crypto";
25164
+ import { existsSync as existsSync6, readFileSync as readFileSync5 } from "node:fs";
25165
+ import { copyFile as copyFile2, mkdir as mkdir21, readFile as readFile32, readdir as readdir10, rm as rm4, writeFile as writeFile20 } from "node:fs/promises";
25166
+ import { dirname as dirname12, join as join23, resolve as resolve30 } from "node:path";
24624
25167
  function catalogIds(catalog = DEFAULT_HARNESS_CATALOG) {
24625
25168
  return catalog.components.map((c) => c.id);
24626
25169
  }
@@ -24670,23 +25213,23 @@ function harnessFingerprint(disabled, contractVersion, ccepProfile = "feature",
24670
25213
  contractVersion,
24671
25214
  ccepProfile
24672
25215
  };
24673
- return createHash5("sha256").update(JSON.stringify(payload)).digest("hex").slice(0, 16);
25216
+ return createHash6("sha256").update(JSON.stringify(payload)).digest("hex").slice(0, 16);
24674
25217
  }
24675
25218
  async function loadHarnessCatalog(projectRoot) {
24676
- const overridePath = resolve29(projectRoot, EVAL_DIR2, CATALOG_FILE);
25219
+ const overridePath = resolve30(projectRoot, EVAL_DIR2, CATALOG_FILE);
24677
25220
  try {
24678
- const raw = await readFile31(overridePath, "utf-8");
25221
+ const raw = await readFile32(overridePath, "utf-8");
24679
25222
  return HarnessCatalogSchema.parse($parse(raw));
24680
25223
  } catch {
24681
25224
  return DEFAULT_HARNESS_CATALOG;
24682
25225
  }
24683
25226
  }
24684
25227
  function activeOverlayPath(projectRoot) {
24685
- return resolve29(projectRoot, EVAL_DIR2, ACTIVE_OVERLAY_FILE);
25228
+ return resolve30(projectRoot, EVAL_DIR2, ACTIVE_OVERLAY_FILE);
24686
25229
  }
24687
25230
  async function readActiveOverlay(projectRoot) {
24688
25231
  try {
24689
- const raw = await readFile31(activeOverlayPath(projectRoot), "utf-8");
25232
+ const raw = await readFile32(activeOverlayPath(projectRoot), "utf-8");
24690
25233
  return HarnessOverlaySchema.parse($parse(raw));
24691
25234
  } catch {
24692
25235
  return null;
@@ -24697,7 +25240,7 @@ function isProductGraphDisabled(projectRoot) {
24697
25240
  const path = activeOverlayPath(projectRoot);
24698
25241
  if (!existsSync6(path))
24699
25242
  return false;
24700
- const overlay = HarnessOverlaySchema.parse($parse(readFileSync4(path, "utf-8")));
25243
+ const overlay = HarnessOverlaySchema.parse($parse(readFileSync5(path, "utf-8")));
24701
25244
  return overlay.disableProductGraph === true || overlay.disabledComponents.includes("product_graph");
24702
25245
  } catch {
24703
25246
  return false;
@@ -24740,25 +25283,25 @@ function applyCatalogToProfile(profile, disabled) {
24740
25283
  return next;
24741
25284
  }
24742
25285
  async function restoreOverlayBackup(projectRoot) {
24743
- const backupRoot = resolve29(projectRoot, EVAL_DIR2, OVERLAY_BACKUP_DIR);
25286
+ const backupRoot = resolve30(projectRoot, EVAL_DIR2, OVERLAY_BACKUP_DIR);
24744
25287
  if (!existsSync6(backupRoot))
24745
25288
  return;
24746
- const configBackup = join22(backupRoot, "config.yml");
24747
- const configDest = resolve29(projectRoot, ".codeconductor", "config.yml");
25289
+ const configBackup = join23(backupRoot, "config.yml");
25290
+ const configDest = resolve30(projectRoot, ".codeconductor", "config.yml");
24748
25291
  if (existsSync6(configBackup)) {
24749
- await mkdir19(dirname11(configDest), { recursive: true });
25292
+ await mkdir21(dirname12(configDest), { recursive: true });
24750
25293
  await copyFile2(configBackup, configDest);
24751
25294
  }
24752
- const workflowsBackup = join22(backupRoot, "workflows");
24753
- const workflowsDest = resolve29(projectRoot, ".codeconductor", "workflows");
25295
+ const workflowsBackup = join23(backupRoot, "workflows");
25296
+ const workflowsDest = resolve30(projectRoot, ".codeconductor", "workflows");
24754
25297
  if (existsSync6(workflowsBackup)) {
24755
- await mkdir19(workflowsDest, { recursive: true });
25298
+ await mkdir21(workflowsDest, { recursive: true });
24756
25299
  const files = await readdir10(workflowsBackup);
24757
25300
  for (const file of files) {
24758
- await copyFile2(join22(workflowsBackup, file), join22(workflowsDest, file));
25301
+ await copyFile2(join23(workflowsBackup, file), join23(workflowsDest, file));
24759
25302
  }
24760
25303
  }
24761
- const overlayBackup = join22(backupRoot, ACTIVE_OVERLAY_FILE);
25304
+ const overlayBackup = join23(backupRoot, ACTIVE_OVERLAY_FILE);
24762
25305
  const overlayDest = activeOverlayPath(projectRoot);
24763
25306
  if (existsSync6(overlayBackup)) {
24764
25307
  await copyFile2(overlayBackup, overlayDest);
@@ -24767,28 +25310,28 @@ async function restoreOverlayBackup(projectRoot) {
24767
25310
  }
24768
25311
  }
24769
25312
  async function snapshotForBackup(projectRoot) {
24770
- const backupRoot = resolve29(projectRoot, EVAL_DIR2, OVERLAY_BACKUP_DIR);
25313
+ const backupRoot = resolve30(projectRoot, EVAL_DIR2, OVERLAY_BACKUP_DIR);
24771
25314
  if (existsSync6(backupRoot))
24772
25315
  return;
24773
- await mkdir19(backupRoot, { recursive: true });
24774
- const configPath = resolve29(projectRoot, ".codeconductor", "config.yml");
25316
+ await mkdir21(backupRoot, { recursive: true });
25317
+ const configPath = resolve30(projectRoot, ".codeconductor", "config.yml");
24775
25318
  if (existsSync6(configPath)) {
24776
- await copyFile2(configPath, join22(backupRoot, "config.yml"));
25319
+ await copyFile2(configPath, join23(backupRoot, "config.yml"));
24777
25320
  }
24778
- const workflowsDir = resolve29(projectRoot, ".codeconductor", "workflows");
25321
+ const workflowsDir = resolve30(projectRoot, ".codeconductor", "workflows");
24779
25322
  if (existsSync6(workflowsDir)) {
24780
- const dest = join22(backupRoot, "workflows");
24781
- await mkdir19(dest, { recursive: true });
25323
+ const dest = join23(backupRoot, "workflows");
25324
+ await mkdir21(dest, { recursive: true });
24782
25325
  const files = await readdir10(workflowsDir);
24783
25326
  for (const file of files) {
24784
25327
  if (file.endsWith(".yml")) {
24785
- await copyFile2(join22(workflowsDir, file), join22(dest, file));
25328
+ await copyFile2(join23(workflowsDir, file), join23(dest, file));
24786
25329
  }
24787
25330
  }
24788
25331
  }
24789
25332
  const overlay = activeOverlayPath(projectRoot);
24790
25333
  if (existsSync6(overlay)) {
24791
- await copyFile2(overlay, join22(backupRoot, ACTIVE_OVERLAY_FILE));
25334
+ await copyFile2(overlay, join23(backupRoot, ACTIVE_OVERLAY_FILE));
24792
25335
  }
24793
25336
  }
24794
25337
  async function applyHarnessOverlay(projectRoot, disabled, options = {}) {
@@ -24797,13 +25340,13 @@ async function applyHarnessOverlay(projectRoot, disabled, options = {}) {
24797
25340
  await restoreOverlayBackup(projectRoot);
24798
25341
  await snapshotForBackup(projectRoot);
24799
25342
  }
24800
- const workflowsDir = resolve29(projectRoot, ".codeconductor", "workflows");
24801
- await mkdir19(workflowsDir, { recursive: true });
24802
- await mkdir19(resolve29(projectRoot, EVAL_DIR2), { recursive: true });
25343
+ const workflowsDir = resolve30(projectRoot, ".codeconductor", "workflows");
25344
+ await mkdir21(workflowsDir, { recursive: true });
25345
+ await mkdir21(resolve30(projectRoot, EVAL_DIR2), { recursive: true });
24803
25346
  for (const command of WORKFLOW_OVERLAY_COMMANDS) {
24804
25347
  const base = loadWorkflowProfile(command);
24805
25348
  const next = applyCatalogToProfile(base, disabled);
24806
- await writeFile19(join22(workflowsDir, `${command}.yml`), $stringify(next), "utf-8");
25349
+ await writeFile20(join23(workflowsDir, `${command}.yml`), $stringify(next), "utf-8");
24807
25350
  }
24808
25351
  const needsConfig = disabled.includes("compile_loop") || disabled.includes("council");
24809
25352
  if (needsConfig) {
@@ -24831,7 +25374,7 @@ async function applyHarnessOverlay(projectRoot, disabled, options = {}) {
24831
25374
  contractVersion: options.contractVersion,
24832
25375
  ccepProfile: options.ccepProfile ?? "feature"
24833
25376
  });
24834
- await writeFile19(activeOverlayPath(projectRoot), $stringify(overlay), "utf-8");
25377
+ await writeFile20(activeOverlayPath(projectRoot), $stringify(overlay), "utf-8");
24835
25378
  return ok(overlay);
24836
25379
  } catch (e) {
24837
25380
  return err(e instanceof Error ? e : new Error(String(e)));
@@ -24942,9 +25485,9 @@ var init_harness_catalog = __esm(() => {
24942
25485
  });
24943
25486
 
24944
25487
  // src/core/openspec/openspec-state.ts
24945
- import { createHash as createHash6 } from "node:crypto";
24946
- import { mkdir as mkdir20, readFile as readFile32, rename as rename4, writeFile as writeFile20 } from "node:fs/promises";
24947
- import { resolve as resolve30 } from "node:path";
25488
+ import { createHash as createHash7 } from "node:crypto";
25489
+ import { mkdir as mkdir22, readFile as readFile33, rename as rename5, writeFile as writeFile21 } from "node:fs/promises";
25490
+ import { resolve as resolve31 } from "node:path";
24948
25491
  function canTransition(from, to) {
24949
25492
  return ALLOWED_TRANSITIONS[from]?.includes(to) ?? false;
24950
25493
  }
@@ -24965,13 +25508,13 @@ function applyBacklogTransition(content, itemId, from, to, progress) {
24965
25508
  }
24966
25509
  async function writeFileAtomic(path, content) {
24967
25510
  const tmp = `${path}.${process.pid}.${Date.now()}.tmp`;
24968
- await writeFile20(tmp, content, "utf-8");
24969
- await rename4(tmp, path);
25511
+ await writeFile21(tmp, content, "utf-8");
25512
+ await rename5(tmp, path);
24970
25513
  }
24971
25514
  async function loadOpenspecState(projectRoot) {
24972
25515
  try {
24973
- const filePath = resolve30(projectRoot, STATE_FILE);
24974
- const content = await readFile32(filePath, "utf-8");
25516
+ const filePath = resolve31(projectRoot, STATE_FILE);
25517
+ const content = await readFile33(filePath, "utf-8");
24975
25518
  const data = JSON.parse(content);
24976
25519
  return ok(OpenspecStateSchema.parse(data));
24977
25520
  } catch (e) {
@@ -24988,10 +25531,10 @@ async function loadOpenspecState(projectRoot) {
24988
25531
  }
24989
25532
  async function writeOpenspecState(projectRoot, state) {
24990
25533
  try {
24991
- const dir = resolve30(projectRoot, ".codeconductor");
24992
- await mkdir20(dir, { recursive: true });
25534
+ const dir = resolve31(projectRoot, ".codeconductor");
25535
+ await mkdir22(dir, { recursive: true });
24993
25536
  const validated = OpenspecStateSchema.parse(state);
24994
- await writeFileAtomic(resolve30(dir, "openspec-state.json"), JSON.stringify(validated, null, 2));
25537
+ await writeFileAtomic(resolve31(dir, "openspec-state.json"), JSON.stringify(validated, null, 2));
24995
25538
  return ok(undefined);
24996
25539
  } catch (e) {
24997
25540
  return err(e instanceof Error ? e : new Error(String(e)));
@@ -25013,7 +25556,7 @@ function getNextTaskCard(state) {
25013
25556
  return null;
25014
25557
  }
25015
25558
  function hashContent(content) {
25016
- return createHash6("sha256").update(content).digest("hex").slice(0, 16);
25559
+ return createHash7("sha256").update(content).digest("hex").slice(0, 16);
25017
25560
  }
25018
25561
  function serializeItemSnapshot(item) {
25019
25562
  return JSON.stringify({
@@ -25063,7 +25606,12 @@ function archiveItemInMarkdown(content, itemId) {
25063
25606
  break;
25064
25607
  }
25065
25608
  }
25066
- const block = lines.slice(itemStart, itemEnd);
25609
+ let inAcceptance = false;
25610
+ const block = lines.slice(itemStart, itemEnd).map((l) => {
25611
+ if (/^-\s+\w+:/.test(l))
25612
+ inAcceptance = /^-\s+Acceptance:/i.test(l);
25613
+ return inAcceptance ? l.replace(/^(\s*-\s+)\[ \]/, "$1[x]") : l;
25614
+ });
25067
25615
  const statusLine = block.findIndex((l) => l.match(/^-\s+Status:/i));
25068
25616
  if (statusLine >= 0)
25069
25617
  block[statusLine] = "- Status: DONE";
@@ -25096,8 +25644,8 @@ var init_openspec_state = __esm(() => {
25096
25644
 
25097
25645
  // src/core/ccep/context-resolver.ts
25098
25646
  import { existsSync as existsSync7 } from "node:fs";
25099
- import { readFile as readFile33 } from "node:fs/promises";
25100
- import { join as join23 } from "node:path";
25647
+ import { readFile as readFile34 } from "node:fs/promises";
25648
+ import { join as join24 } from "node:path";
25101
25649
  async function loadProductKnowledge(projectRoot) {
25102
25650
  if (isProductGraphDisabled(projectRoot)) {
25103
25651
  return {};
@@ -25107,7 +25655,7 @@ async function loadProductKnowledge(projectRoot) {
25107
25655
  return {};
25108
25656
  }
25109
25657
  try {
25110
- const raw = await readFile33(graphPath, "utf-8");
25658
+ const raw = await readFile34(graphPath, "utf-8");
25111
25659
  const graph = ProductGraphSchema.parse(JSON.parse(raw));
25112
25660
  return {
25113
25661
  productName: graph.productName,
@@ -25123,7 +25671,7 @@ async function loadProductKnowledge(projectRoot) {
25123
25671
  }
25124
25672
  async function resolveAstSource(projectRoot) {
25125
25673
  if (isProductGraphDisabled(projectRoot)) {
25126
- const graphifyPath2 = join23(projectRoot, "graphify-out", "graph.json");
25674
+ const graphifyPath2 = join24(projectRoot, "graphify-out", "graph.json");
25127
25675
  if (existsSync7(graphifyPath2)) {
25128
25676
  return { source: "graphify", confidence: "medium" };
25129
25677
  }
@@ -25133,7 +25681,7 @@ async function resolveAstSource(projectRoot) {
25133
25681
  if (existsSync7(graphPath)) {
25134
25682
  return { source: "product-graph", confidence: "high" };
25135
25683
  }
25136
- const graphifyPath = join23(projectRoot, "graphify-out", "graph.json");
25684
+ const graphifyPath = join24(projectRoot, "graphify-out", "graph.json");
25137
25685
  if (existsSync7(graphifyPath)) {
25138
25686
  return { source: "graphify", confidence: "medium" };
25139
25687
  }
@@ -26553,11 +27101,11 @@ var init_backlog_scanner = __esm(() => {
26553
27101
  });
26554
27102
 
26555
27103
  // src/core/openspec/backlog-session.ts
26556
- import { readFile as readFile34 } from "node:fs/promises";
26557
- import { resolve as resolve31 } from "node:path";
27104
+ import { readFile as readFile35 } from "node:fs/promises";
27105
+ import { resolve as resolve32 } from "node:path";
26558
27106
  async function loadBacklogSession(projectRoot) {
26559
27107
  try {
26560
- const raw = await readFile34(resolve31(projectRoot, BACKLOG_FILENAME), "utf-8");
27108
+ const raw = await readFile35(resolve32(projectRoot, BACKLOG_FILENAME), "utf-8");
26561
27109
  const parsed = parseBacklogMarkdown(raw);
26562
27110
  if (!parsed.success)
26563
27111
  return parsed;
@@ -26781,8 +27329,8 @@ var init_backlog_planner = __esm(() => {
26781
27329
  });
26782
27330
 
26783
27331
  // src/core/openspec/openspec-generator.ts
26784
- import { access as access7, mkdir as mkdir21, rename as rename5, writeFile as writeFile21 } from "node:fs/promises";
26785
- import { basename as basename8, resolve as resolve32 } from "node:path";
27332
+ import { access as access7, mkdir as mkdir23, readFile as readFile36, rename as rename6, writeFile as writeFile22 } from "node:fs/promises";
27333
+ import { basename as basename8, resolve as resolve33 } from "node:path";
26786
27334
  function pad3(n) {
26787
27335
  return String(n).padStart(3, "0");
26788
27336
  }
@@ -26868,36 +27416,53 @@ ${blocks.join(`
26868
27416
  `)}
26869
27417
  `;
26870
27418
  }
26871
- async function writeTasksMarkdown(projectRoot, changePath, cards, options = {}) {
26872
- await mkdir21(resolve32(projectRoot, changePath), { recursive: true });
26873
- await writeFile21(resolve32(projectRoot, changePath, "tasks.md"), tasksContent(cards, options), "utf-8");
27419
+ async function syncTaskCardCheckbox(projectRoot, changePath, cardId, done) {
27420
+ const file = resolve33(projectRoot, changePath, "tasks.md");
27421
+ let content;
27422
+ try {
27423
+ content = await readFile36(file, "utf-8");
27424
+ } catch (e) {
27425
+ if (e.code === "ENOENT")
27426
+ return;
27427
+ throw e;
27428
+ }
27429
+ const suffix = `(${cardId})`;
27430
+ const updated = content.split(`
27431
+ `).map((line) => /^\s*-\s*\[[ xX]\]/.test(line) && line.trimEnd().endsWith(suffix) ? line.replace(/\[[ xX]\]/, done ? "[x]" : "[ ]") : line).join(`
27432
+ `);
27433
+ if (updated !== content)
27434
+ await writeFile22(file, updated, "utf-8");
26874
27435
  }
26875
27436
  function tasksContent(cards, options = {}) {
26876
27437
  const criteria = options.acceptanceCriteria ?? [];
27438
+ const tag = (phase) => {
27439
+ const card = cards.find((c) => c.phase === phase);
27440
+ return card ? ` (${card.id})` : "";
27441
+ };
26877
27442
  const lines = [
26878
27443
  "# Implementation Tasks",
26879
27444
  "",
26880
27445
  "## Setup",
26881
27446
  "",
26882
- "- [ ] Confirm scope and OpenSpec change folder",
27447
+ `- [ ] Confirm scope and OpenSpec change folder${tag("discover")}`,
26883
27448
  "",
26884
27449
  "## Foundational",
26885
27450
  "",
26886
- "- [ ] Read existing conventions in scope",
27451
+ `- [ ] Read existing conventions in scope${tag("discover")}`,
26887
27452
  "",
26888
27453
  "## Requirements",
26889
27454
  ""
26890
27455
  ];
26891
27456
  if (criteria.length === 0) {
26892
- lines.push("- [ ] Implementation tasks (generated after plan)");
27457
+ lines.push(`- [ ] Implementation tasks (generated after plan)${tag("implement")}`);
26893
27458
  } else {
26894
27459
  for (const [index, criterion] of criteria.entries()) {
26895
27460
  const n = pad3(index + 1);
26896
27461
  if (options.tddRequired) {
26897
- lines.push(`- [ ] Write failing test for FR-${n} (${criterion})`);
27462
+ lines.push(`- [ ] Write failing test for FR-${n} (${criterion})${tag("test")}`);
26898
27463
  }
26899
- lines.push(`- [ ] Implement FR-${n} (${criterion})`);
26900
- lines.push(`- [ ] Verify SC-${n}`);
27464
+ lines.push(`- [ ] Implement FR-${n} (${criterion})${tag("implement")}`);
27465
+ lines.push(`- [ ] Verify SC-${n}${tag("review")}`);
26901
27466
  }
26902
27467
  }
26903
27468
  const phaseCards = cards.filter((c) => c.phase === "implement" || c.phase === "test");
@@ -26909,25 +27474,25 @@ function tasksContent(cards, options = {}) {
26909
27474
  if (phaseCards.length === 0) {
26910
27475
  lines.push("- [ ] Implementation tasks (generated after plan)");
26911
27476
  }
26912
- lines.push("", "## Polish", "", "- [ ] Run openspec analyze and scorecard create --from-diff");
27477
+ lines.push("", "## Polish", "", `- [ ] Run openspec analyze and scorecard create --from-diff${tag("review")}`);
26913
27478
  return lines.join(`
26914
27479
  `);
26915
27480
  }
26916
27481
  async function generateOpenspecChange(projectRoot, item, taskCards, options = {}) {
26917
27482
  const slug = buildChangeSlug(item);
26918
- const changeDir = resolve32(projectRoot, "openspec", "changes", slug);
26919
- await mkdir21(resolve32(changeDir, "specs"), { recursive: true });
27483
+ const changeDir = resolve33(projectRoot, "openspec", "changes", slug);
27484
+ await mkdir23(resolve33(changeDir, "specs"), { recursive: true });
26920
27485
  const taskOpts = {
26921
27486
  tddRequired: options.tddRequired,
26922
27487
  acceptanceCriteria: options.acceptanceCriteria ?? item.acceptanceCriteria
26923
27488
  };
26924
- await writeFile21(resolve32(changeDir, "proposal.md"), proposalContent(item), "utf-8");
26925
- await writeFile21(resolve32(changeDir, "design.md"), designContent(item), "utf-8");
26926
- await writeFile21(resolve32(changeDir, "tasks.md"), tasksContent(taskCards, taskOpts), "utf-8");
27489
+ await writeFile22(resolve33(changeDir, "proposal.md"), proposalContent(item), "utf-8");
27490
+ await writeFile22(resolve33(changeDir, "design.md"), designContent(item), "utf-8");
27491
+ await writeFile22(resolve33(changeDir, "tasks.md"), tasksContent(taskCards, taskOpts), "utf-8");
26927
27492
  const capability = capabilitySlug(item.title);
26928
- await mkdir21(resolve32(changeDir, "specs", capability), { recursive: true });
26929
- await writeFile21(resolve32(changeDir, "specs", capability, "spec.md"), specDelta(item), "utf-8");
26930
- await writeFile21(resolve32(changeDir, "change.yaml"), `version: 1
27493
+ await mkdir23(resolve33(changeDir, "specs", capability), { recursive: true });
27494
+ await writeFile22(resolve33(changeDir, "specs", capability, "spec.md"), specDelta(item), "utf-8");
27495
+ await writeFile22(resolve33(changeDir, "change.yaml"), `version: 1
26931
27496
  backlogId: ${item.id}
26932
27497
  profile: standard
26933
27498
  capabilities:
@@ -26936,11 +27501,11 @@ capabilities:
26936
27501
  return `openspec/changes/${slug}`;
26937
27502
  }
26938
27503
  async function archiveChangeFolder(projectRoot, changePath) {
26939
- const src = resolve32(projectRoot, changePath);
27504
+ const src = resolve33(projectRoot, changePath);
26940
27505
  const slug = basename8(changePath);
26941
- const destDir = resolve32(projectRoot, "openspec", "changes", "archive");
26942
- await mkdir21(destDir, { recursive: true });
26943
- const dest = resolve32(destDir, slug);
27506
+ const destDir = resolve33(projectRoot, "openspec", "changes", "archive");
27507
+ await mkdir23(destDir, { recursive: true });
27508
+ const dest = resolve33(destDir, slug);
26944
27509
  try {
26945
27510
  await access7(dest);
26946
27511
  throw new Error(`Archive destination already exists: openspec/changes/archive/${slug}`);
@@ -26949,20 +27514,20 @@ async function archiveChangeFolder(projectRoot, changePath) {
26949
27514
  throw error;
26950
27515
  }
26951
27516
  }
26952
- await rename5(src, dest);
27517
+ await rename6(src, dest);
26953
27518
  return `openspec/changes/archive/${slug}`;
26954
27519
  }
26955
27520
  async function ensureOpenspecConfig(projectRoot) {
26956
- const configPath = resolve32(projectRoot, "openspec", "config.yaml");
27521
+ const configPath = resolve33(projectRoot, "openspec", "config.yaml");
26957
27522
  try {
26958
27523
  const { access: access8 } = await import("node:fs/promises");
26959
27524
  await access8(configPath);
26960
27525
  } catch {
26961
- await mkdir21(resolve32(projectRoot, "openspec"), { recursive: true });
27526
+ await mkdir23(resolve33(projectRoot, "openspec"), { recursive: true });
26962
27527
  const stub = `# OpenSpec project config (CodeConductor native compatible)
26963
27528
  schema: spec-driven
26964
27529
  `;
26965
- await writeFile21(configPath, stub, "utf-8");
27530
+ await writeFile22(configPath, stub, "utf-8");
26966
27531
  }
26967
27532
  }
26968
27533
  var init_openspec_generator = __esm(() => {
@@ -26971,8 +27536,31 @@ var init_openspec_generator = __esm(() => {
26971
27536
  });
26972
27537
 
26973
27538
  // src/core/openspec/spec-files.ts
26974
- import { readFile as readFile35, readdir as readdir11 } from "node:fs/promises";
26975
- import { join as join24 } from "node:path";
27539
+ import { readFile as readFile37, readdir as readdir11 } from "node:fs/promises";
27540
+ import { basename as basename9, dirname as dirname13, join as join25 } from "node:path";
27541
+ function requirementId(name, capability) {
27542
+ const frId = name.match(/\bFR-\d{3}\b/)?.[0];
27543
+ if (frId)
27544
+ return frId;
27545
+ return `req:${capability}/${specNameSlug(name)}`;
27546
+ }
27547
+ function specNameSlug(name) {
27548
+ return name.normalize("NFKD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
27549
+ }
27550
+ function specCapability(path) {
27551
+ return basename9(path) === "spec.md" ? basename9(dirname13(path)) : basename9(path, ".md");
27552
+ }
27553
+ function hasMalformedRenames(markdown) {
27554
+ const sections = [...markdown.matchAll(/^## (ADDED|MODIFIED|REMOVED|RENAMED) Requirements\s*$/gm)];
27555
+ return sections.some((section, index) => {
27556
+ if (section[1] !== "RENAMED")
27557
+ return false;
27558
+ const text = markdown.slice((section.index ?? 0) + section[0].length, sections[index + 1]?.index ?? markdown.length).split(/^## /m, 1)[0] ?? "";
27559
+ const renamed = requirementBlocks(`## RENAMED Requirements
27560
+ ${text}`).filter((block) => block.renamedFrom);
27561
+ return renamed.length === 0 || renamed.some((block) => block.id?.endsWith("/") || block.renamedFrom?.endsWith("/")) || (text.match(/^- (?:FROM|TO):/gm)?.length ?? 0) !== renamed.length * 2;
27562
+ });
27563
+ }
26976
27564
  async function walkMarkdownFiles(dir) {
26977
27565
  let entries;
26978
27566
  try {
@@ -26982,7 +27570,7 @@ async function walkMarkdownFiles(dir) {
26982
27570
  }
26983
27571
  const files = [];
26984
27572
  for (const entry of entries) {
26985
- const path = join24(dir, entry.name);
27573
+ const path = join25(dir, entry.name);
26986
27574
  if (entry.isDirectory()) {
26987
27575
  files.push(...await walkMarkdownFiles(path));
26988
27576
  } else if (entry.isFile() && entry.name.endsWith(".md")) {
@@ -26995,18 +27583,46 @@ async function readMarkdownFiles(dir) {
26995
27583
  const files = await walkMarkdownFiles(dir);
26996
27584
  const out = [];
26997
27585
  for (const path of files) {
26998
- out.push({ path, content: await readFile35(path, "utf-8") });
27586
+ out.push({ path, content: await readFile37(path, "utf-8") });
26999
27587
  }
27000
27588
  return out;
27001
27589
  }
27002
- function requirementBlocks(markdown) {
27590
+ function requirementBlocks(markdown, capability) {
27003
27591
  const starts = [...markdown.matchAll(/^### Requirement:.*$/gm)];
27004
- return starts.map((match, index) => {
27592
+ const sections = [...markdown.matchAll(/^## (ADDED|MODIFIED|REMOVED|RENAMED) Requirements\s*$/gm)];
27593
+ const headings = [...markdown.matchAll(/^## (.*)$/gm)];
27594
+ const blocks = starts.map((match, index) => {
27005
27595
  const start = match.index ?? 0;
27006
- const end = starts[index + 1]?.index ?? markdown.length;
27596
+ const heading = [...headings].reverse().find((entry) => (entry.index ?? 0) < start);
27597
+ const operation = heading?.[1]?.trim().match(/^(ADDED|MODIFIED|REMOVED|RENAMED) Requirements$/)?.[1];
27598
+ const nextSection = markdown.slice(start).search(/^## /m);
27599
+ const end = Math.min(starts[index + 1]?.index ?? markdown.length, nextSection < 0 ? markdown.length : start + nextSection);
27007
27600
  const block = markdown.slice(start, end).trim();
27008
- return { id: block.match(REQUIREMENT_HEADING)?.[1] ?? null, markdown: block };
27601
+ const name = match[0].replace(/^### Requirement:\s*/, "").trim();
27602
+ return {
27603
+ id: block.match(REQUIREMENT_HEADING)?.[1] ?? requirementId(name, capability ?? "spec"),
27604
+ markdown: block,
27605
+ name,
27606
+ deltaOperation: operation
27607
+ };
27009
27608
  });
27609
+ for (const [index, section] of sections.entries()) {
27610
+ if (section[1] !== "RENAMED")
27611
+ continue;
27612
+ const text = markdown.slice((section.index ?? 0) + section[0].length, sections[index + 1]?.index ?? markdown.length).split(/^## /m, 1)[0] ?? "";
27613
+ const pairs = [...text.matchAll(/^- FROM:\s*`?### Requirement:\s*(.*?)`?\s*\r?\n- TO:\s*`?### Requirement:\s*(.*?)`?\s*$/gm)];
27614
+ for (const pair of pairs) {
27615
+ const name = pair[2] ?? "";
27616
+ blocks.push({
27617
+ id: requirementId(name, capability ?? "spec"),
27618
+ markdown: pair[0],
27619
+ name,
27620
+ deltaOperation: "RENAMED",
27621
+ renamedFrom: requirementId(pair[1] ?? "", capability ?? "spec")
27622
+ });
27623
+ }
27624
+ }
27625
+ return blocks;
27010
27626
  }
27011
27627
  var REQUIREMENT_HEADING;
27012
27628
  var init_spec_files = __esm(() => {
@@ -27014,8 +27630,8 @@ var init_spec_files = __esm(() => {
27014
27630
  });
27015
27631
 
27016
27632
  // src/core/openspec/spec-quality.ts
27017
- import { readFile as readFile36 } from "node:fs/promises";
27018
- import { join as join25, relative as relative10, resolve as resolve33 } from "node:path";
27633
+ import { readFile as readFile38 } from "node:fs/promises";
27634
+ import { join as join26, relative as relative10, resolve as resolve34 } from "node:path";
27019
27635
  function uniqueIds(matches) {
27020
27636
  return [...new Set(matches ?? [])];
27021
27637
  }
@@ -27023,10 +27639,15 @@ function assessSpecMarkdown(content, path) {
27023
27639
  const issues = [];
27024
27640
  const clarifications = content.match(NEEDS_CLARIFICATION) ?? [];
27025
27641
  const needsClarificationCount = clarifications.length;
27026
- const frIds = uniqueIds(content.match(FR_ID));
27642
+ const blocks = requirementBlocks(content, specCapability(path));
27643
+ const frIds = [...new Set(blocks.map((block) => block.id).filter((id) => /^FR-\d{3}$/.test(id ?? "")))];
27027
27644
  const scIds = uniqueIds(content.match(SC_ID));
27028
27645
  const usAcIds = uniqueIds(content.match(US_AC));
27029
- const hasTraceIds = frIds.length > 0 && (scIds.length > 0 || usAcIds.length > 0);
27646
+ const legacy = blocks.some((block) => /^FR-\d{3}$/.test(block.id ?? "") && block.deltaOperation !== "REMOVED" && block.deltaOperation !== "RENAMED");
27647
+ const hasTraceIds = !legacy || scIds.length > 0 || usAcIds.length > 0;
27648
+ if (hasMalformedRenames(content)) {
27649
+ issues.push({ code: "MALFORMED_RENAME", message: "RENAMED requires paired FROM/TO requirement headings", path, severity: "error" });
27650
+ }
27030
27651
  if (PLACEHOLDER.test(content)) {
27031
27652
  issues.push({
27032
27653
  code: "PLACEHOLDER",
@@ -27051,7 +27672,6 @@ function assessSpecMarkdown(content, path) {
27051
27672
  severity: "error"
27052
27673
  });
27053
27674
  }
27054
- const blocks = requirementBlocks(content);
27055
27675
  if (blocks.length === 0) {
27056
27676
  issues.push({
27057
27677
  code: "MISSING_REQUIREMENT",
@@ -27060,8 +27680,15 @@ function assessSpecMarkdown(content, path) {
27060
27680
  severity: "error"
27061
27681
  });
27062
27682
  }
27683
+ const officialScenarios = [];
27063
27684
  for (const block of blocks) {
27685
+ if (!block.name?.trim() || block.id?.endsWith("/")) {
27686
+ issues.push({ code: "INVALID_REQUIREMENT_NAME", message: "Requirement names MUST produce a nonempty stable ID", path, severity: "error" });
27687
+ }
27688
+ if (block.deltaOperation === "REMOVED" || block.deltaOperation === "RENAMED")
27689
+ continue;
27064
27690
  const text = block.markdown;
27691
+ const legacyBlock = /^FR-\d{3}$/.test(block.id ?? "");
27065
27692
  const heading = text.split(`
27066
27693
  `, 1)[0] ?? "";
27067
27694
  if (!RFC2119.test(text)) {
@@ -27072,7 +27699,17 @@ function assessSpecMarkdown(content, path) {
27072
27699
  severity: "error"
27073
27700
  });
27074
27701
  }
27075
- if (!GWT.test(text)) {
27702
+ const scenarios = [...text.matchAll(/^#### Scenario:\s*(.+)$/gm)];
27703
+ if (!legacyBlock) {
27704
+ for (const [index, scenario] of scenarios.entries()) {
27705
+ const body = text.slice(scenario.index, scenarios[index + 1]?.index ?? text.length);
27706
+ officialScenarios.push({ id: `${block.id}#${specNameSlug(scenario[1] ?? "")}`, text: scenario[1] ?? "" });
27707
+ if (!/\bWHEN\b[\s\S]*?\bTHEN\b/i.test(body)) {
27708
+ issues.push({ code: "MISSING_GWT", message: `Scenario "${scenario[1]}" MUST include WHEN/THEN steps`, path, severity: "error" });
27709
+ }
27710
+ }
27711
+ }
27712
+ if (legacyBlock ? !GWT.test(text) : scenarios.length === 0) {
27076
27713
  issues.push({
27077
27714
  code: "MISSING_GWT",
27078
27715
  message: `Requirement "${heading}" MUST include a Given/When/Then scenario`,
@@ -27089,8 +27726,14 @@ function assessSpecMarkdown(content, path) {
27089
27726
  severity: "warning"
27090
27727
  });
27091
27728
  }
27092
- const requirements = frIds.map((id) => ({ id, text: id }));
27093
- const successCriteria = [...scIds, ...usAcIds].map((id) => ({ id, text: id }));
27729
+ const requirements = [
27730
+ ...frIds.map((id) => ({ id, text: id })),
27731
+ ...blocks.filter((block) => block.id?.startsWith("req:")).map((block) => ({ id: block.id, text: block.name ?? "" }))
27732
+ ];
27733
+ const successCriteria = [
27734
+ ...[...scIds, ...usAcIds].map((id) => ({ id, text: id })),
27735
+ ...officialScenarios
27736
+ ];
27094
27737
  const errors3 = issues.filter((i) => i.severity === "error");
27095
27738
  return {
27096
27739
  valid: errors3.length === 0,
@@ -27126,8 +27769,8 @@ function mergeSpecQualityReports(reports) {
27126
27769
  };
27127
27770
  }
27128
27771
  async function assessChangeFolder(projectRoot, changePath) {
27129
- const root = resolve33(projectRoot);
27130
- const changeRoot = resolve33(root, changePath);
27772
+ const root = resolve34(projectRoot);
27773
+ const changeRoot = resolve34(root, changePath);
27131
27774
  if (!changeRoot.startsWith(root)) {
27132
27775
  return {
27133
27776
  valid: false,
@@ -27145,18 +27788,18 @@ async function assessChangeFolder(projectRoot, changePath) {
27145
27788
  successCriteria: []
27146
27789
  };
27147
27790
  }
27148
- const specDir = join25(changeRoot, "specs");
27791
+ const specDir = join26(changeRoot, "specs");
27149
27792
  const specFiles = await walkMarkdownFiles(specDir);
27150
- const extra = ["proposal.md", "design.md"].map((name) => join25(changeRoot, name));
27793
+ const extra = ["proposal.md", "design.md"].map((name) => join26(changeRoot, name));
27151
27794
  const reports = [];
27152
27795
  for (const file of specFiles) {
27153
- const content = await readFile36(file, "utf-8");
27796
+ const content = await readFile38(file, "utf-8");
27154
27797
  reports.push(assessSpecMarkdown(content, relative10(root, file).replace(/\\/g, "/")));
27155
27798
  }
27156
27799
  for (const file of extra) {
27157
27800
  let content;
27158
27801
  try {
27159
- content = await readFile36(file, "utf-8");
27802
+ content = await readFile38(file, "utf-8");
27160
27803
  } catch {
27161
27804
  continue;
27162
27805
  }
@@ -27198,11 +27841,10 @@ async function assessChangeFolder(projectRoot, changePath) {
27198
27841
  }
27199
27842
  return mergeSpecQualityReports(reports);
27200
27843
  }
27201
- var RFC2119, FR_ID, SC_ID, US_AC, GWT, NEEDS_CLARIFICATION, PLACEHOLDER, HOW_LEAK, MAX_CLARIFICATIONS = 3;
27844
+ var RFC2119, SC_ID, US_AC, GWT, NEEDS_CLARIFICATION, PLACEHOLDER, HOW_LEAK, MAX_CLARIFICATIONS = 3;
27202
27845
  var init_spec_quality = __esm(() => {
27203
27846
  init_spec_files();
27204
27847
  RFC2119 = /\b(MUST(?: NOT)?|SHALL(?: NOT)?|SHOULD(?: NOT)?|MAY)\b/;
27205
- FR_ID = /\bFR-\d{3}\b/g;
27206
27848
  SC_ID = /\bSC-\d{3}\b/g;
27207
27849
  US_AC = /\b(?:US|AC)#?\d+\b/g;
27208
27850
  GWT = /\bGIVEN\b[\s\S]*?\bWHEN\b[\s\S]*?\bTHEN\b/i;
@@ -27212,8 +27854,8 @@ var init_spec_quality = __esm(() => {
27212
27854
  });
27213
27855
 
27214
27856
  // src/core/openspec/spec-analyzer.ts
27215
- import { readFile as readFile37 } from "node:fs/promises";
27216
- import { join as join26, resolve as resolve34 } from "node:path";
27857
+ import { readFile as readFile39 } from "node:fs/promises";
27858
+ import { join as join27, resolve as resolve35 } from "node:path";
27217
27859
  function unique(ids) {
27218
27860
  return [...new Set(ids)];
27219
27861
  }
@@ -27223,7 +27865,10 @@ function coverage(mapped, total) {
27223
27865
  return Math.round(mapped / total * 1000) / 10;
27224
27866
  }
27225
27867
  function mentionsId(haystack, id) {
27226
- return haystack.includes(id);
27868
+ if (!id.startsWith("req:"))
27869
+ return haystack.includes(id);
27870
+ const escaped = id.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
27871
+ return new RegExp(`(?<![\\w:/#-])${escaped}(?![\\w/-])`).test(haystack);
27227
27872
  }
27228
27873
  function testSection(tasksMarkdown) {
27229
27874
  const lines = tasksMarkdown.split(`
@@ -27237,14 +27882,8 @@ function testSection(tasksMarkdown) {
27237
27882
  return kept.join(`
27238
27883
  `);
27239
27884
  }
27240
- async function readDeltaSpecs(specDir) {
27241
- const files = await readMarkdownFiles(specDir);
27242
- return files.map((f) => f.content).filter(Boolean).join(`
27243
-
27244
- `);
27245
- }
27246
27885
  function analyzeSpecArtifacts(input) {
27247
- const quality = assessSpecMarkdown(input.specMarkdown, `${input.changePath}/specs`);
27886
+ const quality = input.specFiles?.length ? mergeSpecQualityReports(input.specFiles.map((file) => assessSpecMarkdown(file.content, file.path))) : assessSpecMarkdown(input.specMarkdown, input.specPath ?? `${input.changePath}/specs`);
27248
27887
  const frIds = unique(quality.requirements.map((r) => r.id));
27249
27888
  const scIds = unique(quality.successCriteria.map((s) => s.id));
27250
27889
  const tasks = input.tasksMarkdown;
@@ -27314,23 +27953,27 @@ function analyzeSpecArtifacts(input) {
27314
27953
  };
27315
27954
  }
27316
27955
  async function analyzeChangeFolder(projectRoot, changePath, options) {
27317
- const changeRoot = resolve34(projectRoot, changePath);
27318
- const specMarkdown = await readDeltaSpecs(join26(changeRoot, "specs"));
27956
+ const changeRoot = resolve35(projectRoot, changePath);
27957
+ const specFiles = await readMarkdownFiles(join27(changeRoot, "specs"));
27958
+ const specMarkdown = specFiles.map((file) => file.content).join(`
27959
+
27960
+ `);
27319
27961
  let tasksMarkdown = "";
27320
27962
  try {
27321
- tasksMarkdown = await readFile37(join26(changeRoot, "tasks.md"), "utf-8");
27963
+ tasksMarkdown = await readFile39(join27(changeRoot, "tasks.md"), "utf-8");
27322
27964
  } catch {
27323
27965
  tasksMarkdown = "";
27324
27966
  }
27325
27967
  let designMarkdown;
27326
27968
  try {
27327
- designMarkdown = await readFile37(join26(changeRoot, "design.md"), "utf-8");
27969
+ designMarkdown = await readFile39(join27(changeRoot, "design.md"), "utf-8");
27328
27970
  } catch {
27329
27971
  designMarkdown = undefined;
27330
27972
  }
27331
27973
  return analyzeSpecArtifacts({
27332
27974
  changePath,
27333
27975
  specMarkdown,
27976
+ specFiles,
27334
27977
  tasksMarkdown,
27335
27978
  designMarkdown,
27336
27979
  policyText: options.policyText,
@@ -27344,32 +27987,41 @@ var init_spec_analyzer = __esm(() => {
27344
27987
  });
27345
27988
 
27346
27989
  // src/core/openspec/spec-sync.ts
27347
- import { mkdir as mkdir22, readFile as readFile38 } from "node:fs/promises";
27348
- import { join as join27, relative as relative11, resolve as resolve35 } from "node:path";
27349
- function deltaRequirements(markdown) {
27350
- const sections = [...markdown.matchAll(SECTION_HEADING)];
27351
- return sections.flatMap((section, index) => {
27352
- const start = (section.index ?? 0) + section[0].length;
27353
- const end = sections[index + 1]?.index ?? markdown.length;
27354
- const operation = section[1];
27355
- return requirementBlocks(markdown.slice(start, end)).filter((requirement) => requirement.id !== null).map((requirement) => ({
27356
- id: requirement.id,
27357
- markdown: requirement.markdown,
27358
- operation
27359
- }));
27360
- });
27361
- }
27362
- function upsertRequirements(existing, deltas, source) {
27363
- const requirements = requirementBlocks(existing).filter((requirement) => requirement.id !== null);
27990
+ import { mkdir as mkdir24, readFile as readFile40 } from "node:fs/promises";
27991
+ import { join as join28, relative as relative11, resolve as resolve36 } from "node:path";
27992
+ function deltaRequirements(markdown, capability) {
27993
+ return requirementBlocks(markdown, capability).filter((requirement) => requirement.id !== null && requirement.deltaOperation !== undefined).map((requirement) => ({
27994
+ id: requirement.id,
27995
+ markdown: requirement.markdown,
27996
+ operation: requirement.deltaOperation,
27997
+ name: requirement.name,
27998
+ renamedFrom: requirement.renamedFrom
27999
+ })).sort((a, b) => Number(b.operation === "RENAMED") - Number(a.operation === "RENAMED"));
28000
+ }
28001
+ function upsertRequirements(existing, deltas, source, capability) {
28002
+ const requirements = requirementBlocks(existing, capability).filter((requirement) => requirement.id !== null);
27364
28003
  const byId = new Map(requirements.map((requirement) => [requirement.id, requirement]));
27365
28004
  if (byId.size !== requirements.length) {
27366
28005
  return { ok: false, error: `${source}: durable spec has duplicate requirement IDs` };
27367
28006
  }
27368
28007
  const seen = new Set;
28008
+ let next = existing.trimEnd();
27369
28009
  for (const delta of deltas) {
27370
- if (seen.has(delta.id)) {
27371
- return { ok: false, error: `${source}: duplicate delta requirement ${delta.id}` };
28010
+ if (delta.operation === "RENAMED") {
28011
+ const current2 = byId.get(delta.renamedFrom ?? "");
28012
+ if (!current2)
28013
+ return { ok: false, error: `${source}: RENAMED source ${delta.renamedFrom} does not exist` };
28014
+ if (delta.id !== delta.renamedFrom && byId.has(delta.id)) {
28015
+ return { ok: false, error: `${source}: RENAMED destination ${delta.id} already exists` };
28016
+ }
28017
+ const renamed = current2.markdown.replace(/^### Requirement:.*$/m, () => `### Requirement: ${delta.name}`);
28018
+ next = next.replace(current2.markdown, () => renamed);
28019
+ byId.delete(delta.renamedFrom ?? "");
28020
+ byId.set(delta.id, { ...current2, id: delta.id, markdown: renamed });
28021
+ continue;
27372
28022
  }
28023
+ if (seen.has(delta.id))
28024
+ return { ok: false, error: `${source}: duplicate delta requirement ${delta.id}` };
27373
28025
  seen.add(delta.id);
27374
28026
  const current = byId.get(delta.id);
27375
28027
  if (delta.operation === "ADDED" && current) {
@@ -27378,10 +28030,6 @@ function upsertRequirements(existing, deltas, source) {
27378
28030
  if ((delta.operation === "MODIFIED" || delta.operation === "REMOVED") && !current) {
27379
28031
  return { ok: false, error: `${source}: ${delta.operation} requirement ${delta.id} does not exist` };
27380
28032
  }
27381
- }
27382
- let next = existing.trimEnd();
27383
- for (const delta of deltas) {
27384
- const current = byId.get(delta.id);
27385
28033
  if (delta.operation === "ADDED") {
27386
28034
  next = `${next}
27387
28035
 
@@ -27405,9 +28053,9 @@ ${delta.markdown}`;
27405
28053
  ` };
27406
28054
  }
27407
28055
  async function syncChangeSpecs(projectRoot, changePath) {
27408
- const root = resolve35(projectRoot);
27409
- const changeRoot = resolve35(root, changePath);
27410
- const changeSpecs = join27(changeRoot, "specs");
28056
+ const root = resolve36(projectRoot);
28057
+ const changeRoot = resolve36(root, changePath);
28058
+ const changeSpecs = join28(changeRoot, "specs");
27411
28059
  if (changeRoot !== root && !changeRoot.startsWith(`${root}/`)) {
27412
28060
  return { success: false, syncedPaths: [], errors: ["Change path escapes project root"] };
27413
28061
  }
@@ -27417,8 +28065,14 @@ async function syncChangeSpecs(projectRoot, changePath) {
27417
28065
  }
27418
28066
  const writes = [];
27419
28067
  for (const file of files) {
27420
- const delta = await readFile38(file, "utf-8");
27421
- const requirements = deltaRequirements(delta);
28068
+ const delta = await readFile40(file, "utf-8");
28069
+ if (hasMalformedRenames(delta)) {
28070
+ return { success: false, syncedPaths: [], errors: [`${relative11(root, file)}: RENAMED requires paired FROM/TO requirement headings`] };
28071
+ }
28072
+ const requirements = deltaRequirements(delta, specCapability(file));
28073
+ if (requirements.some((requirement) => !requirement.name?.trim() || requirement.id.endsWith("/"))) {
28074
+ return { success: false, syncedPaths: [], errors: [`${relative11(root, file)}: requirement names must produce a nonempty stable ID`] };
28075
+ }
27422
28076
  if (requirements.length === 0) {
27423
28077
  return {
27424
28078
  success: false,
@@ -27427,19 +28081,19 @@ async function syncChangeSpecs(projectRoot, changePath) {
27427
28081
  };
27428
28082
  }
27429
28083
  const relativeSpec = relative11(changeSpecs, file);
27430
- const target = join27(root, "openspec", "specs", relativeSpec);
28084
+ const target = join28(root, "openspec", "specs", relativeSpec);
27431
28085
  let existing = `# ${relativeSpec.replace(/\\/g, "/")}
27432
28086
  `;
27433
28087
  try {
27434
- existing = await readFile38(target, "utf-8");
28088
+ existing = await readFile40(target, "utf-8");
27435
28089
  } catch {}
27436
- const merged = upsertRequirements(existing, requirements, relative11(root, file));
28090
+ const merged = upsertRequirements(existing, requirements, relative11(root, file), specCapability(file));
27437
28091
  if (!merged.ok)
27438
28092
  return { success: false, syncedPaths: [], errors: [merged.error] };
27439
28093
  writes.push({ path: target, content: merged.content });
27440
28094
  }
27441
28095
  for (const write of writes) {
27442
- await mkdir22(resolve35(write.path, ".."), { recursive: true });
28096
+ await mkdir24(resolve36(write.path, ".."), { recursive: true });
27443
28097
  await writeFileAtomic(write.path, write.content);
27444
28098
  }
27445
28099
  return {
@@ -27448,16 +28102,14 @@ async function syncChangeSpecs(projectRoot, changePath) {
27448
28102
  errors: []
27449
28103
  };
27450
28104
  }
27451
- var SECTION_HEADING;
27452
28105
  var init_spec_sync = __esm(() => {
27453
28106
  init_openspec_state();
27454
28107
  init_spec_files();
27455
- SECTION_HEADING = /^## (ADDED|MODIFIED|REMOVED) Requirements\s*$/gm;
27456
28108
  });
27457
28109
 
27458
28110
  // src/core/openspec/artifact-progress.ts
27459
- import { access as access8, readdir as readdir12, readFile as readFile39 } from "node:fs/promises";
27460
- import { join as join28, resolve as resolve36 } from "node:path";
28111
+ import { access as access8, readdir as readdir12, readFile as readFile41 } from "node:fs/promises";
28112
+ import { join as join29, resolve as resolve37 } from "node:path";
27461
28113
  function countCheckboxes(markdown) {
27462
28114
  let total = 0;
27463
28115
  let complete = 0;
@@ -27488,7 +28140,7 @@ async function hasMarkdown(dir) {
27488
28140
  return false;
27489
28141
  }
27490
28142
  for (const entry of entries) {
27491
- const full = join28(dir, entry.name);
28143
+ const full = join29(dir, entry.name);
27492
28144
  if (entry.isFile() && entry.name.endsWith(".md"))
27493
28145
  return true;
27494
28146
  if (entry.isDirectory() && await hasMarkdown(full))
@@ -27497,21 +28149,21 @@ async function hasMarkdown(dir) {
27497
28149
  return false;
27498
28150
  }
27499
28151
  async function readArtifactProgress(projectRoot, changePath) {
27500
- const root = resolve36(projectRoot);
27501
- const changeRoot = resolve36(root, changePath);
28152
+ const root = resolve37(projectRoot);
28153
+ const changeRoot = resolve37(root, changePath);
27502
28154
  if (changeRoot !== root && !changeRoot.startsWith(`${root}/`)) {
27503
28155
  return ABSENT;
27504
28156
  }
27505
28157
  const [proposal, design, tasks, specs] = await Promise.all([
27506
- exists(join28(changeRoot, "proposal.md")),
27507
- exists(join28(changeRoot, "design.md")),
27508
- exists(join28(changeRoot, "tasks.md")),
27509
- hasMarkdown(join28(changeRoot, "specs"))
28158
+ exists(join29(changeRoot, "proposal.md")),
28159
+ exists(join29(changeRoot, "design.md")),
28160
+ exists(join29(changeRoot, "tasks.md")),
28161
+ hasMarkdown(join29(changeRoot, "specs"))
27510
28162
  ]);
27511
28163
  let checkboxes = { total: 0, complete: 0, remaining: 0 };
27512
28164
  if (tasks) {
27513
28165
  try {
27514
- checkboxes = countCheckboxes(await readFile39(join28(changeRoot, "tasks.md"), "utf-8"));
28166
+ checkboxes = countCheckboxes(await readFile41(join29(changeRoot, "tasks.md"), "utf-8"));
27515
28167
  } catch {
27516
28168
  checkboxes = { total: 0, complete: 0, remaining: 0 };
27517
28169
  }
@@ -27544,10 +28196,11 @@ var exports_openspec_command = {};
27544
28196
  __export(exports_openspec_command, {
27545
28197
  openspecCommand: () => openspecCommand
27546
28198
  });
27547
- import { readFile as readFile40 } from "node:fs/promises";
27548
- import { resolve as resolve37 } from "node:path";
28199
+ import { readFile as readFile42 } from "node:fs/promises";
28200
+ import { execFileSync as execFileSync2 } from "node:child_process";
28201
+ import { resolve as resolve38 } from "node:path";
27549
28202
  async function openspecCommand(options) {
27550
- const { subcommand, itemId, projectRoot, output, reason } = options;
28203
+ const { subcommand, itemId, projectRoot, output, reason, allowUnchecked } = options;
27551
28204
  switch (subcommand) {
27552
28205
  case "validate":
27553
28206
  return handleValidate(projectRoot);
@@ -27570,7 +28223,7 @@ async function openspecCommand(options) {
27570
28223
  case "unblock":
27571
28224
  return handleUnblock(projectRoot, itemId);
27572
28225
  case "archive":
27573
- return handleArchive(projectRoot, itemId);
28226
+ return handleArchive(projectRoot, itemId, allowUnchecked);
27574
28227
  case "sync":
27575
28228
  return handleSync(projectRoot, itemId);
27576
28229
  case "verify":
@@ -27588,14 +28241,14 @@ async function openspecCommand(options) {
27588
28241
  };
27589
28242
  }
27590
28243
  }
27591
- function fail(command, errors3, extra = {}) {
28244
+ function fail2(command, errors3, extra = {}) {
27592
28245
  return {
27593
28246
  code: 1,
27594
28247
  data: { success: false, command, errors: errors3, ...extra }
27595
28248
  };
27596
28249
  }
27597
28250
  async function persistBacklog(projectRoot, content) {
27598
- await writeFileAtomic(resolve37(projectRoot, BACKLOG_FILENAME), content);
28251
+ await writeFileAtomic(resolve38(projectRoot, BACKLOG_FILENAME), content);
27599
28252
  }
27600
28253
  async function persistState(projectRoot, state) {
27601
28254
  const written = await writeOpenspecState(projectRoot, state);
@@ -27623,12 +28276,12 @@ function resolveActiveChange(state, command, itemId) {
27623
28276
  if (!targetId) {
27624
28277
  return {
27625
28278
  ok: false,
27626
- response: fail(command, ["No active change. Run openspec plan or pass an item id."])
28279
+ response: fail2(command, ["No active change. Run openspec plan or pass an item id."])
27627
28280
  };
27628
28281
  }
27629
28282
  const changePath = state.changePaths[targetId];
27630
28283
  if (!changePath || changePath.includes("/archive/")) {
27631
- return { ok: false, response: fail(command, [`No active change folder for ${targetId}`]) };
28284
+ return { ok: false, response: fail2(command, [`No active change folder for ${targetId}`]) };
27632
28285
  }
27633
28286
  return { ok: true, targetId, changePath };
27634
28287
  }
@@ -27636,7 +28289,7 @@ async function collectAnalyzeReport(projectRoot, session, targetId, changePath)
27636
28289
  const tddRequired = session.doc.global.tddRequired;
27637
28290
  const policyParts = [];
27638
28291
  try {
27639
- policyParts.push(await readFile40(resolve37(projectRoot, "AGENTS.md"), "utf-8"));
28292
+ policyParts.push(await readFile42(resolve38(projectRoot, "AGENTS.md"), "utf-8"));
27640
28293
  } catch {}
27641
28294
  policyParts.push(session.raw);
27642
28295
  const cards = itemCards(session.state, targetId);
@@ -27778,7 +28431,7 @@ async function handleScan(projectRoot) {
27778
28431
  };
27779
28432
  const written = await persistState(projectRoot, state);
27780
28433
  if (!written.ok) {
27781
- return fail("openspec scan", [written.error]);
28434
+ return fail2("openspec scan", [written.error]);
27782
28435
  }
27783
28436
  return {
27784
28437
  code: 0,
@@ -27813,7 +28466,7 @@ async function handlePlan(projectRoot, itemId) {
27813
28466
  }
27814
28467
  const existingState = session.state;
27815
28468
  if (item.status !== "PLANNED" && !canTransition(item.status, "PLANNED")) {
27816
- return fail("openspec plan", [
28469
+ return fail2("openspec plan", [
27817
28470
  `Illegal backlog transition for ${item.id}: ${item.status} → PLANNED.`
27818
28471
  ]);
27819
28472
  }
@@ -27840,11 +28493,11 @@ async function handlePlan(projectRoot, itemId) {
27840
28493
  };
27841
28494
  const written = await persistState(projectRoot, newState);
27842
28495
  if (!written.ok) {
27843
- return fail("openspec plan", [written.error]);
28496
+ return fail2("openspec plan", [written.error]);
27844
28497
  }
27845
28498
  const transition = applyBacklogTransition(session.raw, item.id, item.status, "PLANNED", item.progress);
27846
28499
  if (!transition.success) {
27847
- return fail("openspec plan", [transition.error.message]);
28500
+ return fail2("openspec plan", [transition.error.message]);
27848
28501
  }
27849
28502
  await persistBacklog(projectRoot, transition.data);
27850
28503
  return {
@@ -27865,7 +28518,7 @@ async function handleAnalyze(projectRoot, itemId) {
27865
28518
  const command = "openspec analyze";
27866
28519
  const sessionResult = await loadBacklogSession(projectRoot);
27867
28520
  if (!sessionResult.success)
27868
- return fail(command, [sessionResult.error.message]);
28521
+ return fail2(command, [sessionResult.error.message]);
27869
28522
  const session = sessionResult.data;
27870
28523
  const resolved = resolveActiveChange(session.state, command, itemId);
27871
28524
  if (!resolved.ok)
@@ -27904,7 +28557,7 @@ async function handleSync(projectRoot, itemId) {
27904
28557
  return resolved.response;
27905
28558
  const synced = await syncChangeSpecs(projectRoot, resolved.changePath);
27906
28559
  if (!synced.success) {
27907
- return fail(command, [
28560
+ return fail2(command, [
27908
28561
  `Spec sync failed for ${resolved.targetId}: ${synced.errors.join("; ")}`
27909
28562
  ]);
27910
28563
  }
@@ -27930,7 +28583,7 @@ async function handleVerify(projectRoot, itemId) {
27930
28583
  const command = "openspec verify";
27931
28584
  const sessionResult = await loadBacklogSession(projectRoot);
27932
28585
  if (!sessionResult.success)
27933
- return fail(command, [sessionResult.error.message]);
28586
+ return fail2(command, [sessionResult.error.message]);
27934
28587
  const session = sessionResult.data;
27935
28588
  const resolved = resolveActiveChange(session.state, command, itemId);
27936
28589
  if (!resolved.ok)
@@ -27994,7 +28647,7 @@ async function handleVerify(projectRoot, itemId) {
27994
28647
  dimension: "Coherence"
27995
28648
  });
27996
28649
  }
27997
- const archiveReady = !issues.some((i) => i.severity === "CRITICAL") && cards.length > 0 && doneCount === cards.length && missingArtifacts(progress.artifacts).length === 0 && scorecardOk;
28650
+ const archiveReady = !issues.some((i) => i.severity === "CRITICAL") && cards.length > 0 && doneCount === cards.length && missingArtifacts(progress.artifacts).length === 0 && progress.checkboxes.remaining === 0 && scorecardOk;
27998
28651
  return {
27999
28652
  code: 0,
28000
28653
  data: {
@@ -28065,44 +28718,38 @@ async function handleNext2(projectRoot) {
28065
28718
  }
28066
28719
  const next = getNextTaskCard(stateResult.data);
28067
28720
  if (!next) {
28721
+ const doing = stateResult.data.taskCards.find((c) => c.status === "doing");
28068
28722
  return {
28069
28723
  code: 0,
28070
28724
  data: {
28071
28725
  success: true,
28072
28726
  command: "openspec next",
28073
28727
  taskCard: null,
28074
- message: "No pending task cards. Run openspec plan first."
28728
+ ...doing ? { inProgressCardId: doing.id } : {},
28729
+ message: doing ? `${doing.id} is in progress. Finish it with: openspec done ${doing.id}` : "No pending task cards. Run openspec plan first."
28075
28730
  }
28076
28731
  };
28077
28732
  }
28078
- let loop = undefined;
28079
- if (shouldRunAgentLoop(undefined, next.agent, next.phase)) {
28080
- loop = await runLoopForProject(projectRoot, {
28081
- taskTitle: next.title,
28082
- originalTask: next.prompt
28083
- });
28084
- }
28085
28733
  return {
28086
- code: loop && !loop.success ? 1 : 0,
28734
+ code: 0,
28087
28735
  data: {
28088
- success: !(loop && !loop.success),
28736
+ success: true,
28089
28737
  command: "openspec next",
28090
- taskCard: next,
28091
- ...loop ? { loop } : {}
28738
+ taskCard: next
28092
28739
  }
28093
28740
  };
28094
28741
  }
28095
28742
  async function loadStateOrFail(projectRoot, command) {
28096
28743
  const stateResult = await loadOpenspecState(projectRoot);
28097
28744
  if (!stateResult.success) {
28098
- return { ok: false, response: fail(command, [stateResult.error.message]) };
28745
+ return { ok: false, response: fail2(command, [stateResult.error.message]) };
28099
28746
  }
28100
28747
  return { ok: true, state: stateResult.data };
28101
28748
  }
28102
28749
  function findItemOrFail(session, itemId, command) {
28103
28750
  const item = session.doc.items.find((i) => i.id === itemId) ?? session.doc.archive.find((i) => i.id === itemId);
28104
28751
  if (!item) {
28105
- return { ok: false, response: fail(command, [`Backlog item ${itemId} not found`]) };
28752
+ return { ok: false, response: fail2(command, [`Backlog item ${itemId} not found`]) };
28106
28753
  }
28107
28754
  return {
28108
28755
  ok: true,
@@ -28113,32 +28760,45 @@ function findItemOrFail(session, itemId, command) {
28113
28760
  async function handleStart(projectRoot, cardId) {
28114
28761
  const command = "openspec start";
28115
28762
  if (!cardId) {
28116
- return fail(command, ["Missing card id. Usage: openspec start <cardId>"]);
28763
+ return fail2(command, ["Missing card id. Usage: openspec start <cardId>"]);
28117
28764
  }
28118
28765
  const sessionResult = await loadBacklogSession(projectRoot);
28119
28766
  if (!sessionResult.success)
28120
- return fail(command, [sessionResult.error.message]);
28767
+ return fail2(command, [sessionResult.error.message]);
28121
28768
  const session = sessionResult.data;
28122
28769
  const card = findCard(session.state, cardId);
28123
28770
  if (!card) {
28124
- return fail(command, [`Task card ${cardId} not found`]);
28771
+ return fail2(command, [`Task card ${cardId} not found`]);
28125
28772
  }
28126
28773
  if (card.status !== "pending" && card.status !== "doing") {
28127
- return fail(command, [`Card ${cardId} cannot start from status ${card.status}`]);
28774
+ return fail2(command, [`Card ${cardId} cannot start from status ${card.status}`]);
28128
28775
  }
28129
28776
  const itemLoaded = findItemOrFail(session, card.backlogId, command);
28130
28777
  if (!itemLoaded.ok)
28131
28778
  return itemLoaded.response;
28132
28779
  let state = session.state;
28133
- if (card.status === "pending") {
28780
+ let baseWarning;
28781
+ if (!state.itemBaseCommits?.[card.backlogId]) {
28782
+ try {
28783
+ const base = execFileSync2("git", ["rev-parse", "--verify", "HEAD"], {
28784
+ cwd: projectRoot,
28785
+ encoding: "utf8",
28786
+ stdio: ["ignore", "pipe", "ignore"]
28787
+ }).trim();
28788
+ state = { ...state, itemBaseCommits: { ...state.itemBaseCommits, [card.backlogId]: base } };
28789
+ } catch {
28790
+ baseWarning = "Item base unavailable: could not resolve git HEAD.";
28791
+ }
28792
+ }
28793
+ if (card.status === "pending" || state !== session.state) {
28134
28794
  state = setTaskCardStatus(state, cardId, "doing");
28135
28795
  const written = await persistState(projectRoot, state);
28136
28796
  if (!written.ok)
28137
- return fail(command, [written.error]);
28797
+ return fail2(command, [written.error]);
28138
28798
  }
28139
28799
  const transition = await transitionItem(projectRoot, itemLoaded.item, "IN_PROGRESS", itemLoaded.item.progress, session.raw);
28140
28800
  if (!transition.ok)
28141
- return fail(command, [transition.error]);
28801
+ return fail2(command, [transition.error]);
28142
28802
  return {
28143
28803
  code: 0,
28144
28804
  data: {
@@ -28147,22 +28807,23 @@ async function handleStart(projectRoot, cardId) {
28147
28807
  cardId,
28148
28808
  cardStatus: "doing",
28149
28809
  itemId: itemLoaded.item.id,
28150
- itemStatus: "IN_PROGRESS"
28810
+ itemStatus: "IN_PROGRESS",
28811
+ ...baseWarning ? { warnings: [baseWarning] } : {}
28151
28812
  }
28152
28813
  };
28153
28814
  }
28154
28815
  async function handleDone(projectRoot, cardId) {
28155
28816
  const command = "openspec done";
28156
28817
  if (!cardId) {
28157
- return fail(command, ["Missing card id. Usage: openspec done <cardId>"]);
28818
+ return fail2(command, ["Missing card id. Usage: openspec done <cardId>"]);
28158
28819
  }
28159
28820
  const sessionResult = await loadBacklogSession(projectRoot);
28160
28821
  if (!sessionResult.success)
28161
- return fail(command, [sessionResult.error.message]);
28822
+ return fail2(command, [sessionResult.error.message]);
28162
28823
  const session = sessionResult.data;
28163
28824
  const card = findCard(session.state, cardId);
28164
28825
  if (!card) {
28165
- return fail(command, [`Task card ${cardId} not found`]);
28826
+ return fail2(command, [`Task card ${cardId} not found`]);
28166
28827
  }
28167
28828
  if (card.status === "done") {
28168
28829
  return {
@@ -28171,7 +28832,7 @@ async function handleDone(projectRoot, cardId) {
28171
28832
  };
28172
28833
  }
28173
28834
  if (card.status !== "doing") {
28174
- return fail(command, [`Card ${cardId} must be doing before done (got ${card.status})`]);
28835
+ return fail2(command, [`Card ${cardId} must be doing before done (got ${card.status})`]);
28175
28836
  }
28176
28837
  const itemLoaded = findItemOrFail(session, card.backlogId, command);
28177
28838
  if (!itemLoaded.ok)
@@ -28179,11 +28840,13 @@ async function handleDone(projectRoot, cardId) {
28179
28840
  const tddRequired = session.doc.global.tddRequired;
28180
28841
  if (tddRequired && (card.phase === "test" || card.phase === "implement")) {
28181
28842
  const expectedPhase = card.phase === "test" ? "red" : "green";
28182
- const evidenced = await hasTddRunnerEvidence(projectRoot, cardId, expectedPhase);
28183
- if (!evidenced) {
28184
- return fail(command, [
28185
- `Card ${cardId} (${card.phase}) requires current ${expectedPhase.toUpperCase()} verification-runner TDD evidence. Run captureTddSuiteEvidence before openspec done.`
28186
- ]);
28843
+ const message = `Card ${cardId} (${card.phase}) requires current ${expectedPhase.toUpperCase()} verification-runner TDD evidence. Run: tdd capture --task ${cardId} --phase ${expectedPhase} --command "<test command>", then openspec done.`;
28844
+ if (card.phase === "test") {
28845
+ const recorded = await recordRedValidation(projectRoot, cardId);
28846
+ if (!recorded.success)
28847
+ return fail2(command, [`${message} ${recorded.error.message}`]);
28848
+ } else if (!await hasTddRunnerEvidence(projectRoot, cardId, expectedPhase)) {
28849
+ return fail2(command, [message]);
28187
28850
  }
28188
28851
  }
28189
28852
  const state = setTaskCardStatus(session.state, cardId, "done");
@@ -28193,18 +28856,14 @@ async function handleDone(projectRoot, cardId) {
28193
28856
  const allDone = cards.length > 0 && doneCount === cards.length;
28194
28857
  const written = await persistState(projectRoot, state);
28195
28858
  if (!written.ok)
28196
- return fail(command, [written.error]);
28859
+ return fail2(command, [written.error]);
28197
28860
  const changePath = state.changePaths[card.backlogId];
28198
- if (changePath) {
28199
- await writeTasksMarkdown(projectRoot, changePath, cards, {
28200
- tddRequired,
28201
- acceptanceCriteria: itemLoaded.item.acceptanceCriteria
28202
- });
28203
- }
28861
+ if (changePath)
28862
+ await syncTaskCardCheckbox(projectRoot, changePath, cardId, true);
28204
28863
  const nextStatus = allDone ? "REVIEW" : "IN_PROGRESS";
28205
28864
  const transition = await transitionItem(projectRoot, itemLoaded.item, nextStatus, progress, session.raw);
28206
28865
  if (!transition.ok)
28207
- return fail(command, [transition.error]);
28866
+ return fail2(command, [transition.error]);
28208
28867
  return {
28209
28868
  code: 0,
28210
28869
  data: {
@@ -28222,18 +28881,18 @@ async function handleDone(projectRoot, cardId) {
28222
28881
  async function handleBlock(projectRoot, cardId, reason) {
28223
28882
  const command = "openspec block";
28224
28883
  if (!cardId) {
28225
- return fail(command, ["Missing card id. Usage: openspec block <cardId> --reason <text>"]);
28884
+ return fail2(command, ["Missing card id. Usage: openspec block <cardId> --reason <text>"]);
28226
28885
  }
28227
28886
  if (!reason || !reason.trim()) {
28228
- return fail(command, ["--reason is required"]);
28887
+ return fail2(command, ["--reason is required"]);
28229
28888
  }
28230
28889
  const sessionResult = await loadBacklogSession(projectRoot);
28231
28890
  if (!sessionResult.success)
28232
- return fail(command, [sessionResult.error.message]);
28891
+ return fail2(command, [sessionResult.error.message]);
28233
28892
  const session = sessionResult.data;
28234
28893
  const card = findCard(session.state, cardId);
28235
28894
  if (!card) {
28236
- return fail(command, [`Task card ${cardId} not found`]);
28895
+ return fail2(command, [`Task card ${cardId} not found`]);
28237
28896
  }
28238
28897
  const itemLoaded = findItemOrFail(session, card.backlogId, command);
28239
28898
  if (!itemLoaded.ok)
@@ -28241,10 +28900,10 @@ async function handleBlock(projectRoot, cardId, reason) {
28241
28900
  const state = setTaskCardStatus(session.state, cardId, "blocked");
28242
28901
  const written = await persistState(projectRoot, state);
28243
28902
  if (!written.ok)
28244
- return fail(command, [written.error]);
28903
+ return fail2(command, [written.error]);
28245
28904
  const transition = await transitionItem(projectRoot, itemLoaded.item, "BLOCKED", undefined, session.raw);
28246
28905
  if (!transition.ok)
28247
- return fail(command, [transition.error]);
28906
+ return fail2(command, [transition.error]);
28248
28907
  return {
28249
28908
  code: 0,
28250
28909
  data: {
@@ -28261,41 +28920,37 @@ async function handleBlock(projectRoot, cardId, reason) {
28261
28920
  async function handleUnblock(projectRoot, cardId) {
28262
28921
  const command = "openspec unblock";
28263
28922
  if (!cardId) {
28264
- return fail(command, ["Missing card id. Usage: openspec unblock <cardId>"]);
28923
+ return fail2(command, ["Missing card id. Usage: openspec unblock <cardId>"]);
28265
28924
  }
28266
28925
  const sessionResult = await loadBacklogSession(projectRoot);
28267
28926
  if (!sessionResult.success)
28268
- return fail(command, [sessionResult.error.message]);
28927
+ return fail2(command, [sessionResult.error.message]);
28269
28928
  const session = sessionResult.data;
28270
28929
  const card = findCard(session.state, cardId);
28271
28930
  if (!card) {
28272
- return fail(command, [`Task card ${cardId} not found`]);
28931
+ return fail2(command, [`Task card ${cardId} not found`]);
28273
28932
  }
28274
28933
  if (card.status !== "blocked") {
28275
- return fail(command, [`Card ${cardId} must be blocked before unblock (got ${card.status})`]);
28934
+ return fail2(command, [`Card ${cardId} must be blocked before unblock (got ${card.status})`]);
28276
28935
  }
28277
28936
  const itemLoaded = findItemOrFail(session, card.backlogId, command);
28278
28937
  if (!itemLoaded.ok)
28279
28938
  return itemLoaded.response;
28280
28939
  if (itemLoaded.item.status !== "BLOCKED") {
28281
- return fail(command, [
28940
+ return fail2(command, [
28282
28941
  `Backlog item ${itemLoaded.item.id} must be BLOCKED before unblock (got ${itemLoaded.item.status})`
28283
28942
  ]);
28284
28943
  }
28285
28944
  const state = setTaskCardStatus(session.state, cardId, "pending");
28286
28945
  const written = await persistState(projectRoot, state);
28287
28946
  if (!written.ok)
28288
- return fail(command, [written.error]);
28947
+ return fail2(command, [written.error]);
28289
28948
  const changePath = state.changePaths[card.backlogId];
28290
- if (changePath) {
28291
- await writeTasksMarkdown(projectRoot, changePath, itemCards(state, card.backlogId), {
28292
- tddRequired: session.doc.global.tddRequired,
28293
- acceptanceCriteria: itemLoaded.item.acceptanceCriteria
28294
- });
28295
- }
28949
+ if (changePath)
28950
+ await syncTaskCardCheckbox(projectRoot, changePath, cardId, false);
28296
28951
  const transition = await transitionItem(projectRoot, itemLoaded.item, "READY", undefined, session.raw);
28297
28952
  if (!transition.ok)
28298
- return fail(command, [transition.error]);
28953
+ return fail2(command, [transition.error]);
28299
28954
  return {
28300
28955
  code: 0,
28301
28956
  data: {
@@ -28309,38 +28964,38 @@ async function handleUnblock(projectRoot, cardId) {
28309
28964
  }
28310
28965
  };
28311
28966
  }
28312
- async function handleArchive(projectRoot, itemId) {
28967
+ async function handleArchive(projectRoot, itemId, allowUnchecked = false) {
28313
28968
  const command = "openspec archive";
28314
28969
  if (!itemId) {
28315
- return fail(command, ["Missing item id. Usage: openspec archive <itemId>"]);
28970
+ return fail2(command, ["Missing item id. Usage: openspec archive <itemId>"]);
28316
28971
  }
28317
28972
  const sessionResult = await loadBacklogSession(projectRoot);
28318
28973
  if (!sessionResult.success)
28319
- return fail(command, [sessionResult.error.message]);
28974
+ return fail2(command, [sessionResult.error.message]);
28320
28975
  const session = sessionResult.data;
28321
28976
  const itemLoaded = findItemOrFail(session, itemId, command);
28322
28977
  if (!itemLoaded.ok)
28323
28978
  return itemLoaded.response;
28324
28979
  const cards = itemCards(session.state, itemId);
28325
28980
  if (cards.length === 0) {
28326
- return fail(command, [`No task cards found for ${itemId}. Run openspec plan first.`]);
28981
+ return fail2(command, [`No task cards found for ${itemId}. Run openspec plan first.`]);
28327
28982
  }
28328
28983
  const unfinished = cards.filter((c) => c.status !== "done");
28329
28984
  if (unfinished.length > 0) {
28330
- return fail(command, [
28985
+ return fail2(command, [
28331
28986
  `Cannot archive ${itemId}: ${unfinished.length} card(s) are not done (${unfinished.map((c) => c.id).join(", ")})`
28332
28987
  ]);
28333
28988
  }
28334
28989
  if (itemLoaded.reviewRequired) {
28335
28990
  const reviewCard = cards.find((c) => c.phase === "review");
28336
28991
  if (!reviewCard || reviewCard.status !== "done") {
28337
- return fail(command, [
28992
+ return fail2(command, [
28338
28993
  `Cannot archive ${itemId}: global.reviewRequired needs the review phase card done`
28339
28994
  ]);
28340
28995
  }
28341
28996
  const passed = await hasPassingScorecard(projectRoot, itemId);
28342
28997
  if (!passed) {
28343
- return fail(command, [
28998
+ return fail2(command, [
28344
28999
  `Cannot archive ${itemId}: global.reviewRequired needs a PASS scorecard for this backlog id`
28345
29000
  ]);
28346
29001
  }
@@ -28352,28 +29007,34 @@ async function handleArchive(projectRoot, itemId) {
28352
29007
  const progress = await readArtifactProgress(projectRoot, changePath);
28353
29008
  const missing = missingArtifacts(progress.artifacts);
28354
29009
  if (missing.length > 0) {
28355
- return fail(command, [
29010
+ return fail2(command, [
28356
29011
  `Cannot archive ${itemId}: change folder is missing ${missing.join(", ")}. Re-run openspec plan ${itemId} or restore them.`
28357
29012
  ]);
28358
29013
  }
28359
29014
  const { report } = await collectAnalyzeReport(projectRoot, session, itemId, changePath);
28360
29015
  const critical = report.findings.filter((f) => f.severity === "CRITICAL");
28361
29016
  if (critical.length > 0) {
28362
- return fail(command, [
29017
+ return fail2(command, [
28363
29018
  `Cannot archive ${itemId}: analyze reports ${critical.length} CRITICAL finding(s): ${critical.map((f) => f.code).join(", ")}. Resolve them first.`
28364
29019
  ]);
28365
29020
  }
28366
29021
  if (progress.checkboxes.remaining > 0) {
28367
- warnings.push(`${progress.checkboxes.remaining} of ${progress.checkboxes.total} tasks.md checkboxes are unchecked; tick them as FRs complete (only [x]/[X] counts as done).`);
29022
+ const unchecked = `${progress.checkboxes.remaining} of ${progress.checkboxes.total} tasks.md checkboxes are unchecked (only [x]/[X] counts as done)`;
29023
+ if (!allowUnchecked) {
29024
+ return fail2(command, [
29025
+ `Cannot archive ${itemId}: ${unchecked}. Tick them as the work completes, or pass --allow-unchecked to archive anyway.`
29026
+ ]);
29027
+ }
29028
+ warnings.push(`${unchecked}; archived with --allow-unchecked.`);
28368
29029
  }
28369
29030
  const synced = await syncChangeSpecs(projectRoot, changePath);
28370
29031
  if (!synced.success) {
28371
- return fail(command, [`Cannot archive ${itemId}: spec sync failed: ${synced.errors.join("; ")}`]);
29032
+ return fail2(command, [`Cannot archive ${itemId}: spec sync failed: ${synced.errors.join("; ")}`]);
28372
29033
  }
28373
29034
  try {
28374
29035
  archivedPath = await archiveChangeFolder(projectRoot, changePath);
28375
29036
  } catch (e) {
28376
- return fail(command, [
29037
+ return fail2(command, [
28377
29038
  `Backlog archived but change folder move failed: ${e instanceof Error ? e.message : String(e)}`
28378
29039
  ]);
28379
29040
  }
@@ -28382,7 +29043,7 @@ async function handleArchive(projectRoot, itemId) {
28382
29043
  if (itemLoaded.item.status !== "DONE") {
28383
29044
  const toDone = await transitionItem(projectRoot, itemLoaded.item, "DONE", 100, content);
28384
29045
  if (!toDone.ok)
28385
- return fail(command, [toDone.error]);
29046
+ return fail2(command, [toDone.error]);
28386
29047
  content = toDone.content;
28387
29048
  }
28388
29049
  const archived = archiveItemInMarkdown(content, itemId);
@@ -28394,7 +29055,7 @@ async function handleArchive(projectRoot, itemId) {
28394
29055
  };
28395
29056
  const written = await persistState(projectRoot, nextState);
28396
29057
  if (!written.ok)
28397
- return fail(command, [written.error]);
29058
+ return fail2(command, [written.error]);
28398
29059
  return {
28399
29060
  code: 0,
28400
29061
  data: {
@@ -28421,7 +29082,6 @@ var init_openspec_command = __esm(() => {
28421
29082
  init_outcome_store();
28422
29083
  init_openspec_state();
28423
29084
  init_backlog_parser();
28424
- init_loop_engine();
28425
29085
  });
28426
29086
 
28427
29087
  // src/core/ccep/context-assembly.ts
@@ -28472,25 +29132,25 @@ var init_handoff_envelope = __esm(() => {
28472
29132
  });
28473
29133
 
28474
29134
  // src/core/delivery/delivery-ledger.ts
28475
- import { createHash as createHash7 } from "node:crypto";
28476
- import { mkdir as mkdir23, readFile as readFile41, writeFile as writeFile22 } from "node:fs/promises";
28477
- import { resolve as resolve38, sep as sep9 } from "node:path";
29135
+ import { createHash as createHash8 } from "node:crypto";
29136
+ import { mkdir as mkdir25, readFile as readFile43, writeFile as writeFile23 } from "node:fs/promises";
29137
+ import { resolve as resolve39, sep as sep9 } from "node:path";
28478
29138
  function ledgerPath(projectRoot, id) {
28479
29139
  if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(id))
28480
29140
  throw new Error("Invalid delivery ledger id");
28481
- return resolve38(projectRoot, DELIVERY_DIR, `${id}.md`);
29141
+ return resolve39(projectRoot, DELIVERY_DIR, `${id}.md`);
28482
29142
  }
28483
29143
  async function fingerprintWorkspace(projectRoot, paths) {
28484
- const root = resolve38(projectRoot);
29144
+ const root = resolve39(projectRoot);
28485
29145
  const fingerprints = {};
28486
29146
  for (const path of paths) {
28487
- const candidate = resolve38(root, path);
29147
+ const candidate = resolve39(root, path);
28488
29148
  if (candidate !== root && !candidate.startsWith(`${root}${sep9}`)) {
28489
29149
  fingerprints[path] = "outside-root";
28490
29150
  continue;
28491
29151
  }
28492
29152
  try {
28493
- fingerprints[path] = createHash7("sha256").update(await readFile41(candidate)).digest("hex");
29153
+ fingerprints[path] = createHash8("sha256").update(await readFile43(candidate)).digest("hex");
28494
29154
  } catch {
28495
29155
  fingerprints[path] = "missing";
28496
29156
  }
@@ -28513,7 +29173,7 @@ function parseLedger(content) {
28513
29173
  return DeliveryLedgerSchema.parse($parse(match[1]));
28514
29174
  }
28515
29175
  async function loadDeliveryLedger(projectRoot, id) {
28516
- return parseLedger(await readFile41(ledgerPath(projectRoot, id), "utf-8"));
29176
+ return parseLedger(await readFile43(ledgerPath(projectRoot, id), "utf-8"));
28517
29177
  }
28518
29178
  async function createDeliveryLedger(projectRoot, input) {
28519
29179
  const request = DeliveryLedgerRequestSchema.parse(input);
@@ -28538,9 +29198,9 @@ async function createDeliveryLedger(projectRoot, input) {
28538
29198
  createdAt: now,
28539
29199
  updatedAt: now
28540
29200
  });
28541
- await mkdir23(resolve38(projectRoot, DELIVERY_DIR), { recursive: true });
29201
+ await mkdir25(resolve39(projectRoot, DELIVERY_DIR), { recursive: true });
28542
29202
  try {
28543
- await writeFile22(path, render(ledger), { encoding: "utf-8", flag: "wx" });
29203
+ await writeFile23(path, render(ledger), { encoding: "utf-8", flag: "wx" });
28544
29204
  return { created: true, ledger };
28545
29205
  } catch (error) {
28546
29206
  if (error instanceof Error && error.message.includes("EEXIST")) {
@@ -28870,10 +29530,10 @@ __export(exports_hook_command, {
28870
29530
  parseHookFormat: () => parseHookFormat,
28871
29531
  readStdinText: () => readStdinText
28872
29532
  });
28873
- import { spawnSync } from "node:child_process";
28874
- import { existsSync as existsSync8, readFileSync as readFileSync5 } from "node:fs";
29533
+ import { spawnSync as spawnSync2 } from "node:child_process";
29534
+ import { existsSync as existsSync8, readFileSync as readFileSync6 } from "node:fs";
28875
29535
  import { createRequire as createRequire2 } from "node:module";
28876
- import { dirname as dirname12, resolve as resolve39 } from "node:path";
29536
+ import { dirname as dirname14, resolve as resolve40 } from "node:path";
28877
29537
  function parseHookFormat(raw) {
28878
29538
  return raw === "agy" || raw === "claude" || raw === "muse" ? raw : undefined;
28879
29539
  }
@@ -28905,15 +29565,15 @@ function resolvePreToolInput(options, stdinText, format) {
28905
29565
  };
28906
29566
  }
28907
29567
  async function sessionLines(projectRoot) {
28908
- const backlogPath = resolve39(projectRoot, "BACKLOG.md");
28909
- const profilePath = resolve39(projectRoot, ".codeconductor", "evaluation", "execution-profile.yml");
29568
+ const backlogPath = resolve40(projectRoot, "BACKLOG.md");
29569
+ const profilePath = resolve40(projectRoot, ".codeconductor", "evaluation", "execution-profile.yml");
28910
29570
  return [
28911
29571
  "[CodeConductor] Session start",
28912
29572
  "Skills: openspec, backlog, evaluation, testing-tdd — invoke via /cc-* then CLI.",
28913
- existsSync8(backlogPath) ? "BACKLOG.md present — run: bun run dev openspec status" : "No BACKLOG.md — author with /cc-backlog if you need an item queue.",
28914
- existsSync8(profilePath) ? "Scorecard profile on disk — run: bun run dev scorecard models" : "Scorecard: bun run dev scorecard create --task <id> --from-diff",
28915
- "Hooks: bun run dev hook pre-tool | post-tool | session-start",
28916
- "Eval suites: bun run dev scorecard suite-run --suite workflow-gates"
29573
+ existsSync8(backlogPath) ? "BACKLOG.md present — run: npx cc-codeconductor openspec status" : "No BACKLOG.md — author with /cc-backlog if you need an item queue.",
29574
+ existsSync8(profilePath) ? "Scorecard profile on disk — run: npx cc-codeconductor scorecard models" : "Scorecard: npx cc-codeconductor scorecard create --task <id> --from-diff",
29575
+ "Hooks: npx cc-codeconductor hook pre-tool | post-tool | session-start",
29576
+ "Eval suites: npx cc-codeconductor scorecard suite-run --suite workflow-gates"
28917
29577
  ];
28918
29578
  }
28919
29579
  async function hookCommand(options) {
@@ -28961,21 +29621,21 @@ async function hookCommand(options) {
28961
29621
  function formatWrittenFile(filePath, projectRoot) {
28962
29622
  if (!filePath)
28963
29623
  return;
28964
- filePath = resolve39(projectRoot, filePath);
29624
+ filePath = resolve40(projectRoot, filePath);
28965
29625
  if (!existsSync8(filePath))
28966
29626
  return;
28967
29627
  const prettier = /\.(ts|tsx|js|jsx|mjs|cjs|json|jsonc|md|mdx|css|scss|html|astro|ya?ml)$/i;
28968
29628
  const eslint = /\.(ts|tsx|js|jsx|mjs|cjs)$/i;
28969
29629
  const python = /\.py$/i;
28970
29630
  const opts = { cwd: projectRoot, stdio: "ignore", windowsHide: true, timeout: 5000 };
28971
- const require2 = createRequire2(resolve39(projectRoot, "package.json"));
29631
+ const require2 = createRequire2(resolve40(projectRoot, "package.json"));
28972
29632
  function runNodeTool(name, args) {
28973
29633
  try {
28974
29634
  const manifestPath = require2.resolve(`${name}/package.json`);
28975
- const manifest = JSON.parse(readFileSync5(manifestPath, "utf8"));
29635
+ const manifest = JSON.parse(readFileSync6(manifestPath, "utf8"));
28976
29636
  const bin = typeof manifest.bin === "string" ? manifest.bin : manifest.bin?.[name];
28977
29637
  if (typeof bin === "string")
28978
- spawnSync(process.execPath, [resolve39(dirname12(manifestPath), bin), ...args], opts);
29638
+ spawnSync2(process.execPath, [resolve40(dirname14(manifestPath), bin), ...args], opts);
28979
29639
  } catch {}
28980
29640
  }
28981
29641
  if (prettier.test(filePath)) {
@@ -28985,8 +29645,8 @@ function formatWrittenFile(filePath, projectRoot) {
28985
29645
  runNodeTool("eslint", ["--fix", filePath]);
28986
29646
  }
28987
29647
  if (python.test(filePath)) {
28988
- spawnSync("ruff", ["format", filePath], opts);
28989
- spawnSync("ruff", ["check", "--fix", filePath], opts);
29648
+ spawnSync2("ruff", ["format", filePath], opts);
29649
+ spawnSync2("ruff", ["check", "--fix", filePath], opts);
28990
29650
  }
28991
29651
  }
28992
29652
  var init_hook_command = __esm(() => {
@@ -29016,35 +29676,41 @@ function createDefaultCriteria(overrides = {}) {
29016
29676
  id: def.id,
29017
29677
  label: def.label,
29018
29678
  weight: def.weight,
29019
- score: o?.score ?? 2,
29679
+ score: o ? o.score : 2,
29020
29680
  notes: o?.notes,
29021
- autoSuggested: o?.autoSuggested
29681
+ autoSuggested: o?.autoSuggested,
29682
+ unmeasured: o?.unmeasured
29022
29683
  };
29023
29684
  });
29024
29685
  }
29025
29686
  function computeWeightedScore(criteria) {
29026
29687
  let total = 0;
29027
29688
  for (const c of criteria) {
29028
- total += c.score * c.weight;
29689
+ total += (c.score ?? 0) * c.weight;
29029
29690
  }
29030
29691
  return Math.round(total * 1000) / 1000;
29031
29692
  }
29032
29693
  function computeVerdict(criteria, weightedScore) {
29033
29694
  const byId = new Map(criteria.map((c) => [c.id, c.score]));
29034
- const acceptance = byId.get("acceptance") ?? 0;
29035
- const minimalDiff = byId.get("minimal_diff") ?? 0;
29036
- const regressions = byId.get("regressions") ?? 0;
29695
+ const acceptance = byId.has("acceptance") ? byId.get("acceptance") : 0;
29696
+ const minimalDiff = byId.has("minimal_diff") ? byId.get("minimal_diff") : 0;
29697
+ const regressions = byId.has("regressions") ? byId.get("regressions") : 0;
29037
29698
  if (acceptance === 0 || minimalDiff === 0 || regressions === 0) {
29038
29699
  return "REJECT";
29039
29700
  }
29040
29701
  if (weightedScore < 1.5) {
29041
29702
  return "REJECT";
29042
29703
  }
29704
+ if (pendingCriteria(criteria).length > 0)
29705
+ return "REVISE";
29043
29706
  if (weightedScore >= PASS_THRESHOLD && !criteria.some((c) => c.score === 0)) {
29044
29707
  return "PASS";
29045
29708
  }
29046
29709
  return "REVISE";
29047
29710
  }
29711
+ function pendingCriteria(criteria) {
29712
+ return criteria.filter((c) => c.score === null || c.unmeasured && (c.autoSuggested !== false || !c.notes?.trim())).map((c) => c.id);
29713
+ }
29048
29714
  function buildScorecardRecord(params) {
29049
29715
  const weightedScore = computeWeightedScore(params.criteria);
29050
29716
  const verdict = computeVerdict(params.criteria, weightedScore);
@@ -29389,7 +30055,7 @@ function ccGainToScorecardImpact(result) {
29389
30055
  }
29390
30056
 
29391
30057
  // src/core/evaluation/scorecard-signals.ts
29392
- import { execFileSync as execFileSync2 } from "node:child_process";
30058
+ import { execFileSync as execFileSync3 } from "node:child_process";
29393
30059
  function parseScopeFiles(scope) {
29394
30060
  return scope.split(/[,;]/).map((entry) => entry.trim().replace(/[.;:]$/, "").replace(/^`|`$/g, "")).filter(Boolean);
29395
30061
  }
@@ -29399,6 +30065,18 @@ function isGeneratedBuildCache(path) {
29399
30065
  function collectScorecardSignals(projectRoot, scopeFiles, extra) {
29400
30066
  const findings = [];
29401
30067
  const overrides = {};
30068
+ overrides.tests = {
30069
+ score: null,
30070
+ unmeasured: true,
30071
+ autoSuggested: true,
30072
+ notes: "Unmeasured: no verification-runner evidence supplied"
30073
+ };
30074
+ overrides.cc_gain = {
30075
+ score: null,
30076
+ unmeasured: true,
30077
+ autoSuggested: true,
30078
+ notes: "Unmeasured: no diff available for complexity audit"
30079
+ };
29402
30080
  const scopeViolationCount = extra?.scopeViolationCount;
29403
30081
  if (scopeViolationCount && scopeViolationCount > 0) {
29404
30082
  overrides.minimal_diff = {
@@ -29419,13 +30097,21 @@ function collectScorecardSignals(projectRoot, scopeFiles, extra) {
29419
30097
  }
29420
30098
  let diff = "";
29421
30099
  try {
29422
- diff = execFileSync2("git", ["diff", "HEAD"], {
30100
+ diff = execFileSync3("git", ["diff", extra?.baseCommit ?? "HEAD", "--"], {
29423
30101
  cwd: projectRoot,
29424
30102
  encoding: "utf-8",
29425
30103
  stdio: ["ignore", "pipe", "ignore"]
29426
30104
  });
29427
30105
  } catch {
29428
30106
  findings.push("Could not read git diff; scope audit skipped.");
30107
+ if (!overrides.minimal_diff) {
30108
+ overrides.minimal_diff = {
30109
+ score: null,
30110
+ unmeasured: true,
30111
+ autoSuggested: true,
30112
+ notes: "Unmeasured: git diff unavailable"
30113
+ };
30114
+ }
29429
30115
  return { criteriaOverrides: overrides, findings, scopeViolationCount, hashMismatch };
29430
30116
  }
29431
30117
  if (!diff.trim()) {
@@ -29501,8 +30187,14 @@ function applyAnalyzeSignals(hints, analyze) {
29501
30187
  autoSuggested: true
29502
30188
  };
29503
30189
  findings.push("Tests auto-suggested 0: missing verification-runner evidence.");
30190
+ } else if (analyze.hasTddEvidence === true && !hints.hashMismatch) {
30191
+ criteriaOverrides.tests = {
30192
+ score: 2,
30193
+ notes: "Verification-runner RED/GREEN evidence verified",
30194
+ autoSuggested: true
30195
+ };
29504
30196
  }
29505
- return { criteriaOverrides, findings };
30197
+ return { ...hints, criteriaOverrides, findings };
29506
30198
  }
29507
30199
  function criteriaFromSignals(hints) {
29508
30200
  return createDefaultCriteria(hints.criteriaOverrides);
@@ -29514,24 +30206,24 @@ var init_scorecard_signals = __esm(() => {
29514
30206
 
29515
30207
  // src/core/evaluation/harness-experiment.ts
29516
30208
  import { existsSync as existsSync9 } from "node:fs";
29517
- import { cp, mkdir as mkdir24, readFile as readFile42, readdir as readdir13, writeFile as writeFile23 } from "node:fs/promises";
29518
- import { dirname as dirname13, join as join29, resolve as resolve40 } from "node:path";
30209
+ import { cp, mkdir as mkdir26, readFile as readFile44, readdir as readdir13, writeFile as writeFile24 } from "node:fs/promises";
30210
+ import { dirname as dirname15, join as join30, resolve as resolve41 } from "node:path";
29519
30211
  function experimentDir(projectRoot, experimentId) {
29520
- return resolve40(projectRoot, EVAL_DIR2, EXPERIMENTS_DIR, experimentId);
30212
+ return resolve41(projectRoot, EVAL_DIR2, EXPERIMENTS_DIR, experimentId);
29521
30213
  }
29522
30214
  function experimentYamlPath(projectRoot, experimentId) {
29523
- return join29(experimentDir(projectRoot, experimentId), "experiment.yml");
30215
+ return join30(experimentDir(projectRoot, experimentId), "experiment.yml");
29524
30216
  }
29525
30217
  async function loadHarnessSuite(projectRoot, suiteId, suitePath) {
29526
30218
  const candidates = suitePath ? [suitePath] : [
29527
- resolve40(projectRoot, "eval", "suites", suiteId, "suite.yml"),
29528
- resolve40(projectRoot, EVAL_DIR2, "suites", suiteId, "suite.yml")
30219
+ resolve41(projectRoot, "eval", "suites", suiteId, "suite.yml"),
30220
+ resolve41(projectRoot, EVAL_DIR2, "suites", suiteId, "suite.yml")
29529
30221
  ];
29530
30222
  for (const path of candidates) {
29531
30223
  if (!existsSync9(path))
29532
30224
  continue;
29533
30225
  try {
29534
- const suite = HarnessSuiteSchema.parse($parse(await readFile42(path, "utf-8")));
30226
+ const suite = HarnessSuiteSchema.parse($parse(await readFile44(path, "utf-8")));
29535
30227
  return ok({ ...suite, path });
29536
30228
  } catch (e) {
29537
30229
  return err(e instanceof Error ? e : new Error(String(e)));
@@ -29541,7 +30233,7 @@ async function loadHarnessSuite(projectRoot, suiteId, suitePath) {
29541
30233
  }
29542
30234
  async function loadExperiment(projectRoot, experimentId) {
29543
30235
  try {
29544
- const raw = await readFile42(experimentYamlPath(projectRoot, experimentId), "utf-8");
30236
+ const raw = await readFile44(experimentYamlPath(projectRoot, experimentId), "utf-8");
29545
30237
  return ok(HarnessExperimentSchema.parse($parse(raw)));
29546
30238
  } catch (e) {
29547
30239
  if (e.code === "ENOENT") {
@@ -29551,7 +30243,7 @@ async function loadExperiment(projectRoot, experimentId) {
29551
30243
  }
29552
30244
  }
29553
30245
  async function listExperiments(projectRoot) {
29554
- const root = resolve40(projectRoot, EVAL_DIR2, EXPERIMENTS_DIR);
30246
+ const root = resolve41(projectRoot, EVAL_DIR2, EXPERIMENTS_DIR);
29555
30247
  if (!existsSync9(root))
29556
30248
  return [];
29557
30249
  const ids = await readdir13(root);
@@ -29593,8 +30285,8 @@ function formatTaskCard(task, experimentId, variantId) {
29593
30285
  "When done:",
29594
30286
  "",
29595
30287
  "```",
29596
- `bun run dev scorecard create --task ${task.id} --from-diff`,
29597
- `bun run dev scorecard record --task ${task.id} --verdict PASS|REVISE|REJECT --score <n> --experiment ${experimentId} --variant ${variantId} --suite-task ${task.id}`,
30288
+ `npx cc-codeconductor scorecard create --task ${task.id} --from-diff`,
30289
+ `npx cc-codeconductor scorecard record --task ${task.id} --verdict PASS|REVISE|REJECT --score <n> --experiment ${experimentId} --variant ${variantId} --suite-task ${task.id}`,
29598
30290
  "```",
29599
30291
  task.testCommand ? `
29600
30292
  Fixture test command: \`${task.testCommand}\`
@@ -29618,7 +30310,7 @@ function formatExperimentMarkdown(experiment) {
29618
30310
  "Compare with:",
29619
30311
  "",
29620
30312
  "```",
29621
- `bun run dev scorecard ablation --experiment ${experiment.id}`,
30313
+ `npx cc-codeconductor scorecard ablation --experiment ${experiment.id}`,
29622
30314
  "```",
29623
30315
  ""
29624
30316
  ].join(`
@@ -29630,8 +30322,8 @@ function generateExperimentId(suiteId, now = new Date) {
29630
30322
  return `abl-${date}-${suiteId}-${rand}`;
29631
30323
  }
29632
30324
  async function copyFixture(suitePath, fixtureDir, dest) {
29633
- const source = fixtureDir ? resolve40(dirname13(suitePath), fixtureDir) : join29(dirname13(suitePath), "fixture");
29634
- await mkdir24(dest, { recursive: true });
30325
+ const source = fixtureDir ? resolve41(dirname15(suitePath), fixtureDir) : join30(dirname15(suitePath), "fixture");
30326
+ await mkdir26(dest, { recursive: true });
29635
30327
  if (existsSync9(source)) {
29636
30328
  await cp(source, dest, { recursive: true });
29637
30329
  }
@@ -29653,12 +30345,12 @@ async function startHarnessExperiment(projectRoot, options) {
29653
30345
  suitePath: suite.data.path
29654
30346
  };
29655
30347
  const root = experimentDir(projectRoot, experimentId);
29656
- await mkdir24(root, { recursive: true });
29657
- await writeFile23(experimentYamlPath(projectRoot, experimentId), $stringify(experiment), "utf-8");
29658
- await writeFile23(join29(root, "EXPERIMENT.md"), formatExperimentMarkdown(experiment), "utf-8");
30348
+ await mkdir26(root, { recursive: true });
30349
+ await writeFile24(experimentYamlPath(projectRoot, experimentId), $stringify(experiment), "utf-8");
30350
+ await writeFile24(join30(root, "EXPERIMENT.md"), formatExperimentMarkdown(experiment), "utf-8");
29659
30351
  for (const task of suite.data.tasks) {
29660
30352
  for (const variantId of variants) {
29661
- const runRoot = join29(root, "runs", task.id, variantDirName(variantId));
30353
+ const runRoot = join30(root, "runs", task.id, variantDirName(variantId));
29662
30354
  await copyFixture(suite.data.path, suite.data.fixtureDir, runRoot);
29663
30355
  await writeConfig(runRoot, structuredClone(DEFAULT_CONFIG), true);
29664
30356
  const disabled = variantId === "baseline" ? [] : options.components.filter((id) => variantIdFor(id) === variantId);
@@ -29670,7 +30362,7 @@ async function startHarnessExperiment(projectRoot, options) {
29670
30362
  });
29671
30363
  if (!overlay.success)
29672
30364
  return overlay;
29673
- await writeFile23(join29(runRoot, "TASK.md"), formatTaskCard(task, experimentId, variantId), "utf-8");
30365
+ await writeFile24(join30(runRoot, "TASK.md"), formatTaskCard(task, experimentId, variantId), "utf-8");
29674
30366
  }
29675
30367
  }
29676
30368
  return ok(experiment);
@@ -29703,9 +30395,9 @@ var init_harness_experiment = __esm(() => {
29703
30395
  });
29704
30396
 
29705
30397
  // src/core/evaluation/suite-run.ts
29706
- import { spawnSync as spawnSync2 } from "node:child_process";
30398
+ import { spawnSync as spawnSync3 } from "node:child_process";
29707
30399
  import { existsSync as existsSync10 } from "node:fs";
29708
- import { resolve as resolve41 } from "node:path";
30400
+ import { resolve as resolve42 } from "node:path";
29709
30401
  async function runHarnessSuiteTasks(projectRoot, suiteId, suitePath) {
29710
30402
  const suite = await loadHarnessSuite(projectRoot, suiteId, suitePath);
29711
30403
  if (!suite.success) {
@@ -29765,9 +30457,9 @@ function runTaskCommand(projectRoot, task) {
29765
30457
  if (parts.length === 0) {
29766
30458
  return { ok: false, detail: "Empty testCommand" };
29767
30459
  }
29768
- const bin = parts[0] === "bun" && existsSync10(resolve41(projectRoot, "src/cli/main.ts")) ? "bun" : parts[0];
30460
+ const bin = parts[0] === "bun" && existsSync10(resolve42(projectRoot, "src/cli/main.ts")) ? "bun" : parts[0];
29769
30461
  const args = parts[0] === "bun" ? parts.slice(1) : parts.slice(1);
29770
- const result = spawnSync2(bin, args, {
30462
+ const result = spawnSync3(bin, args, {
29771
30463
  cwd: projectRoot,
29772
30464
  encoding: "utf8",
29773
30465
  windowsHide: true,
@@ -29816,11 +30508,11 @@ var init_suite_run = __esm(() => {
29816
30508
  });
29817
30509
 
29818
30510
  // src/core/evaluation/execution-profile.ts
29819
- import { readFile as readFile43 } from "node:fs/promises";
29820
- import { resolve as resolve42 } from "node:path";
30511
+ import { readFile as readFile45 } from "node:fs/promises";
30512
+ import { resolve as resolve43 } from "node:path";
29821
30513
  async function loadExecutionProfile(projectRoot, defaultTarget = "opencode") {
29822
30514
  try {
29823
- const content = await readFile43(resolve42(projectRoot, PROFILE_FILE), "utf-8");
30515
+ const content = await readFile45(resolve43(projectRoot, PROFILE_FILE), "utf-8");
29824
30516
  const data = $parse(content);
29825
30517
  return ExecutionProfileSchema.parse(data);
29826
30518
  } catch {
@@ -29900,8 +30592,8 @@ var init_execution_profile = __esm(() => {
29900
30592
  });
29901
30593
 
29902
30594
  // src/core/evaluation/prompt-diff.ts
29903
- import { readFile as readFile44, readdir as readdir14 } from "node:fs/promises";
29904
- import { join as join30, resolve as resolve43 } from "node:path";
30595
+ import { readFile as readFile46, readdir as readdir14 } from "node:fs/promises";
30596
+ import { join as join31, resolve as resolve44 } from "node:path";
29905
30597
  function normalizeVersion(v) {
29906
30598
  return v.startsWith("v") ? v : `v${v}`;
29907
30599
  }
@@ -29950,30 +30642,30 @@ async function diffPromptVersions(fromVersion, toVersion, options = {}) {
29950
30642
  const fromV = normalizeVersion(fromVersion);
29951
30643
  const toV = normalizeVersion(toVersion);
29952
30644
  const searchRoots = [
29953
- resolve43(options.projectRoot ?? PACKAGE_ROOT, ".agents", "prompts"),
29954
- join30(ROOT_PRESETS_DIR, target, "prompts"),
29955
- join30(ROOT_PRESETS_DIR, "opencode", "prompts")
30645
+ resolve44(options.projectRoot ?? PACKAGE_ROOT, ".agents", "prompts"),
30646
+ join31(ROOT_PRESETS_DIR, target, "prompts"),
30647
+ join31(ROOT_PRESETS_DIR, "opencode", "prompts")
29956
30648
  ];
29957
30649
  let fromDir = "";
29958
30650
  let toDir = "";
29959
30651
  for (const root of searchRoots) {
29960
- const f = join30(root, fromV);
29961
- const t = join30(root, toV);
30652
+ const f = join31(root, fromV);
30653
+ const t = join31(root, toV);
29962
30654
  try {
29963
- await readFile44(join30(f, "orchestrator.md"), "utf-8");
30655
+ await readFile46(join31(f, "orchestrator.md"), "utf-8");
29964
30656
  fromDir = f;
29965
30657
  toDir = t;
29966
30658
  break;
29967
30659
  } catch {}
29968
30660
  }
29969
30661
  if (!fromDir) {
29970
- fromDir = join30(ROOT_PRESETS_DIR, "opencode", "prompts", fromV);
29971
- toDir = join30(ROOT_PRESETS_DIR, "opencode", "prompts", toV);
30662
+ fromDir = join31(ROOT_PRESETS_DIR, "opencode", "prompts", fromV);
30663
+ toDir = join31(ROOT_PRESETS_DIR, "opencode", "prompts", toV);
29972
30664
  } else {
29973
30665
  try {
29974
- await readFile44(join30(toDir, "orchestrator.md"), "utf-8");
30666
+ await readFile46(join31(toDir, "orchestrator.md"), "utf-8");
29975
30667
  } catch {
29976
- toDir = join30(ROOT_PRESETS_DIR, "opencode", "prompts", toV);
30668
+ toDir = join31(ROOT_PRESETS_DIR, "opencode", "prompts", toV);
29977
30669
  }
29978
30670
  }
29979
30671
  const fromFiles = await listPromptFiles(fromDir);
@@ -29991,12 +30683,12 @@ async function diffPromptVersions(fromVersion, toVersion, options = {}) {
29991
30683
  let oldText = "";
29992
30684
  let newText = "";
29993
30685
  try {
29994
- oldText = await readFile44(join30(fromDir, name), "utf-8");
30686
+ oldText = await readFile46(join31(fromDir, name), "utf-8");
29995
30687
  } catch {
29996
30688
  oldText = "";
29997
30689
  }
29998
30690
  try {
29999
- newText = await readFile44(join30(toDir, name), "utf-8");
30691
+ newText = await readFile46(join31(toDir, name), "utf-8");
30000
30692
  } catch {
30001
30693
  newText = "";
30002
30694
  }
@@ -30035,13 +30727,13 @@ var init_prompt_diff = __esm(() => {
30035
30727
  });
30036
30728
 
30037
30729
  // src/core/evaluation/regression-checklist.ts
30038
- import { execFileSync as execFileSync3 } from "node:child_process";
30039
- import { mkdir as mkdir25, readFile as readFile45, writeFile as writeFile24 } from "node:fs/promises";
30040
- import { dirname as dirname14, resolve as resolve44 } from "node:path";
30730
+ import { execFileSync as execFileSync4 } from "node:child_process";
30731
+ import { mkdir as mkdir27, readFile as readFile47, writeFile as writeFile25 } from "node:fs/promises";
30732
+ import { dirname as dirname16, resolve as resolve45 } from "node:path";
30041
30733
  async function loadRegressionChecklist() {
30042
30734
  try {
30043
- const path = resolve44(ROOT_PRESETS_DIR, "templates", "regression-checklist.yml");
30044
- const content = await readFile45(path, "utf-8");
30735
+ const path = resolve45(ROOT_PRESETS_DIR, "templates", "regression-checklist.yml");
30736
+ const content = await readFile47(path, "utf-8");
30045
30737
  const data = $parse(content);
30046
30738
  return data.checks ?? [];
30047
30739
  } catch {
@@ -30055,7 +30747,7 @@ function runCheckCommand(cmd, cwd) {
30055
30747
  if (!file)
30056
30748
  return { passed: false, message: "Empty command" };
30057
30749
  try {
30058
- execFileSync3(file, args, {
30750
+ execFileSync4(file, args, {
30059
30751
  cwd,
30060
30752
  encoding: "utf-8",
30061
30753
  stdio: ["ignore", "pipe", "pipe"],
@@ -30096,9 +30788,9 @@ async function runRegressionChecklist(projectRoot, options = {}) {
30096
30788
  checks,
30097
30789
  timestamp: new Date().toISOString()
30098
30790
  };
30099
- const outPath = resolve44(projectRoot, ".codeconductor/evaluation/regression-last.json");
30100
- await mkdir25(dirname14(outPath), { recursive: true });
30101
- await writeFile24(outPath, JSON.stringify(report, null, 2), "utf-8");
30791
+ const outPath = resolve45(projectRoot, ".codeconductor/evaluation/regression-last.json");
30792
+ await mkdir27(dirname16(outPath), { recursive: true });
30793
+ await writeFile25(outPath, JSON.stringify(report, null, 2), "utf-8");
30102
30794
  return ok(report);
30103
30795
  } catch (e) {
30104
30796
  return err(e instanceof Error ? e : new Error(String(e)));
@@ -30140,8 +30832,8 @@ var init_model_comparison = __esm(() => {
30140
30832
  });
30141
30833
 
30142
30834
  // src/core/evaluation/cost-quality-matrix.ts
30143
- import { writeFile as writeFile25 } from "node:fs/promises";
30144
- import { resolve as resolve45 } from "node:path";
30835
+ import { writeFile as writeFile26 } from "node:fs/promises";
30836
+ import { resolve as resolve46 } from "node:path";
30145
30837
  async function buildCostQualityMatrix(projectRoot, outcomes) {
30146
30838
  const agg = aggregateOutcomes(outcomes);
30147
30839
  const rows = Object.entries(agg.byModel).map(([model, entry]) => {
@@ -30161,7 +30853,7 @@ async function buildCostQualityMatrix(projectRoot, outcomes) {
30161
30853
  rows
30162
30854
  };
30163
30855
  const dir = await ensureEvaluationDir(projectRoot);
30164
- await writeFile25(resolve45(dir, "matrix.yml"), $stringify(matrix), "utf-8");
30856
+ await writeFile26(resolve46(dir, "matrix.yml"), $stringify(matrix), "utf-8");
30165
30857
  return matrix;
30166
30858
  }
30167
30859
  function formatMatrixMarkdown(matrix) {
@@ -30185,8 +30877,8 @@ var init_cost_quality_matrix = __esm(() => {
30185
30877
  });
30186
30878
 
30187
30879
  // src/core/evaluation/ablation-report.ts
30188
- import { mkdir as mkdir26, writeFile as writeFile26 } from "node:fs/promises";
30189
- import { resolve as resolve46 } from "node:path";
30880
+ import { mkdir as mkdir28, writeFile as writeFile27 } from "node:fs/promises";
30881
+ import { resolve as resolve47 } from "node:path";
30190
30882
  function isPass(o) {
30191
30883
  return o.verdict === "PASS" || o.status === "pass";
30192
30884
  }
@@ -30232,6 +30924,8 @@ async function averageCriteria(projectRoot, outcomes) {
30232
30924
  if (!loaded.success)
30233
30925
  continue;
30234
30926
  for (const c of loaded.data.criteria) {
30927
+ if (c.score === null)
30928
+ continue;
30235
30929
  if (!buckets[c.id])
30236
30930
  buckets[c.id] = [];
30237
30931
  buckets[c.id].push(c.score);
@@ -30292,7 +30986,11 @@ async function buildAblationReport(projectRoot, outcomes, experimentId) {
30292
30986
  ...Object.keys(treatment.criteria ?? {})
30293
30987
  ]);
30294
30988
  for (const cid of criterionIds) {
30295
- deltaCriteria[cid] = (treatment.criteria?.[cid] ?? 0) - (baseline.criteria?.[cid] ?? 0);
30989
+ const baselineScore = baseline.criteria?.[cid];
30990
+ const treatmentScore = treatment.criteria?.[cid];
30991
+ if (baselineScore !== undefined && treatmentScore !== undefined) {
30992
+ deltaCriteria[cid] = treatmentScore - baselineScore;
30993
+ }
30296
30994
  }
30297
30995
  rows.push({
30298
30996
  component: id,
@@ -30354,10 +31052,10 @@ function formatAblationMarkdown(report) {
30354
31052
  `);
30355
31053
  }
30356
31054
  async function persistAblationReport(projectRoot, markdown) {
30357
- const dir = resolve46(projectRoot, EVAL_DIR2);
30358
- await mkdir26(dir, { recursive: true });
30359
- const path = resolve46(dir, "ablation-last.md");
30360
- await writeFile26(path, markdown, "utf-8");
31055
+ const dir = resolve47(projectRoot, EVAL_DIR2);
31056
+ await mkdir28(dir, { recursive: true });
31057
+ const path = resolve47(dir, "ablation-last.md");
31058
+ await writeFile27(path, markdown, "utf-8");
30361
31059
  return path;
30362
31060
  }
30363
31061
  var SCORE_THRESHOLD = 0.1, PASS_RATE_THRESHOLD = 0.05;
@@ -30371,8 +31069,8 @@ var exports_scorecard_command = {};
30371
31069
  __export(exports_scorecard_command, {
30372
31070
  scorecardCommand: () => scorecardCommand
30373
31071
  });
30374
- import { readFile as readFile46 } from "node:fs/promises";
30375
- import { resolve as resolve47 } from "node:path";
31072
+ import { readFile as readFile48 } from "node:fs/promises";
31073
+ import { resolve as resolve48 } from "node:path";
30376
31074
  function contractVersion() {
30377
31075
  return package_default.version;
30378
31076
  }
@@ -30436,19 +31134,22 @@ async function handleCreate(projectRoot, options) {
30436
31134
  scopeFiles = parseScopeFiles(item.scope);
30437
31135
  }
30438
31136
  }
30439
- let hints = collectScorecardSignals(projectRoot, scopeFiles);
30440
31137
  const state = await loadOpenspecState(projectRoot);
30441
31138
  const backlogId = options.taskId?.startsWith("BC-") ? options.taskId : undefined;
31139
+ const baseCommit = backlogId && state.success ? state.data.itemBaseCommits?.[backlogId] : undefined;
31140
+ let hints = collectScorecardSignals(projectRoot, scopeFiles, { baseCommit });
30442
31141
  const changePath = backlogId && state.success ? state.data.changePaths[backlogId] : undefined;
30443
31142
  if (changePath && !changePath.includes("/archive/")) {
30444
31143
  const tddRequired = backlog.success ? backlog.data.global.tddRequired : false;
30445
31144
  const cards = state.success ? state.data.taskCards.filter((c) => c.backlogId === backlogId) : [];
30446
31145
  let hasEvidence;
30447
- if (cards.some((c) => c.phase === "test" || c.phase === "implement")) {
30448
- hasEvidence = false;
30449
- for (const card of cards) {
30450
- if ((card.phase === "test" || card.phase === "implement") && await hasTddRunnerEvidence(projectRoot, card.id)) {
30451
- hasEvidence = true;
31146
+ const tddCards = cards.filter((c) => c.phase === "test" || c.phase === "implement");
31147
+ if (tddCards.length > 0) {
31148
+ hasEvidence = true;
31149
+ for (const card of tddCards) {
31150
+ const expectedPhase = card.phase === "test" ? "red" : "green";
31151
+ if (!await hasTddRunnerEvidence(projectRoot, card.id, expectedPhase)) {
31152
+ hasEvidence = false;
30452
31153
  break;
30453
31154
  }
30454
31155
  }
@@ -30467,6 +31168,10 @@ async function handleCreate(projectRoot, options) {
30467
31168
  criteria = criteriaFromSignals(hints);
30468
31169
  findings = hints.findings;
30469
31170
  }
31171
+ const pending = pendingCriteria(criteria);
31172
+ if (pending.length > 0) {
31173
+ findings.push(`Unmeasured criteria requiring manual scores with notes: ${pending.join(", ")}`);
31174
+ }
30470
31175
  const id = generateEvalId("sc");
30471
31176
  const configResult = await loadConfig(projectRoot);
30472
31177
  const target = configResult.success ? configResult.data.defaults.target : "opencode";
@@ -30660,13 +31365,13 @@ async function handleCompareModels(projectRoot, options) {
30660
31365
  outcomes = outcomes.filter((o) => options.modelsFilter.includes(o.model));
30661
31366
  }
30662
31367
  const markdown = generateModelComparisonMarkdown(outcomes, options.modelsFilter);
30663
- const templatePath = resolve47(projectRoot, ".codeconductor/evaluation/model-comparison-last.md");
31368
+ const templatePath = resolve48(projectRoot, ".codeconductor/evaluation/model-comparison-last.md");
30664
31369
  try {
30665
- await readFile46(templatePath);
31370
+ await readFile48(templatePath);
30666
31371
  } catch {}
30667
- const { writeFile: writeFile27, mkdir: mkdir27 } = await import("node:fs/promises");
30668
- await mkdir27(resolve47(projectRoot, ".codeconductor/evaluation"), { recursive: true });
30669
- await writeFile27(templatePath, markdown, "utf-8");
31372
+ const { writeFile: writeFile28, mkdir: mkdir29 } = await import("node:fs/promises");
31373
+ await mkdir29(resolve48(projectRoot, ".codeconductor/evaluation"), { recursive: true });
31374
+ await writeFile28(templatePath, markdown, "utf-8");
30670
31375
  return {
30671
31376
  code: 0,
30672
31377
  data: {
@@ -30875,9 +31580,9 @@ function getDomain(url) {
30875
31580
  function originOf(url) {
30876
31581
  try {
30877
31582
  const parsed = new URL(url);
30878
- const hostname = parsed.hostname.toLowerCase().replace(/\.$/, "");
31583
+ const hostname2 = parsed.hostname.toLowerCase().replace(/\.$/, "");
30879
31584
  const port = parsed.port !== "" ? parsed.port : parsed.protocol === "https:" ? "443" : "80";
30880
- return `${parsed.protocol}//${hostname}:${port}`;
31585
+ return `${parsed.protocol}//${hostname2}:${port}`;
30881
31586
  } catch {
30882
31587
  return;
30883
31588
  }
@@ -32135,7 +32840,7 @@ var exports_seo_audit_command = {};
32135
32840
  __export(exports_seo_audit_command, {
32136
32841
  seoAuditCommand: () => seoAuditCommand
32137
32842
  });
32138
- import { join as join31 } from "node:path";
32843
+ import { join as join32 } from "node:path";
32139
32844
  async function seoAuditCommand(options) {
32140
32845
  const { url, sitemap, format, failOn, delay: delay2, output, followRedirects, force } = options;
32141
32846
  if (!url && !sitemap) {
@@ -32148,7 +32853,7 @@ async function seoAuditCommand(options) {
32148
32853
  }
32149
32854
  };
32150
32855
  }
32151
- const defaultMarkdownPath = output === undefined && format === "markdown" ? join31("seo-reports", `audit-report-${new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19)}.md`) : undefined;
32856
+ const defaultMarkdownPath = output === undefined && format === "markdown" ? join32("seo-reports", `audit-report-${new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19)}.md`) : undefined;
32152
32857
  const outputPathToWrite = output ?? defaultMarkdownPath;
32153
32858
  if (outputPathToWrite !== undefined) {
32154
32859
  const preflightError = await preflightContainedOutput(options.projectRoot, outputPathToWrite, { force });
@@ -32535,6 +33240,7 @@ var COMMANDS = [
32535
33240
  { name: "orchestrate", group: "workflow", summary: "Run goal execution orchestration.", usage: ["cc-codeconductor orchestrate <subcommand>"] },
32536
33241
  { name: "impact", group: "workflow", summary: "Analyze change impact.", usage: ["cc-codeconductor impact [--files <paths>]"] },
32537
33242
  { name: "verify", group: "workflow", summary: "Verify task completion with evidence.", usage: ["cc-codeconductor verify --task <id>"] },
33243
+ { name: "tdd", group: "workflow", summary: "Capture runner-verified RED/GREEN TDD evidence.", usage: ['cc-codeconductor tdd capture --task <cardId> --phase red|green --command "<test command>"'] },
32538
33244
  { name: "rdd", group: "workflow", summary: "Capture and validate Receipt-Driven Development evidence.", usage: ["cc-codeconductor rdd capture --task <id> [--phase red|green|review]", "cc-codeconductor rdd verify --receipt <id>", "cc-codeconductor rdd status [--task <id>]", "cc-codeconductor rdd git-check", "cc-codeconductor rdd install-hooks"] },
32539
33245
  { name: "seo", group: "tool", summary: "Audit SEO and generate llms.txt.", usage: ["cc-codeconductor seo audit --url <url>"] },
32540
33246
  { name: "debt-harvest", aliases: ["harvest"], group: "tool", summary: "Scan source files for deferred debt.", usage: ["cc-codeconductor debt-harvest"] }
@@ -33110,6 +33816,18 @@ async function routeCommand(args, projectRoot) {
33110
33816
  allowCompileCheck: options["allow-compile-check"] === true || options["allow-compile-check"] === "true"
33111
33817
  });
33112
33818
  }
33819
+ case "tdd": {
33820
+ const { tddCommand: tddCommand2 } = await Promise.resolve().then(() => (init_tdd_command(), exports_tdd_command));
33821
+ return tddCommand2({
33822
+ subcommand: subcommand ?? "",
33823
+ projectRoot,
33824
+ output: flags.output,
33825
+ taskId: options.task ?? args.rest?.[0],
33826
+ phase: options.phase,
33827
+ command: options.command,
33828
+ allowCompileCheck: options["allow-compile-check"] === true || options["allow-compile-check"] === "true"
33829
+ });
33830
+ }
33113
33831
  case "rdd": {
33114
33832
  const validSubs = ["capture", "verify", "status", "git-check", "install-hooks"];
33115
33833
  if (!subcommand || !validSubs.includes(subcommand)) {
@@ -33196,6 +33914,7 @@ async function routeCommand(args, projectRoot) {
33196
33914
  subcommand: openspecSub,
33197
33915
  itemId,
33198
33916
  reason: typeof options.reason === "string" ? options.reason : undefined,
33917
+ allowUnchecked: options["allow-unchecked"] === true || options["allow-unchecked"] === "true",
33199
33918
  projectRoot,
33200
33919
  output: flags.output
33201
33920
  });