@kaddo/cli 3.133.0 → 3.135.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 (35) hide show
  1. package/dist/admin-dist/assets/{architectureDiagram-3BPJPVTR-DR1_1O3v.js → architectureDiagram-3BPJPVTR-DkdJ073y.js} +1 -1
  2. package/dist/admin-dist/assets/{chunk-727SXJPM-COmzRt04.js → chunk-727SXJPM-DRof4aGT.js} +1 -1
  3. package/dist/admin-dist/assets/{chunk-AQP2D5EJ-CXMsTGWW.js → chunk-AQP2D5EJ-BOVZoYng.js} +1 -1
  4. package/dist/admin-dist/assets/{classDiagram-v2-Q7XG4LA2-D2dQFgos.js → classDiagram-4FO5ZUOK-cL_umCGu.js} +1 -1
  5. package/dist/admin-dist/assets/{classDiagram-4FO5ZUOK-D2dQFgos.js → classDiagram-v2-Q7XG4LA2-cL_umCGu.js} +1 -1
  6. package/dist/admin-dist/assets/{dagre-BM42HDAG-BMRsOxw1.js → dagre-BM42HDAG-Cvga2Wk-.js} +1 -1
  7. package/dist/admin-dist/assets/{diagram-2AECGRRQ-CRXNCxDY.js → diagram-2AECGRRQ-C4H51In7.js} +1 -1
  8. package/dist/admin-dist/assets/{diagram-5GNKFQAL-C9bO8FnC.js → diagram-5GNKFQAL-BW2-XCqV.js} +1 -1
  9. package/dist/admin-dist/assets/{diagram-LMA3HP47-ye8rGB9h.js → diagram-LMA3HP47-CQnSrSZs.js} +1 -1
  10. package/dist/admin-dist/assets/{diagram-OG6HWLK6-BL0joNkk.js → diagram-OG6HWLK6-BA6tBaOl.js} +1 -1
  11. package/dist/admin-dist/assets/{erDiagram-TEJ5UH35-lqVTGIq-.js → erDiagram-TEJ5UH35-DQK3b1Yu.js} +1 -1
  12. package/dist/admin-dist/assets/{flowDiagram-I6XJVG4X-DA2CLejf.js → flowDiagram-I6XJVG4X-BvtbwW59.js} +1 -1
  13. package/dist/admin-dist/assets/{ganttDiagram-6RSMTGT7-Dkr4jLLp.js → ganttDiagram-6RSMTGT7-Vb0T68-1.js} +1 -1
  14. package/dist/admin-dist/assets/index-F0fBD3Ys.js +96 -0
  15. package/dist/admin-dist/assets/{infoDiagram-5YYISTIA-PZDUmGz-.js → infoDiagram-5YYISTIA-8oD9uPZj.js} +1 -1
  16. package/dist/admin-dist/assets/{ishikawaDiagram-YF4QCWOH-BByxhIgY.js → ishikawaDiagram-YF4QCWOH-C32f84vy.js} +1 -1
  17. package/dist/admin-dist/assets/{kanban-definition-UN3LZRKU-BSTqfNBc.js → kanban-definition-UN3LZRKU-cJc_snn8.js} +1 -1
  18. package/dist/admin-dist/assets/{linear-DJE08IfY.js → linear-XcP0Xi-K.js} +1 -1
  19. package/dist/admin-dist/assets/{mindmap-definition-RKZ34NQL-CmiCyDY8.js → mindmap-definition-RKZ34NQL-jhlLOmXd.js} +1 -1
  20. package/dist/admin-dist/assets/{pieDiagram-4H26LBE5-BlMxq332.js → pieDiagram-4H26LBE5-cEiC5w8m.js} +1 -1
  21. package/dist/admin-dist/assets/{quadrantDiagram-W4KKPZXB-Cy0zZxaY.js → quadrantDiagram-W4KKPZXB-xjpfY5PD.js} +1 -1
  22. package/dist/admin-dist/assets/{requirementDiagram-4Y6WPE33-CAfQqVXA.js → requirementDiagram-4Y6WPE33-C5KtzYhy.js} +1 -1
  23. package/dist/admin-dist/assets/{sequenceDiagram-3UESZ5HK-CZYFDyTc.js → sequenceDiagram-3UESZ5HK-ByGOoS_6.js} +1 -1
  24. package/dist/admin-dist/assets/{stateDiagram-AJRCARHV-BTWDzbes.js → stateDiagram-AJRCARHV-d9g3cuV4.js} +1 -1
  25. package/dist/admin-dist/assets/{stateDiagram-v2-BHNVJYJU-BcExDjN4.js → stateDiagram-v2-BHNVJYJU-DJ9FtIdZ.js} +1 -1
  26. package/dist/admin-dist/assets/{timeline-definition-PNZ67QCA-Db_z8PtC.js → timeline-definition-PNZ67QCA-BB4Lz6CJ.js} +1 -1
  27. package/dist/admin-dist/assets/{vennDiagram-CIIHVFJN-Dkj99o7j.js → vennDiagram-CIIHVFJN-yj1GFfPu.js} +1 -1
  28. package/dist/admin-dist/assets/{wardleyDiagram-YWT4CUSO-DG8V20tb.js → wardleyDiagram-YWT4CUSO-5nw4MWMx.js} +1 -1
  29. package/dist/admin-dist/assets/{xychartDiagram-2RQKCTM6-B6EVudFe.js → xychartDiagram-2RQKCTM6-C0iogx2l.js} +1 -1
  30. package/dist/admin-dist/index.html +1 -1
  31. package/dist/admin-server/index.js +269 -6
  32. package/dist/core.js +822 -178
  33. package/dist/index.js +1235 -243
  34. package/package.json +1 -1
  35. package/dist/admin-dist/assets/index-CZPZGMX7.js +0 -96
package/dist/core.js CHANGED
@@ -141,8 +141,8 @@ function loadConfig(dir) {
141
141
  const parsed = configSchema.safeParse(raw ?? {});
142
142
  if (!parsed.success) {
143
143
  const issues = parsed.error.issues.map((i) => {
144
- const path8 = i.path.join(".");
145
- return path8 ? ` - ${path8}: ${i.message}` : ` - ${i.message}`;
144
+ const path10 = i.path.join(".");
145
+ return path10 ? ` - ${path10}: ${i.message}` : ` - ${i.message}`;
146
146
  }).join("\n");
147
147
  throw new ConfigError(`Invalid .kaddo/config.yml:
148
148
  ${issues}`);
@@ -409,11 +409,11 @@ function moduleArtifactCoverage(dir, id) {
409
409
  };
410
410
  }
411
411
  function loadMappedModules(dir) {
412
- const path8 = join(dir, DESCRIPTOR_PATH);
413
- if (!exists(path8)) return [];
412
+ const path10 = join(dir, DESCRIPTOR_PATH);
413
+ if (!exists(path10)) return [];
414
414
  let parsed;
415
415
  try {
416
- parsed = parseYaml3(readFile(path8));
416
+ parsed = parseYaml3(readFile(path10));
417
417
  } catch {
418
418
  return [];
419
419
  }
@@ -1644,7 +1644,7 @@ function sectionParagraph(md, title) {
1644
1644
  }
1645
1645
  return "";
1646
1646
  }
1647
- function parseCapsule(id, path8, md) {
1647
+ function parseCapsule(id, path10, md) {
1648
1648
  const { data } = matter2(md);
1649
1649
  const updatedAt = data.updated_at ? String(data.updated_at) : void 0;
1650
1650
  let ageDays = null;
@@ -1654,7 +1654,7 @@ function parseCapsule(id, path8, md) {
1654
1654
  }
1655
1655
  return {
1656
1656
  id,
1657
- path: path8,
1657
+ path: path10,
1658
1658
  system: data.system ? String(data.system) : id,
1659
1659
  owner: data.owner ? String(data.owner) : void 0,
1660
1660
  updatedAt,
@@ -1897,6 +1897,18 @@ var DELIVERY_PLANS_DIR = "knowledge/delivery/plans";
1897
1897
  var EPICS_DIR = "knowledge/delivery/epics";
1898
1898
  var PLAN_STATES = ["draft", "in-progress", "completed", "cancelled"];
1899
1899
  var EPIC_STATES = ["planned", "in-progress", "completed", "cancelled"];
1900
+ var PLAN_TRANSITIONS = {
1901
+ draft: ["in-progress", "cancelled"],
1902
+ "in-progress": ["completed", "cancelled"],
1903
+ completed: [],
1904
+ cancelled: []
1905
+ };
1906
+ var EPIC_TRANSITIONS = {
1907
+ planned: ["in-progress", "cancelled"],
1908
+ "in-progress": ["completed", "cancelled"],
1909
+ completed: [],
1910
+ cancelled: []
1911
+ };
1900
1912
  function toPosix3(p) {
1901
1913
  return p.replace(/\\/g, "/");
1902
1914
  }
@@ -2326,40 +2338,40 @@ function purposeFromBody(body) {
2326
2338
  }
2327
2339
  function toDetail(filePath, relPath, raw) {
2328
2340
  const parsed = matter5(raw);
2329
- const fm = parsed.data ?? {};
2341
+ const fm2 = parsed.data ?? {};
2330
2342
  const body = parsed.content.trim();
2331
- const id = str(fm.id) ?? "";
2343
+ const id = str(fm2.id) ?? "";
2332
2344
  return {
2333
2345
  id,
2334
- title: str(fm.title) ?? id,
2335
- resourceType: str(fm.resource_type),
2336
- provider: str(fm.provider),
2337
- environments: strArray(fm.environments),
2338
- scope: parseScope(fm.scope),
2339
- modules: strArray(fm.modules),
2346
+ title: str(fm2.title) ?? id,
2347
+ resourceType: str(fm2.resource_type),
2348
+ provider: str(fm2.provider),
2349
+ environments: strArray(fm2.environments),
2350
+ scope: parseScope(fm2.scope),
2351
+ modules: strArray(fm2.modules),
2340
2352
  path: relPath,
2341
- purpose: str(fm.purpose) ?? purposeFromBody(body),
2342
- interfaces: parseInterfaces(fm.access_interfaces),
2343
- boundaries: parseBoundaries(fm.access_boundaries),
2353
+ purpose: str(fm2.purpose) ?? purposeFromBody(body),
2354
+ interfaces: parseInterfaces(fm2.access_interfaces),
2355
+ boundaries: parseBoundaries(fm2.access_boundaries),
2344
2356
  ...(() => {
2345
- const a = parseAuth(fm.authentication);
2357
+ const a = parseAuth(fm2.authentication);
2346
2358
  return { authRefs: a.refs, authMode: a.mode };
2347
2359
  })(),
2348
- connectionProfiles: parseConnectionProfiles(fm.connection_profiles),
2360
+ connectionProfiles: parseConnectionProfiles(fm2.connection_profiles),
2349
2361
  markdownBody: body
2350
2362
  };
2351
2363
  }
2352
2364
  function getResources(dir) {
2353
2365
  return discoverKnowledge(dir).filter((a) => a.type === RESOURCE_ARTIFACT_TYPE).map((a) => {
2354
- const fm = a.rawFrontmatter;
2366
+ const fm2 = a.rawFrontmatter;
2355
2367
  return {
2356
- id: a.id || str(fm.id) || a.title,
2357
- title: a.title || str(fm.title) || a.id,
2358
- resourceType: str(fm.resource_type),
2359
- provider: str(fm.provider),
2360
- environments: strArray(fm.environments),
2361
- scope: parseScope(fm.scope),
2362
- modules: strArray(fm.modules),
2368
+ id: a.id || str(fm2.id) || a.title,
2369
+ title: a.title || str(fm2.title) || a.id,
2370
+ resourceType: str(fm2.resource_type),
2371
+ provider: str(fm2.provider),
2372
+ environments: strArray(fm2.environments),
2373
+ scope: parseScope(fm2.scope),
2374
+ modules: strArray(fm2.modules),
2363
2375
  path: a.relPath
2364
2376
  };
2365
2377
  }).sort((x, y) => x.id.localeCompare(y.id));
@@ -2372,8 +2384,8 @@ function getResource(dir, id) {
2372
2384
  const raw = readFile(match.filePath);
2373
2385
  return toDetail(match.filePath, match.relPath, raw);
2374
2386
  }
2375
- function parseWorkItemResources(fm) {
2376
- const v = fm.resources;
2387
+ function parseWorkItemResources(fm2) {
2388
+ const v = fm2.resources;
2377
2389
  if (!Array.isArray(v)) return [];
2378
2390
  const out = [];
2379
2391
  for (const raw of v) {
@@ -2451,8 +2463,8 @@ var SOFT_DEPRECATION_STRATEGIES = [
2451
2463
  function str2(v) {
2452
2464
  return typeof v === "string" && v.trim() ? v.trim() : null;
2453
2465
  }
2454
- function parseWorkItemDeprecationTargets(fm) {
2455
- const v = fm.deprecation_targets;
2466
+ function parseWorkItemDeprecationTargets(fm2) {
2467
+ const v = fm2.deprecation_targets;
2456
2468
  if (!Array.isArray(v)) return [];
2457
2469
  const out = [];
2458
2470
  for (const raw of v) {
@@ -2590,13 +2602,13 @@ function purposeFromBody2(body) {
2590
2602
  }
2591
2603
  function getDeprecationPlans(dir) {
2592
2604
  return discoverKnowledge(dir).filter((a) => a.type === DEPRECATION_ARTIFACT_TYPE).map((a) => {
2593
- const fm = a.rawFrontmatter;
2594
- const targets = parseTargets(fm.targets);
2605
+ const fm2 = a.rawFrontmatter;
2606
+ const targets = parseTargets(fm2.targets);
2595
2607
  return {
2596
- id: a.id || str2(fm.id) || a.title,
2597
- title: a.title || str2(fm.title) || a.id,
2608
+ id: a.id || str2(fm2.id) || a.title,
2609
+ title: a.title || str2(fm2.title) || a.id,
2598
2610
  path: a.relPath,
2599
- status: str2(fm.status),
2611
+ status: str2(fm2.status),
2600
2612
  targetCount: targets.length,
2601
2613
  lifecycleCounts: lifecycleCountsOf(targets)
2602
2614
  };
@@ -2609,17 +2621,17 @@ function getDeprecationPlan(dir, id) {
2609
2621
  if (!match) return null;
2610
2622
  const raw = readFile(match.filePath);
2611
2623
  const parsed = matter6(raw);
2612
- const fm = parsed.data ?? {};
2624
+ const fm2 = parsed.data ?? {};
2613
2625
  const body = parsed.content.trim();
2614
- const targets = parseTargets(fm.targets);
2626
+ const targets = parseTargets(fm2.targets);
2615
2627
  return {
2616
- id: str2(fm.id) ?? match.id,
2617
- title: str2(fm.title) ?? match.title,
2628
+ id: str2(fm2.id) ?? match.id,
2629
+ title: str2(fm2.title) ?? match.title,
2618
2630
  path: match.relPath,
2619
- status: str2(fm.status),
2631
+ status: str2(fm2.status),
2620
2632
  targetCount: targets.length,
2621
2633
  lifecycleCounts: lifecycleCountsOf(targets),
2622
- purpose: str2(fm.purpose) ?? purposeFromBody2(body),
2634
+ purpose: str2(fm2.purpose) ?? purposeFromBody2(body),
2623
2635
  targets,
2624
2636
  markdownBody: body
2625
2637
  };
@@ -2726,9 +2738,9 @@ function buildGraph(dir, config, opts = {}, now = /* @__PURE__ */ new Date()) {
2726
2738
  ];
2727
2739
  const presentLayers = [];
2728
2740
  for (const layer of layerDocs) {
2729
- const path8 = layer.files.map((f) => `${KNOWLEDGE2}/${f}`).find((rel) => exists(join(dir, rel)));
2730
- if (path8) {
2731
- addNode({ id: layer.id, type: layer.type, label: layer.label, path: path8 });
2741
+ const path10 = layer.files.map((f) => `${KNOWLEDGE2}/${f}`).find((rel) => exists(join(dir, rel)));
2742
+ if (path10) {
2743
+ addNode({ id: layer.id, type: layer.type, label: layer.label, path: path10 });
2732
2744
  presentLayers.push(layer.id);
2733
2745
  }
2734
2746
  }
@@ -4156,13 +4168,13 @@ function meaningful(text2) {
4156
4168
  });
4157
4169
  }
4158
4170
  function readPocSummary(dir) {
4159
- const path8 = join(dir, POC_ARTIFACT_PATH);
4160
- if (!exists(path8)) {
4171
+ const path10 = join(dir, POC_ARTIFACT_PATH);
4172
+ if (!exists(path10)) {
4161
4173
  return { exists: false, hypothesisDefined: false, successCriteriaCount: 0, constraintsDefined: false, nonGoalsDefined: false, conclusion: "pending" };
4162
4174
  }
4163
4175
  let markdown = "";
4164
4176
  try {
4165
- markdown = readFile(path8);
4177
+ markdown = readFile(path10);
4166
4178
  } catch {
4167
4179
  return { exists: false, hypothesisDefined: false, successCriteriaCount: 0, constraintsDefined: false, nonGoalsDefined: false, conclusion: "pending" };
4168
4180
  }
@@ -4197,11 +4209,11 @@ function redactSecrets(value) {
4197
4209
  return line.replace(/([:=]\s*)\S+.*/, "$1[redacted]");
4198
4210
  }).join("\n");
4199
4211
  }
4200
- function source(dir, path8, kind) {
4201
- const absolute = join(dir, path8);
4212
+ function source(dir, path10, kind) {
4213
+ const absolute = join(dir, path10);
4202
4214
  if (!exists(absolute)) return null;
4203
4215
  const raw = readFile(absolute);
4204
- return { path: posix(path8), kind, digest: sha(raw), content: redactSecrets(raw) };
4216
+ return { path: posix(path10), kind, digest: sha(raw), content: redactSecrets(raw) };
4205
4217
  }
4206
4218
  function reportFiles(dir) {
4207
4219
  const delivery = join(dir, "knowledge", "delivery");
@@ -4241,9 +4253,9 @@ function buildPocReportContext(dir) {
4241
4253
  };
4242
4254
  }
4243
4255
  const sources = [];
4244
- const add = (path8, kind) => {
4245
- if (sources.some((item2) => item2.path === posix(path8))) return;
4246
- const item = source(dir, path8, kind);
4256
+ const add = (path10, kind) => {
4257
+ if (sources.some((item2) => item2.path === posix(path10))) return;
4258
+ const item = source(dir, path10, kind);
4247
4259
  if (item) sources.push(item);
4248
4260
  };
4249
4261
  add(POC_ARTIFACT_PATH, "poc");
@@ -4271,7 +4283,7 @@ function buildPocReportContext(dir) {
4271
4283
  const sourceFingerprint = sha(sources.map((item) => `${item.path}\0${item.digest}`).join("\n"));
4272
4284
  const status = !latestReport ? "missing" : latestReport.sourceFingerprint === sourceFingerprint ? "current" : "stale";
4273
4285
  const currentManifest = Object.fromEntries(sources.map((item) => [item.path, item.digest]));
4274
- const changesSinceLatest = status === "stale" ? [.../* @__PURE__ */ new Set([...Object.keys(currentManifest), ...Object.keys(latestReport?.sourceManifest ?? {})])].filter((path8) => currentManifest[path8] !== latestReport?.sourceManifest[path8]).sort() : [];
4286
+ const changesSinceLatest = status === "stale" ? [.../* @__PURE__ */ new Set([...Object.keys(currentManifest), ...Object.keys(latestReport?.sourceManifest ?? {})])].filter((path10) => currentManifest[path10] !== latestReport?.sourceManifest[path10]).sort() : [];
4275
4287
  const sourceList = sources.map((item) => `- ${item.path} (${item.kind})`).join("\n") || "- No sources selected.";
4276
4288
  return {
4277
4289
  eligible: true,
@@ -4447,10 +4459,10 @@ function resolveNextStep(dir, now = /* @__PURE__ */ new Date()) {
4447
4459
  const q = (rel) => analyzeKnowledgeArtifact(dir, rel);
4448
4460
  const resolveAgent = (agent) => {
4449
4461
  const file = agent.endsWith(".md") ? agent : `${agent}.md`;
4450
- const path8 = agentInstallPath(file);
4451
- const installed = isFile(join(dir, path8));
4462
+ const path10 = agentInstallPath(file);
4463
+ const installed = isFile(join(dir, path10));
4452
4464
  const group = agentGroupOf(file);
4453
- return { agentPath: path8, agentInstalled: installed, installCommand: installed ? void 0 : `kaddo add agents --group ${group}` };
4465
+ return { agentPath: path10, agentInstalled: installed, installCommand: installed ? void 0 : `kaddo add agents --group ${group}` };
4454
4466
  };
4455
4467
  const moduleRepo = isModule(config);
4456
4468
  const coreRepo = isCore(config);
@@ -8202,7 +8214,7 @@ var AGENT_PROMPTS = [
8202
8214
  // src/modules/agents.ts
8203
8215
  function withAgentFrontMatter(fileName, content) {
8204
8216
  const name = fileName.replace(/\.md$/, "");
8205
- const fm = [
8217
+ const fm2 = [
8206
8218
  "---",
8207
8219
  "type: agent",
8208
8220
  `name: ${name}`,
@@ -8211,7 +8223,7 @@ function withAgentFrontMatter(fileName, content) {
8211
8223
  "---",
8212
8224
  ""
8213
8225
  ].join("\n");
8214
- return fm + content.replace(/^\s+/, "");
8226
+ return fm2 + content.replace(/^\s+/, "");
8215
8227
  }
8216
8228
  var agentReadme = {
8217
8229
  path: "knowledge/agents/README.md",
@@ -9158,8 +9170,8 @@ function analyzeMetadataHealth(dir) {
9158
9170
  if (isFile(p) && entry.endsWith(".md")) {
9159
9171
  try {
9160
9172
  const raw = readFile(p);
9161
- const fm = matter10(raw).data;
9162
- if (fm.status === "done") {
9173
+ const fm2 = matter10(raw).data;
9174
+ if (fm2.status === "done") {
9163
9175
  const rel = p.replace(dir + "/", "").replace(dir + "\\", "").replace(/\\/g, "/");
9164
9176
  findings.push({
9165
9177
  file: rel,
@@ -9492,8 +9504,8 @@ function buildProjectExplanation(dir) {
9492
9504
  };
9493
9505
  }),
9494
9506
  implementationEvidence: workItemArtifacts.filter((a) => a.affectedModules.length > 0).map((a) => {
9495
- const fm = a.rawFrontmatter;
9496
- const evidence = fm.implementation_evidence;
9507
+ const fm2 = a.rawFrontmatter;
9508
+ const evidence = fm2.implementation_evidence;
9497
9509
  const repos = evidence?.repositories ?? {};
9498
9510
  const repoEvidence = {};
9499
9511
  for (const [repoId, data] of Object.entries(repos)) {
@@ -9511,8 +9523,8 @@ function buildProjectExplanation(dir) {
9511
9523
  validationStatus: a.validationStatus || historicalDefault,
9512
9524
  releaseStatus: a.releaseStatus || "not-assessed",
9513
9525
  affectedModules: a.affectedModules,
9514
- releaseGates: Array.isArray(fm.release_gates) ? fm.release_gates : [],
9515
- completionExceptions: Array.isArray(fm.completion_exceptions) ? fm.completion_exceptions : [],
9526
+ releaseGates: Array.isArray(fm2.release_gates) ? fm2.release_gates : [],
9527
+ completionExceptions: Array.isArray(fm2.completion_exceptions) ? fm2.completion_exceptions : [],
9516
9528
  repoEvidence
9517
9529
  };
9518
9530
  })
@@ -9627,7 +9639,7 @@ function buildGuardHistory(dir) {
9627
9639
  const d = hotspotDir(t.code_path);
9628
9640
  hotspotMap.set(d, (hotspotMap.get(d) ?? 0) + 1);
9629
9641
  }
9630
- const hotspots = [...hotspotMap.entries()].map(([path8, warnings]) => ({ path: path8, warnings })).sort((a, b) => b.warnings - a.warnings);
9642
+ const hotspots = [...hotspotMap.entries()].map(([path10, warnings]) => ({ path: path10, warnings })).sort((a, b) => b.warnings - a.warnings);
9631
9643
  return {
9632
9644
  available: true,
9633
9645
  total_runs: sorted.length,
@@ -11118,6 +11130,254 @@ function materializeRoadmapInitiative(dir, rmId) {
11118
11130
  });
11119
11131
  }
11120
11132
 
11133
+ // src/core/delivery-verification.ts
11134
+ function normalizeCriterion(text2) {
11135
+ return text2.trim().toLowerCase().replace(/\s+/g, " ");
11136
+ }
11137
+ var STATUSES = ["passed", "failed", "not-verified", "manual-review-required"];
11138
+ function optStr4(v) {
11139
+ if (typeof v === "string" && v.trim()) return v.trim();
11140
+ if (typeof v === "number") return String(v);
11141
+ return void 0;
11142
+ }
11143
+ function parseEvidenceList(raw) {
11144
+ if (!Array.isArray(raw)) return [];
11145
+ const out = [];
11146
+ for (const entry of raw) {
11147
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
11148
+ const o = entry;
11149
+ const criterion = optStr4(o.criterion);
11150
+ if (!criterion) continue;
11151
+ const statusRaw = optStr4(o.status);
11152
+ const status = STATUSES.includes(statusRaw ?? "") ? statusRaw : "not-verified";
11153
+ const method = optStr4(o.method);
11154
+ out.push({
11155
+ criterion,
11156
+ status,
11157
+ ...optStr4(o.evidence) ? { evidence: optStr4(o.evidence) } : {},
11158
+ ...optStr4(o.reference) ? { reference: optStr4(o.reference) } : {},
11159
+ ...method === "automated" || method === "manual" ? { method } : {},
11160
+ ...optStr4(o.verified_at) ? { verified_at: optStr4(o.verified_at) } : {},
11161
+ ...optStr4(o.verified_by) ? { verified_by: optStr4(o.verified_by) } : {}
11162
+ });
11163
+ }
11164
+ return out;
11165
+ }
11166
+ function parseExceptions(raw) {
11167
+ if (!Array.isArray(raw)) return [];
11168
+ const out = [];
11169
+ for (const entry of raw) {
11170
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
11171
+ const o = entry;
11172
+ const id = optStr4(o.id);
11173
+ if (!id) continue;
11174
+ const st = optStr4(o.status);
11175
+ const status = st === "accepted" || st === "rejected" ? st : "proposed";
11176
+ out.push({
11177
+ id,
11178
+ status,
11179
+ ...optStr4(o.criterion) ? { criterion: optStr4(o.criterion) } : {},
11180
+ ...optStr4(o.reason) ? { reason: optStr4(o.reason) } : {}
11181
+ });
11182
+ }
11183
+ return out;
11184
+ }
11185
+ function buildOutcomeVerification(declared, evidence, exceptions = []) {
11186
+ const byCriterion = /* @__PURE__ */ new Map();
11187
+ for (const e of evidence) byCriterion.set(normalizeCriterion(e.criterion), e);
11188
+ const declaredKeys = new Set(declared.map(normalizeCriterion));
11189
+ const counts = /* @__PURE__ */ new Map();
11190
+ for (const c of declared) counts.set(normalizeCriterion(c), (counts.get(normalizeCriterion(c)) ?? 0) + 1);
11191
+ const ambiguousKeys = new Set([...counts.entries()].filter(([, n]) => n > 1).map(([k]) => k));
11192
+ const waived = new Set(
11193
+ exceptions.filter((x) => x.status === "accepted" && x.reason?.trim() && x.criterion && declaredKeys.has(normalizeCriterion(x.criterion)) && !ambiguousKeys.has(normalizeCriterion(x.criterion))).map((x) => normalizeCriterion(x.criterion))
11194
+ );
11195
+ const criteria = declared.map((criterion) => {
11196
+ const key = normalizeCriterion(criterion);
11197
+ const ambiguous = ambiguousKeys.has(key);
11198
+ const e = ambiguous ? void 0 : byCriterion.get(key);
11199
+ return {
11200
+ criterion,
11201
+ status: e?.status ?? "not-verified",
11202
+ ...e?.evidence ? { evidence: e.evidence } : {},
11203
+ ...e?.reference ? { reference: e.reference } : {},
11204
+ ...e?.method ? { method: e.method } : {},
11205
+ ...e?.verified_at ? { verifiedAt: e.verified_at } : {},
11206
+ ...e?.verified_by ? { verifiedBy: e.verified_by } : {},
11207
+ ...!ambiguous && waived.has(key) ? { waived: true } : {},
11208
+ ...ambiguous ? { ambiguous: true } : {}
11209
+ };
11210
+ });
11211
+ const stale = evidence.filter((e) => !declaredKeys.has(normalizeCriterion(e.criterion)));
11212
+ return {
11213
+ total: criteria.length,
11214
+ // An ambiguous criterion is never counted as passed/waived; it counts as unverified until disambiguated.
11215
+ passed: criteria.filter((c) => !c.ambiguous && (c.status === "passed" || c.waived)).length,
11216
+ failed: criteria.filter((c) => !c.ambiguous && c.status === "failed" && !c.waived).length,
11217
+ notVerified: criteria.filter((c) => c.ambiguous || c.status === "not-verified" && !c.waived).length,
11218
+ manualReview: criteria.filter((c) => !c.ambiguous && c.status === "manual-review-required" && !c.waived).length,
11219
+ ambiguous: criteria.filter((c) => c.ambiguous).length,
11220
+ criteria,
11221
+ stale
11222
+ };
11223
+ }
11224
+ function fm(entity, key) {
11225
+ return entity.rawFrontmatter?.[key];
11226
+ }
11227
+ function epicOutcomeVerification(epic) {
11228
+ return buildOutcomeVerification(
11229
+ epic.successCriteria,
11230
+ parseEvidenceList(fm(epic, "outcome_verifications")),
11231
+ parseExceptions(fm(epic, "completion_exceptions"))
11232
+ );
11233
+ }
11234
+ function planOutcomeVerification(plan) {
11235
+ return buildOutcomeVerification(
11236
+ plan.successCriteria,
11237
+ parseEvidenceList(fm(plan, "outcome_verifications")),
11238
+ parseExceptions(fm(plan, "completion_exceptions"))
11239
+ );
11240
+ }
11241
+ function planMilestoneVerifications(plan) {
11242
+ const rawMs = Array.isArray(fm(plan, "milestones")) ? fm(plan, "milestones") : [];
11243
+ return plan.milestones.map((m) => {
11244
+ const rawEntry = rawMs.find((r) => r && typeof r === "object" && optStr4(r.id)?.toLowerCase() === m.id.toLowerCase());
11245
+ const evidence = parseEvidenceList(rawEntry?.exit_verifications);
11246
+ return { id: m.id, title: m.title, outcome: buildOutcomeVerification(m.exitCriteria, evidence) };
11247
+ });
11248
+ }
11249
+ function decide(blockers, softBlocks, hasAcceptedExceptions) {
11250
+ if (blockers.length > 0) return "BLOCKED";
11251
+ if (softBlocks.length > 0) return "NEEDS_WORK";
11252
+ return hasAcceptedExceptions ? "READY_WITH_EXCEPTIONS" : "READY_TO_COMPLETE";
11253
+ }
11254
+ function evaluateEpicCompletion(dir, epic) {
11255
+ const prog = computeEpicProgress(dir, epic);
11256
+ const exceptions = parseExceptions(fm(epic, "completion_exceptions"));
11257
+ const outcome = epicOutcomeVerification(epic);
11258
+ const blockers = [];
11259
+ const softBlocks = [];
11260
+ const reasons = [];
11261
+ const warnings = [];
11262
+ for (const d of prog.readiness.blockingDependencies) blockers.push(`Blocked by unfinished dependency ${d}.`);
11263
+ for (const f of integrityBlockers(dir, epic.id)) blockers.push(f);
11264
+ evaluateOutcomeInto(epic.outcome, true, outcome, blockers, softBlocks, reasons, warnings);
11265
+ if (prog.delivery.total > 0 && prog.delivery.completed < prog.delivery.total) {
11266
+ softBlocks.push("committed-work-incomplete");
11267
+ reasons.push(`Committed work is incomplete (${prog.delivery.completed}/${prog.delivery.total} Work Items completed).`);
11268
+ }
11269
+ const readiness = decide(blockers, softBlocks, exceptions.some((x) => x.status === "accepted"));
11270
+ pushReadinessReason(readiness, reasons);
11271
+ return {
11272
+ id: epic.id,
11273
+ kind: "epic",
11274
+ status: epic.status,
11275
+ readiness,
11276
+ reasons,
11277
+ blockers,
11278
+ warnings,
11279
+ outcome,
11280
+ delivery: { total: prog.delivery.total, completed: prog.delivery.completed, blocked: prog.delivery.blocked },
11281
+ blockingDependencies: prog.readiness.blockingDependencies,
11282
+ exceptions
11283
+ };
11284
+ }
11285
+ function evaluatePlanCompletion(dir, plan) {
11286
+ const prog = computePlanProgress(dir, plan);
11287
+ const exceptions = parseExceptions(fm(plan, "completion_exceptions"));
11288
+ const outcome = planOutcomeVerification(plan);
11289
+ const milestones = planMilestoneVerifications(plan);
11290
+ const epics = epicsInPlan(dir, plan.id).map((e) => ({ id: e.id, status: e.status }));
11291
+ const blockers = [];
11292
+ const softBlocks = [];
11293
+ const reasons = [];
11294
+ const warnings = [];
11295
+ for (const d of prog.readiness.blockingDependencies) blockers.push(`Blocked by unfinished dependency ${d}.`);
11296
+ for (const f of integrityBlockers(dir, plan.id)) blockers.push(f);
11297
+ evaluateOutcomeInto(plan.objective, false, outcome, blockers, softBlocks, reasons, warnings);
11298
+ if (!plan.objective) warnings.push("No objective is declared for this Plan (optional, but recommended for completion review).");
11299
+ if (prog.delivery.total > 0 && prog.delivery.completed < prog.delivery.total) {
11300
+ softBlocks.push("committed-work-incomplete");
11301
+ reasons.push(`Committed work is incomplete (${prog.delivery.completed}/${prog.delivery.total} Work Items completed).`);
11302
+ }
11303
+ if (epics.length === 0 && prog.delivery.total === 0) {
11304
+ softBlocks.push("no-committed-work");
11305
+ reasons.push("No Epics and no committed Work Items \u2014 the Plan has no verifiable deliverables yet.");
11306
+ }
11307
+ const openEpics = epics.filter((e) => e.status !== "completed" && e.status !== "cancelled");
11308
+ if (openEpics.length > 0) {
11309
+ softBlocks.push("epics-open");
11310
+ reasons.push(`${openEpics.length} Epic(s) not yet completed: ${openEpics.map((e) => e.id).join(", ")}.`);
11311
+ }
11312
+ for (const m of milestones) {
11313
+ if (m.outcome.failed > 0) {
11314
+ blockers.push(`Milestone ${m.id} has a failed exit criterion.`);
11315
+ }
11316
+ const pending = m.outcome.notVerified + m.outcome.manualReview;
11317
+ if (pending > 0) {
11318
+ softBlocks.push(`milestone-${m.id}-pending`);
11319
+ reasons.push(`Milestone ${m.id}: ${pending} exit criterion(s) not verified.`);
11320
+ }
11321
+ if (m.outcome.stale.length > 0) warnings.push(`Milestone ${m.id} has stale exit-criteria evidence.`);
11322
+ }
11323
+ const readiness = decide(blockers, softBlocks, exceptions.some((x) => x.status === "accepted"));
11324
+ pushReadinessReason(readiness, reasons);
11325
+ return {
11326
+ id: plan.id,
11327
+ kind: "plan",
11328
+ status: plan.status,
11329
+ readiness,
11330
+ reasons,
11331
+ blockers,
11332
+ warnings,
11333
+ outcome,
11334
+ delivery: { total: prog.delivery.total, completed: prog.delivery.completed, blocked: prog.delivery.blocked },
11335
+ blockingDependencies: prog.readiness.blockingDependencies,
11336
+ milestones,
11337
+ epics,
11338
+ exceptions
11339
+ };
11340
+ }
11341
+ function integrityBlockers(dir, subjectId) {
11342
+ return validatePlanningGraph(dir).filter((f) => f.level === "error" && f.subject.toLowerCase() === subjectId.toLowerCase()).map((f) => f.message);
11343
+ }
11344
+ function evaluateOutcomeInto(declaredOutcome, requireDeclaredOutcome, outcome, blockers, softBlocks, reasons, warnings) {
11345
+ if (requireDeclaredOutcome && !declaredOutcome) {
11346
+ softBlocks.push("no-outcome");
11347
+ reasons.push("No expected outcome is declared.");
11348
+ }
11349
+ if (outcome.total === 0) {
11350
+ softBlocks.push("no-success-criteria");
11351
+ reasons.push("No success criteria to verify \u2014 completion cannot be judged by outcome.");
11352
+ }
11353
+ if (outcome.ambiguous > 0) {
11354
+ softBlocks.push("criteria-ambiguous");
11355
+ reasons.push(`${outcome.ambiguous} success criterion(s) collide in text \u2014 rename to disambiguate before verifying.`);
11356
+ }
11357
+ if (outcome.failed > 0) {
11358
+ softBlocks.push("criteria-failed");
11359
+ reasons.push(`${outcome.failed} success criterion(s) failed verification.`);
11360
+ }
11361
+ const pending = outcome.notVerified + outcome.manualReview - outcome.ambiguous;
11362
+ if (pending > 0) {
11363
+ softBlocks.push("criteria-unverified");
11364
+ reasons.push(`${pending} success criterion(s) not verified (no or insufficient evidence).`);
11365
+ }
11366
+ if (outcome.stale.length > 0) warnings.push(`${outcome.stale.length} evidence record(s) no longer match a declared criterion (stale).`);
11367
+ }
11368
+ function pushReadinessReason(readiness, reasons) {
11369
+ if (readiness === "READY_TO_COMPLETE") reasons.unshift("All success criteria are verified and committed work is complete. Human approval is still required to close.");
11370
+ else if (readiness === "READY_WITH_EXCEPTIONS") reasons.unshift("Remaining gaps are covered by accepted exceptions. Human approval is still required to close.");
11371
+ }
11372
+ function evaluateEpicById(dir, id) {
11373
+ const e = getEpic(dir, id);
11374
+ return e ? evaluateEpicCompletion(dir, e) : null;
11375
+ }
11376
+ function evaluatePlanById(dir, id) {
11377
+ const p = getPlan(dir, id);
11378
+ return p ? evaluatePlanCompletion(dir, p) : null;
11379
+ }
11380
+
11121
11381
  // src/core/delivery-planning-write.ts
11122
11382
  var DeliveryPlanningWriteError = class extends Error {
11123
11383
  constructor(message) {
@@ -11216,7 +11476,14 @@ function disassociateInitiativeFromEpic(dir, initiativeId) {
11216
11476
  if (!ini.epic) return ini;
11217
11477
  return updateInitiative(dir, ini.id, { epic: null });
11218
11478
  }
11219
- function normalizeMilestones(planId, input) {
11479
+ function normalizeMilestones(planId, input, existing) {
11480
+ const byId = /* @__PURE__ */ new Map();
11481
+ for (const e of existing) {
11482
+ if (e && typeof e === "object" && !Array.isArray(e)) {
11483
+ const eid = typeof e.id === "string" ? e.id.trim().toLowerCase() : "";
11484
+ if (eid) byId.set(eid, e);
11485
+ }
11486
+ }
11220
11487
  const seen = /* @__PURE__ */ new Set();
11221
11488
  const data = [];
11222
11489
  const model = [];
@@ -11228,13 +11495,19 @@ function normalizeMilestones(planId, input) {
11228
11495
  seen.add(key);
11229
11496
  const title = m.title?.trim() || id;
11230
11497
  const exit = cleanList(m.exitCriteria ?? []);
11231
- const entry = { id, title };
11498
+ const entry = { ...byId.get(key) ?? {} };
11499
+ entry.id = id;
11500
+ entry.title = title;
11232
11501
  if (exit.length > 0) entry.exit_criteria = exit;
11502
+ else delete entry.exit_criteria;
11233
11503
  data.push(entry);
11234
11504
  model.push({ id, title, exitCriteria: exit });
11235
11505
  }
11236
11506
  return { data, model };
11237
11507
  }
11508
+ function hasExitEvidence(entry) {
11509
+ return !!entry && Array.isArray(entry.exit_verifications) && entry.exit_verifications.length > 0;
11510
+ }
11238
11511
  function updateDeliveryPlan(dir, id, patch, opts) {
11239
11512
  const plan = getPlan(dir, id);
11240
11513
  if (!plan) throw new DeliveryPlanningWriteError(`Plan ${id} does not exist.`);
@@ -11254,7 +11527,8 @@ function updateDeliveryPlan(dir, id, patch, opts) {
11254
11527
  if (patch.dependsOn !== void 0) setListOrDelete(data, "depends_on", patch.dependsOn);
11255
11528
  if (patch.references !== void 0) setListOrDelete(data, "references", patch.references);
11256
11529
  if (patch.milestones !== void 0) {
11257
- const { data: msData, model } = normalizeMilestones(plan.id, patch.milestones);
11530
+ const existingRaw = Array.isArray(data.milestones) ? data.milestones : [];
11531
+ const { data: msData, model } = normalizeMilestones(plan.id, patch.milestones, existingRaw);
11258
11532
  const newIds = new Set(model.map((m) => m.id.toLowerCase()));
11259
11533
  const referencedByEpic = /* @__PURE__ */ new Map();
11260
11534
  for (const e of epicsInPlan(dir, plan.id)) {
@@ -11270,6 +11544,12 @@ function updateDeliveryPlan(dir, id, patch, opts) {
11270
11544
  const detail = [...referencedByEpic.entries()].map(([ms, epics]) => `${ms} (used by ${epics.join(", ")})`).join("; ");
11271
11545
  throw new DeliveryPlanningWriteError(`Cannot remove or rename milestone(s) still referenced by an Epic: ${detail}. Reassign the Epic first.`);
11272
11546
  }
11547
+ if (!opts?.allowMilestoneEvidenceLoss) {
11548
+ const droppedWithEvidence = existingRaw.filter((e) => e && typeof e === "object" && typeof e.id === "string" && !newIds.has(e.id.trim().toLowerCase()) && hasExitEvidence(e)).map((e) => String(e.id));
11549
+ if (droppedWithEvidence.length > 0) {
11550
+ throw new DeliveryPlanningWriteError(`Milestone(s) ${droppedWithEvidence.join(", ")} still carry exit-criteria evidence. Removing them discards that evidence \u2014 pass allowMilestoneEvidenceLoss to confirm.`);
11551
+ }
11552
+ }
11273
11553
  data.milestones = msData;
11274
11554
  }
11275
11555
  const newContent = matter13.stringify(content, data);
@@ -11335,6 +11615,163 @@ function updateEpic(dir, id, patch, opts) {
11335
11615
  if (!updated) throw new DeliveryPlanningWriteError("Failed to parse the Epic after update.");
11336
11616
  return updated;
11337
11617
  }
11618
+ function today2() {
11619
+ return (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
11620
+ }
11621
+ var PlanningNotReadyError = class extends DeliveryPlanningWriteError {
11622
+ constructor(evaluation) {
11623
+ super(`${evaluation.kind === "plan" ? "Plan" : "Epic"} ${evaluation.id} is not ready to complete (${evaluation.readiness}).`);
11624
+ this.evaluation = evaluation;
11625
+ this.name = "PlanningNotReadyError";
11626
+ }
11627
+ evaluation;
11628
+ };
11629
+ function transitionDeliveryPlan(dir, id, to, opts) {
11630
+ const plan = getPlan(dir, id);
11631
+ if (!plan) throw new DeliveryPlanningWriteError(`Plan ${id} does not exist.`);
11632
+ if (!PLAN_STATES.includes(to)) throw new DeliveryPlanningWriteError(`Invalid plan status: ${to}.`);
11633
+ if (to === "completed") throw new DeliveryPlanningWriteError(`Completing Plan ${id} requires evidence-based review \u2014 use completeDeliveryPlan.`);
11634
+ const raw = readFile(plan.filePath);
11635
+ assertFreshRevision(plan.id, raw, opts);
11636
+ if (plan.status === to) return plan;
11637
+ if (!PLAN_TRANSITIONS[plan.status].includes(to)) throw new DeliveryPlanningWriteError(`Invalid transition ${plan.status} \u2192 ${to} for Plan ${id}.`);
11638
+ const { data, content } = matter13(raw, {});
11639
+ data.status = to;
11640
+ if (to === "completed") data.completed_at = today2();
11641
+ const newContent = matter13.stringify(content, data);
11642
+ writeFile(plan.filePath, newContent);
11643
+ const updated = parseDeliveryPlan(dir, plan.filePath, newContent);
11644
+ if (!updated) throw new DeliveryPlanningWriteError("Failed to parse the Plan after transition.");
11645
+ return updated;
11646
+ }
11647
+ function transitionEpic(dir, id, to, opts) {
11648
+ const epic = getEpic(dir, id);
11649
+ if (!epic) throw new DeliveryPlanningWriteError(`Epic ${id} does not exist.`);
11650
+ if (!EPIC_STATES.includes(to)) throw new DeliveryPlanningWriteError(`Invalid epic status: ${to}.`);
11651
+ if (to === "completed") throw new DeliveryPlanningWriteError(`Completing Epic ${id} requires evidence-based review \u2014 use completeEpic.`);
11652
+ const raw = readFile(epic.filePath);
11653
+ assertFreshRevision(epic.id, raw, opts);
11654
+ if (epic.status === to) return epic;
11655
+ if (!EPIC_TRANSITIONS[epic.status].includes(to)) throw new DeliveryPlanningWriteError(`Invalid transition ${epic.status} \u2192 ${to} for Epic ${id}.`);
11656
+ const { data, content } = matter13(raw, {});
11657
+ data.status = to;
11658
+ if (to === "completed") data.completed_at = today2();
11659
+ const newContent = matter13.stringify(content, data);
11660
+ writeFile(epic.filePath, newContent);
11661
+ const updated = parseEpic(dir, epic.filePath, newContent);
11662
+ if (!updated) throw new DeliveryPlanningWriteError("Failed to parse the Epic after transition.");
11663
+ return updated;
11664
+ }
11665
+ function assertCriterionDeclared(declared, criterion, kind) {
11666
+ const key = normalizeCriterion(criterion);
11667
+ const matches = declared.filter((c) => normalizeCriterion(c) === key).length;
11668
+ if (matches === 0) throw new DeliveryPlanningWriteError(`"${criterion}" is not a declared ${kind} criterion.`);
11669
+ if (matches > 1) throw new DeliveryPlanningWriteError(`"${criterion}" matches more than one declared ${kind} criterion \u2014 rename them to disambiguate before recording evidence.`);
11670
+ }
11671
+ function upsertEvidence(existing, input) {
11672
+ const list2 = Array.isArray(existing) ? existing.filter((e) => e && typeof e === "object" && !Array.isArray(e)) : [];
11673
+ const key = normalizeCriterion(input.criterion);
11674
+ const kept = list2.filter((e) => normalizeCriterion(String(e.criterion ?? "")) !== key);
11675
+ const obj = { criterion: input.criterion.trim(), status: input.status };
11676
+ if (input.evidence?.trim()) obj.evidence = input.evidence.trim();
11677
+ if (input.reference?.trim()) obj.reference = input.reference.trim();
11678
+ if (input.method) obj.method = input.method;
11679
+ obj.verified_at = today2();
11680
+ if (input.verifiedBy?.trim()) obj.verified_by = input.verifiedBy.trim();
11681
+ return [...kept, obj];
11682
+ }
11683
+ function recordEpicOutcomeVerification(dir, id, input, opts) {
11684
+ const epic = getEpic(dir, id);
11685
+ if (!epic) throw new DeliveryPlanningWriteError(`Epic ${id} does not exist.`);
11686
+ assertCriterionDeclared(epic.successCriteria, input.criterion, "success");
11687
+ const raw = readFile(epic.filePath);
11688
+ assertFreshRevision(epic.id, raw, opts);
11689
+ const { data, content } = matter13(raw, {});
11690
+ data.outcome_verifications = upsertEvidence(data.outcome_verifications, input);
11691
+ const newContent = matter13.stringify(content, data);
11692
+ writeFile(epic.filePath, newContent);
11693
+ const updated = parseEpic(dir, epic.filePath, newContent);
11694
+ if (!updated) throw new DeliveryPlanningWriteError("Failed to parse the Epic after recording evidence.");
11695
+ return updated;
11696
+ }
11697
+ function recordPlanOutcomeVerification(dir, id, input, opts) {
11698
+ const plan = getPlan(dir, id);
11699
+ if (!plan) throw new DeliveryPlanningWriteError(`Plan ${id} does not exist.`);
11700
+ assertCriterionDeclared(plan.successCriteria, input.criterion, "success");
11701
+ const raw = readFile(plan.filePath);
11702
+ assertFreshRevision(plan.id, raw, opts);
11703
+ const { data, content } = matter13(raw, {});
11704
+ data.outcome_verifications = upsertEvidence(data.outcome_verifications, input);
11705
+ const newContent = matter13.stringify(content, data);
11706
+ writeFile(plan.filePath, newContent);
11707
+ const updated = parseDeliveryPlan(dir, plan.filePath, newContent);
11708
+ if (!updated) throw new DeliveryPlanningWriteError("Failed to parse the Plan after recording evidence.");
11709
+ return updated;
11710
+ }
11711
+ function recordMilestoneExitVerification(dir, planId, milestoneId, input, opts) {
11712
+ const plan = getPlan(dir, planId);
11713
+ if (!plan) throw new DeliveryPlanningWriteError(`Plan ${planId} does not exist.`);
11714
+ const milestone = plan.milestones.find((m) => m.id.toLowerCase() === milestoneId.toLowerCase());
11715
+ if (!milestone) throw new DeliveryPlanningWriteError(`Milestone ${milestoneId} is not defined in ${planId}.`);
11716
+ assertCriterionDeclared(milestone.exitCriteria, input.criterion, "exit");
11717
+ const raw = readFile(plan.filePath);
11718
+ assertFreshRevision(plan.id, raw, opts);
11719
+ const { data, content } = matter13(raw, {});
11720
+ const rawMs = Array.isArray(data.milestones) ? data.milestones : [];
11721
+ const entry = rawMs.find((m) => m && typeof m === "object" && String(m.id ?? "").toLowerCase() === milestoneId.toLowerCase());
11722
+ if (!entry) throw new DeliveryPlanningWriteError(`Milestone ${milestoneId} entry not found in ${planId} frontmatter.`);
11723
+ entry.exit_verifications = upsertEvidence(entry.exit_verifications, input);
11724
+ data.milestones = rawMs;
11725
+ const newContent = matter13.stringify(content, data);
11726
+ writeFile(plan.filePath, newContent);
11727
+ const updated = parseDeliveryPlan(dir, plan.filePath, newContent);
11728
+ if (!updated) throw new DeliveryPlanningWriteError("Failed to parse the Plan after recording milestone evidence.");
11729
+ return updated;
11730
+ }
11731
+ function completionDecisionRecord(evaluation, input) {
11732
+ const rec = { readiness: evaluation.readiness, decided_at: today2(), reasons: evaluation.reasons };
11733
+ if (input.decidedBy?.trim()) rec.decided_by = input.decidedBy.trim();
11734
+ if (input.note?.trim()) rec.note = input.note.trim();
11735
+ const acceptedExceptions = evaluation.exceptions.filter((x) => x.status === "accepted");
11736
+ if (acceptedExceptions.length > 0) rec.exceptions = acceptedExceptions;
11737
+ return rec;
11738
+ }
11739
+ function completeEpic(dir, id, input = {}, opts) {
11740
+ const epic = getEpic(dir, id);
11741
+ if (!epic) throw new DeliveryPlanningWriteError(`Epic ${id} does not exist.`);
11742
+ const evaluation = evaluateEpicCompletion(dir, epic);
11743
+ if (evaluation.readiness !== "READY_TO_COMPLETE" && evaluation.readiness !== "READY_WITH_EXCEPTIONS") throw new PlanningNotReadyError(evaluation);
11744
+ if (!EPIC_TRANSITIONS[epic.status].includes("completed")) throw new DeliveryPlanningWriteError(`Epic ${id} cannot move from ${epic.status} to completed.`);
11745
+ const raw = readFile(epic.filePath);
11746
+ assertFreshRevision(epic.id, raw, opts);
11747
+ const { data, content } = matter13(raw, {});
11748
+ data.status = "completed";
11749
+ data.completed_at = today2();
11750
+ data.completion_decision = completionDecisionRecord(evaluation, input);
11751
+ const newContent = matter13.stringify(content, data);
11752
+ writeFile(epic.filePath, newContent);
11753
+ const updated = parseEpic(dir, epic.filePath, newContent);
11754
+ if (!updated) throw new DeliveryPlanningWriteError("Failed to parse the Epic after completion.");
11755
+ return updated;
11756
+ }
11757
+ function completeDeliveryPlan(dir, id, input = {}, opts) {
11758
+ const plan = getPlan(dir, id);
11759
+ if (!plan) throw new DeliveryPlanningWriteError(`Plan ${id} does not exist.`);
11760
+ const evaluation = evaluatePlanCompletion(dir, plan);
11761
+ if (evaluation.readiness !== "READY_TO_COMPLETE" && evaluation.readiness !== "READY_WITH_EXCEPTIONS") throw new PlanningNotReadyError(evaluation);
11762
+ if (!PLAN_TRANSITIONS[plan.status].includes("completed")) throw new DeliveryPlanningWriteError(`Plan ${id} cannot move from ${plan.status} to completed.`);
11763
+ const raw = readFile(plan.filePath);
11764
+ assertFreshRevision(plan.id, raw, opts);
11765
+ const { data, content } = matter13(raw, {});
11766
+ data.status = "completed";
11767
+ data.completed_at = today2();
11768
+ data.completion_decision = completionDecisionRecord(evaluation, input);
11769
+ const newContent = matter13.stringify(content, data);
11770
+ writeFile(plan.filePath, newContent);
11771
+ const updated = parseDeliveryPlan(dir, plan.filePath, newContent);
11772
+ if (!updated) throw new DeliveryPlanningWriteError("Failed to parse the Plan after completion.");
11773
+ return updated;
11774
+ }
11338
11775
 
11339
11776
  // src/core/knowledge-consolidation.ts
11340
11777
  import { createHash as createHash3 } from "crypto";
@@ -12615,7 +13052,9 @@ function toListItem(a) {
12615
13052
  releaseStatus: a.releaseStatus || null,
12616
13053
  affectedModules: a.affectedModules,
12617
13054
  scopeConfidenceLevel: a.scopeConfidence?.level ?? null,
12618
- initiative: a.initiative || null
13055
+ initiative: a.initiative || null,
13056
+ owners: Array.isArray(a.rawFrontmatter.owners) ? a.rawFrontmatter.owners.map(String).filter(Boolean) : [],
13057
+ contributors: Array.isArray(a.rawFrontmatter.contributors) ? a.rawFrontmatter.contributors.map(String).filter(Boolean) : []
12619
13058
  };
12620
13059
  }
12621
13060
  function getWorkItem(dir, workItemId) {
@@ -12625,7 +13064,7 @@ function getWorkItem(dir, workItemId) {
12625
13064
  const base = toListItem(match);
12626
13065
  const body = readBody(match.filePath);
12627
13066
  const sections = splitSections(body);
12628
- const fm = match.rawFrontmatter;
13067
+ const fm2 = match.rawFrontmatter;
12629
13068
  const knowledge = discoverKnowledge(dir).filter((a) => !a.isWorkItem);
12630
13069
  const knowledgeById = new Map(knowledge.filter((k) => k.id).map((k) => [k.id, k]));
12631
13070
  const detail = {
@@ -12642,21 +13081,21 @@ function getWorkItem(dir, workItemId) {
12642
13081
  moduleCoverage: normalizeCoverage(match.moduleCoverage),
12643
13082
  impactAnalysis: normalizeImpact(match.impactAnalysis),
12644
13083
  acceptanceCriteria: parseAcceptanceCriteria(sections),
12645
- implementationEvidence: parseEvidence(fm),
12646
- releaseGates: parseReleaseGates(fm),
12647
- completionExceptions: parseExceptions(fm),
13084
+ implementationEvidence: parseEvidence(fm2),
13085
+ releaseGates: parseReleaseGates(fm2),
13086
+ completionExceptions: parseExceptions2(fm2),
12648
13087
  decisions: parseDecisions(match.decisions, knowledgeById),
12649
- relatedKnowledge: parseRelatedKnowledge(fm, knowledgeById),
12650
- source: parseWorkItemSource(fm),
12651
- originalSnapshot: parseOriginalSnapshot(fm),
13088
+ relatedKnowledge: parseRelatedKnowledge(fm2, knowledgeById),
13089
+ source: parseWorkItemSource(fm2),
13090
+ originalSnapshot: parseOriginalSnapshot(fm2),
12652
13091
  path: match.relPath,
12653
13092
  // Faithful source of truth: the artifact body already read above, not reconstructed (WI-025).
12654
13093
  markdownBody: body.trim(),
12655
13094
  // External systems this WI relates to (WI-030), separate from affectedModules (code).
12656
- resources: parseWorkItemResources(fm),
13095
+ resources: parseWorkItemResources(fm2),
12657
13096
  // Deprecation Targets this WI retires (WI-050), referenced not copied.
12658
- deprecationTargets: parseWorkItemDeprecationTargets(fm),
12659
- ...parseSystemImpact(dir, fm)
13097
+ deprecationTargets: parseWorkItemDeprecationTargets(fm2),
13098
+ ...parseSystemImpact(dir, fm2)
12660
13099
  };
12661
13100
  return { ...detail, refinement: computeRefinementStatus(detail) };
12662
13101
  }
@@ -12664,8 +13103,8 @@ function parseGraphReason(v) {
12664
13103
  if (!v || typeof v !== "object") return null;
12665
13104
  const o = v;
12666
13105
  const relationship = typeof o.relationship === "string" && o.relationship.trim() ? o.relationship.trim() : null;
12667
- const path8 = Array.isArray(o.path) ? o.path.map(String).filter(Boolean) : [];
12668
- return relationship || path8.length ? { relationship, path: path8 } : null;
13106
+ const path10 = Array.isArray(o.path) ? o.path.map(String).filter(Boolean) : [];
13107
+ return relationship || path10.length ? { relationship, path: path10 } : null;
12669
13108
  }
12670
13109
  function parseExplain(o) {
12671
13110
  const refs = Array.isArray(o.evidence) ? o.evidence : Array.isArray(o.evidence_refs) ? o.evidence_refs : [];
@@ -12679,14 +13118,14 @@ function parseExplain(o) {
12679
13118
  function emptyExplain() {
12680
13119
  return { reason: null, graphReason: null, evidenceRefs: [], evidenceSummary: null };
12681
13120
  }
12682
- function parseSystemImpact(dir, fm) {
13121
+ function parseSystemImpact(dir, fm2) {
12683
13122
  const topology = loadSystemTopology(dir);
12684
13123
  const byId = new Map(topology.entities.map((e) => [e.id, e]));
12685
13124
  const resolve = (id) => {
12686
13125
  const e = byId.get(id);
12687
13126
  return { id, nodeId: `sys:${id}`, label: e?.label ?? id, kind: e?.kind ?? "unknown", moduleId: e?.moduleId ?? null };
12688
13127
  };
12689
- const affected = Array.isArray(fm.affected_system_entities) ? fm.affected_system_entities.map((raw) => {
13128
+ const affected = Array.isArray(fm2.affected_system_entities) ? fm2.affected_system_entities.map((raw) => {
12690
13129
  if (typeof raw === "string") return raw ? { ...resolve(raw), ...emptyExplain() } : null;
12691
13130
  if (raw && typeof raw === "object") {
12692
13131
  const o = raw;
@@ -12695,13 +13134,13 @@ function parseSystemImpact(dir, fm) {
12695
13134
  }
12696
13135
  return null;
12697
13136
  }).filter((e) => e != null) : [];
12698
- const reviewed = Array.isArray(fm.reviewed_system_entities) ? fm.reviewed_system_entities.filter((r) => Boolean(r) && typeof r === "object").map((r) => ({ ...resolve(String(r.id ?? "")), ...parseExplain(r), status: String(r.status ?? "unknown") })).filter((r) => r.id) : [];
12699
- const graphRevision = typeof fm.graph_revision === "string" && fm.graph_revision.trim() ? fm.graph_revision.trim() : null;
13137
+ const reviewed = Array.isArray(fm2.reviewed_system_entities) ? fm2.reviewed_system_entities.filter((r) => Boolean(r) && typeof r === "object").map((r) => ({ ...resolve(String(r.id ?? "")), ...parseExplain(r), status: String(r.status ?? "unknown") })).filter((r) => r.id) : [];
13138
+ const graphRevision = typeof fm2.graph_revision === "string" && fm2.graph_revision.trim() ? fm2.graph_revision.trim() : null;
12700
13139
  const graphCoverage = topology.entities.length === 0 ? "unavailable" : topology.relationships.length > 0 ? "available" : "partial";
12701
13140
  return { affectedSystemEntities: affected, reviewedSystemEntities: reviewed, graphRevision, graphCoverage };
12702
13141
  }
12703
- function parseOriginalSnapshot(fm) {
12704
- const raw = fm.original_snapshot;
13142
+ function parseOriginalSnapshot(fm2) {
13143
+ const raw = fm2.original_snapshot;
12705
13144
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
12706
13145
  const o = raw;
12707
13146
  const title = typeof o.title === "string" ? o.title : void 0;
@@ -12804,12 +13243,12 @@ function normalizeImpact(ia) {
12804
13243
  ...v.question ? { question: v.question } : {}
12805
13244
  }));
12806
13245
  }
12807
- function optStr4(v) {
13246
+ function optStr5(v) {
12808
13247
  if (typeof v === "string" && v.trim()) return v.trim();
12809
13248
  return void 0;
12810
13249
  }
12811
- function parseEvidence(fm) {
12812
- const evidence = fm.implementation_evidence;
13250
+ function parseEvidence(fm2) {
13251
+ const evidence = fm2.implementation_evidence;
12813
13252
  const repos = evidence?.repositories;
12814
13253
  if (!repos || typeof repos !== "object" || Array.isArray(repos)) return [];
12815
13254
  const out = [];
@@ -12819,13 +13258,13 @@ function parseEvidence(fm) {
12819
13258
  const validations = Array.isArray(d.validations) ? d.validations.map((v) => ({
12820
13259
  command: String(v.command ?? ""),
12821
13260
  status: String(v.status ?? "unknown"),
12822
- ...optStr4(v.reason) ? { reason: optStr4(v.reason) } : {}
13261
+ ...optStr5(v.reason) ? { reason: optStr5(v.reason) } : {}
12823
13262
  })) : [];
12824
13263
  const migrations = Array.isArray(d.migrations) ? d.migrations.map((m) => ({
12825
13264
  id: String(m.id ?? ""),
12826
13265
  environment: String(m.environment ?? ""),
12827
13266
  status: String(m.status ?? "unknown"),
12828
- ...optStr4(m.reason) ? { reason: optStr4(m.reason) } : {}
13267
+ ...optStr5(m.reason) ? { reason: optStr5(m.reason) } : {}
12829
13268
  })) : [];
12830
13269
  out.push({
12831
13270
  module,
@@ -12838,23 +13277,23 @@ function parseEvidence(fm) {
12838
13277
  }
12839
13278
  return out;
12840
13279
  }
12841
- function parseReleaseGates(fm) {
12842
- if (!Array.isArray(fm.release_gates)) return [];
12843
- return fm.release_gates.filter((g) => g && typeof g === "object").map((g) => ({
13280
+ function parseReleaseGates(fm2) {
13281
+ if (!Array.isArray(fm2.release_gates)) return [];
13282
+ return fm2.release_gates.filter((g) => g && typeof g === "object").map((g) => ({
12844
13283
  id: String(g.id ?? ""),
12845
13284
  status: String(g.status ?? "pending"),
12846
- ...optStr4(g.reason) ? { reason: optStr4(g.reason) } : {},
12847
- ...optStr4(g.required_for) ? { requiredFor: optStr4(g.required_for) } : {}
13285
+ ...optStr5(g.reason) ? { reason: optStr5(g.reason) } : {},
13286
+ ...optStr5(g.required_for) ? { requiredFor: optStr5(g.required_for) } : {}
12848
13287
  }));
12849
13288
  }
12850
- function parseExceptions(fm) {
12851
- if (!Array.isArray(fm.completion_exceptions)) return [];
12852
- return fm.completion_exceptions.filter((e) => e && typeof e === "object").map((e) => ({
13289
+ function parseExceptions2(fm2) {
13290
+ if (!Array.isArray(fm2.completion_exceptions)) return [];
13291
+ return fm2.completion_exceptions.filter((e) => e && typeof e === "object").map((e) => ({
12853
13292
  id: String(e.id ?? ""),
12854
13293
  status: String(e.status ?? "proposed"),
12855
- ...optStr4(e.reason) ? { reason: optStr4(e.reason) } : {},
12856
- ...optStr4(e.category) ? { category: optStr4(e.category) } : {},
12857
- ...optStr4(e.impact) ? { impact: optStr4(e.impact) } : {}
13294
+ ...optStr5(e.reason) ? { reason: optStr5(e.reason) } : {},
13295
+ ...optStr5(e.category) ? { category: optStr5(e.category) } : {},
13296
+ ...optStr5(e.impact) ? { impact: optStr5(e.impact) } : {}
12858
13297
  }));
12859
13298
  }
12860
13299
  function parseDecisions(decisions, knowledgeById) {
@@ -12867,10 +13306,10 @@ function parseDecisions(decisions, knowledgeById) {
12867
13306
  };
12868
13307
  });
12869
13308
  }
12870
- function parseRelatedKnowledge(fm, knowledgeById) {
13309
+ function parseRelatedKnowledge(fm2, knowledgeById) {
12871
13310
  const refs = /* @__PURE__ */ new Set();
12872
13311
  for (const field of ["related_knowledge", "knowledge", "related"]) {
12873
- const v = fm[field];
13312
+ const v = fm2[field];
12874
13313
  if (Array.isArray(v)) {
12875
13314
  for (const r of v) if (typeof r === "string" && r.trim()) refs.add(r.trim());
12876
13315
  }
@@ -13264,6 +13703,8 @@ function applyFrontmatter(data, input) {
13264
13703
  next.type = input.type;
13265
13704
  next.work_type = input.type;
13266
13705
  if (input.summary != null) next.summary = input.summary;
13706
+ next.owners = [...new Set((input.owners ?? []).map((v) => v.trim()).filter(Boolean))];
13707
+ next.contributors = [...new Set((input.contributors ?? []).map((v) => v.trim()).filter(Boolean))];
13267
13708
  next.affected_modules = [...input.affectedModules];
13268
13709
  if (input.scopeConfidence && VALID_CONFIDENCE.has(input.scopeConfidence.level)) {
13269
13710
  next.scope_confidence = { level: input.scopeConfidence.level, reasons: input.scopeConfidence.reasons.filter((r) => r.trim()) };
@@ -13347,7 +13788,9 @@ function toInput(data, content) {
13347
13788
  impactAnalysis: ia ? Object.entries(ia).map(([surface, v]) => ({ surface, status: String(v.status ?? ""), ...v.reason ? { reason: String(v.reason) } : {}, ...v.question ? { question: String(v.question) } : {} })) : [],
13348
13789
  acceptanceCriteria: criteria,
13349
13790
  decisions: Array.isArray(data.decisions) ? data.decisions.map(String) : [],
13350
- relatedKnowledge: Array.isArray(data.related_knowledge) ? data.related_knowledge.map(String) : []
13791
+ relatedKnowledge: Array.isArray(data.related_knowledge) ? data.related_knowledge.map(String) : [],
13792
+ owners: Array.isArray(data.owners) ? data.owners.map(String) : [],
13793
+ contributors: Array.isArray(data.contributors) ? data.contributors.map(String) : []
13351
13794
  };
13352
13795
  }
13353
13796
  function getWorkItemForEdit(dir, id) {
@@ -13396,7 +13839,7 @@ function createWorkItem(dir, opts) {
13396
13839
  if (!type) throw new WorkItemWriteError("INVALID_INPUT", `Unknown Work Item type "${opts.type}".`);
13397
13840
  const id = nextWorkItemId2(dir);
13398
13841
  const title = intent.split(/\r?\n/)[0].trim().slice(0, 120);
13399
- const today2 = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
13842
+ const today3 = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
13400
13843
  const summary = opts.summary?.trim() || intent;
13401
13844
  const source2 = opts.source ? { ...opts.source, inferred: false } : { type: "manual", inferred: false };
13402
13845
  const data = {
@@ -13405,7 +13848,7 @@ function createWorkItem(dir, opts) {
13405
13848
  title,
13406
13849
  status: "draft",
13407
13850
  work_type: type,
13408
- created_at: today2,
13851
+ created_at: today3,
13409
13852
  source: source2,
13410
13853
  generated_by: "kaddo-admin",
13411
13854
  affected_modules: [],
@@ -13457,6 +13900,24 @@ function updateWorkItem(dir, id, input, expectedRevision) {
13457
13900
  atomicWrite3(filePath, nextRaw);
13458
13901
  return { revision: revisionOf2(nextRaw), path: relPath };
13459
13902
  }
13903
+ function updateWorkItemAssignments(dir, id, assignments, expectedRevision) {
13904
+ const { filePath, relPath } = findArtifact(dir, id);
13905
+ const raw = readFile(filePath);
13906
+ if (revisionOf2(raw) !== expectedRevision) {
13907
+ throw new WorkItemWriteError("WORK_ITEM_CONFLICT", "This Work Item changed outside Kaddo Admin. Reload the latest version before saving assignments.");
13908
+ }
13909
+ const { data, content } = matter17(raw);
13910
+ const status = lifecycleStateOf({ status: String(data.status ?? ""), filePath });
13911
+ if (!["draft", "ready", "in-progress"].includes(status)) {
13912
+ throw new WorkItemWriteError("WORK_ITEM_NOT_EDITABLE", `Assignments cannot be changed for a ${status} Work Item.`);
13913
+ }
13914
+ const next = { ...data };
13915
+ next.owners = [...new Set((assignments.owners ?? []).map((value) => value.trim()).filter(Boolean))];
13916
+ next.contributors = [...new Set((assignments.contributors ?? []).map((value) => value.trim()).filter(Boolean))];
13917
+ const nextRaw = serialize2(next, content);
13918
+ atomicWrite3(filePath, nextRaw);
13919
+ return { revision: revisionOf2(nextRaw), path: relPath, status };
13920
+ }
13460
13921
  function validateWorkItem(dir, id) {
13461
13922
  const { filePath } = findArtifact(dir, id);
13462
13923
  const raw = readFile(filePath);
@@ -13484,9 +13945,9 @@ function validateWorkItem(dir, id) {
13484
13945
  }
13485
13946
  const topology = loadSystemTopology(dir);
13486
13947
  const entityById = new Map(topology.entities.map((e) => [e.id, e]));
13487
- const fm = data;
13948
+ const fm2 = data;
13488
13949
  const idOf = (raw2) => typeof raw2 === "string" ? raw2 : raw2 && typeof raw2 === "object" ? String(raw2.id ?? "") : "";
13489
- const affectedEntities = Array.isArray(fm.affected_system_entities) ? fm.affected_system_entities.map(idOf).filter(Boolean) : [];
13950
+ const affectedEntities = Array.isArray(fm2.affected_system_entities) ? fm2.affected_system_entities.map(idOf).filter(Boolean) : [];
13490
13951
  for (const eid of affectedEntities) {
13491
13952
  const e = entityById.get(eid);
13492
13953
  if (!e) {
@@ -13497,8 +13958,8 @@ function validateWorkItem(dir, id) {
13497
13958
  findings.push({ level: "warning", message: `System entity "${e.label}" belongs to module "${e.moduleId}", which is not in affected_modules.` });
13498
13959
  }
13499
13960
  }
13500
- if (Array.isArray(fm.reviewed_system_entities)) {
13501
- for (const r of fm.reviewed_system_entities) {
13961
+ if (Array.isArray(fm2.reviewed_system_entities)) {
13962
+ for (const r of fm2.reviewed_system_entities) {
13502
13963
  const rid = r && typeof r === "object" ? String(r.id ?? "") : "";
13503
13964
  if (rid && !entityById.has(rid)) findings.push({ level: "warning", message: `Reviewed system entity "${rid}" does not exist in the semantic topology.` });
13504
13965
  }
@@ -13506,7 +13967,7 @@ function validateWorkItem(dir, id) {
13506
13967
  const canMarkReady = !findings.some((f) => f.level === "blocking");
13507
13968
  return { findings, canMarkReady };
13508
13969
  }
13509
- var ALLOWED = { draft: ["ready"], ready: ["draft"] };
13970
+ var ALLOWED = { draft: ["ready"], ready: ["draft", "in-progress"] };
13510
13971
  function transitionWorkItem(dir, id, to, expectedRevision) {
13511
13972
  const { filePath } = findArtifact(dir, id);
13512
13973
  const raw = readFile(filePath);
@@ -13779,16 +14240,16 @@ function findSystemPaths(dir, source2, target, opts = {}) {
13779
14240
  out.get(r.source).push(r.target);
13780
14241
  }
13781
14242
  const paths = [];
13782
- const walk2 = (node, path8) => {
14243
+ const walk2 = (node, path10) => {
13783
14244
  if (paths.length >= 20) return;
13784
- if (node === target && path8.length > 1) {
13785
- paths.push([...path8]);
14245
+ if (node === target && path10.length > 1) {
14246
+ paths.push([...path10]);
13786
14247
  return;
13787
14248
  }
13788
- if (path8.length > maxDepth) return;
14249
+ if (path10.length > maxDepth) return;
13789
14250
  for (const nxt of out.get(node) ?? []) {
13790
- if (path8.includes(nxt)) continue;
13791
- walk2(nxt, [...path8, nxt]);
14251
+ if (path10.includes(nxt)) continue;
14252
+ walk2(nxt, [...path10, nxt]);
13792
14253
  }
13793
14254
  };
13794
14255
  walk2(source2, [source2]);
@@ -13813,14 +14274,14 @@ function getImpactCandidates(dir, seedIds, opts = {}) {
13813
14274
  existing.reason.push(reason);
13814
14275
  continue;
13815
14276
  }
13816
- const path8 = findSystemPaths(dir, seed, n.id, { maxDepth: opts.maxDepth ?? DEFAULT_MAX_DEPTH })[0];
14277
+ const path10 = findSystemPaths(dir, seed, n.id, { maxDepth: opts.maxDepth ?? DEFAULT_MAX_DEPTH })[0];
13817
14278
  candidates.set(n.id, {
13818
14279
  nodeId: n.id,
13819
14280
  label: n.label,
13820
14281
  kind: n.type,
13821
14282
  ...n.moduleId ? { moduleId: n.moduleId } : {},
13822
14283
  reason: [reason],
13823
- ...path8 ? { graphPath: path8.map((id) => byId.get(id)?.label ?? id) } : {},
14284
+ ...path10 ? { graphPath: path10.map((id) => byId.get(id)?.label ?? id) } : {},
13824
14285
  ...n.implementationRefs?.length ? { implementationRefs: n.implementationRefs } : {},
13825
14286
  ...n.knowledgeRefs?.length ? { knowledgeRefs: n.knowledgeRefs } : {},
13826
14287
  status: "candidate",
@@ -14513,18 +14974,23 @@ function collectImplementationEvidence(dir, workItemId, input) {
14513
14974
  } : {}
14514
14975
  };
14515
14976
  }
14516
- return { repositories };
14977
+ return {
14978
+ repositories,
14979
+ ...input.acVerifications.length > 0 ? {
14980
+ ac_verifications: input.acVerifications.map((verification) => ({ ...verification }))
14981
+ } : {}
14982
+ };
14517
14983
  }
14518
14984
  function verifyWorkItem(dir, workItemId, input) {
14519
14985
  const evidence = collectImplementationEvidence(dir, workItemId, input);
14520
14986
  const artifacts = discoverWorkItems(dir);
14521
14987
  const match = artifacts.find((a) => (a.id || a.title) === workItemId);
14522
14988
  const lifecycle = lifecycleStateOf({ status: match.status, filePath: match.filePath });
14523
- const fm = match.rawFrontmatter;
14989
+ const fm2 = match.rawFrontmatter;
14524
14990
  const acVerifications = mapACVerifications(input.acVerifications);
14525
14991
  const acSummary = computeACSummary(acVerifications);
14526
- const releaseGates = Array.isArray(fm.release_gates) ? fm.release_gates : [];
14527
- const completionExceptions = Array.isArray(fm.completion_exceptions) ? fm.completion_exceptions : [];
14992
+ const releaseGates = Array.isArray(fm2.release_gates) ? fm2.release_gates : [];
14993
+ const completionExceptions = Array.isArray(fm2.completion_exceptions) ? fm2.completion_exceptions : [];
14528
14994
  const plannedVsActual = computePlannedVsActual(match.affectedModules, input.repos);
14529
14995
  const registeredModuleIds = loadMappedModules(dir).map((m) => m.id);
14530
14996
  const modifiedRepoIds = input.repos.map((r) => r.repoId);
@@ -14535,7 +15001,7 @@ function verifyWorkItem(dir, workItemId, input) {
14535
15001
  validationStatus: match.validationStatus || "not-started",
14536
15002
  releaseStatus: match.releaseStatus || "not-assessed",
14537
15003
  affectedModules: match.affectedModules,
14538
- rawFrontmatter: fm,
15004
+ rawFrontmatter: fm2,
14539
15005
  registeredModuleIds,
14540
15006
  modifiedRepoIds
14541
15007
  });
@@ -14573,6 +15039,9 @@ function evaluateCompletion(verification) {
14573
15039
  warnings.push(`Completion exception "${ex.id}" is still proposed (not yet accepted).`);
14574
15040
  }
14575
15041
  }
15042
+ if (verification.acSummary.total === 0) {
15043
+ blockers.push("No acceptance criteria were detected; completion evidence is insufficient.");
15044
+ }
14576
15045
  if (verification.acSummary.failed > 0) {
14577
15046
  const failedACs = verification.acVerifications.filter((ac) => ac.status === "failed");
14578
15047
  for (const ac of failedACs) {
@@ -14584,10 +15053,16 @@ function evaluateCompletion(verification) {
14584
15053
  blockers.push(f.message);
14585
15054
  }
14586
15055
  if (verification.acSummary.manualReview > 0) {
14587
- warnings.push(`${verification.acSummary.manualReview} AC(s) require manual review.`);
15056
+ blockers.push(`${verification.acSummary.manualReview} AC(s) require manual review.`);
14588
15057
  }
14589
15058
  if (verification.acSummary.notVerified > 0) {
14590
- warnings.push(`${verification.acSummary.notVerified} AC(s) not yet verified.`);
15059
+ blockers.push(`${verification.acSummary.notVerified} AC(s) not yet verified.`);
15060
+ }
15061
+ if (verification.implementationStatus !== "completed") {
15062
+ blockers.push(`Implementation status is "${verification.implementationStatus}", not "completed".`);
15063
+ }
15064
+ if (!["passed", "accepted-with-exceptions"].includes(verification.validationStatus)) {
15065
+ blockers.push(`Validation status is "${verification.validationStatus}", not passed.`);
14591
15066
  }
14592
15067
  const warningFindings = verification.findings.filter((f) => f.severity === "warning");
14593
15068
  for (const f of warningFindings) {
@@ -14604,8 +15079,8 @@ function evaluateCompletion(verification) {
14604
15079
  }
14605
15080
  let readiness;
14606
15081
  if (blockers.length > 0) {
14607
- const hasOnlyACFailures = blockers.every((b) => b.startsWith("AC failed:"));
14608
- if (hasOnlyACFailures) {
15082
+ const needsEvidence = blockers.every((b) => b.startsWith("AC failed:") || b.includes("acceptance criteria") || b.includes("AC(s)") || b.startsWith("Implementation status") || b.startsWith("Validation status"));
15083
+ if (needsEvidence) {
14609
15084
  readiness = "NEEDS_WORK";
14610
15085
  reasons.push("Acceptance criteria have failures that must be addressed.");
14611
15086
  } else {
@@ -14686,6 +15161,152 @@ function deriveImplementationStatus(repos) {
14686
15161
  return "in-progress";
14687
15162
  }
14688
15163
 
15164
+ // src/services/git.ts
15165
+ import { execa } from "execa";
15166
+ import path5 from "path";
15167
+ async function getGitRoot(dir) {
15168
+ try {
15169
+ const result = await execa("git", ["rev-parse", "--show-toplevel"], { cwd: dir });
15170
+ return result.stdout.trim() || null;
15171
+ } catch {
15172
+ return null;
15173
+ }
15174
+ }
15175
+ async function observeGit(dir, maxCommits = 100, repositoryId) {
15176
+ const limit = Math.max(1, Math.min(maxCommits, 250));
15177
+ const inspectedAt = (/* @__PURE__ */ new Date()).toISOString();
15178
+ try {
15179
+ const root = await getGitRoot(dir);
15180
+ if (!root) return { availability: "unavailable", repository: null, commits: [], branches: [], inspectedAt, limit };
15181
+ const [log2, refs] = await Promise.all([
15182
+ execa("git", ["log", `--max-count=${limit}`, "--format=%H%x1f%an%x1f%aI%x1f%s", "--name-only"], { cwd: root, timeout: 5e3 }),
15183
+ execa("git", ["for-each-ref", "--format=%(refname:short)", "refs/heads"], { cwd: root, timeout: 5e3 })
15184
+ ]);
15185
+ const commits = [];
15186
+ let current = null;
15187
+ for (const line of log2.stdout.split(/\r?\n/)) {
15188
+ const parts = line.split("");
15189
+ if (parts.length === 4) {
15190
+ if (current) commits.push(current);
15191
+ current = { sha: parts[0], author: parts[1], date: parts[2], subject: parts[3], files: [] };
15192
+ } else if (current && line.trim()) current.files.push(line.trim());
15193
+ }
15194
+ if (current) commits.push(current);
15195
+ return {
15196
+ // The display identity is supplied by the caller when a project observes
15197
+ // several repositories. A basename alone is ambiguous in a multirepo
15198
+ // workspace (for example, two independent `api` folders).
15199
+ availability: "available",
15200
+ repository: repositoryId ?? path5.basename(root),
15201
+ commits,
15202
+ branches: refs.stdout.split(/\r?\n/).map((name) => name.trim()).filter(Boolean).slice(0, 100).map((name) => ({ name })),
15203
+ inspectedAt,
15204
+ limit
15205
+ };
15206
+ } catch {
15207
+ return { availability: "partial", repository: null, commits: [], branches: [], inspectedAt, limit };
15208
+ }
15209
+ }
15210
+
15211
+ // src/core/collaboration.ts
15212
+ import path6 from "path";
15213
+ function matchesWorkItemReference(value, id) {
15214
+ return new RegExp(`(^|[^A-Za-z0-9_-])${id.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?=$|[^A-Za-z0-9_-])`, "i").test(value);
15215
+ }
15216
+ async function observationsForProject(dir) {
15217
+ const corePath = path6.resolve(dir);
15218
+ const mapped = loadMappedModules(dir).filter((module) => Boolean(module.repoPath)).map((module) => ({ path: path6.resolve(corePath, module.repoPath), repositoryId: `module:${module.id}` }));
15219
+ const candidates = [{ path: corePath, repositoryId: "core" }, ...mapped];
15220
+ const resolved = await Promise.all(candidates.map(async (candidate) => ({ ...candidate, root: await getGitRoot(candidate.path) })));
15221
+ const repositories = /* @__PURE__ */ new Map();
15222
+ for (const item of resolved) if (item.root && !repositories.has(item.root)) repositories.set(item.root, { root: item.root, repositoryId: item.repositoryId });
15223
+ const observations = await Promise.all([...repositories.values()].map((repo) => observeGit(repo.root, 100, repo.repositoryId)));
15224
+ return observations;
15225
+ }
15226
+ async function collaborationForWorkItems(dir, ids) {
15227
+ const observations = await observationsForProject(dir);
15228
+ return ids.map((id) => {
15229
+ const wi = getWorkItem(dir, id);
15230
+ const linkedCommits = [];
15231
+ const relatedBranches = [];
15232
+ for (const observation of observations) {
15233
+ const repository = observation.repository ?? "local";
15234
+ for (const commit of observation.commits) {
15235
+ if (!matchesWorkItemReference(commit.subject, wi.id)) continue;
15236
+ linkedCommits.push({ repository, sha: commit.sha, author: commit.author, date: commit.date, subject: commit.subject, paths: commit.files.slice(0, 50), attribution: "explicit-reference", evidence: `Exact reference ${wi.id} in commit subject.` });
15237
+ }
15238
+ for (const branch of observation.branches) {
15239
+ if (!matchesWorkItemReference(branch.name, wi.id)) continue;
15240
+ relatedBranches.push({ repository, name: branch.name, attribution: "branch-associated", evidence: `Exact reference ${wi.id} in local branch name.` });
15241
+ }
15242
+ }
15243
+ const inspectedCommits = observations.reduce((total, observation) => total + observation.commits.length, 0);
15244
+ const available = observations.filter((observation) => observation.availability === "available").length;
15245
+ const availability = available === observations.length ? "available" : available > 0 ? "partial" : observations.some((observation) => observation.availability === "partial") ? "partial" : "unavailable";
15246
+ return {
15247
+ workItemId: wi.id,
15248
+ responsibility: { owners: wi.owners, contributors: wi.contributors },
15249
+ git: {
15250
+ availability,
15251
+ repositories: observations.flatMap((observation) => observation.repository ? [observation.repository] : []),
15252
+ observedAuthors: [...new Set(linkedCommits.map((commit) => commit.author))],
15253
+ linkedCommits,
15254
+ relatedBranches,
15255
+ unattributedActivityCount: Math.max(0, inspectedCommits - linkedCommits.length),
15256
+ inspectedAt: observations.map((observation) => observation.inspectedAt).sort().at(-1) ?? null,
15257
+ coverage: { maxCommits: observations[0]?.limit ?? 100, inspectedCommits, note: "Only the core repository and explicitly mapped module repositories were inspected with read-only Git metadata. File overlap never creates attribution." }
15258
+ }
15259
+ };
15260
+ });
15261
+ }
15262
+ async function getWorkItemsCollaboration(dir, ids) {
15263
+ return collaborationForWorkItems(dir, [...new Set(ids)]);
15264
+ }
15265
+ async function getWorkItemCollaboration(dir, id) {
15266
+ return (await collaborationForWorkItems(dir, [id]))[0];
15267
+ }
15268
+ function aggregate(id, responsibility, items) {
15269
+ const commits = /* @__PURE__ */ new Map();
15270
+ for (const item of items) for (const commit of item.git.linkedCommits) {
15271
+ const key = `${commit.repository}:${commit.sha}`;
15272
+ const existing = commits.get(key);
15273
+ if (existing) existing.workItemIds = [.../* @__PURE__ */ new Set([...existing.workItemIds, item.workItemId])];
15274
+ else commits.set(key, { ...commit, workItemIds: [item.workItemId] });
15275
+ }
15276
+ const first2 = items[0];
15277
+ return {
15278
+ id,
15279
+ responsibility,
15280
+ workItems: items.map((item) => ({ id: item.workItemId, owners: item.responsibility.owners, contributors: item.responsibility.contributors, linkedCommitCount: item.git.linkedCommits.length })),
15281
+ observedAuthors: [...new Set([...commits.values()].map((commit) => commit.author))],
15282
+ linkedCommits: [...commits.values()],
15283
+ unassignedWorkItemIds: items.filter((item) => item.responsibility.owners.length === 0).map((item) => item.workItemId),
15284
+ git: first2?.git ?? { availability: "unavailable", repositories: [], observedAuthors: [], linkedCommits: [], relatedBranches: [], unattributedActivityCount: 0, inspectedAt: null, coverage: { maxCommits: 100, inspectedCommits: 0, note: "No associated Work Items." } }
15285
+ };
15286
+ }
15287
+ async function getInitiativeCollaboration(dir, id) {
15288
+ const initiative = getInitiative(dir, id);
15289
+ if (!initiative) throw new WorkItemNotFoundError(`Initiative ${id} was not found.`);
15290
+ const items = await collaborationForWorkItems(dir, associatedWorkItems(dir, id).map((item) => item.id));
15291
+ return aggregate(id, { owners: initiative.owners, contributors: initiative.contributors }, items);
15292
+ }
15293
+ async function getEpicCollaboration(dir, id) {
15294
+ const epic = getEpic(dir, id);
15295
+ if (!epic) throw new WorkItemNotFoundError(`Epic ${id} was not found.`);
15296
+ const items = await collaborationForWorkItems(dir, workItemsInEpic(dir, id).map((item) => item.id));
15297
+ const initiatives = initiativesInEpic(dir, id);
15298
+ return aggregate(id, { owners: [...new Set(initiatives.flatMap((item) => item.owners))], contributors: [...new Set(initiatives.flatMap((item) => item.contributors))] }, items);
15299
+ }
15300
+ async function getPlanCollaboration(dir, id) {
15301
+ const plan = getPlan(dir, id);
15302
+ if (!plan) throw new WorkItemNotFoundError(`Plan ${id} was not found.`);
15303
+ const epicIds = epicsInPlan(dir, id).map((epic) => epic.id);
15304
+ const workItemIds = [...new Set(epicIds.flatMap((epicId) => workItemsInEpic(dir, epicId).map((item) => item.id)))];
15305
+ const items = await collaborationForWorkItems(dir, workItemIds);
15306
+ const initiatives = epicIds.flatMap((epicId) => initiativesInEpic(dir, epicId));
15307
+ return aggregate(id, { owners: [...new Set(initiatives.flatMap((item) => item.owners))], contributors: [...new Set(initiatives.flatMap((item) => item.contributors))] }, items);
15308
+ }
15309
+
14689
15310
  // src/core/work-item-import.ts
14690
15311
  import crypto3 from "crypto";
14691
15312
  import fs5 from "fs";
@@ -15708,8 +16329,8 @@ async function handleJiraResponse(res) {
15708
16329
  }
15709
16330
  return await res.json();
15710
16331
  }
15711
- async function jiraFetch(baseUrl, path8, auth, timeoutMs, params) {
15712
- const url = new URL(path8, baseUrl + "/");
16332
+ async function jiraFetch(baseUrl, path10, auth, timeoutMs, params) {
16333
+ const url = new URL(path10, baseUrl + "/");
15713
16334
  if (params) for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
15714
16335
  const controller = new AbortController();
15715
16336
  const timer = setTimeout(() => controller.abort(), timeoutMs);
@@ -15727,8 +16348,8 @@ async function jiraFetch(baseUrl, path8, auth, timeoutMs, params) {
15727
16348
  clearTimeout(timer);
15728
16349
  }
15729
16350
  }
15730
- async function jiraPost(baseUrl, path8, auth, timeoutMs, body) {
15731
- const url = new URL(path8, baseUrl + "/");
16351
+ async function jiraPost(baseUrl, path10, auth, timeoutMs, body) {
16352
+ const url = new URL(path10, baseUrl + "/");
15732
16353
  const controller = new AbortController();
15733
16354
  const timer = setTimeout(() => controller.abort(), timeoutMs);
15734
16355
  try {
@@ -16580,7 +17201,7 @@ function evaluateInitiativeCompletion(dir, ini) {
16580
17201
 
16581
17202
  // src/core/deprecation-write.ts
16582
17203
  import fs6 from "fs";
16583
- import path5 from "path";
17204
+ import path7 from "path";
16584
17205
  import matter20 from "gray-matter";
16585
17206
  var DeprecationWriteError = class extends Error {
16586
17207
  constructor(code, message) {
@@ -16696,7 +17317,7 @@ ${(input.purpose ?? "").trim() || "TODO: describe what this plan retires and why
16696
17317
  const relPath = `${DEPRECATION_PLANS_DIR}/${id}-${slug4(title) || "plan"}.md`;
16697
17318
  const filePath = join(dir, relPath);
16698
17319
  if (exists(filePath)) throw new DeprecationWriteError("DUPLICATE", `Plan file already exists: ${relPath}`);
16699
- ensureDir(path5.dirname(filePath));
17320
+ ensureDir(path7.dirname(filePath));
16700
17321
  atomicWrite4(filePath, serialize3(data, body));
16701
17322
  return { id, path: relPath, findings: [] };
16702
17323
  }
@@ -16715,7 +17336,7 @@ function addTarget(dir, planId, input) {
16715
17336
  }
16716
17337
  data.targets = [...targets, raw];
16717
17338
  atomicWrite4(filePath, serialize3(data, body));
16718
- return { planId, targetId, path: `${DEPRECATION_PLANS_DIR}/${path5.basename(filePath)}`, findings };
17339
+ return { planId, targetId, path: `${DEPRECATION_PLANS_DIR}/${path7.basename(filePath)}`, findings };
16719
17340
  }
16720
17341
  function updateTarget(dir, planId, targetId, patch) {
16721
17342
  const { filePath, data, body } = loadPlanRaw(dir, planId);
@@ -16731,7 +17352,7 @@ function updateTarget(dir, planId, targetId, patch) {
16731
17352
  next[idx] = merged;
16732
17353
  data.targets = next;
16733
17354
  atomicWrite4(filePath, serialize3(data, body));
16734
- return { planId, targetId: String(targets[idx].id), path: `${DEPRECATION_PLANS_DIR}/${path5.basename(filePath)}`, findings };
17355
+ return { planId, targetId: String(targets[idx].id), path: `${DEPRECATION_PLANS_DIR}/${path7.basename(filePath)}`, findings };
16735
17356
  }
16736
17357
  function removeTarget(dir, planId, targetId, opts = {}) {
16737
17358
  const { filePath, data, body } = loadPlanRaw(dir, planId);
@@ -16744,7 +17365,7 @@ function removeTarget(dir, planId, targetId, opts = {}) {
16744
17365
  }
16745
17366
  data.targets = targets.filter((t) => String(t.id ?? "").toUpperCase() !== targetId.toUpperCase());
16746
17367
  atomicWrite4(filePath, serialize3(data, body));
16747
- return { removed: true, path: `${DEPRECATION_PLANS_DIR}/${path5.basename(filePath)}` };
17368
+ return { removed: true, path: `${DEPRECATION_PLANS_DIR}/${path7.basename(filePath)}` };
16748
17369
  }
16749
17370
 
16750
17371
  // src/core/deprecation-runbook.ts
@@ -16827,7 +17448,7 @@ function buildProductionRunbookContext(dir, planId, targetId) {
16827
17448
  blockers.push(`Dependency ${dependency.id} is not retired (current: ${dependency.lifecycle}).`);
16828
17449
  }
16829
17450
  }
16830
- const path8 = runbookPath(dir, target);
17451
+ const path10 = runbookPath(dir, target);
16831
17452
  return {
16832
17453
  eligible: blockers.length === 0,
16833
17454
  plan: { id: plan.id, title: plan.title, purpose: plan.purpose },
@@ -16835,7 +17456,7 @@ function buildProductionRunbookContext(dir, planId, targetId) {
16835
17456
  resource: target.resource ? getResource(dir, target.resource) : null,
16836
17457
  dependencies,
16837
17458
  blockers,
16838
- nextPath: path8,
17459
+ nextPath: path10,
16839
17460
  nextStep: blockers.length > 0 ? "Resolve the listed safeguards; no production proposal can be persisted yet." : "Review the generated proposal, obtain human approval, execute manually, then record evidence and validate the observation window."
16840
17461
  };
16841
17462
  }
@@ -16928,8 +17549,8 @@ function renderRunbook(context) {
16928
17549
  function createProductionRunbook(dir, planId, targetId) {
16929
17550
  const context = buildProductionRunbookContext(dir, planId, targetId);
16930
17551
  if (!context.eligible) throw new ProductionRunbookError(context.blockers.join(" "));
16931
- const path8 = context.nextPath;
16932
- const id = path8.split("/").pop()?.match(/^(RB-\d+)-/)?.[1] ?? "";
17552
+ const path10 = context.nextPath;
17553
+ const id = path10.split("/").pop()?.match(/^(RB-\d+)-/)?.[1] ?? "";
16933
17554
  const content = matter21.stringify(renderRunbook(context), {
16934
17555
  id,
16935
17556
  type: PRODUCTION_RUNBOOK_ARTIFACT_TYPE,
@@ -16939,13 +17560,13 @@ function createProductionRunbook(dir, planId, targetId) {
16939
17560
  resource: context.target.resource,
16940
17561
  approval: { required: true, status: "pending", approved_by: null, approved_at: null }
16941
17562
  });
16942
- const absolute = join(dir, path8);
16943
- if (exists(absolute)) throw new ProductionRunbookError(`Runbook already exists: ${path8}`);
17563
+ const absolute = join(dir, path10);
17564
+ if (exists(absolute)) throw new ProductionRunbookError(`Runbook already exists: ${path10}`);
16944
17565
  writeFile(absolute, content);
16945
17566
  return {
16946
17567
  id,
16947
17568
  title: `Production runbook \u2014 ${context.target.title ?? context.target.id}`,
16948
- path: path8,
17569
+ path: path10,
16949
17570
  planId: context.plan.id,
16950
17571
  targetId: context.target.id,
16951
17572
  approval: { required: true, status: "pending", approvedBy: null, approvedAt: null },
@@ -16956,14 +17577,14 @@ function getProductionRunbook(dir, id) {
16956
17577
  const root = join(dir, PRODUCTION_RUNBOOKS_DIR);
16957
17578
  for (const name of readDir(root)) {
16958
17579
  if (!name.toLowerCase().startsWith(`${id.toLowerCase()}-`) || !name.endsWith(".md")) continue;
16959
- const path8 = `${PRODUCTION_RUNBOOKS_DIR}/${name}`;
16960
- const parsed = matter21(readFile(join(dir, path8)));
17580
+ const path10 = `${PRODUCTION_RUNBOOKS_DIR}/${name}`;
17581
+ const parsed = matter21(readFile(join(dir, path10)));
16961
17582
  const data = parsed.data;
16962
17583
  if (data.type !== PRODUCTION_RUNBOOK_ARTIFACT_TYPE) continue;
16963
17584
  return {
16964
17585
  id: stringValue(data.id) ?? id,
16965
17586
  title: stringValue(data.title) ?? id,
16966
- path: path8,
17587
+ path: path10,
16967
17588
  planId: stringValue(data.deprecation_plan) ?? "",
16968
17589
  targetId: stringValue(data.deprecation_target) ?? "",
16969
17590
  approval: parseApproval(data.approval),
@@ -16988,7 +17609,7 @@ function validateProductionRunbook(runbook) {
16988
17609
 
16989
17610
  // src/core/okf/export.ts
16990
17611
  import fs7 from "fs";
16991
- import path6 from "path";
17612
+ import path8 from "path";
16992
17613
 
16993
17614
  // src/core/okf/mapping.ts
16994
17615
  import matter22 from "gray-matter";
@@ -17058,9 +17679,9 @@ function conceptBundlePath(a, id) {
17058
17679
  return `misc/${file}`;
17059
17680
  }
17060
17681
  }
17061
- function workItemRelations(fm) {
17682
+ function workItemRelations(fm2) {
17062
17683
  const out = [];
17063
- const resources = fm.resources;
17684
+ const resources = fm2.resources;
17064
17685
  if (Array.isArray(resources)) {
17065
17686
  for (const r of resources) {
17066
17687
  if (r && typeof r === "object") {
@@ -17069,16 +17690,16 @@ function workItemRelations(fm) {
17069
17690
  }
17070
17691
  }
17071
17692
  }
17072
- const dep = fm.deprecation_targets;
17693
+ const dep = fm2.deprecation_targets;
17073
17694
  if (Array.isArray(dep)) {
17074
17695
  for (const d of dep) {
17075
17696
  const s = typeof d === "string" ? d : d && typeof d === "object" ? str3(d.plan) : null;
17076
17697
  if (s) out.push({ id: s.includes("/") ? s.split("/")[0] : s, role: "deprecates-via" });
17077
17698
  }
17078
17699
  }
17079
- const parent = str3(fm.parent);
17700
+ const parent = str3(fm2.parent);
17080
17701
  if (parent) out.push({ id: parent, role: "child-of" });
17081
- for (const dId of strArray3(fm.decisions)) out.push({ id: dId, role: "decided-by" });
17702
+ for (const dId of strArray3(fm2.decisions)) out.push({ id: dId, role: "decided-by" });
17082
17703
  return out;
17083
17704
  }
17084
17705
  function slugify5(s) {
@@ -17231,16 +17852,16 @@ function frontmatter(data) {
17231
17852
  return lines.join("\n");
17232
17853
  }
17233
17854
  function relLink(fromPath, toPath) {
17234
- const rel = path6.posix.relative(path6.posix.dirname(fromPath), toPath);
17855
+ const rel = path8.posix.relative(path8.posix.dirname(fromPath), toPath);
17235
17856
  return rel.startsWith(".") ? rel : `./${rel}`;
17236
17857
  }
17237
17858
  function rewriteBodyLinks(body, sourcePath, srcToBundle, selfBundlePath) {
17238
- const srcDir = path6.posix.dirname(sourcePath);
17859
+ const srcDir = path8.posix.dirname(sourcePath);
17239
17860
  return body.replace(/\]\(([^)]+)\)/g, (whole, href) => {
17240
17861
  const raw = href.trim();
17241
17862
  const bare = raw.split("#")[0].split(" ")[0];
17242
17863
  if (!bare || /^(https?:|mailto:|#)/.test(bare)) return whole;
17243
- const candidate = bare.startsWith("/") ? bare.replace(/^\/+/, "") : path6.posix.normalize(path6.posix.join(srcDir, bare));
17864
+ const candidate = bare.startsWith("/") ? bare.replace(/^\/+/, "") : path8.posix.normalize(path8.posix.join(srcDir, bare));
17244
17865
  const target = srcToBundle.get(candidate);
17245
17866
  if (!target) return whole;
17246
17867
  const anchor = raw.includes("#") ? "#" + raw.split("#").slice(1).join("#") : "";
@@ -17317,22 +17938,22 @@ function sensitiveLabels(content) {
17317
17938
  return [...new Set(SENSITIVE_PATTERNS.filter((p) => p.re.test(content)).map((p) => p.label))];
17318
17939
  }
17319
17940
  function assertSafeDestination(dir, outputDir) {
17320
- const root = path6.resolve(dir);
17321
- const out = path6.resolve(outputDir);
17941
+ const root = path8.resolve(dir);
17942
+ const out = path8.resolve(outputDir);
17322
17943
  const within = (child, parent) => {
17323
- const rel = path6.relative(parent, child);
17324
- return rel === "" || !rel.startsWith("..") && !path6.isAbsolute(rel);
17944
+ const rel = path8.relative(parent, child);
17945
+ return rel === "" || !rel.startsWith("..") && !path8.isAbsolute(rel);
17325
17946
  };
17326
17947
  if (out === root) throw new OkfExportError("UNSAFE_DESTINATION", "Refusing to export onto the project root.");
17327
17948
  if (within(root, out)) throw new OkfExportError("UNSAFE_DESTINATION", "Refusing to export onto a parent of the project.");
17328
17949
  for (const protectedDir of ["knowledge", "packages", "apps", "src", "node_modules", ".git"]) {
17329
- const p = path6.join(root, protectedDir);
17950
+ const p = path8.join(root, protectedDir);
17330
17951
  if (out === p || within(out, p)) throw new OkfExportError("UNSAFE_DESTINATION", `Refusing to export into a protected directory: ${protectedDir}/`);
17331
17952
  }
17332
17953
  if (fs7.existsSync(out)) {
17333
17954
  try {
17334
17955
  const entries = fs7.readdirSync(out);
17335
- const looksOkf = entries.includes("index.md") && /okf_version/.test(fs7.readFileSync(path6.join(out, "index.md"), "utf-8"));
17956
+ const looksOkf = entries.includes("index.md") && /okf_version/.test(fs7.readFileSync(path8.join(out, "index.md"), "utf-8"));
17336
17957
  if (entries.length > 0 && !looksOkf) {
17337
17958
  throw new OkfExportError("UNSAFE_DESTINATION", `Destination is not empty and is not an OKF bundle: ${outputDir}. Use an empty or dedicated directory.`);
17338
17959
  }
@@ -17357,7 +17978,7 @@ function detectCollisions(concepts) {
17357
17978
  }
17358
17979
  function exportOkf(dir, opts = {}) {
17359
17980
  const outRel = opts.output ?? OKF_DEFAULT_OUTPUT;
17360
- const outputDir = path6.isAbsolute(outRel) ? outRel : path6.join(dir, outRel);
17981
+ const outputDir = path8.isAbsolute(outRel) ? outRel : path8.join(dir, outRel);
17361
17982
  assertSafeDestination(dir, outputDir);
17362
17983
  const extraWarnings = [];
17363
17984
  const artifacts = discoverKnowledge(dir);
@@ -17413,7 +18034,7 @@ ${c.body ?? ""}`;
17413
18034
  const dirs = /* @__PURE__ */ new Map();
17414
18035
  const childDirs = /* @__PURE__ */ new Map();
17415
18036
  for (const c of concepts) {
17416
- const d = path6.posix.dirname(c.path);
18037
+ const d = path8.posix.dirname(c.path);
17417
18038
  (dirs.get(d) ?? dirs.set(d, []).get(d)).push(c);
17418
18039
  const segs = d === "." ? [] : d.split("/");
17419
18040
  for (let i = 0; i < segs.length; i++) {
@@ -17439,8 +18060,8 @@ ${c.body ?? ""}`;
17439
18060
  try {
17440
18061
  fs7.rmSync(staging, { recursive: true, force: true });
17441
18062
  for (const [rel, content] of files) {
17442
- const full = path6.join(staging, rel);
17443
- fs7.mkdirSync(path6.dirname(full), { recursive: true });
18063
+ const full = path8.join(staging, rel);
18064
+ fs7.mkdirSync(path8.dirname(full), { recursive: true });
17444
18065
  fs7.writeFileSync(full, content, "utf-8");
17445
18066
  }
17446
18067
  const backup = `${outputDir}.old-${process.pid}-${Date.now()}`;
@@ -17469,13 +18090,13 @@ ${c.body ?? ""}`;
17469
18090
 
17470
18091
  // src/core/okf/validate.ts
17471
18092
  import fs8 from "fs";
17472
- import path7 from "path";
18093
+ import path9 from "path";
17473
18094
  import matter23 from "gray-matter";
17474
18095
  function walk(root) {
17475
18096
  const out = [];
17476
18097
  const rec = (d) => {
17477
18098
  for (const entry of fs8.readdirSync(d)) {
17478
- const full = path7.join(d, entry);
18099
+ const full = path9.join(d, entry);
17479
18100
  const st = fs8.statSync(full);
17480
18101
  if (st.isDirectory()) rec(full);
17481
18102
  else if (entry.endsWith(".md")) out.push(full);
@@ -17497,24 +18118,24 @@ function internalLinks(body) {
17497
18118
  }
17498
18119
  function validateOkf(dir, opts = {}) {
17499
18120
  const loc = opts.location ?? OKF_DEFAULT_OUTPUT;
17500
- const bundleDir = path7.isAbsolute(loc) ? loc : path7.join(dir, loc);
18121
+ const bundleDir = path9.isAbsolute(loc) ? loc : path9.join(dir, loc);
17501
18122
  const findings = [];
17502
18123
  if (!fs8.existsSync(bundleDir)) {
17503
18124
  findings.push({ level: "conformance", message: `OKF bundle directory not found: ${loc}. Run \`kaddo okf export\` first.` });
17504
18125
  return { dir: bundleDir, conformant: false, conceptCount: 0, findings, counts: { conformance: 1, warning: 0, info: 0 } };
17505
18126
  }
17506
18127
  const files = walk(bundleDir);
17507
- const rel = (f) => path7.relative(bundleDir, f).split(path7.sep).join("/");
18128
+ const rel = (f) => path9.relative(bundleDir, f).split(path9.sep).join("/");
17508
18129
  const present = new Set(files.map(rel));
17509
18130
  const idToFile = /* @__PURE__ */ new Map();
17510
18131
  let conceptCount = 0;
17511
- const rootIndex = path7.join(bundleDir, "index.md");
18132
+ const rootIndex = path9.join(bundleDir, "index.md");
17512
18133
  if (!fs8.existsSync(rootIndex)) {
17513
18134
  findings.push({ level: "warning", message: "No root index.md \u2014 the bundle has no top-level navigation entry." });
17514
18135
  }
17515
18136
  for (const file of files) {
17516
18137
  const r = rel(file);
17517
- const isIndex = path7.basename(file) === "index.md";
18138
+ const isIndex = path9.basename(file) === "index.md";
17518
18139
  let data = {};
17519
18140
  try {
17520
18141
  data = matter23(fs8.readFileSync(file, "utf-8")).data ?? {};
@@ -17545,7 +18166,7 @@ function validateOkf(dir, opts = {}) {
17545
18166
  }
17546
18167
  })();
17547
18168
  for (const href of internalLinks(body)) {
17548
- const resolved = path7.posix.normalize(path7.posix.join(path7.posix.dirname(r), href));
18169
+ const resolved = path9.posix.normalize(path9.posix.join(path9.posix.dirname(r), href));
17549
18170
  if (!present.has(resolved)) findings.push({ level: "info", file: r, message: `Internal link not resolvable yet: ${href}` });
17550
18171
  }
17551
18172
  }
@@ -17594,6 +18215,7 @@ export {
17594
18215
  PRODUCTION_RUNBOOKS_DIR,
17595
18216
  PRODUCTION_RUNBOOK_ARTIFACT_TYPE,
17596
18217
  PlanningConflictError,
18218
+ PlanningNotReadyError,
17597
18219
  ProductionRunbookError,
17598
18220
  REDACTED_COORDINATE,
17599
18221
  RESOURCE_ARTIFACT_TYPE,
@@ -17625,6 +18247,7 @@ export {
17625
18247
  buildImpactReport,
17626
18248
  buildImplementationHandoff,
17627
18249
  buildImportIndex,
18250
+ buildOutcomeVerification,
17628
18251
  buildPocReportContext,
17629
18252
  buildProductionRunbookContext,
17630
18253
  buildProjectExplanation,
@@ -17634,6 +18257,8 @@ export {
17634
18257
  buildSavingsReport,
17635
18258
  buildTopologyEnrichmentHandoff,
17636
18259
  collectImplementationEvidence,
18260
+ completeDeliveryPlan,
18261
+ completeEpic,
17637
18262
  computeContentHash,
17638
18263
  computeEpicProgress,
17639
18264
  computeInitiativeProgress,
@@ -17667,9 +18292,14 @@ export {
17667
18292
  discoverWorkItems,
17668
18293
  enableIntegration,
17669
18294
  environmentSummary,
18295
+ epicOutcomeVerification,
17670
18296
  epicsInPlan,
17671
18297
  evaluateCompletion,
18298
+ evaluateEpicById,
18299
+ evaluateEpicCompletion,
17672
18300
  evaluateInitiativeCompletion,
18301
+ evaluatePlanById,
18302
+ evaluatePlanCompletion,
17673
18303
  exists,
17674
18304
  exportOkf,
17675
18305
  filterSecretPaths,
@@ -17682,14 +18312,17 @@ export {
17682
18312
  getDeprecationPlan,
17683
18313
  getDeprecationPlans,
17684
18314
  getEpic,
18315
+ getEpicCollaboration,
17685
18316
  getExternalWorkItem,
17686
18317
  getImpactCandidates,
17687
18318
  getInitiative,
18319
+ getInitiativeCollaboration,
17688
18320
  getInitiativeContext,
17689
18321
  getIntegration,
17690
18322
  getIntegrationFilters,
17691
18323
  getIntegrationSecretStatus,
17692
18324
  getPlan,
18325
+ getPlanCollaboration,
17693
18326
  getProductionRunbook,
17694
18327
  getResource,
17695
18328
  getResourceReferences,
@@ -17700,8 +18333,10 @@ export {
17700
18333
  getStatus as getTelemetryStatus,
17701
18334
  getWorkItem,
17702
18335
  getWorkItemCaptureDefinition,
18336
+ getWorkItemCollaboration,
17703
18337
  getWorkItemForEdit,
17704
18338
  getWorkItems,
18339
+ getWorkItemsCollaboration,
17705
18340
  getWorkItemsSummary,
17706
18341
  importExternalWorkItem,
17707
18342
  importWorkItem,
@@ -17738,6 +18373,7 @@ export {
17738
18373
  nextInitiativeId,
17739
18374
  nextPlanId2 as nextPlanId,
17740
18375
  nextTargetId,
18376
+ normalizeCriterion,
17741
18377
  observationStatus,
17742
18378
  okfConceptType,
17743
18379
  parseContent,
@@ -17755,11 +18391,16 @@ export {
17755
18391
  persistConsent,
17756
18392
  persistPocReport,
17757
18393
  planIntelligence,
18394
+ planMilestoneVerifications,
18395
+ planOutcomeVerification,
17758
18396
  previewImport,
17759
18397
  projectMode,
17760
18398
  proposeWorkItemCandidates,
17761
18399
  readFile,
17762
18400
  readPocSummary,
18401
+ recordEpicOutcomeVerification,
18402
+ recordMilestoneExitVerification,
18403
+ recordPlanOutcomeVerification,
17763
18404
  redactSecrets,
17764
18405
  removeIntegrationSecret,
17765
18406
  removeTarget,
@@ -17779,6 +18420,8 @@ export {
17779
18420
  targetsEligibleForRemoval,
17780
18421
  targetsPastObservation,
17781
18422
  topologyRevision,
18423
+ transitionDeliveryPlan,
18424
+ transitionEpic,
17782
18425
  transitionInitiative,
17783
18426
  transitionWorkItem,
17784
18427
  updateDeliveryPlan,
@@ -17789,6 +18432,7 @@ export {
17789
18432
  updateResource,
17790
18433
  updateTarget,
17791
18434
  updateWorkItem,
18435
+ updateWorkItemAssignments,
17792
18436
  validateConfigAgainstSchema,
17793
18437
  validateEpicDependencyChange,
17794
18438
  validateOkf,