@kaddo/cli 3.134.0 → 3.136.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-CYNwLGE7.js → architectureDiagram-3BPJPVTR-LjksP4qj.js} +1 -1
  2. package/dist/admin-dist/assets/{chunk-727SXJPM-Cet603Hl.js → chunk-727SXJPM-B9bbDh_M.js} +1 -1
  3. package/dist/admin-dist/assets/{chunk-AQP2D5EJ-8XEHPg3a.js → chunk-AQP2D5EJ-BD776tm_.js} +1 -1
  4. package/dist/admin-dist/assets/{classDiagram-v2-Q7XG4LA2-Bhwb9850.js → classDiagram-4FO5ZUOK-D_59IJDh.js} +1 -1
  5. package/dist/admin-dist/assets/{classDiagram-4FO5ZUOK-Bhwb9850.js → classDiagram-v2-Q7XG4LA2-D_59IJDh.js} +1 -1
  6. package/dist/admin-dist/assets/{dagre-BM42HDAG-DqQXdP8F.js → dagre-BM42HDAG-Bz-INcCu.js} +1 -1
  7. package/dist/admin-dist/assets/{diagram-2AECGRRQ-B1bysbNR.js → diagram-2AECGRRQ-uWqqhcHf.js} +1 -1
  8. package/dist/admin-dist/assets/{diagram-5GNKFQAL-DRifvijh.js → diagram-5GNKFQAL-BanaZANB.js} +1 -1
  9. package/dist/admin-dist/assets/{diagram-LMA3HP47-DajL2Tv-.js → diagram-LMA3HP47-DNXl16UE.js} +1 -1
  10. package/dist/admin-dist/assets/{diagram-OG6HWLK6-WCJo9oL4.js → diagram-OG6HWLK6-BPuwqdOA.js} +1 -1
  11. package/dist/admin-dist/assets/{erDiagram-TEJ5UH35-DwgqKm6b.js → erDiagram-TEJ5UH35-CjHdHiPN.js} +1 -1
  12. package/dist/admin-dist/assets/{flowDiagram-I6XJVG4X-M0kG8sQQ.js → flowDiagram-I6XJVG4X-8LugweYq.js} +1 -1
  13. package/dist/admin-dist/assets/{ganttDiagram-6RSMTGT7-DtyZt9Ti.js → ganttDiagram-6RSMTGT7-T1r39UBo.js} +1 -1
  14. package/dist/admin-dist/assets/index-Cm0J_POl.js +97 -0
  15. package/dist/admin-dist/assets/{infoDiagram-5YYISTIA-Vwdw_1gf.js → infoDiagram-5YYISTIA-Bt5lkett.js} +1 -1
  16. package/dist/admin-dist/assets/{ishikawaDiagram-YF4QCWOH-CIi6B5fy.js → ishikawaDiagram-YF4QCWOH-BAEvG6rZ.js} +1 -1
  17. package/dist/admin-dist/assets/{kanban-definition-UN3LZRKU-5HNFMSQ7.js → kanban-definition-UN3LZRKU-BXlgj75s.js} +1 -1
  18. package/dist/admin-dist/assets/{linear-D3H69r3G.js → linear-CcJpsi8a.js} +1 -1
  19. package/dist/admin-dist/assets/{mindmap-definition-RKZ34NQL-BI0w0H_c.js → mindmap-definition-RKZ34NQL-BDUe2xi4.js} +1 -1
  20. package/dist/admin-dist/assets/{pieDiagram-4H26LBE5-5oMGjRSP.js → pieDiagram-4H26LBE5-Cw_a1v5z.js} +1 -1
  21. package/dist/admin-dist/assets/{quadrantDiagram-W4KKPZXB-Cf4_7xD4.js → quadrantDiagram-W4KKPZXB-CJvWU8a3.js} +1 -1
  22. package/dist/admin-dist/assets/{requirementDiagram-4Y6WPE33-tKyHvrMo.js → requirementDiagram-4Y6WPE33-D-vDruTz.js} +1 -1
  23. package/dist/admin-dist/assets/{sequenceDiagram-3UESZ5HK-XJChOzcT.js → sequenceDiagram-3UESZ5HK-B4PJZymc.js} +1 -1
  24. package/dist/admin-dist/assets/{stateDiagram-AJRCARHV-CG6QHhPz.js → stateDiagram-AJRCARHV-B8K87k9v.js} +1 -1
  25. package/dist/admin-dist/assets/{stateDiagram-v2-BHNVJYJU-COU53r4o.js → stateDiagram-v2-BHNVJYJU-C5Q0Gwxn.js} +1 -1
  26. package/dist/admin-dist/assets/{timeline-definition-PNZ67QCA-CszwARJN.js → timeline-definition-PNZ67QCA-BHQwwDwf.js} +1 -1
  27. package/dist/admin-dist/assets/{vennDiagram-CIIHVFJN-kMR7sGYN.js → vennDiagram-CIIHVFJN-k_l2q31S.js} +1 -1
  28. package/dist/admin-dist/assets/{wardleyDiagram-YWT4CUSO-Cu44stm7.js → wardleyDiagram-YWT4CUSO-CYNfnm_M.js} +1 -1
  29. package/dist/admin-dist/assets/{xychartDiagram-2RQKCTM6-DeU0-PgC.js → xychartDiagram-2RQKCTM6-JF9I5EAO.js} +1 -1
  30. package/dist/admin-dist/index.html +1 -1
  31. package/dist/admin-server/index.js +315 -6
  32. package/dist/core.js +991 -224
  33. package/dist/index.js +1080 -239
  34. package/package.json +1 -1
  35. package/dist/admin-dist/assets/index-CZVvIq5M.js +0 -96
package/dist/core.js CHANGED
@@ -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
  };
@@ -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
  })
@@ -10777,15 +10789,497 @@ import matter13 from "gray-matter";
10777
10789
 
10778
10790
  // src/core/initiative-write.ts
10779
10791
  import matter12 from "gray-matter";
10792
+
10793
+ // src/core/initiative-analysis.ts
10794
+ var SUCCESS_HEADING_RE = /^#{1,6}\s*(success criteria|criterios de[ét]xito|criterios de éxito)\s*$/i;
10795
+ var HEADING_RE2 = /^#{1,6}\s+/;
10796
+ var CHECK_ITEM_RE = /^\s*[-*]\s+\[([ xX])\]\s+(.*)$/;
10797
+ var BULLET_RE2 = /^\s*[-*]\s+(.*)$/;
10798
+ var PLACEHOLDER_RE = /^_.*_$/;
10799
+ function parseSuccessCriteria(body) {
10800
+ const lines = body.split(/\r?\n/);
10801
+ const out = [];
10802
+ let capture = false;
10803
+ for (const line of lines) {
10804
+ if (capture && HEADING_RE2.test(line)) break;
10805
+ if (!capture) {
10806
+ if (SUCCESS_HEADING_RE.test(line.trim())) capture = true;
10807
+ continue;
10808
+ }
10809
+ const check = line.match(CHECK_ITEM_RE);
10810
+ if (check) {
10811
+ const text2 = check[2].trim();
10812
+ if (text2 && !PLACEHOLDER_RE.test(text2)) {
10813
+ out.push({ text: text2, checked: check[1].toLowerCase() === "x" });
10814
+ }
10815
+ continue;
10816
+ }
10817
+ const bullet = line.match(BULLET_RE2);
10818
+ if (bullet) {
10819
+ const text2 = bullet[1].trim();
10820
+ if (text2 && !PLACEHOLDER_RE.test(text2)) out.push({ text: text2, checked: null });
10821
+ }
10822
+ }
10823
+ return out;
10824
+ }
10825
+ function analyzeInitiative(dir, ini) {
10826
+ const progress = computeInitiativeProgress(dir, ini);
10827
+ const successCriteria = parseSuccessCriteria(ini.body);
10828
+ const pendingCandidates = ini.candidates.filter((c) => !c.materializedAs);
10829
+ const associated = associatedWorkItems(dir, ini.id);
10830
+ const findings = [];
10831
+ if (successCriteria.length === 0) {
10832
+ findings.push({
10833
+ code: "no-success-criteria",
10834
+ severity: "warning",
10835
+ message: "The Initiative has no explicit Success Criteria; completion cannot be judged by outcome, only by delivery."
10836
+ });
10837
+ } else {
10838
+ const uncovered = successCriteria.filter((c) => c.checked === false);
10839
+ if (uncovered.length > 0) {
10840
+ findings.push({
10841
+ code: "uncovered-success-criteria",
10842
+ severity: "blocking",
10843
+ message: `${uncovered.length} success criterion/criteria remain uncovered.`,
10844
+ items: uncovered.map((c) => c.text)
10845
+ });
10846
+ }
10847
+ }
10848
+ if (pendingCandidates.length > 0) {
10849
+ findings.push({
10850
+ code: "pending-candidates",
10851
+ severity: "blocking",
10852
+ message: `${pendingCandidates.length} committed candidate(s) not yet materialized into Work Items.`,
10853
+ items: pendingCandidates.map((c) => `${c.id}: ${c.title}`)
10854
+ });
10855
+ }
10856
+ const notCompleted = associated.filter((w) => w.status !== "completed" && w.status !== "archived");
10857
+ if (associated.length === 0) {
10858
+ findings.push({
10859
+ code: "no-delivery",
10860
+ severity: "info",
10861
+ message: "No Work Items are associated with this Initiative yet."
10862
+ });
10863
+ } else if (notCompleted.length > 0) {
10864
+ findings.push({
10865
+ code: "incomplete-delivery",
10866
+ severity: "blocking",
10867
+ message: `${notCompleted.length} associated Work Item(s) are not completed.`,
10868
+ items: notCompleted.map((w) => `${w.id} (${w.status})`)
10869
+ });
10870
+ }
10871
+ return {
10872
+ initiative: ini.id,
10873
+ status: ini.status,
10874
+ progress,
10875
+ successCriteria,
10876
+ pendingCandidates,
10877
+ findings,
10878
+ suggestedCandidates: pendingCandidates
10879
+ };
10880
+ }
10881
+
10882
+ // src/core/delivery-verification.ts
10883
+ function normalizeCriterion(text2) {
10884
+ return text2.trim().toLowerCase().replace(/\s+/g, " ");
10885
+ }
10886
+ var STATUSES = ["passed", "failed", "not-verified", "manual-review-required"];
10887
+ function optStr4(v) {
10888
+ if (typeof v === "string" && v.trim()) return v.trim();
10889
+ if (typeof v === "number") return String(v);
10890
+ return void 0;
10891
+ }
10892
+ function parseEvidenceList(raw) {
10893
+ if (!Array.isArray(raw)) return [];
10894
+ const out = [];
10895
+ for (const entry of raw) {
10896
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
10897
+ const o = entry;
10898
+ const criterion = optStr4(o.criterion);
10899
+ if (!criterion) continue;
10900
+ const statusRaw = optStr4(o.status);
10901
+ const status = STATUSES.includes(statusRaw ?? "") ? statusRaw : "not-verified";
10902
+ const method = optStr4(o.method);
10903
+ out.push({
10904
+ criterion,
10905
+ status,
10906
+ ...optStr4(o.evidence) ? { evidence: optStr4(o.evidence) } : {},
10907
+ ...optStr4(o.reference) ? { reference: optStr4(o.reference) } : {},
10908
+ ...method === "automated" || method === "manual" ? { method } : {},
10909
+ ...optStr4(o.verified_at) ? { verified_at: optStr4(o.verified_at) } : {},
10910
+ ...optStr4(o.verified_by) ? { verified_by: optStr4(o.verified_by) } : {}
10911
+ });
10912
+ }
10913
+ return out;
10914
+ }
10915
+ function parseExceptions(raw) {
10916
+ if (!Array.isArray(raw)) return [];
10917
+ const out = [];
10918
+ for (const entry of raw) {
10919
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
10920
+ const o = entry;
10921
+ const id = optStr4(o.id);
10922
+ if (!id) continue;
10923
+ const st = optStr4(o.status);
10924
+ const status = st === "accepted" || st === "rejected" ? st : "proposed";
10925
+ out.push({
10926
+ id,
10927
+ status,
10928
+ ...optStr4(o.criterion) ? { criterion: optStr4(o.criterion) } : {},
10929
+ ...optStr4(o.reason) ? { reason: optStr4(o.reason) } : {}
10930
+ });
10931
+ }
10932
+ return out;
10933
+ }
10934
+ function buildOutcomeVerification(declared, evidence, exceptions = []) {
10935
+ const byCriterion = /* @__PURE__ */ new Map();
10936
+ for (const e of evidence) byCriterion.set(normalizeCriterion(e.criterion), e);
10937
+ const declaredKeys = new Set(declared.map(normalizeCriterion));
10938
+ const counts = /* @__PURE__ */ new Map();
10939
+ for (const c of declared) counts.set(normalizeCriterion(c), (counts.get(normalizeCriterion(c)) ?? 0) + 1);
10940
+ const ambiguousKeys = new Set([...counts.entries()].filter(([, n]) => n > 1).map(([k]) => k));
10941
+ const waived = new Set(
10942
+ 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))
10943
+ );
10944
+ const criteria = declared.map((criterion) => {
10945
+ const key = normalizeCriterion(criterion);
10946
+ const ambiguous = ambiguousKeys.has(key);
10947
+ const e = ambiguous ? void 0 : byCriterion.get(key);
10948
+ return {
10949
+ criterion,
10950
+ status: e?.status ?? "not-verified",
10951
+ ...e?.evidence ? { evidence: e.evidence } : {},
10952
+ ...e?.reference ? { reference: e.reference } : {},
10953
+ ...e?.method ? { method: e.method } : {},
10954
+ ...e?.verified_at ? { verifiedAt: e.verified_at } : {},
10955
+ ...e?.verified_by ? { verifiedBy: e.verified_by } : {},
10956
+ ...!ambiguous && waived.has(key) ? { waived: true } : {},
10957
+ ...ambiguous ? { ambiguous: true } : {}
10958
+ };
10959
+ });
10960
+ const stale = evidence.filter((e) => !declaredKeys.has(normalizeCriterion(e.criterion)));
10961
+ return {
10962
+ total: criteria.length,
10963
+ // An ambiguous criterion is never counted as passed/waived; it counts as unverified until disambiguated.
10964
+ passed: criteria.filter((c) => !c.ambiguous && (c.status === "passed" || c.waived)).length,
10965
+ failed: criteria.filter((c) => !c.ambiguous && c.status === "failed" && !c.waived).length,
10966
+ notVerified: criteria.filter((c) => c.ambiguous || c.status === "not-verified" && !c.waived).length,
10967
+ manualReview: criteria.filter((c) => !c.ambiguous && c.status === "manual-review-required" && !c.waived).length,
10968
+ ambiguous: criteria.filter((c) => c.ambiguous).length,
10969
+ criteria,
10970
+ stale
10971
+ };
10972
+ }
10973
+ function fm(entity, key) {
10974
+ return entity.rawFrontmatter?.[key];
10975
+ }
10976
+ function epicOutcomeVerification(epic) {
10977
+ return buildOutcomeVerification(
10978
+ epic.successCriteria,
10979
+ parseEvidenceList(fm(epic, "outcome_verifications")),
10980
+ parseExceptions(fm(epic, "completion_exceptions"))
10981
+ );
10982
+ }
10983
+ function planOutcomeVerification(plan) {
10984
+ return buildOutcomeVerification(
10985
+ plan.successCriteria,
10986
+ parseEvidenceList(fm(plan, "outcome_verifications")),
10987
+ parseExceptions(fm(plan, "completion_exceptions"))
10988
+ );
10989
+ }
10990
+ function planMilestoneVerifications(plan) {
10991
+ const rawMs = Array.isArray(fm(plan, "milestones")) ? fm(plan, "milestones") : [];
10992
+ return plan.milestones.map((m) => {
10993
+ const rawEntry = rawMs.find((r) => r && typeof r === "object" && optStr4(r.id)?.toLowerCase() === m.id.toLowerCase());
10994
+ const evidence = parseEvidenceList(rawEntry?.exit_verifications);
10995
+ return { id: m.id, title: m.title, outcome: buildOutcomeVerification(m.exitCriteria, evidence) };
10996
+ });
10997
+ }
10998
+ function decide(blockers, softBlocks, hasAcceptedExceptions) {
10999
+ if (blockers.length > 0) return "BLOCKED";
11000
+ if (softBlocks.length > 0) return "NEEDS_WORK";
11001
+ return hasAcceptedExceptions ? "READY_WITH_EXCEPTIONS" : "READY_TO_COMPLETE";
11002
+ }
11003
+ function evaluateEpicCompletion(dir, epic) {
11004
+ const prog = computeEpicProgress(dir, epic);
11005
+ const exceptions = parseExceptions(fm(epic, "completion_exceptions"));
11006
+ const outcome = epicOutcomeVerification(epic);
11007
+ const blockers = [];
11008
+ const softBlocks = [];
11009
+ const reasons = [];
11010
+ const warnings = [];
11011
+ for (const d of prog.readiness.blockingDependencies) blockers.push(`Blocked by unfinished dependency ${d}.`);
11012
+ for (const f of integrityBlockers(dir, epic.id)) blockers.push(f);
11013
+ evaluateOutcomeInto(epic.outcome, true, outcome, blockers, softBlocks, reasons, warnings);
11014
+ if (prog.delivery.total > 0 && prog.delivery.completed < prog.delivery.total) {
11015
+ softBlocks.push("committed-work-incomplete");
11016
+ reasons.push(`Committed work is incomplete (${prog.delivery.completed}/${prog.delivery.total} Work Items completed).`);
11017
+ }
11018
+ const readiness = decide(blockers, softBlocks, exceptions.some((x) => x.status === "accepted"));
11019
+ pushReadinessReason(readiness, reasons);
11020
+ return {
11021
+ id: epic.id,
11022
+ kind: "epic",
11023
+ status: epic.status,
11024
+ readiness,
11025
+ reasons,
11026
+ blockers,
11027
+ warnings,
11028
+ outcome,
11029
+ delivery: { total: prog.delivery.total, completed: prog.delivery.completed, blocked: prog.delivery.blocked },
11030
+ blockingDependencies: prog.readiness.blockingDependencies,
11031
+ exceptions
11032
+ };
11033
+ }
11034
+ function evaluatePlanCompletion(dir, plan) {
11035
+ const prog = computePlanProgress(dir, plan);
11036
+ const exceptions = parseExceptions(fm(plan, "completion_exceptions"));
11037
+ const outcome = planOutcomeVerification(plan);
11038
+ const milestones = planMilestoneVerifications(plan);
11039
+ const epics = epicsInPlan(dir, plan.id).map((e) => ({ id: e.id, status: e.status }));
11040
+ const blockers = [];
11041
+ const softBlocks = [];
11042
+ const reasons = [];
11043
+ const warnings = [];
11044
+ for (const d of prog.readiness.blockingDependencies) blockers.push(`Blocked by unfinished dependency ${d}.`);
11045
+ for (const f of integrityBlockers(dir, plan.id)) blockers.push(f);
11046
+ evaluateOutcomeInto(plan.objective, false, outcome, blockers, softBlocks, reasons, warnings);
11047
+ if (!plan.objective) warnings.push("No objective is declared for this Plan (optional, but recommended for completion review).");
11048
+ if (prog.delivery.total > 0 && prog.delivery.completed < prog.delivery.total) {
11049
+ softBlocks.push("committed-work-incomplete");
11050
+ reasons.push(`Committed work is incomplete (${prog.delivery.completed}/${prog.delivery.total} Work Items completed).`);
11051
+ }
11052
+ if (epics.length === 0 && prog.delivery.total === 0) {
11053
+ softBlocks.push("no-committed-work");
11054
+ reasons.push("No Epics and no committed Work Items \u2014 the Plan has no verifiable deliverables yet.");
11055
+ }
11056
+ const openEpics = epics.filter((e) => e.status !== "completed" && e.status !== "cancelled");
11057
+ if (openEpics.length > 0) {
11058
+ softBlocks.push("epics-open");
11059
+ reasons.push(`${openEpics.length} Epic(s) not yet completed: ${openEpics.map((e) => e.id).join(", ")}.`);
11060
+ }
11061
+ for (const m of milestones) {
11062
+ if (m.outcome.failed > 0) {
11063
+ blockers.push(`Milestone ${m.id} has a failed exit criterion.`);
11064
+ }
11065
+ const pending = m.outcome.notVerified + m.outcome.manualReview;
11066
+ if (pending > 0) {
11067
+ softBlocks.push(`milestone-${m.id}-pending`);
11068
+ reasons.push(`Milestone ${m.id}: ${pending} exit criterion(s) not verified.`);
11069
+ }
11070
+ if (m.outcome.stale.length > 0) warnings.push(`Milestone ${m.id} has stale exit-criteria evidence.`);
11071
+ }
11072
+ const readiness = decide(blockers, softBlocks, exceptions.some((x) => x.status === "accepted"));
11073
+ pushReadinessReason(readiness, reasons);
11074
+ return {
11075
+ id: plan.id,
11076
+ kind: "plan",
11077
+ status: plan.status,
11078
+ readiness,
11079
+ reasons,
11080
+ blockers,
11081
+ warnings,
11082
+ outcome,
11083
+ delivery: { total: prog.delivery.total, completed: prog.delivery.completed, blocked: prog.delivery.blocked },
11084
+ blockingDependencies: prog.readiness.blockingDependencies,
11085
+ milestones,
11086
+ epics,
11087
+ exceptions
11088
+ };
11089
+ }
11090
+ function integrityBlockers(dir, subjectId) {
11091
+ return validatePlanningGraph(dir).filter((f) => f.level === "error" && f.subject.toLowerCase() === subjectId.toLowerCase()).map((f) => f.message);
11092
+ }
11093
+ function evaluateOutcomeInto(declaredOutcome, requireDeclaredOutcome, outcome, blockers, softBlocks, reasons, warnings) {
11094
+ if (requireDeclaredOutcome && !declaredOutcome) {
11095
+ softBlocks.push("no-outcome");
11096
+ reasons.push("No expected outcome is declared.");
11097
+ }
11098
+ if (outcome.total === 0) {
11099
+ softBlocks.push("no-success-criteria");
11100
+ reasons.push("No success criteria to verify \u2014 completion cannot be judged by outcome.");
11101
+ }
11102
+ if (outcome.ambiguous > 0) {
11103
+ softBlocks.push("criteria-ambiguous");
11104
+ reasons.push(`${outcome.ambiguous} success criterion(s) collide in text \u2014 rename to disambiguate before verifying.`);
11105
+ }
11106
+ if (outcome.failed > 0) {
11107
+ softBlocks.push("criteria-failed");
11108
+ reasons.push(`${outcome.failed} success criterion(s) failed verification.`);
11109
+ }
11110
+ const pending = outcome.notVerified + outcome.manualReview - outcome.ambiguous;
11111
+ if (pending > 0) {
11112
+ softBlocks.push("criteria-unverified");
11113
+ reasons.push(`${pending} success criterion(s) not verified (no or insufficient evidence).`);
11114
+ }
11115
+ if (outcome.stale.length > 0) warnings.push(`${outcome.stale.length} evidence record(s) no longer match a declared criterion (stale).`);
11116
+ }
11117
+ function pushReadinessReason(readiness, reasons) {
11118
+ if (readiness === "READY_TO_COMPLETE") reasons.unshift("All success criteria are verified and committed work is complete. Human approval is still required to close.");
11119
+ else if (readiness === "READY_WITH_EXCEPTIONS") reasons.unshift("Remaining gaps are covered by accepted exceptions. Human approval is still required to close.");
11120
+ }
11121
+ function evaluateEpicById(dir, id) {
11122
+ const e = getEpic(dir, id);
11123
+ return e ? evaluateEpicCompletion(dir, e) : null;
11124
+ }
11125
+ function evaluatePlanById(dir, id) {
11126
+ const p = getPlan(dir, id);
11127
+ return p ? evaluatePlanCompletion(dir, p) : null;
11128
+ }
11129
+
11130
+ // src/core/initiative-verification.ts
11131
+ function optStr5(v) {
11132
+ return typeof v === "string" && v.trim() ? v.trim() : void 0;
11133
+ }
11134
+ function parseCompletionExceptions(raw) {
11135
+ if (!Array.isArray(raw)) return [];
11136
+ const out = [];
11137
+ for (const entry of raw) {
11138
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
11139
+ const o = entry;
11140
+ const id = optStr5(o.id);
11141
+ if (!id) continue;
11142
+ const st = optStr5(o.status);
11143
+ out.push({
11144
+ id,
11145
+ status: st === "accepted" || st === "rejected" ? st : "proposed",
11146
+ ...optStr5(o.criterion) ? { criterion: optStr5(o.criterion) } : {},
11147
+ ...optStr5(o.reason) ? { reason: optStr5(o.reason) } : {}
11148
+ });
11149
+ }
11150
+ return out;
11151
+ }
11152
+ function initiativeOutcomeVerification(ini) {
11153
+ const declared = parseSuccessCriteria(ini.body).map((c) => c.text);
11154
+ const evidence = parseEvidenceList(ini.rawFrontmatter?.outcome_verifications);
11155
+ const exceptions = parseCompletionExceptions(ini.rawFrontmatter?.completion_exceptions);
11156
+ return buildOutcomeVerification(declared, evidence, exceptions);
11157
+ }
11158
+ function initiativeProvenanceIssues(dir, ini) {
11159
+ const issues = [];
11160
+ const wis = discoverWorkItems(dir);
11161
+ for (const c of ini.candidates) {
11162
+ if (!c.materializedAs) continue;
11163
+ const wi = wis.find((w) => w.id.toLowerCase() === c.materializedAs.toLowerCase());
11164
+ if (!wi) {
11165
+ issues.push(`Candidate ${c.id} points at missing Work Item ${c.materializedAs}.`);
11166
+ continue;
11167
+ }
11168
+ const owner = typeof wi.rawFrontmatter?.initiative === "string" ? wi.rawFrontmatter.initiative : void 0;
11169
+ if (owner && owner.toLowerCase() !== ini.id.toLowerCase()) {
11170
+ issues.push(`Work Item ${wi.id} (materialized from ${c.id}) is associated with ${owner}, not ${ini.id}.`);
11171
+ }
11172
+ }
11173
+ return issues;
11174
+ }
11175
+ function decide2(blockers, softBlocks, hasAcceptedExceptions) {
11176
+ if (blockers.length > 0) return "BLOCKED";
11177
+ if (softBlocks.length > 0) return "NEEDS_WORK";
11178
+ return hasAcceptedExceptions ? "READY_WITH_EXCEPTIONS" : "READY_TO_COMPLETE";
11179
+ }
11180
+ function evaluateInitiativeCompletion(dir, ini) {
11181
+ const progress = computeInitiativeProgress(dir, ini);
11182
+ const outcome = initiativeOutcomeVerification(ini);
11183
+ const exceptions = parseCompletionExceptions(ini.rawFrontmatter?.completion_exceptions);
11184
+ const pending = ini.candidates.filter((c) => !c.materializedAs);
11185
+ const associated = associatedWorkItems(dir, ini.id);
11186
+ const incomplete = associated.filter((w) => w.status !== "completed" && w.status !== "archived");
11187
+ const provenanceIssues = initiativeProvenanceIssues(dir, ini);
11188
+ const blockers = [];
11189
+ const softBlocks = [];
11190
+ const reasons = [];
11191
+ const warnings = [];
11192
+ for (const p of provenanceIssues) blockers.push(p);
11193
+ if (outcome.total === 0) {
11194
+ softBlocks.push("no-success-criteria");
11195
+ reasons.push("No success criteria to verify \u2014 completion cannot be judged by outcome.");
11196
+ }
11197
+ if (outcome.ambiguous > 0) {
11198
+ softBlocks.push("criteria-ambiguous");
11199
+ reasons.push(`${outcome.ambiguous} success criterion(s) collide in text \u2014 disambiguate before verifying.`);
11200
+ }
11201
+ if (outcome.failed > 0) {
11202
+ softBlocks.push("criteria-failed");
11203
+ reasons.push(`${outcome.failed} success criterion(s) failed verification.`);
11204
+ }
11205
+ const unverified = outcome.notVerified + outcome.manualReview - outcome.ambiguous;
11206
+ if (unverified > 0) {
11207
+ softBlocks.push("criteria-unverified");
11208
+ reasons.push(`${unverified} success criterion(s) not verified (no or insufficient evidence).`);
11209
+ }
11210
+ if (outcome.stale.length > 0) warnings.push(`${outcome.stale.length} evidence record(s) no longer match a declared criterion (stale).`);
11211
+ if (pending.length > 0) {
11212
+ softBlocks.push("pending-candidates");
11213
+ reasons.push(`${pending.length} committed candidate(s) not yet materialized.`);
11214
+ }
11215
+ if (incomplete.length > 0) {
11216
+ softBlocks.push("incomplete-delivery");
11217
+ reasons.push(`${incomplete.length} associated Work Item(s) are not completed.`);
11218
+ }
11219
+ if (associated.length === 0 && pending.length === 0) {
11220
+ softBlocks.push("no-deliverables");
11221
+ reasons.push("Nothing has been delivered or committed under this Initiative.");
11222
+ }
11223
+ const readiness = decide2(blockers, softBlocks, exceptions.some((x) => x.status === "accepted"));
11224
+ if (readiness === "READY_TO_COMPLETE") reasons.unshift("All success criteria are verified and committed scope is delivered. Human approval is still required to close.");
11225
+ else if (readiness === "READY_WITH_EXCEPTIONS") reasons.unshift("Remaining gaps are covered by accepted exceptions. Human approval is still required to close.");
11226
+ const completed = progress.delivery.byState?.completed ?? 0;
11227
+ return {
11228
+ id: ini.id,
11229
+ kind: "initiative",
11230
+ status: ini.status,
11231
+ readiness,
11232
+ ready: readiness === "READY_TO_COMPLETE" || readiness === "READY_WITH_EXCEPTIONS",
11233
+ reasons,
11234
+ blockers,
11235
+ warnings,
11236
+ outcome,
11237
+ delivery: { total: progress.delivery.total, completed, incomplete: incomplete.length },
11238
+ pendingCandidates: pending.map((c) => c.id),
11239
+ provenanceIssues,
11240
+ exceptions
11241
+ };
11242
+ }
11243
+ function evaluateInitiativeById(dir, id) {
11244
+ const ini = getInitiative(dir, id);
11245
+ return ini ? evaluateInitiativeCompletion(dir, ini) : null;
11246
+ }
11247
+
11248
+ // src/core/initiative-write.ts
10780
11249
  var WORK_ITEMS_DIR = "knowledge/delivery/work-items";
10781
11250
  var DRAFT_DIR = `${WORK_ITEMS_DIR}/draft`;
10782
11251
  var ROADMAP_PATH2 = "knowledge/delivery/roadmap.md";
11252
+ function assertFreshInitiative(id, currentContent, opts) {
11253
+ if (!opts?.expectedRevision) return;
11254
+ const actual = revisionOf(currentContent);
11255
+ if (actual !== opts.expectedRevision) throw new InitiativeConflictError(id, opts.expectedRevision, actual);
11256
+ }
11257
+ function nextCandidateId(existing) {
11258
+ let max = 0;
11259
+ for (const c of existing) {
11260
+ const m = typeof c?.id === "string" ? c.id.match(/^WI-CANDIDATE-(\d+)$/i) : null;
11261
+ if (m) max = Math.max(max, Number.parseInt(m[1], 10));
11262
+ }
11263
+ return `WI-CANDIDATE-${String(max + 1).padStart(3, "0")}`;
11264
+ }
10783
11265
  var InitiativeWriteError = class extends Error {
10784
11266
  constructor(message) {
10785
11267
  super(message);
10786
11268
  this.name = "InitiativeWriteError";
10787
11269
  }
10788
11270
  };
11271
+ var InitiativeConflictError = class extends InitiativeWriteError {
11272
+ constructor(id, expectedRevision, actualRevision) {
11273
+ super(`Initiative "${id}" was modified since it was loaded (expected revision ${expectedRevision}, found ${actualRevision}). Reload and try again.`);
11274
+ this.id = id;
11275
+ this.expectedRevision = expectedRevision;
11276
+ this.actualRevision = actualRevision;
11277
+ this.name = "InitiativeConflictError";
11278
+ }
11279
+ id;
11280
+ expectedRevision;
11281
+ actualRevision;
11282
+ };
10789
11283
  function slugify2(s) {
10790
11284
  return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 50);
10791
11285
  }
@@ -10907,32 +11401,47 @@ function createInitiative(dir, input) {
10907
11401
  if (!ini) throw new InitiativeWriteError("Failed to parse the Initiative just written.");
10908
11402
  return ini;
10909
11403
  }
10910
- function transitionInitiative(dir, id, to) {
11404
+ function transitionInitiative(dir, id, to, opts) {
10911
11405
  const ini = getInitiative(dir, id);
10912
11406
  if (!ini) throw new InitiativeWriteError(`Initiative ${id} not found.`);
10913
11407
  if (!isValidInitiativeStatus(to)) throw new InitiativeWriteError(`Invalid status: ${to}.`);
11408
+ if (to === "completed") throw new InitiativeWriteError(`Completing Initiative ${id} requires evidence-based review \u2014 use completeInitiative.`);
10914
11409
  if (ini.status === to) return ini;
10915
11410
  if (!isValidInitiativeTransition(ini.status, to)) {
10916
11411
  throw new InitiativeWriteError(`Invalid transition ${ini.status} \u2192 ${to}.`);
10917
11412
  }
10918
11413
  const raw = readFile(ini.filePath);
11414
+ assertFreshInitiative(ini.id, raw, opts);
10919
11415
  const { data, content } = matter12(raw, {});
10920
11416
  data.status = to;
10921
- if (to === "completed") data.completed_at = today();
10922
11417
  const newContent = matter12.stringify(content, data);
10923
11418
  writeFile(ini.filePath, newContent);
10924
11419
  const updated = parseInitiative(dir, ini.filePath, newContent);
10925
11420
  if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after transition.");
10926
11421
  return updated;
10927
11422
  }
10928
- function addCandidate(dir, id, candidate) {
11423
+ function findMaterializedWorkItem(dir, initiativeId, candidateId) {
11424
+ for (const wi of discoverWorkItems(dir)) {
11425
+ const fm2 = wi.rawFrontmatter ?? {};
11426
+ const si = typeof fm2.source_initiative === "string" ? fm2.source_initiative : void 0;
11427
+ const sid = typeof fm2.source_id === "string" ? fm2.source_id : void 0;
11428
+ if (si?.toLowerCase() === initiativeId.toLowerCase() && sid === candidateId) {
11429
+ return { id: wi.id, initiative: typeof fm2.initiative === "string" ? fm2.initiative : void 0 };
11430
+ }
11431
+ }
11432
+ return null;
11433
+ }
11434
+ function addCandidate(dir, id, candidate, opts) {
10929
11435
  const ini = getInitiative(dir, id);
10930
11436
  if (!ini) throw new InitiativeWriteError(`Initiative ${id} not found.`);
10931
11437
  const raw = readFile(ini.filePath);
11438
+ assertFreshInitiative(ini.id, raw, opts);
10932
11439
  const { data, content } = matter12(raw, {});
10933
11440
  const existing = Array.isArray(data.candidates) ? data.candidates : [];
10934
- const fallbackId = `WI-CANDIDATE-${String(existing.length + 1).padStart(3, "0")}`;
11441
+ const removed = Array.isArray(data.removed_candidates) ? data.removed_candidates : [];
11442
+ const fallbackId = nextCandidateId([...existing, ...removed]);
10935
11443
  const normalized = normalizeCandidate(candidate, fallbackId);
11444
+ normalized.materializedAs = null;
10936
11445
  if (ini.candidates.some((c) => c.id === normalized.id)) {
10937
11446
  throw new InitiativeWriteError(`Candidate ${normalized.id} already exists in ${id}.`);
10938
11447
  }
@@ -10943,11 +11452,46 @@ function addCandidate(dir, id, candidate) {
10943
11452
  if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after adding a candidate.");
10944
11453
  return updated;
10945
11454
  }
10946
- function updateInitiative(dir, id, patch) {
11455
+ function replaceBodySection(body, heading, newContent) {
11456
+ const lines = body.split(/\r?\n/);
11457
+ const want = heading.trim().toLowerCase();
11458
+ let start = -1;
11459
+ let level = 0;
11460
+ for (let i = 0; i < lines.length; i++) {
11461
+ const h = lines[i].match(/^(#{1,6})\s+(.*)$/);
11462
+ if (h && h[2].trim().toLowerCase() === want) {
11463
+ start = i;
11464
+ level = h[1].length;
11465
+ break;
11466
+ }
11467
+ }
11468
+ const block = `${"#".repeat(level || 2)} ${heading.trim()}
11469
+
11470
+ ${newContent.trim()}
11471
+ `;
11472
+ if (start === -1) {
11473
+ return `${body.trimEnd()}
11474
+
11475
+ ${block}`;
11476
+ }
11477
+ let end = lines.length;
11478
+ for (let i = start + 1; i < lines.length; i++) {
11479
+ const h = lines[i].match(/^(#{1,6})\s+/);
11480
+ if (h && h[1].length <= level) {
11481
+ end = i;
11482
+ break;
11483
+ }
11484
+ }
11485
+ const before = lines.slice(0, start).join("\n").replace(/\s+$/, "");
11486
+ const after = lines.slice(end).join("\n").replace(/^\s+/, "");
11487
+ return [before, before ? "" : null, block.trimEnd(), after ? "" : null, after].filter((x) => x !== null).join("\n").replace(/\n{3,}/g, "\n\n");
11488
+ }
11489
+ function updateInitiative(dir, id, patch, opts) {
10947
11490
  const ini = getInitiative(dir, id);
10948
11491
  if (!ini) throw new InitiativeWriteError(`Initiative ${id} not found.`);
10949
11492
  const raw = readFile(ini.filePath);
10950
- const { data, content } = matter12(raw, {});
11493
+ assertFreshInitiative(ini.id, raw, opts);
11494
+ let { data, content } = matter12(raw, {});
10951
11495
  if (patch.title !== void 0) {
10952
11496
  if (!patch.title.trim()) throw new InitiativeWriteError("Initiative title cannot be empty.");
10953
11497
  data.title = patch.title.trim();
@@ -10963,12 +11507,63 @@ function updateInitiative(dir, id, patch) {
10963
11507
  }
10964
11508
  if (patch.owners !== void 0) data.owners = patch.owners.map((o) => o.trim()).filter(Boolean);
10965
11509
  if (patch.contributors !== void 0) data.contributors = patch.contributors.map((c) => c.trim()).filter(Boolean);
11510
+ if (patch.sections) {
11511
+ for (const [heading, value] of Object.entries(patch.sections)) content = replaceBodySection(content, heading, value);
11512
+ }
10966
11513
  const newContent = matter12.stringify(content, data);
10967
11514
  writeFile(ini.filePath, newContent);
10968
11515
  const updated = parseInitiative(dir, ini.filePath, newContent);
10969
11516
  if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after update.");
10970
11517
  return updated;
10971
11518
  }
11519
+ function updateCandidate(dir, id, candidateId, patch, opts) {
11520
+ const ini = getInitiative(dir, id);
11521
+ if (!ini) throw new InitiativeWriteError(`Initiative ${id} not found.`);
11522
+ const current = ini.candidates.find((c) => c.id === candidateId);
11523
+ if (!current) throw new InitiativeWriteError(`Candidate ${candidateId} not found in ${id}.`);
11524
+ if (current.materializedAs) throw new InitiativeWriteError(`Candidate ${candidateId} is materialized as ${current.materializedAs}; edit the Work Item instead.`);
11525
+ const raw = readFile(ini.filePath);
11526
+ assertFreshInitiative(ini.id, raw, opts);
11527
+ const { data, content } = matter12(raw, {});
11528
+ const cands = Array.isArray(data.candidates) ? data.candidates : [];
11529
+ const entry = cands.find((c) => c && typeof c === "object" && String(c.id) === candidateId);
11530
+ if (!entry) throw new InitiativeWriteError(`Candidate ${candidateId} entry not found in ${id} frontmatter.`);
11531
+ if (patch.title !== void 0) entry.title = patch.title.trim();
11532
+ if (patch.type !== void 0) entry.type = patch.type?.trim() || void 0;
11533
+ if (patch.suggestedKnowledgeLevel !== void 0) entry.suggested_knowledge_level = patch.suggestedKnowledgeLevel?.trim() || void 0;
11534
+ if (patch.expectedValue !== void 0) entry.expected_value = patch.expectedValue?.trim() || void 0;
11535
+ if (patch.notes !== void 0) entry.notes = patch.notes?.trim() || void 0;
11536
+ if (patch.sourceSignals !== void 0) entry.source_signals = patch.sourceSignals;
11537
+ if (patch.dependencies !== void 0) entry.dependencies = patch.dependencies;
11538
+ for (const k of Object.keys(entry)) if (entry[k] === void 0) delete entry[k];
11539
+ data.candidates = cands;
11540
+ const newContent = matter12.stringify(content, data);
11541
+ writeFile(ini.filePath, newContent);
11542
+ const updated = parseInitiative(dir, ini.filePath, newContent);
11543
+ if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after editing a candidate.");
11544
+ return updated;
11545
+ }
11546
+ function removeCandidate(dir, id, candidateId, reason, opts) {
11547
+ if (!reason?.trim()) throw new InitiativeWriteError("A justification is required to remove a candidate.");
11548
+ const ini = getInitiative(dir, id);
11549
+ if (!ini) throw new InitiativeWriteError(`Initiative ${id} not found.`);
11550
+ const current = ini.candidates.find((c) => c.id === candidateId);
11551
+ if (!current) throw new InitiativeWriteError(`Candidate ${candidateId} not found in ${id}.`);
11552
+ if (current.materializedAs) throw new InitiativeWriteError(`Candidate ${candidateId} is materialized as ${current.materializedAs}; it cannot be removed from scope.`);
11553
+ const raw = readFile(ini.filePath);
11554
+ assertFreshInitiative(ini.id, raw, opts);
11555
+ const { data, content } = matter12(raw, {});
11556
+ const cands = Array.isArray(data.candidates) ? data.candidates : [];
11557
+ data.candidates = cands.filter((c) => !(c && typeof c === "object" && String(c.id) === candidateId));
11558
+ const log2 = Array.isArray(data.removed_candidates) ? data.removed_candidates : [];
11559
+ log2.push({ id: candidateId, title: current.title, reason: reason.trim(), removed_at: today() });
11560
+ data.removed_candidates = log2;
11561
+ const newContent = matter12.stringify(content, data);
11562
+ writeFile(ini.filePath, newContent);
11563
+ const updated = parseInitiative(dir, ini.filePath, newContent);
11564
+ if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after removing a candidate.");
11565
+ return updated;
11566
+ }
10972
11567
  function addExternalLink(dir, id, link) {
10973
11568
  const ini = getInitiative(dir, id);
10974
11569
  if (!ini) throw new InitiativeWriteError(`Initiative ${id} not found.`);
@@ -11055,32 +11650,43 @@ function buildWorkItemContent(wiId, iniId, candidate) {
11055
11650
  ].join("\n");
11056
11651
  return matter12.stringify("\n" + body, data);
11057
11652
  }
11058
- function materializeCandidate(dir, id, candidateId) {
11653
+ function setCandidateMaterialized(dir, ini, candidateId, wiId) {
11654
+ const raw = readFile(ini.filePath);
11655
+ const { data, content } = matter12(raw, {});
11656
+ const cands = Array.isArray(data.candidates) ? data.candidates : [];
11657
+ for (const c of cands) if (c && typeof c === "object" && String(c.id) === candidateId) c.materialized_as = wiId;
11658
+ data.candidates = cands;
11659
+ const newContent = matter12.stringify(content, data);
11660
+ writeFile(ini.filePath, newContent);
11661
+ const updated = parseInitiative(dir, ini.filePath, newContent);
11662
+ if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after materialization.");
11663
+ return updated;
11664
+ }
11665
+ function materializeCandidate(dir, id, candidateId, opts) {
11059
11666
  const ini = getInitiative(dir, id);
11060
11667
  if (!ini) throw new InitiativeWriteError(`Initiative ${id} not found.`);
11668
+ assertFreshInitiative(ini.id, readFile(ini.filePath), opts);
11061
11669
  const candidate = ini.candidates.find((c) => c.id === candidateId);
11062
11670
  if (!candidate) throw new InitiativeWriteError(`Candidate ${candidateId} not found in ${id}.`);
11063
11671
  if (candidate.materializedAs) {
11064
- throw new InitiativeWriteError(
11065
- `Candidate ${candidateId} is already materialized as ${candidate.materializedAs}.`
11066
- );
11672
+ const exists2 = discoverWorkItems(dir).some((w) => w.id.toLowerCase() === candidate.materializedAs.toLowerCase());
11673
+ if (!exists2) throw new InitiativeWriteError(`Candidate ${candidateId} points at missing Work Item ${candidate.materializedAs} (broken relation). Resolve it before materializing.`);
11674
+ return { workItemId: candidate.materializedAs, fileName: null, initiative: ini, alreadyMaterialized: true };
11675
+ }
11676
+ const existing = findMaterializedWorkItem(dir, ini.id, candidateId);
11677
+ if (existing) {
11678
+ if (existing.initiative && existing.initiative.toLowerCase() !== ini.id.toLowerCase()) {
11679
+ throw new InitiativeWriteError(`A Work Item for candidate ${candidateId} already belongs to ${existing.initiative} (conflicting provenance).`);
11680
+ }
11681
+ const repaired = setCandidateMaterialized(dir, ini, candidateId, existing.id);
11682
+ return { workItemId: existing.id, fileName: null, initiative: repaired, alreadyMaterialized: true };
11067
11683
  }
11068
11684
  const wiId = nextWorkItemId(dir);
11069
11685
  const fileName = `${wiId}-${slugify2(candidate.title)}.md`;
11070
11686
  ensureDir(join(dir, DRAFT_DIR));
11071
11687
  writeFile(join(dir, DRAFT_DIR, fileName), buildWorkItemContent(wiId, ini.id, candidate));
11072
- const raw = readFile(ini.filePath);
11073
- const { data, content } = matter12(raw, {});
11074
- const cands = Array.isArray(data.candidates) ? data.candidates : [];
11075
- for (const c of cands) {
11076
- if (c && typeof c === "object" && String(c.id) === candidateId) c.materialized_as = wiId;
11077
- }
11078
- data.candidates = cands;
11079
- const newContent = matter12.stringify(content, data);
11080
- writeFile(ini.filePath, newContent);
11081
- const updated = parseInitiative(dir, ini.filePath, newContent);
11082
- if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after materialization.");
11083
- return { workItemId: wiId, fileName, initiative: updated };
11688
+ const updated = setCandidateMaterialized(dir, ini, candidateId, wiId);
11689
+ return { workItemId: wiId, fileName, initiative: updated, alreadyMaterialized: false };
11084
11690
  }
11085
11691
  function materializeRoadmapInitiative(dir, rmId) {
11086
11692
  const roadmapFull = join(dir, ROADMAP_PATH2);
@@ -11117,6 +11723,69 @@ function materializeRoadmapInitiative(dir, rmId) {
11117
11723
  candidates
11118
11724
  });
11119
11725
  }
11726
+ function assertDeclaredCriterion(declared, criterion) {
11727
+ const key = normalizeCriterion(criterion);
11728
+ const matches = declared.filter((c) => normalizeCriterion(c) === key).length;
11729
+ if (matches === 0) throw new InitiativeWriteError(`"${criterion}" is not a declared success criterion.`);
11730
+ if (matches > 1) throw new InitiativeWriteError(`"${criterion}" matches more than one declared criterion \u2014 disambiguate before recording evidence.`);
11731
+ }
11732
+ function upsertEvidence(existing, input) {
11733
+ const list2 = (Array.isArray(existing) ? existing : []).filter((e) => e && typeof e === "object" && !Array.isArray(e));
11734
+ const key = normalizeCriterion(input.criterion);
11735
+ const kept = list2.filter((e) => normalizeCriterion(String(e.criterion ?? "")) !== key);
11736
+ const obj = { criterion: input.criterion.trim(), status: input.status };
11737
+ if (input.evidence?.trim()) obj.evidence = input.evidence.trim();
11738
+ if (input.reference?.trim()) obj.reference = input.reference.trim();
11739
+ if (input.method) obj.method = input.method;
11740
+ obj.verified_at = today();
11741
+ if (input.verifiedBy?.trim()) obj.verified_by = input.verifiedBy.trim();
11742
+ return [...kept, obj];
11743
+ }
11744
+ function recordInitiativeOutcomeVerification(dir, id, input, opts) {
11745
+ const ini = getInitiative(dir, id);
11746
+ if (!ini) throw new InitiativeWriteError(`Initiative ${id} not found.`);
11747
+ assertDeclaredCriterion(parseSuccessCriteria(ini.body).map((c) => c.text), input.criterion);
11748
+ const raw = readFile(ini.filePath);
11749
+ assertFreshInitiative(ini.id, raw, opts);
11750
+ const { data, content } = matter12(raw, {});
11751
+ data.outcome_verifications = upsertEvidence(data.outcome_verifications, input);
11752
+ const newContent = matter12.stringify(content, data);
11753
+ writeFile(ini.filePath, newContent);
11754
+ const updated = parseInitiative(dir, ini.filePath, newContent);
11755
+ if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after recording evidence.");
11756
+ return updated;
11757
+ }
11758
+ var InitiativeNotReadyError = class extends InitiativeWriteError {
11759
+ constructor(evaluation) {
11760
+ super(`Initiative ${evaluation.id} is not ready to complete (${evaluation.readiness}).`);
11761
+ this.evaluation = evaluation;
11762
+ this.name = "InitiativeNotReadyError";
11763
+ }
11764
+ evaluation;
11765
+ };
11766
+ function completeInitiative(dir, id, input = {}, opts) {
11767
+ const ini = getInitiative(dir, id);
11768
+ if (!ini) throw new InitiativeWriteError(`Initiative ${id} not found.`);
11769
+ const evaluation = evaluateInitiativeCompletion(dir, ini);
11770
+ if (evaluation.readiness !== "READY_TO_COMPLETE" && evaluation.readiness !== "READY_WITH_EXCEPTIONS") throw new InitiativeNotReadyError(evaluation);
11771
+ if (!isValidInitiativeTransition(ini.status, "completed")) throw new InitiativeWriteError(`Initiative ${id} cannot move from ${ini.status} to completed.`);
11772
+ const raw = readFile(ini.filePath);
11773
+ assertFreshInitiative(ini.id, raw, opts);
11774
+ const { data, content } = matter12(raw, {});
11775
+ data.status = "completed";
11776
+ data.completed_at = today();
11777
+ const decision = { readiness: evaluation.readiness, decided_at: today(), reasons: evaluation.reasons };
11778
+ if (input.decidedBy?.trim()) decision.decided_by = input.decidedBy.trim();
11779
+ if (input.note?.trim()) decision.note = input.note.trim();
11780
+ const accepted = evaluation.exceptions.filter((x) => x.status === "accepted");
11781
+ if (accepted.length > 0) decision.exceptions = accepted;
11782
+ data.completion_decision = decision;
11783
+ const newContent = matter12.stringify(content, data);
11784
+ writeFile(ini.filePath, newContent);
11785
+ const updated = parseInitiative(dir, ini.filePath, newContent);
11786
+ if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after completion.");
11787
+ return updated;
11788
+ }
11120
11789
 
11121
11790
  // src/core/delivery-planning-write.ts
11122
11791
  var DeliveryPlanningWriteError = class extends Error {
@@ -11216,7 +11885,14 @@ function disassociateInitiativeFromEpic(dir, initiativeId) {
11216
11885
  if (!ini.epic) return ini;
11217
11886
  return updateInitiative(dir, ini.id, { epic: null });
11218
11887
  }
11219
- function normalizeMilestones(planId, input) {
11888
+ function normalizeMilestones(planId, input, existing) {
11889
+ const byId = /* @__PURE__ */ new Map();
11890
+ for (const e of existing) {
11891
+ if (e && typeof e === "object" && !Array.isArray(e)) {
11892
+ const eid = typeof e.id === "string" ? e.id.trim().toLowerCase() : "";
11893
+ if (eid) byId.set(eid, e);
11894
+ }
11895
+ }
11220
11896
  const seen = /* @__PURE__ */ new Set();
11221
11897
  const data = [];
11222
11898
  const model = [];
@@ -11228,13 +11904,19 @@ function normalizeMilestones(planId, input) {
11228
11904
  seen.add(key);
11229
11905
  const title = m.title?.trim() || id;
11230
11906
  const exit = cleanList(m.exitCriteria ?? []);
11231
- const entry = { id, title };
11907
+ const entry = { ...byId.get(key) ?? {} };
11908
+ entry.id = id;
11909
+ entry.title = title;
11232
11910
  if (exit.length > 0) entry.exit_criteria = exit;
11911
+ else delete entry.exit_criteria;
11233
11912
  data.push(entry);
11234
11913
  model.push({ id, title, exitCriteria: exit });
11235
11914
  }
11236
11915
  return { data, model };
11237
11916
  }
11917
+ function hasExitEvidence(entry) {
11918
+ return !!entry && Array.isArray(entry.exit_verifications) && entry.exit_verifications.length > 0;
11919
+ }
11238
11920
  function updateDeliveryPlan(dir, id, patch, opts) {
11239
11921
  const plan = getPlan(dir, id);
11240
11922
  if (!plan) throw new DeliveryPlanningWriteError(`Plan ${id} does not exist.`);
@@ -11254,7 +11936,8 @@ function updateDeliveryPlan(dir, id, patch, opts) {
11254
11936
  if (patch.dependsOn !== void 0) setListOrDelete(data, "depends_on", patch.dependsOn);
11255
11937
  if (patch.references !== void 0) setListOrDelete(data, "references", patch.references);
11256
11938
  if (patch.milestones !== void 0) {
11257
- const { data: msData, model } = normalizeMilestones(plan.id, patch.milestones);
11939
+ const existingRaw = Array.isArray(data.milestones) ? data.milestones : [];
11940
+ const { data: msData, model } = normalizeMilestones(plan.id, patch.milestones, existingRaw);
11258
11941
  const newIds = new Set(model.map((m) => m.id.toLowerCase()));
11259
11942
  const referencedByEpic = /* @__PURE__ */ new Map();
11260
11943
  for (const e of epicsInPlan(dir, plan.id)) {
@@ -11270,6 +11953,12 @@ function updateDeliveryPlan(dir, id, patch, opts) {
11270
11953
  const detail = [...referencedByEpic.entries()].map(([ms, epics]) => `${ms} (used by ${epics.join(", ")})`).join("; ");
11271
11954
  throw new DeliveryPlanningWriteError(`Cannot remove or rename milestone(s) still referenced by an Epic: ${detail}. Reassign the Epic first.`);
11272
11955
  }
11956
+ if (!opts?.allowMilestoneEvidenceLoss) {
11957
+ 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));
11958
+ if (droppedWithEvidence.length > 0) {
11959
+ throw new DeliveryPlanningWriteError(`Milestone(s) ${droppedWithEvidence.join(", ")} still carry exit-criteria evidence. Removing them discards that evidence \u2014 pass allowMilestoneEvidenceLoss to confirm.`);
11960
+ }
11961
+ }
11273
11962
  data.milestones = msData;
11274
11963
  }
11275
11964
  const newContent = matter13.stringify(content, data);
@@ -11335,6 +12024,163 @@ function updateEpic(dir, id, patch, opts) {
11335
12024
  if (!updated) throw new DeliveryPlanningWriteError("Failed to parse the Epic after update.");
11336
12025
  return updated;
11337
12026
  }
12027
+ function today2() {
12028
+ return (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
12029
+ }
12030
+ var PlanningNotReadyError = class extends DeliveryPlanningWriteError {
12031
+ constructor(evaluation) {
12032
+ super(`${evaluation.kind === "plan" ? "Plan" : "Epic"} ${evaluation.id} is not ready to complete (${evaluation.readiness}).`);
12033
+ this.evaluation = evaluation;
12034
+ this.name = "PlanningNotReadyError";
12035
+ }
12036
+ evaluation;
12037
+ };
12038
+ function transitionDeliveryPlan(dir, id, to, opts) {
12039
+ const plan = getPlan(dir, id);
12040
+ if (!plan) throw new DeliveryPlanningWriteError(`Plan ${id} does not exist.`);
12041
+ if (!PLAN_STATES.includes(to)) throw new DeliveryPlanningWriteError(`Invalid plan status: ${to}.`);
12042
+ if (to === "completed") throw new DeliveryPlanningWriteError(`Completing Plan ${id} requires evidence-based review \u2014 use completeDeliveryPlan.`);
12043
+ const raw = readFile(plan.filePath);
12044
+ assertFreshRevision(plan.id, raw, opts);
12045
+ if (plan.status === to) return plan;
12046
+ if (!PLAN_TRANSITIONS[plan.status].includes(to)) throw new DeliveryPlanningWriteError(`Invalid transition ${plan.status} \u2192 ${to} for Plan ${id}.`);
12047
+ const { data, content } = matter13(raw, {});
12048
+ data.status = to;
12049
+ if (to === "completed") data.completed_at = today2();
12050
+ const newContent = matter13.stringify(content, data);
12051
+ writeFile(plan.filePath, newContent);
12052
+ const updated = parseDeliveryPlan(dir, plan.filePath, newContent);
12053
+ if (!updated) throw new DeliveryPlanningWriteError("Failed to parse the Plan after transition.");
12054
+ return updated;
12055
+ }
12056
+ function transitionEpic(dir, id, to, opts) {
12057
+ const epic = getEpic(dir, id);
12058
+ if (!epic) throw new DeliveryPlanningWriteError(`Epic ${id} does not exist.`);
12059
+ if (!EPIC_STATES.includes(to)) throw new DeliveryPlanningWriteError(`Invalid epic status: ${to}.`);
12060
+ if (to === "completed") throw new DeliveryPlanningWriteError(`Completing Epic ${id} requires evidence-based review \u2014 use completeEpic.`);
12061
+ const raw = readFile(epic.filePath);
12062
+ assertFreshRevision(epic.id, raw, opts);
12063
+ if (epic.status === to) return epic;
12064
+ if (!EPIC_TRANSITIONS[epic.status].includes(to)) throw new DeliveryPlanningWriteError(`Invalid transition ${epic.status} \u2192 ${to} for Epic ${id}.`);
12065
+ const { data, content } = matter13(raw, {});
12066
+ data.status = to;
12067
+ if (to === "completed") data.completed_at = today2();
12068
+ const newContent = matter13.stringify(content, data);
12069
+ writeFile(epic.filePath, newContent);
12070
+ const updated = parseEpic(dir, epic.filePath, newContent);
12071
+ if (!updated) throw new DeliveryPlanningWriteError("Failed to parse the Epic after transition.");
12072
+ return updated;
12073
+ }
12074
+ function assertCriterionDeclared(declared, criterion, kind) {
12075
+ const key = normalizeCriterion(criterion);
12076
+ const matches = declared.filter((c) => normalizeCriterion(c) === key).length;
12077
+ if (matches === 0) throw new DeliveryPlanningWriteError(`"${criterion}" is not a declared ${kind} criterion.`);
12078
+ if (matches > 1) throw new DeliveryPlanningWriteError(`"${criterion}" matches more than one declared ${kind} criterion \u2014 rename them to disambiguate before recording evidence.`);
12079
+ }
12080
+ function upsertEvidence2(existing, input) {
12081
+ const list2 = Array.isArray(existing) ? existing.filter((e) => e && typeof e === "object" && !Array.isArray(e)) : [];
12082
+ const key = normalizeCriterion(input.criterion);
12083
+ const kept = list2.filter((e) => normalizeCriterion(String(e.criterion ?? "")) !== key);
12084
+ const obj = { criterion: input.criterion.trim(), status: input.status };
12085
+ if (input.evidence?.trim()) obj.evidence = input.evidence.trim();
12086
+ if (input.reference?.trim()) obj.reference = input.reference.trim();
12087
+ if (input.method) obj.method = input.method;
12088
+ obj.verified_at = today2();
12089
+ if (input.verifiedBy?.trim()) obj.verified_by = input.verifiedBy.trim();
12090
+ return [...kept, obj];
12091
+ }
12092
+ function recordEpicOutcomeVerification(dir, id, input, opts) {
12093
+ const epic = getEpic(dir, id);
12094
+ if (!epic) throw new DeliveryPlanningWriteError(`Epic ${id} does not exist.`);
12095
+ assertCriterionDeclared(epic.successCriteria, input.criterion, "success");
12096
+ const raw = readFile(epic.filePath);
12097
+ assertFreshRevision(epic.id, raw, opts);
12098
+ const { data, content } = matter13(raw, {});
12099
+ data.outcome_verifications = upsertEvidence2(data.outcome_verifications, input);
12100
+ const newContent = matter13.stringify(content, data);
12101
+ writeFile(epic.filePath, newContent);
12102
+ const updated = parseEpic(dir, epic.filePath, newContent);
12103
+ if (!updated) throw new DeliveryPlanningWriteError("Failed to parse the Epic after recording evidence.");
12104
+ return updated;
12105
+ }
12106
+ function recordPlanOutcomeVerification(dir, id, input, opts) {
12107
+ const plan = getPlan(dir, id);
12108
+ if (!plan) throw new DeliveryPlanningWriteError(`Plan ${id} does not exist.`);
12109
+ assertCriterionDeclared(plan.successCriteria, input.criterion, "success");
12110
+ const raw = readFile(plan.filePath);
12111
+ assertFreshRevision(plan.id, raw, opts);
12112
+ const { data, content } = matter13(raw, {});
12113
+ data.outcome_verifications = upsertEvidence2(data.outcome_verifications, input);
12114
+ const newContent = matter13.stringify(content, data);
12115
+ writeFile(plan.filePath, newContent);
12116
+ const updated = parseDeliveryPlan(dir, plan.filePath, newContent);
12117
+ if (!updated) throw new DeliveryPlanningWriteError("Failed to parse the Plan after recording evidence.");
12118
+ return updated;
12119
+ }
12120
+ function recordMilestoneExitVerification(dir, planId, milestoneId, input, opts) {
12121
+ const plan = getPlan(dir, planId);
12122
+ if (!plan) throw new DeliveryPlanningWriteError(`Plan ${planId} does not exist.`);
12123
+ const milestone = plan.milestones.find((m) => m.id.toLowerCase() === milestoneId.toLowerCase());
12124
+ if (!milestone) throw new DeliveryPlanningWriteError(`Milestone ${milestoneId} is not defined in ${planId}.`);
12125
+ assertCriterionDeclared(milestone.exitCriteria, input.criterion, "exit");
12126
+ const raw = readFile(plan.filePath);
12127
+ assertFreshRevision(plan.id, raw, opts);
12128
+ const { data, content } = matter13(raw, {});
12129
+ const rawMs = Array.isArray(data.milestones) ? data.milestones : [];
12130
+ const entry = rawMs.find((m) => m && typeof m === "object" && String(m.id ?? "").toLowerCase() === milestoneId.toLowerCase());
12131
+ if (!entry) throw new DeliveryPlanningWriteError(`Milestone ${milestoneId} entry not found in ${planId} frontmatter.`);
12132
+ entry.exit_verifications = upsertEvidence2(entry.exit_verifications, input);
12133
+ data.milestones = rawMs;
12134
+ const newContent = matter13.stringify(content, data);
12135
+ writeFile(plan.filePath, newContent);
12136
+ const updated = parseDeliveryPlan(dir, plan.filePath, newContent);
12137
+ if (!updated) throw new DeliveryPlanningWriteError("Failed to parse the Plan after recording milestone evidence.");
12138
+ return updated;
12139
+ }
12140
+ function completionDecisionRecord(evaluation, input) {
12141
+ const rec = { readiness: evaluation.readiness, decided_at: today2(), reasons: evaluation.reasons };
12142
+ if (input.decidedBy?.trim()) rec.decided_by = input.decidedBy.trim();
12143
+ if (input.note?.trim()) rec.note = input.note.trim();
12144
+ const acceptedExceptions = evaluation.exceptions.filter((x) => x.status === "accepted");
12145
+ if (acceptedExceptions.length > 0) rec.exceptions = acceptedExceptions;
12146
+ return rec;
12147
+ }
12148
+ function completeEpic(dir, id, input = {}, opts) {
12149
+ const epic = getEpic(dir, id);
12150
+ if (!epic) throw new DeliveryPlanningWriteError(`Epic ${id} does not exist.`);
12151
+ const evaluation = evaluateEpicCompletion(dir, epic);
12152
+ if (evaluation.readiness !== "READY_TO_COMPLETE" && evaluation.readiness !== "READY_WITH_EXCEPTIONS") throw new PlanningNotReadyError(evaluation);
12153
+ if (!EPIC_TRANSITIONS[epic.status].includes("completed")) throw new DeliveryPlanningWriteError(`Epic ${id} cannot move from ${epic.status} to completed.`);
12154
+ const raw = readFile(epic.filePath);
12155
+ assertFreshRevision(epic.id, raw, opts);
12156
+ const { data, content } = matter13(raw, {});
12157
+ data.status = "completed";
12158
+ data.completed_at = today2();
12159
+ data.completion_decision = completionDecisionRecord(evaluation, input);
12160
+ const newContent = matter13.stringify(content, data);
12161
+ writeFile(epic.filePath, newContent);
12162
+ const updated = parseEpic(dir, epic.filePath, newContent);
12163
+ if (!updated) throw new DeliveryPlanningWriteError("Failed to parse the Epic after completion.");
12164
+ return updated;
12165
+ }
12166
+ function completeDeliveryPlan(dir, id, input = {}, opts) {
12167
+ const plan = getPlan(dir, id);
12168
+ if (!plan) throw new DeliveryPlanningWriteError(`Plan ${id} does not exist.`);
12169
+ const evaluation = evaluatePlanCompletion(dir, plan);
12170
+ if (evaluation.readiness !== "READY_TO_COMPLETE" && evaluation.readiness !== "READY_WITH_EXCEPTIONS") throw new PlanningNotReadyError(evaluation);
12171
+ if (!PLAN_TRANSITIONS[plan.status].includes("completed")) throw new DeliveryPlanningWriteError(`Plan ${id} cannot move from ${plan.status} to completed.`);
12172
+ const raw = readFile(plan.filePath);
12173
+ assertFreshRevision(plan.id, raw, opts);
12174
+ const { data, content } = matter13(raw, {});
12175
+ data.status = "completed";
12176
+ data.completed_at = today2();
12177
+ data.completion_decision = completionDecisionRecord(evaluation, input);
12178
+ const newContent = matter13.stringify(content, data);
12179
+ writeFile(plan.filePath, newContent);
12180
+ const updated = parseDeliveryPlan(dir, plan.filePath, newContent);
12181
+ if (!updated) throw new DeliveryPlanningWriteError("Failed to parse the Plan after completion.");
12182
+ return updated;
12183
+ }
11338
12184
 
11339
12185
  // src/core/knowledge-consolidation.ts
11340
12186
  import { createHash as createHash3 } from "crypto";
@@ -12627,7 +13473,7 @@ function getWorkItem(dir, workItemId) {
12627
13473
  const base = toListItem(match);
12628
13474
  const body = readBody(match.filePath);
12629
13475
  const sections = splitSections(body);
12630
- const fm = match.rawFrontmatter;
13476
+ const fm2 = match.rawFrontmatter;
12631
13477
  const knowledge = discoverKnowledge(dir).filter((a) => !a.isWorkItem);
12632
13478
  const knowledgeById = new Map(knowledge.filter((k) => k.id).map((k) => [k.id, k]));
12633
13479
  const detail = {
@@ -12644,21 +13490,21 @@ function getWorkItem(dir, workItemId) {
12644
13490
  moduleCoverage: normalizeCoverage(match.moduleCoverage),
12645
13491
  impactAnalysis: normalizeImpact(match.impactAnalysis),
12646
13492
  acceptanceCriteria: parseAcceptanceCriteria(sections),
12647
- implementationEvidence: parseEvidence(fm),
12648
- releaseGates: parseReleaseGates(fm),
12649
- completionExceptions: parseExceptions(fm),
13493
+ implementationEvidence: parseEvidence(fm2),
13494
+ releaseGates: parseReleaseGates(fm2),
13495
+ completionExceptions: parseExceptions2(fm2),
12650
13496
  decisions: parseDecisions(match.decisions, knowledgeById),
12651
- relatedKnowledge: parseRelatedKnowledge(fm, knowledgeById),
12652
- source: parseWorkItemSource(fm),
12653
- originalSnapshot: parseOriginalSnapshot(fm),
13497
+ relatedKnowledge: parseRelatedKnowledge(fm2, knowledgeById),
13498
+ source: parseWorkItemSource(fm2),
13499
+ originalSnapshot: parseOriginalSnapshot(fm2),
12654
13500
  path: match.relPath,
12655
13501
  // Faithful source of truth: the artifact body already read above, not reconstructed (WI-025).
12656
13502
  markdownBody: body.trim(),
12657
13503
  // External systems this WI relates to (WI-030), separate from affectedModules (code).
12658
- resources: parseWorkItemResources(fm),
13504
+ resources: parseWorkItemResources(fm2),
12659
13505
  // Deprecation Targets this WI retires (WI-050), referenced not copied.
12660
- deprecationTargets: parseWorkItemDeprecationTargets(fm),
12661
- ...parseSystemImpact(dir, fm)
13506
+ deprecationTargets: parseWorkItemDeprecationTargets(fm2),
13507
+ ...parseSystemImpact(dir, fm2)
12662
13508
  };
12663
13509
  return { ...detail, refinement: computeRefinementStatus(detail) };
12664
13510
  }
@@ -12681,14 +13527,14 @@ function parseExplain(o) {
12681
13527
  function emptyExplain() {
12682
13528
  return { reason: null, graphReason: null, evidenceRefs: [], evidenceSummary: null };
12683
13529
  }
12684
- function parseSystemImpact(dir, fm) {
13530
+ function parseSystemImpact(dir, fm2) {
12685
13531
  const topology = loadSystemTopology(dir);
12686
13532
  const byId = new Map(topology.entities.map((e) => [e.id, e]));
12687
13533
  const resolve = (id) => {
12688
13534
  const e = byId.get(id);
12689
13535
  return { id, nodeId: `sys:${id}`, label: e?.label ?? id, kind: e?.kind ?? "unknown", moduleId: e?.moduleId ?? null };
12690
13536
  };
12691
- const affected = Array.isArray(fm.affected_system_entities) ? fm.affected_system_entities.map((raw) => {
13537
+ const affected = Array.isArray(fm2.affected_system_entities) ? fm2.affected_system_entities.map((raw) => {
12692
13538
  if (typeof raw === "string") return raw ? { ...resolve(raw), ...emptyExplain() } : null;
12693
13539
  if (raw && typeof raw === "object") {
12694
13540
  const o = raw;
@@ -12697,13 +13543,13 @@ function parseSystemImpact(dir, fm) {
12697
13543
  }
12698
13544
  return null;
12699
13545
  }).filter((e) => e != null) : [];
12700
- 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) : [];
12701
- const graphRevision = typeof fm.graph_revision === "string" && fm.graph_revision.trim() ? fm.graph_revision.trim() : null;
13546
+ 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) : [];
13547
+ const graphRevision = typeof fm2.graph_revision === "string" && fm2.graph_revision.trim() ? fm2.graph_revision.trim() : null;
12702
13548
  const graphCoverage = topology.entities.length === 0 ? "unavailable" : topology.relationships.length > 0 ? "available" : "partial";
12703
13549
  return { affectedSystemEntities: affected, reviewedSystemEntities: reviewed, graphRevision, graphCoverage };
12704
13550
  }
12705
- function parseOriginalSnapshot(fm) {
12706
- const raw = fm.original_snapshot;
13551
+ function parseOriginalSnapshot(fm2) {
13552
+ const raw = fm2.original_snapshot;
12707
13553
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
12708
13554
  const o = raw;
12709
13555
  const title = typeof o.title === "string" ? o.title : void 0;
@@ -12806,12 +13652,12 @@ function normalizeImpact(ia) {
12806
13652
  ...v.question ? { question: v.question } : {}
12807
13653
  }));
12808
13654
  }
12809
- function optStr4(v) {
13655
+ function optStr6(v) {
12810
13656
  if (typeof v === "string" && v.trim()) return v.trim();
12811
13657
  return void 0;
12812
13658
  }
12813
- function parseEvidence(fm) {
12814
- const evidence = fm.implementation_evidence;
13659
+ function parseEvidence(fm2) {
13660
+ const evidence = fm2.implementation_evidence;
12815
13661
  const repos = evidence?.repositories;
12816
13662
  if (!repos || typeof repos !== "object" || Array.isArray(repos)) return [];
12817
13663
  const out = [];
@@ -12821,13 +13667,13 @@ function parseEvidence(fm) {
12821
13667
  const validations = Array.isArray(d.validations) ? d.validations.map((v) => ({
12822
13668
  command: String(v.command ?? ""),
12823
13669
  status: String(v.status ?? "unknown"),
12824
- ...optStr4(v.reason) ? { reason: optStr4(v.reason) } : {}
13670
+ ...optStr6(v.reason) ? { reason: optStr6(v.reason) } : {}
12825
13671
  })) : [];
12826
13672
  const migrations = Array.isArray(d.migrations) ? d.migrations.map((m) => ({
12827
13673
  id: String(m.id ?? ""),
12828
13674
  environment: String(m.environment ?? ""),
12829
13675
  status: String(m.status ?? "unknown"),
12830
- ...optStr4(m.reason) ? { reason: optStr4(m.reason) } : {}
13676
+ ...optStr6(m.reason) ? { reason: optStr6(m.reason) } : {}
12831
13677
  })) : [];
12832
13678
  out.push({
12833
13679
  module,
@@ -12840,23 +13686,23 @@ function parseEvidence(fm) {
12840
13686
  }
12841
13687
  return out;
12842
13688
  }
12843
- function parseReleaseGates(fm) {
12844
- if (!Array.isArray(fm.release_gates)) return [];
12845
- return fm.release_gates.filter((g) => g && typeof g === "object").map((g) => ({
13689
+ function parseReleaseGates(fm2) {
13690
+ if (!Array.isArray(fm2.release_gates)) return [];
13691
+ return fm2.release_gates.filter((g) => g && typeof g === "object").map((g) => ({
12846
13692
  id: String(g.id ?? ""),
12847
13693
  status: String(g.status ?? "pending"),
12848
- ...optStr4(g.reason) ? { reason: optStr4(g.reason) } : {},
12849
- ...optStr4(g.required_for) ? { requiredFor: optStr4(g.required_for) } : {}
13694
+ ...optStr6(g.reason) ? { reason: optStr6(g.reason) } : {},
13695
+ ...optStr6(g.required_for) ? { requiredFor: optStr6(g.required_for) } : {}
12850
13696
  }));
12851
13697
  }
12852
- function parseExceptions(fm) {
12853
- if (!Array.isArray(fm.completion_exceptions)) return [];
12854
- return fm.completion_exceptions.filter((e) => e && typeof e === "object").map((e) => ({
13698
+ function parseExceptions2(fm2) {
13699
+ if (!Array.isArray(fm2.completion_exceptions)) return [];
13700
+ return fm2.completion_exceptions.filter((e) => e && typeof e === "object").map((e) => ({
12855
13701
  id: String(e.id ?? ""),
12856
13702
  status: String(e.status ?? "proposed"),
12857
- ...optStr4(e.reason) ? { reason: optStr4(e.reason) } : {},
12858
- ...optStr4(e.category) ? { category: optStr4(e.category) } : {},
12859
- ...optStr4(e.impact) ? { impact: optStr4(e.impact) } : {}
13703
+ ...optStr6(e.reason) ? { reason: optStr6(e.reason) } : {},
13704
+ ...optStr6(e.category) ? { category: optStr6(e.category) } : {},
13705
+ ...optStr6(e.impact) ? { impact: optStr6(e.impact) } : {}
12860
13706
  }));
12861
13707
  }
12862
13708
  function parseDecisions(decisions, knowledgeById) {
@@ -12869,10 +13715,10 @@ function parseDecisions(decisions, knowledgeById) {
12869
13715
  };
12870
13716
  });
12871
13717
  }
12872
- function parseRelatedKnowledge(fm, knowledgeById) {
13718
+ function parseRelatedKnowledge(fm2, knowledgeById) {
12873
13719
  const refs = /* @__PURE__ */ new Set();
12874
13720
  for (const field of ["related_knowledge", "knowledge", "related"]) {
12875
- const v = fm[field];
13721
+ const v = fm2[field];
12876
13722
  if (Array.isArray(v)) {
12877
13723
  for (const r of v) if (typeof r === "string" && r.trim()) refs.add(r.trim());
12878
13724
  }
@@ -13402,7 +14248,7 @@ function createWorkItem(dir, opts) {
13402
14248
  if (!type) throw new WorkItemWriteError("INVALID_INPUT", `Unknown Work Item type "${opts.type}".`);
13403
14249
  const id = nextWorkItemId2(dir);
13404
14250
  const title = intent.split(/\r?\n/)[0].trim().slice(0, 120);
13405
- const today2 = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
14251
+ const today3 = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
13406
14252
  const summary = opts.summary?.trim() || intent;
13407
14253
  const source2 = opts.source ? { ...opts.source, inferred: false } : { type: "manual", inferred: false };
13408
14254
  const data = {
@@ -13411,7 +14257,7 @@ function createWorkItem(dir, opts) {
13411
14257
  title,
13412
14258
  status: "draft",
13413
14259
  work_type: type,
13414
- created_at: today2,
14260
+ created_at: today3,
13415
14261
  source: source2,
13416
14262
  generated_by: "kaddo-admin",
13417
14263
  affected_modules: [],
@@ -13508,9 +14354,9 @@ function validateWorkItem(dir, id) {
13508
14354
  }
13509
14355
  const topology = loadSystemTopology(dir);
13510
14356
  const entityById = new Map(topology.entities.map((e) => [e.id, e]));
13511
- const fm = data;
14357
+ const fm2 = data;
13512
14358
  const idOf = (raw2) => typeof raw2 === "string" ? raw2 : raw2 && typeof raw2 === "object" ? String(raw2.id ?? "") : "";
13513
- const affectedEntities = Array.isArray(fm.affected_system_entities) ? fm.affected_system_entities.map(idOf).filter(Boolean) : [];
14359
+ const affectedEntities = Array.isArray(fm2.affected_system_entities) ? fm2.affected_system_entities.map(idOf).filter(Boolean) : [];
13514
14360
  for (const eid of affectedEntities) {
13515
14361
  const e = entityById.get(eid);
13516
14362
  if (!e) {
@@ -13521,8 +14367,8 @@ function validateWorkItem(dir, id) {
13521
14367
  findings.push({ level: "warning", message: `System entity "${e.label}" belongs to module "${e.moduleId}", which is not in affected_modules.` });
13522
14368
  }
13523
14369
  }
13524
- if (Array.isArray(fm.reviewed_system_entities)) {
13525
- for (const r of fm.reviewed_system_entities) {
14370
+ if (Array.isArray(fm2.reviewed_system_entities)) {
14371
+ for (const r of fm2.reviewed_system_entities) {
13526
14372
  const rid = r && typeof r === "object" ? String(r.id ?? "") : "";
13527
14373
  if (rid && !entityById.has(rid)) findings.push({ level: "warning", message: `Reviewed system entity "${rid}" does not exist in the semantic topology.` });
13528
14374
  }
@@ -14549,11 +15395,11 @@ function verifyWorkItem(dir, workItemId, input) {
14549
15395
  const artifacts = discoverWorkItems(dir);
14550
15396
  const match = artifacts.find((a) => (a.id || a.title) === workItemId);
14551
15397
  const lifecycle = lifecycleStateOf({ status: match.status, filePath: match.filePath });
14552
- const fm = match.rawFrontmatter;
15398
+ const fm2 = match.rawFrontmatter;
14553
15399
  const acVerifications = mapACVerifications(input.acVerifications);
14554
15400
  const acSummary = computeACSummary(acVerifications);
14555
- const releaseGates = Array.isArray(fm.release_gates) ? fm.release_gates : [];
14556
- const completionExceptions = Array.isArray(fm.completion_exceptions) ? fm.completion_exceptions : [];
15401
+ const releaseGates = Array.isArray(fm2.release_gates) ? fm2.release_gates : [];
15402
+ const completionExceptions = Array.isArray(fm2.completion_exceptions) ? fm2.completion_exceptions : [];
14557
15403
  const plannedVsActual = computePlannedVsActual(match.affectedModules, input.repos);
14558
15404
  const registeredModuleIds = loadMappedModules(dir).map((m) => m.id);
14559
15405
  const modifiedRepoIds = input.repos.map((r) => r.repoId);
@@ -14564,7 +15410,7 @@ function verifyWorkItem(dir, workItemId, input) {
14564
15410
  validationStatus: match.validationStatus || "not-started",
14565
15411
  releaseStatus: match.releaseStatus || "not-assessed",
14566
15412
  affectedModules: match.affectedModules,
14567
- rawFrontmatter: fm,
15413
+ rawFrontmatter: fm2,
14568
15414
  registeredModuleIds,
14569
15415
  modifiedRepoIds
14570
15416
  });
@@ -16656,112 +17502,6 @@ function getStatus(dir) {
16656
17502
  };
16657
17503
  }
16658
17504
 
16659
- // src/core/initiative-analysis.ts
16660
- var SUCCESS_HEADING_RE = /^#{1,6}\s*(success criteria|criterios de[ét]xito|criterios de éxito)\s*$/i;
16661
- var HEADING_RE2 = /^#{1,6}\s+/;
16662
- var CHECK_ITEM_RE = /^\s*[-*]\s+\[([ xX])\]\s+(.*)$/;
16663
- var BULLET_RE2 = /^\s*[-*]\s+(.*)$/;
16664
- var PLACEHOLDER_RE = /^_.*_$/;
16665
- function parseSuccessCriteria(body) {
16666
- const lines = body.split(/\r?\n/);
16667
- const out = [];
16668
- let capture = false;
16669
- for (const line of lines) {
16670
- if (capture && HEADING_RE2.test(line)) break;
16671
- if (!capture) {
16672
- if (SUCCESS_HEADING_RE.test(line.trim())) capture = true;
16673
- continue;
16674
- }
16675
- const check = line.match(CHECK_ITEM_RE);
16676
- if (check) {
16677
- const text2 = check[2].trim();
16678
- if (text2 && !PLACEHOLDER_RE.test(text2)) {
16679
- out.push({ text: text2, checked: check[1].toLowerCase() === "x" });
16680
- }
16681
- continue;
16682
- }
16683
- const bullet = line.match(BULLET_RE2);
16684
- if (bullet) {
16685
- const text2 = bullet[1].trim();
16686
- if (text2 && !PLACEHOLDER_RE.test(text2)) out.push({ text: text2, checked: null });
16687
- }
16688
- }
16689
- return out;
16690
- }
16691
- function analyzeInitiative(dir, ini) {
16692
- const progress = computeInitiativeProgress(dir, ini);
16693
- const successCriteria = parseSuccessCriteria(ini.body);
16694
- const pendingCandidates = ini.candidates.filter((c) => !c.materializedAs);
16695
- const associated = associatedWorkItems(dir, ini.id);
16696
- const findings = [];
16697
- if (successCriteria.length === 0) {
16698
- findings.push({
16699
- code: "no-success-criteria",
16700
- severity: "warning",
16701
- message: "The Initiative has no explicit Success Criteria; completion cannot be judged by outcome, only by delivery."
16702
- });
16703
- } else {
16704
- const uncovered = successCriteria.filter((c) => c.checked === false);
16705
- if (uncovered.length > 0) {
16706
- findings.push({
16707
- code: "uncovered-success-criteria",
16708
- severity: "blocking",
16709
- message: `${uncovered.length} success criterion/criteria remain uncovered.`,
16710
- items: uncovered.map((c) => c.text)
16711
- });
16712
- }
16713
- }
16714
- if (pendingCandidates.length > 0) {
16715
- findings.push({
16716
- code: "pending-candidates",
16717
- severity: "blocking",
16718
- message: `${pendingCandidates.length} committed candidate(s) not yet materialized into Work Items.`,
16719
- items: pendingCandidates.map((c) => `${c.id}: ${c.title}`)
16720
- });
16721
- }
16722
- const notCompleted = associated.filter((w) => w.status !== "completed" && w.status !== "archived");
16723
- if (associated.length === 0) {
16724
- findings.push({
16725
- code: "no-delivery",
16726
- severity: "info",
16727
- message: "No Work Items are associated with this Initiative yet."
16728
- });
16729
- } else if (notCompleted.length > 0) {
16730
- findings.push({
16731
- code: "incomplete-delivery",
16732
- severity: "blocking",
16733
- message: `${notCompleted.length} associated Work Item(s) are not completed.`,
16734
- items: notCompleted.map((w) => `${w.id} (${w.status})`)
16735
- });
16736
- }
16737
- return {
16738
- initiative: ini.id,
16739
- status: ini.status,
16740
- progress,
16741
- successCriteria,
16742
- pendingCandidates,
16743
- findings,
16744
- suggestedCandidates: pendingCandidates
16745
- };
16746
- }
16747
- function evaluateInitiativeCompletion(dir, ini) {
16748
- const analysis = analyzeInitiative(dir, ini);
16749
- const reasons = [];
16750
- for (const f of analysis.findings) {
16751
- if (f.severity === "blocking") reasons.push(f.message);
16752
- }
16753
- if (analysis.progress.delivery.total === 0 && analysis.pendingCandidates.length === 0) {
16754
- reasons.push("Nothing has been delivered or committed under this Initiative.");
16755
- }
16756
- const ready = reasons.length === 0;
16757
- return {
16758
- initiative: ini.id,
16759
- ready,
16760
- readiness: ready ? "ready" : "not-ready",
16761
- reasons
16762
- };
16763
- }
16764
-
16765
17505
  // src/core/deprecation-write.ts
16766
17506
  import fs6 from "fs";
16767
17507
  import path7 from "path";
@@ -17242,9 +17982,9 @@ function conceptBundlePath(a, id) {
17242
17982
  return `misc/${file}`;
17243
17983
  }
17244
17984
  }
17245
- function workItemRelations(fm) {
17985
+ function workItemRelations(fm2) {
17246
17986
  const out = [];
17247
- const resources = fm.resources;
17987
+ const resources = fm2.resources;
17248
17988
  if (Array.isArray(resources)) {
17249
17989
  for (const r of resources) {
17250
17990
  if (r && typeof r === "object") {
@@ -17253,16 +17993,16 @@ function workItemRelations(fm) {
17253
17993
  }
17254
17994
  }
17255
17995
  }
17256
- const dep = fm.deprecation_targets;
17996
+ const dep = fm2.deprecation_targets;
17257
17997
  if (Array.isArray(dep)) {
17258
17998
  for (const d of dep) {
17259
17999
  const s = typeof d === "string" ? d : d && typeof d === "object" ? str3(d.plan) : null;
17260
18000
  if (s) out.push({ id: s.includes("/") ? s.split("/")[0] : s, role: "deprecates-via" });
17261
18001
  }
17262
18002
  }
17263
- const parent = str3(fm.parent);
18003
+ const parent = str3(fm2.parent);
17264
18004
  if (parent) out.push({ id: parent, role: "child-of" });
17265
- for (const dId of strArray3(fm.decisions)) out.push({ id: dId, role: "decided-by" });
18005
+ for (const dId of strArray3(fm2.decisions)) out.push({ id: dId, role: "decided-by" });
17266
18006
  return out;
17267
18007
  }
17268
18008
  function slugify5(s) {
@@ -17761,6 +18501,8 @@ export {
17761
18501
  INTEGRATIONS_FILE,
17762
18502
  INTERFACE_TYPES,
17763
18503
  ImportError,
18504
+ InitiativeConflictError,
18505
+ InitiativeNotReadyError,
17764
18506
  InitiativeWriteError,
17765
18507
  IntegrationError,
17766
18508
  IntegrationServiceError,
@@ -17778,6 +18520,7 @@ export {
17778
18520
  PRODUCTION_RUNBOOKS_DIR,
17779
18521
  PRODUCTION_RUNBOOK_ARTIFACT_TYPE,
17780
18522
  PlanningConflictError,
18523
+ PlanningNotReadyError,
17781
18524
  ProductionRunbookError,
17782
18525
  REDACTED_COORDINATE,
17783
18526
  RESOURCE_ARTIFACT_TYPE,
@@ -17809,6 +18552,7 @@ export {
17809
18552
  buildImpactReport,
17810
18553
  buildImplementationHandoff,
17811
18554
  buildImportIndex,
18555
+ buildOutcomeVerification,
17812
18556
  buildPocReportContext,
17813
18557
  buildProductionRunbookContext,
17814
18558
  buildProjectExplanation,
@@ -17818,6 +18562,9 @@ export {
17818
18562
  buildSavingsReport,
17819
18563
  buildTopologyEnrichmentHandoff,
17820
18564
  collectImplementationEvidence,
18565
+ completeDeliveryPlan,
18566
+ completeEpic,
18567
+ completeInitiative,
17821
18568
  computeContentHash,
17822
18569
  computeEpicProgress,
17823
18570
  computeInitiativeProgress,
@@ -17851,9 +18598,15 @@ export {
17851
18598
  discoverWorkItems,
17852
18599
  enableIntegration,
17853
18600
  environmentSummary,
18601
+ epicOutcomeVerification,
17854
18602
  epicsInPlan,
17855
18603
  evaluateCompletion,
18604
+ evaluateEpicById,
18605
+ evaluateEpicCompletion,
18606
+ evaluateInitiativeById,
17856
18607
  evaluateInitiativeCompletion,
18608
+ evaluatePlanById,
18609
+ evaluatePlanCompletion,
17857
18610
  exists,
17858
18611
  exportOkf,
17859
18612
  filterSecretPaths,
@@ -17894,6 +18647,8 @@ export {
17894
18647
  getWorkItemsSummary,
17895
18648
  importExternalWorkItem,
17896
18649
  importWorkItem,
18650
+ initiativeOutcomeVerification,
18651
+ initiativeProvenanceIssues,
17897
18652
  initiativesInEpic,
17898
18653
  integrationRegistry,
17899
18654
  isActiveState,
@@ -17927,6 +18682,7 @@ export {
17927
18682
  nextInitiativeId,
17928
18683
  nextPlanId2 as nextPlanId,
17929
18684
  nextTargetId,
18685
+ normalizeCriterion,
17930
18686
  observationStatus,
17931
18687
  okfConceptType,
17932
18688
  parseContent,
@@ -17944,18 +18700,26 @@ export {
17944
18700
  persistConsent,
17945
18701
  persistPocReport,
17946
18702
  planIntelligence,
18703
+ planMilestoneVerifications,
18704
+ planOutcomeVerification,
17947
18705
  previewImport,
17948
18706
  projectMode,
17949
18707
  proposeWorkItemCandidates,
17950
18708
  readFile,
17951
18709
  readPocSummary,
18710
+ recordEpicOutcomeVerification,
18711
+ recordInitiativeOutcomeVerification,
18712
+ recordMilestoneExitVerification,
18713
+ recordPlanOutcomeVerification,
17952
18714
  redactSecrets,
18715
+ removeCandidate,
17953
18716
  removeIntegrationSecret,
17954
18717
  removeTarget,
17955
18718
  renderConsolidationMarkdown,
17956
18719
  renderDriftMarkdown,
17957
18720
  renderImpactMarkdown,
17958
18721
  renderSavingsMarkdown,
18722
+ replaceBodySection,
17959
18723
  revisionOf,
17960
18724
  searchSystemNodes,
17961
18725
  serializeConsolidationJson,
@@ -17968,8 +18732,11 @@ export {
17968
18732
  targetsEligibleForRemoval,
17969
18733
  targetsPastObservation,
17970
18734
  topologyRevision,
18735
+ transitionDeliveryPlan,
18736
+ transitionEpic,
17971
18737
  transitionInitiative,
17972
18738
  transitionWorkItem,
18739
+ updateCandidate,
17973
18740
  updateDeliveryPlan,
17974
18741
  updateEpic,
17975
18742
  updateInitiative,