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/library.js CHANGED
@@ -156,7 +156,7 @@ function validateProductEvent(data) {
156
156
  function validateSkillsRegistry(data) {
157
157
  return SkillsRegistrySchema.parse(data);
158
158
  }
159
- 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;
159
+ 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;
160
160
  var init_schemas = __esm(() => {
161
161
  init_runner_target();
162
162
  CouncilAgentSpecSchema = z.object({
@@ -400,6 +400,7 @@ var init_schemas = __esm(() => {
400
400
  title: z.string(),
401
401
  type: z.enum(["feature", "fix", "refactor", "test", "docs"]),
402
402
  risk: z.enum(["low", "medium", "high"]),
403
+ priority: z.enum(["P0", "P1", "P2", "P3"]).optional(),
403
404
  status: z.enum(["pending", "in-progress", "done", "blocked"]),
404
405
  depends_on: z.array(z.string()).optional().default([]),
405
406
  acceptance_criteria: z.array(z.string()),
@@ -472,6 +473,13 @@ var init_schemas = __esm(() => {
472
473
  summary: z.string().optional(),
473
474
  data: z.record(z.string(), z.unknown()).optional()
474
475
  });
476
+ TddValidationRecordSchema = z.object({
477
+ taskId: z.string().min(1),
478
+ evidenceId: z.string().min(1),
479
+ receiptNonce: z.string().regex(/^[0-9a-f]{32}$/),
480
+ manifestHash: z.string().regex(/^[0-9a-f]{64}$/),
481
+ validatedAt: z.string().datetime()
482
+ }).strict();
475
483
  CanonicalTaskCardStatusSchema = z.enum([
476
484
  "draft",
477
485
  "ready",
@@ -536,6 +544,7 @@ var init_schemas = __esm(() => {
536
544
  ProductEventTypeSchema = z.enum([
537
545
  "task.started",
538
546
  "task.completed",
547
+ "lock.recovered",
539
548
  "decision.recorded",
540
549
  "evidence.added",
541
550
  "ingest.completed",
@@ -672,7 +681,8 @@ var init_schemas = __esm(() => {
672
681
  lastScanHash: z.string().optional(),
673
682
  lastScanAt: z.string().optional(),
674
683
  changePaths: z.record(z.string(), z.string()).optional().default({}),
675
- itemSnapshots: z.record(z.string(), z.string()).optional().default({})
684
+ itemSnapshots: z.record(z.string(), z.string()).optional().default({}),
685
+ itemBaseCommits: z.record(z.string(), z.string()).optional()
676
686
  });
677
687
  SpecAnalyzeFindingSchema = z.object({
678
688
  severity: z.enum(["CRITICAL", "HIGH", "MEDIUM", "LOW"]),
@@ -908,7 +918,8 @@ var init_schemas = __esm(() => {
908
918
  id: ScorecardCriterionIdSchema,
909
919
  label: z.string(),
910
920
  weight: z.number().min(0).max(1),
911
- score: z.number().int().min(0).max(3),
921
+ score: z.number().int().min(0).max(3).nullable(),
922
+ unmeasured: z.boolean().optional(),
912
923
  notes: z.string().optional(),
913
924
  autoSuggested: z.boolean().optional()
914
925
  });
@@ -1140,16 +1151,228 @@ function err(error) {
1140
1151
  return { success: false, error };
1141
1152
  }
1142
1153
 
1154
+ // src/core/product-graph/paths.ts
1155
+ import { join } from "node:path";
1156
+ function productGraphPath(projectRoot) {
1157
+ return join(projectRoot, PRODUCT_DIR, PRODUCT_GRAPH_FILE);
1158
+ }
1159
+ function eventsPath(projectRoot) {
1160
+ return join(projectRoot, PRODUCT_DIR, EVENTS_FILE);
1161
+ }
1162
+ function operationalStatePath(projectRoot) {
1163
+ return join(projectRoot, PRODUCT_DIR, OPERATIONAL_STATE_FILE);
1164
+ }
1165
+ function evidenceDir(projectRoot) {
1166
+ return join(projectRoot, PRODUCT_DIR, EVIDENCE_DIR);
1167
+ }
1168
+ var PRODUCT_DIR = ".codeconductor", PRODUCT_GRAPH_FILE = "product-graph.json", EVENTS_FILE = "events.jsonl", OPERATIONAL_STATE_FILE = "operational-state.json", EVIDENCE_DIR = "evidence";
1169
+ var init_paths = () => {};
1170
+
1171
+ // src/core/memory/episodic-store.ts
1172
+ import { appendFile, mkdir as mkdir2, readFile as readFile2 } from "node:fs/promises";
1173
+ import { resolve } from "node:path";
1174
+ async function appendEvent(projectRoot, event) {
1175
+ try {
1176
+ const full = ProductEventSchema.parse({
1177
+ ...event,
1178
+ id: event.id ?? `evt-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
1179
+ });
1180
+ const path = eventsPath(projectRoot);
1181
+ await mkdir2(resolve(projectRoot, ".codeconductor"), { recursive: true });
1182
+ await appendFile(path, JSON.stringify(full) + `
1183
+ `, "utf-8");
1184
+ return ok(full);
1185
+ } catch (e) {
1186
+ return err(e instanceof Error ? e : new Error(String(e)));
1187
+ }
1188
+ }
1189
+ var init_episodic_store = __esm(() => {
1190
+ init_schemas();
1191
+ init_paths();
1192
+ });
1193
+
1194
+ // src/core/queue/lock.ts
1195
+ import { createHash, randomUUID } from "node:crypto";
1196
+ import { AsyncLocalStorage } from "node:async_hooks";
1197
+ import { mkdir as mkdir3, open, readFile as readFile3, unlink } from "node:fs/promises";
1198
+ import { hostname } from "node:os";
1199
+ import { resolve as resolve2 } from "node:path";
1200
+ async function readOwner(path) {
1201
+ const owner = JSON.parse(await readFile3(path, "utf8"));
1202
+ if (!Number.isInteger(owner.pid) || owner.pid <= 0 || typeof owner.hostname !== "string" || typeof owner.token !== "string" || !owner.token || !Number.isFinite(Date.parse(owner.timestamp))) {
1203
+ throw new Error("Invalid queue lock metadata");
1204
+ }
1205
+ return owner;
1206
+ }
1207
+ function isOrphan(owner) {
1208
+ if (owner.hostname !== hostname() || Date.now() - Date.parse(owner.timestamp) < STALE_MS)
1209
+ return false;
1210
+ try {
1211
+ process.kill(owner.pid, 0);
1212
+ return false;
1213
+ } catch (e) {
1214
+ return e.code === "ESRCH";
1215
+ }
1216
+ }
1217
+ async function removeOwned(path, token) {
1218
+ try {
1219
+ if ((await readOwner(path)).token === token)
1220
+ await unlink(path);
1221
+ } catch (e) {
1222
+ if (e.code !== "ENOENT")
1223
+ throw e;
1224
+ }
1225
+ }
1226
+ async function electRecovery(dir, token, owner) {
1227
+ const registry = resolve2(dir, "recoveries");
1228
+ await mkdir3(registry, { recursive: true });
1229
+ const seen = new Set;
1230
+ while (!seen.has(token)) {
1231
+ seen.add(token);
1232
+ const path = resolve2(registry, `${createHash("sha256").update(token).digest("hex")}.json`);
1233
+ try {
1234
+ const file = await open(path, "wx");
1235
+ try {
1236
+ await file.writeFile(JSON.stringify(owner));
1237
+ } finally {
1238
+ await file.close();
1239
+ }
1240
+ return true;
1241
+ } catch (e) {
1242
+ if (e.code !== "EEXIST")
1243
+ throw e;
1244
+ }
1245
+ const elected = await readOwner(path);
1246
+ if (elected.token === owner.token)
1247
+ return true;
1248
+ if (!isOrphan(elected))
1249
+ return false;
1250
+ token = elected.token;
1251
+ }
1252
+ throw new Error("Invalid queue lock recovery chain");
1253
+ }
1254
+ async function withQueueLock(projectRoot, action) {
1255
+ const root = resolve2(projectRoot);
1256
+ const held = heldLocks.getStore();
1257
+ if (held?.has(root))
1258
+ return action();
1259
+ const dir = resolve2(projectRoot, ".codeconductor/queue");
1260
+ const path = resolve2(dir, ".lock");
1261
+ const recoveryPath = resolve2(dir, ".lock.recovery");
1262
+ const owner = {
1263
+ pid: process.pid,
1264
+ hostname: hostname(),
1265
+ timestamp: new Date().toISOString(),
1266
+ token: randomUUID()
1267
+ };
1268
+ let acquired = false;
1269
+ try {
1270
+ await mkdir3(dir, { recursive: true });
1271
+ for (let attempt = 0;attempt < 40; attempt++) {
1272
+ try {
1273
+ const recoveryOwner = await readOwner(recoveryPath);
1274
+ if (isOrphan(recoveryOwner) && await electRecovery(dir, recoveryOwner.token, owner)) {
1275
+ await removeOwned(recoveryPath, recoveryOwner.token);
1276
+ continue;
1277
+ }
1278
+ } catch (e) {
1279
+ if (e instanceof SyntaxError || e instanceof Error && e.message === "Invalid queue lock metadata") {
1280
+ await new Promise((resolveWait) => setTimeout(resolveWait, 25));
1281
+ continue;
1282
+ }
1283
+ if (e.code !== "ENOENT")
1284
+ throw e;
1285
+ try {
1286
+ const file = await open(path, "wx");
1287
+ try {
1288
+ await file.writeFile(JSON.stringify(owner));
1289
+ } finally {
1290
+ await file.close();
1291
+ }
1292
+ acquired = true;
1293
+ break;
1294
+ } catch (e2) {
1295
+ if (e2.code !== "EEXIST")
1296
+ throw e2;
1297
+ }
1298
+ try {
1299
+ const existing = await readOwner(path);
1300
+ if (isOrphan(existing) && await electRecovery(dir, existing.token, owner)) {
1301
+ const current = await readOwner(path);
1302
+ if (current.token === existing.token && isOrphan(current)) {
1303
+ await unlink(path);
1304
+ const recovered = await appendEvent(projectRoot, {
1305
+ type: "lock.recovered",
1306
+ timestamp: new Date().toISOString(),
1307
+ payload: { owner: current }
1308
+ });
1309
+ if (!recovered.success)
1310
+ return recovered;
1311
+ }
1312
+ continue;
1313
+ }
1314
+ } catch (e2) {
1315
+ if (!(e2 instanceof SyntaxError) && !(e2 instanceof Error && e2.message === "Invalid queue lock metadata") && !["ENOENT", "EEXIST"].includes(e2.code ?? ""))
1316
+ throw e2;
1317
+ }
1318
+ }
1319
+ await new Promise((resolveWait) => setTimeout(resolveWait, 25));
1320
+ }
1321
+ if (!acquired)
1322
+ return err(new Error("Queue lock is held by another process; retry after it finishes"));
1323
+ return await heldLocks.run(new Set([...held ?? [], root]), action);
1324
+ } catch (e) {
1325
+ return err(e instanceof Error ? e : new Error(String(e)));
1326
+ } finally {
1327
+ if (acquired) {
1328
+ try {
1329
+ await removeOwned(path, owner.token);
1330
+ } catch (e) {
1331
+ return err(e instanceof Error ? e : new Error(String(e)));
1332
+ }
1333
+ }
1334
+ }
1335
+ }
1336
+ var STALE_MS, heldLocks;
1337
+ var init_lock = __esm(() => {
1338
+ init_episodic_store();
1339
+ STALE_MS = 5 * 60 * 1000;
1340
+ heldLocks = new AsyncLocalStorage;
1341
+ });
1342
+
1143
1343
  // src/core/goal/goal-state.ts
1144
1344
  var exports_goal_state = {};
1145
1345
  __export(exports_goal_state, {
1146
1346
  loadGoal: () => loadGoal,
1147
1347
  markTaskBlocked: () => markTaskBlocked,
1348
+ propagateBlockedTasks: () => propagateBlockedTasks,
1148
1349
  writeGoal: () => writeGoal
1149
1350
  });
1150
- import { mkdir as mkdir2, readFile as readFile2, writeFile as writeFile2 } from "node:fs/promises";
1151
- import { resolve } from "node:path";
1351
+ import { randomUUID as randomUUID2 } from "node:crypto";
1352
+ import { mkdir as mkdir4, readFile as readFile4, rename, unlink as unlink2, writeFile as writeFile2 } from "node:fs/promises";
1353
+ import { resolve as resolve3 } from "node:path";
1152
1354
  import { parse, stringify } from "yaml";
1355
+ function propagateBlockedTasks(graph) {
1356
+ const blocked = new Set(graph.tasks.filter((task) => task.status === "blocked").map((task) => task.id));
1357
+ let changed = false;
1358
+ let progressed;
1359
+ do {
1360
+ progressed = false;
1361
+ for (const task of graph.tasks) {
1362
+ if (task.status !== "pending")
1363
+ continue;
1364
+ const dependency = (task.depends_on ?? []).find((id) => blocked.has(id));
1365
+ if (!dependency)
1366
+ continue;
1367
+ task.status = "blocked";
1368
+ task.blocked_reason = `Blocked by dependency "${dependency}"`;
1369
+ blocked.add(task.id);
1370
+ progressed = true;
1371
+ changed = true;
1372
+ }
1373
+ } while (progressed);
1374
+ return changed;
1375
+ }
1153
1376
  function validateGoalGraph2(graph) {
1154
1377
  const ids = new Set(graph.tasks.map((t) => t.id));
1155
1378
  if (ids.size !== graph.tasks.length) {
@@ -1164,14 +1387,20 @@ function validateGoalGraph2(graph) {
1164
1387
  }
1165
1388
  const visited = new Set;
1166
1389
  const inStack = new Set;
1390
+ const path = [];
1391
+ let cycle = [];
1392
+ const tasksById = new Map(graph.tasks.map((task) => [task.id, task]));
1167
1393
  function dfs(taskId) {
1168
- if (inStack.has(taskId))
1394
+ if (inStack.has(taskId)) {
1395
+ cycle = [...path.slice(path.indexOf(taskId)), taskId];
1169
1396
  return true;
1397
+ }
1170
1398
  if (visited.has(taskId))
1171
1399
  return false;
1172
1400
  visited.add(taskId);
1173
1401
  inStack.add(taskId);
1174
- const task = graph.tasks.find((t) => t.id === taskId);
1402
+ path.push(taskId);
1403
+ const task = tasksById.get(taskId);
1175
1404
  if (task) {
1176
1405
  for (const dep of task.depends_on ?? []) {
1177
1406
  if (dfs(dep))
@@ -1179,29 +1408,43 @@ function validateGoalGraph2(graph) {
1179
1408
  }
1180
1409
  }
1181
1410
  inStack.delete(taskId);
1411
+ path.pop();
1182
1412
  return false;
1183
1413
  }
1184
1414
  for (const task of graph.tasks) {
1185
1415
  if (dfs(task.id)) {
1186
- return err(new Error(`Cycle detected involving task "${task.id}"`));
1416
+ return err(new Error(`Cycle detected: ${cycle.join(" -> ")}`));
1187
1417
  }
1188
1418
  }
1189
1419
  return ok(graph);
1190
1420
  }
1191
1421
  async function writeGoal(projectRoot, graph) {
1422
+ return withQueueLock(projectRoot, () => writeGoalUnlocked(projectRoot, graph));
1423
+ }
1424
+ async function writeGoalUnlocked(projectRoot, graph) {
1192
1425
  const validation = validateGoalGraph2(graph);
1193
1426
  if (!validation.success)
1194
1427
  return validation;
1195
- const dir = resolve(projectRoot, ".codeconductor");
1196
- await mkdir2(dir, { recursive: true });
1197
- const yaml = stringify(graph);
1198
- await writeFile2(resolve(dir, "current-goal.yml"), yaml, "utf-8");
1199
- return ok(undefined);
1428
+ const dir = resolve3(projectRoot, ".codeconductor");
1429
+ const temporary = resolve3(dir, `current-goal.${process.pid}.${randomUUID2()}.tmp`);
1430
+ try {
1431
+ await mkdir4(dir, { recursive: true });
1432
+ await writeFile2(temporary, stringify(graph), { encoding: "utf-8", flag: "wx" });
1433
+ await rename(temporary, resolve3(dir, "current-goal.yml"));
1434
+ return ok(undefined);
1435
+ } catch (e) {
1436
+ return err(e instanceof Error ? e : new Error(String(e)));
1437
+ } finally {
1438
+ await unlink2(temporary).catch((e) => {
1439
+ if (e.code !== "ENOENT")
1440
+ throw e;
1441
+ });
1442
+ }
1200
1443
  }
1201
1444
  async function loadGoal(projectRoot) {
1202
1445
  try {
1203
- const filePath = resolve(projectRoot, GOAL_FILE);
1204
- const content = await readFile2(filePath, "utf-8");
1446
+ const filePath = resolve3(projectRoot, GOAL_FILE);
1447
+ const content = await readFile4(filePath, "utf-8");
1205
1448
  const data = parse(content);
1206
1449
  const validated = GoalGraphSchema.parse(data);
1207
1450
  return validateGoalGraph2(validated);
@@ -1210,6 +1453,9 @@ async function loadGoal(projectRoot) {
1210
1453
  }
1211
1454
  }
1212
1455
  async function markTaskBlocked(projectRoot, taskId, reason) {
1456
+ return withQueueLock(projectRoot, () => markTaskBlockedUnlocked(projectRoot, taskId, reason));
1457
+ }
1458
+ async function markTaskBlockedUnlocked(projectRoot, taskId, reason) {
1213
1459
  const loadResult = await loadGoal(projectRoot);
1214
1460
  if (!loadResult.success)
1215
1461
  return loadResult;
@@ -1220,11 +1466,13 @@ async function markTaskBlocked(projectRoot, taskId, reason) {
1220
1466
  }
1221
1467
  task.status = "blocked";
1222
1468
  task.blocked_reason = reason;
1469
+ propagateBlockedTasks(graph);
1223
1470
  return writeGoal(projectRoot, graph);
1224
1471
  }
1225
1472
  var GOAL_FILE = ".codeconductor/current-goal.yml";
1226
1473
  var init_goal_state = __esm(() => {
1227
1474
  init_schemas();
1475
+ init_lock();
1228
1476
  });
1229
1477
 
1230
1478
  // src/core/product-graph/graph-store.ts
@@ -1259,27 +1507,8 @@ function resolveCliBin(env = process.env, argv = process.argv) {
1259
1507
  return "cc-codeconductor";
1260
1508
  }
1261
1509
 
1262
- // src/core/product-graph/paths.ts
1263
- import { join } from "node:path";
1264
- var PRODUCT_DIR = ".codeconductor";
1265
- var PRODUCT_GRAPH_FILE = "product-graph.json";
1266
- var EVENTS_FILE = "events.jsonl";
1267
- var OPERATIONAL_STATE_FILE = "operational-state.json";
1268
- var EVIDENCE_DIR = "evidence";
1269
- function productGraphPath(projectRoot) {
1270
- return join(projectRoot, PRODUCT_DIR, PRODUCT_GRAPH_FILE);
1271
- }
1272
- function eventsPath(projectRoot) {
1273
- return join(projectRoot, PRODUCT_DIR, EVENTS_FILE);
1274
- }
1275
- function operationalStatePath(projectRoot) {
1276
- return join(projectRoot, PRODUCT_DIR, OPERATIONAL_STATE_FILE);
1277
- }
1278
- function evidenceDir(projectRoot) {
1279
- return join(projectRoot, PRODUCT_DIR, EVIDENCE_DIR);
1280
- }
1281
-
1282
1510
  // src/core/product-graph/graph-store.ts
1511
+ init_paths();
1283
1512
  async function loadGraph(projectRoot) {
1284
1513
  try {
1285
1514
  const raw = await readFile(productGraphPath(projectRoot), "utf-8");
@@ -1357,34 +1586,17 @@ function enrichGoalWithProduct(graph, productGraph) {
1357
1586
 
1358
1587
  // src/core/orchestrator/runtime-orchestrator.ts
1359
1588
  init_goal_state();
1360
-
1361
- // src/core/memory/episodic-store.ts
1362
- init_schemas();
1363
- import { appendFile, mkdir as mkdir3, readFile as readFile3 } from "node:fs/promises";
1364
- import { resolve as resolve2 } from "node:path";
1365
- async function appendEvent(projectRoot, event) {
1366
- try {
1367
- const full = ProductEventSchema.parse({
1368
- ...event,
1369
- id: event.id ?? `evt-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
1370
- });
1371
- const path = eventsPath(projectRoot);
1372
- await mkdir3(resolve2(projectRoot, ".codeconductor"), { recursive: true });
1373
- await appendFile(path, JSON.stringify(full) + `
1374
- `, "utf-8");
1375
- return ok(full);
1376
- } catch (e) {
1377
- return err(e instanceof Error ? e : new Error(String(e)));
1378
- }
1379
- }
1589
+ init_lock();
1590
+ init_episodic_store();
1380
1591
 
1381
1592
  // src/core/memory/operational-state.ts
1382
1593
  init_schemas();
1383
- import { mkdir as mkdir4, readFile as readFile4, writeFile as writeFile3 } from "node:fs/promises";
1384
- import { resolve as resolve3 } from "node:path";
1594
+ init_paths();
1595
+ import { mkdir as mkdir5, readFile as readFile5, writeFile as writeFile3 } from "node:fs/promises";
1596
+ import { resolve as resolve4 } from "node:path";
1385
1597
  async function loadOperationalState(projectRoot) {
1386
1598
  try {
1387
- const raw = await readFile4(operationalStatePath(projectRoot), "utf-8");
1599
+ const raw = await readFile5(operationalStatePath(projectRoot), "utf-8");
1388
1600
  return ok(OperationalStateSchema.parse(JSON.parse(raw)));
1389
1601
  } catch (e) {
1390
1602
  if (e.code === "ENOENT") {
@@ -1406,7 +1618,7 @@ async function saveOperationalState(projectRoot, state) {
1406
1618
  updatedAt: new Date().toISOString()
1407
1619
  });
1408
1620
  const path = operationalStatePath(projectRoot);
1409
- await mkdir4(resolve3(projectRoot, ".codeconductor"), { recursive: true });
1621
+ await mkdir5(resolve4(projectRoot, ".codeconductor"), { recursive: true });
1410
1622
  await writeFile3(path, JSON.stringify(validated, null, 2), "utf-8");
1411
1623
  return ok(undefined);
1412
1624
  } catch (e) {
@@ -1439,12 +1651,12 @@ async function clearActiveTask(projectRoot, taskId) {
1439
1651
  // src/core/verification/verification-runner.ts
1440
1652
  init_schemas();
1441
1653
  import { existsSync } from "node:fs";
1442
- import { readFile as readFile7 } from "node:fs/promises";
1443
- import { dirname, join as join3, resolve as resolve6 } from "node:path";
1654
+ import { readFile as readFile8 } from "node:fs/promises";
1655
+ import { dirname, join as join3, resolve as resolve7 } from "node:path";
1444
1656
 
1445
1657
  // src/core/config/config-loader.ts
1446
- import { readFile as readFile5 } from "node:fs/promises";
1447
- import { resolve as resolve4 } from "node:path";
1658
+ import { readFile as readFile6 } from "node:fs/promises";
1659
+ import { resolve as resolve5 } from "node:path";
1448
1660
  import { parse as parse2 } from "yaml";
1449
1661
 
1450
1662
  // src/cli/errors.ts
@@ -1480,8 +1692,8 @@ init_schemas();
1480
1692
  var CONFIG_FILE = ".codeconductor/config.yml";
1481
1693
  async function loadConfig(projectRoot) {
1482
1694
  try {
1483
- const configPath = resolve4(projectRoot, CONFIG_FILE);
1484
- const content = await readFile5(configPath, "utf-8");
1695
+ const configPath = resolve5(projectRoot, CONFIG_FILE);
1696
+ const content = await readFile6(configPath, "utf-8");
1485
1697
  const data = parse2(content);
1486
1698
  if (!data) {
1487
1699
  return err(new ValidationError("Empty config file"));
@@ -1500,6 +1712,7 @@ async function loadConfig(projectRoot) {
1500
1712
  }
1501
1713
 
1502
1714
  // src/core/compilation/compile-checker.ts
1715
+ import { spawn } from "node:child_process";
1503
1716
  var DEFAULT_COMMAND = "tsc --noEmit";
1504
1717
  var DEFAULT_TIMEOUT_MS = 120000;
1505
1718
  function tokenizeCommand(cmd) {
@@ -1670,40 +1883,37 @@ async function runCompileCheck(options) {
1670
1883
  const startTime = performance.now();
1671
1884
  let timedOut = false;
1672
1885
  const parts = Array.isArray(command) ? command : tokenizeCommand(command);
1886
+ const failure = (stderr) => ({
1887
+ success: false,
1888
+ exitCode: -1,
1889
+ stdout: "",
1890
+ stderr,
1891
+ errors: [],
1892
+ durationMs: performance.now() - startTime,
1893
+ timedOut: false
1894
+ });
1673
1895
  let proc;
1674
1896
  try {
1675
- proc = Bun.spawn(parts, {
1897
+ proc = spawn(parts[0], parts.slice(1), {
1676
1898
  cwd,
1677
- stdout: "pipe",
1678
- stderr: "pipe",
1899
+ stdio: ["ignore", "pipe", "pipe"],
1679
1900
  env: minimalChildEnv(),
1680
1901
  detached: process.platform !== "win32"
1681
1902
  });
1682
1903
  } catch (err2) {
1683
- const durationMs = performance.now() - startTime;
1684
- return {
1685
- success: false,
1686
- exitCode: -1,
1687
- stdout: "",
1688
- stderr: String(err2),
1689
- errors: [],
1690
- durationMs,
1691
- timedOut: false
1692
- };
1904
+ return failure(String(err2));
1693
1905
  }
1694
- const collectOutput = (async () => {
1695
- const stdoutStream = proc.stdout;
1696
- const stderrStream = proc.stderr;
1697
- const [stdout, stderr] = await Promise.all([
1698
- new Response(stdoutStream).text(),
1699
- new Response(stderrStream).text()
1700
- ]);
1701
- return { stdout, stderr, exitCode: await proc.exited };
1702
- })();
1703
- collectOutput.catch(() => {});
1906
+ const collectOutput = new Promise((resolvePromise) => {
1907
+ let stdout = "";
1908
+ let stderr = "";
1909
+ proc.stdout.setEncoding("utf-8").on("data", (chunk) => stdout += chunk);
1910
+ proc.stderr.setEncoding("utf-8").on("data", (chunk) => stderr += chunk);
1911
+ proc.on("error", (err2) => resolvePromise({ stdout: "", stderr: String(err2), exitCode: -1 }));
1912
+ proc.on("close", (code) => resolvePromise({ stdout, stderr, exitCode: code ?? -1 }));
1913
+ });
1704
1914
  let timeoutId;
1705
- const timeout = new Promise((resolve5) => {
1706
- timeoutId = setTimeout(() => resolve5("timeout"), timeoutMs);
1915
+ const timeout = new Promise((resolvePromise) => {
1916
+ timeoutId = setTimeout(() => resolvePromise("timeout"), timeoutMs);
1707
1917
  });
1708
1918
  try {
1709
1919
  const outcome = await Promise.race([collectOutput, timeout]);
@@ -1711,8 +1921,7 @@ async function runCompileCheck(options) {
1711
1921
  timedOut = true;
1712
1922
  try {
1713
1923
  if (process.platform === "win32") {
1714
- const taskkill = Bun.spawn(["taskkill", "/PID", String(proc.pid), "/T", "/F"], { stdout: "ignore", stderr: "ignore" });
1715
- await taskkill.exited;
1924
+ spawn("taskkill", ["/PID", String(proc.pid), "/T", "/F"], { stdio: "ignore" }).on("error", () => proc.kill("SIGKILL"));
1716
1925
  } else {
1717
1926
  process.kill(-proc.pid, "SIGKILL");
1718
1927
  }
@@ -1721,7 +1930,6 @@ async function runCompileCheck(options) {
1721
1930
  proc.kill("SIGKILL");
1722
1931
  } catch {}
1723
1932
  }
1724
- await proc.exited;
1725
1933
  return {
1726
1934
  success: false,
1727
1935
  exitCode: proc.exitCode ?? -1,
@@ -1742,26 +1950,21 @@ async function runCompileCheck(options) {
1742
1950
  timedOut
1743
1951
  };
1744
1952
  } catch (err2) {
1745
- return {
1746
- success: false,
1747
- exitCode: -1,
1748
- stdout: "",
1749
- stderr: String(err2),
1750
- errors: [],
1751
- durationMs: performance.now() - startTime,
1752
- timedOut
1753
- };
1953
+ return { ...failure(String(err2)), timedOut };
1754
1954
  } finally {
1755
1955
  clearTimeout(timeoutId);
1756
1956
  }
1757
1957
  }
1958
+
1758
1959
  // src/core/verification/verification-runner.ts
1759
- import { mkdir as mkdir5, readdir as readdir2, writeFile as writeFile4 } from "node:fs/promises";
1960
+ init_paths();
1961
+ init_episodic_store();
1962
+ import { mkdir as mkdir7, readdir as readdir2, writeFile as writeFile5 } from "node:fs/promises";
1760
1963
 
1761
1964
  // src/core/verification/rdd-receipt.ts
1762
- import { createHash } from "node:crypto";
1763
- import { readdir, readFile as readFile6 } from "node:fs/promises";
1764
- import { join as join2, relative, resolve as resolve5, sep } from "node:path";
1965
+ import { createHash as createHash2, randomBytes } from "node:crypto";
1966
+ import { mkdir as mkdir6, readdir, readFile as readFile7, writeFile as writeFile4 } from "node:fs/promises";
1967
+ import { join as join2, relative, resolve as resolve6, sep } from "node:path";
1765
1968
  var EXCLUDED_DIRECTORIES = new Set([
1766
1969
  ".git",
1767
1970
  ".codeconductor",
@@ -1771,11 +1974,11 @@ var EXCLUDED_DIRECTORIES = new Set([
1771
1974
  "graphify-out"
1772
1975
  ]);
1773
1976
  function sha256(content) {
1774
- return createHash("sha256").update(content).digest("hex");
1977
+ return createHash2("sha256").update(content).digest("hex");
1775
1978
  }
1776
1979
  function canonicalPath(projectRoot, input) {
1777
- const root = resolve5(projectRoot);
1778
- const absolute = resolve5(root, input);
1980
+ const root = resolve6(projectRoot);
1981
+ const absolute = resolve6(root, input);
1779
1982
  if (absolute !== root && !absolute.startsWith(`${root}${sep}`)) {
1780
1983
  throw new Error(`RDD receipt path "${input}" is outside the project root`);
1781
1984
  }
@@ -1793,7 +1996,7 @@ async function fingerprint(projectRoot, paths) {
1793
1996
  }
1794
1997
  const result = [];
1795
1998
  for (const [path, absolute] of [...deduplicated.entries()].sort(([left], [right]) => left.localeCompare(right))) {
1796
- result.push({ path, hash: sha256(await readFile6(absolute)) });
1999
+ result.push({ path, hash: sha256(await readFile7(absolute)) });
1797
2000
  }
1798
2001
  return result;
1799
2002
  }
@@ -1801,6 +2004,23 @@ function manifestHash(paths) {
1801
2004
  return sha256(paths.map((entry) => `${entry.path}\x00${entry.hash}`).join(`
1802
2005
  `));
1803
2006
  }
2007
+ function receiptRegistryDir(projectRoot) {
2008
+ return join2(resolve6(projectRoot), ".codeconductor", "rdd-receipts");
2009
+ }
2010
+ function isWellFormedNonce(nonce) {
2011
+ return typeof nonce === "string" && /^[0-9a-f]{32}$/.test(nonce);
2012
+ }
2013
+ async function isRegisteredReceipt(projectRoot, receipt) {
2014
+ if (!isWellFormedNonce(receipt.nonce))
2015
+ return false;
2016
+ try {
2017
+ const raw = await readFile7(join2(receiptRegistryDir(projectRoot), `${receipt.nonce}.json`), "utf-8");
2018
+ const entry = JSON.parse(raw);
2019
+ return entry.manifestHash === receipt.manifestHash;
2020
+ } catch {
2021
+ return false;
2022
+ }
2023
+ }
1804
2024
  function isRddReceipt(value) {
1805
2025
  if (!value || typeof value !== "object")
1806
2026
  return false;
@@ -1814,20 +2034,29 @@ async function captureReceipt(projectRoot, input) {
1814
2034
  throw new Error("RDD receipts require at least one protected path");
1815
2035
  }
1816
2036
  const paths = await fingerprint(projectRoot, input.paths);
1817
- return {
2037
+ const hashed = manifestHash(paths);
2038
+ const nonce = randomBytes(16).toString("hex");
2039
+ const capturedAt = new Date().toISOString();
2040
+ const receipt = {
1818
2041
  version: 1,
1819
2042
  taskId: input.taskId,
1820
2043
  phase: input.phase,
1821
2044
  paths,
1822
2045
  coverage: input.coverage ?? "paths",
1823
- manifestHash: manifestHash(paths),
2046
+ manifestHash: hashed,
1824
2047
  command: input.command,
1825
2048
  outcome: input.outcome,
1826
- capturedAt: new Date().toISOString()
2049
+ capturedAt,
2050
+ nonce
1827
2051
  };
2052
+ const directory = receiptRegistryDir(projectRoot);
2053
+ await mkdir6(directory, { recursive: true });
2054
+ const entry = { manifestHash: hashed, taskId: input.taskId, capturedAt };
2055
+ await writeFile4(join2(directory, `${nonce}.json`), JSON.stringify(entry, null, 2), "utf-8");
2056
+ return receipt;
1828
2057
  }
1829
2058
  async function collectReceiptPaths(projectRoot) {
1830
- const root = resolve5(projectRoot);
2059
+ const root = resolve6(projectRoot);
1831
2060
  const paths = [];
1832
2061
  async function visit(current) {
1833
2062
  const entries = await readdir(current, { withFileTypes: true });
@@ -1845,6 +2074,7 @@ async function collectReceiptPaths(projectRoot) {
1845
2074
  return paths.sort();
1846
2075
  }
1847
2076
  async function verifyReceipt(projectRoot, receipt) {
2077
+ const registered = await isRegisteredReceipt(projectRoot, receipt);
1848
2078
  const expected = new Map(receipt.paths.map((entry) => [entry.path, entry.hash]));
1849
2079
  const changedPaths = [];
1850
2080
  const current = [];
@@ -1853,7 +2083,7 @@ async function verifyReceipt(projectRoot, receipt) {
1853
2083
  for (const path of pathsToCheck) {
1854
2084
  try {
1855
2085
  const canonical = canonicalPath(projectRoot, path);
1856
- const hash = sha256(await readFile6(canonical.absolute));
2086
+ const hash = sha256(await readFile7(canonical.absolute));
1857
2087
  const currentEntry = { path: canonical.relative, hash };
1858
2088
  current.push(currentEntry);
1859
2089
  currentByPath.set(currentEntry.path, currentEntry);
@@ -1870,7 +2100,7 @@ async function verifyReceipt(projectRoot, receipt) {
1870
2100
  changedPaths.sort();
1871
2101
  const actualHash = manifestHash(current.sort((left, right) => left.path.localeCompare(right.path)));
1872
2102
  return {
1873
- valid: changedPaths.length === 0 && actualHash === receipt.manifestHash,
2103
+ valid: registered && changedPaths.length === 0 && actualHash === receipt.manifestHash,
1874
2104
  expectedHash: receipt.manifestHash,
1875
2105
  actualHash,
1876
2106
  changedPaths
@@ -1903,8 +2133,8 @@ async function isCurrentPassingEvidence(projectRoot, ev) {
1903
2133
  return (await verifyReceipt(projectRoot, receipt)).valid;
1904
2134
  }
1905
2135
  function evidenceFilePath(evDir, id) {
1906
- const path = resolve6(evDir, `${id.replace(/[^A-Za-z0-9_-]/g, "_")}.json`);
1907
- if (dirname(path) !== resolve6(evDir)) {
2136
+ const path = resolve7(evDir, `${id.replace(/[^A-Za-z0-9_-]/g, "_")}.json`);
2137
+ if (dirname(path) !== resolve7(evDir)) {
1908
2138
  return err(new Error(`Refusing to write evidence for "${id}" outside ${evDir}`));
1909
2139
  }
1910
2140
  return ok(path);
@@ -1915,8 +2145,8 @@ async function persistEvidence(projectRoot, evidence) {
1915
2145
  if (!evidencePath.success)
1916
2146
  return evidencePath;
1917
2147
  try {
1918
- await mkdir5(evDir, { recursive: true });
1919
- await writeFile4(evidencePath.data, JSON.stringify(evidence, null, 2), "utf-8");
2148
+ await mkdir7(evDir, { recursive: true });
2149
+ await writeFile5(evidencePath.data, JSON.stringify(evidence, null, 2), "utf-8");
1920
2150
  } catch (e) {
1921
2151
  return err(e instanceof Error ? e : new Error(String(e)));
1922
2152
  }
@@ -1938,7 +2168,7 @@ async function collectTaskEvidence(projectRoot, taskId) {
1938
2168
  if (!file.endsWith(".json"))
1939
2169
  continue;
1940
2170
  try {
1941
- const raw = await readFile7(join3(evDir, file), "utf-8");
2171
+ const raw = await readFile8(join3(evDir, file), "utf-8");
1942
2172
  const ev = EvidenceSchema.parse(JSON.parse(raw));
1943
2173
  if (ev.relatedTask === taskId)
1944
2174
  records.push(ev);
@@ -2138,7 +2368,7 @@ async function captureTddSuiteEvidence(projectRoot, taskId, options) {
2138
2368
  cwd: projectRoot
2139
2369
  });
2140
2370
  const suitePassed = result.success && !result.timedOut && result.exitCode === 0;
2141
- const suiteFailed = !result.timedOut && result.exitCode !== 0;
2371
+ const suiteFailed = !result.timedOut && result.exitCode > 0;
2142
2372
  const receipt = { ...before, outcome: suitePassed ? "passed" : "failed" };
2143
2373
  const receiptResult = await verifyReceipt(projectRoot, receipt);
2144
2374
  if (!receiptResult.valid) {
@@ -2185,14 +2415,14 @@ async function captureTddSuiteEvidence(projectRoot, taskId, options) {
2185
2415
  receipt
2186
2416
  });
2187
2417
  }
2188
- async function loadTddSuiteEvidence(projectRoot, taskId, evidenceId) {
2418
+ async function readRunnerTddEvidence(projectRoot, taskId, evidenceId) {
2189
2419
  const evDir = evidenceDir(projectRoot);
2190
2420
  const path = evidenceFilePath(evDir, evidenceId);
2191
2421
  if (!path.success)
2192
2422
  return path;
2193
2423
  let raw;
2194
2424
  try {
2195
- raw = await readFile7(path.data, "utf-8");
2425
+ raw = await readFile8(path.data, "utf-8");
2196
2426
  } catch (e) {
2197
2427
  return err(e instanceof Error ? e : new Error(String(e)));
2198
2428
  }
@@ -2221,24 +2451,52 @@ async function loadTddSuiteEvidence(projectRoot, taskId, evidenceId) {
2221
2451
  if (receipt.taskId !== taskId) {
2222
2452
  return err(new Error(`Evidence "${evidenceId}" receipt belongs to another task`));
2223
2453
  }
2224
- const verified = await verifyReceipt(projectRoot, receipt);
2454
+ return ok({ capturedBy, suiteFailed, suitePassed, receipt });
2455
+ }
2456
+ async function loadTddSuiteEvidence(projectRoot, taskId, evidenceId) {
2457
+ const read = await readRunnerTddEvidence(projectRoot, taskId, evidenceId);
2458
+ if (!read.success)
2459
+ return read;
2460
+ const verified = await verifyReceipt(projectRoot, read.data.receipt);
2225
2461
  if (!verified.valid) {
2226
2462
  return err(new Error(`Evidence "${evidenceId}" RDD receipt is stale: ${verified.changedPaths.join(", ")}`));
2227
2463
  }
2228
- return ok({ capturedBy, suiteFailed, suitePassed, receipt });
2464
+ return read;
2229
2465
  }
2230
- async function hasTddRunnerEvidence(projectRoot, taskId, expectedPhase) {
2466
+ async function listRunnerTddRecords(projectRoot, taskId) {
2231
2467
  const collected = await collectTaskEvidence(projectRoot, taskId);
2232
2468
  if (!collected.success)
2233
- return false;
2234
- for (const ev of collected.data.records) {
2235
- if (ev.type !== "tdd" || ev.source !== TDD_EVIDENCE_SOURCE || ev.data?.capturedBy !== TDD_CAPTURED_BY) {
2236
- continue;
2469
+ return [];
2470
+ return collected.data.records.filter((ev) => ev.type === "tdd" && ev.source === TDD_EVIDENCE_SOURCE && ev.data?.capturedBy === TDD_CAPTURED_BY);
2471
+ }
2472
+ function tddValidationFilePath(projectRoot, taskId) {
2473
+ return evidenceFilePath(join3(resolve7(projectRoot), ".codeconductor", "tdd-validations"), taskId);
2474
+ }
2475
+ async function loadTddValidation(projectRoot, taskId) {
2476
+ const path = tddValidationFilePath(projectRoot, taskId);
2477
+ if (!path.success)
2478
+ return;
2479
+ try {
2480
+ const record = TddValidationRecordSchema.parse(JSON.parse(await readFile8(path.data, "utf-8")));
2481
+ return record.taskId === taskId ? record : undefined;
2482
+ } catch {
2483
+ return;
2484
+ }
2485
+ }
2486
+ var isRedSuite = (e) => e.suiteFailed && !e.suitePassed;
2487
+ async function hasTddRunnerEvidence(projectRoot, taskId, expectedPhase) {
2488
+ const validation = expectedPhase === "red" ? await loadTddValidation(projectRoot, taskId) : undefined;
2489
+ for (const ev of await listRunnerTddRecords(projectRoot, taskId)) {
2490
+ if (expectedPhase === "red" && validation?.evidenceId === ev.id) {
2491
+ const read = await readRunnerTddEvidence(projectRoot, taskId, ev.id);
2492
+ 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)) {
2493
+ return true;
2494
+ }
2237
2495
  }
2238
2496
  const loaded = await loadTddSuiteEvidence(projectRoot, taskId, ev.id);
2239
2497
  if (!loaded.success)
2240
2498
  continue;
2241
- if (expectedPhase === "red" && (!loaded.data.suiteFailed || loaded.data.suitePassed))
2499
+ if (expectedPhase === "red" && !isRedSuite(loaded.data))
2242
2500
  continue;
2243
2501
  if (expectedPhase === "green" && (!loaded.data.suitePassed || loaded.data.suiteFailed))
2244
2502
  continue;
@@ -2249,22 +2507,23 @@ async function hasTddRunnerEvidence(projectRoot, taskId, expectedPhase) {
2249
2507
 
2250
2508
  // src/core/orchestrator/runtime-orchestrator.ts
2251
2509
  async function rollbackTaskStatus(projectRoot, graph, task, previousStatus, previousState, cause) {
2252
- task.status = previousStatus;
2253
- const write = await writeGoal(projectRoot, graph);
2254
- const restored = write.success ? await saveOperationalState(projectRoot, previousState) : write;
2255
- return restored.success ? err(cause) : err(new Error(`${cause.message} (rollback failed: ${restored.error.message})`));
2510
+ return withQueueLock(projectRoot, async () => {
2511
+ task.status = previousStatus;
2512
+ const write = await writeGoal(projectRoot, graph);
2513
+ const restored = write.success ? await saveOperationalState(projectRoot, previousState) : write;
2514
+ return restored.success ? err(cause) : err(new Error(`${cause.message} (rollback failed: ${restored.error.message})`));
2515
+ });
2256
2516
  }
2257
2517
  function getReadyTasks(graph) {
2518
+ propagateBlockedTasks(graph);
2258
2519
  const done = new Set(graph.tasks.filter((t) => t.status === "done").map((t) => t.id));
2259
- const blocked = new Set(graph.tasks.filter((t) => t.status === "blocked").map((t) => t.id));
2520
+ const order = new Map(graph.tasks.map((task, index) => [task.id, index]));
2260
2521
  return graph.tasks.filter((task) => {
2261
2522
  if (task.status !== "pending")
2262
2523
  return false;
2263
- if (blocked.has(task.id))
2264
- return false;
2265
2524
  const deps = task.depends_on ?? [];
2266
2525
  return deps.every((d) => done.has(d));
2267
- });
2526
+ }).sort((a, b) => (a.priority ?? "P2").localeCompare(b.priority ?? "P2") || order.get(a.id) - order.get(b.id) || a.id.localeCompare(b.id));
2268
2527
  }
2269
2528
  function goalTaskToCanonicalCard(task, objective) {
2270
2529
  return {
@@ -2309,9 +2568,23 @@ function buildTaskEnvelope(card, projectRoot, projectName) {
2309
2568
  };
2310
2569
  }
2311
2570
  async function getNextTask(projectRoot, projectName) {
2571
+ return withQueueLock(projectRoot, () => getNextTaskUnlocked(projectRoot, projectName));
2572
+ }
2573
+ async function startTask(projectRoot, taskId, agent) {
2574
+ return withQueueLock(projectRoot, () => startTaskUnlocked(projectRoot, taskId, agent));
2575
+ }
2576
+ async function completeTask(projectRoot, taskId, evidenceIds) {
2577
+ return withQueueLock(projectRoot, () => completeTaskUnlocked(projectRoot, taskId, evidenceIds));
2578
+ }
2579
+ async function getNextTaskUnlocked(projectRoot, projectName) {
2312
2580
  const goalResult = await loadGoal(projectRoot);
2313
2581
  if (!goalResult.success)
2314
2582
  return goalResult;
2583
+ if (propagateBlockedTasks(goalResult.data)) {
2584
+ const write = await writeGoal(projectRoot, goalResult.data);
2585
+ if (!write.success)
2586
+ return write;
2587
+ }
2315
2588
  const graphResult = await loadGraph(projectRoot);
2316
2589
  const productGraph = graphResult.success ? graphResult.data : undefined;
2317
2590
  const enriched = enrichGoalWithProduct(goalResult.data, productGraph);
@@ -2329,7 +2602,7 @@ async function getNextTask(projectRoot, projectName) {
2329
2602
  readyCount: ready.length
2330
2603
  });
2331
2604
  }
2332
- async function startTask(projectRoot, taskId, agent) {
2605
+ async function startTaskUnlocked(projectRoot, taskId, agent) {
2333
2606
  const goalResult = await loadGoal(projectRoot);
2334
2607
  if (!goalResult.success)
2335
2608
  return goalResult;
@@ -2339,6 +2612,10 @@ async function startTask(projectRoot, taskId, agent) {
2339
2612
  if (task.status !== "pending") {
2340
2613
  return err(new Error(`Task ${taskId} is ${task.status}, expected pending`));
2341
2614
  }
2615
+ const done = new Set(goalResult.data.tasks.filter((t) => t.status === "done").map((t) => t.id));
2616
+ const unmet = (task.depends_on ?? []).filter((id) => !done.has(id));
2617
+ if (unmet.length > 0)
2618
+ return err(new Error(`Task ${taskId} has unmet dependencies: ${unmet.join(", ")}`));
2342
2619
  const stateBefore = await loadOperationalState(projectRoot);
2343
2620
  if (!stateBefore.success)
2344
2621
  return stateBefore;
@@ -2362,7 +2639,7 @@ async function startTask(projectRoot, taskId, agent) {
2362
2639
  }
2363
2640
  return ok(undefined);
2364
2641
  }
2365
- async function completeTask(projectRoot, taskId, evidenceIds) {
2642
+ async function completeTaskUnlocked(projectRoot, taskId, evidenceIds) {
2366
2643
  const goalResult = await loadGoal(projectRoot);
2367
2644
  if (!goalResult.success)
2368
2645
  return goalResult;
@@ -3084,6 +3361,7 @@ export {
3084
3361
  TaskOutcomeSchema,
3085
3362
  TaskOutcomeSourceSchema,
3086
3363
  TaskOutcomeStatusSchema,
3364
+ TddValidationRecordSchema,
3087
3365
  TechnicalPlanOutputSchema,
3088
3366
  TokenUsageSchema,
3089
3367
  ToolProviderNamesSchema,