@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/index.js CHANGED
@@ -5948,7 +5948,7 @@ function selectAgentFiles(opts) {
5948
5948
  // src/modules/agents.ts
5949
5949
  function withAgentFrontMatter(fileName, content) {
5950
5950
  const name = fileName.replace(/\.md$/, "");
5951
- const fm2 = [
5951
+ const fm3 = [
5952
5952
  "---",
5953
5953
  "type: agent",
5954
5954
  `name: ${name}`,
@@ -5957,7 +5957,7 @@ function withAgentFrontMatter(fileName, content) {
5957
5957
  "---",
5958
5958
  ""
5959
5959
  ].join("\n");
5960
- return fm2 + content.replace(/^\s+/, "");
5960
+ return fm3 + content.replace(/^\s+/, "");
5961
5961
  }
5962
5962
  var agentReadme = {
5963
5963
  path: "knowledge/agents/README.md",
@@ -6678,7 +6678,7 @@ function formatList(items) {
6678
6678
  return items.map((i) => `- ${i.trim()}`).join("\n");
6679
6679
  }
6680
6680
  function buildFrontMatter(id, type, level, title, answers) {
6681
- const today3 = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
6681
+ const today4 = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
6682
6682
  const lines = [
6683
6683
  "---",
6684
6684
  `type: ${type}`,
@@ -6691,7 +6691,7 @@ function buildFrontMatter(id, type, level, title, answers) {
6691
6691
  `initiative:`,
6692
6692
  `domains: []`,
6693
6693
  `code: []`,
6694
- `created_at: ${today3}`,
6694
+ `created_at: ${today4}`,
6695
6695
  `source:`,
6696
6696
  ` type: manual`,
6697
6697
  ` inferred: false`,
@@ -6766,7 +6766,7 @@ _What did we learn from this change? Update after completion._
6766
6766
  return sections.join("\n");
6767
6767
  }
6768
6768
  function buildModuleFrontMatter(id, modType, title, answers) {
6769
- const today3 = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
6769
+ const today4 = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
6770
6770
  const extra = modType.extraFrontMatter ?? {};
6771
6771
  const extraLines = Object.entries(extra).map(
6772
6772
  ([k, v]) => `${k}: ${JSON.stringify(v)}`
@@ -6782,7 +6782,7 @@ function buildModuleFrontMatter(id, modType, title, answers) {
6782
6782
  `initiative:`,
6783
6783
  `domains: []`,
6784
6784
  `code: []`,
6785
- `created_at: ${today3}`,
6785
+ `created_at: ${today4}`,
6786
6786
  `source: manual`,
6787
6787
  `summary: "${title}"`,
6788
6788
  ...extraLines,
@@ -6930,7 +6930,7 @@ function resolveCandidateLevel(candidate, type) {
6930
6930
  return getLevelForType(type);
6931
6931
  }
6932
6932
  function buildRoadmapFrontMatter(id, type, level, title, candidate, answers) {
6933
- const today3 = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
6933
+ const today4 = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
6934
6934
  const summary = (answers.problem?.split(".")[0] ?? candidate.expectedValue ?? title).trim();
6935
6935
  const initiative = candidate.initiative?.title ?? candidate.initiative?.id ?? "";
6936
6936
  const q = (s) => s.replace(/"/g, "'");
@@ -6953,7 +6953,7 @@ function buildRoadmapFrontMatter(id, type, level, title, candidate, answers) {
6953
6953
  ...yamlList2("domains", domains),
6954
6954
  ...domains.length === 0 ? ["domains: []"] : [],
6955
6955
  `code: []`,
6956
- `created_at: ${today3}`,
6956
+ `created_at: ${today4}`,
6957
6957
  `source: roadmap`,
6958
6958
  `source_id: ${candidate.id}`,
6959
6959
  `source_initiative: ${candidate.initiative?.id ?? "unknown"}`,
@@ -7763,8 +7763,8 @@ function analyzeMetadataHealth(dir) {
7763
7763
  if (isFile(p) && entry.endsWith(".md")) {
7764
7764
  try {
7765
7765
  const raw = readFile(p);
7766
- const fm2 = matter2(raw).data;
7767
- if (fm2.status === "done") {
7766
+ const fm3 = matter2(raw).data;
7767
+ if (fm3.status === "done") {
7768
7768
  const rel = p.replace(dir + "/", "").replace(dir + "\\", "").replace(/\\/g, "/");
7769
7769
  findings.push({
7770
7770
  file: rel,
@@ -11255,7 +11255,7 @@ ${items.map((i) => `- ${i}`).join("\n")}
11255
11255
  `;
11256
11256
  }
11257
11257
  function renderCapsuleMarkdown(c) {
11258
- const fm2 = [
11258
+ const fm3 = [
11259
11259
  "---",
11260
11260
  "type: knowledge-capsule",
11261
11261
  `system: ${c.system}`,
@@ -11267,7 +11267,7 @@ function renderCapsuleMarkdown(c) {
11267
11267
  "---"
11268
11268
  ].join("\n");
11269
11269
  const parts = [
11270
- fm2,
11270
+ fm3,
11271
11271
  "",
11272
11272
  `# ${c.system} \u2014 Knowledge Capsule`,
11273
11273
  "",
@@ -11574,6 +11574,18 @@ var DELIVERY_PLANS_DIR = "knowledge/delivery/plans";
11574
11574
  var EPICS_DIR = "knowledge/delivery/epics";
11575
11575
  var PLAN_STATES = ["draft", "in-progress", "completed", "cancelled"];
11576
11576
  var EPIC_STATES = ["planned", "in-progress", "completed", "cancelled"];
11577
+ var PLAN_TRANSITIONS = {
11578
+ draft: ["in-progress", "cancelled"],
11579
+ "in-progress": ["completed", "cancelled"],
11580
+ completed: [],
11581
+ cancelled: []
11582
+ };
11583
+ var EPIC_TRANSITIONS = {
11584
+ planned: ["in-progress", "cancelled"],
11585
+ "in-progress": ["completed", "cancelled"],
11586
+ completed: [],
11587
+ cancelled: []
11588
+ };
11577
11589
  function toPosix5(p) {
11578
11590
  return p.replace(/\\/g, "/");
11579
11591
  }
@@ -11854,6 +11866,9 @@ function validatePlanningGraph(dir) {
11854
11866
  findings.push({ level: "warning", kind: "pending_dependency", subject: e.id, message: `Epic ${e.id} is blocked by unfinished dependency ${d}.` });
11855
11867
  return findings;
11856
11868
  }
11869
+ function revisionOf(content) {
11870
+ return createHash("sha256").update(content, "utf8").digest("hex").slice(0, 16);
11871
+ }
11857
11872
 
11858
11873
  // src/core/resources.ts
11859
11874
  import matter6 from "gray-matter";
@@ -11973,40 +11988,40 @@ function purposeFromBody(body) {
11973
11988
  }
11974
11989
  function toDetail(filePath, relPath, raw) {
11975
11990
  const parsed = matter6(raw);
11976
- const fm2 = parsed.data ?? {};
11991
+ const fm3 = parsed.data ?? {};
11977
11992
  const body = parsed.content.trim();
11978
- const id = str(fm2.id) ?? "";
11993
+ const id = str(fm3.id) ?? "";
11979
11994
  return {
11980
11995
  id,
11981
- title: str(fm2.title) ?? id,
11982
- resourceType: str(fm2.resource_type),
11983
- provider: str(fm2.provider),
11984
- environments: strArray(fm2.environments),
11985
- scope: parseScope(fm2.scope),
11986
- modules: strArray(fm2.modules),
11996
+ title: str(fm3.title) ?? id,
11997
+ resourceType: str(fm3.resource_type),
11998
+ provider: str(fm3.provider),
11999
+ environments: strArray(fm3.environments),
12000
+ scope: parseScope(fm3.scope),
12001
+ modules: strArray(fm3.modules),
11987
12002
  path: relPath,
11988
- purpose: str(fm2.purpose) ?? purposeFromBody(body),
11989
- interfaces: parseInterfaces(fm2.access_interfaces),
11990
- boundaries: parseBoundaries(fm2.access_boundaries),
12003
+ purpose: str(fm3.purpose) ?? purposeFromBody(body),
12004
+ interfaces: parseInterfaces(fm3.access_interfaces),
12005
+ boundaries: parseBoundaries(fm3.access_boundaries),
11991
12006
  ...(() => {
11992
- const a = parseAuth(fm2.authentication);
12007
+ const a = parseAuth(fm3.authentication);
11993
12008
  return { authRefs: a.refs, authMode: a.mode };
11994
12009
  })(),
11995
- connectionProfiles: parseConnectionProfiles(fm2.connection_profiles),
12010
+ connectionProfiles: parseConnectionProfiles(fm3.connection_profiles),
11996
12011
  markdownBody: body
11997
12012
  };
11998
12013
  }
11999
12014
  function getResources(dir) {
12000
12015
  return discoverKnowledge(dir).filter((a) => a.type === RESOURCE_ARTIFACT_TYPE).map((a) => {
12001
- const fm2 = a.rawFrontmatter;
12016
+ const fm3 = a.rawFrontmatter;
12002
12017
  return {
12003
- id: a.id || str(fm2.id) || a.title,
12004
- title: a.title || str(fm2.title) || a.id,
12005
- resourceType: str(fm2.resource_type),
12006
- provider: str(fm2.provider),
12007
- environments: strArray(fm2.environments),
12008
- scope: parseScope(fm2.scope),
12009
- modules: strArray(fm2.modules),
12018
+ id: a.id || str(fm3.id) || a.title,
12019
+ title: a.title || str(fm3.title) || a.id,
12020
+ resourceType: str(fm3.resource_type),
12021
+ provider: str(fm3.provider),
12022
+ environments: strArray(fm3.environments),
12023
+ scope: parseScope(fm3.scope),
12024
+ modules: strArray(fm3.modules),
12010
12025
  path: a.relPath
12011
12026
  };
12012
12027
  }).sort((x, y) => x.id.localeCompare(y.id));
@@ -12019,8 +12034,8 @@ function getResource(dir, id) {
12019
12034
  const raw = readFile(match.filePath);
12020
12035
  return toDetail(match.filePath, match.relPath, raw);
12021
12036
  }
12022
- function parseWorkItemResources(fm2) {
12023
- const v = fm2.resources;
12037
+ function parseWorkItemResources(fm3) {
12038
+ const v = fm3.resources;
12024
12039
  if (!Array.isArray(v)) return [];
12025
12040
  const out = [];
12026
12041
  for (const raw of v) {
@@ -12072,8 +12087,8 @@ var EVIDENCE_SIGNALS = [
12072
12087
  function str2(v) {
12073
12088
  return typeof v === "string" && v.trim() ? v.trim() : null;
12074
12089
  }
12075
- function parseWorkItemDeprecationTargets(fm2) {
12076
- const v = fm2.deprecation_targets;
12090
+ function parseWorkItemDeprecationTargets(fm3) {
12091
+ const v = fm3.deprecation_targets;
12077
12092
  if (!Array.isArray(v)) return [];
12078
12093
  const out = [];
12079
12094
  for (const raw of v) {
@@ -12207,13 +12222,13 @@ function purposeFromBody2(body) {
12207
12222
  }
12208
12223
  function getDeprecationPlans(dir) {
12209
12224
  return discoverKnowledge(dir).filter((a) => a.type === DEPRECATION_ARTIFACT_TYPE).map((a) => {
12210
- const fm2 = a.rawFrontmatter;
12211
- const targets = parseTargets(fm2.targets);
12225
+ const fm3 = a.rawFrontmatter;
12226
+ const targets = parseTargets(fm3.targets);
12212
12227
  return {
12213
- id: a.id || str2(fm2.id) || a.title,
12214
- title: a.title || str2(fm2.title) || a.id,
12228
+ id: a.id || str2(fm3.id) || a.title,
12229
+ title: a.title || str2(fm3.title) || a.id,
12215
12230
  path: a.relPath,
12216
- status: str2(fm2.status),
12231
+ status: str2(fm3.status),
12217
12232
  targetCount: targets.length,
12218
12233
  lifecycleCounts: lifecycleCountsOf(targets)
12219
12234
  };
@@ -12226,17 +12241,17 @@ function getDeprecationPlan(dir, id) {
12226
12241
  if (!match) return null;
12227
12242
  const raw = readFile(match.filePath);
12228
12243
  const parsed = matter7(raw);
12229
- const fm2 = parsed.data ?? {};
12244
+ const fm3 = parsed.data ?? {};
12230
12245
  const body = parsed.content.trim();
12231
- const targets = parseTargets(fm2.targets);
12246
+ const targets = parseTargets(fm3.targets);
12232
12247
  return {
12233
- id: str2(fm2.id) ?? match.id,
12234
- title: str2(fm2.title) ?? match.title,
12248
+ id: str2(fm3.id) ?? match.id,
12249
+ title: str2(fm3.title) ?? match.title,
12235
12250
  path: match.relPath,
12236
- status: str2(fm2.status),
12251
+ status: str2(fm3.status),
12237
12252
  targetCount: targets.length,
12238
12253
  lifecycleCounts: lifecycleCountsOf(targets),
12239
- purpose: str2(fm2.purpose) ?? purposeFromBody2(body),
12254
+ purpose: str2(fm3.purpose) ?? purposeFromBody2(body),
12240
12255
  targets,
12241
12256
  markdownBody: body
12242
12257
  };
@@ -12762,9 +12777,9 @@ var QUALITY_NOTE = {
12762
12777
  sparse: "The graph has many nodes but few meaningful edges.",
12763
12778
  empty: "The graph has almost no relationships."
12764
12779
  };
12765
- function yamlBlock(fm2) {
12780
+ function yamlBlock(fm3) {
12766
12781
  const lines = ["```yaml"];
12767
- for (const [k, vals] of Object.entries(fm2)) {
12782
+ for (const [k, vals] of Object.entries(fm3)) {
12768
12783
  lines.push(`${k}:`);
12769
12784
  for (const v of vals) lines.push(` - ${v}`);
12770
12785
  }
@@ -15678,8 +15693,8 @@ function buildProjectExplanation(dir) {
15678
15693
  };
15679
15694
  }),
15680
15695
  implementationEvidence: workItemArtifacts.filter((a) => a.affectedModules.length > 0).map((a) => {
15681
- const fm2 = a.rawFrontmatter;
15682
- const evidence = fm2.implementation_evidence;
15696
+ const fm3 = a.rawFrontmatter;
15697
+ const evidence = fm3.implementation_evidence;
15683
15698
  const repos = evidence?.repositories ?? {};
15684
15699
  const repoEvidence = {};
15685
15700
  for (const [repoId, data] of Object.entries(repos)) {
@@ -15697,8 +15712,8 @@ function buildProjectExplanation(dir) {
15697
15712
  validationStatus: a.validationStatus || historicalDefault,
15698
15713
  releaseStatus: a.releaseStatus || "not-assessed",
15699
15714
  affectedModules: a.affectedModules,
15700
- releaseGates: Array.isArray(fm2.release_gates) ? fm2.release_gates : [],
15701
- completionExceptions: Array.isArray(fm2.completion_exceptions) ? fm2.completion_exceptions : [],
15715
+ releaseGates: Array.isArray(fm3.release_gates) ? fm3.release_gates : [],
15716
+ completionExceptions: Array.isArray(fm3.completion_exceptions) ? fm3.completion_exceptions : [],
15702
15717
  repoEvidence
15703
15718
  };
15704
15719
  })
@@ -16143,9 +16158,9 @@ function readConfig(dir) {
16143
16158
  }
16144
16159
  function filterBySince(artifacts, since) {
16145
16160
  return artifacts.filter((a) => {
16146
- const fm2 = a;
16147
- if (!fm2.created_at) return true;
16148
- return fm2.created_at >= since;
16161
+ const fm3 = a;
16162
+ if (!fm3.created_at) return true;
16163
+ return fm3.created_at >= since;
16149
16164
  });
16150
16165
  }
16151
16166
  function filterByScope(artifacts, scope) {
@@ -19197,8 +19212,8 @@ var DIR_TARGETS = ["knowledge/tech/decisions", "knowledge/tech/discovery", "know
19197
19212
  function withLanguageDirective(content, language) {
19198
19213
  if (language !== "es") return content;
19199
19214
  const note = "> Idioma del proyecto: **espa\xF1ol**. Escribe este conocimiento en espa\xF1ol. Mant\xE9n en ingl\xE9s el c\xF3digo, los nombres de archivo, los comandos y las claves de configuraci\xF3n.\n";
19200
- const fm2 = content.match(/^---\n[\s\S]*?\n---\n/);
19201
- if (fm2) return content.slice(0, fm2[0].length) + "\n" + note + content.slice(fm2[0].length);
19215
+ const fm3 = content.match(/^---\n[\s\S]*?\n---\n/);
19216
+ if (fm3) return content.slice(0, fm3[0].length) + "\n" + note + content.slice(fm3[0].length);
19202
19217
  return `${note}
19203
19218
  ${content}`;
19204
19219
  }
@@ -21097,9 +21112,9 @@ function conceptBundlePath(a, id) {
21097
21112
  return `misc/${file}`;
21098
21113
  }
21099
21114
  }
21100
- function workItemRelations(fm2) {
21115
+ function workItemRelations(fm3) {
21101
21116
  const out = [];
21102
- const resources = fm2.resources;
21117
+ const resources = fm3.resources;
21103
21118
  if (Array.isArray(resources)) {
21104
21119
  for (const r of resources) {
21105
21120
  if (r && typeof r === "object") {
@@ -21108,16 +21123,16 @@ function workItemRelations(fm2) {
21108
21123
  }
21109
21124
  }
21110
21125
  }
21111
- const dep = fm2.deprecation_targets;
21126
+ const dep = fm3.deprecation_targets;
21112
21127
  if (Array.isArray(dep)) {
21113
21128
  for (const d of dep) {
21114
21129
  const s = typeof d === "string" ? d : d && typeof d === "object" ? str3(d.plan) : null;
21115
21130
  if (s) out.push({ id: s.includes("/") ? s.split("/")[0] : s, role: "deprecates-via" });
21116
21131
  }
21117
21132
  }
21118
- const parent = str3(fm2.parent);
21133
+ const parent = str3(fm3.parent);
21119
21134
  if (parent) out.push({ id: parent, role: "child-of" });
21120
- for (const dId of strArray3(fm2.decisions)) out.push({ id: dId, role: "decided-by" });
21135
+ for (const dId of strArray3(fm3.decisions)) out.push({ id: dId, role: "decided-by" });
21121
21136
  return out;
21122
21137
  }
21123
21138
  function slugify5(s) {
@@ -22820,7 +22835,7 @@ var WorkItemWriteError = class extends Error {
22820
22835
  code;
22821
22836
  };
22822
22837
  var EDITABLE_STATES = ["draft"];
22823
- function revisionOf(raw) {
22838
+ function revisionOf2(raw) {
22824
22839
  return crypto2.createHash("sha256").update(raw, "utf-8").digest("hex");
22825
22840
  }
22826
22841
  function slugify6(s) {
@@ -23022,7 +23037,7 @@ function getWorkItemForEdit(dir, id) {
23022
23037
  ...input,
23023
23038
  id,
23024
23039
  status,
23025
- revision: revisionOf(raw),
23040
+ revision: revisionOf2(raw),
23026
23041
  path: relPath,
23027
23042
  editable,
23028
23043
  ...editable ? {} : { editableReason: status === "ready" ? "This Work Item is Ready. Reopen it as Draft to edit its scope." : `This Work Item is ${status} and cannot be edited from the structured editor.` }
@@ -23057,7 +23072,7 @@ function createWorkItem(dir, opts) {
23057
23072
  if (!type) throw new WorkItemWriteError("INVALID_INPUT", `Unknown Work Item type "${opts.type}".`);
23058
23073
  const id = nextWorkItemId2(dir);
23059
23074
  const title = intent.split(/\r?\n/)[0].trim().slice(0, 120);
23060
- const today3 = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
23075
+ const today4 = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
23061
23076
  const summary = opts.summary?.trim() || intent;
23062
23077
  const source2 = opts.source ? { ...opts.source, inferred: false } : { type: "manual", inferred: false };
23063
23078
  const data = {
@@ -23066,7 +23081,7 @@ function createWorkItem(dir, opts) {
23066
23081
  title,
23067
23082
  status: "draft",
23068
23083
  work_type: type,
23069
- created_at: today3,
23084
+ created_at: today4,
23070
23085
  source: source2,
23071
23086
  generated_by: "kaddo-admin",
23072
23087
  affected_modules: [],
@@ -23094,7 +23109,7 @@ function createWorkItem(dir, opts) {
23094
23109
  if (exists(filePath)) throw new WorkItemWriteError("INVALID_INPUT", `Work Item file already exists: ${relPath}`);
23095
23110
  const raw = serialize3(data, body);
23096
23111
  atomicWrite4(filePath, raw);
23097
- return { id, path: relPath, revision: revisionOf(raw) };
23112
+ return { id, path: relPath, revision: revisionOf2(raw) };
23098
23113
  }
23099
23114
  function validateWorkItem(dir, id) {
23100
23115
  const { filePath } = findArtifact(dir, id);
@@ -23123,9 +23138,9 @@ function validateWorkItem(dir, id) {
23123
23138
  }
23124
23139
  const topology = loadSystemTopology(dir);
23125
23140
  const entityById = new Map(topology.entities.map((e) => [e.id, e]));
23126
- const fm2 = data;
23141
+ const fm3 = data;
23127
23142
  const idOf = (raw2) => typeof raw2 === "string" ? raw2 : raw2 && typeof raw2 === "object" ? String(raw2.id ?? "") : "";
23128
- const affectedEntities = Array.isArray(fm2.affected_system_entities) ? fm2.affected_system_entities.map(idOf).filter(Boolean) : [];
23143
+ const affectedEntities = Array.isArray(fm3.affected_system_entities) ? fm3.affected_system_entities.map(idOf).filter(Boolean) : [];
23129
23144
  for (const eid of affectedEntities) {
23130
23145
  const e = entityById.get(eid);
23131
23146
  if (!e) {
@@ -23136,8 +23151,8 @@ function validateWorkItem(dir, id) {
23136
23151
  findings.push({ level: "warning", message: `System entity "${e.label}" belongs to module "${e.moduleId}", which is not in affected_modules.` });
23137
23152
  }
23138
23153
  }
23139
- if (Array.isArray(fm2.reviewed_system_entities)) {
23140
- for (const r of fm2.reviewed_system_entities) {
23154
+ if (Array.isArray(fm3.reviewed_system_entities)) {
23155
+ for (const r of fm3.reviewed_system_entities) {
23141
23156
  const rid = r && typeof r === "object" ? String(r.id ?? "") : "";
23142
23157
  if (rid && !entityById.has(rid)) findings.push({ level: "warning", message: `Reviewed system entity "${rid}" does not exist in the semantic topology.` });
23143
23158
  }
@@ -23149,7 +23164,7 @@ var ALLOWED = { draft: ["ready"], ready: ["draft", "in-progress"] };
23149
23164
  function transitionWorkItem(dir, id, to, expectedRevision) {
23150
23165
  const { filePath } = findArtifact(dir, id);
23151
23166
  const raw = readFile(filePath);
23152
- if (revisionOf(raw) !== expectedRevision) {
23167
+ if (revisionOf2(raw) !== expectedRevision) {
23153
23168
  throw new WorkItemWriteError("WORK_ITEM_CONFLICT", "This Work Item changed outside Kaddo Admin. Reload the latest version before continuing.");
23154
23169
  }
23155
23170
  const { data, content } = matter21(raw);
@@ -23173,7 +23188,7 @@ function transitionWorkItem(dir, id, to, expectedRevision) {
23173
23188
  } catch {
23174
23189
  }
23175
23190
  }
23176
- return { revision: revisionOf(nextRaw), status: to, path: targetRel };
23191
+ return { revision: revisionOf2(nextRaw), status: to, path: targetRel };
23177
23192
  }
23178
23193
 
23179
23194
  // ../integrations/src/errors.ts
@@ -24891,9 +24906,9 @@ function isResolvedSection(text2) {
24891
24906
  function transitionToReady(filePath) {
24892
24907
  const raw = readFile(filePath);
24893
24908
  const { data, content } = matter23(raw);
24894
- const today3 = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
24909
+ const today4 = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
24895
24910
  data.status = "ready";
24896
- data.ready_at = today3;
24911
+ data.ready_at = today4;
24897
24912
  const newContent = matter23.stringify(content, data);
24898
24913
  const posix2 = filePath.replace(/\\/g, "/");
24899
24914
  let newPath = filePath;
@@ -25184,7 +25199,7 @@ function getWorkItem(dir, workItemId) {
25184
25199
  const base = toListItem(match);
25185
25200
  const body = readBody2(match.filePath);
25186
25201
  const sections = splitSections(body);
25187
- const fm2 = match.rawFrontmatter;
25202
+ const fm3 = match.rawFrontmatter;
25188
25203
  const knowledge = discoverKnowledge(dir).filter((a) => !a.isWorkItem);
25189
25204
  const knowledgeById = new Map(knowledge.filter((k) => k.id).map((k) => [k.id, k]));
25190
25205
  const detail = {
@@ -25201,21 +25216,21 @@ function getWorkItem(dir, workItemId) {
25201
25216
  moduleCoverage: normalizeCoverage(match.moduleCoverage),
25202
25217
  impactAnalysis: normalizeImpact(match.impactAnalysis),
25203
25218
  acceptanceCriteria: parseAcceptanceCriteria(sections),
25204
- implementationEvidence: parseEvidence(fm2),
25205
- releaseGates: parseReleaseGates(fm2),
25206
- completionExceptions: parseExceptions(fm2),
25219
+ implementationEvidence: parseEvidence(fm3),
25220
+ releaseGates: parseReleaseGates(fm3),
25221
+ completionExceptions: parseExceptions(fm3),
25207
25222
  decisions: parseDecisions(match.decisions, knowledgeById),
25208
- relatedKnowledge: parseRelatedKnowledge(fm2, knowledgeById),
25209
- source: parseWorkItemSource(fm2),
25210
- originalSnapshot: parseOriginalSnapshot(fm2),
25223
+ relatedKnowledge: parseRelatedKnowledge(fm3, knowledgeById),
25224
+ source: parseWorkItemSource(fm3),
25225
+ originalSnapshot: parseOriginalSnapshot(fm3),
25211
25226
  path: match.relPath,
25212
25227
  // Faithful source of truth: the artifact body already read above, not reconstructed (WI-025).
25213
25228
  markdownBody: body.trim(),
25214
25229
  // External systems this WI relates to (WI-030), separate from affectedModules (code).
25215
- resources: parseWorkItemResources(fm2),
25230
+ resources: parseWorkItemResources(fm3),
25216
25231
  // Deprecation Targets this WI retires (WI-050), referenced not copied.
25217
- deprecationTargets: parseWorkItemDeprecationTargets(fm2),
25218
- ...parseSystemImpact(dir, fm2)
25232
+ deprecationTargets: parseWorkItemDeprecationTargets(fm3),
25233
+ ...parseSystemImpact(dir, fm3)
25219
25234
  };
25220
25235
  return { ...detail, refinement: computeRefinementStatus(detail) };
25221
25236
  }
@@ -25238,14 +25253,14 @@ function parseExplain(o) {
25238
25253
  function emptyExplain() {
25239
25254
  return { reason: null, graphReason: null, evidenceRefs: [], evidenceSummary: null };
25240
25255
  }
25241
- function parseSystemImpact(dir, fm2) {
25256
+ function parseSystemImpact(dir, fm3) {
25242
25257
  const topology = loadSystemTopology(dir);
25243
25258
  const byId = new Map(topology.entities.map((e) => [e.id, e]));
25244
25259
  const resolve = (id) => {
25245
25260
  const e = byId.get(id);
25246
25261
  return { id, nodeId: `sys:${id}`, label: e?.label ?? id, kind: e?.kind ?? "unknown", moduleId: e?.moduleId ?? null };
25247
25262
  };
25248
- const affected = Array.isArray(fm2.affected_system_entities) ? fm2.affected_system_entities.map((raw) => {
25263
+ const affected = Array.isArray(fm3.affected_system_entities) ? fm3.affected_system_entities.map((raw) => {
25249
25264
  if (typeof raw === "string") return raw ? { ...resolve(raw), ...emptyExplain() } : null;
25250
25265
  if (raw && typeof raw === "object") {
25251
25266
  const o = raw;
@@ -25254,13 +25269,13 @@ function parseSystemImpact(dir, fm2) {
25254
25269
  }
25255
25270
  return null;
25256
25271
  }).filter((e) => e != null) : [];
25257
- 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) : [];
25258
- const graphRevision = typeof fm2.graph_revision === "string" && fm2.graph_revision.trim() ? fm2.graph_revision.trim() : null;
25272
+ const reviewed = Array.isArray(fm3.reviewed_system_entities) ? fm3.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) : [];
25273
+ const graphRevision = typeof fm3.graph_revision === "string" && fm3.graph_revision.trim() ? fm3.graph_revision.trim() : null;
25259
25274
  const graphCoverage = topology.entities.length === 0 ? "unavailable" : topology.relationships.length > 0 ? "available" : "partial";
25260
25275
  return { affectedSystemEntities: affected, reviewedSystemEntities: reviewed, graphRevision, graphCoverage };
25261
25276
  }
25262
- function parseOriginalSnapshot(fm2) {
25263
- const raw = fm2.original_snapshot;
25277
+ function parseOriginalSnapshot(fm3) {
25278
+ const raw = fm3.original_snapshot;
25264
25279
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
25265
25280
  const o = raw;
25266
25281
  const title = typeof o.title === "string" ? o.title : void 0;
@@ -25367,8 +25382,8 @@ function optStr4(v) {
25367
25382
  if (typeof v === "string" && v.trim()) return v.trim();
25368
25383
  return void 0;
25369
25384
  }
25370
- function parseEvidence(fm2) {
25371
- const evidence = fm2.implementation_evidence;
25385
+ function parseEvidence(fm3) {
25386
+ const evidence = fm3.implementation_evidence;
25372
25387
  const repos = evidence?.repositories;
25373
25388
  if (!repos || typeof repos !== "object" || Array.isArray(repos)) return [];
25374
25389
  const out = [];
@@ -25397,18 +25412,18 @@ function parseEvidence(fm2) {
25397
25412
  }
25398
25413
  return out;
25399
25414
  }
25400
- function parseReleaseGates(fm2) {
25401
- if (!Array.isArray(fm2.release_gates)) return [];
25402
- return fm2.release_gates.filter((g) => g && typeof g === "object").map((g) => ({
25415
+ function parseReleaseGates(fm3) {
25416
+ if (!Array.isArray(fm3.release_gates)) return [];
25417
+ return fm3.release_gates.filter((g) => g && typeof g === "object").map((g) => ({
25403
25418
  id: String(g.id ?? ""),
25404
25419
  status: String(g.status ?? "pending"),
25405
25420
  ...optStr4(g.reason) ? { reason: optStr4(g.reason) } : {},
25406
25421
  ...optStr4(g.required_for) ? { requiredFor: optStr4(g.required_for) } : {}
25407
25422
  }));
25408
25423
  }
25409
- function parseExceptions(fm2) {
25410
- if (!Array.isArray(fm2.completion_exceptions)) return [];
25411
- return fm2.completion_exceptions.filter((e) => e && typeof e === "object").map((e) => ({
25424
+ function parseExceptions(fm3) {
25425
+ if (!Array.isArray(fm3.completion_exceptions)) return [];
25426
+ return fm3.completion_exceptions.filter((e) => e && typeof e === "object").map((e) => ({
25412
25427
  id: String(e.id ?? ""),
25413
25428
  status: String(e.status ?? "proposed"),
25414
25429
  ...optStr4(e.reason) ? { reason: optStr4(e.reason) } : {},
@@ -25426,10 +25441,10 @@ function parseDecisions(decisions, knowledgeById) {
25426
25441
  };
25427
25442
  });
25428
25443
  }
25429
- function parseRelatedKnowledge(fm2, knowledgeById) {
25444
+ function parseRelatedKnowledge(fm3, knowledgeById) {
25430
25445
  const refs = /* @__PURE__ */ new Set();
25431
25446
  for (const field of ["related_knowledge", "knowledge", "related"]) {
25432
- const v = fm2[field];
25447
+ const v = fm3[field];
25433
25448
  if (Array.isArray(v)) {
25434
25449
  for (const r of v) if (typeof r === "string" && r.trim()) refs.add(r.trim());
25435
25450
  }
@@ -26163,11 +26178,11 @@ function verifyWorkItem(dir, workItemId, input) {
26163
26178
  const artifacts = discoverWorkItems(dir);
26164
26179
  const match = artifacts.find((a) => (a.id || a.title) === workItemId);
26165
26180
  const lifecycle = lifecycleStateOf({ status: match.status, filePath: match.filePath });
26166
- const fm2 = match.rawFrontmatter;
26181
+ const fm3 = match.rawFrontmatter;
26167
26182
  const acVerifications = mapACVerifications(input.acVerifications);
26168
26183
  const acSummary = computeACSummary(acVerifications);
26169
- const releaseGates = Array.isArray(fm2.release_gates) ? fm2.release_gates : [];
26170
- const completionExceptions = Array.isArray(fm2.completion_exceptions) ? fm2.completion_exceptions : [];
26184
+ const releaseGates = Array.isArray(fm3.release_gates) ? fm3.release_gates : [];
26185
+ const completionExceptions = Array.isArray(fm3.completion_exceptions) ? fm3.completion_exceptions : [];
26171
26186
  const plannedVsActual = computePlannedVsActual(match.affectedModules, input.repos);
26172
26187
  const registeredModuleIds = loadMappedModules(dir).map((m) => m.id);
26173
26188
  const modifiedRepoIds = input.repos.map((r) => r.repoId);
@@ -26178,7 +26193,7 @@ function verifyWorkItem(dir, workItemId, input) {
26178
26193
  validationStatus: match.validationStatus || "not-started",
26179
26194
  releaseStatus: match.releaseStatus || "not-assessed",
26180
26195
  affectedModules: match.affectedModules,
26181
- rawFrontmatter: fm2,
26196
+ rawFrontmatter: fm3,
26182
26197
  registeredModuleIds,
26183
26198
  modifiedRepoIds
26184
26199
  });
@@ -26363,15 +26378,22 @@ function buildACVerifications(acs, persisted) {
26363
26378
  }
26364
26379
  function extractACsFromBody(body) {
26365
26380
  const lines = body.split(/\r?\n/);
26366
- let inAC = false;
26381
+ let acLevel = 0;
26367
26382
  const acs = [];
26368
26383
  for (const line of lines) {
26369
- if (/^#{1,6}\s+(?:\d+(?:\.\d+)*\.?\s+)?(acceptance\s+criteria|criterios\s+de\s+aceptaci[oó]n)\s*$/i.test(line)) {
26370
- inAC = true;
26384
+ const heading = line.match(/^(#{1,6})\s+(.*)$/);
26385
+ if (heading) {
26386
+ const level = heading[1].length;
26387
+ if (acLevel === 0) {
26388
+ if (/^(?:\d+(?:\.\d+)*\.?\s+)?(acceptance\s+criteria|criterios\s+de\s+aceptaci[oó]n)\s*$/i.test(heading[2].trim())) {
26389
+ acLevel = level;
26390
+ }
26391
+ continue;
26392
+ }
26393
+ if (level <= acLevel) break;
26371
26394
  continue;
26372
26395
  }
26373
- if (inAC && /^#{1,6}\s+/.test(line)) break;
26374
- if (inAC) {
26396
+ if (acLevel > 0) {
26375
26397
  const m = line.match(/^\s*[-*+]\s+(?:\[([ xX])\]\s*)?(.+)$/);
26376
26398
  if (m) {
26377
26399
  const text2 = m[2].trim();
@@ -26412,9 +26434,9 @@ async function runVerify(workItemId, opts = {}) {
26412
26434
  const changedPaths = await getModifiedFiles("head");
26413
26435
  const raw = readFile(match.filePath);
26414
26436
  const parsed = matter26(raw);
26415
- const fm2 = parsed.data;
26437
+ const fm3 = parsed.data;
26416
26438
  const acs = extractACsFromBody(parsed.content);
26417
- const existingEvidence = fm2.implementation_evidence;
26439
+ const existingEvidence = fm3.implementation_evidence;
26418
26440
  const existingRepos = existingEvidence?.repositories ?? {};
26419
26441
  const repos = Object.keys(existingRepos).length > 0 ? Object.entries(existingRepos).map(([repoId, data]) => {
26420
26442
  const d = data;
@@ -27106,14 +27128,476 @@ import matter29 from "gray-matter";
27106
27128
 
27107
27129
  // src/core/initiative-write.ts
27108
27130
  import matter28 from "gray-matter";
27131
+
27132
+ // src/core/initiative-analysis.ts
27133
+ var SUCCESS_HEADING_RE = /^#{1,6}\s*(success criteria|criterios de[ét]xito|criterios de éxito)\s*$/i;
27134
+ var HEADING_RE2 = /^#{1,6}\s+/;
27135
+ var CHECK_ITEM_RE = /^\s*[-*]\s+\[([ xX])\]\s+(.*)$/;
27136
+ var BULLET_RE2 = /^\s*[-*]\s+(.*)$/;
27137
+ var PLACEHOLDER_RE = /^_.*_$/;
27138
+ function parseSuccessCriteria(body) {
27139
+ const lines = body.split(/\r?\n/);
27140
+ const out = [];
27141
+ let capture = false;
27142
+ for (const line of lines) {
27143
+ if (capture && HEADING_RE2.test(line)) break;
27144
+ if (!capture) {
27145
+ if (SUCCESS_HEADING_RE.test(line.trim())) capture = true;
27146
+ continue;
27147
+ }
27148
+ const check = line.match(CHECK_ITEM_RE);
27149
+ if (check) {
27150
+ const text2 = check[2].trim();
27151
+ if (text2 && !PLACEHOLDER_RE.test(text2)) {
27152
+ out.push({ text: text2, checked: check[1].toLowerCase() === "x" });
27153
+ }
27154
+ continue;
27155
+ }
27156
+ const bullet = line.match(BULLET_RE2);
27157
+ if (bullet) {
27158
+ const text2 = bullet[1].trim();
27159
+ if (text2 && !PLACEHOLDER_RE.test(text2)) out.push({ text: text2, checked: null });
27160
+ }
27161
+ }
27162
+ return out;
27163
+ }
27164
+ function analyzeInitiative(dir, ini) {
27165
+ const progress = computeInitiativeProgress(dir, ini);
27166
+ const successCriteria = parseSuccessCriteria(ini.body);
27167
+ const pendingCandidates = ini.candidates.filter((c) => !c.materializedAs);
27168
+ const associated = associatedWorkItems(dir, ini.id);
27169
+ const findings = [];
27170
+ if (successCriteria.length === 0) {
27171
+ findings.push({
27172
+ code: "no-success-criteria",
27173
+ severity: "warning",
27174
+ message: "The Initiative has no explicit Success Criteria; completion cannot be judged by outcome, only by delivery."
27175
+ });
27176
+ } else {
27177
+ const uncovered = successCriteria.filter((c) => c.checked === false);
27178
+ if (uncovered.length > 0) {
27179
+ findings.push({
27180
+ code: "uncovered-success-criteria",
27181
+ severity: "blocking",
27182
+ message: `${uncovered.length} success criterion/criteria remain uncovered.`,
27183
+ items: uncovered.map((c) => c.text)
27184
+ });
27185
+ }
27186
+ }
27187
+ if (pendingCandidates.length > 0) {
27188
+ findings.push({
27189
+ code: "pending-candidates",
27190
+ severity: "blocking",
27191
+ message: `${pendingCandidates.length} committed candidate(s) not yet materialized into Work Items.`,
27192
+ items: pendingCandidates.map((c) => `${c.id}: ${c.title}`)
27193
+ });
27194
+ }
27195
+ const notCompleted = associated.filter((w) => w.status !== "completed" && w.status !== "archived");
27196
+ if (associated.length === 0) {
27197
+ findings.push({
27198
+ code: "no-delivery",
27199
+ severity: "info",
27200
+ message: "No Work Items are associated with this Initiative yet."
27201
+ });
27202
+ } else if (notCompleted.length > 0) {
27203
+ findings.push({
27204
+ code: "incomplete-delivery",
27205
+ severity: "blocking",
27206
+ message: `${notCompleted.length} associated Work Item(s) are not completed.`,
27207
+ items: notCompleted.map((w) => `${w.id} (${w.status})`)
27208
+ });
27209
+ }
27210
+ return {
27211
+ initiative: ini.id,
27212
+ status: ini.status,
27213
+ progress,
27214
+ successCriteria,
27215
+ pendingCandidates,
27216
+ findings,
27217
+ suggestedCandidates: pendingCandidates
27218
+ };
27219
+ }
27220
+
27221
+ // src/core/delivery-verification.ts
27222
+ function normalizeCriterion(text2) {
27223
+ return text2.trim().toLowerCase().replace(/\s+/g, " ");
27224
+ }
27225
+ var STATUSES = ["passed", "failed", "not-verified", "manual-review-required"];
27226
+ function optStr5(v) {
27227
+ if (typeof v === "string" && v.trim()) return v.trim();
27228
+ if (typeof v === "number") return String(v);
27229
+ return void 0;
27230
+ }
27231
+ function parseEvidenceList(raw) {
27232
+ if (!Array.isArray(raw)) return [];
27233
+ const out = [];
27234
+ for (const entry of raw) {
27235
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
27236
+ const o = entry;
27237
+ const criterion = optStr5(o.criterion);
27238
+ if (!criterion) continue;
27239
+ const statusRaw = optStr5(o.status);
27240
+ const status = STATUSES.includes(statusRaw ?? "") ? statusRaw : "not-verified";
27241
+ const method = optStr5(o.method);
27242
+ out.push({
27243
+ criterion,
27244
+ status,
27245
+ ...optStr5(o.evidence) ? { evidence: optStr5(o.evidence) } : {},
27246
+ ...optStr5(o.reference) ? { reference: optStr5(o.reference) } : {},
27247
+ ...method === "automated" || method === "manual" ? { method } : {},
27248
+ ...optStr5(o.verified_at) ? { verified_at: optStr5(o.verified_at) } : {},
27249
+ ...optStr5(o.verified_by) ? { verified_by: optStr5(o.verified_by) } : {}
27250
+ });
27251
+ }
27252
+ return out;
27253
+ }
27254
+ function parseExceptions2(raw) {
27255
+ if (!Array.isArray(raw)) return [];
27256
+ const out = [];
27257
+ for (const entry of raw) {
27258
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
27259
+ const o = entry;
27260
+ const id = optStr5(o.id);
27261
+ if (!id) continue;
27262
+ const st = optStr5(o.status);
27263
+ const status = st === "accepted" || st === "rejected" ? st : "proposed";
27264
+ out.push({
27265
+ id,
27266
+ status,
27267
+ ...optStr5(o.criterion) ? { criterion: optStr5(o.criterion) } : {},
27268
+ ...optStr5(o.reason) ? { reason: optStr5(o.reason) } : {}
27269
+ });
27270
+ }
27271
+ return out;
27272
+ }
27273
+ function buildOutcomeVerification(declared, evidence, exceptions = []) {
27274
+ const byCriterion = /* @__PURE__ */ new Map();
27275
+ for (const e of evidence) byCriterion.set(normalizeCriterion(e.criterion), e);
27276
+ const declaredKeys = new Set(declared.map(normalizeCriterion));
27277
+ const counts = /* @__PURE__ */ new Map();
27278
+ for (const c of declared) counts.set(normalizeCriterion(c), (counts.get(normalizeCriterion(c)) ?? 0) + 1);
27279
+ const ambiguousKeys = new Set([...counts.entries()].filter(([, n]) => n > 1).map(([k]) => k));
27280
+ const waived = new Set(
27281
+ 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))
27282
+ );
27283
+ const criteria = declared.map((criterion) => {
27284
+ const key = normalizeCriterion(criterion);
27285
+ const ambiguous = ambiguousKeys.has(key);
27286
+ const e = ambiguous ? void 0 : byCriterion.get(key);
27287
+ return {
27288
+ criterion,
27289
+ status: e?.status ?? "not-verified",
27290
+ ...e?.evidence ? { evidence: e.evidence } : {},
27291
+ ...e?.reference ? { reference: e.reference } : {},
27292
+ ...e?.method ? { method: e.method } : {},
27293
+ ...e?.verified_at ? { verifiedAt: e.verified_at } : {},
27294
+ ...e?.verified_by ? { verifiedBy: e.verified_by } : {},
27295
+ ...!ambiguous && waived.has(key) ? { waived: true } : {},
27296
+ ...ambiguous ? { ambiguous: true } : {}
27297
+ };
27298
+ });
27299
+ const stale = evidence.filter((e) => !declaredKeys.has(normalizeCriterion(e.criterion)));
27300
+ return {
27301
+ total: criteria.length,
27302
+ // An ambiguous criterion is never counted as passed/waived; it counts as unverified until disambiguated.
27303
+ passed: criteria.filter((c) => !c.ambiguous && (c.status === "passed" || c.waived)).length,
27304
+ failed: criteria.filter((c) => !c.ambiguous && c.status === "failed" && !c.waived).length,
27305
+ notVerified: criteria.filter((c) => c.ambiguous || c.status === "not-verified" && !c.waived).length,
27306
+ manualReview: criteria.filter((c) => !c.ambiguous && c.status === "manual-review-required" && !c.waived).length,
27307
+ ambiguous: criteria.filter((c) => c.ambiguous).length,
27308
+ criteria,
27309
+ stale
27310
+ };
27311
+ }
27312
+ function fm2(entity, key) {
27313
+ return entity.rawFrontmatter?.[key];
27314
+ }
27315
+ function epicOutcomeVerification(epic) {
27316
+ return buildOutcomeVerification(
27317
+ epic.successCriteria,
27318
+ parseEvidenceList(fm2(epic, "outcome_verifications")),
27319
+ parseExceptions2(fm2(epic, "completion_exceptions"))
27320
+ );
27321
+ }
27322
+ function planOutcomeVerification(plan) {
27323
+ return buildOutcomeVerification(
27324
+ plan.successCriteria,
27325
+ parseEvidenceList(fm2(plan, "outcome_verifications")),
27326
+ parseExceptions2(fm2(plan, "completion_exceptions"))
27327
+ );
27328
+ }
27329
+ function planMilestoneVerifications(plan) {
27330
+ const rawMs = Array.isArray(fm2(plan, "milestones")) ? fm2(plan, "milestones") : [];
27331
+ return plan.milestones.map((m) => {
27332
+ const rawEntry = rawMs.find((r) => r && typeof r === "object" && optStr5(r.id)?.toLowerCase() === m.id.toLowerCase());
27333
+ const evidence = parseEvidenceList(rawEntry?.exit_verifications);
27334
+ return { id: m.id, title: m.title, outcome: buildOutcomeVerification(m.exitCriteria, evidence) };
27335
+ });
27336
+ }
27337
+ function decide(blockers, softBlocks, hasAcceptedExceptions) {
27338
+ if (blockers.length > 0) return "BLOCKED";
27339
+ if (softBlocks.length > 0) return "NEEDS_WORK";
27340
+ return hasAcceptedExceptions ? "READY_WITH_EXCEPTIONS" : "READY_TO_COMPLETE";
27341
+ }
27342
+ function evaluateEpicCompletion(dir, epic) {
27343
+ const prog = computeEpicProgress(dir, epic);
27344
+ const exceptions = parseExceptions2(fm2(epic, "completion_exceptions"));
27345
+ const outcome = epicOutcomeVerification(epic);
27346
+ const blockers = [];
27347
+ const softBlocks = [];
27348
+ const reasons = [];
27349
+ const warnings = [];
27350
+ for (const d of prog.readiness.blockingDependencies) blockers.push(`Blocked by unfinished dependency ${d}.`);
27351
+ for (const f of integrityBlockers(dir, epic.id)) blockers.push(f);
27352
+ evaluateOutcomeInto(epic.outcome, true, outcome, blockers, softBlocks, reasons, warnings);
27353
+ if (prog.delivery.total > 0 && prog.delivery.completed < prog.delivery.total) {
27354
+ softBlocks.push("committed-work-incomplete");
27355
+ reasons.push(`Committed work is incomplete (${prog.delivery.completed}/${prog.delivery.total} Work Items completed).`);
27356
+ }
27357
+ const readiness = decide(blockers, softBlocks, exceptions.some((x) => x.status === "accepted"));
27358
+ pushReadinessReason(readiness, reasons);
27359
+ return {
27360
+ id: epic.id,
27361
+ kind: "epic",
27362
+ status: epic.status,
27363
+ readiness,
27364
+ reasons,
27365
+ blockers,
27366
+ warnings,
27367
+ outcome,
27368
+ delivery: { total: prog.delivery.total, completed: prog.delivery.completed, blocked: prog.delivery.blocked },
27369
+ blockingDependencies: prog.readiness.blockingDependencies,
27370
+ exceptions
27371
+ };
27372
+ }
27373
+ function evaluatePlanCompletion(dir, plan) {
27374
+ const prog = computePlanProgress(dir, plan);
27375
+ const exceptions = parseExceptions2(fm2(plan, "completion_exceptions"));
27376
+ const outcome = planOutcomeVerification(plan);
27377
+ const milestones = planMilestoneVerifications(plan);
27378
+ const epics = epicsInPlan(dir, plan.id).map((e) => ({ id: e.id, status: e.status }));
27379
+ const blockers = [];
27380
+ const softBlocks = [];
27381
+ const reasons = [];
27382
+ const warnings = [];
27383
+ for (const d of prog.readiness.blockingDependencies) blockers.push(`Blocked by unfinished dependency ${d}.`);
27384
+ for (const f of integrityBlockers(dir, plan.id)) blockers.push(f);
27385
+ evaluateOutcomeInto(plan.objective, false, outcome, blockers, softBlocks, reasons, warnings);
27386
+ if (!plan.objective) warnings.push("No objective is declared for this Plan (optional, but recommended for completion review).");
27387
+ if (prog.delivery.total > 0 && prog.delivery.completed < prog.delivery.total) {
27388
+ softBlocks.push("committed-work-incomplete");
27389
+ reasons.push(`Committed work is incomplete (${prog.delivery.completed}/${prog.delivery.total} Work Items completed).`);
27390
+ }
27391
+ if (epics.length === 0 && prog.delivery.total === 0) {
27392
+ softBlocks.push("no-committed-work");
27393
+ reasons.push("No Epics and no committed Work Items \u2014 the Plan has no verifiable deliverables yet.");
27394
+ }
27395
+ const openEpics = epics.filter((e) => e.status !== "completed" && e.status !== "cancelled");
27396
+ if (openEpics.length > 0) {
27397
+ softBlocks.push("epics-open");
27398
+ reasons.push(`${openEpics.length} Epic(s) not yet completed: ${openEpics.map((e) => e.id).join(", ")}.`);
27399
+ }
27400
+ for (const m of milestones) {
27401
+ if (m.outcome.failed > 0) {
27402
+ blockers.push(`Milestone ${m.id} has a failed exit criterion.`);
27403
+ }
27404
+ const pending = m.outcome.notVerified + m.outcome.manualReview;
27405
+ if (pending > 0) {
27406
+ softBlocks.push(`milestone-${m.id}-pending`);
27407
+ reasons.push(`Milestone ${m.id}: ${pending} exit criterion(s) not verified.`);
27408
+ }
27409
+ if (m.outcome.stale.length > 0) warnings.push(`Milestone ${m.id} has stale exit-criteria evidence.`);
27410
+ }
27411
+ const readiness = decide(blockers, softBlocks, exceptions.some((x) => x.status === "accepted"));
27412
+ pushReadinessReason(readiness, reasons);
27413
+ return {
27414
+ id: plan.id,
27415
+ kind: "plan",
27416
+ status: plan.status,
27417
+ readiness,
27418
+ reasons,
27419
+ blockers,
27420
+ warnings,
27421
+ outcome,
27422
+ delivery: { total: prog.delivery.total, completed: prog.delivery.completed, blocked: prog.delivery.blocked },
27423
+ blockingDependencies: prog.readiness.blockingDependencies,
27424
+ milestones,
27425
+ epics,
27426
+ exceptions
27427
+ };
27428
+ }
27429
+ function integrityBlockers(dir, subjectId) {
27430
+ return validatePlanningGraph(dir).filter((f) => f.level === "error" && f.subject.toLowerCase() === subjectId.toLowerCase()).map((f) => f.message);
27431
+ }
27432
+ function evaluateOutcomeInto(declaredOutcome, requireDeclaredOutcome, outcome, blockers, softBlocks, reasons, warnings) {
27433
+ if (requireDeclaredOutcome && !declaredOutcome) {
27434
+ softBlocks.push("no-outcome");
27435
+ reasons.push("No expected outcome is declared.");
27436
+ }
27437
+ if (outcome.total === 0) {
27438
+ softBlocks.push("no-success-criteria");
27439
+ reasons.push("No success criteria to verify \u2014 completion cannot be judged by outcome.");
27440
+ }
27441
+ if (outcome.ambiguous > 0) {
27442
+ softBlocks.push("criteria-ambiguous");
27443
+ reasons.push(`${outcome.ambiguous} success criterion(s) collide in text \u2014 rename to disambiguate before verifying.`);
27444
+ }
27445
+ if (outcome.failed > 0) {
27446
+ softBlocks.push("criteria-failed");
27447
+ reasons.push(`${outcome.failed} success criterion(s) failed verification.`);
27448
+ }
27449
+ const pending = outcome.notVerified + outcome.manualReview - outcome.ambiguous;
27450
+ if (pending > 0) {
27451
+ softBlocks.push("criteria-unverified");
27452
+ reasons.push(`${pending} success criterion(s) not verified (no or insufficient evidence).`);
27453
+ }
27454
+ if (outcome.stale.length > 0) warnings.push(`${outcome.stale.length} evidence record(s) no longer match a declared criterion (stale).`);
27455
+ }
27456
+ function pushReadinessReason(readiness, reasons) {
27457
+ if (readiness === "READY_TO_COMPLETE") reasons.unshift("All success criteria are verified and committed work is complete. Human approval is still required to close.");
27458
+ else if (readiness === "READY_WITH_EXCEPTIONS") reasons.unshift("Remaining gaps are covered by accepted exceptions. Human approval is still required to close.");
27459
+ }
27460
+
27461
+ // src/core/initiative-verification.ts
27462
+ function optStr6(v) {
27463
+ return typeof v === "string" && v.trim() ? v.trim() : void 0;
27464
+ }
27465
+ function parseCompletionExceptions(raw) {
27466
+ if (!Array.isArray(raw)) return [];
27467
+ const out = [];
27468
+ for (const entry of raw) {
27469
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
27470
+ const o = entry;
27471
+ const id = optStr6(o.id);
27472
+ if (!id) continue;
27473
+ const st = optStr6(o.status);
27474
+ out.push({
27475
+ id,
27476
+ status: st === "accepted" || st === "rejected" ? st : "proposed",
27477
+ ...optStr6(o.criterion) ? { criterion: optStr6(o.criterion) } : {},
27478
+ ...optStr6(o.reason) ? { reason: optStr6(o.reason) } : {}
27479
+ });
27480
+ }
27481
+ return out;
27482
+ }
27483
+ function initiativeOutcomeVerification(ini) {
27484
+ const declared = parseSuccessCriteria(ini.body).map((c) => c.text);
27485
+ const evidence = parseEvidenceList(ini.rawFrontmatter?.outcome_verifications);
27486
+ const exceptions = parseCompletionExceptions(ini.rawFrontmatter?.completion_exceptions);
27487
+ return buildOutcomeVerification(declared, evidence, exceptions);
27488
+ }
27489
+ function initiativeProvenanceIssues(dir, ini) {
27490
+ const issues = [];
27491
+ const wis = discoverWorkItems(dir);
27492
+ for (const c of ini.candidates) {
27493
+ if (!c.materializedAs) continue;
27494
+ const wi = wis.find((w) => w.id.toLowerCase() === c.materializedAs.toLowerCase());
27495
+ if (!wi) {
27496
+ issues.push(`Candidate ${c.id} points at missing Work Item ${c.materializedAs}.`);
27497
+ continue;
27498
+ }
27499
+ const owner = typeof wi.rawFrontmatter?.initiative === "string" ? wi.rawFrontmatter.initiative : void 0;
27500
+ if (owner && owner.toLowerCase() !== ini.id.toLowerCase()) {
27501
+ issues.push(`Work Item ${wi.id} (materialized from ${c.id}) is associated with ${owner}, not ${ini.id}.`);
27502
+ }
27503
+ }
27504
+ return issues;
27505
+ }
27506
+ function decide2(blockers, softBlocks, hasAcceptedExceptions) {
27507
+ if (blockers.length > 0) return "BLOCKED";
27508
+ if (softBlocks.length > 0) return "NEEDS_WORK";
27509
+ return hasAcceptedExceptions ? "READY_WITH_EXCEPTIONS" : "READY_TO_COMPLETE";
27510
+ }
27511
+ function evaluateInitiativeCompletion(dir, ini) {
27512
+ const progress = computeInitiativeProgress(dir, ini);
27513
+ const outcome = initiativeOutcomeVerification(ini);
27514
+ const exceptions = parseCompletionExceptions(ini.rawFrontmatter?.completion_exceptions);
27515
+ const pending = ini.candidates.filter((c) => !c.materializedAs);
27516
+ const associated = associatedWorkItems(dir, ini.id);
27517
+ const incomplete = associated.filter((w) => w.status !== "completed" && w.status !== "archived");
27518
+ const provenanceIssues = initiativeProvenanceIssues(dir, ini);
27519
+ const blockers = [];
27520
+ const softBlocks = [];
27521
+ const reasons = [];
27522
+ const warnings = [];
27523
+ for (const p of provenanceIssues) blockers.push(p);
27524
+ if (outcome.total === 0) {
27525
+ softBlocks.push("no-success-criteria");
27526
+ reasons.push("No success criteria to verify \u2014 completion cannot be judged by outcome.");
27527
+ }
27528
+ if (outcome.ambiguous > 0) {
27529
+ softBlocks.push("criteria-ambiguous");
27530
+ reasons.push(`${outcome.ambiguous} success criterion(s) collide in text \u2014 disambiguate before verifying.`);
27531
+ }
27532
+ if (outcome.failed > 0) {
27533
+ softBlocks.push("criteria-failed");
27534
+ reasons.push(`${outcome.failed} success criterion(s) failed verification.`);
27535
+ }
27536
+ const unverified = outcome.notVerified + outcome.manualReview - outcome.ambiguous;
27537
+ if (unverified > 0) {
27538
+ softBlocks.push("criteria-unverified");
27539
+ reasons.push(`${unverified} success criterion(s) not verified (no or insufficient evidence).`);
27540
+ }
27541
+ if (outcome.stale.length > 0) warnings.push(`${outcome.stale.length} evidence record(s) no longer match a declared criterion (stale).`);
27542
+ if (pending.length > 0) {
27543
+ softBlocks.push("pending-candidates");
27544
+ reasons.push(`${pending.length} committed candidate(s) not yet materialized.`);
27545
+ }
27546
+ if (incomplete.length > 0) {
27547
+ softBlocks.push("incomplete-delivery");
27548
+ reasons.push(`${incomplete.length} associated Work Item(s) are not completed.`);
27549
+ }
27550
+ if (associated.length === 0 && pending.length === 0) {
27551
+ softBlocks.push("no-deliverables");
27552
+ reasons.push("Nothing has been delivered or committed under this Initiative.");
27553
+ }
27554
+ const readiness = decide2(blockers, softBlocks, exceptions.some((x) => x.status === "accepted"));
27555
+ if (readiness === "READY_TO_COMPLETE") reasons.unshift("All success criteria are verified and committed scope is delivered. Human approval is still required to close.");
27556
+ else if (readiness === "READY_WITH_EXCEPTIONS") reasons.unshift("Remaining gaps are covered by accepted exceptions. Human approval is still required to close.");
27557
+ const completed = progress.delivery.byState?.completed ?? 0;
27558
+ return {
27559
+ id: ini.id,
27560
+ kind: "initiative",
27561
+ status: ini.status,
27562
+ readiness,
27563
+ ready: readiness === "READY_TO_COMPLETE" || readiness === "READY_WITH_EXCEPTIONS",
27564
+ reasons,
27565
+ blockers,
27566
+ warnings,
27567
+ outcome,
27568
+ delivery: { total: progress.delivery.total, completed, incomplete: incomplete.length },
27569
+ pendingCandidates: pending.map((c) => c.id),
27570
+ provenanceIssues,
27571
+ exceptions
27572
+ };
27573
+ }
27574
+
27575
+ // src/core/initiative-write.ts
27109
27576
  var WORK_ITEMS_DIR4 = "knowledge/delivery/work-items";
27110
27577
  var DRAFT_DIR2 = `${WORK_ITEMS_DIR4}/draft`;
27578
+ function assertFreshInitiative(id, currentContent, opts) {
27579
+ if (!opts?.expectedRevision) return;
27580
+ const actual = revisionOf(currentContent);
27581
+ if (actual !== opts.expectedRevision) throw new InitiativeConflictError(id, opts.expectedRevision, actual);
27582
+ }
27111
27583
  var InitiativeWriteError = class extends Error {
27112
27584
  constructor(message) {
27113
27585
  super(message);
27114
27586
  this.name = "InitiativeWriteError";
27115
27587
  }
27116
27588
  };
27589
+ var InitiativeConflictError = class extends InitiativeWriteError {
27590
+ constructor(id, expectedRevision, actualRevision) {
27591
+ super(`Initiative "${id}" was modified since it was loaded (expected revision ${expectedRevision}, found ${actualRevision}). Reload and try again.`);
27592
+ this.id = id;
27593
+ this.expectedRevision = expectedRevision;
27594
+ this.actualRevision = actualRevision;
27595
+ this.name = "InitiativeConflictError";
27596
+ }
27597
+ id;
27598
+ expectedRevision;
27599
+ actualRevision;
27600
+ };
27117
27601
  function slugify7(s) {
27118
27602
  return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 50);
27119
27603
  }
@@ -27235,29 +27719,76 @@ function createInitiative(dir, input) {
27235
27719
  if (!ini) throw new InitiativeWriteError("Failed to parse the Initiative just written.");
27236
27720
  return ini;
27237
27721
  }
27238
- function transitionInitiative(dir, id, to) {
27722
+ function transitionInitiative(dir, id, to, opts) {
27239
27723
  const ini = getInitiative(dir, id);
27240
27724
  if (!ini) throw new InitiativeWriteError(`Initiative ${id} not found.`);
27241
27725
  if (!isValidInitiativeStatus(to)) throw new InitiativeWriteError(`Invalid status: ${to}.`);
27726
+ if (to === "completed") throw new InitiativeWriteError(`Completing Initiative ${id} requires evidence-based review \u2014 use completeInitiative.`);
27242
27727
  if (ini.status === to) return ini;
27243
27728
  if (!isValidInitiativeTransition(ini.status, to)) {
27244
27729
  throw new InitiativeWriteError(`Invalid transition ${ini.status} \u2192 ${to}.`);
27245
27730
  }
27246
27731
  const raw = readFile(ini.filePath);
27732
+ assertFreshInitiative(ini.id, raw, opts);
27247
27733
  const { data, content } = matter28(raw, {});
27248
27734
  data.status = to;
27249
- if (to === "completed") data.completed_at = today2();
27250
27735
  const newContent = matter28.stringify(content, data);
27251
27736
  writeFile(ini.filePath, newContent);
27252
27737
  const updated = parseInitiative(dir, ini.filePath, newContent);
27253
27738
  if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after transition.");
27254
27739
  return updated;
27255
27740
  }
27256
- function updateInitiative(dir, id, patch) {
27741
+ function findMaterializedWorkItem(dir, initiativeId, candidateId) {
27742
+ for (const wi of discoverWorkItems(dir)) {
27743
+ const fm3 = wi.rawFrontmatter ?? {};
27744
+ const si = typeof fm3.source_initiative === "string" ? fm3.source_initiative : void 0;
27745
+ const sid = typeof fm3.source_id === "string" ? fm3.source_id : void 0;
27746
+ if (si?.toLowerCase() === initiativeId.toLowerCase() && sid === candidateId) {
27747
+ return { id: wi.id, initiative: typeof fm3.initiative === "string" ? fm3.initiative : void 0 };
27748
+ }
27749
+ }
27750
+ return null;
27751
+ }
27752
+ function replaceBodySection(body, heading, newContent) {
27753
+ const lines = body.split(/\r?\n/);
27754
+ const want = heading.trim().toLowerCase();
27755
+ let start = -1;
27756
+ let level = 0;
27757
+ for (let i = 0; i < lines.length; i++) {
27758
+ const h = lines[i].match(/^(#{1,6})\s+(.*)$/);
27759
+ if (h && h[2].trim().toLowerCase() === want) {
27760
+ start = i;
27761
+ level = h[1].length;
27762
+ break;
27763
+ }
27764
+ }
27765
+ const block = `${"#".repeat(level || 2)} ${heading.trim()}
27766
+
27767
+ ${newContent.trim()}
27768
+ `;
27769
+ if (start === -1) {
27770
+ return `${body.trimEnd()}
27771
+
27772
+ ${block}`;
27773
+ }
27774
+ let end = lines.length;
27775
+ for (let i = start + 1; i < lines.length; i++) {
27776
+ const h = lines[i].match(/^(#{1,6})\s+/);
27777
+ if (h && h[1].length <= level) {
27778
+ end = i;
27779
+ break;
27780
+ }
27781
+ }
27782
+ const before = lines.slice(0, start).join("\n").replace(/\s+$/, "");
27783
+ const after = lines.slice(end).join("\n").replace(/^\s+/, "");
27784
+ return [before, before ? "" : null, block.trimEnd(), after ? "" : null, after].filter((x) => x !== null).join("\n").replace(/\n{3,}/g, "\n\n");
27785
+ }
27786
+ function updateInitiative(dir, id, patch, opts) {
27257
27787
  const ini = getInitiative(dir, id);
27258
27788
  if (!ini) throw new InitiativeWriteError(`Initiative ${id} not found.`);
27259
27789
  const raw = readFile(ini.filePath);
27260
- const { data, content } = matter28(raw, {});
27790
+ assertFreshInitiative(ini.id, raw, opts);
27791
+ let { data, content } = matter28(raw, {});
27261
27792
  if (patch.title !== void 0) {
27262
27793
  if (!patch.title.trim()) throw new InitiativeWriteError("Initiative title cannot be empty.");
27263
27794
  data.title = patch.title.trim();
@@ -27273,6 +27804,9 @@ function updateInitiative(dir, id, patch) {
27273
27804
  }
27274
27805
  if (patch.owners !== void 0) data.owners = patch.owners.map((o) => o.trim()).filter(Boolean);
27275
27806
  if (patch.contributors !== void 0) data.contributors = patch.contributors.map((c) => c.trim()).filter(Boolean);
27807
+ if (patch.sections) {
27808
+ for (const [heading, value] of Object.entries(patch.sections)) content = replaceBodySection(content, heading, value);
27809
+ }
27276
27810
  const newContent = matter28.stringify(content, data);
27277
27811
  writeFile(ini.filePath, newContent);
27278
27812
  const updated = parseInitiative(dir, ini.filePath, newContent);
@@ -27344,32 +27878,74 @@ function buildWorkItemContent(wiId, iniId, candidate) {
27344
27878
  ].join("\n");
27345
27879
  return matter28.stringify("\n" + body, data);
27346
27880
  }
27347
- function materializeCandidate(dir, id, candidateId) {
27881
+ function setCandidateMaterialized(dir, ini, candidateId, wiId) {
27882
+ const raw = readFile(ini.filePath);
27883
+ const { data, content } = matter28(raw, {});
27884
+ const cands = Array.isArray(data.candidates) ? data.candidates : [];
27885
+ for (const c of cands) if (c && typeof c === "object" && String(c.id) === candidateId) c.materialized_as = wiId;
27886
+ data.candidates = cands;
27887
+ const newContent = matter28.stringify(content, data);
27888
+ writeFile(ini.filePath, newContent);
27889
+ const updated = parseInitiative(dir, ini.filePath, newContent);
27890
+ if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after materialization.");
27891
+ return updated;
27892
+ }
27893
+ function materializeCandidate(dir, id, candidateId, opts) {
27348
27894
  const ini = getInitiative(dir, id);
27349
27895
  if (!ini) throw new InitiativeWriteError(`Initiative ${id} not found.`);
27896
+ assertFreshInitiative(ini.id, readFile(ini.filePath), opts);
27350
27897
  const candidate = ini.candidates.find((c) => c.id === candidateId);
27351
27898
  if (!candidate) throw new InitiativeWriteError(`Candidate ${candidateId} not found in ${id}.`);
27352
27899
  if (candidate.materializedAs) {
27353
- throw new InitiativeWriteError(
27354
- `Candidate ${candidateId} is already materialized as ${candidate.materializedAs}.`
27355
- );
27900
+ const exists3 = discoverWorkItems(dir).some((w) => w.id.toLowerCase() === candidate.materializedAs.toLowerCase());
27901
+ if (!exists3) throw new InitiativeWriteError(`Candidate ${candidateId} points at missing Work Item ${candidate.materializedAs} (broken relation). Resolve it before materializing.`);
27902
+ return { workItemId: candidate.materializedAs, fileName: null, initiative: ini, alreadyMaterialized: true };
27903
+ }
27904
+ const existing = findMaterializedWorkItem(dir, ini.id, candidateId);
27905
+ if (existing) {
27906
+ if (existing.initiative && existing.initiative.toLowerCase() !== ini.id.toLowerCase()) {
27907
+ throw new InitiativeWriteError(`A Work Item for candidate ${candidateId} already belongs to ${existing.initiative} (conflicting provenance).`);
27908
+ }
27909
+ const repaired = setCandidateMaterialized(dir, ini, candidateId, existing.id);
27910
+ return { workItemId: existing.id, fileName: null, initiative: repaired, alreadyMaterialized: true };
27356
27911
  }
27357
27912
  const wiId = nextWorkItemId3(dir);
27358
27913
  const fileName = `${wiId}-${slugify7(candidate.title)}.md`;
27359
27914
  ensureDir(join(dir, DRAFT_DIR2));
27360
27915
  writeFile(join(dir, DRAFT_DIR2, fileName), buildWorkItemContent(wiId, ini.id, candidate));
27916
+ const updated = setCandidateMaterialized(dir, ini, candidateId, wiId);
27917
+ return { workItemId: wiId, fileName, initiative: updated, alreadyMaterialized: false };
27918
+ }
27919
+ var InitiativeNotReadyError = class extends InitiativeWriteError {
27920
+ constructor(evaluation) {
27921
+ super(`Initiative ${evaluation.id} is not ready to complete (${evaluation.readiness}).`);
27922
+ this.evaluation = evaluation;
27923
+ this.name = "InitiativeNotReadyError";
27924
+ }
27925
+ evaluation;
27926
+ };
27927
+ function completeInitiative(dir, id, input = {}, opts) {
27928
+ const ini = getInitiative(dir, id);
27929
+ if (!ini) throw new InitiativeWriteError(`Initiative ${id} not found.`);
27930
+ const evaluation = evaluateInitiativeCompletion(dir, ini);
27931
+ if (evaluation.readiness !== "READY_TO_COMPLETE" && evaluation.readiness !== "READY_WITH_EXCEPTIONS") throw new InitiativeNotReadyError(evaluation);
27932
+ if (!isValidInitiativeTransition(ini.status, "completed")) throw new InitiativeWriteError(`Initiative ${id} cannot move from ${ini.status} to completed.`);
27361
27933
  const raw = readFile(ini.filePath);
27934
+ assertFreshInitiative(ini.id, raw, opts);
27362
27935
  const { data, content } = matter28(raw, {});
27363
- const cands = Array.isArray(data.candidates) ? data.candidates : [];
27364
- for (const c of cands) {
27365
- if (c && typeof c === "object" && String(c.id) === candidateId) c.materialized_as = wiId;
27366
- }
27367
- data.candidates = cands;
27936
+ data.status = "completed";
27937
+ data.completed_at = today2();
27938
+ const decision = { readiness: evaluation.readiness, decided_at: today2(), reasons: evaluation.reasons };
27939
+ if (input.decidedBy?.trim()) decision.decided_by = input.decidedBy.trim();
27940
+ if (input.note?.trim()) decision.note = input.note.trim();
27941
+ const accepted = evaluation.exceptions.filter((x) => x.status === "accepted");
27942
+ if (accepted.length > 0) decision.exceptions = accepted;
27943
+ data.completion_decision = decision;
27368
27944
  const newContent = matter28.stringify(content, data);
27369
27945
  writeFile(ini.filePath, newContent);
27370
27946
  const updated = parseInitiative(dir, ini.filePath, newContent);
27371
- if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after materialization.");
27372
- return { workItemId: wiId, fileName, initiative: updated };
27947
+ if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after completion.");
27948
+ return updated;
27373
27949
  }
27374
27950
 
27375
27951
  // src/core/delivery-planning-write.ts
@@ -27379,6 +27955,23 @@ var DeliveryPlanningWriteError = class extends Error {
27379
27955
  this.name = "DeliveryPlanningWriteError";
27380
27956
  }
27381
27957
  };
27958
+ var PlanningConflictError = class extends Error {
27959
+ constructor(id, expectedRevision, actualRevision) {
27960
+ super(`"${id}" was modified since it was loaded (expected revision ${expectedRevision}, found ${actualRevision}). Reload and try again.`);
27961
+ this.id = id;
27962
+ this.expectedRevision = expectedRevision;
27963
+ this.actualRevision = actualRevision;
27964
+ this.name = "PlanningConflictError";
27965
+ }
27966
+ id;
27967
+ expectedRevision;
27968
+ actualRevision;
27969
+ };
27970
+ function assertFreshRevision(id, currentContent, opts) {
27971
+ if (!opts?.expectedRevision) return;
27972
+ const actual = revisionOf(currentContent);
27973
+ if (actual !== opts.expectedRevision) throw new PlanningConflictError(id, opts.expectedRevision, actual);
27974
+ }
27382
27975
  function slugify8(s) {
27383
27976
  return s.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "item";
27384
27977
  }
@@ -27439,6 +28032,163 @@ function associateInitiativeWithEpic(dir, initiativeId, epicId) {
27439
28032
  if (!getEpic(dir, epicId)) throw new DeliveryPlanningWriteError(`Epic ${epicId} does not exist.`);
27440
28033
  return updateInitiative(dir, ini.id, { epic: epicId });
27441
28034
  }
28035
+ function today3() {
28036
+ return (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
28037
+ }
28038
+ var PlanningNotReadyError = class extends DeliveryPlanningWriteError {
28039
+ constructor(evaluation) {
28040
+ super(`${evaluation.kind === "plan" ? "Plan" : "Epic"} ${evaluation.id} is not ready to complete (${evaluation.readiness}).`);
28041
+ this.evaluation = evaluation;
28042
+ this.name = "PlanningNotReadyError";
28043
+ }
28044
+ evaluation;
28045
+ };
28046
+ function transitionDeliveryPlan(dir, id, to, opts) {
28047
+ const plan = getPlan(dir, id);
28048
+ if (!plan) throw new DeliveryPlanningWriteError(`Plan ${id} does not exist.`);
28049
+ if (!PLAN_STATES.includes(to)) throw new DeliveryPlanningWriteError(`Invalid plan status: ${to}.`);
28050
+ if (to === "completed") throw new DeliveryPlanningWriteError(`Completing Plan ${id} requires evidence-based review \u2014 use completeDeliveryPlan.`);
28051
+ const raw = readFile(plan.filePath);
28052
+ assertFreshRevision(plan.id, raw, opts);
28053
+ if (plan.status === to) return plan;
28054
+ if (!PLAN_TRANSITIONS[plan.status].includes(to)) throw new DeliveryPlanningWriteError(`Invalid transition ${plan.status} \u2192 ${to} for Plan ${id}.`);
28055
+ const { data, content } = matter29(raw, {});
28056
+ data.status = to;
28057
+ if (to === "completed") data.completed_at = today3();
28058
+ const newContent = matter29.stringify(content, data);
28059
+ writeFile(plan.filePath, newContent);
28060
+ const updated = parseDeliveryPlan(dir, plan.filePath, newContent);
28061
+ if (!updated) throw new DeliveryPlanningWriteError("Failed to parse the Plan after transition.");
28062
+ return updated;
28063
+ }
28064
+ function transitionEpic(dir, id, to, opts) {
28065
+ const epic = getEpic(dir, id);
28066
+ if (!epic) throw new DeliveryPlanningWriteError(`Epic ${id} does not exist.`);
28067
+ if (!EPIC_STATES.includes(to)) throw new DeliveryPlanningWriteError(`Invalid epic status: ${to}.`);
28068
+ if (to === "completed") throw new DeliveryPlanningWriteError(`Completing Epic ${id} requires evidence-based review \u2014 use completeEpic.`);
28069
+ const raw = readFile(epic.filePath);
28070
+ assertFreshRevision(epic.id, raw, opts);
28071
+ if (epic.status === to) return epic;
28072
+ if (!EPIC_TRANSITIONS[epic.status].includes(to)) throw new DeliveryPlanningWriteError(`Invalid transition ${epic.status} \u2192 ${to} for Epic ${id}.`);
28073
+ const { data, content } = matter29(raw, {});
28074
+ data.status = to;
28075
+ if (to === "completed") data.completed_at = today3();
28076
+ const newContent = matter29.stringify(content, data);
28077
+ writeFile(epic.filePath, newContent);
28078
+ const updated = parseEpic(dir, epic.filePath, newContent);
28079
+ if (!updated) throw new DeliveryPlanningWriteError("Failed to parse the Epic after transition.");
28080
+ return updated;
28081
+ }
28082
+ function assertCriterionDeclared(declared, criterion, kind) {
28083
+ const key = normalizeCriterion(criterion);
28084
+ const matches = declared.filter((c) => normalizeCriterion(c) === key).length;
28085
+ if (matches === 0) throw new DeliveryPlanningWriteError(`"${criterion}" is not a declared ${kind} criterion.`);
28086
+ if (matches > 1) throw new DeliveryPlanningWriteError(`"${criterion}" matches more than one declared ${kind} criterion \u2014 rename them to disambiguate before recording evidence.`);
28087
+ }
28088
+ function upsertEvidence(existing, input) {
28089
+ const list2 = Array.isArray(existing) ? existing.filter((e) => e && typeof e === "object" && !Array.isArray(e)) : [];
28090
+ const key = normalizeCriterion(input.criterion);
28091
+ const kept = list2.filter((e) => normalizeCriterion(String(e.criterion ?? "")) !== key);
28092
+ const obj = { criterion: input.criterion.trim(), status: input.status };
28093
+ if (input.evidence?.trim()) obj.evidence = input.evidence.trim();
28094
+ if (input.reference?.trim()) obj.reference = input.reference.trim();
28095
+ if (input.method) obj.method = input.method;
28096
+ obj.verified_at = today3();
28097
+ if (input.verifiedBy?.trim()) obj.verified_by = input.verifiedBy.trim();
28098
+ return [...kept, obj];
28099
+ }
28100
+ function recordEpicOutcomeVerification(dir, id, input, opts) {
28101
+ const epic = getEpic(dir, id);
28102
+ if (!epic) throw new DeliveryPlanningWriteError(`Epic ${id} does not exist.`);
28103
+ assertCriterionDeclared(epic.successCriteria, input.criterion, "success");
28104
+ const raw = readFile(epic.filePath);
28105
+ assertFreshRevision(epic.id, raw, opts);
28106
+ const { data, content } = matter29(raw, {});
28107
+ data.outcome_verifications = upsertEvidence(data.outcome_verifications, input);
28108
+ const newContent = matter29.stringify(content, data);
28109
+ writeFile(epic.filePath, newContent);
28110
+ const updated = parseEpic(dir, epic.filePath, newContent);
28111
+ if (!updated) throw new DeliveryPlanningWriteError("Failed to parse the Epic after recording evidence.");
28112
+ return updated;
28113
+ }
28114
+ function recordPlanOutcomeVerification(dir, id, input, opts) {
28115
+ const plan = getPlan(dir, id);
28116
+ if (!plan) throw new DeliveryPlanningWriteError(`Plan ${id} does not exist.`);
28117
+ assertCriterionDeclared(plan.successCriteria, input.criterion, "success");
28118
+ const raw = readFile(plan.filePath);
28119
+ assertFreshRevision(plan.id, raw, opts);
28120
+ const { data, content } = matter29(raw, {});
28121
+ data.outcome_verifications = upsertEvidence(data.outcome_verifications, input);
28122
+ const newContent = matter29.stringify(content, data);
28123
+ writeFile(plan.filePath, newContent);
28124
+ const updated = parseDeliveryPlan(dir, plan.filePath, newContent);
28125
+ if (!updated) throw new DeliveryPlanningWriteError("Failed to parse the Plan after recording evidence.");
28126
+ return updated;
28127
+ }
28128
+ function recordMilestoneExitVerification(dir, planId, milestoneId, input, opts) {
28129
+ const plan = getPlan(dir, planId);
28130
+ if (!plan) throw new DeliveryPlanningWriteError(`Plan ${planId} does not exist.`);
28131
+ const milestone = plan.milestones.find((m) => m.id.toLowerCase() === milestoneId.toLowerCase());
28132
+ if (!milestone) throw new DeliveryPlanningWriteError(`Milestone ${milestoneId} is not defined in ${planId}.`);
28133
+ assertCriterionDeclared(milestone.exitCriteria, input.criterion, "exit");
28134
+ const raw = readFile(plan.filePath);
28135
+ assertFreshRevision(plan.id, raw, opts);
28136
+ const { data, content } = matter29(raw, {});
28137
+ const rawMs = Array.isArray(data.milestones) ? data.milestones : [];
28138
+ const entry = rawMs.find((m) => m && typeof m === "object" && String(m.id ?? "").toLowerCase() === milestoneId.toLowerCase());
28139
+ if (!entry) throw new DeliveryPlanningWriteError(`Milestone ${milestoneId} entry not found in ${planId} frontmatter.`);
28140
+ entry.exit_verifications = upsertEvidence(entry.exit_verifications, input);
28141
+ data.milestones = rawMs;
28142
+ const newContent = matter29.stringify(content, data);
28143
+ writeFile(plan.filePath, newContent);
28144
+ const updated = parseDeliveryPlan(dir, plan.filePath, newContent);
28145
+ if (!updated) throw new DeliveryPlanningWriteError("Failed to parse the Plan after recording milestone evidence.");
28146
+ return updated;
28147
+ }
28148
+ function completionDecisionRecord(evaluation, input) {
28149
+ const rec = { readiness: evaluation.readiness, decided_at: today3(), reasons: evaluation.reasons };
28150
+ if (input.decidedBy?.trim()) rec.decided_by = input.decidedBy.trim();
28151
+ if (input.note?.trim()) rec.note = input.note.trim();
28152
+ const acceptedExceptions = evaluation.exceptions.filter((x) => x.status === "accepted");
28153
+ if (acceptedExceptions.length > 0) rec.exceptions = acceptedExceptions;
28154
+ return rec;
28155
+ }
28156
+ function completeEpic(dir, id, input = {}, opts) {
28157
+ const epic = getEpic(dir, id);
28158
+ if (!epic) throw new DeliveryPlanningWriteError(`Epic ${id} does not exist.`);
28159
+ const evaluation = evaluateEpicCompletion(dir, epic);
28160
+ if (evaluation.readiness !== "READY_TO_COMPLETE" && evaluation.readiness !== "READY_WITH_EXCEPTIONS") throw new PlanningNotReadyError(evaluation);
28161
+ if (!EPIC_TRANSITIONS[epic.status].includes("completed")) throw new DeliveryPlanningWriteError(`Epic ${id} cannot move from ${epic.status} to completed.`);
28162
+ const raw = readFile(epic.filePath);
28163
+ assertFreshRevision(epic.id, raw, opts);
28164
+ const { data, content } = matter29(raw, {});
28165
+ data.status = "completed";
28166
+ data.completed_at = today3();
28167
+ data.completion_decision = completionDecisionRecord(evaluation, input);
28168
+ const newContent = matter29.stringify(content, data);
28169
+ writeFile(epic.filePath, newContent);
28170
+ const updated = parseEpic(dir, epic.filePath, newContent);
28171
+ if (!updated) throw new DeliveryPlanningWriteError("Failed to parse the Epic after completion.");
28172
+ return updated;
28173
+ }
28174
+ function completeDeliveryPlan(dir, id, input = {}, opts) {
28175
+ const plan = getPlan(dir, id);
28176
+ if (!plan) throw new DeliveryPlanningWriteError(`Plan ${id} does not exist.`);
28177
+ const evaluation = evaluatePlanCompletion(dir, plan);
28178
+ if (evaluation.readiness !== "READY_TO_COMPLETE" && evaluation.readiness !== "READY_WITH_EXCEPTIONS") throw new PlanningNotReadyError(evaluation);
28179
+ if (!PLAN_TRANSITIONS[plan.status].includes("completed")) throw new DeliveryPlanningWriteError(`Plan ${id} cannot move from ${plan.status} to completed.`);
28180
+ const raw = readFile(plan.filePath);
28181
+ assertFreshRevision(plan.id, raw, opts);
28182
+ const { data, content } = matter29(raw, {});
28183
+ data.status = "completed";
28184
+ data.completed_at = today3();
28185
+ data.completion_decision = completionDecisionRecord(evaluation, input);
28186
+ const newContent = matter29.stringify(content, data);
28187
+ writeFile(plan.filePath, newContent);
28188
+ const updated = parseDeliveryPlan(dir, plan.filePath, newContent);
28189
+ if (!updated) throw new DeliveryPlanningWriteError("Failed to parse the Plan after completion.");
28190
+ return updated;
28191
+ }
27442
28192
 
27443
28193
  // src/commands/plan.ts
27444
28194
  function requireInit(dir) {
@@ -27631,6 +28381,186 @@ async function runEpicAssociate(epicId, initiativeId) {
27631
28381
  process.exit(1);
27632
28382
  }
27633
28383
  }
28384
+ var EVIDENCE_STATUSES = ["passed", "failed", "not-verified", "manual-review-required"];
28385
+ function printEvaluation(ev) {
28386
+ log.info(` Readiness: ${ev.readiness}`);
28387
+ const o = ev.outcome;
28388
+ log.info(` Outcome criteria: ${o.passed}/${o.total} passed${o.failed ? ` \xB7 ${o.failed} failed` : ""}${o.notVerified ? ` \xB7 ${o.notVerified} unverified` : ""}${o.ambiguous ? ` \xB7 ${o.ambiguous} ambiguous` : ""}`);
28389
+ for (const c of o.criteria) log.info(` [${c.status}${c.waived ? "/waived" : ""}${c.ambiguous ? "/ambiguous" : ""}] ${c.criterion}`);
28390
+ if (o.stale.length) log.warn(` Stale evidence (criterion changed): ${o.stale.map((s) => s.criterion).join("; ")}`);
28391
+ if (ev.milestones) for (const m of ev.milestones) log.info(` Milestone ${m.id}: ${m.outcome.passed}/${m.outcome.total} exit criteria verified`);
28392
+ if (ev.blockingDependencies.length) log.warn(` Blocking dependencies: ${ev.blockingDependencies.join(", ")}`);
28393
+ for (const b of ev.blockers) log.warn(` Blocker: ${b}`);
28394
+ for (const w of ev.warnings) log.warn(` Warning: ${w}`);
28395
+ for (const r of ev.reasons) log.info(` ${r}`);
28396
+ log.info(" Completion is never automatic \u2014 it always requires an explicit human decision.");
28397
+ }
28398
+ function evidenceInput(opts) {
28399
+ if (!opts.criterion?.trim()) {
28400
+ log.error("A --criterion is required.");
28401
+ process.exit(1);
28402
+ }
28403
+ const status = opts.status ?? "passed";
28404
+ if (!EVIDENCE_STATUSES.includes(status)) {
28405
+ log.error(`--status must be one of: ${EVIDENCE_STATUSES.join(", ")}.`);
28406
+ process.exit(1);
28407
+ }
28408
+ const method = opts.method === "automated" || opts.method === "manual" ? opts.method : void 0;
28409
+ return { criterion: opts.criterion.trim(), status, evidence: opts.evidence, reference: opts.reference, method, verifiedBy: opts.by };
28410
+ }
28411
+ function runPlanStart(id) {
28412
+ const dir = cwd();
28413
+ requireInit(dir);
28414
+ intro(`kaddo plan start ${id}`);
28415
+ try {
28416
+ const p = transitionDeliveryPlan(dir, id, "in-progress");
28417
+ log.success(`Plan ${p.id} is now ${p.status}.`);
28418
+ outro("Started.");
28419
+ } catch (err) {
28420
+ log.error(err instanceof DeliveryPlanningWriteError ? err.message : String(err));
28421
+ process.exit(1);
28422
+ }
28423
+ }
28424
+ function runPlanVerify(id, opts = {}) {
28425
+ const dir = cwd();
28426
+ requireInit(dir);
28427
+ const plan = getPlan(dir, id);
28428
+ if (!plan) {
28429
+ if (opts.json) console.log(JSON.stringify({ error: `Plan ${id} not found.` }));
28430
+ else log.error(`Plan ${id} not found.`);
28431
+ process.exit(1);
28432
+ }
28433
+ const ev = evaluatePlanCompletion(dir, plan);
28434
+ if (opts.json) {
28435
+ console.log(JSON.stringify(ev, null, 2));
28436
+ return;
28437
+ }
28438
+ intro(`kaddo plan verify ${id}`);
28439
+ printEvaluation(ev);
28440
+ outro(`Plan ${id} \u2014 ${ev.readiness}.`);
28441
+ }
28442
+ async function runPlanComplete(id, opts = {}) {
28443
+ const dir = cwd();
28444
+ requireInit(dir);
28445
+ intro(`kaddo plan complete ${id}`);
28446
+ const plan = getPlan(dir, id);
28447
+ if (!plan) {
28448
+ log.error(`Plan ${id} not found.`);
28449
+ process.exit(1);
28450
+ }
28451
+ const ev = evaluatePlanCompletion(dir, plan);
28452
+ printEvaluation(ev);
28453
+ if (ev.readiness !== "READY_TO_COMPLETE" && ev.readiness !== "READY_WITH_EXCEPTIONS") {
28454
+ log.error(`Plan ${id} is not ready to complete (${ev.readiness}).`);
28455
+ process.exit(1);
28456
+ }
28457
+ const ok = opts.yes === true || await confirm({ message: `Complete Plan ${id}? This records a human completion decision.` }) === true;
28458
+ if (!ok) {
28459
+ cancel("Cancelled.");
28460
+ return;
28461
+ }
28462
+ try {
28463
+ const done = completeDeliveryPlan(dir, id, { decidedBy: opts.by });
28464
+ log.success(`Plan ${done.id} completed (${ev.readiness}).`);
28465
+ outro("Completion decision recorded.");
28466
+ } catch (err) {
28467
+ log.error(err instanceof DeliveryPlanningWriteError ? err.message : String(err));
28468
+ process.exit(1);
28469
+ }
28470
+ }
28471
+ function runPlanEvidence(id, opts = {}) {
28472
+ const dir = cwd();
28473
+ requireInit(dir);
28474
+ intro(`kaddo plan evidence ${id}`);
28475
+ const input = evidenceInput(opts);
28476
+ try {
28477
+ if (opts.milestone) {
28478
+ recordMilestoneExitVerification(dir, id, opts.milestone, input);
28479
+ log.success(`Recorded evidence for milestone ${opts.milestone} criterion.`);
28480
+ } else {
28481
+ recordPlanOutcomeVerification(dir, id, input);
28482
+ log.success("Recorded Plan outcome evidence.");
28483
+ }
28484
+ outro(`[${input.status}] ${input.criterion}`);
28485
+ } catch (err) {
28486
+ log.error(err instanceof DeliveryPlanningWriteError ? err.message : String(err));
28487
+ process.exit(1);
28488
+ }
28489
+ }
28490
+ function runEpicStart(id) {
28491
+ const dir = cwd();
28492
+ requireInit(dir);
28493
+ intro(`kaddo epic start ${id}`);
28494
+ try {
28495
+ const e = transitionEpic(dir, id, "in-progress");
28496
+ log.success(`Epic ${e.id} is now ${e.status}.`);
28497
+ outro("Started.");
28498
+ } catch (err) {
28499
+ log.error(err instanceof DeliveryPlanningWriteError ? err.message : String(err));
28500
+ process.exit(1);
28501
+ }
28502
+ }
28503
+ function runEpicVerify(id, opts = {}) {
28504
+ const dir = cwd();
28505
+ requireInit(dir);
28506
+ const epic = getEpic(dir, id);
28507
+ if (!epic) {
28508
+ if (opts.json) console.log(JSON.stringify({ error: `Epic ${id} not found.` }));
28509
+ else log.error(`Epic ${id} not found.`);
28510
+ process.exit(1);
28511
+ }
28512
+ const ev = evaluateEpicCompletion(dir, epic);
28513
+ if (opts.json) {
28514
+ console.log(JSON.stringify(ev, null, 2));
28515
+ return;
28516
+ }
28517
+ intro(`kaddo epic verify ${id}`);
28518
+ printEvaluation(ev);
28519
+ outro(`Epic ${id} \u2014 ${ev.readiness}.`);
28520
+ }
28521
+ async function runEpicComplete(id, opts = {}) {
28522
+ const dir = cwd();
28523
+ requireInit(dir);
28524
+ intro(`kaddo epic complete ${id}`);
28525
+ const epic = getEpic(dir, id);
28526
+ if (!epic) {
28527
+ log.error(`Epic ${id} not found.`);
28528
+ process.exit(1);
28529
+ }
28530
+ const ev = evaluateEpicCompletion(dir, epic);
28531
+ printEvaluation(ev);
28532
+ if (ev.readiness !== "READY_TO_COMPLETE" && ev.readiness !== "READY_WITH_EXCEPTIONS") {
28533
+ log.error(`Epic ${id} is not ready to complete (${ev.readiness}).`);
28534
+ process.exit(1);
28535
+ }
28536
+ const ok = opts.yes === true || await confirm({ message: `Complete Epic ${id}? This records a human completion decision.` }) === true;
28537
+ if (!ok) {
28538
+ cancel("Cancelled.");
28539
+ return;
28540
+ }
28541
+ try {
28542
+ const done = completeEpic(dir, id, { decidedBy: opts.by });
28543
+ log.success(`Epic ${done.id} completed (${ev.readiness}).`);
28544
+ outro("Completion decision recorded.");
28545
+ } catch (err) {
28546
+ log.error(err instanceof PlanningNotReadyError || err instanceof DeliveryPlanningWriteError ? err.message : String(err));
28547
+ process.exit(1);
28548
+ }
28549
+ }
28550
+ function runEpicEvidence(id, opts = {}) {
28551
+ const dir = cwd();
28552
+ requireInit(dir);
28553
+ intro(`kaddo epic evidence ${id}`);
28554
+ const input = evidenceInput(opts);
28555
+ try {
28556
+ recordEpicOutcomeVerification(dir, id, input);
28557
+ log.success("Recorded Epic outcome evidence.");
28558
+ outro(`[${input.status}] ${input.criterion}`);
28559
+ } catch (err) {
28560
+ log.error(err instanceof DeliveryPlanningWriteError ? err.message : String(err));
28561
+ process.exit(1);
28562
+ }
28563
+ }
27634
28564
 
27635
28565
  // src/core/telemetry.ts
27636
28566
  import crypto6 from "crypto";
@@ -27971,112 +28901,6 @@ async function runCollaborationShow(dir, id) {
27971
28901
  }
27972
28902
  }
27973
28903
 
27974
- // src/core/initiative-analysis.ts
27975
- var SUCCESS_HEADING_RE = /^#{1,6}\s*(success criteria|criterios de[ét]xito|criterios de éxito)\s*$/i;
27976
- var HEADING_RE2 = /^#{1,6}\s+/;
27977
- var CHECK_ITEM_RE = /^\s*[-*]\s+\[([ xX])\]\s+(.*)$/;
27978
- var BULLET_RE2 = /^\s*[-*]\s+(.*)$/;
27979
- var PLACEHOLDER_RE = /^_.*_$/;
27980
- function parseSuccessCriteria(body) {
27981
- const lines = body.split(/\r?\n/);
27982
- const out = [];
27983
- let capture = false;
27984
- for (const line of lines) {
27985
- if (capture && HEADING_RE2.test(line)) break;
27986
- if (!capture) {
27987
- if (SUCCESS_HEADING_RE.test(line.trim())) capture = true;
27988
- continue;
27989
- }
27990
- const check = line.match(CHECK_ITEM_RE);
27991
- if (check) {
27992
- const text2 = check[2].trim();
27993
- if (text2 && !PLACEHOLDER_RE.test(text2)) {
27994
- out.push({ text: text2, checked: check[1].toLowerCase() === "x" });
27995
- }
27996
- continue;
27997
- }
27998
- const bullet = line.match(BULLET_RE2);
27999
- if (bullet) {
28000
- const text2 = bullet[1].trim();
28001
- if (text2 && !PLACEHOLDER_RE.test(text2)) out.push({ text: text2, checked: null });
28002
- }
28003
- }
28004
- return out;
28005
- }
28006
- function analyzeInitiative(dir, ini) {
28007
- const progress = computeInitiativeProgress(dir, ini);
28008
- const successCriteria = parseSuccessCriteria(ini.body);
28009
- const pendingCandidates = ini.candidates.filter((c) => !c.materializedAs);
28010
- const associated = associatedWorkItems(dir, ini.id);
28011
- const findings = [];
28012
- if (successCriteria.length === 0) {
28013
- findings.push({
28014
- code: "no-success-criteria",
28015
- severity: "warning",
28016
- message: "The Initiative has no explicit Success Criteria; completion cannot be judged by outcome, only by delivery."
28017
- });
28018
- } else {
28019
- const uncovered = successCriteria.filter((c) => c.checked === false);
28020
- if (uncovered.length > 0) {
28021
- findings.push({
28022
- code: "uncovered-success-criteria",
28023
- severity: "blocking",
28024
- message: `${uncovered.length} success criterion/criteria remain uncovered.`,
28025
- items: uncovered.map((c) => c.text)
28026
- });
28027
- }
28028
- }
28029
- if (pendingCandidates.length > 0) {
28030
- findings.push({
28031
- code: "pending-candidates",
28032
- severity: "blocking",
28033
- message: `${pendingCandidates.length} committed candidate(s) not yet materialized into Work Items.`,
28034
- items: pendingCandidates.map((c) => `${c.id}: ${c.title}`)
28035
- });
28036
- }
28037
- const notCompleted = associated.filter((w) => w.status !== "completed" && w.status !== "archived");
28038
- if (associated.length === 0) {
28039
- findings.push({
28040
- code: "no-delivery",
28041
- severity: "info",
28042
- message: "No Work Items are associated with this Initiative yet."
28043
- });
28044
- } else if (notCompleted.length > 0) {
28045
- findings.push({
28046
- code: "incomplete-delivery",
28047
- severity: "blocking",
28048
- message: `${notCompleted.length} associated Work Item(s) are not completed.`,
28049
- items: notCompleted.map((w) => `${w.id} (${w.status})`)
28050
- });
28051
- }
28052
- return {
28053
- initiative: ini.id,
28054
- status: ini.status,
28055
- progress,
28056
- successCriteria,
28057
- pendingCandidates,
28058
- findings,
28059
- suggestedCandidates: pendingCandidates
28060
- };
28061
- }
28062
- function evaluateInitiativeCompletion(dir, ini) {
28063
- const analysis = analyzeInitiative(dir, ini);
28064
- const reasons = [];
28065
- for (const f of analysis.findings) {
28066
- if (f.severity === "blocking") reasons.push(f.message);
28067
- }
28068
- if (analysis.progress.delivery.total === 0 && analysis.pendingCandidates.length === 0) {
28069
- reasons.push("Nothing has been delivered or committed under this Initiative.");
28070
- }
28071
- const ready = reasons.length === 0;
28072
- return {
28073
- initiative: ini.id,
28074
- ready,
28075
- readiness: ready ? "ready" : "not-ready",
28076
- reasons
28077
- };
28078
- }
28079
-
28080
28904
  // src/commands/initiative.ts
28081
28905
  function requireInit2(dir) {
28082
28906
  if (!loadConfig(dir)) {
@@ -28253,15 +29077,15 @@ async function runInitiativeComplete(id, opts = {}) {
28253
29077
  }
28254
29078
  const readiness = evaluateInitiativeCompletion(dir, ini);
28255
29079
  if (readiness.ready) {
28256
- log.success("Completion readiness: ready.");
29080
+ log.success(`Completion readiness: ${readiness.readiness}.`);
28257
29081
  } else {
28258
- log.warn("Completion readiness: NOT ready.");
29082
+ log.warn(`Completion readiness: ${readiness.readiness} \u2014 NOT ready.`);
28259
29083
  for (const r of readiness.reasons) log.warn(` - ${r}`);
28260
29084
  }
28261
29085
  if (!opts.yes) {
28262
29086
  log.info("");
28263
29087
  const proceed = await confirm({
28264
- message: readiness.ready ? "Mark this Initiative as completed?" : "This Initiative is not ready. Complete it anyway?",
29088
+ message: readiness.ready ? "Mark this Initiative as completed?" : "This Initiative is not ready. Try to complete it anyway?",
28265
29089
  initialValue: false
28266
29090
  });
28267
29091
  if (!proceed) {
@@ -28270,10 +29094,15 @@ async function runInitiativeComplete(id, opts = {}) {
28270
29094
  }
28271
29095
  }
28272
29096
  try {
28273
- const done = transitionInitiative(dir, id, "completed");
29097
+ const done = completeInitiative(dir, id);
28274
29098
  log.success(`Status: ${done.status}`);
28275
29099
  outro(`Initiative ${done.id} completed.`);
28276
29100
  } catch (err) {
29101
+ if (err instanceof InitiativeNotReadyError) {
29102
+ log.error(err.message);
29103
+ log.warn("Record outcome evidence and resolve blockers before completing this Initiative.");
29104
+ process.exit(1);
29105
+ }
28277
29106
  log.error(err instanceof InitiativeWriteError ? err.message : String(err));
28278
29107
  process.exit(1);
28279
29108
  }
@@ -28347,6 +29176,12 @@ planCmd.command("progress <id>").description("Planning coverage, delivery progre
28347
29176
  planCmd.command("create").description("Create a new delivery plan (interactive)").action(() => {
28348
29177
  void runPlanCreate();
28349
29178
  });
29179
+ planCmd.command("start <id>").description("Transition a Delivery Plan to in-progress (WI-078)").action((id) => runPlanStart(id));
29180
+ planCmd.command("verify <id>").description("Evidence-based completion readiness of a Plan (read-only)").option("--json", "Machine-readable output").action((id, o) => runPlanVerify(id, o));
29181
+ planCmd.command("evidence <id>").description("Record outcome (or milestone exit) verification evidence").requiredOption("--criterion <text>", "The declared success / exit criterion").option("--status <status>", "passed | failed | not-verified | manual-review-required", "passed").option("--evidence <text>", "What the evidence shows").option("--reference <ref>", "File, test, ADR or report").option("--method <method>", "automated | manual").option("--milestone <id>", "Verify a milestone exit criterion instead of a Plan success criterion").option("--by <who>", "Who verified it").action((id, o) => runPlanEvidence(id, o));
29182
+ planCmd.command("complete <id>").description("Complete a Plan after an evidence-based review (human-gated)").option("-y, --yes", "Skip the confirmation prompt").option("--by <who>", "Who approved the completion").action((id, o) => {
29183
+ void runPlanComplete(id, o);
29184
+ });
28350
29185
  var epicCmd = program.command("epic").description("Delivery Epics \u2014 significant outcomes spanning Initiatives and Work Items (WI-074)");
28351
29186
  epicCmd.command("list").description("List epics with progress").action(() => runEpicList());
28352
29187
  epicCmd.command("show <id>").description("Show an epic, its plan/milestone and initiatives").action((id) => runEpicShow(id));
@@ -28357,6 +29192,12 @@ epicCmd.command("create").description("Create a new epic (interactive)").action(
28357
29192
  epicCmd.command("associate <epicId> <initiativeId>").description("Associate an existing Initiative with an Epic").action((e, i) => {
28358
29193
  void runEpicAssociate(e, i);
28359
29194
  });
29195
+ epicCmd.command("start <id>").description("Transition an Epic to in-progress (WI-078)").action((id) => runEpicStart(id));
29196
+ epicCmd.command("verify <id>").description("Evidence-based completion readiness of an Epic (read-only)").option("--json", "Machine-readable output").action((id, o) => runEpicVerify(id, o));
29197
+ epicCmd.command("evidence <id>").description("Record outcome verification evidence for a success criterion").requiredOption("--criterion <text>", "The declared success criterion").option("--status <status>", "passed | failed | not-verified | manual-review-required", "passed").option("--evidence <text>", "What the evidence shows").option("--reference <ref>", "File, test, ADR or report").option("--method <method>", "automated | manual").option("--by <who>", "Who verified it").action((id, o) => runEpicEvidence(id, o));
29198
+ epicCmd.command("complete <id>").description("Complete an Epic after an evidence-based review (human-gated)").option("-y, --yes", "Skip the confirmation prompt").option("--by <who>", "Who approved the completion").action((id, o) => {
29199
+ void runEpicComplete(id, o);
29200
+ });
28360
29201
  var topologyCmd = program.command("topology").description("Validate and apply a semantic system topology proposal (agent proposes, human confirms, Core applies)");
28361
29202
  topologyCmd.command("validate <file>").description("Validate a topology proposal file deterministically (no write)").action((file) => {
28362
29203
  runTopologyValidate(file);