@kaddo/cli 3.104.0 → 3.106.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 (3) hide show
  1. package/dist/core.js +536 -3
  2. package/dist/index.js +593 -10
  3. package/package.json +1 -1
package/dist/core.js CHANGED
@@ -13,6 +13,9 @@ function writeFile(filePath, content) {
13
13
  fs.mkdirSync(path.dirname(filePath), { recursive: true });
14
14
  fs.writeFileSync(filePath, content, "utf-8");
15
15
  }
16
+ function ensureDir(dirPath) {
17
+ fs.mkdirSync(dirPath, { recursive: true });
18
+ }
16
19
  function readDir(dirPath) {
17
20
  if (!exists(dirPath)) return [];
18
21
  return fs.readdirSync(dirPath);
@@ -9150,7 +9153,7 @@ function createWorkItem(dir, opts) {
9150
9153
  if (!type) throw new WorkItemWriteError("INVALID_INPUT", `Unknown Work Item type "${opts.type}".`);
9151
9154
  const id = nextWorkItemId(dir);
9152
9155
  const title = intent.split(/\r?\n/)[0].trim().slice(0, 120);
9153
- const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
9156
+ const today2 = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
9154
9157
  const source = opts.source ? { ...opts.source, inferred: false } : { type: "manual", inferred: false };
9155
9158
  const data = {
9156
9159
  type,
@@ -9158,7 +9161,7 @@ function createWorkItem(dir, opts) {
9158
9161
  title,
9159
9162
  status: "draft",
9160
9163
  work_type: type,
9161
- created_at: today,
9164
+ created_at: today2,
9162
9165
  source,
9163
9166
  generated_by: "kaddo-admin",
9164
9167
  affected_modules: [],
@@ -11881,10 +11884,524 @@ function getStatus(dir) {
11881
11884
  lastError: null
11882
11885
  };
11883
11886
  }
11887
+
11888
+ // src/core/initiative.ts
11889
+ import matter10 from "gray-matter";
11890
+ var INITIATIVES_DIR = "knowledge/delivery/initiatives";
11891
+ var INITIATIVE_STATES = [
11892
+ "candidate",
11893
+ "planned",
11894
+ "in-progress",
11895
+ "completed",
11896
+ "deferred",
11897
+ "cancelled"
11898
+ ];
11899
+ var INITIATIVE_TRANSITIONS = {
11900
+ candidate: ["planned", "cancelled"],
11901
+ planned: ["in-progress", "deferred", "cancelled"],
11902
+ "in-progress": ["completed", "deferred", "cancelled"],
11903
+ deferred: ["planned", "cancelled"],
11904
+ completed: [],
11905
+ cancelled: []
11906
+ };
11907
+ var STATUS_SET = new Set(INITIATIVE_STATES);
11908
+ function isValidInitiativeStatus(s) {
11909
+ return STATUS_SET.has(s);
11910
+ }
11911
+ function isValidInitiativeTransition(from, to) {
11912
+ return INITIATIVE_TRANSITIONS[from].includes(to);
11913
+ }
11914
+ function toPosix4(p) {
11915
+ return p.replace(/\\/g, "/");
11916
+ }
11917
+ function optStr3(v) {
11918
+ if (typeof v === "string" && v.trim()) return v.trim();
11919
+ if (typeof v === "number") return String(v);
11920
+ return void 0;
11921
+ }
11922
+ function strList2(v) {
11923
+ if (!Array.isArray(v)) return [];
11924
+ return v.map((x) => typeof x === "string" ? x.trim() : String(x)).filter(Boolean);
11925
+ }
11926
+ function parseCandidates(data) {
11927
+ const raw = data.candidates;
11928
+ if (!Array.isArray(raw)) return [];
11929
+ const out = [];
11930
+ for (const entry of raw) {
11931
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
11932
+ const o = entry;
11933
+ const id = optStr3(o.id);
11934
+ const title = optStr3(o.title);
11935
+ if (!id || !title) continue;
11936
+ out.push({
11937
+ id,
11938
+ title,
11939
+ type: optStr3(o.type),
11940
+ suggestedKnowledgeLevel: optStr3(o.suggested_knowledge_level ?? o.knowledge_level),
11941
+ expectedValue: optStr3(o.expected_value),
11942
+ notes: optStr3(o.notes),
11943
+ sourceSignals: strList2(o.source_signals),
11944
+ dependencies: strList2(o.dependencies),
11945
+ materializedAs: optStr3(o.materialized_as) ?? null
11946
+ });
11947
+ }
11948
+ return out;
11949
+ }
11950
+ function parseExternalLinks(data) {
11951
+ const raw = data.external_links;
11952
+ if (!Array.isArray(raw)) return [];
11953
+ const out = [];
11954
+ for (const entry of raw) {
11955
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
11956
+ const o = entry;
11957
+ const integration = optStr3(o.integration);
11958
+ const externalId = optStr3(o.external_id);
11959
+ if (!integration || !externalId) continue;
11960
+ out.push({
11961
+ integration,
11962
+ externalId,
11963
+ externalType: optStr3(o.external_type),
11964
+ url: optStr3(o.url)
11965
+ });
11966
+ }
11967
+ return out;
11968
+ }
11969
+ function parseInitiative(dir, filePath, raw) {
11970
+ let parsed;
11971
+ try {
11972
+ parsed = matter10(raw, {});
11973
+ } catch {
11974
+ return null;
11975
+ }
11976
+ const data = parsed.data;
11977
+ if (optStr3(data.type) !== "initiative") return null;
11978
+ const id = optStr3(data.id);
11979
+ if (!id) return null;
11980
+ const statusRaw = optStr3(data.status) ?? "planned";
11981
+ const status = isValidInitiativeStatus(statusRaw) ? statusRaw : "planned";
11982
+ return {
11983
+ id,
11984
+ title: optStr3(data.title) ?? id,
11985
+ status,
11986
+ horizon: optStr3(data.horizon) ?? null,
11987
+ priority: optStr3(data.priority) ?? null,
11988
+ knowledgeLevel: optStr3(data.knowledge_level) ?? null,
11989
+ domains: strList2(data.domains),
11990
+ relatedCapabilities: strList2(data.related_capabilities),
11991
+ source: optStr3(data.source) ?? null,
11992
+ sourceId: optStr3(data.source_id) ?? null,
11993
+ createdAt: optStr3(data.created_at) ?? null,
11994
+ externalLinks: parseExternalLinks(data),
11995
+ candidates: parseCandidates(data),
11996
+ filePath,
11997
+ relPath: toPosix4(filePath).startsWith(toPosix4(dir) + "/") ? toPosix4(filePath).slice(toPosix4(dir).length + 1) : toPosix4(filePath),
11998
+ body: parsed.content.trim(),
11999
+ rawFrontmatter: data
12000
+ };
12001
+ }
12002
+ function discoverInitiatives(dir) {
12003
+ const iniDir = join(dir, INITIATIVES_DIR);
12004
+ if (!exists(iniDir)) return [];
12005
+ const out = [];
12006
+ for (const entry of readDir(iniDir)) {
12007
+ if (!entry.endsWith(".md")) continue;
12008
+ const full = join(iniDir, entry);
12009
+ if (!isFile(full)) continue;
12010
+ const ini = parseInitiative(dir, full, readFile(full));
12011
+ if (ini) out.push(ini);
12012
+ }
12013
+ return out.sort((a, b) => a.id.localeCompare(b.id));
12014
+ }
12015
+ function getInitiative(dir, id) {
12016
+ const want = id.trim().toLowerCase();
12017
+ return discoverInitiatives(dir).find((i) => i.id.toLowerCase() === want) ?? null;
12018
+ }
12019
+ function nextInitiativeId(dir) {
12020
+ const iniDir = join(dir, INITIATIVES_DIR);
12021
+ let max = 0;
12022
+ if (exists(iniDir)) {
12023
+ for (const entry of readDir(iniDir)) {
12024
+ const m = entry.match(/INI-(\d+)/);
12025
+ if (m) max = Math.max(max, parseInt(m[1], 10));
12026
+ }
12027
+ }
12028
+ return `INI-${String(max + 1).padStart(3, "0")}`;
12029
+ }
12030
+ function workItemBelongsToInitiative(workItemInitiative, iniId) {
12031
+ const v = (workItemInitiative ?? "").trim().toLowerCase();
12032
+ return v !== "" && v === iniId.trim().toLowerCase();
12033
+ }
12034
+ function associatedWorkItems(dir, iniId) {
12035
+ return discoverWorkItems(dir).filter((wi) => workItemBelongsToInitiative(wi.initiative, iniId)).map((wi) => ({
12036
+ id: wi.id,
12037
+ title: wi.title,
12038
+ status: wi.lifecycle ?? "ready"
12039
+ })).sort((a, b) => a.id.localeCompare(b.id));
12040
+ }
12041
+ function computeInitiativeProgress(dir, ini) {
12042
+ const totalCandidates = ini.candidates.length;
12043
+ const materialized = ini.candidates.filter((c) => c.materializedAs).length;
12044
+ const byState = emptyLifecycleCounts();
12045
+ const associated = associatedWorkItems(dir, ini.id);
12046
+ for (const wi of associated) byState[wi.status]++;
12047
+ return {
12048
+ initiative: ini.id,
12049
+ status: ini.status,
12050
+ planning: {
12051
+ totalCandidates,
12052
+ materialized,
12053
+ remaining: Math.max(0, totalCandidates - materialized)
12054
+ },
12055
+ delivery: {
12056
+ total: associated.length,
12057
+ byState
12058
+ }
12059
+ };
12060
+ }
12061
+ function getInitiativeContext(dir, ini) {
12062
+ return {
12063
+ initiative: {
12064
+ id: ini.id,
12065
+ title: ini.title,
12066
+ status: ini.status,
12067
+ horizon: ini.horizon,
12068
+ priority: ini.priority,
12069
+ knowledgeLevel: ini.knowledgeLevel,
12070
+ domains: ini.domains,
12071
+ relatedCapabilities: ini.relatedCapabilities,
12072
+ source: ini.source,
12073
+ sourceId: ini.sourceId
12074
+ },
12075
+ progress: computeInitiativeProgress(dir, ini),
12076
+ candidates: {
12077
+ total: ini.candidates.length,
12078
+ materialized: ini.candidates.filter((c) => c.materializedAs),
12079
+ pending: ini.candidates.filter((c) => !c.materializedAs)
12080
+ },
12081
+ workItems: associatedWorkItems(dir, ini.id),
12082
+ externalLinks: ini.externalLinks
12083
+ };
12084
+ }
12085
+
12086
+ // src/core/initiative-write.ts
12087
+ import matter11 from "gray-matter";
12088
+ var WORK_ITEMS_DIR2 = "knowledge/delivery/work-items";
12089
+ var DRAFT_DIR = `${WORK_ITEMS_DIR2}/draft`;
12090
+ var ROADMAP_PATH2 = "knowledge/delivery/roadmap.md";
12091
+ var InitiativeWriteError = class extends Error {
12092
+ constructor(message) {
12093
+ super(message);
12094
+ this.name = "InitiativeWriteError";
12095
+ }
12096
+ };
12097
+ function slugify3(s) {
12098
+ return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 50);
12099
+ }
12100
+ function today() {
12101
+ return (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
12102
+ }
12103
+ function candidateToData(c) {
12104
+ const out = { id: c.id, title: c.title };
12105
+ if (c.type) out.type = c.type;
12106
+ if (c.suggestedKnowledgeLevel) out.suggested_knowledge_level = c.suggestedKnowledgeLevel;
12107
+ if (c.expectedValue) out.expected_value = c.expectedValue;
12108
+ if (c.notes) out.notes = c.notes;
12109
+ if (c.sourceSignals.length) out.source_signals = c.sourceSignals;
12110
+ if (c.dependencies.length) out.dependencies = c.dependencies;
12111
+ if (c.materializedAs) out.materialized_as = c.materializedAs;
12112
+ return out;
12113
+ }
12114
+ function externalLinkToData(l) {
12115
+ const out = { integration: l.integration, external_id: l.externalId };
12116
+ if (l.externalType) out.external_type = l.externalType;
12117
+ if (l.url) out.url = l.url;
12118
+ return out;
12119
+ }
12120
+ function normalizeCandidate(input, fallbackId) {
12121
+ return {
12122
+ id: input.id?.trim() || fallbackId,
12123
+ title: input.title.trim(),
12124
+ type: input.type?.trim() || void 0,
12125
+ suggestedKnowledgeLevel: input.suggestedKnowledgeLevel?.trim() || void 0,
12126
+ expectedValue: input.expectedValue?.trim() || void 0,
12127
+ notes: input.notes?.trim() || void 0,
12128
+ sourceSignals: input.sourceSignals ?? [],
12129
+ dependencies: input.dependencies ?? [],
12130
+ materializedAs: input.materializedAs ?? null
12131
+ };
12132
+ }
12133
+ function defaultBody(title) {
12134
+ return [
12135
+ `# ${title}`,
12136
+ "",
12137
+ "## Goal",
12138
+ "",
12139
+ "_What outcome does this Initiative pursue?_",
12140
+ "",
12141
+ "## Expected Value",
12142
+ "",
12143
+ "_Why it matters._",
12144
+ "",
12145
+ "## Scope",
12146
+ "",
12147
+ "_What this Initiative covers._",
12148
+ "",
12149
+ "## Out of Scope",
12150
+ "",
12151
+ "_What it explicitly does not cover._",
12152
+ "",
12153
+ "## Success Criteria",
12154
+ "",
12155
+ '_Observable outcomes that define completion (not just "all Work Items done")._',
12156
+ "",
12157
+ "## Dependencies",
12158
+ "",
12159
+ "_Other Initiatives, modules, or external work this depends on._",
12160
+ "",
12161
+ "## Work Item Candidates",
12162
+ "",
12163
+ "_Candidates live in frontmatter `candidates`; summarize them here as they evolve._",
12164
+ "",
12165
+ "## Open Questions",
12166
+ "",
12167
+ "_Unresolved questions for this Initiative._",
12168
+ "",
12169
+ "## Learning",
12170
+ "",
12171
+ "_Captured on completion: what was delivered, what stayed out of scope, outcome reached._",
12172
+ ""
12173
+ ].join("\n");
12174
+ }
12175
+ function buildInitiativeContent(id, input) {
12176
+ const status = input.status ?? "planned";
12177
+ if (!isValidInitiativeStatus(status)) {
12178
+ throw new InitiativeWriteError(`Invalid initiative status: ${status}.`);
12179
+ }
12180
+ const candidates = (input.candidates ?? []).map(
12181
+ (c, i) => normalizeCandidate(c, `WI-CANDIDATE-${String(i + 1).padStart(3, "0")}`)
12182
+ );
12183
+ const data = {
12184
+ type: "initiative",
12185
+ id,
12186
+ title: input.title.trim(),
12187
+ status,
12188
+ knowledge_level: input.knowledgeLevel ?? "K2",
12189
+ domains: input.domains ?? [],
12190
+ related_capabilities: input.relatedCapabilities ?? [],
12191
+ created_at: today(),
12192
+ external_links: (input.externalLinks ?? []).map(externalLinkToData),
12193
+ candidates: candidates.map(candidateToData)
12194
+ };
12195
+ if (input.horizon) data.horizon = input.horizon;
12196
+ if (input.priority) data.priority = input.priority;
12197
+ if (input.source) data.source = input.source;
12198
+ if (input.sourceId) data.source_id = input.sourceId;
12199
+ return matter11.stringify("\n" + (input.body ?? defaultBody(input.title.trim())), data);
12200
+ }
12201
+ function createInitiative(dir, input) {
12202
+ if (!input.title?.trim()) throw new InitiativeWriteError("Initiative title is required.");
12203
+ const id = nextInitiativeId(dir);
12204
+ const fileName = `${id}-${slugify3(input.title)}.md`;
12205
+ const iniDir = join(dir, INITIATIVES_DIR);
12206
+ ensureDir(iniDir);
12207
+ const filePath = join(iniDir, fileName);
12208
+ const content = buildInitiativeContent(id, input);
12209
+ writeFile(filePath, content);
12210
+ const ini = parseInitiative(dir, filePath, content);
12211
+ if (!ini) throw new InitiativeWriteError("Failed to parse the Initiative just written.");
12212
+ return ini;
12213
+ }
12214
+ function transitionInitiative(dir, id, to) {
12215
+ const ini = getInitiative(dir, id);
12216
+ if (!ini) throw new InitiativeWriteError(`Initiative ${id} not found.`);
12217
+ if (!isValidInitiativeStatus(to)) throw new InitiativeWriteError(`Invalid status: ${to}.`);
12218
+ if (ini.status === to) return ini;
12219
+ if (!isValidInitiativeTransition(ini.status, to)) {
12220
+ throw new InitiativeWriteError(`Invalid transition ${ini.status} \u2192 ${to}.`);
12221
+ }
12222
+ const raw = readFile(ini.filePath);
12223
+ const { data, content } = matter11(raw, {});
12224
+ data.status = to;
12225
+ if (to === "completed") data.completed_at = today();
12226
+ const newContent = matter11.stringify(content, data);
12227
+ writeFile(ini.filePath, newContent);
12228
+ const updated = parseInitiative(dir, ini.filePath, newContent);
12229
+ if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after transition.");
12230
+ return updated;
12231
+ }
12232
+ function addCandidate(dir, id, candidate) {
12233
+ const ini = getInitiative(dir, id);
12234
+ if (!ini) throw new InitiativeWriteError(`Initiative ${id} not found.`);
12235
+ const raw = readFile(ini.filePath);
12236
+ const { data, content } = matter11(raw, {});
12237
+ const existing = Array.isArray(data.candidates) ? data.candidates : [];
12238
+ const fallbackId = `WI-CANDIDATE-${String(existing.length + 1).padStart(3, "0")}`;
12239
+ const normalized = normalizeCandidate(candidate, fallbackId);
12240
+ if (ini.candidates.some((c) => c.id === normalized.id)) {
12241
+ throw new InitiativeWriteError(`Candidate ${normalized.id} already exists in ${id}.`);
12242
+ }
12243
+ data.candidates = [...existing, candidateToData(normalized)];
12244
+ const newContent = matter11.stringify(content, data);
12245
+ writeFile(ini.filePath, newContent);
12246
+ const updated = parseInitiative(dir, ini.filePath, newContent);
12247
+ if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after adding a candidate.");
12248
+ return updated;
12249
+ }
12250
+ function updateInitiative(dir, id, patch) {
12251
+ const ini = getInitiative(dir, id);
12252
+ if (!ini) throw new InitiativeWriteError(`Initiative ${id} not found.`);
12253
+ const raw = readFile(ini.filePath);
12254
+ const { data, content } = matter11(raw, {});
12255
+ if (patch.title !== void 0) {
12256
+ if (!patch.title.trim()) throw new InitiativeWriteError("Initiative title cannot be empty.");
12257
+ data.title = patch.title.trim();
12258
+ }
12259
+ if (patch.horizon !== void 0) data.horizon = patch.horizon;
12260
+ if (patch.priority !== void 0) data.priority = patch.priority;
12261
+ if (patch.knowledgeLevel !== void 0) data.knowledge_level = patch.knowledgeLevel;
12262
+ if (patch.domains !== void 0) data.domains = patch.domains;
12263
+ if (patch.relatedCapabilities !== void 0) data.related_capabilities = patch.relatedCapabilities;
12264
+ const newContent = matter11.stringify(content, data);
12265
+ writeFile(ini.filePath, newContent);
12266
+ const updated = parseInitiative(dir, ini.filePath, newContent);
12267
+ if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after update.");
12268
+ return updated;
12269
+ }
12270
+ function nextWorkItemId2(dir) {
12271
+ const wiDir = join(dir, WORK_ITEMS_DIR2);
12272
+ let max = 0;
12273
+ const walk = (d) => {
12274
+ if (!exists(d)) return;
12275
+ for (const entry of readDir(d)) {
12276
+ const full = join(d, entry);
12277
+ if (isFile(full)) {
12278
+ const m = entry.match(/WI-(\d+)/);
12279
+ if (m) max = Math.max(max, parseInt(m[1], 10));
12280
+ } else if (!entry.startsWith(".")) {
12281
+ walk(full);
12282
+ }
12283
+ }
12284
+ };
12285
+ walk(wiDir);
12286
+ return `WI-${String(max + 1).padStart(3, "0")}`;
12287
+ }
12288
+ function buildWorkItemContent(wiId, iniId, candidate) {
12289
+ const data = {
12290
+ type: candidate.type ?? "feature",
12291
+ id: wiId,
12292
+ title: candidate.title,
12293
+ knowledge_level: candidate.suggestedKnowledgeLevel ?? "K2",
12294
+ status: "draft",
12295
+ phase: "now",
12296
+ initiative: iniId,
12297
+ domains: [],
12298
+ code: [],
12299
+ created_at: today(),
12300
+ source: "initiative",
12301
+ source_id: candidate.id,
12302
+ source_initiative: iniId,
12303
+ affected_modules: []
12304
+ };
12305
+ if (candidate.sourceSignals.length) data.source_signals = candidate.sourceSignals;
12306
+ if (candidate.dependencies.length) data.dependencies = candidate.dependencies;
12307
+ const body = [
12308
+ `# ${candidate.title}`,
12309
+ "",
12310
+ `> Materialized from Initiative ${iniId}, candidate ${candidate.id}.`,
12311
+ "",
12312
+ "## Problem",
12313
+ "",
12314
+ candidate.expectedValue ? `_Expected value:_ ${candidate.expectedValue}` : "_Describe the problem._",
12315
+ "",
12316
+ "## Acceptance Criteria",
12317
+ "",
12318
+ "- [ ] _Define at least one testable criterion._",
12319
+ "",
12320
+ "## Out of scope",
12321
+ "",
12322
+ "_Not included in this Work Item._",
12323
+ "",
12324
+ "## Validation",
12325
+ "",
12326
+ "_How will this be validated?_",
12327
+ "",
12328
+ "## Learning",
12329
+ "",
12330
+ "_What did we learn? Update after completion._",
12331
+ ""
12332
+ ].join("\n");
12333
+ return matter11.stringify("\n" + body, data);
12334
+ }
12335
+ function materializeCandidate(dir, id, candidateId) {
12336
+ const ini = getInitiative(dir, id);
12337
+ if (!ini) throw new InitiativeWriteError(`Initiative ${id} not found.`);
12338
+ const candidate = ini.candidates.find((c) => c.id === candidateId);
12339
+ if (!candidate) throw new InitiativeWriteError(`Candidate ${candidateId} not found in ${id}.`);
12340
+ if (candidate.materializedAs) {
12341
+ throw new InitiativeWriteError(
12342
+ `Candidate ${candidateId} is already materialized as ${candidate.materializedAs}.`
12343
+ );
12344
+ }
12345
+ const wiId = nextWorkItemId2(dir);
12346
+ const fileName = `${wiId}-${slugify3(candidate.title)}.md`;
12347
+ ensureDir(join(dir, DRAFT_DIR));
12348
+ writeFile(join(dir, DRAFT_DIR, fileName), buildWorkItemContent(wiId, ini.id, candidate));
12349
+ const raw = readFile(ini.filePath);
12350
+ const { data, content } = matter11(raw, {});
12351
+ const cands = Array.isArray(data.candidates) ? data.candidates : [];
12352
+ for (const c of cands) {
12353
+ if (c && typeof c === "object" && String(c.id) === candidateId) c.materialized_as = wiId;
12354
+ }
12355
+ data.candidates = cands;
12356
+ const newContent = matter11.stringify(content, data);
12357
+ writeFile(ini.filePath, newContent);
12358
+ const updated = parseInitiative(dir, ini.filePath, newContent);
12359
+ if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after materialization.");
12360
+ return { workItemId: wiId, fileName, initiative: updated };
12361
+ }
12362
+ function materializeRoadmapInitiative(dir, rmId) {
12363
+ const roadmapFull = join(dir, ROADMAP_PATH2);
12364
+ if (!exists(roadmapFull)) throw new InitiativeWriteError(`No roadmap found at ${ROADMAP_PATH2}.`);
12365
+ const all = parseRoadmapCandidates(readFile(roadmapFull));
12366
+ const want = rmId.trim().toLowerCase();
12367
+ const belonging = all.filter((c) => (c.initiative?.id ?? "").toLowerCase() === want);
12368
+ if (belonging.length === 0) {
12369
+ throw new InitiativeWriteError(`No roadmap initiative "${rmId}" with candidates found.`);
12370
+ }
12371
+ const title = belonging[0].initiative?.title?.trim() || rmId;
12372
+ const candidates = belonging.map((c) => ({
12373
+ id: c.id,
12374
+ title: c.title,
12375
+ type: c.type,
12376
+ suggestedKnowledgeLevel: c.suggestedKnowledgeLevel,
12377
+ expectedValue: c.expectedValue,
12378
+ notes: c.notes,
12379
+ sourceSignals: c.sourceSignals ?? [],
12380
+ dependencies: c.dependencies ?? [],
12381
+ materializedAs: null
12382
+ }));
12383
+ const domains = belonging[0].domain ? [belonging[0].domain] : [];
12384
+ const relatedCapabilities = Array.from(
12385
+ new Set(belonging.flatMap((c) => c.relatedCapabilities ?? []))
12386
+ );
12387
+ return createInitiative(dir, {
12388
+ title,
12389
+ status: "planned",
12390
+ domains,
12391
+ relatedCapabilities,
12392
+ source: "roadmap",
12393
+ sourceId: rmId,
12394
+ candidates
12395
+ });
12396
+ }
11884
12397
  export {
11885
12398
  CURRENT_CONSENT_VERSION,
12399
+ INITIATIVES_DIR,
12400
+ INITIATIVE_STATES,
12401
+ INITIATIVE_TRANSITIONS,
11886
12402
  INTEGRATIONS_FILE,
11887
12403
  ImportError,
12404
+ InitiativeWriteError,
11888
12405
  IntegrationError,
11889
12406
  IntegrationServiceError,
11890
12407
  TOPOLOGY_FILE,
@@ -11893,9 +12410,11 @@ export {
11893
12410
  WorkItemNotInProgressError,
11894
12411
  WorkItemNotReadyError,
11895
12412
  WorkItemWriteError,
12413
+ addCandidate,
11896
12414
  analyzeCrossRepoEvidence,
11897
12415
  analyzeScopeCoverage,
11898
12416
  applyTopologyProposal,
12417
+ associatedWorkItems,
11899
12418
  buildImplementationHandoff,
11900
12419
  buildImportIndex,
11901
12420
  buildProjectExplanation,
@@ -11905,8 +12424,10 @@ export {
11905
12424
  buildTopologyEnrichmentHandoff,
11906
12425
  collectImplementationEvidence,
11907
12426
  computeContentHash,
12427
+ computeInitiativeProgress,
11908
12428
  computeRefinementStatus,
11909
12429
  consentNotice,
12430
+ createInitiative,
11910
12431
  createIntegration,
11911
12432
  createWorkItem,
11912
12433
  cwd,
@@ -11915,6 +12436,7 @@ export {
11915
12436
  detectFormat,
11916
12437
  disableIntegration,
11917
12438
  discoverExternalWorkItems,
12439
+ discoverInitiatives,
11918
12440
  discoverKnowledge,
11919
12441
  discoverWorkItems,
11920
12442
  enableIntegration,
@@ -11929,6 +12451,8 @@ export {
11929
12451
  getConsentState,
11930
12452
  getExternalWorkItem,
11931
12453
  getImpactCandidates,
12454
+ getInitiative,
12455
+ getInitiativeContext,
11932
12456
  getIntegration,
11933
12457
  getIntegrationFilters,
11934
12458
  getIntegrationSecretStatus,
@@ -11949,6 +12473,8 @@ export {
11949
12473
  isInteractive,
11950
12474
  isModule,
11951
12475
  isEnabled as isTelemetryEnabled,
12476
+ isValidInitiativeStatus,
12477
+ isValidInitiativeTransition,
11952
12478
  join,
11953
12479
  knowledgeLayers,
11954
12480
  lifecycleCounts,
@@ -11958,7 +12484,11 @@ export {
11958
12484
  loadConfig,
11959
12485
  loadMappedModules,
11960
12486
  loadSystemTopology,
12487
+ materializeCandidate,
12488
+ materializeRoadmapInitiative,
12489
+ nextInitiativeId,
11961
12490
  parseContent,
12491
+ parseInitiative,
11962
12492
  persistConsent,
11963
12493
  previewImport,
11964
12494
  readFile,
@@ -11966,7 +12496,9 @@ export {
11966
12496
  searchSystemNodes,
11967
12497
  setIntegrationSecret,
11968
12498
  topologyRevision,
12499
+ transitionInitiative,
11969
12500
  transitionWorkItem,
12501
+ updateInitiative,
11970
12502
  updateIntegration,
11971
12503
  updateIntegrationFilters,
11972
12504
  updateWorkItem,
@@ -11975,5 +12507,6 @@ export {
11975
12507
  validateTopologyProposal,
11976
12508
  validateWorkItem,
11977
12509
  verifyIntegration,
11978
- verifyWorkItem
12510
+ verifyWorkItem,
12511
+ workItemBelongsToInitiative
11979
12512
  };
package/dist/index.js CHANGED
@@ -6247,7 +6247,7 @@ function formatList(items) {
6247
6247
  return items.map((i) => `- ${i.trim()}`).join("\n");
6248
6248
  }
6249
6249
  function buildFrontMatter(id, type, level, title, answers) {
6250
- const today2 = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
6250
+ const today3 = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
6251
6251
  const lines = [
6252
6252
  "---",
6253
6253
  `type: ${type}`,
@@ -6260,7 +6260,7 @@ function buildFrontMatter(id, type, level, title, answers) {
6260
6260
  `initiative:`,
6261
6261
  `domains: []`,
6262
6262
  `code: []`,
6263
- `created_at: ${today2}`,
6263
+ `created_at: ${today3}`,
6264
6264
  `source:`,
6265
6265
  ` type: manual`,
6266
6266
  ` inferred: false`,
@@ -6335,7 +6335,7 @@ _What did we learn from this change? Update after completion._
6335
6335
  return sections.join("\n");
6336
6336
  }
6337
6337
  function buildModuleFrontMatter(id, modType, title, answers) {
6338
- const today2 = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
6338
+ const today3 = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
6339
6339
  const extra = modType.extraFrontMatter ?? {};
6340
6340
  const extraLines = Object.entries(extra).map(
6341
6341
  ([k, v]) => `${k}: ${JSON.stringify(v)}`
@@ -6351,7 +6351,7 @@ function buildModuleFrontMatter(id, modType, title, answers) {
6351
6351
  `initiative:`,
6352
6352
  `domains: []`,
6353
6353
  `code: []`,
6354
- `created_at: ${today2}`,
6354
+ `created_at: ${today3}`,
6355
6355
  `source: manual`,
6356
6356
  `summary: "${title}"`,
6357
6357
  ...extraLines,
@@ -6499,7 +6499,7 @@ function resolveCandidateLevel(candidate, type) {
6499
6499
  return getLevelForType(type);
6500
6500
  }
6501
6501
  function buildRoadmapFrontMatter(id, type, level, title, candidate, answers) {
6502
- const today2 = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
6502
+ const today3 = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
6503
6503
  const summary = (answers.problem?.split(".")[0] ?? candidate.expectedValue ?? title).trim();
6504
6504
  const initiative = candidate.initiative?.title ?? candidate.initiative?.id ?? "";
6505
6505
  const q = (s) => s.replace(/"/g, "'");
@@ -6522,7 +6522,7 @@ function buildRoadmapFrontMatter(id, type, level, title, candidate, answers) {
6522
6522
  ...yamlList2("domains", domains),
6523
6523
  ...domains.length === 0 ? ["domains: []"] : [],
6524
6524
  `code: []`,
6525
- `created_at: ${today2}`,
6525
+ `created_at: ${today3}`,
6526
6526
  `source: roadmap`,
6527
6527
  `source_id: ${candidate.id}`,
6528
6528
  `source_initiative: ${candidate.initiative?.id ?? "unknown"}`,
@@ -17924,7 +17924,7 @@ function createWorkItem(dir, opts) {
17924
17924
  if (!type) throw new WorkItemWriteError("INVALID_INPUT", `Unknown Work Item type "${opts.type}".`);
17925
17925
  const id = nextWorkItemId2(dir);
17926
17926
  const title = intent.split(/\r?\n/)[0].trim().slice(0, 120);
17927
- const today2 = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
17927
+ const today3 = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
17928
17928
  const source = opts.source ? { ...opts.source, inferred: false } : { type: "manual", inferred: false };
17929
17929
  const data = {
17930
17930
  type,
@@ -17932,7 +17932,7 @@ function createWorkItem(dir, opts) {
17932
17932
  title,
17933
17933
  status: "draft",
17934
17934
  work_type: type,
17935
- created_at: today2,
17935
+ created_at: today3,
17936
17936
  source,
17937
17937
  generated_by: "kaddo-admin",
17938
17938
  affected_modules: [],
@@ -20481,9 +20481,9 @@ function isResolvedSection(text2) {
20481
20481
  function transitionToReady(filePath) {
20482
20482
  const raw = readFile(filePath);
20483
20483
  const { data, content } = matter13(raw);
20484
- const today2 = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
20484
+ const today3 = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
20485
20485
  data.status = "ready";
20486
- data.ready_at = today2;
20486
+ data.ready_at = today3;
20487
20487
  const newContent = matter13.stringify(content, data);
20488
20488
  const posix = filePath.replace(/\\/g, "/");
20489
20489
  let newPath = filePath;
@@ -22292,6 +22292,567 @@ function runTelemetryDisable() {
22292
22292
  outro("Run `kaddo telemetry enable` to re-enable.");
22293
22293
  }
22294
22294
 
22295
+ // src/core/initiative.ts
22296
+ import matter17 from "gray-matter";
22297
+ var INITIATIVES_DIR = "knowledge/delivery/initiatives";
22298
+ var INITIATIVE_STATES = [
22299
+ "candidate",
22300
+ "planned",
22301
+ "in-progress",
22302
+ "completed",
22303
+ "deferred",
22304
+ "cancelled"
22305
+ ];
22306
+ var INITIATIVE_TRANSITIONS = {
22307
+ candidate: ["planned", "cancelled"],
22308
+ planned: ["in-progress", "deferred", "cancelled"],
22309
+ "in-progress": ["completed", "deferred", "cancelled"],
22310
+ deferred: ["planned", "cancelled"],
22311
+ completed: [],
22312
+ cancelled: []
22313
+ };
22314
+ var STATUS_SET = new Set(INITIATIVE_STATES);
22315
+ function isValidInitiativeStatus(s) {
22316
+ return STATUS_SET.has(s);
22317
+ }
22318
+ function isValidInitiativeTransition(from, to) {
22319
+ return INITIATIVE_TRANSITIONS[from].includes(to);
22320
+ }
22321
+ function toPosix6(p) {
22322
+ return p.replace(/\\/g, "/");
22323
+ }
22324
+ function optStr3(v) {
22325
+ if (typeof v === "string" && v.trim()) return v.trim();
22326
+ if (typeof v === "number") return String(v);
22327
+ return void 0;
22328
+ }
22329
+ function strList2(v) {
22330
+ if (!Array.isArray(v)) return [];
22331
+ return v.map((x) => typeof x === "string" ? x.trim() : String(x)).filter(Boolean);
22332
+ }
22333
+ function parseCandidates(data) {
22334
+ const raw = data.candidates;
22335
+ if (!Array.isArray(raw)) return [];
22336
+ const out = [];
22337
+ for (const entry of raw) {
22338
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
22339
+ const o = entry;
22340
+ const id = optStr3(o.id);
22341
+ const title = optStr3(o.title);
22342
+ if (!id || !title) continue;
22343
+ out.push({
22344
+ id,
22345
+ title,
22346
+ type: optStr3(o.type),
22347
+ suggestedKnowledgeLevel: optStr3(o.suggested_knowledge_level ?? o.knowledge_level),
22348
+ expectedValue: optStr3(o.expected_value),
22349
+ notes: optStr3(o.notes),
22350
+ sourceSignals: strList2(o.source_signals),
22351
+ dependencies: strList2(o.dependencies),
22352
+ materializedAs: optStr3(o.materialized_as) ?? null
22353
+ });
22354
+ }
22355
+ return out;
22356
+ }
22357
+ function parseExternalLinks(data) {
22358
+ const raw = data.external_links;
22359
+ if (!Array.isArray(raw)) return [];
22360
+ const out = [];
22361
+ for (const entry of raw) {
22362
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
22363
+ const o = entry;
22364
+ const integration = optStr3(o.integration);
22365
+ const externalId = optStr3(o.external_id);
22366
+ if (!integration || !externalId) continue;
22367
+ out.push({
22368
+ integration,
22369
+ externalId,
22370
+ externalType: optStr3(o.external_type),
22371
+ url: optStr3(o.url)
22372
+ });
22373
+ }
22374
+ return out;
22375
+ }
22376
+ function parseInitiative(dir, filePath, raw) {
22377
+ let parsed;
22378
+ try {
22379
+ parsed = matter17(raw, {});
22380
+ } catch {
22381
+ return null;
22382
+ }
22383
+ const data = parsed.data;
22384
+ if (optStr3(data.type) !== "initiative") return null;
22385
+ const id = optStr3(data.id);
22386
+ if (!id) return null;
22387
+ const statusRaw = optStr3(data.status) ?? "planned";
22388
+ const status = isValidInitiativeStatus(statusRaw) ? statusRaw : "planned";
22389
+ return {
22390
+ id,
22391
+ title: optStr3(data.title) ?? id,
22392
+ status,
22393
+ horizon: optStr3(data.horizon) ?? null,
22394
+ priority: optStr3(data.priority) ?? null,
22395
+ knowledgeLevel: optStr3(data.knowledge_level) ?? null,
22396
+ domains: strList2(data.domains),
22397
+ relatedCapabilities: strList2(data.related_capabilities),
22398
+ source: optStr3(data.source) ?? null,
22399
+ sourceId: optStr3(data.source_id) ?? null,
22400
+ createdAt: optStr3(data.created_at) ?? null,
22401
+ externalLinks: parseExternalLinks(data),
22402
+ candidates: parseCandidates(data),
22403
+ filePath,
22404
+ relPath: toPosix6(filePath).startsWith(toPosix6(dir) + "/") ? toPosix6(filePath).slice(toPosix6(dir).length + 1) : toPosix6(filePath),
22405
+ body: parsed.content.trim(),
22406
+ rawFrontmatter: data
22407
+ };
22408
+ }
22409
+ function discoverInitiatives(dir) {
22410
+ const iniDir = join(dir, INITIATIVES_DIR);
22411
+ if (!exists(iniDir)) return [];
22412
+ const out = [];
22413
+ for (const entry of readDir(iniDir)) {
22414
+ if (!entry.endsWith(".md")) continue;
22415
+ const full = join(iniDir, entry);
22416
+ if (!isFile(full)) continue;
22417
+ const ini = parseInitiative(dir, full, readFile(full));
22418
+ if (ini) out.push(ini);
22419
+ }
22420
+ return out.sort((a, b) => a.id.localeCompare(b.id));
22421
+ }
22422
+ function getInitiative(dir, id) {
22423
+ const want = id.trim().toLowerCase();
22424
+ return discoverInitiatives(dir).find((i) => i.id.toLowerCase() === want) ?? null;
22425
+ }
22426
+ function nextInitiativeId(dir) {
22427
+ const iniDir = join(dir, INITIATIVES_DIR);
22428
+ let max = 0;
22429
+ if (exists(iniDir)) {
22430
+ for (const entry of readDir(iniDir)) {
22431
+ const m = entry.match(/INI-(\d+)/);
22432
+ if (m) max = Math.max(max, parseInt(m[1], 10));
22433
+ }
22434
+ }
22435
+ return `INI-${String(max + 1).padStart(3, "0")}`;
22436
+ }
22437
+ function workItemBelongsToInitiative(workItemInitiative, iniId) {
22438
+ const v = (workItemInitiative ?? "").trim().toLowerCase();
22439
+ return v !== "" && v === iniId.trim().toLowerCase();
22440
+ }
22441
+ function associatedWorkItems(dir, iniId) {
22442
+ return discoverWorkItems(dir).filter((wi) => workItemBelongsToInitiative(wi.initiative, iniId)).map((wi) => ({
22443
+ id: wi.id,
22444
+ title: wi.title,
22445
+ status: wi.lifecycle ?? "ready"
22446
+ })).sort((a, b) => a.id.localeCompare(b.id));
22447
+ }
22448
+ function computeInitiativeProgress(dir, ini) {
22449
+ const totalCandidates = ini.candidates.length;
22450
+ const materialized = ini.candidates.filter((c) => c.materializedAs).length;
22451
+ const byState = emptyLifecycleCounts();
22452
+ const associated = associatedWorkItems(dir, ini.id);
22453
+ for (const wi of associated) byState[wi.status]++;
22454
+ return {
22455
+ initiative: ini.id,
22456
+ status: ini.status,
22457
+ planning: {
22458
+ totalCandidates,
22459
+ materialized,
22460
+ remaining: Math.max(0, totalCandidates - materialized)
22461
+ },
22462
+ delivery: {
22463
+ total: associated.length,
22464
+ byState
22465
+ }
22466
+ };
22467
+ }
22468
+
22469
+ // src/core/initiative-write.ts
22470
+ import matter18 from "gray-matter";
22471
+ var WORK_ITEMS_DIR4 = "knowledge/delivery/work-items";
22472
+ var DRAFT_DIR2 = `${WORK_ITEMS_DIR4}/draft`;
22473
+ var InitiativeWriteError = class extends Error {
22474
+ constructor(message) {
22475
+ super(message);
22476
+ this.name = "InitiativeWriteError";
22477
+ }
22478
+ };
22479
+ function slugify6(s) {
22480
+ return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 50);
22481
+ }
22482
+ function today2() {
22483
+ return (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
22484
+ }
22485
+ function candidateToData(c) {
22486
+ const out = { id: c.id, title: c.title };
22487
+ if (c.type) out.type = c.type;
22488
+ if (c.suggestedKnowledgeLevel) out.suggested_knowledge_level = c.suggestedKnowledgeLevel;
22489
+ if (c.expectedValue) out.expected_value = c.expectedValue;
22490
+ if (c.notes) out.notes = c.notes;
22491
+ if (c.sourceSignals.length) out.source_signals = c.sourceSignals;
22492
+ if (c.dependencies.length) out.dependencies = c.dependencies;
22493
+ if (c.materializedAs) out.materialized_as = c.materializedAs;
22494
+ return out;
22495
+ }
22496
+ function externalLinkToData(l) {
22497
+ const out = { integration: l.integration, external_id: l.externalId };
22498
+ if (l.externalType) out.external_type = l.externalType;
22499
+ if (l.url) out.url = l.url;
22500
+ return out;
22501
+ }
22502
+ function normalizeCandidate(input, fallbackId) {
22503
+ return {
22504
+ id: input.id?.trim() || fallbackId,
22505
+ title: input.title.trim(),
22506
+ type: input.type?.trim() || void 0,
22507
+ suggestedKnowledgeLevel: input.suggestedKnowledgeLevel?.trim() || void 0,
22508
+ expectedValue: input.expectedValue?.trim() || void 0,
22509
+ notes: input.notes?.trim() || void 0,
22510
+ sourceSignals: input.sourceSignals ?? [],
22511
+ dependencies: input.dependencies ?? [],
22512
+ materializedAs: input.materializedAs ?? null
22513
+ };
22514
+ }
22515
+ function defaultBody(title) {
22516
+ return [
22517
+ `# ${title}`,
22518
+ "",
22519
+ "## Goal",
22520
+ "",
22521
+ "_What outcome does this Initiative pursue?_",
22522
+ "",
22523
+ "## Expected Value",
22524
+ "",
22525
+ "_Why it matters._",
22526
+ "",
22527
+ "## Scope",
22528
+ "",
22529
+ "_What this Initiative covers._",
22530
+ "",
22531
+ "## Out of Scope",
22532
+ "",
22533
+ "_What it explicitly does not cover._",
22534
+ "",
22535
+ "## Success Criteria",
22536
+ "",
22537
+ '_Observable outcomes that define completion (not just "all Work Items done")._',
22538
+ "",
22539
+ "## Dependencies",
22540
+ "",
22541
+ "_Other Initiatives, modules, or external work this depends on._",
22542
+ "",
22543
+ "## Work Item Candidates",
22544
+ "",
22545
+ "_Candidates live in frontmatter `candidates`; summarize them here as they evolve._",
22546
+ "",
22547
+ "## Open Questions",
22548
+ "",
22549
+ "_Unresolved questions for this Initiative._",
22550
+ "",
22551
+ "## Learning",
22552
+ "",
22553
+ "_Captured on completion: what was delivered, what stayed out of scope, outcome reached._",
22554
+ ""
22555
+ ].join("\n");
22556
+ }
22557
+ function buildInitiativeContent(id, input) {
22558
+ const status = input.status ?? "planned";
22559
+ if (!isValidInitiativeStatus(status)) {
22560
+ throw new InitiativeWriteError(`Invalid initiative status: ${status}.`);
22561
+ }
22562
+ const candidates = (input.candidates ?? []).map(
22563
+ (c, i) => normalizeCandidate(c, `WI-CANDIDATE-${String(i + 1).padStart(3, "0")}`)
22564
+ );
22565
+ const data = {
22566
+ type: "initiative",
22567
+ id,
22568
+ title: input.title.trim(),
22569
+ status,
22570
+ knowledge_level: input.knowledgeLevel ?? "K2",
22571
+ domains: input.domains ?? [],
22572
+ related_capabilities: input.relatedCapabilities ?? [],
22573
+ created_at: today2(),
22574
+ external_links: (input.externalLinks ?? []).map(externalLinkToData),
22575
+ candidates: candidates.map(candidateToData)
22576
+ };
22577
+ if (input.horizon) data.horizon = input.horizon;
22578
+ if (input.priority) data.priority = input.priority;
22579
+ if (input.source) data.source = input.source;
22580
+ if (input.sourceId) data.source_id = input.sourceId;
22581
+ return matter18.stringify("\n" + (input.body ?? defaultBody(input.title.trim())), data);
22582
+ }
22583
+ function createInitiative(dir, input) {
22584
+ if (!input.title?.trim()) throw new InitiativeWriteError("Initiative title is required.");
22585
+ const id = nextInitiativeId(dir);
22586
+ const fileName = `${id}-${slugify6(input.title)}.md`;
22587
+ const iniDir = join(dir, INITIATIVES_DIR);
22588
+ ensureDir(iniDir);
22589
+ const filePath = join(iniDir, fileName);
22590
+ const content = buildInitiativeContent(id, input);
22591
+ writeFile(filePath, content);
22592
+ const ini = parseInitiative(dir, filePath, content);
22593
+ if (!ini) throw new InitiativeWriteError("Failed to parse the Initiative just written.");
22594
+ return ini;
22595
+ }
22596
+ function transitionInitiative(dir, id, to) {
22597
+ const ini = getInitiative(dir, id);
22598
+ if (!ini) throw new InitiativeWriteError(`Initiative ${id} not found.`);
22599
+ if (!isValidInitiativeStatus(to)) throw new InitiativeWriteError(`Invalid status: ${to}.`);
22600
+ if (ini.status === to) return ini;
22601
+ if (!isValidInitiativeTransition(ini.status, to)) {
22602
+ throw new InitiativeWriteError(`Invalid transition ${ini.status} \u2192 ${to}.`);
22603
+ }
22604
+ const raw = readFile(ini.filePath);
22605
+ const { data, content } = matter18(raw, {});
22606
+ data.status = to;
22607
+ if (to === "completed") data.completed_at = today2();
22608
+ const newContent = matter18.stringify(content, data);
22609
+ writeFile(ini.filePath, newContent);
22610
+ const updated = parseInitiative(dir, ini.filePath, newContent);
22611
+ if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after transition.");
22612
+ return updated;
22613
+ }
22614
+ function nextWorkItemId3(dir) {
22615
+ const wiDir = join(dir, WORK_ITEMS_DIR4);
22616
+ let max = 0;
22617
+ const walk = (d) => {
22618
+ if (!exists(d)) return;
22619
+ for (const entry of readDir(d)) {
22620
+ const full = join(d, entry);
22621
+ if (isFile(full)) {
22622
+ const m = entry.match(/WI-(\d+)/);
22623
+ if (m) max = Math.max(max, parseInt(m[1], 10));
22624
+ } else if (!entry.startsWith(".")) {
22625
+ walk(full);
22626
+ }
22627
+ }
22628
+ };
22629
+ walk(wiDir);
22630
+ return `WI-${String(max + 1).padStart(3, "0")}`;
22631
+ }
22632
+ function buildWorkItemContent(wiId, iniId, candidate) {
22633
+ const data = {
22634
+ type: candidate.type ?? "feature",
22635
+ id: wiId,
22636
+ title: candidate.title,
22637
+ knowledge_level: candidate.suggestedKnowledgeLevel ?? "K2",
22638
+ status: "draft",
22639
+ phase: "now",
22640
+ initiative: iniId,
22641
+ domains: [],
22642
+ code: [],
22643
+ created_at: today2(),
22644
+ source: "initiative",
22645
+ source_id: candidate.id,
22646
+ source_initiative: iniId,
22647
+ affected_modules: []
22648
+ };
22649
+ if (candidate.sourceSignals.length) data.source_signals = candidate.sourceSignals;
22650
+ if (candidate.dependencies.length) data.dependencies = candidate.dependencies;
22651
+ const body = [
22652
+ `# ${candidate.title}`,
22653
+ "",
22654
+ `> Materialized from Initiative ${iniId}, candidate ${candidate.id}.`,
22655
+ "",
22656
+ "## Problem",
22657
+ "",
22658
+ candidate.expectedValue ? `_Expected value:_ ${candidate.expectedValue}` : "_Describe the problem._",
22659
+ "",
22660
+ "## Acceptance Criteria",
22661
+ "",
22662
+ "- [ ] _Define at least one testable criterion._",
22663
+ "",
22664
+ "## Out of scope",
22665
+ "",
22666
+ "_Not included in this Work Item._",
22667
+ "",
22668
+ "## Validation",
22669
+ "",
22670
+ "_How will this be validated?_",
22671
+ "",
22672
+ "## Learning",
22673
+ "",
22674
+ "_What did we learn? Update after completion._",
22675
+ ""
22676
+ ].join("\n");
22677
+ return matter18.stringify("\n" + body, data);
22678
+ }
22679
+ function materializeCandidate(dir, id, candidateId) {
22680
+ const ini = getInitiative(dir, id);
22681
+ if (!ini) throw new InitiativeWriteError(`Initiative ${id} not found.`);
22682
+ const candidate = ini.candidates.find((c) => c.id === candidateId);
22683
+ if (!candidate) throw new InitiativeWriteError(`Candidate ${candidateId} not found in ${id}.`);
22684
+ if (candidate.materializedAs) {
22685
+ throw new InitiativeWriteError(
22686
+ `Candidate ${candidateId} is already materialized as ${candidate.materializedAs}.`
22687
+ );
22688
+ }
22689
+ const wiId = nextWorkItemId3(dir);
22690
+ const fileName = `${wiId}-${slugify6(candidate.title)}.md`;
22691
+ ensureDir(join(dir, DRAFT_DIR2));
22692
+ writeFile(join(dir, DRAFT_DIR2, fileName), buildWorkItemContent(wiId, ini.id, candidate));
22693
+ const raw = readFile(ini.filePath);
22694
+ const { data, content } = matter18(raw, {});
22695
+ const cands = Array.isArray(data.candidates) ? data.candidates : [];
22696
+ for (const c of cands) {
22697
+ if (c && typeof c === "object" && String(c.id) === candidateId) c.materialized_as = wiId;
22698
+ }
22699
+ data.candidates = cands;
22700
+ const newContent = matter18.stringify(content, data);
22701
+ writeFile(ini.filePath, newContent);
22702
+ const updated = parseInitiative(dir, ini.filePath, newContent);
22703
+ if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after materialization.");
22704
+ return { workItemId: wiId, fileName, initiative: updated };
22705
+ }
22706
+
22707
+ // src/commands/initiative.ts
22708
+ function requireInit(dir) {
22709
+ if (!loadConfig(dir)) {
22710
+ log.error("Kaddo is not initialized. Run `kaddo init` first.");
22711
+ process.exit(1);
22712
+ }
22713
+ }
22714
+ function runInitiativeList() {
22715
+ const dir = cwd();
22716
+ requireInit(dir);
22717
+ intro("kaddo initiative list");
22718
+ const all = discoverInitiatives(dir);
22719
+ if (all.length === 0) {
22720
+ log.info("No initiatives yet. Create one with `kaddo initiative create`.");
22721
+ outro("Nothing to show.");
22722
+ return;
22723
+ }
22724
+ for (const ini of all) {
22725
+ const p = computeInitiativeProgress(dir, ini);
22726
+ log.info(
22727
+ `${ini.id} \u2014 ${ini.title} [${ini.status}] planning ${p.planning.materialized}/${p.planning.totalCandidates} \xB7 delivery ${p.delivery.byState.completed}/${p.delivery.total} completed`
22728
+ );
22729
+ }
22730
+ outro(`${all.length} initiative(s).`);
22731
+ }
22732
+ function runInitiativeShow(id) {
22733
+ const dir = cwd();
22734
+ requireInit(dir);
22735
+ intro(`kaddo initiative show ${id}`);
22736
+ const ini = getInitiative(dir, id);
22737
+ if (!ini) {
22738
+ log.error(`Initiative ${id} not found.`);
22739
+ process.exit(1);
22740
+ }
22741
+ log.info(` ${ini.id} \u2014 ${ini.title}`);
22742
+ log.info(` Status: ${ini.status}`);
22743
+ if (ini.horizon) log.info(` Horizon: ${ini.horizon}`);
22744
+ if (ini.priority) log.info(` Priority: ${ini.priority}`);
22745
+ if (ini.domains.length) log.info(` Domains: ${ini.domains.join(", ")}`);
22746
+ if (ini.relatedCapabilities.length) log.info(` Capabilities: ${ini.relatedCapabilities.join(", ")}`);
22747
+ if (ini.source) log.info(` Source: ${ini.source}${ini.sourceId ? ` (${ini.sourceId})` : ""}`);
22748
+ log.info(` Candidates: ${ini.candidates.length}`);
22749
+ for (const c of ini.candidates) {
22750
+ log.info(` - ${c.id}: ${c.title}${c.materializedAs ? ` \u2192 ${c.materializedAs}` : " (pending)"}`);
22751
+ }
22752
+ outro(`Initiative ${ini.id}.`);
22753
+ }
22754
+ function runInitiativeProgress(id) {
22755
+ const dir = cwd();
22756
+ requireInit(dir);
22757
+ intro(`kaddo initiative progress ${id}`);
22758
+ const ini = getInitiative(dir, id);
22759
+ if (!ini) {
22760
+ log.error(`Initiative ${id} not found.`);
22761
+ process.exit(1);
22762
+ }
22763
+ const p = computeInitiativeProgress(dir, ini);
22764
+ log.info(` Status: ${p.status}`);
22765
+ log.info("");
22766
+ log.info(` Planning: ${p.planning.materialized}/${p.planning.totalCandidates} candidates materialized (${p.planning.remaining} remaining)`);
22767
+ log.info("");
22768
+ log.info(` Delivery: ${p.delivery.total} associated Work Items`);
22769
+ for (const [state, n] of Object.entries(p.delivery.byState)) {
22770
+ if (n > 0) log.info(` ${state}: ${n}`);
22771
+ }
22772
+ outro(`Progress for ${ini.id}.`);
22773
+ }
22774
+ function runInitiativeCandidates(id) {
22775
+ const dir = cwd();
22776
+ requireInit(dir);
22777
+ intro(`kaddo initiative candidates ${id}`);
22778
+ const ini = getInitiative(dir, id);
22779
+ if (!ini) {
22780
+ log.error(`Initiative ${id} not found.`);
22781
+ process.exit(1);
22782
+ }
22783
+ if (ini.candidates.length === 0) {
22784
+ log.info("No candidates on this initiative.");
22785
+ outro("Nothing to show.");
22786
+ return;
22787
+ }
22788
+ for (const c of ini.candidates) {
22789
+ log.info(` ${c.id}: ${c.title}${c.materializedAs ? ` \u2192 ${c.materializedAs}` : " (pending)"}`);
22790
+ if (c.expectedValue) log.info(` value: ${c.expectedValue}`);
22791
+ }
22792
+ outro(`${ini.candidates.length} candidate(s).`);
22793
+ }
22794
+ async function runInitiativeCreate(opts) {
22795
+ const dir = cwd();
22796
+ requireInit(dir);
22797
+ intro("kaddo initiative create");
22798
+ const title = opts.title?.trim() || (await text({
22799
+ message: "Initiative title",
22800
+ validate: (v) => v.trim().length === 0 ? "Title is required." : void 0
22801
+ })).trim();
22802
+ try {
22803
+ const ini = createInitiative(dir, { title });
22804
+ log.success(`Created ${ini.id} \u2014 ${ini.title}`);
22805
+ log.info(` knowledge/delivery/initiatives/`);
22806
+ outro(`Initiative ${ini.id} created.`);
22807
+ } catch (err) {
22808
+ log.error(err instanceof InitiativeWriteError ? err.message : String(err));
22809
+ process.exit(1);
22810
+ }
22811
+ }
22812
+ async function runInitiativeUpdate(id, opts) {
22813
+ const dir = cwd();
22814
+ requireInit(dir);
22815
+ intro(`kaddo initiative update ${id}`);
22816
+ const ini = getInitiative(dir, id);
22817
+ if (!ini) {
22818
+ log.error(`Initiative ${id} not found.`);
22819
+ process.exit(1);
22820
+ }
22821
+ const to = opts.status ?? await select({
22822
+ message: "New status",
22823
+ options: [
22824
+ { value: "planned", label: "planned" },
22825
+ { value: "in-progress", label: "in-progress" },
22826
+ { value: "completed", label: "completed" },
22827
+ { value: "deferred", label: "deferred" },
22828
+ { value: "cancelled", label: "cancelled" }
22829
+ ]
22830
+ });
22831
+ try {
22832
+ const updated = transitionInitiative(dir, id, to);
22833
+ log.success(`Status: ${updated.status}`);
22834
+ outro(`Initiative ${updated.id} updated.`);
22835
+ } catch (err) {
22836
+ log.error(err instanceof InitiativeWriteError ? err.message : String(err));
22837
+ process.exit(1);
22838
+ }
22839
+ }
22840
+ function runInitiativeMaterialize(id, candidateId) {
22841
+ const dir = cwd();
22842
+ requireInit(dir);
22843
+ intro(`kaddo initiative materialize ${id} ${candidateId}`);
22844
+ try {
22845
+ const result = materializeCandidate(dir, id, candidateId);
22846
+ log.success(`Materialized ${candidateId} \u2192 ${result.workItemId}`);
22847
+ log.info(` knowledge/delivery/work-items/draft/${result.fileName}`);
22848
+ log.info(` Associated to ${id} via \`initiative: ${id}\`.`);
22849
+ outro(`Work Item ${result.workItemId} created from candidate.`);
22850
+ } catch (err) {
22851
+ log.error(err instanceof InitiativeWriteError ? err.message : String(err));
22852
+ process.exit(1);
22853
+ }
22854
+ }
22855
+
22295
22856
  // src/index.ts
22296
22857
  var require2 = createRequire(import.meta.url);
22297
22858
  var { version } = require2("../package.json");
@@ -22469,6 +23030,28 @@ program.command("add [module]").description("Install an optional Kaddo module (a
22469
23030
  program.command("admin").description("Start Kaddo Admin \u2014 a local web interface for the project knowledge").option("--port <port>", "Server port (default: 4173)", parseInt).option("--host <host>", "Server host (default: 127.0.0.1)").option("--no-open", "Do not open the browser automatically").action(async (opts) => {
22470
23031
  await runAdmin({ port: opts.port, host: opts.host, noOpen: opts.open === false });
22471
23032
  });
23033
+ var initiativeCmd = program.command("initiative").description("Manage initiatives \u2014 the optional outcome layer over Work Items");
23034
+ initiativeCmd.command("list").description("List initiatives with planning and delivery progress").action(() => {
23035
+ runInitiativeList();
23036
+ });
23037
+ initiativeCmd.command("show <id>").description("Show an initiative, its metadata and candidates").action((id) => {
23038
+ runInitiativeShow(id);
23039
+ });
23040
+ initiativeCmd.command("progress <id>").description("Show planning coverage and delivery progress for an initiative").action((id) => {
23041
+ runInitiativeProgress(id);
23042
+ });
23043
+ initiativeCmd.command("candidates <id>").description("List the Work Item candidates of an initiative").action((id) => {
23044
+ runInitiativeCandidates(id);
23045
+ });
23046
+ initiativeCmd.command("create").description("Create a new initiative").option("--title <title>", "Initiative title (prompts if omitted)").action(async (opts) => {
23047
+ await runInitiativeCreate(opts);
23048
+ });
23049
+ initiativeCmd.command("update <id>").description("Update an initiative status (valid lifecycle transitions only)").option("--status <status>", "New status: planned, in-progress, completed, deferred, cancelled").action(async (id, opts) => {
23050
+ await runInitiativeUpdate(id, opts);
23051
+ });
23052
+ initiativeCmd.command("materialize <id> <candidateId>").description("Materialize an initiative candidate into a draft Work Item").action((id, candidateId) => {
23053
+ runInitiativeMaterialize(id, candidateId);
23054
+ });
22472
23055
  var telemetryCmd = program.command("telemetry").description("Manage anonymous usage telemetry");
22473
23056
  telemetryCmd.command("status").description("Show telemetry status (enabled, registered, pending events)").action(() => {
22474
23057
  runTelemetryStatus();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kaddo/cli",
3
- "version": "3.104.0",
3
+ "version": "3.106.0",
4
4
  "description": "Knowledge Driven Development toolkit",
5
5
  "license": "MIT",
6
6
  "repository": {