@kaddo/cli 3.135.0 → 3.137.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 (34) hide show
  1. package/dist/admin-dist/assets/{architectureDiagram-3BPJPVTR-DkdJ073y.js → architectureDiagram-3BPJPVTR-qOdtmvT5.js} +1 -1
  2. package/dist/admin-dist/assets/{chunk-727SXJPM-DRof4aGT.js → chunk-727SXJPM-MS0dJfvK.js} +1 -1
  3. package/dist/admin-dist/assets/{chunk-AQP2D5EJ-BOVZoYng.js → chunk-AQP2D5EJ-C8Ckq2rf.js} +1 -1
  4. package/dist/admin-dist/assets/{classDiagram-v2-Q7XG4LA2-cL_umCGu.js → classDiagram-4FO5ZUOK-DtyxSt6Z.js} +1 -1
  5. package/dist/admin-dist/assets/{classDiagram-4FO5ZUOK-cL_umCGu.js → classDiagram-v2-Q7XG4LA2-DtyxSt6Z.js} +1 -1
  6. package/dist/admin-dist/assets/{dagre-BM42HDAG-Cvga2Wk-.js → dagre-BM42HDAG-iQnGmcD6.js} +1 -1
  7. package/dist/admin-dist/assets/{diagram-2AECGRRQ-C4H51In7.js → diagram-2AECGRRQ-7M48Igpl.js} +1 -1
  8. package/dist/admin-dist/assets/{diagram-5GNKFQAL-BW2-XCqV.js → diagram-5GNKFQAL-CW5WzE_Q.js} +1 -1
  9. package/dist/admin-dist/assets/{diagram-LMA3HP47-CQnSrSZs.js → diagram-LMA3HP47-CZMFC4Uc.js} +1 -1
  10. package/dist/admin-dist/assets/{diagram-OG6HWLK6-BA6tBaOl.js → diagram-OG6HWLK6-BHkicWmb.js} +1 -1
  11. package/dist/admin-dist/assets/{erDiagram-TEJ5UH35-DQK3b1Yu.js → erDiagram-TEJ5UH35-B-BqPAdG.js} +1 -1
  12. package/dist/admin-dist/assets/{flowDiagram-I6XJVG4X-BvtbwW59.js → flowDiagram-I6XJVG4X-DuWPjEER.js} +1 -1
  13. package/dist/admin-dist/assets/{ganttDiagram-6RSMTGT7-Vb0T68-1.js → ganttDiagram-6RSMTGT7--XgeUMvh.js} +1 -1
  14. package/dist/admin-dist/assets/{index-F0fBD3Ys.js → index-BKSBm4WZ.js} +57 -56
  15. package/dist/admin-dist/assets/{infoDiagram-5YYISTIA-8oD9uPZj.js → infoDiagram-5YYISTIA-DuKlogCg.js} +1 -1
  16. package/dist/admin-dist/assets/{ishikawaDiagram-YF4QCWOH-C32f84vy.js → ishikawaDiagram-YF4QCWOH-CcxzKf38.js} +1 -1
  17. package/dist/admin-dist/assets/{kanban-definition-UN3LZRKU-cJc_snn8.js → kanban-definition-UN3LZRKU-C4VpQNpi.js} +1 -1
  18. package/dist/admin-dist/assets/{linear-XcP0Xi-K.js → linear-Dxc0ZqN6.js} +1 -1
  19. package/dist/admin-dist/assets/{mindmap-definition-RKZ34NQL-jhlLOmXd.js → mindmap-definition-RKZ34NQL-B2AitzPX.js} +1 -1
  20. package/dist/admin-dist/assets/{pieDiagram-4H26LBE5-cEiC5w8m.js → pieDiagram-4H26LBE5-6G4NtHFU.js} +1 -1
  21. package/dist/admin-dist/assets/{quadrantDiagram-W4KKPZXB-xjpfY5PD.js → quadrantDiagram-W4KKPZXB-wzC0LbYk.js} +1 -1
  22. package/dist/admin-dist/assets/{requirementDiagram-4Y6WPE33-C5KtzYhy.js → requirementDiagram-4Y6WPE33-_lleuZ0s.js} +1 -1
  23. package/dist/admin-dist/assets/{sequenceDiagram-3UESZ5HK-ByGOoS_6.js → sequenceDiagram-3UESZ5HK-DacKEVg5.js} +1 -1
  24. package/dist/admin-dist/assets/{stateDiagram-AJRCARHV-d9g3cuV4.js → stateDiagram-AJRCARHV-Zv0724sR.js} +1 -1
  25. package/dist/admin-dist/assets/{stateDiagram-v2-BHNVJYJU-DJ9FtIdZ.js → stateDiagram-v2-BHNVJYJU-CfuH3332.js} +1 -1
  26. package/dist/admin-dist/assets/{timeline-definition-PNZ67QCA-BB4Lz6CJ.js → timeline-definition-PNZ67QCA-DhVaiJlv.js} +1 -1
  27. package/dist/admin-dist/assets/{vennDiagram-CIIHVFJN-yj1GFfPu.js → vennDiagram-CIIHVFJN-B1vi_1GC.js} +1 -1
  28. package/dist/admin-dist/assets/{wardleyDiagram-YWT4CUSO-5nw4MWMx.js → wardleyDiagram-YWT4CUSO-DzXLLmHU.js} +1 -1
  29. package/dist/admin-dist/assets/{xychartDiagram-2RQKCTM6-C0iogx2l.js → xychartDiagram-2RQKCTM6-CciKukqO.js} +1 -1
  30. package/dist/admin-dist/index.html +1 -1
  31. package/dist/admin-server/index.js +163 -5
  32. package/dist/core.js +1087 -618
  33. package/dist/index.js +673 -460
  34. package/package.json +1 -1
package/dist/core.js CHANGED
@@ -2080,6 +2080,9 @@ function deliveryOf(wis, dir) {
2080
2080
  }
2081
2081
  return { total: wis.length, byState, blocked, completed: byState.completed };
2082
2082
  }
2083
+ function computeDeliveryProgress(wis, dir) {
2084
+ return deliveryOf(wis, dir);
2085
+ }
2083
2086
  function computeEpicProgress(dir, epic) {
2084
2087
  const inis = initiativesInEpic(dir, epic.id);
2085
2088
  const candidates = inis.reduce((n, i) => n + i.candidates.length, 0);
@@ -10789,593 +10792,1002 @@ import matter13 from "gray-matter";
10789
10792
 
10790
10793
  // src/core/initiative-write.ts
10791
10794
  import matter12 from "gray-matter";
10792
- var WORK_ITEMS_DIR = "knowledge/delivery/work-items";
10793
- var DRAFT_DIR = `${WORK_ITEMS_DIR}/draft`;
10794
- var ROADMAP_PATH2 = "knowledge/delivery/roadmap.md";
10795
- var InitiativeWriteError = class extends Error {
10796
- constructor(message) {
10797
- super(message);
10798
- this.name = "InitiativeWriteError";
10795
+
10796
+ // src/core/initiative-analysis.ts
10797
+ var SUCCESS_HEADING_RE = /^#{1,6}\s*(success criteria|criterios de[ét]xito|criterios de éxito)\s*$/i;
10798
+ var HEADING_RE2 = /^#{1,6}\s+/;
10799
+ var CHECK_ITEM_RE = /^\s*[-*]\s+\[([ xX])\]\s+(.*)$/;
10800
+ var BULLET_RE2 = /^\s*[-*]\s+(.*)$/;
10801
+ var PLACEHOLDER_RE = /^_.*_$/;
10802
+ function parseSuccessCriteria(body) {
10803
+ const lines = body.split(/\r?\n/);
10804
+ const out = [];
10805
+ let capture = false;
10806
+ for (const line of lines) {
10807
+ if (capture && HEADING_RE2.test(line)) break;
10808
+ if (!capture) {
10809
+ if (SUCCESS_HEADING_RE.test(line.trim())) capture = true;
10810
+ continue;
10811
+ }
10812
+ const check = line.match(CHECK_ITEM_RE);
10813
+ if (check) {
10814
+ const text2 = check[2].trim();
10815
+ if (text2 && !PLACEHOLDER_RE.test(text2)) {
10816
+ out.push({ text: text2, checked: check[1].toLowerCase() === "x" });
10817
+ }
10818
+ continue;
10819
+ }
10820
+ const bullet = line.match(BULLET_RE2);
10821
+ if (bullet) {
10822
+ const text2 = bullet[1].trim();
10823
+ if (text2 && !PLACEHOLDER_RE.test(text2)) out.push({ text: text2, checked: null });
10824
+ }
10799
10825
  }
10800
- };
10801
- function slugify2(s) {
10802
- return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 50);
10826
+ return out;
10803
10827
  }
10804
- function today() {
10805
- return (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
10828
+ function analyzeInitiative(dir, ini) {
10829
+ const progress = computeInitiativeProgress(dir, ini);
10830
+ const successCriteria = parseSuccessCriteria(ini.body);
10831
+ const pendingCandidates = ini.candidates.filter((c) => !c.materializedAs);
10832
+ const associated = associatedWorkItems(dir, ini.id);
10833
+ const findings = [];
10834
+ if (successCriteria.length === 0) {
10835
+ findings.push({
10836
+ code: "no-success-criteria",
10837
+ severity: "warning",
10838
+ message: "The Initiative has no explicit Success Criteria; completion cannot be judged by outcome, only by delivery."
10839
+ });
10840
+ } else {
10841
+ const uncovered = successCriteria.filter((c) => c.checked === false);
10842
+ if (uncovered.length > 0) {
10843
+ findings.push({
10844
+ code: "uncovered-success-criteria",
10845
+ severity: "blocking",
10846
+ message: `${uncovered.length} success criterion/criteria remain uncovered.`,
10847
+ items: uncovered.map((c) => c.text)
10848
+ });
10849
+ }
10850
+ }
10851
+ if (pendingCandidates.length > 0) {
10852
+ findings.push({
10853
+ code: "pending-candidates",
10854
+ severity: "blocking",
10855
+ message: `${pendingCandidates.length} committed candidate(s) not yet materialized into Work Items.`,
10856
+ items: pendingCandidates.map((c) => `${c.id}: ${c.title}`)
10857
+ });
10858
+ }
10859
+ const notCompleted = associated.filter((w) => w.status !== "completed" && w.status !== "archived");
10860
+ if (associated.length === 0) {
10861
+ findings.push({
10862
+ code: "no-delivery",
10863
+ severity: "info",
10864
+ message: "No Work Items are associated with this Initiative yet."
10865
+ });
10866
+ } else if (notCompleted.length > 0) {
10867
+ findings.push({
10868
+ code: "incomplete-delivery",
10869
+ severity: "blocking",
10870
+ message: `${notCompleted.length} associated Work Item(s) are not completed.`,
10871
+ items: notCompleted.map((w) => `${w.id} (${w.status})`)
10872
+ });
10873
+ }
10874
+ return {
10875
+ initiative: ini.id,
10876
+ status: ini.status,
10877
+ progress,
10878
+ successCriteria,
10879
+ pendingCandidates,
10880
+ findings,
10881
+ suggestedCandidates: pendingCandidates
10882
+ };
10806
10883
  }
10807
- function candidateToData(c) {
10808
- const out = { id: c.id, title: c.title };
10809
- if (c.type) out.type = c.type;
10810
- if (c.suggestedKnowledgeLevel) out.suggested_knowledge_level = c.suggestedKnowledgeLevel;
10811
- if (c.expectedValue) out.expected_value = c.expectedValue;
10812
- if (c.notes) out.notes = c.notes;
10813
- if (c.sourceSignals.length) out.source_signals = c.sourceSignals;
10814
- if (c.dependencies.length) out.dependencies = c.dependencies;
10815
- if (c.materializedAs) out.materialized_as = c.materializedAs;
10884
+
10885
+ // src/core/delivery-verification.ts
10886
+ function normalizeCriterion(text2) {
10887
+ return text2.trim().toLowerCase().replace(/\s+/g, " ");
10888
+ }
10889
+ var STATUSES = ["passed", "failed", "not-verified", "manual-review-required"];
10890
+ function optStr4(v) {
10891
+ if (typeof v === "string" && v.trim()) return v.trim();
10892
+ if (typeof v === "number") return String(v);
10893
+ return void 0;
10894
+ }
10895
+ function parseEvidenceList(raw) {
10896
+ if (!Array.isArray(raw)) return [];
10897
+ const out = [];
10898
+ for (const entry of raw) {
10899
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
10900
+ const o = entry;
10901
+ const criterion = optStr4(o.criterion);
10902
+ if (!criterion) continue;
10903
+ const statusRaw = optStr4(o.status);
10904
+ const status = STATUSES.includes(statusRaw ?? "") ? statusRaw : "not-verified";
10905
+ const method = optStr4(o.method);
10906
+ out.push({
10907
+ criterion,
10908
+ status,
10909
+ ...optStr4(o.evidence) ? { evidence: optStr4(o.evidence) } : {},
10910
+ ...optStr4(o.reference) ? { reference: optStr4(o.reference) } : {},
10911
+ ...method === "automated" || method === "manual" ? { method } : {},
10912
+ ...optStr4(o.verified_at) ? { verified_at: optStr4(o.verified_at) } : {},
10913
+ ...optStr4(o.verified_by) ? { verified_by: optStr4(o.verified_by) } : {}
10914
+ });
10915
+ }
10816
10916
  return out;
10817
10917
  }
10818
- function externalLinkToData(l) {
10819
- const out = { integration: l.integration, external_id: l.externalId };
10820
- if (l.externalType) out.external_type = l.externalType;
10821
- if (l.url) out.url = l.url;
10822
- if (l.externalStatus) out.external_status = l.externalStatus;
10918
+ function parseExceptions(raw) {
10919
+ if (!Array.isArray(raw)) return [];
10920
+ const out = [];
10921
+ for (const entry of raw) {
10922
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
10923
+ const o = entry;
10924
+ const id = optStr4(o.id);
10925
+ if (!id) continue;
10926
+ const st = optStr4(o.status);
10927
+ const status = st === "accepted" || st === "rejected" ? st : "proposed";
10928
+ out.push({
10929
+ id,
10930
+ status,
10931
+ ...optStr4(o.criterion) ? { criterion: optStr4(o.criterion) } : {},
10932
+ ...optStr4(o.reason) ? { reason: optStr4(o.reason) } : {}
10933
+ });
10934
+ }
10823
10935
  return out;
10824
10936
  }
10825
- function normalizeCandidate(input, fallbackId) {
10937
+ function buildOutcomeVerification(declared, evidence, exceptions = []) {
10938
+ const byCriterion = /* @__PURE__ */ new Map();
10939
+ for (const e of evidence) byCriterion.set(normalizeCriterion(e.criterion), e);
10940
+ const declaredKeys = new Set(declared.map(normalizeCriterion));
10941
+ const counts = /* @__PURE__ */ new Map();
10942
+ for (const c of declared) counts.set(normalizeCriterion(c), (counts.get(normalizeCriterion(c)) ?? 0) + 1);
10943
+ const ambiguousKeys = new Set([...counts.entries()].filter(([, n]) => n > 1).map(([k]) => k));
10944
+ const waived = new Set(
10945
+ 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))
10946
+ );
10947
+ const criteria = declared.map((criterion) => {
10948
+ const key = normalizeCriterion(criterion);
10949
+ const ambiguous = ambiguousKeys.has(key);
10950
+ const e = ambiguous ? void 0 : byCriterion.get(key);
10951
+ return {
10952
+ criterion,
10953
+ status: e?.status ?? "not-verified",
10954
+ ...e?.evidence ? { evidence: e.evidence } : {},
10955
+ ...e?.reference ? { reference: e.reference } : {},
10956
+ ...e?.method ? { method: e.method } : {},
10957
+ ...e?.verified_at ? { verifiedAt: e.verified_at } : {},
10958
+ ...e?.verified_by ? { verifiedBy: e.verified_by } : {},
10959
+ ...!ambiguous && waived.has(key) ? { waived: true } : {},
10960
+ ...ambiguous ? { ambiguous: true } : {}
10961
+ };
10962
+ });
10963
+ const stale = evidence.filter((e) => !declaredKeys.has(normalizeCriterion(e.criterion)));
10826
10964
  return {
10827
- id: input.id?.trim() || fallbackId,
10828
- title: input.title.trim(),
10829
- type: input.type?.trim() || void 0,
10830
- suggestedKnowledgeLevel: input.suggestedKnowledgeLevel?.trim() || void 0,
10831
- expectedValue: input.expectedValue?.trim() || void 0,
10832
- notes: input.notes?.trim() || void 0,
10833
- sourceSignals: input.sourceSignals ?? [],
10834
- dependencies: input.dependencies ?? [],
10835
- materializedAs: input.materializedAs ?? null
10965
+ total: criteria.length,
10966
+ // An ambiguous criterion is never counted as passed/waived; it counts as unverified until disambiguated.
10967
+ passed: criteria.filter((c) => !c.ambiguous && (c.status === "passed" || c.waived)).length,
10968
+ failed: criteria.filter((c) => !c.ambiguous && c.status === "failed" && !c.waived).length,
10969
+ notVerified: criteria.filter((c) => c.ambiguous || c.status === "not-verified" && !c.waived).length,
10970
+ manualReview: criteria.filter((c) => !c.ambiguous && c.status === "manual-review-required" && !c.waived).length,
10971
+ ambiguous: criteria.filter((c) => c.ambiguous).length,
10972
+ criteria,
10973
+ stale
10836
10974
  };
10837
10975
  }
10838
- function defaultBody(title) {
10839
- return [
10840
- `# ${title}`,
10841
- "",
10842
- "## Goal",
10843
- "",
10844
- "_What outcome does this Initiative pursue?_",
10845
- "",
10846
- "## Expected Value",
10847
- "",
10848
- "_Why it matters._",
10849
- "",
10850
- "## Scope",
10851
- "",
10852
- "_What this Initiative covers._",
10853
- "",
10854
- "## Out of Scope",
10855
- "",
10856
- "_What it explicitly does not cover._",
10857
- "",
10858
- "## Success Criteria",
10859
- "",
10860
- '_Observable outcomes that define completion (not just "all Work Items done")._',
10861
- "",
10862
- "## Dependencies",
10863
- "",
10864
- "_Other Initiatives, modules, or external work this depends on._",
10865
- "",
10866
- "## Work Item Candidates",
10867
- "",
10868
- "_Candidates live in frontmatter `candidates`; summarize them here as they evolve._",
10869
- "",
10870
- "## Open Questions",
10871
- "",
10872
- "_Unresolved questions for this Initiative._",
10873
- "",
10874
- "## Learning",
10875
- "",
10876
- "_Captured on completion: what was delivered, what stayed out of scope, outcome reached._",
10877
- ""
10878
- ].join("\n");
10976
+ function fm(entity, key) {
10977
+ return entity.rawFrontmatter?.[key];
10879
10978
  }
10880
- function buildInitiativeContent(id, input) {
10881
- const status = input.status ?? "planned";
10882
- if (!isValidInitiativeStatus(status)) {
10883
- throw new InitiativeWriteError(`Invalid initiative status: ${status}.`);
10884
- }
10885
- const candidates = (input.candidates ?? []).map(
10886
- (c, i) => normalizeCandidate(c, `WI-CANDIDATE-${String(i + 1).padStart(3, "0")}`)
10979
+ function epicOutcomeVerification(epic) {
10980
+ return buildOutcomeVerification(
10981
+ epic.successCriteria,
10982
+ parseEvidenceList(fm(epic, "outcome_verifications")),
10983
+ parseExceptions(fm(epic, "completion_exceptions"))
10887
10984
  );
10888
- const data = {
10889
- type: "initiative",
10890
- id,
10891
- title: input.title.trim(),
10892
- status,
10893
- knowledge_level: input.knowledgeLevel ?? "K2",
10894
- domains: input.domains ?? [],
10895
- related_capabilities: input.relatedCapabilities ?? [],
10896
- created_at: today(),
10897
- external_links: (input.externalLinks ?? []).map(externalLinkToData),
10898
- candidates: candidates.map(candidateToData)
10899
- };
10900
- if (input.horizon) data.horizon = input.horizon;
10901
- if (input.priority) data.priority = input.priority;
10902
- if (input.source) data.source = input.source;
10903
- if (input.sourceId) data.source_id = input.sourceId;
10904
- if (input.epic) data.epic = input.epic.trim();
10905
- if (input.owners?.length) data.owners = input.owners.map((o) => o.trim()).filter(Boolean);
10906
- if (input.contributors?.length) data.contributors = input.contributors.map((c) => c.trim()).filter(Boolean);
10907
- return matter12.stringify("\n" + (input.body ?? defaultBody(input.title.trim())), data);
10908
10985
  }
10909
- function createInitiative(dir, input) {
10910
- if (!input.title?.trim()) throw new InitiativeWriteError("Initiative title is required.");
10911
- const id = nextInitiativeId(dir);
10912
- const fileName = `${id}-${slugify2(input.title)}.md`;
10913
- const iniDir = join(dir, INITIATIVES_DIR);
10914
- ensureDir(iniDir);
10915
- const filePath = join(iniDir, fileName);
10916
- const content = buildInitiativeContent(id, input);
10917
- writeFile(filePath, content);
10918
- const ini = parseInitiative(dir, filePath, content);
10919
- if (!ini) throw new InitiativeWriteError("Failed to parse the Initiative just written.");
10920
- return ini;
10986
+ function planOutcomeVerification(plan) {
10987
+ return buildOutcomeVerification(
10988
+ plan.successCriteria,
10989
+ parseEvidenceList(fm(plan, "outcome_verifications")),
10990
+ parseExceptions(fm(plan, "completion_exceptions"))
10991
+ );
10921
10992
  }
10922
- function transitionInitiative(dir, id, to) {
10923
- const ini = getInitiative(dir, id);
10924
- if (!ini) throw new InitiativeWriteError(`Initiative ${id} not found.`);
10925
- if (!isValidInitiativeStatus(to)) throw new InitiativeWriteError(`Invalid status: ${to}.`);
10926
- if (ini.status === to) return ini;
10927
- if (!isValidInitiativeTransition(ini.status, to)) {
10928
- throw new InitiativeWriteError(`Invalid transition ${ini.status} \u2192 ${to}.`);
10929
- }
10930
- const raw = readFile(ini.filePath);
10931
- const { data, content } = matter12(raw, {});
10932
- data.status = to;
10933
- if (to === "completed") data.completed_at = today();
10934
- const newContent = matter12.stringify(content, data);
10935
- writeFile(ini.filePath, newContent);
10936
- const updated = parseInitiative(dir, ini.filePath, newContent);
10937
- if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after transition.");
10938
- return updated;
10993
+ function planMilestoneVerifications(plan) {
10994
+ const rawMs = Array.isArray(fm(plan, "milestones")) ? fm(plan, "milestones") : [];
10995
+ return plan.milestones.map((m) => {
10996
+ const rawEntry = rawMs.find((r) => r && typeof r === "object" && optStr4(r.id)?.toLowerCase() === m.id.toLowerCase());
10997
+ const evidence = parseEvidenceList(rawEntry?.exit_verifications);
10998
+ return { id: m.id, title: m.title, outcome: buildOutcomeVerification(m.exitCriteria, evidence) };
10999
+ });
10939
11000
  }
10940
- function addCandidate(dir, id, candidate) {
10941
- const ini = getInitiative(dir, id);
10942
- if (!ini) throw new InitiativeWriteError(`Initiative ${id} not found.`);
10943
- const raw = readFile(ini.filePath);
10944
- const { data, content } = matter12(raw, {});
10945
- const existing = Array.isArray(data.candidates) ? data.candidates : [];
10946
- const fallbackId = `WI-CANDIDATE-${String(existing.length + 1).padStart(3, "0")}`;
10947
- const normalized = normalizeCandidate(candidate, fallbackId);
10948
- if (ini.candidates.some((c) => c.id === normalized.id)) {
10949
- throw new InitiativeWriteError(`Candidate ${normalized.id} already exists in ${id}.`);
11001
+ function decide(blockers, softBlocks, hasAcceptedExceptions) {
11002
+ if (blockers.length > 0) return "BLOCKED";
11003
+ if (softBlocks.length > 0) return "NEEDS_WORK";
11004
+ return hasAcceptedExceptions ? "READY_WITH_EXCEPTIONS" : "READY_TO_COMPLETE";
11005
+ }
11006
+ function evaluateEpicCompletion(dir, epic) {
11007
+ const prog = computeEpicProgress(dir, epic);
11008
+ const exceptions = parseExceptions(fm(epic, "completion_exceptions"));
11009
+ const outcome = epicOutcomeVerification(epic);
11010
+ const blockers = [];
11011
+ const softBlocks = [];
11012
+ const reasons = [];
11013
+ const warnings = [];
11014
+ for (const d of prog.readiness.blockingDependencies) blockers.push(`Blocked by unfinished dependency ${d}.`);
11015
+ for (const f of integrityBlockers(dir, epic.id)) blockers.push(f);
11016
+ evaluateOutcomeInto(epic.outcome, true, outcome, blockers, softBlocks, reasons, warnings);
11017
+ if (prog.delivery.total > 0 && prog.delivery.completed < prog.delivery.total) {
11018
+ softBlocks.push("committed-work-incomplete");
11019
+ reasons.push(`Committed work is incomplete (${prog.delivery.completed}/${prog.delivery.total} Work Items completed).`);
10950
11020
  }
10951
- data.candidates = [...existing, candidateToData(normalized)];
10952
- const newContent = matter12.stringify(content, data);
10953
- writeFile(ini.filePath, newContent);
10954
- const updated = parseInitiative(dir, ini.filePath, newContent);
10955
- if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after adding a candidate.");
10956
- return updated;
11021
+ const readiness = decide(blockers, softBlocks, exceptions.some((x) => x.status === "accepted"));
11022
+ pushReadinessReason(readiness, reasons);
11023
+ return {
11024
+ id: epic.id,
11025
+ kind: "epic",
11026
+ status: epic.status,
11027
+ readiness,
11028
+ reasons,
11029
+ blockers,
11030
+ warnings,
11031
+ outcome,
11032
+ delivery: { total: prog.delivery.total, completed: prog.delivery.completed, blocked: prog.delivery.blocked },
11033
+ blockingDependencies: prog.readiness.blockingDependencies,
11034
+ exceptions
11035
+ };
10957
11036
  }
10958
- function updateInitiative(dir, id, patch) {
10959
- const ini = getInitiative(dir, id);
10960
- if (!ini) throw new InitiativeWriteError(`Initiative ${id} not found.`);
10961
- const raw = readFile(ini.filePath);
10962
- const { data, content } = matter12(raw, {});
10963
- if (patch.title !== void 0) {
10964
- if (!patch.title.trim()) throw new InitiativeWriteError("Initiative title cannot be empty.");
10965
- data.title = patch.title.trim();
11037
+ function evaluatePlanCompletion(dir, plan) {
11038
+ const prog = computePlanProgress(dir, plan);
11039
+ const exceptions = parseExceptions(fm(plan, "completion_exceptions"));
11040
+ const outcome = planOutcomeVerification(plan);
11041
+ const milestones = planMilestoneVerifications(plan);
11042
+ const epics = epicsInPlan(dir, plan.id).map((e) => ({ id: e.id, status: e.status }));
11043
+ const blockers = [];
11044
+ const softBlocks = [];
11045
+ const reasons = [];
11046
+ const warnings = [];
11047
+ for (const d of prog.readiness.blockingDependencies) blockers.push(`Blocked by unfinished dependency ${d}.`);
11048
+ for (const f of integrityBlockers(dir, plan.id)) blockers.push(f);
11049
+ evaluateOutcomeInto(plan.objective, false, outcome, blockers, softBlocks, reasons, warnings);
11050
+ if (!plan.objective) warnings.push("No objective is declared for this Plan (optional, but recommended for completion review).");
11051
+ if (prog.delivery.total > 0 && prog.delivery.completed < prog.delivery.total) {
11052
+ softBlocks.push("committed-work-incomplete");
11053
+ reasons.push(`Committed work is incomplete (${prog.delivery.completed}/${prog.delivery.total} Work Items completed).`);
10966
11054
  }
10967
- if (patch.horizon !== void 0) data.horizon = patch.horizon;
10968
- if (patch.priority !== void 0) data.priority = patch.priority;
10969
- if (patch.knowledgeLevel !== void 0) data.knowledge_level = patch.knowledgeLevel;
10970
- if (patch.domains !== void 0) data.domains = patch.domains;
10971
- if (patch.relatedCapabilities !== void 0) data.related_capabilities = patch.relatedCapabilities;
10972
- if (patch.epic !== void 0) {
10973
- if (patch.epic === null || patch.epic.trim() === "") delete data.epic;
10974
- else data.epic = patch.epic.trim();
11055
+ if (epics.length === 0 && prog.delivery.total === 0) {
11056
+ softBlocks.push("no-committed-work");
11057
+ reasons.push("No Epics and no committed Work Items \u2014 the Plan has no verifiable deliverables yet.");
10975
11058
  }
10976
- if (patch.owners !== void 0) data.owners = patch.owners.map((o) => o.trim()).filter(Boolean);
10977
- if (patch.contributors !== void 0) data.contributors = patch.contributors.map((c) => c.trim()).filter(Boolean);
10978
- const newContent = matter12.stringify(content, data);
10979
- writeFile(ini.filePath, newContent);
10980
- const updated = parseInitiative(dir, ini.filePath, newContent);
10981
- if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after update.");
10982
- return updated;
11059
+ const openEpics = epics.filter((e) => e.status !== "completed" && e.status !== "cancelled");
11060
+ if (openEpics.length > 0) {
11061
+ softBlocks.push("epics-open");
11062
+ reasons.push(`${openEpics.length} Epic(s) not yet completed: ${openEpics.map((e) => e.id).join(", ")}.`);
11063
+ }
11064
+ for (const m of milestones) {
11065
+ if (m.outcome.failed > 0) {
11066
+ blockers.push(`Milestone ${m.id} has a failed exit criterion.`);
11067
+ }
11068
+ const pending = m.outcome.notVerified + m.outcome.manualReview;
11069
+ if (pending > 0) {
11070
+ softBlocks.push(`milestone-${m.id}-pending`);
11071
+ reasons.push(`Milestone ${m.id}: ${pending} exit criterion(s) not verified.`);
11072
+ }
11073
+ if (m.outcome.stale.length > 0) warnings.push(`Milestone ${m.id} has stale exit-criteria evidence.`);
11074
+ }
11075
+ const readiness = decide(blockers, softBlocks, exceptions.some((x) => x.status === "accepted"));
11076
+ pushReadinessReason(readiness, reasons);
11077
+ return {
11078
+ id: plan.id,
11079
+ kind: "plan",
11080
+ status: plan.status,
11081
+ readiness,
11082
+ reasons,
11083
+ blockers,
11084
+ warnings,
11085
+ outcome,
11086
+ delivery: { total: prog.delivery.total, completed: prog.delivery.completed, blocked: prog.delivery.blocked },
11087
+ blockingDependencies: prog.readiness.blockingDependencies,
11088
+ milestones,
11089
+ epics,
11090
+ exceptions
11091
+ };
10983
11092
  }
10984
- function addExternalLink(dir, id, link) {
10985
- const ini = getInitiative(dir, id);
10986
- if (!ini) throw new InitiativeWriteError(`Initiative ${id} not found.`);
10987
- if (!link.integration?.trim() || !link.externalId?.trim()) {
10988
- throw new InitiativeWriteError("External link requires integration and externalId.");
11093
+ function integrityBlockers(dir, subjectId) {
11094
+ return validatePlanningGraph(dir).filter((f) => f.level === "error" && f.subject.toLowerCase() === subjectId.toLowerCase()).map((f) => f.message);
11095
+ }
11096
+ function evaluateOutcomeInto(declaredOutcome, requireDeclaredOutcome, outcome, blockers, softBlocks, reasons, warnings) {
11097
+ if (requireDeclaredOutcome && !declaredOutcome) {
11098
+ softBlocks.push("no-outcome");
11099
+ reasons.push("No expected outcome is declared.");
10989
11100
  }
10990
- if (ini.externalLinks.some(
10991
- (l) => l.integration.trim().toLowerCase() === link.integration.trim().toLowerCase() && l.externalId.trim().toLowerCase() === link.externalId.trim().toLowerCase()
10992
- )) {
10993
- throw new InitiativeWriteError(`External link ${link.integration}:${link.externalId} already exists on ${id}.`);
11101
+ if (outcome.total === 0) {
11102
+ softBlocks.push("no-success-criteria");
11103
+ reasons.push("No success criteria to verify \u2014 completion cannot be judged by outcome.");
10994
11104
  }
10995
- const raw = readFile(ini.filePath);
10996
- const { data, content } = matter12(raw, {});
10997
- const existing = Array.isArray(data.external_links) ? data.external_links : [];
10998
- data.external_links = [...existing, externalLinkToData(link)];
10999
- const newContent = matter12.stringify(content, data);
11000
- writeFile(ini.filePath, newContent);
11001
- const updated = parseInitiative(dir, ini.filePath, newContent);
11002
- if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after adding an external link.");
11003
- return updated;
11105
+ if (outcome.ambiguous > 0) {
11106
+ softBlocks.push("criteria-ambiguous");
11107
+ reasons.push(`${outcome.ambiguous} success criterion(s) collide in text \u2014 rename to disambiguate before verifying.`);
11108
+ }
11109
+ if (outcome.failed > 0) {
11110
+ softBlocks.push("criteria-failed");
11111
+ reasons.push(`${outcome.failed} success criterion(s) failed verification.`);
11112
+ }
11113
+ const pending = outcome.notVerified + outcome.manualReview - outcome.ambiguous;
11114
+ if (pending > 0) {
11115
+ softBlocks.push("criteria-unverified");
11116
+ reasons.push(`${pending} success criterion(s) not verified (no or insufficient evidence).`);
11117
+ }
11118
+ if (outcome.stale.length > 0) warnings.push(`${outcome.stale.length} evidence record(s) no longer match a declared criterion (stale).`);
11004
11119
  }
11005
- function nextWorkItemId(dir) {
11006
- const wiDir = join(dir, WORK_ITEMS_DIR);
11007
- let max = 0;
11008
- const walk2 = (d) => {
11009
- if (!exists(d)) return;
11010
- for (const entry of readDir(d)) {
11011
- const full = join(d, entry);
11012
- if (isFile(full)) {
11013
- const m = entry.match(/WI-(\d+)/);
11014
- if (m) max = Math.max(max, parseInt(m[1], 10));
11015
- } else if (!entry.startsWith(".")) {
11016
- walk2(full);
11017
- }
11018
- }
11019
- };
11020
- walk2(wiDir);
11021
- return `WI-${String(max + 1).padStart(3, "0")}`;
11120
+ function pushReadinessReason(readiness, reasons) {
11121
+ if (readiness === "READY_TO_COMPLETE") reasons.unshift("All success criteria are verified and committed work is complete. Human approval is still required to close.");
11122
+ else if (readiness === "READY_WITH_EXCEPTIONS") reasons.unshift("Remaining gaps are covered by accepted exceptions. Human approval is still required to close.");
11022
11123
  }
11023
- function buildWorkItemContent(wiId, iniId, candidate) {
11024
- const data = {
11025
- type: candidate.type ?? "feature",
11026
- id: wiId,
11027
- title: candidate.title,
11028
- knowledge_level: candidate.suggestedKnowledgeLevel ?? "K2",
11029
- status: "draft",
11030
- phase: "now",
11031
- initiative: iniId,
11032
- domains: [],
11033
- code: [],
11034
- created_at: today(),
11035
- source: "initiative",
11036
- source_id: candidate.id,
11037
- source_initiative: iniId,
11038
- affected_modules: []
11039
- };
11040
- if (candidate.sourceSignals.length) data.source_signals = candidate.sourceSignals;
11041
- if (candidate.dependencies.length) data.dependencies = candidate.dependencies;
11042
- const body = [
11043
- `# ${candidate.title}`,
11044
- "",
11045
- `> Materialized from Initiative ${iniId}, candidate ${candidate.id}.`,
11046
- "",
11047
- "## Problem",
11048
- "",
11049
- candidate.expectedValue ? `_Expected value:_ ${candidate.expectedValue}` : "_Describe the problem._",
11050
- "",
11051
- "## Acceptance Criteria",
11052
- "",
11053
- "- [ ] _Define at least one testable criterion._",
11054
- "",
11055
- "## Out of scope",
11056
- "",
11057
- "_Not included in this Work Item._",
11058
- "",
11059
- "## Validation",
11060
- "",
11061
- "_How will this be validated?_",
11062
- "",
11063
- "## Learning",
11064
- "",
11065
- "_What did we learn? Update after completion._",
11066
- ""
11067
- ].join("\n");
11068
- return matter12.stringify("\n" + body, data);
11069
- }
11070
- function materializeCandidate(dir, id, candidateId) {
11071
- const ini = getInitiative(dir, id);
11072
- if (!ini) throw new InitiativeWriteError(`Initiative ${id} not found.`);
11073
- const candidate = ini.candidates.find((c) => c.id === candidateId);
11074
- if (!candidate) throw new InitiativeWriteError(`Candidate ${candidateId} not found in ${id}.`);
11075
- if (candidate.materializedAs) {
11076
- throw new InitiativeWriteError(
11077
- `Candidate ${candidateId} is already materialized as ${candidate.materializedAs}.`
11078
- );
11079
- }
11080
- const wiId = nextWorkItemId(dir);
11081
- const fileName = `${wiId}-${slugify2(candidate.title)}.md`;
11082
- ensureDir(join(dir, DRAFT_DIR));
11083
- writeFile(join(dir, DRAFT_DIR, fileName), buildWorkItemContent(wiId, ini.id, candidate));
11084
- const raw = readFile(ini.filePath);
11085
- const { data, content } = matter12(raw, {});
11086
- const cands = Array.isArray(data.candidates) ? data.candidates : [];
11087
- for (const c of cands) {
11088
- if (c && typeof c === "object" && String(c.id) === candidateId) c.materialized_as = wiId;
11089
- }
11090
- data.candidates = cands;
11091
- const newContent = matter12.stringify(content, data);
11092
- writeFile(ini.filePath, newContent);
11093
- const updated = parseInitiative(dir, ini.filePath, newContent);
11094
- if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after materialization.");
11095
- return { workItemId: wiId, fileName, initiative: updated };
11124
+ function evaluateEpicById(dir, id) {
11125
+ const e = getEpic(dir, id);
11126
+ return e ? evaluateEpicCompletion(dir, e) : null;
11096
11127
  }
11097
- function materializeRoadmapInitiative(dir, rmId) {
11098
- const roadmapFull = join(dir, ROADMAP_PATH2);
11099
- if (!exists(roadmapFull)) throw new InitiativeWriteError(`No roadmap found at ${ROADMAP_PATH2}.`);
11100
- const all = parseRoadmapCandidates(readFile(roadmapFull));
11101
- const want = rmId.trim().toLowerCase();
11102
- const belonging = all.filter((c) => (c.initiative?.id ?? "").toLowerCase() === want);
11103
- if (belonging.length === 0) {
11104
- throw new InitiativeWriteError(`No roadmap initiative "${rmId}" with candidates found.`);
11105
- }
11106
- const title = belonging[0].initiative?.title?.trim() || rmId;
11107
- const candidates = belonging.map((c) => ({
11108
- id: c.id,
11109
- title: c.title,
11110
- type: c.type,
11111
- suggestedKnowledgeLevel: c.suggestedKnowledgeLevel,
11112
- expectedValue: c.expectedValue,
11113
- notes: c.notes,
11114
- sourceSignals: c.sourceSignals ?? [],
11115
- dependencies: c.dependencies ?? [],
11116
- materializedAs: null
11117
- }));
11118
- const domains = belonging[0].domain ? [belonging[0].domain] : [];
11119
- const relatedCapabilities = Array.from(
11120
- new Set(belonging.flatMap((c) => c.relatedCapabilities ?? []))
11121
- );
11122
- return createInitiative(dir, {
11123
- title,
11124
- status: "planned",
11125
- domains,
11126
- relatedCapabilities,
11127
- source: "roadmap",
11128
- sourceId: rmId,
11129
- candidates
11130
- });
11128
+ function evaluatePlanById(dir, id) {
11129
+ const p = getPlan(dir, id);
11130
+ return p ? evaluatePlanCompletion(dir, p) : null;
11131
11131
  }
11132
11132
 
11133
- // src/core/delivery-verification.ts
11134
- function normalizeCriterion(text2) {
11135
- return text2.trim().toLowerCase().replace(/\s+/g, " ");
11136
- }
11137
- var STATUSES = ["passed", "failed", "not-verified", "manual-review-required"];
11138
- function optStr4(v) {
11139
- if (typeof v === "string" && v.trim()) return v.trim();
11140
- if (typeof v === "number") return String(v);
11141
- return void 0;
11142
- }
11143
- function parseEvidenceList(raw) {
11144
- if (!Array.isArray(raw)) return [];
11145
- const out = [];
11146
- for (const entry of raw) {
11147
- if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
11148
- const o = entry;
11149
- const criterion = optStr4(o.criterion);
11150
- if (!criterion) continue;
11151
- const statusRaw = optStr4(o.status);
11152
- const status = STATUSES.includes(statusRaw ?? "") ? statusRaw : "not-verified";
11153
- const method = optStr4(o.method);
11154
- out.push({
11155
- criterion,
11156
- status,
11157
- ...optStr4(o.evidence) ? { evidence: optStr4(o.evidence) } : {},
11158
- ...optStr4(o.reference) ? { reference: optStr4(o.reference) } : {},
11159
- ...method === "automated" || method === "manual" ? { method } : {},
11160
- ...optStr4(o.verified_at) ? { verified_at: optStr4(o.verified_at) } : {},
11161
- ...optStr4(o.verified_by) ? { verified_by: optStr4(o.verified_by) } : {}
11162
- });
11163
- }
11164
- return out;
11133
+ // src/core/initiative-verification.ts
11134
+ function optStr5(v) {
11135
+ return typeof v === "string" && v.trim() ? v.trim() : void 0;
11165
11136
  }
11166
- function parseExceptions(raw) {
11137
+ function parseCompletionExceptions(raw) {
11167
11138
  if (!Array.isArray(raw)) return [];
11168
11139
  const out = [];
11169
11140
  for (const entry of raw) {
11170
11141
  if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
11171
11142
  const o = entry;
11172
- const id = optStr4(o.id);
11143
+ const id = optStr5(o.id);
11173
11144
  if (!id) continue;
11174
- const st = optStr4(o.status);
11175
- const status = st === "accepted" || st === "rejected" ? st : "proposed";
11145
+ const st = optStr5(o.status);
11176
11146
  out.push({
11177
11147
  id,
11178
- status,
11179
- ...optStr4(o.criterion) ? { criterion: optStr4(o.criterion) } : {},
11180
- ...optStr4(o.reason) ? { reason: optStr4(o.reason) } : {}
11148
+ status: st === "accepted" || st === "rejected" ? st : "proposed",
11149
+ ...optStr5(o.criterion) ? { criterion: optStr5(o.criterion) } : {},
11150
+ ...optStr5(o.reason) ? { reason: optStr5(o.reason) } : {}
11181
11151
  });
11182
11152
  }
11183
11153
  return out;
11184
11154
  }
11185
- function buildOutcomeVerification(declared, evidence, exceptions = []) {
11186
- const byCriterion = /* @__PURE__ */ new Map();
11187
- for (const e of evidence) byCriterion.set(normalizeCriterion(e.criterion), e);
11188
- const declaredKeys = new Set(declared.map(normalizeCriterion));
11189
- const counts = /* @__PURE__ */ new Map();
11190
- for (const c of declared) counts.set(normalizeCriterion(c), (counts.get(normalizeCriterion(c)) ?? 0) + 1);
11191
- const ambiguousKeys = new Set([...counts.entries()].filter(([, n]) => n > 1).map(([k]) => k));
11192
- const waived = new Set(
11193
- exceptions.filter((x) => x.status === "accepted" && x.reason?.trim() && x.criterion && declaredKeys.has(normalizeCriterion(x.criterion)) && !ambiguousKeys.has(normalizeCriterion(x.criterion))).map((x) => normalizeCriterion(x.criterion))
11194
- );
11195
- const criteria = declared.map((criterion) => {
11196
- const key = normalizeCriterion(criterion);
11197
- const ambiguous = ambiguousKeys.has(key);
11198
- const e = ambiguous ? void 0 : byCriterion.get(key);
11199
- return {
11200
- criterion,
11201
- status: e?.status ?? "not-verified",
11202
- ...e?.evidence ? { evidence: e.evidence } : {},
11203
- ...e?.reference ? { reference: e.reference } : {},
11204
- ...e?.method ? { method: e.method } : {},
11205
- ...e?.verified_at ? { verifiedAt: e.verified_at } : {},
11206
- ...e?.verified_by ? { verifiedBy: e.verified_by } : {},
11207
- ...!ambiguous && waived.has(key) ? { waived: true } : {},
11208
- ...ambiguous ? { ambiguous: true } : {}
11209
- };
11210
- });
11211
- const stale = evidence.filter((e) => !declaredKeys.has(normalizeCriterion(e.criterion)));
11212
- return {
11213
- total: criteria.length,
11214
- // An ambiguous criterion is never counted as passed/waived; it counts as unverified until disambiguated.
11215
- passed: criteria.filter((c) => !c.ambiguous && (c.status === "passed" || c.waived)).length,
11216
- failed: criteria.filter((c) => !c.ambiguous && c.status === "failed" && !c.waived).length,
11217
- notVerified: criteria.filter((c) => c.ambiguous || c.status === "not-verified" && !c.waived).length,
11218
- manualReview: criteria.filter((c) => !c.ambiguous && c.status === "manual-review-required" && !c.waived).length,
11219
- ambiguous: criteria.filter((c) => c.ambiguous).length,
11220
- criteria,
11221
- stale
11222
- };
11223
- }
11224
- function fm(entity, key) {
11225
- return entity.rawFrontmatter?.[key];
11226
- }
11227
- function epicOutcomeVerification(epic) {
11228
- return buildOutcomeVerification(
11229
- epic.successCriteria,
11230
- parseEvidenceList(fm(epic, "outcome_verifications")),
11231
- parseExceptions(fm(epic, "completion_exceptions"))
11232
- );
11233
- }
11234
- function planOutcomeVerification(plan) {
11235
- return buildOutcomeVerification(
11236
- plan.successCriteria,
11237
- parseEvidenceList(fm(plan, "outcome_verifications")),
11238
- parseExceptions(fm(plan, "completion_exceptions"))
11239
- );
11155
+ function initiativeOutcomeVerification(ini) {
11156
+ const declared = parseSuccessCriteria(ini.body).map((c) => c.text);
11157
+ const evidence = parseEvidenceList(ini.rawFrontmatter?.outcome_verifications);
11158
+ const exceptions = parseCompletionExceptions(ini.rawFrontmatter?.completion_exceptions);
11159
+ return buildOutcomeVerification(declared, evidence, exceptions);
11240
11160
  }
11241
- function planMilestoneVerifications(plan) {
11242
- const rawMs = Array.isArray(fm(plan, "milestones")) ? fm(plan, "milestones") : [];
11243
- return plan.milestones.map((m) => {
11244
- const rawEntry = rawMs.find((r) => r && typeof r === "object" && optStr4(r.id)?.toLowerCase() === m.id.toLowerCase());
11245
- const evidence = parseEvidenceList(rawEntry?.exit_verifications);
11246
- return { id: m.id, title: m.title, outcome: buildOutcomeVerification(m.exitCriteria, evidence) };
11247
- });
11161
+ function initiativeProvenanceIssues(dir, ini) {
11162
+ const issues = [];
11163
+ const wis = discoverWorkItems(dir);
11164
+ for (const c of ini.candidates) {
11165
+ if (!c.materializedAs) continue;
11166
+ const wi = wis.find((w) => w.id.toLowerCase() === c.materializedAs.toLowerCase());
11167
+ if (!wi) {
11168
+ issues.push(`Candidate ${c.id} points at missing Work Item ${c.materializedAs}.`);
11169
+ continue;
11170
+ }
11171
+ const owner = typeof wi.rawFrontmatter?.initiative === "string" ? wi.rawFrontmatter.initiative : void 0;
11172
+ if (owner && owner.toLowerCase() !== ini.id.toLowerCase()) {
11173
+ issues.push(`Work Item ${wi.id} (materialized from ${c.id}) is associated with ${owner}, not ${ini.id}.`);
11174
+ }
11175
+ }
11176
+ return issues;
11248
11177
  }
11249
- function decide(blockers, softBlocks, hasAcceptedExceptions) {
11178
+ function decide2(blockers, softBlocks, hasAcceptedExceptions) {
11250
11179
  if (blockers.length > 0) return "BLOCKED";
11251
11180
  if (softBlocks.length > 0) return "NEEDS_WORK";
11252
11181
  return hasAcceptedExceptions ? "READY_WITH_EXCEPTIONS" : "READY_TO_COMPLETE";
11253
11182
  }
11254
- function evaluateEpicCompletion(dir, epic) {
11255
- const prog = computeEpicProgress(dir, epic);
11256
- const exceptions = parseExceptions(fm(epic, "completion_exceptions"));
11257
- const outcome = epicOutcomeVerification(epic);
11183
+ function evaluateInitiativeCompletion(dir, ini) {
11184
+ const progress = computeInitiativeProgress(dir, ini);
11185
+ const outcome = initiativeOutcomeVerification(ini);
11186
+ const exceptions = parseCompletionExceptions(ini.rawFrontmatter?.completion_exceptions);
11187
+ const pending = ini.candidates.filter((c) => !c.materializedAs);
11188
+ const associated = associatedWorkItems(dir, ini.id);
11189
+ const incomplete = associated.filter((w) => w.status !== "completed" && w.status !== "archived");
11190
+ const provenanceIssues = initiativeProvenanceIssues(dir, ini);
11258
11191
  const blockers = [];
11259
11192
  const softBlocks = [];
11260
11193
  const reasons = [];
11261
11194
  const warnings = [];
11262
- for (const d of prog.readiness.blockingDependencies) blockers.push(`Blocked by unfinished dependency ${d}.`);
11263
- for (const f of integrityBlockers(dir, epic.id)) blockers.push(f);
11264
- evaluateOutcomeInto(epic.outcome, true, outcome, blockers, softBlocks, reasons, warnings);
11265
- if (prog.delivery.total > 0 && prog.delivery.completed < prog.delivery.total) {
11266
- softBlocks.push("committed-work-incomplete");
11267
- reasons.push(`Committed work is incomplete (${prog.delivery.completed}/${prog.delivery.total} Work Items completed).`);
11195
+ for (const p of provenanceIssues) blockers.push(p);
11196
+ if (outcome.total === 0) {
11197
+ softBlocks.push("no-success-criteria");
11198
+ reasons.push("No success criteria to verify \u2014 completion cannot be judged by outcome.");
11268
11199
  }
11269
- const readiness = decide(blockers, softBlocks, exceptions.some((x) => x.status === "accepted"));
11270
- pushReadinessReason(readiness, reasons);
11200
+ if (outcome.ambiguous > 0) {
11201
+ softBlocks.push("criteria-ambiguous");
11202
+ reasons.push(`${outcome.ambiguous} success criterion(s) collide in text \u2014 disambiguate before verifying.`);
11203
+ }
11204
+ if (outcome.failed > 0) {
11205
+ softBlocks.push("criteria-failed");
11206
+ reasons.push(`${outcome.failed} success criterion(s) failed verification.`);
11207
+ }
11208
+ const unverified2 = outcome.notVerified + outcome.manualReview - outcome.ambiguous;
11209
+ if (unverified2 > 0) {
11210
+ softBlocks.push("criteria-unverified");
11211
+ reasons.push(`${unverified2} success criterion(s) not verified (no or insufficient evidence).`);
11212
+ }
11213
+ if (outcome.stale.length > 0) warnings.push(`${outcome.stale.length} evidence record(s) no longer match a declared criterion (stale).`);
11214
+ if (pending.length > 0) {
11215
+ softBlocks.push("pending-candidates");
11216
+ reasons.push(`${pending.length} committed candidate(s) not yet materialized.`);
11217
+ }
11218
+ if (incomplete.length > 0) {
11219
+ softBlocks.push("incomplete-delivery");
11220
+ reasons.push(`${incomplete.length} associated Work Item(s) are not completed.`);
11221
+ }
11222
+ if (associated.length === 0 && pending.length === 0) {
11223
+ softBlocks.push("no-deliverables");
11224
+ reasons.push("Nothing has been delivered or committed under this Initiative.");
11225
+ }
11226
+ const readiness = decide2(blockers, softBlocks, exceptions.some((x) => x.status === "accepted"));
11227
+ if (readiness === "READY_TO_COMPLETE") reasons.unshift("All success criteria are verified and committed scope is delivered. Human approval is still required to close.");
11228
+ else if (readiness === "READY_WITH_EXCEPTIONS") reasons.unshift("Remaining gaps are covered by accepted exceptions. Human approval is still required to close.");
11229
+ const completed = progress.delivery.byState?.completed ?? 0;
11271
11230
  return {
11272
- id: epic.id,
11273
- kind: "epic",
11274
- status: epic.status,
11231
+ id: ini.id,
11232
+ kind: "initiative",
11233
+ status: ini.status,
11275
11234
  readiness,
11235
+ ready: readiness === "READY_TO_COMPLETE" || readiness === "READY_WITH_EXCEPTIONS",
11276
11236
  reasons,
11277
11237
  blockers,
11278
11238
  warnings,
11279
11239
  outcome,
11280
- delivery: { total: prog.delivery.total, completed: prog.delivery.completed, blocked: prog.delivery.blocked },
11281
- blockingDependencies: prog.readiness.blockingDependencies,
11240
+ delivery: { total: progress.delivery.total, completed, incomplete: incomplete.length },
11241
+ pendingCandidates: pending.map((c) => c.id),
11242
+ provenanceIssues,
11282
11243
  exceptions
11283
11244
  };
11284
11245
  }
11285
- function evaluatePlanCompletion(dir, plan) {
11286
- const prog = computePlanProgress(dir, plan);
11287
- const exceptions = parseExceptions(fm(plan, "completion_exceptions"));
11288
- const outcome = planOutcomeVerification(plan);
11289
- const milestones = planMilestoneVerifications(plan);
11290
- const epics = epicsInPlan(dir, plan.id).map((e) => ({ id: e.id, status: e.status }));
11291
- const blockers = [];
11292
- const softBlocks = [];
11293
- const reasons = [];
11294
- const warnings = [];
11295
- for (const d of prog.readiness.blockingDependencies) blockers.push(`Blocked by unfinished dependency ${d}.`);
11296
- for (const f of integrityBlockers(dir, plan.id)) blockers.push(f);
11297
- evaluateOutcomeInto(plan.objective, false, outcome, blockers, softBlocks, reasons, warnings);
11298
- if (!plan.objective) warnings.push("No objective is declared for this Plan (optional, but recommended for completion review).");
11299
- if (prog.delivery.total > 0 && prog.delivery.completed < prog.delivery.total) {
11300
- softBlocks.push("committed-work-incomplete");
11301
- reasons.push(`Committed work is incomplete (${prog.delivery.completed}/${prog.delivery.total} Work Items completed).`);
11246
+ function evaluateInitiativeById(dir, id) {
11247
+ const ini = getInitiative(dir, id);
11248
+ return ini ? evaluateInitiativeCompletion(dir, ini) : null;
11249
+ }
11250
+
11251
+ // src/core/initiative-write.ts
11252
+ var WORK_ITEMS_DIR = "knowledge/delivery/work-items";
11253
+ var DRAFT_DIR = `${WORK_ITEMS_DIR}/draft`;
11254
+ var ROADMAP_PATH2 = "knowledge/delivery/roadmap.md";
11255
+ function assertFreshInitiative(id, currentContent, opts) {
11256
+ if (!opts?.expectedRevision) return;
11257
+ const actual = revisionOf(currentContent);
11258
+ if (actual !== opts.expectedRevision) throw new InitiativeConflictError(id, opts.expectedRevision, actual);
11259
+ }
11260
+ function nextCandidateId(existing) {
11261
+ let max = 0;
11262
+ for (const c of existing) {
11263
+ const m = typeof c?.id === "string" ? c.id.match(/^WI-CANDIDATE-(\d+)$/i) : null;
11264
+ if (m) max = Math.max(max, Number.parseInt(m[1], 10));
11302
11265
  }
11303
- if (epics.length === 0 && prog.delivery.total === 0) {
11304
- softBlocks.push("no-committed-work");
11305
- reasons.push("No Epics and no committed Work Items \u2014 the Plan has no verifiable deliverables yet.");
11266
+ return `WI-CANDIDATE-${String(max + 1).padStart(3, "0")}`;
11267
+ }
11268
+ var InitiativeWriteError = class extends Error {
11269
+ constructor(message) {
11270
+ super(message);
11271
+ this.name = "InitiativeWriteError";
11306
11272
  }
11307
- const openEpics = epics.filter((e) => e.status !== "completed" && e.status !== "cancelled");
11308
- if (openEpics.length > 0) {
11309
- softBlocks.push("epics-open");
11310
- reasons.push(`${openEpics.length} Epic(s) not yet completed: ${openEpics.map((e) => e.id).join(", ")}.`);
11273
+ };
11274
+ var InitiativeConflictError = class extends InitiativeWriteError {
11275
+ constructor(id, expectedRevision, actualRevision) {
11276
+ super(`Initiative "${id}" was modified since it was loaded (expected revision ${expectedRevision}, found ${actualRevision}). Reload and try again.`);
11277
+ this.id = id;
11278
+ this.expectedRevision = expectedRevision;
11279
+ this.actualRevision = actualRevision;
11280
+ this.name = "InitiativeConflictError";
11311
11281
  }
11312
- for (const m of milestones) {
11313
- if (m.outcome.failed > 0) {
11314
- blockers.push(`Milestone ${m.id} has a failed exit criterion.`);
11282
+ id;
11283
+ expectedRevision;
11284
+ actualRevision;
11285
+ };
11286
+ function slugify2(s) {
11287
+ return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 50);
11288
+ }
11289
+ function today() {
11290
+ return (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
11291
+ }
11292
+ function candidateToData(c) {
11293
+ const out = { id: c.id, title: c.title };
11294
+ if (c.type) out.type = c.type;
11295
+ if (c.suggestedKnowledgeLevel) out.suggested_knowledge_level = c.suggestedKnowledgeLevel;
11296
+ if (c.expectedValue) out.expected_value = c.expectedValue;
11297
+ if (c.notes) out.notes = c.notes;
11298
+ if (c.sourceSignals.length) out.source_signals = c.sourceSignals;
11299
+ if (c.dependencies.length) out.dependencies = c.dependencies;
11300
+ if (c.materializedAs) out.materialized_as = c.materializedAs;
11301
+ return out;
11302
+ }
11303
+ function externalLinkToData(l) {
11304
+ const out = { integration: l.integration, external_id: l.externalId };
11305
+ if (l.externalType) out.external_type = l.externalType;
11306
+ if (l.url) out.url = l.url;
11307
+ if (l.externalStatus) out.external_status = l.externalStatus;
11308
+ return out;
11309
+ }
11310
+ function normalizeCandidate(input, fallbackId) {
11311
+ return {
11312
+ id: input.id?.trim() || fallbackId,
11313
+ title: input.title.trim(),
11314
+ type: input.type?.trim() || void 0,
11315
+ suggestedKnowledgeLevel: input.suggestedKnowledgeLevel?.trim() || void 0,
11316
+ expectedValue: input.expectedValue?.trim() || void 0,
11317
+ notes: input.notes?.trim() || void 0,
11318
+ sourceSignals: input.sourceSignals ?? [],
11319
+ dependencies: input.dependencies ?? [],
11320
+ materializedAs: input.materializedAs ?? null
11321
+ };
11322
+ }
11323
+ function defaultBody(title) {
11324
+ return [
11325
+ `# ${title}`,
11326
+ "",
11327
+ "## Goal",
11328
+ "",
11329
+ "_What outcome does this Initiative pursue?_",
11330
+ "",
11331
+ "## Expected Value",
11332
+ "",
11333
+ "_Why it matters._",
11334
+ "",
11335
+ "## Scope",
11336
+ "",
11337
+ "_What this Initiative covers._",
11338
+ "",
11339
+ "## Out of Scope",
11340
+ "",
11341
+ "_What it explicitly does not cover._",
11342
+ "",
11343
+ "## Success Criteria",
11344
+ "",
11345
+ '_Observable outcomes that define completion (not just "all Work Items done")._',
11346
+ "",
11347
+ "## Dependencies",
11348
+ "",
11349
+ "_Other Initiatives, modules, or external work this depends on._",
11350
+ "",
11351
+ "## Work Item Candidates",
11352
+ "",
11353
+ "_Candidates live in frontmatter `candidates`; summarize them here as they evolve._",
11354
+ "",
11355
+ "## Open Questions",
11356
+ "",
11357
+ "_Unresolved questions for this Initiative._",
11358
+ "",
11359
+ "## Learning",
11360
+ "",
11361
+ "_Captured on completion: what was delivered, what stayed out of scope, outcome reached._",
11362
+ ""
11363
+ ].join("\n");
11364
+ }
11365
+ function buildInitiativeContent(id, input) {
11366
+ const status = input.status ?? "planned";
11367
+ if (!isValidInitiativeStatus(status)) {
11368
+ throw new InitiativeWriteError(`Invalid initiative status: ${status}.`);
11369
+ }
11370
+ const candidates = (input.candidates ?? []).map(
11371
+ (c, i) => normalizeCandidate(c, `WI-CANDIDATE-${String(i + 1).padStart(3, "0")}`)
11372
+ );
11373
+ const data = {
11374
+ type: "initiative",
11375
+ id,
11376
+ title: input.title.trim(),
11377
+ status,
11378
+ knowledge_level: input.knowledgeLevel ?? "K2",
11379
+ domains: input.domains ?? [],
11380
+ related_capabilities: input.relatedCapabilities ?? [],
11381
+ created_at: today(),
11382
+ external_links: (input.externalLinks ?? []).map(externalLinkToData),
11383
+ candidates: candidates.map(candidateToData)
11384
+ };
11385
+ if (input.horizon) data.horizon = input.horizon;
11386
+ if (input.priority) data.priority = input.priority;
11387
+ if (input.source) data.source = input.source;
11388
+ if (input.sourceId) data.source_id = input.sourceId;
11389
+ if (input.epic) data.epic = input.epic.trim();
11390
+ if (input.owners?.length) data.owners = input.owners.map((o) => o.trim()).filter(Boolean);
11391
+ if (input.contributors?.length) data.contributors = input.contributors.map((c) => c.trim()).filter(Boolean);
11392
+ return matter12.stringify("\n" + (input.body ?? defaultBody(input.title.trim())), data);
11393
+ }
11394
+ function createInitiative(dir, input) {
11395
+ if (!input.title?.trim()) throw new InitiativeWriteError("Initiative title is required.");
11396
+ const id = nextInitiativeId(dir);
11397
+ const fileName = `${id}-${slugify2(input.title)}.md`;
11398
+ const iniDir = join(dir, INITIATIVES_DIR);
11399
+ ensureDir(iniDir);
11400
+ const filePath = join(iniDir, fileName);
11401
+ const content = buildInitiativeContent(id, input);
11402
+ writeFile(filePath, content);
11403
+ const ini = parseInitiative(dir, filePath, content);
11404
+ if (!ini) throw new InitiativeWriteError("Failed to parse the Initiative just written.");
11405
+ return ini;
11406
+ }
11407
+ function transitionInitiative(dir, id, to, opts) {
11408
+ const ini = getInitiative(dir, id);
11409
+ if (!ini) throw new InitiativeWriteError(`Initiative ${id} not found.`);
11410
+ if (!isValidInitiativeStatus(to)) throw new InitiativeWriteError(`Invalid status: ${to}.`);
11411
+ if (to === "completed") throw new InitiativeWriteError(`Completing Initiative ${id} requires evidence-based review \u2014 use completeInitiative.`);
11412
+ if (ini.status === to) return ini;
11413
+ if (!isValidInitiativeTransition(ini.status, to)) {
11414
+ throw new InitiativeWriteError(`Invalid transition ${ini.status} \u2192 ${to}.`);
11415
+ }
11416
+ const raw = readFile(ini.filePath);
11417
+ assertFreshInitiative(ini.id, raw, opts);
11418
+ const { data, content } = matter12(raw, {});
11419
+ data.status = to;
11420
+ const newContent = matter12.stringify(content, data);
11421
+ writeFile(ini.filePath, newContent);
11422
+ const updated = parseInitiative(dir, ini.filePath, newContent);
11423
+ if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after transition.");
11424
+ return updated;
11425
+ }
11426
+ function findMaterializedWorkItem(dir, initiativeId, candidateId) {
11427
+ for (const wi of discoverWorkItems(dir)) {
11428
+ const fm2 = wi.rawFrontmatter ?? {};
11429
+ const si = typeof fm2.source_initiative === "string" ? fm2.source_initiative : void 0;
11430
+ const sid = typeof fm2.source_id === "string" ? fm2.source_id : void 0;
11431
+ if (si?.toLowerCase() === initiativeId.toLowerCase() && sid === candidateId) {
11432
+ return { id: wi.id, initiative: typeof fm2.initiative === "string" ? fm2.initiative : void 0 };
11315
11433
  }
11316
- const pending = m.outcome.notVerified + m.outcome.manualReview;
11317
- if (pending > 0) {
11318
- softBlocks.push(`milestone-${m.id}-pending`);
11319
- reasons.push(`Milestone ${m.id}: ${pending} exit criterion(s) not verified.`);
11434
+ }
11435
+ return null;
11436
+ }
11437
+ function addCandidate(dir, id, candidate, opts) {
11438
+ const ini = getInitiative(dir, id);
11439
+ if (!ini) throw new InitiativeWriteError(`Initiative ${id} not found.`);
11440
+ const raw = readFile(ini.filePath);
11441
+ assertFreshInitiative(ini.id, raw, opts);
11442
+ const { data, content } = matter12(raw, {});
11443
+ const existing = Array.isArray(data.candidates) ? data.candidates : [];
11444
+ const removed = Array.isArray(data.removed_candidates) ? data.removed_candidates : [];
11445
+ const fallbackId = nextCandidateId([...existing, ...removed]);
11446
+ const normalized = normalizeCandidate(candidate, fallbackId);
11447
+ normalized.materializedAs = null;
11448
+ if (ini.candidates.some((c) => c.id === normalized.id)) {
11449
+ throw new InitiativeWriteError(`Candidate ${normalized.id} already exists in ${id}.`);
11450
+ }
11451
+ data.candidates = [...existing, candidateToData(normalized)];
11452
+ const newContent = matter12.stringify(content, data);
11453
+ writeFile(ini.filePath, newContent);
11454
+ const updated = parseInitiative(dir, ini.filePath, newContent);
11455
+ if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after adding a candidate.");
11456
+ return updated;
11457
+ }
11458
+ function replaceBodySection(body, heading, newContent) {
11459
+ const lines = body.split(/\r?\n/);
11460
+ const want = heading.trim().toLowerCase();
11461
+ let start = -1;
11462
+ let level = 0;
11463
+ for (let i = 0; i < lines.length; i++) {
11464
+ const h = lines[i].match(/^(#{1,6})\s+(.*)$/);
11465
+ if (h && h[2].trim().toLowerCase() === want) {
11466
+ start = i;
11467
+ level = h[1].length;
11468
+ break;
11320
11469
  }
11321
- if (m.outcome.stale.length > 0) warnings.push(`Milestone ${m.id} has stale exit-criteria evidence.`);
11322
11470
  }
11323
- const readiness = decide(blockers, softBlocks, exceptions.some((x) => x.status === "accepted"));
11324
- pushReadinessReason(readiness, reasons);
11325
- return {
11326
- id: plan.id,
11327
- kind: "plan",
11328
- status: plan.status,
11329
- readiness,
11330
- reasons,
11331
- blockers,
11332
- warnings,
11333
- outcome,
11334
- delivery: { total: prog.delivery.total, completed: prog.delivery.completed, blocked: prog.delivery.blocked },
11335
- blockingDependencies: prog.readiness.blockingDependencies,
11336
- milestones,
11337
- epics,
11338
- exceptions
11471
+ const block = `${"#".repeat(level || 2)} ${heading.trim()}
11472
+
11473
+ ${newContent.trim()}
11474
+ `;
11475
+ if (start === -1) {
11476
+ return `${body.trimEnd()}
11477
+
11478
+ ${block}`;
11479
+ }
11480
+ let end = lines.length;
11481
+ for (let i = start + 1; i < lines.length; i++) {
11482
+ const h = lines[i].match(/^(#{1,6})\s+/);
11483
+ if (h && h[1].length <= level) {
11484
+ end = i;
11485
+ break;
11486
+ }
11487
+ }
11488
+ const before = lines.slice(0, start).join("\n").replace(/\s+$/, "");
11489
+ const after = lines.slice(end).join("\n").replace(/^\s+/, "");
11490
+ return [before, before ? "" : null, block.trimEnd(), after ? "" : null, after].filter((x) => x !== null).join("\n").replace(/\n{3,}/g, "\n\n");
11491
+ }
11492
+ function updateInitiative(dir, id, patch, opts) {
11493
+ const ini = getInitiative(dir, id);
11494
+ if (!ini) throw new InitiativeWriteError(`Initiative ${id} not found.`);
11495
+ const raw = readFile(ini.filePath);
11496
+ assertFreshInitiative(ini.id, raw, opts);
11497
+ let { data, content } = matter12(raw, {});
11498
+ if (patch.title !== void 0) {
11499
+ if (!patch.title.trim()) throw new InitiativeWriteError("Initiative title cannot be empty.");
11500
+ data.title = patch.title.trim();
11501
+ }
11502
+ if (patch.horizon !== void 0) data.horizon = patch.horizon;
11503
+ if (patch.priority !== void 0) data.priority = patch.priority;
11504
+ if (patch.knowledgeLevel !== void 0) data.knowledge_level = patch.knowledgeLevel;
11505
+ if (patch.domains !== void 0) data.domains = patch.domains;
11506
+ if (patch.relatedCapabilities !== void 0) data.related_capabilities = patch.relatedCapabilities;
11507
+ if (patch.epic !== void 0) {
11508
+ if (patch.epic === null || patch.epic.trim() === "") delete data.epic;
11509
+ else data.epic = patch.epic.trim();
11510
+ }
11511
+ if (patch.owners !== void 0) data.owners = patch.owners.map((o) => o.trim()).filter(Boolean);
11512
+ if (patch.contributors !== void 0) data.contributors = patch.contributors.map((c) => c.trim()).filter(Boolean);
11513
+ if (patch.sections) {
11514
+ for (const [heading, value] of Object.entries(patch.sections)) content = replaceBodySection(content, heading, value);
11515
+ }
11516
+ const newContent = matter12.stringify(content, data);
11517
+ writeFile(ini.filePath, newContent);
11518
+ const updated = parseInitiative(dir, ini.filePath, newContent);
11519
+ if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after update.");
11520
+ return updated;
11521
+ }
11522
+ function updateCandidate(dir, id, candidateId, patch, opts) {
11523
+ const ini = getInitiative(dir, id);
11524
+ if (!ini) throw new InitiativeWriteError(`Initiative ${id} not found.`);
11525
+ const current = ini.candidates.find((c) => c.id === candidateId);
11526
+ if (!current) throw new InitiativeWriteError(`Candidate ${candidateId} not found in ${id}.`);
11527
+ if (current.materializedAs) throw new InitiativeWriteError(`Candidate ${candidateId} is materialized as ${current.materializedAs}; edit the Work Item instead.`);
11528
+ const raw = readFile(ini.filePath);
11529
+ assertFreshInitiative(ini.id, raw, opts);
11530
+ const { data, content } = matter12(raw, {});
11531
+ const cands = Array.isArray(data.candidates) ? data.candidates : [];
11532
+ const entry = cands.find((c) => c && typeof c === "object" && String(c.id) === candidateId);
11533
+ if (!entry) throw new InitiativeWriteError(`Candidate ${candidateId} entry not found in ${id} frontmatter.`);
11534
+ if (patch.title !== void 0) entry.title = patch.title.trim();
11535
+ if (patch.type !== void 0) entry.type = patch.type?.trim() || void 0;
11536
+ if (patch.suggestedKnowledgeLevel !== void 0) entry.suggested_knowledge_level = patch.suggestedKnowledgeLevel?.trim() || void 0;
11537
+ if (patch.expectedValue !== void 0) entry.expected_value = patch.expectedValue?.trim() || void 0;
11538
+ if (patch.notes !== void 0) entry.notes = patch.notes?.trim() || void 0;
11539
+ if (patch.sourceSignals !== void 0) entry.source_signals = patch.sourceSignals;
11540
+ if (patch.dependencies !== void 0) entry.dependencies = patch.dependencies;
11541
+ for (const k of Object.keys(entry)) if (entry[k] === void 0) delete entry[k];
11542
+ data.candidates = cands;
11543
+ const newContent = matter12.stringify(content, data);
11544
+ writeFile(ini.filePath, newContent);
11545
+ const updated = parseInitiative(dir, ini.filePath, newContent);
11546
+ if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after editing a candidate.");
11547
+ return updated;
11548
+ }
11549
+ function removeCandidate(dir, id, candidateId, reason, opts) {
11550
+ if (!reason?.trim()) throw new InitiativeWriteError("A justification is required to remove a candidate.");
11551
+ const ini = getInitiative(dir, id);
11552
+ if (!ini) throw new InitiativeWriteError(`Initiative ${id} not found.`);
11553
+ const current = ini.candidates.find((c) => c.id === candidateId);
11554
+ if (!current) throw new InitiativeWriteError(`Candidate ${candidateId} not found in ${id}.`);
11555
+ if (current.materializedAs) throw new InitiativeWriteError(`Candidate ${candidateId} is materialized as ${current.materializedAs}; it cannot be removed from scope.`);
11556
+ const raw = readFile(ini.filePath);
11557
+ assertFreshInitiative(ini.id, raw, opts);
11558
+ const { data, content } = matter12(raw, {});
11559
+ const cands = Array.isArray(data.candidates) ? data.candidates : [];
11560
+ data.candidates = cands.filter((c) => !(c && typeof c === "object" && String(c.id) === candidateId));
11561
+ const log2 = Array.isArray(data.removed_candidates) ? data.removed_candidates : [];
11562
+ log2.push({ id: candidateId, title: current.title, reason: reason.trim(), removed_at: today() });
11563
+ data.removed_candidates = log2;
11564
+ const newContent = matter12.stringify(content, data);
11565
+ writeFile(ini.filePath, newContent);
11566
+ const updated = parseInitiative(dir, ini.filePath, newContent);
11567
+ if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after removing a candidate.");
11568
+ return updated;
11569
+ }
11570
+ function addExternalLink(dir, id, link) {
11571
+ const ini = getInitiative(dir, id);
11572
+ if (!ini) throw new InitiativeWriteError(`Initiative ${id} not found.`);
11573
+ if (!link.integration?.trim() || !link.externalId?.trim()) {
11574
+ throw new InitiativeWriteError("External link requires integration and externalId.");
11575
+ }
11576
+ if (ini.externalLinks.some(
11577
+ (l) => l.integration.trim().toLowerCase() === link.integration.trim().toLowerCase() && l.externalId.trim().toLowerCase() === link.externalId.trim().toLowerCase()
11578
+ )) {
11579
+ throw new InitiativeWriteError(`External link ${link.integration}:${link.externalId} already exists on ${id}.`);
11580
+ }
11581
+ const raw = readFile(ini.filePath);
11582
+ const { data, content } = matter12(raw, {});
11583
+ const existing = Array.isArray(data.external_links) ? data.external_links : [];
11584
+ data.external_links = [...existing, externalLinkToData(link)];
11585
+ const newContent = matter12.stringify(content, data);
11586
+ writeFile(ini.filePath, newContent);
11587
+ const updated = parseInitiative(dir, ini.filePath, newContent);
11588
+ if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after adding an external link.");
11589
+ return updated;
11590
+ }
11591
+ function nextWorkItemId(dir) {
11592
+ const wiDir = join(dir, WORK_ITEMS_DIR);
11593
+ let max = 0;
11594
+ const walk2 = (d) => {
11595
+ if (!exists(d)) return;
11596
+ for (const entry of readDir(d)) {
11597
+ const full = join(d, entry);
11598
+ if (isFile(full)) {
11599
+ const m = entry.match(/WI-(\d+)/);
11600
+ if (m) max = Math.max(max, parseInt(m[1], 10));
11601
+ } else if (!entry.startsWith(".")) {
11602
+ walk2(full);
11603
+ }
11604
+ }
11605
+ };
11606
+ walk2(wiDir);
11607
+ return `WI-${String(max + 1).padStart(3, "0")}`;
11608
+ }
11609
+ function buildWorkItemContent(wiId, iniId, candidate) {
11610
+ const data = {
11611
+ type: candidate.type ?? "feature",
11612
+ id: wiId,
11613
+ title: candidate.title,
11614
+ knowledge_level: candidate.suggestedKnowledgeLevel ?? "K2",
11615
+ status: "draft",
11616
+ phase: "now",
11617
+ initiative: iniId,
11618
+ domains: [],
11619
+ code: [],
11620
+ created_at: today(),
11621
+ source: "initiative",
11622
+ source_id: candidate.id,
11623
+ source_initiative: iniId,
11624
+ affected_modules: []
11339
11625
  };
11626
+ if (candidate.sourceSignals.length) data.source_signals = candidate.sourceSignals;
11627
+ if (candidate.dependencies.length) data.dependencies = candidate.dependencies;
11628
+ const body = [
11629
+ `# ${candidate.title}`,
11630
+ "",
11631
+ `> Materialized from Initiative ${iniId}, candidate ${candidate.id}.`,
11632
+ "",
11633
+ "## Problem",
11634
+ "",
11635
+ candidate.expectedValue ? `_Expected value:_ ${candidate.expectedValue}` : "_Describe the problem._",
11636
+ "",
11637
+ "## Acceptance Criteria",
11638
+ "",
11639
+ "- [ ] _Define at least one testable criterion._",
11640
+ "",
11641
+ "## Out of scope",
11642
+ "",
11643
+ "_Not included in this Work Item._",
11644
+ "",
11645
+ "## Validation",
11646
+ "",
11647
+ "_How will this be validated?_",
11648
+ "",
11649
+ "## Learning",
11650
+ "",
11651
+ "_What did we learn? Update after completion._",
11652
+ ""
11653
+ ].join("\n");
11654
+ return matter12.stringify("\n" + body, data);
11340
11655
  }
11341
- function integrityBlockers(dir, subjectId) {
11342
- return validatePlanningGraph(dir).filter((f) => f.level === "error" && f.subject.toLowerCase() === subjectId.toLowerCase()).map((f) => f.message);
11656
+ function setCandidateMaterialized(dir, ini, candidateId, wiId) {
11657
+ const raw = readFile(ini.filePath);
11658
+ const { data, content } = matter12(raw, {});
11659
+ const cands = Array.isArray(data.candidates) ? data.candidates : [];
11660
+ for (const c of cands) if (c && typeof c === "object" && String(c.id) === candidateId) c.materialized_as = wiId;
11661
+ data.candidates = cands;
11662
+ const newContent = matter12.stringify(content, data);
11663
+ writeFile(ini.filePath, newContent);
11664
+ const updated = parseInitiative(dir, ini.filePath, newContent);
11665
+ if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after materialization.");
11666
+ return updated;
11343
11667
  }
11344
- function evaluateOutcomeInto(declaredOutcome, requireDeclaredOutcome, outcome, blockers, softBlocks, reasons, warnings) {
11345
- if (requireDeclaredOutcome && !declaredOutcome) {
11346
- softBlocks.push("no-outcome");
11347
- reasons.push("No expected outcome is declared.");
11348
- }
11349
- if (outcome.total === 0) {
11350
- softBlocks.push("no-success-criteria");
11351
- reasons.push("No success criteria to verify \u2014 completion cannot be judged by outcome.");
11352
- }
11353
- if (outcome.ambiguous > 0) {
11354
- softBlocks.push("criteria-ambiguous");
11355
- reasons.push(`${outcome.ambiguous} success criterion(s) collide in text \u2014 rename to disambiguate before verifying.`);
11668
+ function materializeCandidate(dir, id, candidateId, opts) {
11669
+ const ini = getInitiative(dir, id);
11670
+ if (!ini) throw new InitiativeWriteError(`Initiative ${id} not found.`);
11671
+ assertFreshInitiative(ini.id, readFile(ini.filePath), opts);
11672
+ const candidate = ini.candidates.find((c) => c.id === candidateId);
11673
+ if (!candidate) throw new InitiativeWriteError(`Candidate ${candidateId} not found in ${id}.`);
11674
+ if (candidate.materializedAs) {
11675
+ const exists2 = discoverWorkItems(dir).some((w) => w.id.toLowerCase() === candidate.materializedAs.toLowerCase());
11676
+ if (!exists2) throw new InitiativeWriteError(`Candidate ${candidateId} points at missing Work Item ${candidate.materializedAs} (broken relation). Resolve it before materializing.`);
11677
+ return { workItemId: candidate.materializedAs, fileName: null, initiative: ini, alreadyMaterialized: true };
11356
11678
  }
11357
- if (outcome.failed > 0) {
11358
- softBlocks.push("criteria-failed");
11359
- reasons.push(`${outcome.failed} success criterion(s) failed verification.`);
11679
+ const existing = findMaterializedWorkItem(dir, ini.id, candidateId);
11680
+ if (existing) {
11681
+ if (existing.initiative && existing.initiative.toLowerCase() !== ini.id.toLowerCase()) {
11682
+ throw new InitiativeWriteError(`A Work Item for candidate ${candidateId} already belongs to ${existing.initiative} (conflicting provenance).`);
11683
+ }
11684
+ const repaired = setCandidateMaterialized(dir, ini, candidateId, existing.id);
11685
+ return { workItemId: existing.id, fileName: null, initiative: repaired, alreadyMaterialized: true };
11360
11686
  }
11361
- const pending = outcome.notVerified + outcome.manualReview - outcome.ambiguous;
11362
- if (pending > 0) {
11363
- softBlocks.push("criteria-unverified");
11364
- reasons.push(`${pending} success criterion(s) not verified (no or insufficient evidence).`);
11687
+ const wiId = nextWorkItemId(dir);
11688
+ const fileName = `${wiId}-${slugify2(candidate.title)}.md`;
11689
+ ensureDir(join(dir, DRAFT_DIR));
11690
+ writeFile(join(dir, DRAFT_DIR, fileName), buildWorkItemContent(wiId, ini.id, candidate));
11691
+ const updated = setCandidateMaterialized(dir, ini, candidateId, wiId);
11692
+ return { workItemId: wiId, fileName, initiative: updated, alreadyMaterialized: false };
11693
+ }
11694
+ function materializeRoadmapInitiative(dir, rmId) {
11695
+ const roadmapFull = join(dir, ROADMAP_PATH2);
11696
+ if (!exists(roadmapFull)) throw new InitiativeWriteError(`No roadmap found at ${ROADMAP_PATH2}.`);
11697
+ const all = parseRoadmapCandidates(readFile(roadmapFull));
11698
+ const want = rmId.trim().toLowerCase();
11699
+ const belonging = all.filter((c) => (c.initiative?.id ?? "").toLowerCase() === want);
11700
+ if (belonging.length === 0) {
11701
+ throw new InitiativeWriteError(`No roadmap initiative "${rmId}" with candidates found.`);
11365
11702
  }
11366
- if (outcome.stale.length > 0) warnings.push(`${outcome.stale.length} evidence record(s) no longer match a declared criterion (stale).`);
11703
+ const title = belonging[0].initiative?.title?.trim() || rmId;
11704
+ const candidates = belonging.map((c) => ({
11705
+ id: c.id,
11706
+ title: c.title,
11707
+ type: c.type,
11708
+ suggestedKnowledgeLevel: c.suggestedKnowledgeLevel,
11709
+ expectedValue: c.expectedValue,
11710
+ notes: c.notes,
11711
+ sourceSignals: c.sourceSignals ?? [],
11712
+ dependencies: c.dependencies ?? [],
11713
+ materializedAs: null
11714
+ }));
11715
+ const domains = belonging[0].domain ? [belonging[0].domain] : [];
11716
+ const relatedCapabilities = Array.from(
11717
+ new Set(belonging.flatMap((c) => c.relatedCapabilities ?? []))
11718
+ );
11719
+ return createInitiative(dir, {
11720
+ title,
11721
+ status: "planned",
11722
+ domains,
11723
+ relatedCapabilities,
11724
+ source: "roadmap",
11725
+ sourceId: rmId,
11726
+ candidates
11727
+ });
11367
11728
  }
11368
- function pushReadinessReason(readiness, reasons) {
11369
- if (readiness === "READY_TO_COMPLETE") reasons.unshift("All success criteria are verified and committed work is complete. Human approval is still required to close.");
11370
- else if (readiness === "READY_WITH_EXCEPTIONS") reasons.unshift("Remaining gaps are covered by accepted exceptions. Human approval is still required to close.");
11729
+ function assertDeclaredCriterion(declared, criterion) {
11730
+ const key = normalizeCriterion(criterion);
11731
+ const matches = declared.filter((c) => normalizeCriterion(c) === key).length;
11732
+ if (matches === 0) throw new InitiativeWriteError(`"${criterion}" is not a declared success criterion.`);
11733
+ if (matches > 1) throw new InitiativeWriteError(`"${criterion}" matches more than one declared criterion \u2014 disambiguate before recording evidence.`);
11371
11734
  }
11372
- function evaluateEpicById(dir, id) {
11373
- const e = getEpic(dir, id);
11374
- return e ? evaluateEpicCompletion(dir, e) : null;
11735
+ function upsertEvidence(existing, input) {
11736
+ const list2 = (Array.isArray(existing) ? existing : []).filter((e) => e && typeof e === "object" && !Array.isArray(e));
11737
+ const key = normalizeCriterion(input.criterion);
11738
+ const kept = list2.filter((e) => normalizeCriterion(String(e.criterion ?? "")) !== key);
11739
+ const obj = { criterion: input.criterion.trim(), status: input.status };
11740
+ if (input.evidence?.trim()) obj.evidence = input.evidence.trim();
11741
+ if (input.reference?.trim()) obj.reference = input.reference.trim();
11742
+ if (input.method) obj.method = input.method;
11743
+ obj.verified_at = today();
11744
+ if (input.verifiedBy?.trim()) obj.verified_by = input.verifiedBy.trim();
11745
+ return [...kept, obj];
11375
11746
  }
11376
- function evaluatePlanById(dir, id) {
11377
- const p = getPlan(dir, id);
11378
- return p ? evaluatePlanCompletion(dir, p) : null;
11747
+ function recordInitiativeOutcomeVerification(dir, id, input, opts) {
11748
+ const ini = getInitiative(dir, id);
11749
+ if (!ini) throw new InitiativeWriteError(`Initiative ${id} not found.`);
11750
+ assertDeclaredCriterion(parseSuccessCriteria(ini.body).map((c) => c.text), input.criterion);
11751
+ const raw = readFile(ini.filePath);
11752
+ assertFreshInitiative(ini.id, raw, opts);
11753
+ const { data, content } = matter12(raw, {});
11754
+ data.outcome_verifications = upsertEvidence(data.outcome_verifications, input);
11755
+ const newContent = matter12.stringify(content, data);
11756
+ writeFile(ini.filePath, newContent);
11757
+ const updated = parseInitiative(dir, ini.filePath, newContent);
11758
+ if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after recording evidence.");
11759
+ return updated;
11760
+ }
11761
+ var InitiativeNotReadyError = class extends InitiativeWriteError {
11762
+ constructor(evaluation) {
11763
+ super(`Initiative ${evaluation.id} is not ready to complete (${evaluation.readiness}).`);
11764
+ this.evaluation = evaluation;
11765
+ this.name = "InitiativeNotReadyError";
11766
+ }
11767
+ evaluation;
11768
+ };
11769
+ function completeInitiative(dir, id, input = {}, opts) {
11770
+ const ini = getInitiative(dir, id);
11771
+ if (!ini) throw new InitiativeWriteError(`Initiative ${id} not found.`);
11772
+ const evaluation = evaluateInitiativeCompletion(dir, ini);
11773
+ if (evaluation.readiness !== "READY_TO_COMPLETE" && evaluation.readiness !== "READY_WITH_EXCEPTIONS") throw new InitiativeNotReadyError(evaluation);
11774
+ if (!isValidInitiativeTransition(ini.status, "completed")) throw new InitiativeWriteError(`Initiative ${id} cannot move from ${ini.status} to completed.`);
11775
+ const raw = readFile(ini.filePath);
11776
+ assertFreshInitiative(ini.id, raw, opts);
11777
+ const { data, content } = matter12(raw, {});
11778
+ data.status = "completed";
11779
+ data.completed_at = today();
11780
+ const decision = { readiness: evaluation.readiness, decided_at: today(), reasons: evaluation.reasons };
11781
+ if (input.decidedBy?.trim()) decision.decided_by = input.decidedBy.trim();
11782
+ if (input.note?.trim()) decision.note = input.note.trim();
11783
+ const accepted = evaluation.exceptions.filter((x) => x.status === "accepted");
11784
+ if (accepted.length > 0) decision.exceptions = accepted;
11785
+ data.completion_decision = decision;
11786
+ const newContent = matter12.stringify(content, data);
11787
+ writeFile(ini.filePath, newContent);
11788
+ const updated = parseInitiative(dir, ini.filePath, newContent);
11789
+ if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after completion.");
11790
+ return updated;
11379
11791
  }
11380
11792
 
11381
11793
  // src/core/delivery-planning-write.ts
@@ -11668,7 +12080,7 @@ function assertCriterionDeclared(declared, criterion, kind) {
11668
12080
  if (matches === 0) throw new DeliveryPlanningWriteError(`"${criterion}" is not a declared ${kind} criterion.`);
11669
12081
  if (matches > 1) throw new DeliveryPlanningWriteError(`"${criterion}" matches more than one declared ${kind} criterion \u2014 rename them to disambiguate before recording evidence.`);
11670
12082
  }
11671
- function upsertEvidence(existing, input) {
12083
+ function upsertEvidence2(existing, input) {
11672
12084
  const list2 = Array.isArray(existing) ? existing.filter((e) => e && typeof e === "object" && !Array.isArray(e)) : [];
11673
12085
  const key = normalizeCriterion(input.criterion);
11674
12086
  const kept = list2.filter((e) => normalizeCriterion(String(e.criterion ?? "")) !== key);
@@ -11687,7 +12099,7 @@ function recordEpicOutcomeVerification(dir, id, input, opts) {
11687
12099
  const raw = readFile(epic.filePath);
11688
12100
  assertFreshRevision(epic.id, raw, opts);
11689
12101
  const { data, content } = matter13(raw, {});
11690
- data.outcome_verifications = upsertEvidence(data.outcome_verifications, input);
12102
+ data.outcome_verifications = upsertEvidence2(data.outcome_verifications, input);
11691
12103
  const newContent = matter13.stringify(content, data);
11692
12104
  writeFile(epic.filePath, newContent);
11693
12105
  const updated = parseEpic(dir, epic.filePath, newContent);
@@ -11701,7 +12113,7 @@ function recordPlanOutcomeVerification(dir, id, input, opts) {
11701
12113
  const raw = readFile(plan.filePath);
11702
12114
  assertFreshRevision(plan.id, raw, opts);
11703
12115
  const { data, content } = matter13(raw, {});
11704
- data.outcome_verifications = upsertEvidence(data.outcome_verifications, input);
12116
+ data.outcome_verifications = upsertEvidence2(data.outcome_verifications, input);
11705
12117
  const newContent = matter13.stringify(content, data);
11706
12118
  writeFile(plan.filePath, newContent);
11707
12119
  const updated = parseDeliveryPlan(dir, plan.filePath, newContent);
@@ -11720,7 +12132,7 @@ function recordMilestoneExitVerification(dir, planId, milestoneId, input, opts)
11720
12132
  const rawMs = Array.isArray(data.milestones) ? data.milestones : [];
11721
12133
  const entry = rawMs.find((m) => m && typeof m === "object" && String(m.id ?? "").toLowerCase() === milestoneId.toLowerCase());
11722
12134
  if (!entry) throw new DeliveryPlanningWriteError(`Milestone ${milestoneId} entry not found in ${planId} frontmatter.`);
11723
- entry.exit_verifications = upsertEvidence(entry.exit_verifications, input);
12135
+ entry.exit_verifications = upsertEvidence2(entry.exit_verifications, input);
11724
12136
  data.milestones = rawMs;
11725
12137
  const newContent = matter13.stringify(content, data);
11726
12138
  writeFile(plan.filePath, newContent);
@@ -13243,7 +13655,7 @@ function normalizeImpact(ia) {
13243
13655
  ...v.question ? { question: v.question } : {}
13244
13656
  }));
13245
13657
  }
13246
- function optStr5(v) {
13658
+ function optStr6(v) {
13247
13659
  if (typeof v === "string" && v.trim()) return v.trim();
13248
13660
  return void 0;
13249
13661
  }
@@ -13258,13 +13670,13 @@ function parseEvidence(fm2) {
13258
13670
  const validations = Array.isArray(d.validations) ? d.validations.map((v) => ({
13259
13671
  command: String(v.command ?? ""),
13260
13672
  status: String(v.status ?? "unknown"),
13261
- ...optStr5(v.reason) ? { reason: optStr5(v.reason) } : {}
13673
+ ...optStr6(v.reason) ? { reason: optStr6(v.reason) } : {}
13262
13674
  })) : [];
13263
13675
  const migrations = Array.isArray(d.migrations) ? d.migrations.map((m) => ({
13264
13676
  id: String(m.id ?? ""),
13265
13677
  environment: String(m.environment ?? ""),
13266
13678
  status: String(m.status ?? "unknown"),
13267
- ...optStr5(m.reason) ? { reason: optStr5(m.reason) } : {}
13679
+ ...optStr6(m.reason) ? { reason: optStr6(m.reason) } : {}
13268
13680
  })) : [];
13269
13681
  out.push({
13270
13682
  module,
@@ -13282,8 +13694,8 @@ function parseReleaseGates(fm2) {
13282
13694
  return fm2.release_gates.filter((g) => g && typeof g === "object").map((g) => ({
13283
13695
  id: String(g.id ?? ""),
13284
13696
  status: String(g.status ?? "pending"),
13285
- ...optStr5(g.reason) ? { reason: optStr5(g.reason) } : {},
13286
- ...optStr5(g.required_for) ? { requiredFor: optStr5(g.required_for) } : {}
13697
+ ...optStr6(g.reason) ? { reason: optStr6(g.reason) } : {},
13698
+ ...optStr6(g.required_for) ? { requiredFor: optStr6(g.required_for) } : {}
13287
13699
  }));
13288
13700
  }
13289
13701
  function parseExceptions2(fm2) {
@@ -13291,9 +13703,9 @@ function parseExceptions2(fm2) {
13291
13703
  return fm2.completion_exceptions.filter((e) => e && typeof e === "object").map((e) => ({
13292
13704
  id: String(e.id ?? ""),
13293
13705
  status: String(e.status ?? "proposed"),
13294
- ...optStr5(e.reason) ? { reason: optStr5(e.reason) } : {},
13295
- ...optStr5(e.category) ? { category: optStr5(e.category) } : {},
13296
- ...optStr5(e.impact) ? { impact: optStr5(e.impact) } : {}
13706
+ ...optStr6(e.reason) ? { reason: optStr6(e.reason) } : {},
13707
+ ...optStr6(e.category) ? { category: optStr6(e.category) } : {},
13708
+ ...optStr6(e.impact) ? { impact: optStr6(e.impact) } : {}
13297
13709
  }));
13298
13710
  }
13299
13711
  function parseDecisions(decisions, knowledgeById) {
@@ -17093,109 +17505,155 @@ function getStatus(dir) {
17093
17505
  };
17094
17506
  }
17095
17507
 
17096
- // src/core/initiative-analysis.ts
17097
- var SUCCESS_HEADING_RE = /^#{1,6}\s*(success criteria|criterios de[ét]xito|criterios de éxito)\s*$/i;
17098
- var HEADING_RE2 = /^#{1,6}\s+/;
17099
- var CHECK_ITEM_RE = /^\s*[-*]\s+\[([ xX])\]\s+(.*)$/;
17100
- var BULLET_RE2 = /^\s*[-*]\s+(.*)$/;
17101
- var PLACEHOLDER_RE = /^_.*_$/;
17102
- function parseSuccessCriteria(body) {
17103
- const lines = body.split(/\r?\n/);
17104
- const out = [];
17105
- let capture = false;
17106
- for (const line of lines) {
17107
- if (capture && HEADING_RE2.test(line)) break;
17108
- if (!capture) {
17109
- if (SUCCESS_HEADING_RE.test(line.trim())) capture = true;
17110
- continue;
17111
- }
17112
- const check = line.match(CHECK_ITEM_RE);
17113
- if (check) {
17114
- const text2 = check[2].trim();
17115
- if (text2 && !PLACEHOLDER_RE.test(text2)) {
17116
- out.push({ text: text2, checked: check[1].toLowerCase() === "x" });
17117
- }
17118
- continue;
17119
- }
17120
- const bullet = line.match(BULLET_RE2);
17121
- if (bullet) {
17122
- const text2 = bullet[1].trim();
17123
- if (text2 && !PLACEHOLDER_RE.test(text2)) out.push({ text: text2, checked: null });
17124
- }
17508
+ // src/core/planning-insights.ts
17509
+ function optStr7(v) {
17510
+ return typeof v === "string" && v.trim() ? v.trim() : void 0;
17511
+ }
17512
+ function kindOf(id) {
17513
+ const up = id.toUpperCase();
17514
+ if (up.startsWith("PLAN-")) return "plan";
17515
+ if (up.startsWith("EP-")) return "epic";
17516
+ if (up.startsWith("INI-")) return "initiative";
17517
+ return "work-item";
17518
+ }
17519
+ function linkFor(id, kind) {
17520
+ switch (kind) {
17521
+ case "plan":
17522
+ return `/planning/plans/${id}`;
17523
+ case "epic":
17524
+ return `/planning/epics/${id}`;
17525
+ case "initiative":
17526
+ return `/initiatives/${id}`;
17527
+ case "work-item":
17528
+ return `/work-items/${id}`;
17125
17529
  }
17530
+ }
17531
+ function tally(ids) {
17532
+ const out = {};
17533
+ for (const s of ids) out[s] = (out[s] ?? 0) + 1;
17126
17534
  return out;
17127
17535
  }
17128
- function analyzeInitiative(dir, ini) {
17129
- const progress = computeInitiativeProgress(dir, ini);
17130
- const successCriteria = parseSuccessCriteria(ini.body);
17131
- const pendingCandidates = ini.candidates.filter((c) => !c.materializedAs);
17132
- const associated = associatedWorkItems(dir, ini.id);
17133
- const findings = [];
17134
- if (successCriteria.length === 0) {
17135
- findings.push({
17136
- code: "no-success-criteria",
17137
- severity: "warning",
17138
- message: "The Initiative has no explicit Success Criteria; completion cannot be judged by outcome, only by delivery."
17139
- });
17140
- } else {
17141
- const uncovered = successCriteria.filter((c) => c.checked === false);
17142
- if (uncovered.length > 0) {
17143
- findings.push({
17144
- code: "uncovered-success-criteria",
17145
- severity: "blocking",
17146
- message: `${uncovered.length} success criterion/criteria remain uncovered.`,
17147
- items: uncovered.map((c) => c.text)
17148
- });
17149
- }
17150
- }
17151
- if (pendingCandidates.length > 0) {
17152
- findings.push({
17153
- code: "pending-candidates",
17154
- severity: "blocking",
17155
- message: `${pendingCandidates.length} committed candidate(s) not yet materialized into Work Items.`,
17156
- items: pendingCandidates.map((c) => `${c.id}: ${c.title}`)
17536
+ function unverified(o) {
17537
+ return o.failed + o.notVerified + o.manualReview + o.ambiguous;
17538
+ }
17539
+ function isPlanningAssociated(wi) {
17540
+ return Boolean(wi.initiative) || Boolean(optStr7(wi.rawFrontmatter?.epic));
17541
+ }
17542
+ function computePlanningInsights(dir) {
17543
+ const plans = discoverDeliveryPlans(dir);
17544
+ const epics = discoverEpics(dir);
17545
+ const initiatives = discoverInitiatives(dir);
17546
+ const findings = validatePlanningGraph(dir);
17547
+ const allWis = discoverWorkItems(dir);
17548
+ const associatedWis = allWis.filter(isPlanningAssociated);
17549
+ const independentWis = allWis.filter((w) => !isPlanningAssociated(w));
17550
+ const delivery = {
17551
+ associated: computeDeliveryProgress(associatedWis, dir),
17552
+ independent: computeDeliveryProgress(independentWis, dir)
17553
+ };
17554
+ const totalCandidates = initiatives.reduce((n, i) => n + i.candidates.length, 0);
17555
+ const materialized = initiatives.reduce((n, i) => n + i.candidates.filter((c) => c.materializedAs).length, 0);
17556
+ const coverage = { totalCandidates, materialized, pending: totalCandidates - materialized };
17557
+ const planEvals = plans.map((p) => ({ p, ev: evaluatePlanCompletion(dir, p) }));
17558
+ const epicEvals = epics.map((e) => ({ e, ev: evaluateEpicCompletion(dir, e) }));
17559
+ const iniEvals = initiatives.map((i) => ({ i, ev: evaluateInitiativeCompletion(dir, i) }));
17560
+ const outcome = { total: 0, passed: 0, failed: 0, notVerified: 0, manualReview: 0, ambiguous: 0, stale: 0 };
17561
+ const addOutcome = (o) => {
17562
+ outcome.total += o.total;
17563
+ outcome.passed += o.passed;
17564
+ outcome.failed += o.failed;
17565
+ outcome.notVerified += o.notVerified;
17566
+ outcome.manualReview += o.manualReview;
17567
+ outcome.ambiguous += o.ambiguous;
17568
+ outcome.stale += o.stale.length;
17569
+ };
17570
+ planEvals.forEach(({ ev }) => addOutcome(ev.outcome));
17571
+ epicEvals.forEach(({ ev }) => addOutcome(ev.outcome));
17572
+ iniEvals.forEach(({ ev }) => addOutcome(ev.outcome));
17573
+ const attention = [];
17574
+ const push = (it) => attention.push(it);
17575
+ for (const f of findings) {
17576
+ const kind = kindOf(f.subject);
17577
+ const type = f.kind === "dependency_cycle" || f.kind === "pending_dependency" ? "dependency" : "provenance";
17578
+ push({
17579
+ type,
17580
+ severity: f.level === "error" ? "blocking" : "warning",
17581
+ artifactId: f.subject,
17582
+ artifactKind: kind,
17583
+ title: f.subject,
17584
+ reason: f.message,
17585
+ link: linkFor(f.subject, kind)
17157
17586
  });
17158
17587
  }
17159
- const notCompleted = associated.filter((w) => w.status !== "completed" && w.status !== "archived");
17160
- if (associated.length === 0) {
17161
- findings.push({
17162
- code: "no-delivery",
17163
- severity: "info",
17164
- message: "No Work Items are associated with this Initiative yet."
17165
- });
17166
- } else if (notCompleted.length > 0) {
17167
- findings.push({
17168
- code: "incomplete-delivery",
17169
- severity: "blocking",
17170
- message: `${notCompleted.length} associated Work Item(s) are not completed.`,
17171
- items: notCompleted.map((w) => `${w.id} (${w.status})`)
17172
- });
17588
+ for (const p of plans) for (const r of p.risks) {
17589
+ push({ type: "declared-risk", severity: "info", artifactId: p.id, artifactKind: "plan", title: p.title, reason: r, link: linkFor(p.id, "plan") });
17173
17590
  }
17174
- return {
17175
- initiative: ini.id,
17176
- status: ini.status,
17177
- progress,
17178
- successCriteria,
17179
- pendingCandidates,
17180
- findings,
17181
- suggestedCandidates: pendingCandidates
17591
+ const outcomeSignal = (id, kind, title, o) => {
17592
+ const n = unverified(o);
17593
+ if (n > 0) push({ type: "unverified-outcome", severity: "warning", artifactId: id, artifactKind: kind, title, reason: `${n} success criterion(s) without valid evidence (failed/not-verified/manual-review/ambiguous).`, link: linkFor(id, kind) });
17594
+ if (o.stale.length > 0) push({ type: "unverified-outcome", severity: "warning", artifactId: id, artifactKind: kind, title, reason: `${o.stale.length} evidence record(s) stale: the criterion changed and is not reattributed.`, link: linkFor(id, kind) });
17182
17595
  };
17183
- }
17184
- function evaluateInitiativeCompletion(dir, ini) {
17185
- const analysis = analyzeInitiative(dir, ini);
17186
- const reasons = [];
17187
- for (const f of analysis.findings) {
17188
- if (f.severity === "blocking") reasons.push(f.message);
17189
- }
17190
- if (analysis.progress.delivery.total === 0 && analysis.pendingCandidates.length === 0) {
17191
- reasons.push("Nothing has been delivered or committed under this Initiative.");
17596
+ const incompleteSignal = (id, kind, title, status, total, completed) => {
17597
+ if (status === "in-progress" && total > 0 && completed < total) {
17598
+ push({ type: "incomplete-delivery", severity: "info", artifactId: id, artifactKind: kind, title, reason: `${total - completed} of ${total} committed Work Item(s) not completed.`, link: linkFor(id, kind) });
17599
+ }
17600
+ };
17601
+ planEvals.forEach(({ p, ev }) => {
17602
+ outcomeSignal(p.id, "plan", p.title, ev.outcome);
17603
+ incompleteSignal(p.id, "plan", p.title, p.status, ev.delivery.total, ev.delivery.completed);
17604
+ });
17605
+ epicEvals.forEach(({ e, ev }) => {
17606
+ outcomeSignal(e.id, "epic", e.title, ev.outcome);
17607
+ incompleteSignal(e.id, "epic", e.title, e.status, ev.delivery.total, ev.delivery.completed);
17608
+ });
17609
+ iniEvals.forEach(({ i, ev }) => {
17610
+ outcomeSignal(i.id, "initiative", i.title, ev.outcome);
17611
+ incompleteSignal(i.id, "initiative", i.title, i.status, ev.delivery.total, ev.delivery.completed);
17612
+ if (ev.pendingCandidates.length > 0) push({ type: "pending-candidates", severity: "info", artifactId: i.id, artifactKind: "initiative", title: i.title, reason: `${ev.pendingCandidates.length} committed candidate(s) not yet materialized (coverage signal, not an execution blocker).`, link: linkFor(i.id, "initiative") });
17613
+ for (const pv of ev.provenanceIssues) push({ type: "provenance", severity: "blocking", artifactId: i.id, artifactKind: "initiative", title: i.title, reason: pv, link: linkFor(i.id, "initiative") });
17614
+ });
17615
+ const seen = /* @__PURE__ */ new Set();
17616
+ const consolidated = attention.filter((a) => {
17617
+ const key = `${a.type}|${a.artifactId.toLowerCase()}|${a.reason}`;
17618
+ if (seen.has(key)) return false;
17619
+ seen.add(key);
17620
+ return true;
17621
+ });
17622
+ const sevRank = { blocking: 0, warning: 1, info: 2 };
17623
+ const kindRank = { plan: 0, epic: 1, initiative: 2, "work-item": 3 };
17624
+ consolidated.sort(
17625
+ (a, b) => sevRank[a.severity] - sevRank[b.severity] || kindRank[a.artifactKind] - kindRank[b.artifactKind] || a.artifactId.localeCompare(b.artifactId) || a.type.localeCompare(b.type) || a.reason.localeCompare(b.reason)
17626
+ );
17627
+ const milestones = [];
17628
+ for (const p of plans) {
17629
+ for (const mv of planMilestoneVerifications(p)) {
17630
+ const epicsForM = epics.filter((e) => e.plan?.toLowerCase() === p.id.toLowerCase() && e.milestone?.toLowerCase() === mv.id.toLowerCase()).length;
17631
+ milestones.push({ id: mv.id, title: mv.title, planId: p.id, planTitle: p.title, epics: epicsForM, outcome: mv.outcome, needsReview: unverified(mv.outcome) > 0 || mv.outcome.stale.length > 0 });
17632
+ }
17192
17633
  }
17193
- const ready = reasons.length === 0;
17634
+ const entities = [
17635
+ ...planEvals.map(({ p, ev }) => ({ id: p.id, kind: "plan", title: p.title, status: p.status, readiness: ev.readiness, delivery: { total: ev.delivery.total, completed: ev.delivery.completed, blocked: ev.delivery.blocked }, outcome: { total: ev.outcome.total, passed: ev.outcome.passed, needsVerification: unverified(ev.outcome) }, link: linkFor(p.id, "plan") })),
17636
+ ...epicEvals.map(({ e, ev }) => ({ id: e.id, kind: "epic", title: e.title, status: e.status, readiness: ev.readiness, delivery: { total: ev.delivery.total, completed: ev.delivery.completed, blocked: ev.delivery.blocked }, outcome: { total: ev.outcome.total, passed: ev.outcome.passed, needsVerification: unverified(ev.outcome) }, link: linkFor(e.id, "epic") })),
17637
+ // Initiatives do not track blocked Work Items here (consistent with the Planning overview), so blocked is 0.
17638
+ ...iniEvals.map(({ i, ev }) => ({ id: i.id, kind: "initiative", title: i.title, status: i.status, readiness: ev.readiness, delivery: { total: ev.delivery.total, completed: ev.delivery.completed, blocked: 0 }, outcome: { total: ev.outcome.total, passed: ev.outcome.passed, needsVerification: unverified(ev.outcome) }, link: linkFor(i.id, "initiative") }))
17639
+ ];
17194
17640
  return {
17195
- initiative: ini.id,
17196
- ready,
17197
- readiness: ready ? "ready" : "not-ready",
17198
- reasons
17641
+ counts: {
17642
+ plans: tally(plans.map((p) => p.status)),
17643
+ epics: tally(epics.map((e) => e.status)),
17644
+ initiatives: tally(initiatives.map((i) => i.status))
17645
+ },
17646
+ coverage,
17647
+ delivery,
17648
+ outcome,
17649
+ indicators: {
17650
+ blockingIssues: consolidated.filter((a) => a.severity === "blocking").length,
17651
+ outcomeNeedsVerification: outcome.failed + outcome.notVerified + outcome.manualReview + outcome.ambiguous,
17652
+ milestonesNeedingReview: milestones.filter((m) => m.needsReview).length
17653
+ },
17654
+ attention: consolidated,
17655
+ milestones,
17656
+ entities
17199
17657
  };
17200
17658
  }
17201
17659
 
@@ -18198,6 +18656,8 @@ export {
18198
18656
  INTEGRATIONS_FILE,
18199
18657
  INTERFACE_TYPES,
18200
18658
  ImportError,
18659
+ InitiativeConflictError,
18660
+ InitiativeNotReadyError,
18201
18661
  InitiativeWriteError,
18202
18662
  IntegrationError,
18203
18663
  IntegrationServiceError,
@@ -18259,10 +18719,12 @@ export {
18259
18719
  collectImplementationEvidence,
18260
18720
  completeDeliveryPlan,
18261
18721
  completeEpic,
18722
+ completeInitiative,
18262
18723
  computeContentHash,
18263
18724
  computeEpicProgress,
18264
18725
  computeInitiativeProgress,
18265
18726
  computePlanProgress,
18727
+ computePlanningInsights,
18266
18728
  computeRefinementStatus,
18267
18729
  conceptBundlePath,
18268
18730
  consentNotice,
@@ -18297,6 +18759,7 @@ export {
18297
18759
  evaluateCompletion,
18298
18760
  evaluateEpicById,
18299
18761
  evaluateEpicCompletion,
18762
+ evaluateInitiativeById,
18300
18763
  evaluateInitiativeCompletion,
18301
18764
  evaluatePlanById,
18302
18765
  evaluatePlanCompletion,
@@ -18340,6 +18803,8 @@ export {
18340
18803
  getWorkItemsSummary,
18341
18804
  importExternalWorkItem,
18342
18805
  importWorkItem,
18806
+ initiativeOutcomeVerification,
18807
+ initiativeProvenanceIssues,
18343
18808
  initiativesInEpic,
18344
18809
  integrationRegistry,
18345
18810
  isActiveState,
@@ -18399,15 +18864,18 @@ export {
18399
18864
  readFile,
18400
18865
  readPocSummary,
18401
18866
  recordEpicOutcomeVerification,
18867
+ recordInitiativeOutcomeVerification,
18402
18868
  recordMilestoneExitVerification,
18403
18869
  recordPlanOutcomeVerification,
18404
18870
  redactSecrets,
18871
+ removeCandidate,
18405
18872
  removeIntegrationSecret,
18406
18873
  removeTarget,
18407
18874
  renderConsolidationMarkdown,
18408
18875
  renderDriftMarkdown,
18409
18876
  renderImpactMarkdown,
18410
18877
  renderSavingsMarkdown,
18878
+ replaceBodySection,
18411
18879
  revisionOf,
18412
18880
  searchSystemNodes,
18413
18881
  serializeConsolidationJson,
@@ -18424,6 +18892,7 @@ export {
18424
18892
  transitionEpic,
18425
18893
  transitionInitiative,
18426
18894
  transitionWorkItem,
18895
+ updateCandidate,
18427
18896
  updateDeliveryPlan,
18428
18897
  updateEpic,
18429
18898
  updateInitiative,