@kaddo/cli 3.135.0 → 3.136.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/dist/admin-dist/assets/{architectureDiagram-3BPJPVTR-DkdJ073y.js → architectureDiagram-3BPJPVTR-LjksP4qj.js} +1 -1
  2. package/dist/admin-dist/assets/{chunk-727SXJPM-DRof4aGT.js → chunk-727SXJPM-B9bbDh_M.js} +1 -1
  3. package/dist/admin-dist/assets/{chunk-AQP2D5EJ-BOVZoYng.js → chunk-AQP2D5EJ-BD776tm_.js} +1 -1
  4. package/dist/admin-dist/assets/{classDiagram-v2-Q7XG4LA2-cL_umCGu.js → classDiagram-4FO5ZUOK-D_59IJDh.js} +1 -1
  5. package/dist/admin-dist/assets/{classDiagram-4FO5ZUOK-cL_umCGu.js → classDiagram-v2-Q7XG4LA2-D_59IJDh.js} +1 -1
  6. package/dist/admin-dist/assets/{dagre-BM42HDAG-Cvga2Wk-.js → dagre-BM42HDAG-Bz-INcCu.js} +1 -1
  7. package/dist/admin-dist/assets/{diagram-2AECGRRQ-C4H51In7.js → diagram-2AECGRRQ-uWqqhcHf.js} +1 -1
  8. package/dist/admin-dist/assets/{diagram-5GNKFQAL-BW2-XCqV.js → diagram-5GNKFQAL-BanaZANB.js} +1 -1
  9. package/dist/admin-dist/assets/{diagram-LMA3HP47-CQnSrSZs.js → diagram-LMA3HP47-DNXl16UE.js} +1 -1
  10. package/dist/admin-dist/assets/{diagram-OG6HWLK6-BA6tBaOl.js → diagram-OG6HWLK6-BPuwqdOA.js} +1 -1
  11. package/dist/admin-dist/assets/{erDiagram-TEJ5UH35-DQK3b1Yu.js → erDiagram-TEJ5UH35-CjHdHiPN.js} +1 -1
  12. package/dist/admin-dist/assets/{flowDiagram-I6XJVG4X-BvtbwW59.js → flowDiagram-I6XJVG4X-8LugweYq.js} +1 -1
  13. package/dist/admin-dist/assets/{ganttDiagram-6RSMTGT7-Vb0T68-1.js → ganttDiagram-6RSMTGT7-T1r39UBo.js} +1 -1
  14. package/dist/admin-dist/assets/{index-F0fBD3Ys.js → index-Cm0J_POl.js} +7 -6
  15. package/dist/admin-dist/assets/{infoDiagram-5YYISTIA-8oD9uPZj.js → infoDiagram-5YYISTIA-Bt5lkett.js} +1 -1
  16. package/dist/admin-dist/assets/{ishikawaDiagram-YF4QCWOH-C32f84vy.js → ishikawaDiagram-YF4QCWOH-BAEvG6rZ.js} +1 -1
  17. package/dist/admin-dist/assets/{kanban-definition-UN3LZRKU-cJc_snn8.js → kanban-definition-UN3LZRKU-BXlgj75s.js} +1 -1
  18. package/dist/admin-dist/assets/{linear-XcP0Xi-K.js → linear-CcJpsi8a.js} +1 -1
  19. package/dist/admin-dist/assets/{mindmap-definition-RKZ34NQL-jhlLOmXd.js → mindmap-definition-RKZ34NQL-BDUe2xi4.js} +1 -1
  20. package/dist/admin-dist/assets/{pieDiagram-4H26LBE5-cEiC5w8m.js → pieDiagram-4H26LBE5-Cw_a1v5z.js} +1 -1
  21. package/dist/admin-dist/assets/{quadrantDiagram-W4KKPZXB-xjpfY5PD.js → quadrantDiagram-W4KKPZXB-CJvWU8a3.js} +1 -1
  22. package/dist/admin-dist/assets/{requirementDiagram-4Y6WPE33-C5KtzYhy.js → requirementDiagram-4Y6WPE33-D-vDruTz.js} +1 -1
  23. package/dist/admin-dist/assets/{sequenceDiagram-3UESZ5HK-ByGOoS_6.js → sequenceDiagram-3UESZ5HK-B4PJZymc.js} +1 -1
  24. package/dist/admin-dist/assets/{stateDiagram-AJRCARHV-d9g3cuV4.js → stateDiagram-AJRCARHV-B8K87k9v.js} +1 -1
  25. package/dist/admin-dist/assets/{stateDiagram-v2-BHNVJYJU-DJ9FtIdZ.js → stateDiagram-v2-BHNVJYJU-C5Q0Gwxn.js} +1 -1
  26. package/dist/admin-dist/assets/{timeline-definition-PNZ67QCA-BB4Lz6CJ.js → timeline-definition-PNZ67QCA-BHQwwDwf.js} +1 -1
  27. package/dist/admin-dist/assets/{vennDiagram-CIIHVFJN-yj1GFfPu.js → vennDiagram-CIIHVFJN-k_l2q31S.js} +1 -1
  28. package/dist/admin-dist/assets/{wardleyDiagram-YWT4CUSO-5nw4MWMx.js → wardleyDiagram-YWT4CUSO-CYNfnm_M.js} +1 -1
  29. package/dist/admin-dist/assets/{xychartDiagram-2RQKCTM6-C0iogx2l.js → xychartDiagram-2RQKCTM6-JF9I5EAO.js} +1 -1
  30. package/dist/admin-dist/index.html +1 -1
  31. package/dist/admin-server/index.js +158 -5
  32. package/dist/core.js +947 -634
  33. package/dist/index.js +673 -460
  34. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -27128,270 +27128,94 @@ import matter29 from "gray-matter";
27128
27128
 
27129
27129
  // src/core/initiative-write.ts
27130
27130
  import matter28 from "gray-matter";
27131
- var WORK_ITEMS_DIR4 = "knowledge/delivery/work-items";
27132
- var DRAFT_DIR2 = `${WORK_ITEMS_DIR4}/draft`;
27133
- var InitiativeWriteError = class extends Error {
27134
- constructor(message) {
27135
- super(message);
27136
- this.name = "InitiativeWriteError";
27131
+
27132
+ // src/core/initiative-analysis.ts
27133
+ var SUCCESS_HEADING_RE = /^#{1,6}\s*(success criteria|criterios de[ét]xito|criterios de éxito)\s*$/i;
27134
+ var HEADING_RE2 = /^#{1,6}\s+/;
27135
+ var CHECK_ITEM_RE = /^\s*[-*]\s+\[([ xX])\]\s+(.*)$/;
27136
+ var BULLET_RE2 = /^\s*[-*]\s+(.*)$/;
27137
+ var PLACEHOLDER_RE = /^_.*_$/;
27138
+ function parseSuccessCriteria(body) {
27139
+ const lines = body.split(/\r?\n/);
27140
+ const out = [];
27141
+ let capture = false;
27142
+ for (const line of lines) {
27143
+ if (capture && HEADING_RE2.test(line)) break;
27144
+ if (!capture) {
27145
+ if (SUCCESS_HEADING_RE.test(line.trim())) capture = true;
27146
+ continue;
27147
+ }
27148
+ const check = line.match(CHECK_ITEM_RE);
27149
+ if (check) {
27150
+ const text2 = check[2].trim();
27151
+ if (text2 && !PLACEHOLDER_RE.test(text2)) {
27152
+ out.push({ text: text2, checked: check[1].toLowerCase() === "x" });
27153
+ }
27154
+ continue;
27155
+ }
27156
+ const bullet = line.match(BULLET_RE2);
27157
+ if (bullet) {
27158
+ const text2 = bullet[1].trim();
27159
+ if (text2 && !PLACEHOLDER_RE.test(text2)) out.push({ text: text2, checked: null });
27160
+ }
27137
27161
  }
27138
- };
27139
- function slugify7(s) {
27140
- return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 50);
27141
- }
27142
- function today2() {
27143
- return (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
27144
- }
27145
- function candidateToData(c) {
27146
- const out = { id: c.id, title: c.title };
27147
- if (c.type) out.type = c.type;
27148
- if (c.suggestedKnowledgeLevel) out.suggested_knowledge_level = c.suggestedKnowledgeLevel;
27149
- if (c.expectedValue) out.expected_value = c.expectedValue;
27150
- if (c.notes) out.notes = c.notes;
27151
- if (c.sourceSignals.length) out.source_signals = c.sourceSignals;
27152
- if (c.dependencies.length) out.dependencies = c.dependencies;
27153
- if (c.materializedAs) out.materialized_as = c.materializedAs;
27154
27162
  return out;
27155
27163
  }
27156
- function externalLinkToData(l) {
27157
- const out = { integration: l.integration, external_id: l.externalId };
27158
- if (l.externalType) out.external_type = l.externalType;
27159
- if (l.url) out.url = l.url;
27160
- if (l.externalStatus) out.external_status = l.externalStatus;
27161
- return out;
27162
- }
27163
- function normalizeCandidate(input, fallbackId) {
27164
- return {
27165
- id: input.id?.trim() || fallbackId,
27166
- title: input.title.trim(),
27167
- type: input.type?.trim() || void 0,
27168
- suggestedKnowledgeLevel: input.suggestedKnowledgeLevel?.trim() || void 0,
27169
- expectedValue: input.expectedValue?.trim() || void 0,
27170
- notes: input.notes?.trim() || void 0,
27171
- sourceSignals: input.sourceSignals ?? [],
27172
- dependencies: input.dependencies ?? [],
27173
- materializedAs: input.materializedAs ?? null
27174
- };
27175
- }
27176
- function defaultBody(title) {
27177
- return [
27178
- `# ${title}`,
27179
- "",
27180
- "## Goal",
27181
- "",
27182
- "_What outcome does this Initiative pursue?_",
27183
- "",
27184
- "## Expected Value",
27185
- "",
27186
- "_Why it matters._",
27187
- "",
27188
- "## Scope",
27189
- "",
27190
- "_What this Initiative covers._",
27191
- "",
27192
- "## Out of Scope",
27193
- "",
27194
- "_What it explicitly does not cover._",
27195
- "",
27196
- "## Success Criteria",
27197
- "",
27198
- '_Observable outcomes that define completion (not just "all Work Items done")._',
27199
- "",
27200
- "## Dependencies",
27201
- "",
27202
- "_Other Initiatives, modules, or external work this depends on._",
27203
- "",
27204
- "## Work Item Candidates",
27205
- "",
27206
- "_Candidates live in frontmatter `candidates`; summarize them here as they evolve._",
27207
- "",
27208
- "## Open Questions",
27209
- "",
27210
- "_Unresolved questions for this Initiative._",
27211
- "",
27212
- "## Learning",
27213
- "",
27214
- "_Captured on completion: what was delivered, what stayed out of scope, outcome reached._",
27215
- ""
27216
- ].join("\n");
27217
- }
27218
- function buildInitiativeContent(id, input) {
27219
- const status = input.status ?? "planned";
27220
- if (!isValidInitiativeStatus(status)) {
27221
- throw new InitiativeWriteError(`Invalid initiative status: ${status}.`);
27222
- }
27223
- const candidates = (input.candidates ?? []).map(
27224
- (c, i) => normalizeCandidate(c, `WI-CANDIDATE-${String(i + 1).padStart(3, "0")}`)
27225
- );
27226
- const data = {
27227
- type: "initiative",
27228
- id,
27229
- title: input.title.trim(),
27230
- status,
27231
- knowledge_level: input.knowledgeLevel ?? "K2",
27232
- domains: input.domains ?? [],
27233
- related_capabilities: input.relatedCapabilities ?? [],
27234
- created_at: today2(),
27235
- external_links: (input.externalLinks ?? []).map(externalLinkToData),
27236
- candidates: candidates.map(candidateToData)
27237
- };
27238
- if (input.horizon) data.horizon = input.horizon;
27239
- if (input.priority) data.priority = input.priority;
27240
- if (input.source) data.source = input.source;
27241
- if (input.sourceId) data.source_id = input.sourceId;
27242
- if (input.epic) data.epic = input.epic.trim();
27243
- if (input.owners?.length) data.owners = input.owners.map((o) => o.trim()).filter(Boolean);
27244
- if (input.contributors?.length) data.contributors = input.contributors.map((c) => c.trim()).filter(Boolean);
27245
- return matter28.stringify("\n" + (input.body ?? defaultBody(input.title.trim())), data);
27246
- }
27247
- function createInitiative(dir, input) {
27248
- if (!input.title?.trim()) throw new InitiativeWriteError("Initiative title is required.");
27249
- const id = nextInitiativeId(dir);
27250
- const fileName = `${id}-${slugify7(input.title)}.md`;
27251
- const iniDir = join(dir, INITIATIVES_DIR);
27252
- ensureDir(iniDir);
27253
- const filePath = join(iniDir, fileName);
27254
- const content = buildInitiativeContent(id, input);
27255
- writeFile(filePath, content);
27256
- const ini = parseInitiative(dir, filePath, content);
27257
- if (!ini) throw new InitiativeWriteError("Failed to parse the Initiative just written.");
27258
- return ini;
27259
- }
27260
- function transitionInitiative(dir, id, to) {
27261
- const ini = getInitiative(dir, id);
27262
- if (!ini) throw new InitiativeWriteError(`Initiative ${id} not found.`);
27263
- if (!isValidInitiativeStatus(to)) throw new InitiativeWriteError(`Invalid status: ${to}.`);
27264
- if (ini.status === to) return ini;
27265
- if (!isValidInitiativeTransition(ini.status, to)) {
27266
- throw new InitiativeWriteError(`Invalid transition ${ini.status} \u2192 ${to}.`);
27164
+ function analyzeInitiative(dir, ini) {
27165
+ const progress = computeInitiativeProgress(dir, ini);
27166
+ const successCriteria = parseSuccessCriteria(ini.body);
27167
+ const pendingCandidates = ini.candidates.filter((c) => !c.materializedAs);
27168
+ const associated = associatedWorkItems(dir, ini.id);
27169
+ const findings = [];
27170
+ if (successCriteria.length === 0) {
27171
+ findings.push({
27172
+ code: "no-success-criteria",
27173
+ severity: "warning",
27174
+ message: "The Initiative has no explicit Success Criteria; completion cannot be judged by outcome, only by delivery."
27175
+ });
27176
+ } else {
27177
+ const uncovered = successCriteria.filter((c) => c.checked === false);
27178
+ if (uncovered.length > 0) {
27179
+ findings.push({
27180
+ code: "uncovered-success-criteria",
27181
+ severity: "blocking",
27182
+ message: `${uncovered.length} success criterion/criteria remain uncovered.`,
27183
+ items: uncovered.map((c) => c.text)
27184
+ });
27185
+ }
27267
27186
  }
27268
- const raw = readFile(ini.filePath);
27269
- const { data, content } = matter28(raw, {});
27270
- data.status = to;
27271
- if (to === "completed") data.completed_at = today2();
27272
- const newContent = matter28.stringify(content, data);
27273
- writeFile(ini.filePath, newContent);
27274
- const updated = parseInitiative(dir, ini.filePath, newContent);
27275
- if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after transition.");
27276
- return updated;
27277
- }
27278
- function updateInitiative(dir, id, patch) {
27279
- const ini = getInitiative(dir, id);
27280
- if (!ini) throw new InitiativeWriteError(`Initiative ${id} not found.`);
27281
- const raw = readFile(ini.filePath);
27282
- const { data, content } = matter28(raw, {});
27283
- if (patch.title !== void 0) {
27284
- if (!patch.title.trim()) throw new InitiativeWriteError("Initiative title cannot be empty.");
27285
- data.title = patch.title.trim();
27187
+ if (pendingCandidates.length > 0) {
27188
+ findings.push({
27189
+ code: "pending-candidates",
27190
+ severity: "blocking",
27191
+ message: `${pendingCandidates.length} committed candidate(s) not yet materialized into Work Items.`,
27192
+ items: pendingCandidates.map((c) => `${c.id}: ${c.title}`)
27193
+ });
27286
27194
  }
27287
- if (patch.horizon !== void 0) data.horizon = patch.horizon;
27288
- if (patch.priority !== void 0) data.priority = patch.priority;
27289
- if (patch.knowledgeLevel !== void 0) data.knowledge_level = patch.knowledgeLevel;
27290
- if (patch.domains !== void 0) data.domains = patch.domains;
27291
- if (patch.relatedCapabilities !== void 0) data.related_capabilities = patch.relatedCapabilities;
27292
- if (patch.epic !== void 0) {
27293
- if (patch.epic === null || patch.epic.trim() === "") delete data.epic;
27294
- else data.epic = patch.epic.trim();
27195
+ const notCompleted = associated.filter((w) => w.status !== "completed" && w.status !== "archived");
27196
+ if (associated.length === 0) {
27197
+ findings.push({
27198
+ code: "no-delivery",
27199
+ severity: "info",
27200
+ message: "No Work Items are associated with this Initiative yet."
27201
+ });
27202
+ } else if (notCompleted.length > 0) {
27203
+ findings.push({
27204
+ code: "incomplete-delivery",
27205
+ severity: "blocking",
27206
+ message: `${notCompleted.length} associated Work Item(s) are not completed.`,
27207
+ items: notCompleted.map((w) => `${w.id} (${w.status})`)
27208
+ });
27295
27209
  }
27296
- if (patch.owners !== void 0) data.owners = patch.owners.map((o) => o.trim()).filter(Boolean);
27297
- if (patch.contributors !== void 0) data.contributors = patch.contributors.map((c) => c.trim()).filter(Boolean);
27298
- const newContent = matter28.stringify(content, data);
27299
- writeFile(ini.filePath, newContent);
27300
- const updated = parseInitiative(dir, ini.filePath, newContent);
27301
- if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after update.");
27302
- return updated;
27303
- }
27304
- function nextWorkItemId3(dir) {
27305
- const wiDir = join(dir, WORK_ITEMS_DIR4);
27306
- let max = 0;
27307
- const walk2 = (d) => {
27308
- if (!exists(d)) return;
27309
- for (const entry of readDir(d)) {
27310
- const full = join(d, entry);
27311
- if (isFile(full)) {
27312
- const m = entry.match(/WI-(\d+)/);
27313
- if (m) max = Math.max(max, parseInt(m[1], 10));
27314
- } else if (!entry.startsWith(".")) {
27315
- walk2(full);
27316
- }
27317
- }
27318
- };
27319
- walk2(wiDir);
27320
- return `WI-${String(max + 1).padStart(3, "0")}`;
27321
- }
27322
- function buildWorkItemContent(wiId, iniId, candidate) {
27323
- const data = {
27324
- type: candidate.type ?? "feature",
27325
- id: wiId,
27326
- title: candidate.title,
27327
- knowledge_level: candidate.suggestedKnowledgeLevel ?? "K2",
27328
- status: "draft",
27329
- phase: "now",
27330
- initiative: iniId,
27331
- domains: [],
27332
- code: [],
27333
- created_at: today2(),
27334
- source: "initiative",
27335
- source_id: candidate.id,
27336
- source_initiative: iniId,
27337
- affected_modules: []
27210
+ return {
27211
+ initiative: ini.id,
27212
+ status: ini.status,
27213
+ progress,
27214
+ successCriteria,
27215
+ pendingCandidates,
27216
+ findings,
27217
+ suggestedCandidates: pendingCandidates
27338
27218
  };
27339
- if (candidate.sourceSignals.length) data.source_signals = candidate.sourceSignals;
27340
- if (candidate.dependencies.length) data.dependencies = candidate.dependencies;
27341
- const body = [
27342
- `# ${candidate.title}`,
27343
- "",
27344
- `> Materialized from Initiative ${iniId}, candidate ${candidate.id}.`,
27345
- "",
27346
- "## Problem",
27347
- "",
27348
- candidate.expectedValue ? `_Expected value:_ ${candidate.expectedValue}` : "_Describe the problem._",
27349
- "",
27350
- "## Acceptance Criteria",
27351
- "",
27352
- "- [ ] _Define at least one testable criterion._",
27353
- "",
27354
- "## Out of scope",
27355
- "",
27356
- "_Not included in this Work Item._",
27357
- "",
27358
- "## Validation",
27359
- "",
27360
- "_How will this be validated?_",
27361
- "",
27362
- "## Learning",
27363
- "",
27364
- "_What did we learn? Update after completion._",
27365
- ""
27366
- ].join("\n");
27367
- return matter28.stringify("\n" + body, data);
27368
- }
27369
- function materializeCandidate(dir, id, candidateId) {
27370
- const ini = getInitiative(dir, id);
27371
- if (!ini) throw new InitiativeWriteError(`Initiative ${id} not found.`);
27372
- const candidate = ini.candidates.find((c) => c.id === candidateId);
27373
- if (!candidate) throw new InitiativeWriteError(`Candidate ${candidateId} not found in ${id}.`);
27374
- if (candidate.materializedAs) {
27375
- throw new InitiativeWriteError(
27376
- `Candidate ${candidateId} is already materialized as ${candidate.materializedAs}.`
27377
- );
27378
- }
27379
- const wiId = nextWorkItemId3(dir);
27380
- const fileName = `${wiId}-${slugify7(candidate.title)}.md`;
27381
- ensureDir(join(dir, DRAFT_DIR2));
27382
- writeFile(join(dir, DRAFT_DIR2, fileName), buildWorkItemContent(wiId, ini.id, candidate));
27383
- const raw = readFile(ini.filePath);
27384
- const { data, content } = matter28(raw, {});
27385
- const cands = Array.isArray(data.candidates) ? data.candidates : [];
27386
- for (const c of cands) {
27387
- if (c && typeof c === "object" && String(c.id) === candidateId) c.materialized_as = wiId;
27388
- }
27389
- data.candidates = cands;
27390
- const newContent = matter28.stringify(content, data);
27391
- writeFile(ini.filePath, newContent);
27392
- const updated = parseInitiative(dir, ini.filePath, newContent);
27393
- if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after materialization.");
27394
- return { workItemId: wiId, fileName, initiative: updated };
27395
27219
  }
27396
27220
 
27397
27221
  // src/core/delivery-verification.ts
@@ -27515,123 +27339,613 @@ function decide(blockers, softBlocks, hasAcceptedExceptions) {
27515
27339
  if (softBlocks.length > 0) return "NEEDS_WORK";
27516
27340
  return hasAcceptedExceptions ? "READY_WITH_EXCEPTIONS" : "READY_TO_COMPLETE";
27517
27341
  }
27518
- function evaluateEpicCompletion(dir, epic) {
27519
- const prog = computeEpicProgress(dir, epic);
27520
- const exceptions = parseExceptions2(fm2(epic, "completion_exceptions"));
27521
- const outcome = epicOutcomeVerification(epic);
27342
+ function evaluateEpicCompletion(dir, epic) {
27343
+ const prog = computeEpicProgress(dir, epic);
27344
+ const exceptions = parseExceptions2(fm2(epic, "completion_exceptions"));
27345
+ const outcome = epicOutcomeVerification(epic);
27346
+ const blockers = [];
27347
+ const softBlocks = [];
27348
+ const reasons = [];
27349
+ const warnings = [];
27350
+ for (const d of prog.readiness.blockingDependencies) blockers.push(`Blocked by unfinished dependency ${d}.`);
27351
+ for (const f of integrityBlockers(dir, epic.id)) blockers.push(f);
27352
+ evaluateOutcomeInto(epic.outcome, true, outcome, blockers, softBlocks, reasons, warnings);
27353
+ if (prog.delivery.total > 0 && prog.delivery.completed < prog.delivery.total) {
27354
+ softBlocks.push("committed-work-incomplete");
27355
+ reasons.push(`Committed work is incomplete (${prog.delivery.completed}/${prog.delivery.total} Work Items completed).`);
27356
+ }
27357
+ const readiness = decide(blockers, softBlocks, exceptions.some((x) => x.status === "accepted"));
27358
+ pushReadinessReason(readiness, reasons);
27359
+ return {
27360
+ id: epic.id,
27361
+ kind: "epic",
27362
+ status: epic.status,
27363
+ readiness,
27364
+ reasons,
27365
+ blockers,
27366
+ warnings,
27367
+ outcome,
27368
+ delivery: { total: prog.delivery.total, completed: prog.delivery.completed, blocked: prog.delivery.blocked },
27369
+ blockingDependencies: prog.readiness.blockingDependencies,
27370
+ exceptions
27371
+ };
27372
+ }
27373
+ function evaluatePlanCompletion(dir, plan) {
27374
+ const prog = computePlanProgress(dir, plan);
27375
+ const exceptions = parseExceptions2(fm2(plan, "completion_exceptions"));
27376
+ const outcome = planOutcomeVerification(plan);
27377
+ const milestones = planMilestoneVerifications(plan);
27378
+ const epics = epicsInPlan(dir, plan.id).map((e) => ({ id: e.id, status: e.status }));
27379
+ const blockers = [];
27380
+ const softBlocks = [];
27381
+ const reasons = [];
27382
+ const warnings = [];
27383
+ for (const d of prog.readiness.blockingDependencies) blockers.push(`Blocked by unfinished dependency ${d}.`);
27384
+ for (const f of integrityBlockers(dir, plan.id)) blockers.push(f);
27385
+ evaluateOutcomeInto(plan.objective, false, outcome, blockers, softBlocks, reasons, warnings);
27386
+ if (!plan.objective) warnings.push("No objective is declared for this Plan (optional, but recommended for completion review).");
27387
+ if (prog.delivery.total > 0 && prog.delivery.completed < prog.delivery.total) {
27388
+ softBlocks.push("committed-work-incomplete");
27389
+ reasons.push(`Committed work is incomplete (${prog.delivery.completed}/${prog.delivery.total} Work Items completed).`);
27390
+ }
27391
+ if (epics.length === 0 && prog.delivery.total === 0) {
27392
+ softBlocks.push("no-committed-work");
27393
+ reasons.push("No Epics and no committed Work Items \u2014 the Plan has no verifiable deliverables yet.");
27394
+ }
27395
+ const openEpics = epics.filter((e) => e.status !== "completed" && e.status !== "cancelled");
27396
+ if (openEpics.length > 0) {
27397
+ softBlocks.push("epics-open");
27398
+ reasons.push(`${openEpics.length} Epic(s) not yet completed: ${openEpics.map((e) => e.id).join(", ")}.`);
27399
+ }
27400
+ for (const m of milestones) {
27401
+ if (m.outcome.failed > 0) {
27402
+ blockers.push(`Milestone ${m.id} has a failed exit criterion.`);
27403
+ }
27404
+ const pending = m.outcome.notVerified + m.outcome.manualReview;
27405
+ if (pending > 0) {
27406
+ softBlocks.push(`milestone-${m.id}-pending`);
27407
+ reasons.push(`Milestone ${m.id}: ${pending} exit criterion(s) not verified.`);
27408
+ }
27409
+ if (m.outcome.stale.length > 0) warnings.push(`Milestone ${m.id} has stale exit-criteria evidence.`);
27410
+ }
27411
+ const readiness = decide(blockers, softBlocks, exceptions.some((x) => x.status === "accepted"));
27412
+ pushReadinessReason(readiness, reasons);
27413
+ return {
27414
+ id: plan.id,
27415
+ kind: "plan",
27416
+ status: plan.status,
27417
+ readiness,
27418
+ reasons,
27419
+ blockers,
27420
+ warnings,
27421
+ outcome,
27422
+ delivery: { total: prog.delivery.total, completed: prog.delivery.completed, blocked: prog.delivery.blocked },
27423
+ blockingDependencies: prog.readiness.blockingDependencies,
27424
+ milestones,
27425
+ epics,
27426
+ exceptions
27427
+ };
27428
+ }
27429
+ function integrityBlockers(dir, subjectId) {
27430
+ return validatePlanningGraph(dir).filter((f) => f.level === "error" && f.subject.toLowerCase() === subjectId.toLowerCase()).map((f) => f.message);
27431
+ }
27432
+ function evaluateOutcomeInto(declaredOutcome, requireDeclaredOutcome, outcome, blockers, softBlocks, reasons, warnings) {
27433
+ if (requireDeclaredOutcome && !declaredOutcome) {
27434
+ softBlocks.push("no-outcome");
27435
+ reasons.push("No expected outcome is declared.");
27436
+ }
27437
+ if (outcome.total === 0) {
27438
+ softBlocks.push("no-success-criteria");
27439
+ reasons.push("No success criteria to verify \u2014 completion cannot be judged by outcome.");
27440
+ }
27441
+ if (outcome.ambiguous > 0) {
27442
+ softBlocks.push("criteria-ambiguous");
27443
+ reasons.push(`${outcome.ambiguous} success criterion(s) collide in text \u2014 rename to disambiguate before verifying.`);
27444
+ }
27445
+ if (outcome.failed > 0) {
27446
+ softBlocks.push("criteria-failed");
27447
+ reasons.push(`${outcome.failed} success criterion(s) failed verification.`);
27448
+ }
27449
+ const pending = outcome.notVerified + outcome.manualReview - outcome.ambiguous;
27450
+ if (pending > 0) {
27451
+ softBlocks.push("criteria-unverified");
27452
+ reasons.push(`${pending} success criterion(s) not verified (no or insufficient evidence).`);
27453
+ }
27454
+ if (outcome.stale.length > 0) warnings.push(`${outcome.stale.length} evidence record(s) no longer match a declared criterion (stale).`);
27455
+ }
27456
+ function pushReadinessReason(readiness, reasons) {
27457
+ if (readiness === "READY_TO_COMPLETE") reasons.unshift("All success criteria are verified and committed work is complete. Human approval is still required to close.");
27458
+ else if (readiness === "READY_WITH_EXCEPTIONS") reasons.unshift("Remaining gaps are covered by accepted exceptions. Human approval is still required to close.");
27459
+ }
27460
+
27461
+ // src/core/initiative-verification.ts
27462
+ function optStr6(v) {
27463
+ return typeof v === "string" && v.trim() ? v.trim() : void 0;
27464
+ }
27465
+ function parseCompletionExceptions(raw) {
27466
+ if (!Array.isArray(raw)) return [];
27467
+ const out = [];
27468
+ for (const entry of raw) {
27469
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
27470
+ const o = entry;
27471
+ const id = optStr6(o.id);
27472
+ if (!id) continue;
27473
+ const st = optStr6(o.status);
27474
+ out.push({
27475
+ id,
27476
+ status: st === "accepted" || st === "rejected" ? st : "proposed",
27477
+ ...optStr6(o.criterion) ? { criterion: optStr6(o.criterion) } : {},
27478
+ ...optStr6(o.reason) ? { reason: optStr6(o.reason) } : {}
27479
+ });
27480
+ }
27481
+ return out;
27482
+ }
27483
+ function initiativeOutcomeVerification(ini) {
27484
+ const declared = parseSuccessCriteria(ini.body).map((c) => c.text);
27485
+ const evidence = parseEvidenceList(ini.rawFrontmatter?.outcome_verifications);
27486
+ const exceptions = parseCompletionExceptions(ini.rawFrontmatter?.completion_exceptions);
27487
+ return buildOutcomeVerification(declared, evidence, exceptions);
27488
+ }
27489
+ function initiativeProvenanceIssues(dir, ini) {
27490
+ const issues = [];
27491
+ const wis = discoverWorkItems(dir);
27492
+ for (const c of ini.candidates) {
27493
+ if (!c.materializedAs) continue;
27494
+ const wi = wis.find((w) => w.id.toLowerCase() === c.materializedAs.toLowerCase());
27495
+ if (!wi) {
27496
+ issues.push(`Candidate ${c.id} points at missing Work Item ${c.materializedAs}.`);
27497
+ continue;
27498
+ }
27499
+ const owner = typeof wi.rawFrontmatter?.initiative === "string" ? wi.rawFrontmatter.initiative : void 0;
27500
+ if (owner && owner.toLowerCase() !== ini.id.toLowerCase()) {
27501
+ issues.push(`Work Item ${wi.id} (materialized from ${c.id}) is associated with ${owner}, not ${ini.id}.`);
27502
+ }
27503
+ }
27504
+ return issues;
27505
+ }
27506
+ function decide2(blockers, softBlocks, hasAcceptedExceptions) {
27507
+ if (blockers.length > 0) return "BLOCKED";
27508
+ if (softBlocks.length > 0) return "NEEDS_WORK";
27509
+ return hasAcceptedExceptions ? "READY_WITH_EXCEPTIONS" : "READY_TO_COMPLETE";
27510
+ }
27511
+ function evaluateInitiativeCompletion(dir, ini) {
27512
+ const progress = computeInitiativeProgress(dir, ini);
27513
+ const outcome = initiativeOutcomeVerification(ini);
27514
+ const exceptions = parseCompletionExceptions(ini.rawFrontmatter?.completion_exceptions);
27515
+ const pending = ini.candidates.filter((c) => !c.materializedAs);
27516
+ const associated = associatedWorkItems(dir, ini.id);
27517
+ const incomplete = associated.filter((w) => w.status !== "completed" && w.status !== "archived");
27518
+ const provenanceIssues = initiativeProvenanceIssues(dir, ini);
27522
27519
  const blockers = [];
27523
27520
  const softBlocks = [];
27524
27521
  const reasons = [];
27525
27522
  const warnings = [];
27526
- for (const d of prog.readiness.blockingDependencies) blockers.push(`Blocked by unfinished dependency ${d}.`);
27527
- for (const f of integrityBlockers(dir, epic.id)) blockers.push(f);
27528
- evaluateOutcomeInto(epic.outcome, true, outcome, blockers, softBlocks, reasons, warnings);
27529
- if (prog.delivery.total > 0 && prog.delivery.completed < prog.delivery.total) {
27530
- softBlocks.push("committed-work-incomplete");
27531
- reasons.push(`Committed work is incomplete (${prog.delivery.completed}/${prog.delivery.total} Work Items completed).`);
27523
+ for (const p of provenanceIssues) blockers.push(p);
27524
+ if (outcome.total === 0) {
27525
+ softBlocks.push("no-success-criteria");
27526
+ reasons.push("No success criteria to verify \u2014 completion cannot be judged by outcome.");
27532
27527
  }
27533
- const readiness = decide(blockers, softBlocks, exceptions.some((x) => x.status === "accepted"));
27534
- pushReadinessReason(readiness, reasons);
27528
+ if (outcome.ambiguous > 0) {
27529
+ softBlocks.push("criteria-ambiguous");
27530
+ reasons.push(`${outcome.ambiguous} success criterion(s) collide in text \u2014 disambiguate before verifying.`);
27531
+ }
27532
+ if (outcome.failed > 0) {
27533
+ softBlocks.push("criteria-failed");
27534
+ reasons.push(`${outcome.failed} success criterion(s) failed verification.`);
27535
+ }
27536
+ const unverified = outcome.notVerified + outcome.manualReview - outcome.ambiguous;
27537
+ if (unverified > 0) {
27538
+ softBlocks.push("criteria-unverified");
27539
+ reasons.push(`${unverified} success criterion(s) not verified (no or insufficient evidence).`);
27540
+ }
27541
+ if (outcome.stale.length > 0) warnings.push(`${outcome.stale.length} evidence record(s) no longer match a declared criterion (stale).`);
27542
+ if (pending.length > 0) {
27543
+ softBlocks.push("pending-candidates");
27544
+ reasons.push(`${pending.length} committed candidate(s) not yet materialized.`);
27545
+ }
27546
+ if (incomplete.length > 0) {
27547
+ softBlocks.push("incomplete-delivery");
27548
+ reasons.push(`${incomplete.length} associated Work Item(s) are not completed.`);
27549
+ }
27550
+ if (associated.length === 0 && pending.length === 0) {
27551
+ softBlocks.push("no-deliverables");
27552
+ reasons.push("Nothing has been delivered or committed under this Initiative.");
27553
+ }
27554
+ const readiness = decide2(blockers, softBlocks, exceptions.some((x) => x.status === "accepted"));
27555
+ if (readiness === "READY_TO_COMPLETE") reasons.unshift("All success criteria are verified and committed scope is delivered. Human approval is still required to close.");
27556
+ else if (readiness === "READY_WITH_EXCEPTIONS") reasons.unshift("Remaining gaps are covered by accepted exceptions. Human approval is still required to close.");
27557
+ const completed = progress.delivery.byState?.completed ?? 0;
27535
27558
  return {
27536
- id: epic.id,
27537
- kind: "epic",
27538
- status: epic.status,
27559
+ id: ini.id,
27560
+ kind: "initiative",
27561
+ status: ini.status,
27539
27562
  readiness,
27563
+ ready: readiness === "READY_TO_COMPLETE" || readiness === "READY_WITH_EXCEPTIONS",
27540
27564
  reasons,
27541
27565
  blockers,
27542
27566
  warnings,
27543
27567
  outcome,
27544
- delivery: { total: prog.delivery.total, completed: prog.delivery.completed, blocked: prog.delivery.blocked },
27545
- blockingDependencies: prog.readiness.blockingDependencies,
27568
+ delivery: { total: progress.delivery.total, completed, incomplete: incomplete.length },
27569
+ pendingCandidates: pending.map((c) => c.id),
27570
+ provenanceIssues,
27546
27571
  exceptions
27547
27572
  };
27548
27573
  }
27549
- function evaluatePlanCompletion(dir, plan) {
27550
- const prog = computePlanProgress(dir, plan);
27551
- const exceptions = parseExceptions2(fm2(plan, "completion_exceptions"));
27552
- const outcome = planOutcomeVerification(plan);
27553
- const milestones = planMilestoneVerifications(plan);
27554
- const epics = epicsInPlan(dir, plan.id).map((e) => ({ id: e.id, status: e.status }));
27555
- const blockers = [];
27556
- const softBlocks = [];
27557
- const reasons = [];
27558
- const warnings = [];
27559
- for (const d of prog.readiness.blockingDependencies) blockers.push(`Blocked by unfinished dependency ${d}.`);
27560
- for (const f of integrityBlockers(dir, plan.id)) blockers.push(f);
27561
- evaluateOutcomeInto(plan.objective, false, outcome, blockers, softBlocks, reasons, warnings);
27562
- if (!plan.objective) warnings.push("No objective is declared for this Plan (optional, but recommended for completion review).");
27563
- if (prog.delivery.total > 0 && prog.delivery.completed < prog.delivery.total) {
27564
- softBlocks.push("committed-work-incomplete");
27565
- reasons.push(`Committed work is incomplete (${prog.delivery.completed}/${prog.delivery.total} Work Items completed).`);
27574
+
27575
+ // src/core/initiative-write.ts
27576
+ var WORK_ITEMS_DIR4 = "knowledge/delivery/work-items";
27577
+ var DRAFT_DIR2 = `${WORK_ITEMS_DIR4}/draft`;
27578
+ function assertFreshInitiative(id, currentContent, opts) {
27579
+ if (!opts?.expectedRevision) return;
27580
+ const actual = revisionOf(currentContent);
27581
+ if (actual !== opts.expectedRevision) throw new InitiativeConflictError(id, opts.expectedRevision, actual);
27582
+ }
27583
+ var InitiativeWriteError = class extends Error {
27584
+ constructor(message) {
27585
+ super(message);
27586
+ this.name = "InitiativeWriteError";
27566
27587
  }
27567
- if (epics.length === 0 && prog.delivery.total === 0) {
27568
- softBlocks.push("no-committed-work");
27569
- reasons.push("No Epics and no committed Work Items \u2014 the Plan has no verifiable deliverables yet.");
27588
+ };
27589
+ var InitiativeConflictError = class extends InitiativeWriteError {
27590
+ constructor(id, expectedRevision, actualRevision) {
27591
+ super(`Initiative "${id}" was modified since it was loaded (expected revision ${expectedRevision}, found ${actualRevision}). Reload and try again.`);
27592
+ this.id = id;
27593
+ this.expectedRevision = expectedRevision;
27594
+ this.actualRevision = actualRevision;
27595
+ this.name = "InitiativeConflictError";
27570
27596
  }
27571
- const openEpics = epics.filter((e) => e.status !== "completed" && e.status !== "cancelled");
27572
- if (openEpics.length > 0) {
27573
- softBlocks.push("epics-open");
27574
- reasons.push(`${openEpics.length} Epic(s) not yet completed: ${openEpics.map((e) => e.id).join(", ")}.`);
27597
+ id;
27598
+ expectedRevision;
27599
+ actualRevision;
27600
+ };
27601
+ function slugify7(s) {
27602
+ return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 50);
27603
+ }
27604
+ function today2() {
27605
+ return (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
27606
+ }
27607
+ function candidateToData(c) {
27608
+ const out = { id: c.id, title: c.title };
27609
+ if (c.type) out.type = c.type;
27610
+ if (c.suggestedKnowledgeLevel) out.suggested_knowledge_level = c.suggestedKnowledgeLevel;
27611
+ if (c.expectedValue) out.expected_value = c.expectedValue;
27612
+ if (c.notes) out.notes = c.notes;
27613
+ if (c.sourceSignals.length) out.source_signals = c.sourceSignals;
27614
+ if (c.dependencies.length) out.dependencies = c.dependencies;
27615
+ if (c.materializedAs) out.materialized_as = c.materializedAs;
27616
+ return out;
27617
+ }
27618
+ function externalLinkToData(l) {
27619
+ const out = { integration: l.integration, external_id: l.externalId };
27620
+ if (l.externalType) out.external_type = l.externalType;
27621
+ if (l.url) out.url = l.url;
27622
+ if (l.externalStatus) out.external_status = l.externalStatus;
27623
+ return out;
27624
+ }
27625
+ function normalizeCandidate(input, fallbackId) {
27626
+ return {
27627
+ id: input.id?.trim() || fallbackId,
27628
+ title: input.title.trim(),
27629
+ type: input.type?.trim() || void 0,
27630
+ suggestedKnowledgeLevel: input.suggestedKnowledgeLevel?.trim() || void 0,
27631
+ expectedValue: input.expectedValue?.trim() || void 0,
27632
+ notes: input.notes?.trim() || void 0,
27633
+ sourceSignals: input.sourceSignals ?? [],
27634
+ dependencies: input.dependencies ?? [],
27635
+ materializedAs: input.materializedAs ?? null
27636
+ };
27637
+ }
27638
+ function defaultBody(title) {
27639
+ return [
27640
+ `# ${title}`,
27641
+ "",
27642
+ "## Goal",
27643
+ "",
27644
+ "_What outcome does this Initiative pursue?_",
27645
+ "",
27646
+ "## Expected Value",
27647
+ "",
27648
+ "_Why it matters._",
27649
+ "",
27650
+ "## Scope",
27651
+ "",
27652
+ "_What this Initiative covers._",
27653
+ "",
27654
+ "## Out of Scope",
27655
+ "",
27656
+ "_What it explicitly does not cover._",
27657
+ "",
27658
+ "## Success Criteria",
27659
+ "",
27660
+ '_Observable outcomes that define completion (not just "all Work Items done")._',
27661
+ "",
27662
+ "## Dependencies",
27663
+ "",
27664
+ "_Other Initiatives, modules, or external work this depends on._",
27665
+ "",
27666
+ "## Work Item Candidates",
27667
+ "",
27668
+ "_Candidates live in frontmatter `candidates`; summarize them here as they evolve._",
27669
+ "",
27670
+ "## Open Questions",
27671
+ "",
27672
+ "_Unresolved questions for this Initiative._",
27673
+ "",
27674
+ "## Learning",
27675
+ "",
27676
+ "_Captured on completion: what was delivered, what stayed out of scope, outcome reached._",
27677
+ ""
27678
+ ].join("\n");
27679
+ }
27680
+ function buildInitiativeContent(id, input) {
27681
+ const status = input.status ?? "planned";
27682
+ if (!isValidInitiativeStatus(status)) {
27683
+ throw new InitiativeWriteError(`Invalid initiative status: ${status}.`);
27684
+ }
27685
+ const candidates = (input.candidates ?? []).map(
27686
+ (c, i) => normalizeCandidate(c, `WI-CANDIDATE-${String(i + 1).padStart(3, "0")}`)
27687
+ );
27688
+ const data = {
27689
+ type: "initiative",
27690
+ id,
27691
+ title: input.title.trim(),
27692
+ status,
27693
+ knowledge_level: input.knowledgeLevel ?? "K2",
27694
+ domains: input.domains ?? [],
27695
+ related_capabilities: input.relatedCapabilities ?? [],
27696
+ created_at: today2(),
27697
+ external_links: (input.externalLinks ?? []).map(externalLinkToData),
27698
+ candidates: candidates.map(candidateToData)
27699
+ };
27700
+ if (input.horizon) data.horizon = input.horizon;
27701
+ if (input.priority) data.priority = input.priority;
27702
+ if (input.source) data.source = input.source;
27703
+ if (input.sourceId) data.source_id = input.sourceId;
27704
+ if (input.epic) data.epic = input.epic.trim();
27705
+ if (input.owners?.length) data.owners = input.owners.map((o) => o.trim()).filter(Boolean);
27706
+ if (input.contributors?.length) data.contributors = input.contributors.map((c) => c.trim()).filter(Boolean);
27707
+ return matter28.stringify("\n" + (input.body ?? defaultBody(input.title.trim())), data);
27708
+ }
27709
+ function createInitiative(dir, input) {
27710
+ if (!input.title?.trim()) throw new InitiativeWriteError("Initiative title is required.");
27711
+ const id = nextInitiativeId(dir);
27712
+ const fileName = `${id}-${slugify7(input.title)}.md`;
27713
+ const iniDir = join(dir, INITIATIVES_DIR);
27714
+ ensureDir(iniDir);
27715
+ const filePath = join(iniDir, fileName);
27716
+ const content = buildInitiativeContent(id, input);
27717
+ writeFile(filePath, content);
27718
+ const ini = parseInitiative(dir, filePath, content);
27719
+ if (!ini) throw new InitiativeWriteError("Failed to parse the Initiative just written.");
27720
+ return ini;
27721
+ }
27722
+ function transitionInitiative(dir, id, to, opts) {
27723
+ const ini = getInitiative(dir, id);
27724
+ if (!ini) throw new InitiativeWriteError(`Initiative ${id} not found.`);
27725
+ if (!isValidInitiativeStatus(to)) throw new InitiativeWriteError(`Invalid status: ${to}.`);
27726
+ if (to === "completed") throw new InitiativeWriteError(`Completing Initiative ${id} requires evidence-based review \u2014 use completeInitiative.`);
27727
+ if (ini.status === to) return ini;
27728
+ if (!isValidInitiativeTransition(ini.status, to)) {
27729
+ throw new InitiativeWriteError(`Invalid transition ${ini.status} \u2192 ${to}.`);
27730
+ }
27731
+ const raw = readFile(ini.filePath);
27732
+ assertFreshInitiative(ini.id, raw, opts);
27733
+ const { data, content } = matter28(raw, {});
27734
+ data.status = to;
27735
+ const newContent = matter28.stringify(content, data);
27736
+ writeFile(ini.filePath, newContent);
27737
+ const updated = parseInitiative(dir, ini.filePath, newContent);
27738
+ if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after transition.");
27739
+ return updated;
27740
+ }
27741
+ function findMaterializedWorkItem(dir, initiativeId, candidateId) {
27742
+ for (const wi of discoverWorkItems(dir)) {
27743
+ const fm3 = wi.rawFrontmatter ?? {};
27744
+ const si = typeof fm3.source_initiative === "string" ? fm3.source_initiative : void 0;
27745
+ const sid = typeof fm3.source_id === "string" ? fm3.source_id : void 0;
27746
+ if (si?.toLowerCase() === initiativeId.toLowerCase() && sid === candidateId) {
27747
+ return { id: wi.id, initiative: typeof fm3.initiative === "string" ? fm3.initiative : void 0 };
27748
+ }
27749
+ }
27750
+ return null;
27751
+ }
27752
+ function replaceBodySection(body, heading, newContent) {
27753
+ const lines = body.split(/\r?\n/);
27754
+ const want = heading.trim().toLowerCase();
27755
+ let start = -1;
27756
+ let level = 0;
27757
+ for (let i = 0; i < lines.length; i++) {
27758
+ const h = lines[i].match(/^(#{1,6})\s+(.*)$/);
27759
+ if (h && h[2].trim().toLowerCase() === want) {
27760
+ start = i;
27761
+ level = h[1].length;
27762
+ break;
27763
+ }
27764
+ }
27765
+ const block = `${"#".repeat(level || 2)} ${heading.trim()}
27766
+
27767
+ ${newContent.trim()}
27768
+ `;
27769
+ if (start === -1) {
27770
+ return `${body.trimEnd()}
27771
+
27772
+ ${block}`;
27773
+ }
27774
+ let end = lines.length;
27775
+ for (let i = start + 1; i < lines.length; i++) {
27776
+ const h = lines[i].match(/^(#{1,6})\s+/);
27777
+ if (h && h[1].length <= level) {
27778
+ end = i;
27779
+ break;
27780
+ }
27781
+ }
27782
+ const before = lines.slice(0, start).join("\n").replace(/\s+$/, "");
27783
+ const after = lines.slice(end).join("\n").replace(/^\s+/, "");
27784
+ return [before, before ? "" : null, block.trimEnd(), after ? "" : null, after].filter((x) => x !== null).join("\n").replace(/\n{3,}/g, "\n\n");
27785
+ }
27786
+ function updateInitiative(dir, id, patch, opts) {
27787
+ const ini = getInitiative(dir, id);
27788
+ if (!ini) throw new InitiativeWriteError(`Initiative ${id} not found.`);
27789
+ const raw = readFile(ini.filePath);
27790
+ assertFreshInitiative(ini.id, raw, opts);
27791
+ let { data, content } = matter28(raw, {});
27792
+ if (patch.title !== void 0) {
27793
+ if (!patch.title.trim()) throw new InitiativeWriteError("Initiative title cannot be empty.");
27794
+ data.title = patch.title.trim();
27795
+ }
27796
+ if (patch.horizon !== void 0) data.horizon = patch.horizon;
27797
+ if (patch.priority !== void 0) data.priority = patch.priority;
27798
+ if (patch.knowledgeLevel !== void 0) data.knowledge_level = patch.knowledgeLevel;
27799
+ if (patch.domains !== void 0) data.domains = patch.domains;
27800
+ if (patch.relatedCapabilities !== void 0) data.related_capabilities = patch.relatedCapabilities;
27801
+ if (patch.epic !== void 0) {
27802
+ if (patch.epic === null || patch.epic.trim() === "") delete data.epic;
27803
+ else data.epic = patch.epic.trim();
27804
+ }
27805
+ if (patch.owners !== void 0) data.owners = patch.owners.map((o) => o.trim()).filter(Boolean);
27806
+ if (patch.contributors !== void 0) data.contributors = patch.contributors.map((c) => c.trim()).filter(Boolean);
27807
+ if (patch.sections) {
27808
+ for (const [heading, value] of Object.entries(patch.sections)) content = replaceBodySection(content, heading, value);
27575
27809
  }
27576
- for (const m of milestones) {
27577
- if (m.outcome.failed > 0) {
27578
- blockers.push(`Milestone ${m.id} has a failed exit criterion.`);
27579
- }
27580
- const pending = m.outcome.notVerified + m.outcome.manualReview;
27581
- if (pending > 0) {
27582
- softBlocks.push(`milestone-${m.id}-pending`);
27583
- reasons.push(`Milestone ${m.id}: ${pending} exit criterion(s) not verified.`);
27810
+ const newContent = matter28.stringify(content, data);
27811
+ writeFile(ini.filePath, newContent);
27812
+ const updated = parseInitiative(dir, ini.filePath, newContent);
27813
+ if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after update.");
27814
+ return updated;
27815
+ }
27816
+ function nextWorkItemId3(dir) {
27817
+ const wiDir = join(dir, WORK_ITEMS_DIR4);
27818
+ let max = 0;
27819
+ const walk2 = (d) => {
27820
+ if (!exists(d)) return;
27821
+ for (const entry of readDir(d)) {
27822
+ const full = join(d, entry);
27823
+ if (isFile(full)) {
27824
+ const m = entry.match(/WI-(\d+)/);
27825
+ if (m) max = Math.max(max, parseInt(m[1], 10));
27826
+ } else if (!entry.startsWith(".")) {
27827
+ walk2(full);
27828
+ }
27584
27829
  }
27585
- if (m.outcome.stale.length > 0) warnings.push(`Milestone ${m.id} has stale exit-criteria evidence.`);
27586
- }
27587
- const readiness = decide(blockers, softBlocks, exceptions.some((x) => x.status === "accepted"));
27588
- pushReadinessReason(readiness, reasons);
27589
- return {
27590
- id: plan.id,
27591
- kind: "plan",
27592
- status: plan.status,
27593
- readiness,
27594
- reasons,
27595
- blockers,
27596
- warnings,
27597
- outcome,
27598
- delivery: { total: prog.delivery.total, completed: prog.delivery.completed, blocked: prog.delivery.blocked },
27599
- blockingDependencies: prog.readiness.blockingDependencies,
27600
- milestones,
27601
- epics,
27602
- exceptions
27603
27830
  };
27831
+ walk2(wiDir);
27832
+ return `WI-${String(max + 1).padStart(3, "0")}`;
27604
27833
  }
27605
- function integrityBlockers(dir, subjectId) {
27606
- return validatePlanningGraph(dir).filter((f) => f.level === "error" && f.subject.toLowerCase() === subjectId.toLowerCase()).map((f) => f.message);
27834
+ function buildWorkItemContent(wiId, iniId, candidate) {
27835
+ const data = {
27836
+ type: candidate.type ?? "feature",
27837
+ id: wiId,
27838
+ title: candidate.title,
27839
+ knowledge_level: candidate.suggestedKnowledgeLevel ?? "K2",
27840
+ status: "draft",
27841
+ phase: "now",
27842
+ initiative: iniId,
27843
+ domains: [],
27844
+ code: [],
27845
+ created_at: today2(),
27846
+ source: "initiative",
27847
+ source_id: candidate.id,
27848
+ source_initiative: iniId,
27849
+ affected_modules: []
27850
+ };
27851
+ if (candidate.sourceSignals.length) data.source_signals = candidate.sourceSignals;
27852
+ if (candidate.dependencies.length) data.dependencies = candidate.dependencies;
27853
+ const body = [
27854
+ `# ${candidate.title}`,
27855
+ "",
27856
+ `> Materialized from Initiative ${iniId}, candidate ${candidate.id}.`,
27857
+ "",
27858
+ "## Problem",
27859
+ "",
27860
+ candidate.expectedValue ? `_Expected value:_ ${candidate.expectedValue}` : "_Describe the problem._",
27861
+ "",
27862
+ "## Acceptance Criteria",
27863
+ "",
27864
+ "- [ ] _Define at least one testable criterion._",
27865
+ "",
27866
+ "## Out of scope",
27867
+ "",
27868
+ "_Not included in this Work Item._",
27869
+ "",
27870
+ "## Validation",
27871
+ "",
27872
+ "_How will this be validated?_",
27873
+ "",
27874
+ "## Learning",
27875
+ "",
27876
+ "_What did we learn? Update after completion._",
27877
+ ""
27878
+ ].join("\n");
27879
+ return matter28.stringify("\n" + body, data);
27607
27880
  }
27608
- function evaluateOutcomeInto(declaredOutcome, requireDeclaredOutcome, outcome, blockers, softBlocks, reasons, warnings) {
27609
- if (requireDeclaredOutcome && !declaredOutcome) {
27610
- softBlocks.push("no-outcome");
27611
- reasons.push("No expected outcome is declared.");
27612
- }
27613
- if (outcome.total === 0) {
27614
- softBlocks.push("no-success-criteria");
27615
- reasons.push("No success criteria to verify \u2014 completion cannot be judged by outcome.");
27616
- }
27617
- if (outcome.ambiguous > 0) {
27618
- softBlocks.push("criteria-ambiguous");
27619
- reasons.push(`${outcome.ambiguous} success criterion(s) collide in text \u2014 rename to disambiguate before verifying.`);
27620
- }
27621
- if (outcome.failed > 0) {
27622
- softBlocks.push("criteria-failed");
27623
- reasons.push(`${outcome.failed} success criterion(s) failed verification.`);
27881
+ function setCandidateMaterialized(dir, ini, candidateId, wiId) {
27882
+ const raw = readFile(ini.filePath);
27883
+ const { data, content } = matter28(raw, {});
27884
+ const cands = Array.isArray(data.candidates) ? data.candidates : [];
27885
+ for (const c of cands) if (c && typeof c === "object" && String(c.id) === candidateId) c.materialized_as = wiId;
27886
+ data.candidates = cands;
27887
+ const newContent = matter28.stringify(content, data);
27888
+ writeFile(ini.filePath, newContent);
27889
+ const updated = parseInitiative(dir, ini.filePath, newContent);
27890
+ if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after materialization.");
27891
+ return updated;
27892
+ }
27893
+ function materializeCandidate(dir, id, candidateId, opts) {
27894
+ const ini = getInitiative(dir, id);
27895
+ if (!ini) throw new InitiativeWriteError(`Initiative ${id} not found.`);
27896
+ assertFreshInitiative(ini.id, readFile(ini.filePath), opts);
27897
+ const candidate = ini.candidates.find((c) => c.id === candidateId);
27898
+ if (!candidate) throw new InitiativeWriteError(`Candidate ${candidateId} not found in ${id}.`);
27899
+ if (candidate.materializedAs) {
27900
+ const exists3 = discoverWorkItems(dir).some((w) => w.id.toLowerCase() === candidate.materializedAs.toLowerCase());
27901
+ if (!exists3) throw new InitiativeWriteError(`Candidate ${candidateId} points at missing Work Item ${candidate.materializedAs} (broken relation). Resolve it before materializing.`);
27902
+ return { workItemId: candidate.materializedAs, fileName: null, initiative: ini, alreadyMaterialized: true };
27624
27903
  }
27625
- const pending = outcome.notVerified + outcome.manualReview - outcome.ambiguous;
27626
- if (pending > 0) {
27627
- softBlocks.push("criteria-unverified");
27628
- reasons.push(`${pending} success criterion(s) not verified (no or insufficient evidence).`);
27904
+ const existing = findMaterializedWorkItem(dir, ini.id, candidateId);
27905
+ if (existing) {
27906
+ if (existing.initiative && existing.initiative.toLowerCase() !== ini.id.toLowerCase()) {
27907
+ throw new InitiativeWriteError(`A Work Item for candidate ${candidateId} already belongs to ${existing.initiative} (conflicting provenance).`);
27908
+ }
27909
+ const repaired = setCandidateMaterialized(dir, ini, candidateId, existing.id);
27910
+ return { workItemId: existing.id, fileName: null, initiative: repaired, alreadyMaterialized: true };
27629
27911
  }
27630
- if (outcome.stale.length > 0) warnings.push(`${outcome.stale.length} evidence record(s) no longer match a declared criterion (stale).`);
27912
+ const wiId = nextWorkItemId3(dir);
27913
+ const fileName = `${wiId}-${slugify7(candidate.title)}.md`;
27914
+ ensureDir(join(dir, DRAFT_DIR2));
27915
+ writeFile(join(dir, DRAFT_DIR2, fileName), buildWorkItemContent(wiId, ini.id, candidate));
27916
+ const updated = setCandidateMaterialized(dir, ini, candidateId, wiId);
27917
+ return { workItemId: wiId, fileName, initiative: updated, alreadyMaterialized: false };
27631
27918
  }
27632
- function pushReadinessReason(readiness, reasons) {
27633
- if (readiness === "READY_TO_COMPLETE") reasons.unshift("All success criteria are verified and committed work is complete. Human approval is still required to close.");
27634
- else if (readiness === "READY_WITH_EXCEPTIONS") reasons.unshift("Remaining gaps are covered by accepted exceptions. Human approval is still required to close.");
27919
+ var InitiativeNotReadyError = class extends InitiativeWriteError {
27920
+ constructor(evaluation) {
27921
+ super(`Initiative ${evaluation.id} is not ready to complete (${evaluation.readiness}).`);
27922
+ this.evaluation = evaluation;
27923
+ this.name = "InitiativeNotReadyError";
27924
+ }
27925
+ evaluation;
27926
+ };
27927
+ function completeInitiative(dir, id, input = {}, opts) {
27928
+ const ini = getInitiative(dir, id);
27929
+ if (!ini) throw new InitiativeWriteError(`Initiative ${id} not found.`);
27930
+ const evaluation = evaluateInitiativeCompletion(dir, ini);
27931
+ if (evaluation.readiness !== "READY_TO_COMPLETE" && evaluation.readiness !== "READY_WITH_EXCEPTIONS") throw new InitiativeNotReadyError(evaluation);
27932
+ if (!isValidInitiativeTransition(ini.status, "completed")) throw new InitiativeWriteError(`Initiative ${id} cannot move from ${ini.status} to completed.`);
27933
+ const raw = readFile(ini.filePath);
27934
+ assertFreshInitiative(ini.id, raw, opts);
27935
+ const { data, content } = matter28(raw, {});
27936
+ data.status = "completed";
27937
+ data.completed_at = today2();
27938
+ const decision = { readiness: evaluation.readiness, decided_at: today2(), reasons: evaluation.reasons };
27939
+ if (input.decidedBy?.trim()) decision.decided_by = input.decidedBy.trim();
27940
+ if (input.note?.trim()) decision.note = input.note.trim();
27941
+ const accepted = evaluation.exceptions.filter((x) => x.status === "accepted");
27942
+ if (accepted.length > 0) decision.exceptions = accepted;
27943
+ data.completion_decision = decision;
27944
+ const newContent = matter28.stringify(content, data);
27945
+ writeFile(ini.filePath, newContent);
27946
+ const updated = parseInitiative(dir, ini.filePath, newContent);
27947
+ if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after completion.");
27948
+ return updated;
27635
27949
  }
27636
27950
 
27637
27951
  // src/core/delivery-planning-write.ts
@@ -28587,112 +28901,6 @@ async function runCollaborationShow(dir, id) {
28587
28901
  }
28588
28902
  }
28589
28903
 
28590
- // src/core/initiative-analysis.ts
28591
- var SUCCESS_HEADING_RE = /^#{1,6}\s*(success criteria|criterios de[ét]xito|criterios de éxito)\s*$/i;
28592
- var HEADING_RE2 = /^#{1,6}\s+/;
28593
- var CHECK_ITEM_RE = /^\s*[-*]\s+\[([ xX])\]\s+(.*)$/;
28594
- var BULLET_RE2 = /^\s*[-*]\s+(.*)$/;
28595
- var PLACEHOLDER_RE = /^_.*_$/;
28596
- function parseSuccessCriteria(body) {
28597
- const lines = body.split(/\r?\n/);
28598
- const out = [];
28599
- let capture = false;
28600
- for (const line of lines) {
28601
- if (capture && HEADING_RE2.test(line)) break;
28602
- if (!capture) {
28603
- if (SUCCESS_HEADING_RE.test(line.trim())) capture = true;
28604
- continue;
28605
- }
28606
- const check = line.match(CHECK_ITEM_RE);
28607
- if (check) {
28608
- const text2 = check[2].trim();
28609
- if (text2 && !PLACEHOLDER_RE.test(text2)) {
28610
- out.push({ text: text2, checked: check[1].toLowerCase() === "x" });
28611
- }
28612
- continue;
28613
- }
28614
- const bullet = line.match(BULLET_RE2);
28615
- if (bullet) {
28616
- const text2 = bullet[1].trim();
28617
- if (text2 && !PLACEHOLDER_RE.test(text2)) out.push({ text: text2, checked: null });
28618
- }
28619
- }
28620
- return out;
28621
- }
28622
- function analyzeInitiative(dir, ini) {
28623
- const progress = computeInitiativeProgress(dir, ini);
28624
- const successCriteria = parseSuccessCriteria(ini.body);
28625
- const pendingCandidates = ini.candidates.filter((c) => !c.materializedAs);
28626
- const associated = associatedWorkItems(dir, ini.id);
28627
- const findings = [];
28628
- if (successCriteria.length === 0) {
28629
- findings.push({
28630
- code: "no-success-criteria",
28631
- severity: "warning",
28632
- message: "The Initiative has no explicit Success Criteria; completion cannot be judged by outcome, only by delivery."
28633
- });
28634
- } else {
28635
- const uncovered = successCriteria.filter((c) => c.checked === false);
28636
- if (uncovered.length > 0) {
28637
- findings.push({
28638
- code: "uncovered-success-criteria",
28639
- severity: "blocking",
28640
- message: `${uncovered.length} success criterion/criteria remain uncovered.`,
28641
- items: uncovered.map((c) => c.text)
28642
- });
28643
- }
28644
- }
28645
- if (pendingCandidates.length > 0) {
28646
- findings.push({
28647
- code: "pending-candidates",
28648
- severity: "blocking",
28649
- message: `${pendingCandidates.length} committed candidate(s) not yet materialized into Work Items.`,
28650
- items: pendingCandidates.map((c) => `${c.id}: ${c.title}`)
28651
- });
28652
- }
28653
- const notCompleted = associated.filter((w) => w.status !== "completed" && w.status !== "archived");
28654
- if (associated.length === 0) {
28655
- findings.push({
28656
- code: "no-delivery",
28657
- severity: "info",
28658
- message: "No Work Items are associated with this Initiative yet."
28659
- });
28660
- } else if (notCompleted.length > 0) {
28661
- findings.push({
28662
- code: "incomplete-delivery",
28663
- severity: "blocking",
28664
- message: `${notCompleted.length} associated Work Item(s) are not completed.`,
28665
- items: notCompleted.map((w) => `${w.id} (${w.status})`)
28666
- });
28667
- }
28668
- return {
28669
- initiative: ini.id,
28670
- status: ini.status,
28671
- progress,
28672
- successCriteria,
28673
- pendingCandidates,
28674
- findings,
28675
- suggestedCandidates: pendingCandidates
28676
- };
28677
- }
28678
- function evaluateInitiativeCompletion(dir, ini) {
28679
- const analysis = analyzeInitiative(dir, ini);
28680
- const reasons = [];
28681
- for (const f of analysis.findings) {
28682
- if (f.severity === "blocking") reasons.push(f.message);
28683
- }
28684
- if (analysis.progress.delivery.total === 0 && analysis.pendingCandidates.length === 0) {
28685
- reasons.push("Nothing has been delivered or committed under this Initiative.");
28686
- }
28687
- const ready = reasons.length === 0;
28688
- return {
28689
- initiative: ini.id,
28690
- ready,
28691
- readiness: ready ? "ready" : "not-ready",
28692
- reasons
28693
- };
28694
- }
28695
-
28696
28904
  // src/commands/initiative.ts
28697
28905
  function requireInit2(dir) {
28698
28906
  if (!loadConfig(dir)) {
@@ -28869,15 +29077,15 @@ async function runInitiativeComplete(id, opts = {}) {
28869
29077
  }
28870
29078
  const readiness = evaluateInitiativeCompletion(dir, ini);
28871
29079
  if (readiness.ready) {
28872
- log.success("Completion readiness: ready.");
29080
+ log.success(`Completion readiness: ${readiness.readiness}.`);
28873
29081
  } else {
28874
- log.warn("Completion readiness: NOT ready.");
29082
+ log.warn(`Completion readiness: ${readiness.readiness} \u2014 NOT ready.`);
28875
29083
  for (const r of readiness.reasons) log.warn(` - ${r}`);
28876
29084
  }
28877
29085
  if (!opts.yes) {
28878
29086
  log.info("");
28879
29087
  const proceed = await confirm({
28880
- message: readiness.ready ? "Mark this Initiative as completed?" : "This Initiative is not ready. Complete it anyway?",
29088
+ message: readiness.ready ? "Mark this Initiative as completed?" : "This Initiative is not ready. Try to complete it anyway?",
28881
29089
  initialValue: false
28882
29090
  });
28883
29091
  if (!proceed) {
@@ -28886,10 +29094,15 @@ async function runInitiativeComplete(id, opts = {}) {
28886
29094
  }
28887
29095
  }
28888
29096
  try {
28889
- const done = transitionInitiative(dir, id, "completed");
29097
+ const done = completeInitiative(dir, id);
28890
29098
  log.success(`Status: ${done.status}`);
28891
29099
  outro(`Initiative ${done.id} completed.`);
28892
29100
  } catch (err) {
29101
+ if (err instanceof InitiativeNotReadyError) {
29102
+ log.error(err.message);
29103
+ log.warn("Record outcome evidence and resolve blockers before completing this Initiative.");
29104
+ process.exit(1);
29105
+ }
28893
29106
  log.error(err instanceof InitiativeWriteError ? err.message : String(err));
28894
29107
  process.exit(1);
28895
29108
  }