@kaddo/cli 3.124.4 → 3.125.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 (36) hide show
  1. package/dist/admin-dist/assets/{architectureDiagram-3BPJPVTR-Bf-HvJ1Z.js → architectureDiagram-3BPJPVTR-Rtpa6T1Z.js} +1 -1
  2. package/dist/admin-dist/assets/{chunk-727SXJPM-ClhePGXw.js → chunk-727SXJPM-D0IPGrFO.js} +1 -1
  3. package/dist/admin-dist/assets/{chunk-AQP2D5EJ-6XNz6ELl.js → chunk-AQP2D5EJ-B5u711rj.js} +1 -1
  4. package/dist/admin-dist/assets/{classDiagram-v2-Q7XG4LA2-Dak_aejZ.js → classDiagram-4FO5ZUOK-B6g4N7KV.js} +1 -1
  5. package/dist/admin-dist/assets/{classDiagram-4FO5ZUOK-Dak_aejZ.js → classDiagram-v2-Q7XG4LA2-B6g4N7KV.js} +1 -1
  6. package/dist/admin-dist/assets/{dagre-BM42HDAG-CzGfT3A1.js → dagre-BM42HDAG-BcuopJ2-.js} +1 -1
  7. package/dist/admin-dist/assets/{diagram-2AECGRRQ-CTOSLKXV.js → diagram-2AECGRRQ-DiqICCsP.js} +1 -1
  8. package/dist/admin-dist/assets/{diagram-5GNKFQAL-DtrHLRNL.js → diagram-5GNKFQAL-B1Cwxlde.js} +1 -1
  9. package/dist/admin-dist/assets/{diagram-LMA3HP47-XgeGDWDX.js → diagram-LMA3HP47-DZAncExj.js} +1 -1
  10. package/dist/admin-dist/assets/{diagram-OG6HWLK6-Ct81U7Cu.js → diagram-OG6HWLK6-lBaQqvc9.js} +1 -1
  11. package/dist/admin-dist/assets/{erDiagram-TEJ5UH35-BQKfuN9V.js → erDiagram-TEJ5UH35-ADAEF9j2.js} +1 -1
  12. package/dist/admin-dist/assets/{flowDiagram-I6XJVG4X-duNCHH8m.js → flowDiagram-I6XJVG4X-0v986Mee.js} +1 -1
  13. package/dist/admin-dist/assets/{ganttDiagram-6RSMTGT7-CdX3ioQS.js → ganttDiagram-6RSMTGT7-Drv2mWjq.js} +1 -1
  14. package/dist/admin-dist/assets/{index-Bht5nnnB.js → index-DFugfSm-.js} +53 -53
  15. package/dist/admin-dist/assets/index-ekyeZH2V.css +2 -0
  16. package/dist/admin-dist/assets/{infoDiagram-5YYISTIA-BhmF-Wrb.js → infoDiagram-5YYISTIA-CHFdC6lD.js} +1 -1
  17. package/dist/admin-dist/assets/{ishikawaDiagram-YF4QCWOH-R0-zDUcd.js → ishikawaDiagram-YF4QCWOH-BKCJRQRe.js} +1 -1
  18. package/dist/admin-dist/assets/{kanban-definition-UN3LZRKU-DxCs8FgR.js → kanban-definition-UN3LZRKU-BfjPjt1T.js} +1 -1
  19. package/dist/admin-dist/assets/{linear-BcBNcPq4.js → linear-DxfQIps4.js} +1 -1
  20. package/dist/admin-dist/assets/{mindmap-definition-RKZ34NQL-CGRPxnXA.js → mindmap-definition-RKZ34NQL-BZpX-Ep3.js} +1 -1
  21. package/dist/admin-dist/assets/{pieDiagram-4H26LBE5-CzRqbJlG.js → pieDiagram-4H26LBE5-C3d8NIsK.js} +1 -1
  22. package/dist/admin-dist/assets/{quadrantDiagram-W4KKPZXB-D3MvUaaK.js → quadrantDiagram-W4KKPZXB-D1gnR57w.js} +1 -1
  23. package/dist/admin-dist/assets/{requirementDiagram-4Y6WPE33-LeXKuaNM.js → requirementDiagram-4Y6WPE33-EWKDboM9.js} +1 -1
  24. package/dist/admin-dist/assets/{sequenceDiagram-3UESZ5HK-CisjzAeU.js → sequenceDiagram-3UESZ5HK-5bTESgbD.js} +1 -1
  25. package/dist/admin-dist/assets/{stateDiagram-AJRCARHV-Ckz_YV-g.js → stateDiagram-AJRCARHV-EJpT9JyC.js} +1 -1
  26. package/dist/admin-dist/assets/{stateDiagram-v2-BHNVJYJU-BQL9PwTU.js → stateDiagram-v2-BHNVJYJU-CeUANvv7.js} +1 -1
  27. package/dist/admin-dist/assets/{timeline-definition-PNZ67QCA-DdT4yCQE.js → timeline-definition-PNZ67QCA-BlBAaPs5.js} +1 -1
  28. package/dist/admin-dist/assets/{vennDiagram-CIIHVFJN-DdPmvnd8.js → vennDiagram-CIIHVFJN-CFzqZSE2.js} +1 -1
  29. package/dist/admin-dist/assets/{wardleyDiagram-YWT4CUSO-Bzactu5G.js → wardleyDiagram-YWT4CUSO-C45BZ2wq.js} +1 -1
  30. package/dist/admin-dist/assets/{xychartDiagram-2RQKCTM6-AHL4ky3j.js → xychartDiagram-2RQKCTM6-BFsQVcMX.js} +1 -1
  31. package/dist/admin-dist/index.html +2 -2
  32. package/dist/admin-server/index.js +59 -7
  33. package/dist/core.js +1836 -133
  34. package/dist/index.js +3005 -2530
  35. package/package.json +1 -1
  36. package/dist/admin-dist/assets/index-CS-lPjXU.css +0 -2
package/dist/core.js CHANGED
@@ -141,8 +141,8 @@ function loadConfig(dir) {
141
141
  const parsed = configSchema.safeParse(raw ?? {});
142
142
  if (!parsed.success) {
143
143
  const issues = parsed.error.issues.map((i) => {
144
- const path6 = i.path.join(".");
145
- return path6 ? ` - ${path6}: ${i.message}` : ` - ${i.message}`;
144
+ const path8 = i.path.join(".");
145
+ return path8 ? ` - ${path8}: ${i.message}` : ` - ${i.message}`;
146
146
  }).join("\n");
147
147
  throw new ConfigError(`Invalid .kaddo/config.yml:
148
148
  ${issues}`);
@@ -394,11 +394,11 @@ function moduleArtifactCoverage(dir, id) {
394
394
  };
395
395
  }
396
396
  function loadMappedModules(dir) {
397
- const path6 = join(dir, DESCRIPTOR_PATH);
398
- if (!exists(path6)) return [];
397
+ const path8 = join(dir, DESCRIPTOR_PATH);
398
+ if (!exists(path8)) return [];
399
399
  let parsed;
400
400
  try {
401
- parsed = parseYaml3(readFile(path6));
401
+ parsed = parseYaml3(readFile(path8));
402
402
  } catch {
403
403
  return [];
404
404
  }
@@ -1629,7 +1629,7 @@ function sectionParagraph(md, title) {
1629
1629
  }
1630
1630
  return "";
1631
1631
  }
1632
- function parseCapsule(id, path6, md) {
1632
+ function parseCapsule(id, path8, md) {
1633
1633
  const { data } = matter2(md);
1634
1634
  const updatedAt = data.updated_at ? String(data.updated_at) : void 0;
1635
1635
  let ageDays = null;
@@ -1639,7 +1639,7 @@ function parseCapsule(id, path6, md) {
1639
1639
  }
1640
1640
  return {
1641
1641
  id,
1642
- path: path6,
1642
+ path: path8,
1643
1643
  system: data.system ? String(data.system) : id,
1644
1644
  owner: data.owner ? String(data.owner) : void 0,
1645
1645
  updatedAt,
@@ -2344,9 +2344,9 @@ function buildGraph(dir, config, opts = {}, now = /* @__PURE__ */ new Date()) {
2344
2344
  ];
2345
2345
  const presentLayers = [];
2346
2346
  for (const layer of layerDocs) {
2347
- const path6 = layer.files.map((f) => `${KNOWLEDGE2}/${f}`).find((rel) => exists(join(dir, rel)));
2348
- if (path6) {
2349
- addNode({ id: layer.id, type: layer.type, label: layer.label, path: path6 });
2347
+ const path8 = layer.files.map((f) => `${KNOWLEDGE2}/${f}`).find((rel) => exists(join(dir, rel)));
2348
+ if (path8) {
2349
+ addNode({ id: layer.id, type: layer.type, label: layer.label, path: path8 });
2350
2350
  presentLayers.push(layer.id);
2351
2351
  }
2352
2352
  }
@@ -3490,14 +3490,14 @@ function discoverAgents(dir) {
3490
3490
  const base = join(dir, "knowledge", "agents");
3491
3491
  if (!exists(base) || !isDir(base)) return [];
3492
3492
  const out = /* @__PURE__ */ new Set();
3493
- const walk = (d) => {
3493
+ const walk2 = (d) => {
3494
3494
  for (const e of readDir(d)) {
3495
3495
  const full = join(d, e);
3496
- if (isDir(full)) walk(full);
3496
+ if (isDir(full)) walk2(full);
3497
3497
  else if (e.endsWith("-agent.md")) out.add(e.replace(/\.md$/, ""));
3498
3498
  }
3499
3499
  };
3500
- walk(base);
3500
+ walk2(base);
3501
3501
  return [...out].sort();
3502
3502
  }
3503
3503
  function buildCodexAdapterContext(dir) {
@@ -3752,13 +3752,13 @@ function meaningful(text2) {
3752
3752
  });
3753
3753
  }
3754
3754
  function readPocSummary(dir) {
3755
- const path6 = join(dir, POC_ARTIFACT_PATH);
3756
- if (!exists(path6)) {
3755
+ const path8 = join(dir, POC_ARTIFACT_PATH);
3756
+ if (!exists(path8)) {
3757
3757
  return { exists: false, hypothesisDefined: false, successCriteriaCount: 0, constraintsDefined: false, nonGoalsDefined: false, conclusion: "pending" };
3758
3758
  }
3759
3759
  let markdown = "";
3760
3760
  try {
3761
- markdown = readFile(path6);
3761
+ markdown = readFile(path8);
3762
3762
  } catch {
3763
3763
  return { exists: false, hypothesisDefined: false, successCriteriaCount: 0, constraintsDefined: false, nonGoalsDefined: false, conclusion: "pending" };
3764
3764
  }
@@ -3793,11 +3793,11 @@ function redactSecrets(value) {
3793
3793
  return line.replace(/([:=]\s*)\S+.*/, "$1[redacted]");
3794
3794
  }).join("\n");
3795
3795
  }
3796
- function source(dir, path6, kind) {
3797
- const absolute = join(dir, path6);
3796
+ function source(dir, path8, kind) {
3797
+ const absolute = join(dir, path8);
3798
3798
  if (!exists(absolute)) return null;
3799
3799
  const raw = readFile(absolute);
3800
- return { path: posix(path6), kind, digest: sha(raw), content: redactSecrets(raw) };
3800
+ return { path: posix(path8), kind, digest: sha(raw), content: redactSecrets(raw) };
3801
3801
  }
3802
3802
  function reportFiles(dir) {
3803
3803
  const delivery = join(dir, "knowledge", "delivery");
@@ -3837,9 +3837,9 @@ function buildPocReportContext(dir) {
3837
3837
  };
3838
3838
  }
3839
3839
  const sources = [];
3840
- const add = (path6, kind) => {
3841
- if (sources.some((item2) => item2.path === posix(path6))) return;
3842
- const item = source(dir, path6, kind);
3840
+ const add = (path8, kind) => {
3841
+ if (sources.some((item2) => item2.path === posix(path8))) return;
3842
+ const item = source(dir, path8, kind);
3843
3843
  if (item) sources.push(item);
3844
3844
  };
3845
3845
  add(POC_ARTIFACT_PATH, "poc");
@@ -3867,7 +3867,7 @@ function buildPocReportContext(dir) {
3867
3867
  const sourceFingerprint = sha(sources.map((item) => `${item.path}\0${item.digest}`).join("\n"));
3868
3868
  const status = !latestReport ? "missing" : latestReport.sourceFingerprint === sourceFingerprint ? "current" : "stale";
3869
3869
  const currentManifest = Object.fromEntries(sources.map((item) => [item.path, item.digest]));
3870
- const changesSinceLatest = status === "stale" ? [.../* @__PURE__ */ new Set([...Object.keys(currentManifest), ...Object.keys(latestReport?.sourceManifest ?? {})])].filter((path6) => currentManifest[path6] !== latestReport?.sourceManifest[path6]).sort() : [];
3870
+ const changesSinceLatest = status === "stale" ? [.../* @__PURE__ */ new Set([...Object.keys(currentManifest), ...Object.keys(latestReport?.sourceManifest ?? {})])].filter((path8) => currentManifest[path8] !== latestReport?.sourceManifest[path8]).sort() : [];
3871
3871
  const sourceList = sources.map((item) => `- ${item.path} (${item.kind})`).join("\n") || "- No sources selected.";
3872
3872
  return {
3873
3873
  eligible: true,
@@ -4043,10 +4043,10 @@ function resolveNextStep(dir, now = /* @__PURE__ */ new Date()) {
4043
4043
  const q = (rel) => analyzeKnowledgeArtifact(dir, rel);
4044
4044
  const resolveAgent = (agent) => {
4045
4045
  const file = agent.endsWith(".md") ? agent : `${agent}.md`;
4046
- const path6 = agentInstallPath(file);
4047
- const installed = isFile(join(dir, path6));
4046
+ const path8 = agentInstallPath(file);
4047
+ const installed = isFile(join(dir, path8));
4048
4048
  const group = agentGroupOf(file);
4049
- return { agentPath: path6, agentInstalled: installed, installCommand: installed ? void 0 : `kaddo add agents --group ${group}` };
4049
+ return { agentPath: path8, agentInstalled: installed, installCommand: installed ? void 0 : `kaddo add agents --group ${group}` };
4050
4050
  };
4051
4051
  const moduleRepo = isModule(config);
4052
4052
  const coreRepo = isCore(config);
@@ -5592,8 +5592,8 @@ function withResponsibilityTrace(fileName, content) {
5592
5592
  const skills = renderSkillsSection(agent);
5593
5593
  const skillsBlock = skills ? `${skills}
5594
5594
  ` : "";
5595
- const frontmatter = renderFrontmatterRules(agent);
5596
- const frontmatterBlock = frontmatter ? `${frontmatter}
5595
+ const frontmatter2 = renderFrontmatterRules(agent);
5596
+ const frontmatterBlock = frontmatter2 ? `${frontmatter2}
5597
5597
  ` : "";
5598
5598
  return `${content.trimEnd()}
5599
5599
 
@@ -7943,23 +7943,23 @@ var VALID_SOURCES = [
7943
7943
  function isValidSource(s) {
7944
7944
  return VALID_SOURCES.includes(s);
7945
7945
  }
7946
- function parseWorkItemSource(frontmatter) {
7947
- const rawSource = frontmatter.source;
7946
+ function parseWorkItemSource(frontmatter2) {
7947
+ const rawSource = frontmatter2.source;
7948
7948
  if (rawSource != null && typeof rawSource === "object" && !Array.isArray(rawSource)) {
7949
7949
  const obj = rawSource;
7950
7950
  const t = optStr2(obj.type);
7951
7951
  const type = t && isValidSource(t) ? t : "unknown";
7952
7952
  return {
7953
7953
  type,
7954
- id: optStr2(obj.id) ?? optStr2(frontmatter.source_id),
7955
- title: optStr2(obj.title) ?? optStr2(frontmatter.source_title),
7956
- context: optStr2(obj.context) ?? optStr2(frontmatter.source_context),
7957
- provider: optStr2(obj.provider) ?? optStr2(frontmatter.source_provider),
7958
- integration: optStr2(obj.integration) ?? optStr2(frontmatter.source_integration),
7959
- url: optStr2(obj.url) ?? optStr2(frontmatter.source_url),
7960
- imported_at: optStr2(obj.imported_at) ?? optStr2(frontmatter.source_imported_at),
7961
- external_updated_at: optStr2(obj.external_updated_at) ?? optStr2(frontmatter.source_external_updated_at),
7962
- synced_at: optStr2(obj.synced_at) ?? optStr2(frontmatter.source_synced_at),
7954
+ id: optStr2(obj.id) ?? optStr2(frontmatter2.source_id),
7955
+ title: optStr2(obj.title) ?? optStr2(frontmatter2.source_title),
7956
+ context: optStr2(obj.context) ?? optStr2(frontmatter2.source_context),
7957
+ provider: optStr2(obj.provider) ?? optStr2(frontmatter2.source_provider),
7958
+ integration: optStr2(obj.integration) ?? optStr2(frontmatter2.source_integration),
7959
+ url: optStr2(obj.url) ?? optStr2(frontmatter2.source_url),
7960
+ imported_at: optStr2(obj.imported_at) ?? optStr2(frontmatter2.source_imported_at),
7961
+ external_updated_at: optStr2(obj.external_updated_at) ?? optStr2(frontmatter2.source_external_updated_at),
7962
+ synced_at: optStr2(obj.synced_at) ?? optStr2(frontmatter2.source_synced_at),
7963
7963
  inferred: obj.inferred === true || obj.inferred === "true",
7964
7964
  reason: t && !isValidSource(t) ? `Invalid source type in object: "${t}".` : void 0
7965
7965
  };
@@ -7968,45 +7968,45 @@ function parseWorkItemSource(frontmatter) {
7968
7968
  if (raw && isValidSource(raw)) {
7969
7969
  return {
7970
7970
  type: raw,
7971
- id: optStr2(frontmatter.source_id),
7972
- title: optStr2(frontmatter.source_title),
7973
- context: optStr2(frontmatter.source_context),
7974
- provider: optStr2(frontmatter.source_provider),
7975
- url: optStr2(frontmatter.source_url),
7976
- imported_at: optStr2(frontmatter.source_imported_at),
7977
- external_updated_at: optStr2(frontmatter.source_external_updated_at),
7978
- synced_at: optStr2(frontmatter.source_synced_at),
7971
+ id: optStr2(frontmatter2.source_id),
7972
+ title: optStr2(frontmatter2.source_title),
7973
+ context: optStr2(frontmatter2.source_context),
7974
+ provider: optStr2(frontmatter2.source_provider),
7975
+ url: optStr2(frontmatter2.source_url),
7976
+ imported_at: optStr2(frontmatter2.source_imported_at),
7977
+ external_updated_at: optStr2(frontmatter2.source_external_updated_at),
7978
+ synced_at: optStr2(frontmatter2.source_synced_at),
7979
7979
  inferred: false
7980
7980
  };
7981
7981
  }
7982
7982
  if (raw && !isValidSource(raw)) {
7983
7983
  return {
7984
7984
  type: "unknown",
7985
- id: optStr2(frontmatter.source_id),
7986
- title: optStr2(frontmatter.source_title),
7987
- context: optStr2(frontmatter.source_context),
7988
- provider: optStr2(frontmatter.source_provider),
7989
- url: optStr2(frontmatter.source_url),
7990
- imported_at: optStr2(frontmatter.source_imported_at),
7991
- external_updated_at: optStr2(frontmatter.source_external_updated_at),
7992
- synced_at: optStr2(frontmatter.source_synced_at),
7985
+ id: optStr2(frontmatter2.source_id),
7986
+ title: optStr2(frontmatter2.source_title),
7987
+ context: optStr2(frontmatter2.source_context),
7988
+ provider: optStr2(frontmatter2.source_provider),
7989
+ url: optStr2(frontmatter2.source_url),
7990
+ imported_at: optStr2(frontmatter2.source_imported_at),
7991
+ external_updated_at: optStr2(frontmatter2.source_external_updated_at),
7992
+ synced_at: optStr2(frontmatter2.source_synced_at),
7993
7993
  inferred: true,
7994
7994
  reason: `Invalid source value: "${raw}".`
7995
7995
  };
7996
7996
  }
7997
- if (frontmatter.source_work_item_candidate || frontmatter.source_roadmap_initiative) {
7997
+ if (frontmatter2.source_work_item_candidate || frontmatter2.source_roadmap_initiative) {
7998
7998
  return {
7999
7999
  type: "roadmap",
8000
- id: optStr2(frontmatter.source_id) ?? optStr2(frontmatter.source_work_item_candidate),
8001
- title: optStr2(frontmatter.source_initiative_title),
8000
+ id: optStr2(frontmatter2.source_id) ?? optStr2(frontmatter2.source_work_item_candidate),
8001
+ title: optStr2(frontmatter2.source_initiative_title),
8002
8002
  inferred: true,
8003
8003
  reason: "Inferred from legacy roadmap fields."
8004
8004
  };
8005
8005
  }
8006
- if (frontmatter.source_id) {
8006
+ if (frontmatter2.source_id) {
8007
8007
  return {
8008
8008
  type: "unknown",
8009
- id: optStr2(frontmatter.source_id),
8009
+ id: optStr2(frontmatter2.source_id),
8010
8010
  inferred: true,
8011
8011
  reason: "Has source_id but no source type."
8012
8012
  };
@@ -8959,10 +8959,1263 @@ function buildProjectExplanation(dir) {
8959
8959
  };
8960
8960
  }
8961
8961
 
8962
+ // src/core/impact-report.ts
8963
+ import matter10 from "gray-matter";
8964
+
8965
+ // src/core/guard-history.ts
8966
+ var HISTORY_DIR = ".kaddo/history";
8967
+ var RUNS_PATH = `${HISTORY_DIR}/guard-runs.jsonl`;
8968
+ var SUMMARY_PATH = `${HISTORY_DIR}/guard-summary.json`;
8969
+ function toPosix5(p) {
8970
+ return p.replace(/\\/g, "/");
8971
+ }
8972
+ function loadGuardRuns(dir) {
8973
+ const p = join(dir, RUNS_PATH);
8974
+ if (!exists(p)) return [];
8975
+ const out = [];
8976
+ for (const line of readFile(p).split(/\r?\n/)) {
8977
+ const t = line.trim();
8978
+ if (!t) continue;
8979
+ try {
8980
+ out.push(JSON.parse(t));
8981
+ } catch {
8982
+ }
8983
+ }
8984
+ return out;
8985
+ }
8986
+ function resolveDriftThreads(runs) {
8987
+ const sorted = [...runs].sort((a, b) => a.generated_at.localeCompare(b.generated_at));
8988
+ const paths = /* @__PURE__ */ new Set();
8989
+ for (const r of sorted) for (const w of r.warnings) paths.add(w.code_path);
8990
+ const threads = [];
8991
+ for (const codePath of paths) {
8992
+ const related = /* @__PURE__ */ new Set();
8993
+ let firstDetected = "";
8994
+ let lastWarn = "";
8995
+ for (const r of sorted) {
8996
+ const w = r.warnings.find((x) => x.code_path === codePath);
8997
+ if (w) {
8998
+ if (!firstDetected) firstDetected = r.generated_at;
8999
+ lastWarn = r.generated_at;
9000
+ for (const a of w.related_artifacts) related.add(a);
9001
+ }
9002
+ }
9003
+ let resolvedAt;
9004
+ for (const r of sorted) {
9005
+ if (r.generated_at <= lastWarn) continue;
9006
+ const touched = r.touched_files.some((f) => toPosix5(f) === codePath);
9007
+ const warnedHere = r.warnings.some((x) => x.code_path === codePath);
9008
+ const updatedRelated = r.updated_artifacts.some((a) => related.has(a));
9009
+ if (touched && updatedRelated && !warnedHere) {
9010
+ resolvedAt = r.generated_at;
9011
+ break;
9012
+ }
9013
+ }
9014
+ threads.push({
9015
+ code_path: codePath,
9016
+ related_artifacts: [...related],
9017
+ first_detected: firstDetected,
9018
+ last_seen: lastWarn,
9019
+ status: resolvedAt ? "resolved" : "open",
9020
+ ...resolvedAt ? { resolved_at: resolvedAt } : {}
9021
+ });
9022
+ }
9023
+ return threads;
9024
+ }
9025
+ function hotspotDir(codePath) {
9026
+ const i = codePath.lastIndexOf("/");
9027
+ return i >= 0 ? codePath.slice(0, i + 1) : codePath;
9028
+ }
9029
+ function computeTrend(runs) {
9030
+ if (runs.length < 2) return { direction: "unknown", reason: "Not enough recorded runs to detect a trend." };
9031
+ const sorted = [...runs].sort((a, b) => a.generated_at.localeCompare(b.generated_at));
9032
+ const mid = Math.floor(sorted.length / 2);
9033
+ const avg = (arr) => arr.length ? arr.reduce((s, r) => s + r.warnings.length, 0) / arr.length : 0;
9034
+ const earlier = avg(sorted.slice(0, mid));
9035
+ const recent = avg(sorted.slice(mid));
9036
+ if (recent < earlier) return { direction: "improving", reason: "Fewer warnings in the last recorded runs." };
9037
+ if (recent > earlier) return { direction: "worsening", reason: "More warnings in the last recorded runs." };
9038
+ return { direction: "stable", reason: "Warning volume is roughly stable across recorded runs." };
9039
+ }
9040
+ function buildGuardHistory(dir) {
9041
+ const runs = loadGuardRuns(dir);
9042
+ if (runs.length === 0) {
9043
+ return {
9044
+ available: false,
9045
+ total_runs: 0,
9046
+ first_run: null,
9047
+ last_run: null,
9048
+ runs_with_warnings: 0,
9049
+ runs_clean: 0,
9050
+ detected: 0,
9051
+ open: 0,
9052
+ resolved: 0,
9053
+ resolution_rate: 0,
9054
+ threads: [],
9055
+ hotspots: [],
9056
+ trend: { direction: "unknown", reason: "No guard history recorded yet." }
9057
+ };
9058
+ }
9059
+ const sorted = [...runs].sort((a, b) => a.generated_at.localeCompare(b.generated_at));
9060
+ const threads = resolveDriftThreads(sorted);
9061
+ const open = threads.filter((t) => t.status === "open").length;
9062
+ const resolved = threads.filter((t) => t.status === "resolved").length;
9063
+ const detected = threads.length;
9064
+ const runsWithWarnings = sorted.filter((r) => r.warnings.length > 0).length;
9065
+ const hotspotMap = /* @__PURE__ */ new Map();
9066
+ for (const t of threads) {
9067
+ const d = hotspotDir(t.code_path);
9068
+ hotspotMap.set(d, (hotspotMap.get(d) ?? 0) + 1);
9069
+ }
9070
+ const hotspots = [...hotspotMap.entries()].map(([path8, warnings]) => ({ path: path8, warnings })).sort((a, b) => b.warnings - a.warnings);
9071
+ return {
9072
+ available: true,
9073
+ total_runs: sorted.length,
9074
+ first_run: sorted[0].generated_at,
9075
+ last_run: sorted[sorted.length - 1].generated_at,
9076
+ runs_with_warnings: runsWithWarnings,
9077
+ runs_clean: sorted.length - runsWithWarnings,
9078
+ detected,
9079
+ open,
9080
+ resolved,
9081
+ resolution_rate: detected > 0 ? Math.round(resolved / detected * 1e3) / 10 : 0,
9082
+ threads,
9083
+ hotspots,
9084
+ trend: computeTrend(sorted)
9085
+ };
9086
+ }
9087
+
9088
+ // src/core/reporting-evidence.ts
9089
+ function graphHintFinding(hint) {
9090
+ const affected = [hint.artifact_id, ...hint.path ? [hint.path] : []];
9091
+ const semantics = {
9092
+ "work-item": { classification: "coverage_gap", priority: "medium", action: "Review whether the active Work Item needs the missing declared relationship." },
9093
+ decision: { classification: "coverage_gap", priority: "low", action: "Review whether this decision should declare governed code paths." },
9094
+ capability: { classification: "coverage_gap", priority: "low", action: "Review whether this capability should connect to existing Work Items; the relationship is optional." },
9095
+ "knowledge-capsule": { classification: "review_hint", priority: "low", action: "Confirm whether this capsule is intended for direct contextual use or Work Item relationships." }
9096
+ };
9097
+ const semantic = semantics[hint.artifact_type];
9098
+ return {
9099
+ id: `graph-hint:${hint.artifact_id}:${hint.missing.join(",")}`,
9100
+ category: "topology",
9101
+ classification: semantic.classification,
9102
+ resolution_status: "open",
9103
+ source: "graph-hints",
9104
+ affected_artifacts: affected,
9105
+ // Graph Hints are intentionally non-blocking; their type determines priority and meaning.
9106
+ priority: semantic.priority,
9107
+ evidence: hint.reason,
9108
+ explanation: hint.message,
9109
+ suggested_action: semantic.action
9110
+ };
9111
+ }
9112
+ function reportingProjectContext(dir) {
9113
+ const config = loadConfig(dir);
9114
+ if (!config) return { state: "unknown", mode: "unknown", repository_structure: "unknown" };
9115
+ return {
9116
+ state: config.project.state,
9117
+ mode: projectMode(config),
9118
+ repository_structure: config.project.structure
9119
+ };
9120
+ }
9121
+ function knowledgeLayerEvidence(context, layer, present) {
9122
+ const baseline = context.mode === "poc" ? ["Tech", "Delivery"] : ["Business", "Product", "Tech", "Delivery"];
9123
+ if (!baseline.includes(layer)) {
9124
+ return { id: `knowledge.${layer.toLowerCase()}`, label: `${layer} knowledge`, classification: "not_applicable", reason: "This layer is outside the configured POC baseline." };
9125
+ }
9126
+ return {
9127
+ id: `knowledge.${layer.toLowerCase()}`,
9128
+ label: `${layer} knowledge`,
9129
+ classification: present ? "observed" : "unknown",
9130
+ reason: present ? "A structured knowledge artifact is present." : "No structured artifact was found; absence is not proof that knowledge does not exist."
9131
+ };
9132
+ }
9133
+ function deliveryCapabilityEvidence(dir, context) {
9134
+ const initiatives = discoverInitiatives(dir);
9135
+ const resources = getResources(dir);
9136
+ const modules = loadMappedModules(dir);
9137
+ return [
9138
+ { id: "initiatives", label: "Initiatives", classification: initiatives.length ? "observed" : "not_applicable", reason: initiatives.length ? `${initiatives.length} optional Initiative artifact(s) were discovered.` : "Initiatives are optional and no Initiative artifacts were discovered." },
9139
+ { id: "resources", label: "Project Resources", classification: resources.length ? "observed" : "not_applicable", reason: resources.length ? `${resources.length} Project Resource artifact(s) were discovered.` : "Resources are optional and no Resource artifacts were discovered." },
9140
+ { id: "multirepo", label: "Multirepo mapping", classification: context.repository_structure === "multirepo" ? modules.length ? "observed" : "unknown" : "not_applicable", reason: context.repository_structure === "multirepo" ? modules.length ? `${modules.length} module mapping(s) were discovered.` : "Project is multirepo but no module mappings were found." : "The project is configured as a monorepo." }
9141
+ ];
9142
+ }
9143
+
9144
+ // src/core/impact-report.ts
9145
+ function isBroadGlob(glob) {
9146
+ if (!glob.endsWith("/**")) return false;
9147
+ const prefix = glob.slice(0, -3);
9148
+ return prefix.length > 0 && prefix.split("/").length <= 2;
9149
+ }
9150
+ function levelFromRatio(r) {
9151
+ if (r >= 0.9) return "Very High";
9152
+ if (r >= 0.7) return "High";
9153
+ if (r >= 0.4) return "Medium";
9154
+ return "Low";
9155
+ }
9156
+ function hasSection(body, re) {
9157
+ return body.split(/\r?\n/).some((l) => /^#{1,6}\s+/.test(l) && re.test(l));
9158
+ }
9159
+ function buildImpactReport(dir, opts = {}, now = /* @__PURE__ */ new Date()) {
9160
+ const resolvedScope = opts.scope ?? "all";
9161
+ const scopeSource = opts.scopeSource ?? (opts.scope ? "explicit" : "default");
9162
+ const exp = buildProjectExplanation(dir);
9163
+ const projectContext = reportingProjectContext(dir);
9164
+ const wis = discoverWorkItems(dir);
9165
+ const total = wis.length;
9166
+ const completedWis = wis.filter((wi) => wi.lifecycle === "completed");
9167
+ const verifiedWorkItems = completedWis.filter((wi) => wi.validationStatus === "passed").length;
9168
+ const failedValidationWorkItems = completedWis.filter((wi) => wi.validationStatus === "failed").length;
9169
+ const pendingValidationWorkItems = completedWis.filter((wi) => Boolean(wi.validationStatus) && !["passed", "failed"].includes(wi.validationStatus)).length;
9170
+ const notRecordedValidationWorkItems = completedWis.length - verifiedWorkItems - failedValidationWorkItems - pendingValidationWorkItems;
9171
+ let withOwnership = 0;
9172
+ let withSource = 0;
9173
+ let withInitiative = 0;
9174
+ let withLevel = 0;
9175
+ let withAcceptance = 0;
9176
+ let withDoD = 0;
9177
+ let withValidation = 0;
9178
+ const connectedRoadmapCandidates = /* @__PURE__ */ new Set();
9179
+ const globCounts = /* @__PURE__ */ new Map();
9180
+ const globOwners = /* @__PURE__ */ new Map();
9181
+ const gaps = {
9182
+ missing_source: [],
9183
+ missing_initiative: [],
9184
+ missing_code_ownership: [],
9185
+ missing_knowledge_level: [],
9186
+ missing_acceptance_criteria: [],
9187
+ missing_definition_of_done: [],
9188
+ missing_validation: [],
9189
+ broad_ownership_globs: [],
9190
+ ownership_overlaps: []
9191
+ };
9192
+ const gapItem = (wi, action) => ({
9193
+ id: wi.id || wi.title,
9194
+ title: wi.title,
9195
+ status: wi.lifecycle ?? wi.status,
9196
+ path: wi.relPath,
9197
+ suggested_action: action
9198
+ });
9199
+ for (const wi of wis) {
9200
+ const id = wi.id || wi.title;
9201
+ if (wi.codeGlobs.length > 0) withOwnership++;
9202
+ else if (wi.type === "bugfix" || wi.type === "hotfix") {
9203
+ gaps.missing_code_ownership.push(gapItem(wi, "Add `code:` globs to connect this corrective Work Item to source paths (`kaddo owners suggest`)."));
9204
+ }
9205
+ const roadmapOrigin = wi.source === "roadmap";
9206
+ const hasSource = Boolean(wi.source) || Boolean(wi.sourceId);
9207
+ if (hasSource) withSource++;
9208
+ if (roadmapOrigin && !wi.sourceId) {
9209
+ gaps.missing_source.push(gapItem(wi, "Add `source_id` for this roadmap-originated Work Item."));
9210
+ }
9211
+ if (roadmapOrigin && wi.sourceId) connectedRoadmapCandidates.add(wi.sourceId);
9212
+ if (wi.initiative) withInitiative++;
9213
+ if (wi.knowledgeLevel) withLevel++;
9214
+ else gaps.missing_knowledge_level.push(gapItem(wi, "Add `knowledge_level` (K0\u2013K4) to the front matter."));
9215
+ for (const g2 of wi.codeGlobs) {
9216
+ globCounts.set(g2, (globCounts.get(g2) ?? 0) + 1);
9217
+ globOwners.set(g2, [...globOwners.get(g2) ?? [], id]);
9218
+ if (isBroadGlob(g2)) {
9219
+ gaps.broad_ownership_globs.push({ id, title: wi.title, glob: g2, suggested_action: "Replace with specific files or narrower module paths." });
9220
+ }
9221
+ }
9222
+ try {
9223
+ const body = matter10(readFile(wi.filePath)).content;
9224
+ if (hasSection(body, /acceptance|criterios de aceptaci/i)) withAcceptance++;
9225
+ else gaps.missing_acceptance_criteria.push(gapItem(wi, "Add an `## Acceptance Criteria` section."));
9226
+ if (hasSection(body, /definition of done|^#{1,6}\s*dod\b|definici[oó]n de (terminado|hecho)/i)) withDoD++;
9227
+ else gaps.missing_definition_of_done.push(gapItem(wi, "Add a `## Definition of Done` section."));
9228
+ if (hasSection(body, /how to test|validation|validaci|c[oó]mo probarlo/i)) withValidation++;
9229
+ else gaps.missing_validation.push(gapItem(wi, "Add a `## How to test it` (validation) section."));
9230
+ } catch {
9231
+ }
9232
+ }
9233
+ const ownedCodePaths = [...globCounts.values()].reduce((a, b) => a + b, 0);
9234
+ const connectedRoadmap = connectedRoadmapCandidates.size;
9235
+ const broadGlobs = [...globCounts.keys()].filter((g2) => isBroadGlob(g2)).length;
9236
+ for (const [glob, owners] of globOwners) {
9237
+ if (owners.length > 1) {
9238
+ gaps.ownership_overlaps.push({ code_path: glob, work_items: [...new Set(owners)], suggested_action: "Shared historical modification path; it is not a conflict unless incompatible ownership is documented." });
9239
+ }
9240
+ }
9241
+ const ownershipOverlaps = gaps.ownership_overlaps.length;
9242
+ let g;
9243
+ let graphHintEntries = [];
9244
+ const config = loadConfig(dir);
9245
+ if (config) {
9246
+ const graph = buildGraph(dir, config, { scope: resolvedScope }, now);
9247
+ const hints = buildGraphHints(dir, graph, now);
9248
+ graphHintEntries = hints.hints;
9249
+ g = { available: true, scope: graph.scope, scopeReason: graph.scope_reason, nodes: graph.nodes.length, edges: graph.edges.length, quality: hints.quality, hints: hints.summary.hints, generatedAt: graph.generated_at };
9250
+ } else {
9251
+ g = { available: false, scope: resolvedScope, scopeReason: "", nodes: 0, edges: 0, quality: "unknown", hints: 0, generatedAt: "" };
9252
+ }
9253
+ const layerStatus = (name) => exp.layers.find((l) => l.layer === name)?.status ?? "Missing";
9254
+ const byState = exp.workItems.byState;
9255
+ const skills = discoverInstalledSkills(dir);
9256
+ const knowledge_health = {
9257
+ Business: layerStatus("Business"),
9258
+ Product: layerStatus("Product"),
9259
+ Tech: layerStatus("Tech"),
9260
+ Delivery: layerStatus("Delivery"),
9261
+ Inventory: exp.knowledge.hasInventory ? "available" : "missing",
9262
+ "Context pack": exp.knowledge.hasContextPack ? "available" : "missing",
9263
+ Agents: exp.knowledge.hasAgents ? "available" : "missing",
9264
+ Skills: skills.length > 0 ? "available" : "missing"
9265
+ };
9266
+ const knowledge_coverage = [
9267
+ { label: "Work Items with ownership", have: withOwnership, total },
9268
+ { label: "Work Items with source", have: withSource, total },
9269
+ // Initiatives are optional: report their observed use, but do not use absence as a gap or score input.
9270
+ { label: "Work Items using optional initiatives", have: withInitiative, total },
9271
+ { label: "Work Items with acceptance criteria", have: withAcceptance, total },
9272
+ { label: "Work Items with Definition of Done", have: withDoD, total },
9273
+ { label: "Work Items with knowledge level", have: withLevel, total }
9274
+ ];
9275
+ const coverageRatio = (have) => total > 0 ? have / total : 0;
9276
+ const deliveryTraceable = ["Traceable", "Structured", "Consolidated"].includes(layerStatus("Delivery"));
9277
+ const ctxReasons = [];
9278
+ let ctxScore = 0;
9279
+ if (["Consolidated", "Structured"].includes(layerStatus("Business"))) {
9280
+ ctxScore++;
9281
+ ctxReasons.push("Business knowledge is present.");
9282
+ }
9283
+ if (["Consolidated", "Structured"].includes(layerStatus("Product"))) {
9284
+ ctxScore++;
9285
+ ctxReasons.push("Product knowledge is present.");
9286
+ }
9287
+ if (layerStatus("Tech") !== "Missing") {
9288
+ ctxScore++;
9289
+ ctxReasons.push("Tech knowledge is structured.");
9290
+ }
9291
+ if (deliveryTraceable) {
9292
+ ctxScore++;
9293
+ ctxReasons.push("Delivery is traceable.");
9294
+ }
9295
+ if (exp.knowledge.hasContextPack) {
9296
+ ctxScore++;
9297
+ ctxReasons.push("Context pack is available.");
9298
+ }
9299
+ if (g.available && g.quality !== "empty") {
9300
+ ctxScore++;
9301
+ ctxReasons.push(`Graph quality is ${g.quality}.`);
9302
+ }
9303
+ const ctxLevel = ctxScore >= 6 ? "Very High" : ctxScore >= 4 ? "High" : ctxScore >= 2 ? "Medium" : "Low";
9304
+ const ambiguityRatio = total > 0 ? (withAcceptance + withDoD + withSource) / (3 * total) : 0;
9305
+ const aiReady = exp.knowledge.hasContextPack && g.available && g.quality !== "empty" && skills.length > 0 && deliveryTraceable ? "High" : exp.knowledge.hasContextPack && g.available && g.quality !== "empty" ? "Medium" : "Low";
9306
+ const onboarding = levelFromRatio(
9307
+ [layerStatus("Business"), layerStatus("Product"), layerStatus("Tech"), layerStatus("Delivery")].filter((s) => s !== "Missing").length / 4 * (exp.knowledge.hasContextPack ? 1 : 0.6)
9308
+ );
9309
+ const deliveryTrace = levelFromRatio(
9310
+ coverageRatio(withOwnership) * 0.5 + (g.available && g.edges > 0 ? 1 : 0) * 0.25 + (exp.roadmap.present ? 1 : 0) * 0.25
9311
+ );
9312
+ const guardHistory = buildGuardHistory(dir);
9313
+ const impact_signals = {
9314
+ ambiguity_reduction: levelFromRatio(ambiguityRatio),
9315
+ drift_prevention: guardHistory.available && guardHistory.resolved > 0 ? "Observed" : "Unknown",
9316
+ onboarding_support: onboarding,
9317
+ delivery_traceability: deliveryTrace,
9318
+ ai_context_readiness: aiReady,
9319
+ maintenance_readiness: levelFromRatio((coverageRatio(withOwnership) + (deliveryTraceable ? 1 : 0)) / 2)
9320
+ };
9321
+ const baselineLayers = projectContext.mode === "poc" ? ["Tech", "Delivery"] : ["Business", "Product", "Tech", "Delivery"];
9322
+ const findings = [];
9323
+ for (const layer of baselineLayers) {
9324
+ const status = layerStatus(layer);
9325
+ if (status !== "Weak" && status !== "Missing") continue;
9326
+ findings.push({
9327
+ id: `knowledge-health:${layer.toLowerCase()}`,
9328
+ category: "knowledge",
9329
+ classification: "coverage_gap",
9330
+ resolution_status: "open",
9331
+ source: "knowledge-health",
9332
+ affected_artifacts: [layer],
9333
+ priority: status === "Missing" ? "medium" : "low",
9334
+ evidence: `${layer} knowledge maturity is ${status}.`,
9335
+ explanation: `This assesses documented ${layer} knowledge, not the quality of the product or implementation.`,
9336
+ suggested_action: `Review ${layer} knowledge coverage and the artifacts or relationships available for it.`
9337
+ });
9338
+ }
9339
+ for (const gap of gaps.missing_code_ownership) {
9340
+ findings.push({
9341
+ id: `ownership:${gap.id}`,
9342
+ category: "delivery",
9343
+ classification: "coverage_gap",
9344
+ resolution_status: "open",
9345
+ source: "work-item-ownership",
9346
+ affected_artifacts: [gap.id, gap.path],
9347
+ priority: "medium",
9348
+ evidence: "A corrective Work Item has no declared code ownership.",
9349
+ explanation: gap.title,
9350
+ suggested_action: "Review and add relevant code ownership declarations."
9351
+ });
9352
+ }
9353
+ for (const wi of completedWis) {
9354
+ if (!wi.validationStatus || !["not-started", "in-progress", "partial", "failed", "blocked"].includes(wi.validationStatus)) continue;
9355
+ findings.push({
9356
+ id: `completion-validation:${wi.id || wi.title}`,
9357
+ category: "delivery",
9358
+ classification: "review_hint",
9359
+ resolution_status: "open",
9360
+ source: "work-item-lifecycle",
9361
+ affected_artifacts: [wi.id || wi.title, wi.relPath],
9362
+ priority: "medium",
9363
+ evidence: `Lifecycle is completed while persisted validation is ${wi.validationStatus}.`,
9364
+ explanation: "This requires review against the Work Item completion contract; it is not automatically a failed or invalid completion.",
9365
+ suggested_action: "Review the validation evidence and confirm whether the completed lifecycle state is consistent with the Work Item completion contract."
9366
+ });
9367
+ }
9368
+ findings.push(...graphHintEntries.map(graphHintFinding));
9369
+ const priorityOrder = { high: 0, medium: 1, low: 2, unknown: 3 };
9370
+ findings.sort((a, b) => priorityOrder[a.priority] - priorityOrder[b.priority] || a.id.localeCompare(b.id));
9371
+ let score = null;
9372
+ let score_breakdown = null;
9373
+ if (total > 0) {
9374
+ const layerMaturity = { Consolidated: 1, Structured: 0.8, Traceable: 0.75, Weak: 0.4, Missing: 0 };
9375
+ const healthPts = [layerStatus("Business"), layerStatus("Product"), layerStatus("Tech"), layerStatus("Delivery")].reduce((sum, status) => sum + (layerMaturity[status] ?? 0), 0) / 4 * 20;
9376
+ const applicableCoverage = knowledge_coverage.filter((c) => c.label !== "Work Items using optional initiatives");
9377
+ const covAvg = applicableCoverage.reduce((a, c) => a + coverageRatio(c.have), 0) / applicableCoverage.length;
9378
+ const coveragePts = covAvg * 20;
9379
+ const ownPts = coverageRatio(withOwnership) * 15;
9380
+ const roadmapTraceRatio = exp.roadmap.candidates > 0 ? Math.min(connectedRoadmap, exp.roadmap.candidates) / exp.roadmap.candidates : null;
9381
+ const traceSignals = [coverageRatio(withOwnership), ...roadmapTraceRatio === null ? [] : [roadmapTraceRatio]];
9382
+ const traceBlend = traceSignals.reduce((sum, value) => sum + value, 0) / traceSignals.length;
9383
+ const tracePts = traceBlend * 20;
9384
+ const qualityMap = { good: 1, partial: 0.6, sparse: 0.3, empty: 0, unknown: 0 };
9385
+ const graphPts = (g.available ? qualityMap[g.quality] ?? 0 : 0) * 15;
9386
+ const ctxPts = { Low: 0.25, Medium: 0.5, High: 0.8, "Very High": 1 }[ctxLevel] * 10;
9387
+ score_breakdown = {
9388
+ knowledge_health: { points: Math.round(healthPts), max: 20 },
9389
+ knowledge_coverage: { points: Math.round(coveragePts), max: 20 },
9390
+ ownership_coverage: { points: Math.round(ownPts), max: 15 },
9391
+ traceability: { points: Math.round(tracePts), max: 20 },
9392
+ graph_quality: { points: Math.round(graphPts), max: 15 },
9393
+ context_readiness: { points: Math.round(ctxPts), max: 10 }
9394
+ };
9395
+ score = Object.values(score_breakdown).reduce((sum, component) => sum + component.points, 0);
9396
+ }
9397
+ const idsOf = (items) => items.map((i) => i.id);
9398
+ const groupedAction = (items, verb) => {
9399
+ if (items.length === 0) return null;
9400
+ const ids = idsOf(items);
9401
+ return ids.length <= 3 ? `${verb} ${ids.join(", ")}.` : `${verb} ${ids.length} Work Items: ${ids.slice(0, 3).join(", ")}, \u2026`;
9402
+ };
9403
+ const actions = [];
9404
+ if (!g.available) actions.push("Run `kaddo graph export --scope all` to inspect full traceability.");
9405
+ else if (g.scope === "active" && g.quality === "empty") actions.push("Run `kaddo impact --scope all` to measure accumulated knowledge impact.");
9406
+ if (exp.roadmap.remaining > 0) actions.push(`Materialize the ${exp.roadmap.remaining} remaining roadmap candidate(s) with \`kaddo create --from roadmap\`.`);
9407
+ for (const a of [
9408
+ groupedAction(gaps.missing_source, "Add `source`/`source_id` to")
9409
+ ]) if (a) actions.push(a);
9410
+ if (gaps.broad_ownership_globs.length > 0) actions.push(`Narrow ${gaps.broad_ownership_globs.length} broad ownership glob(s) into specific paths.`);
9411
+ for (const finding of findings) {
9412
+ if (!actions.includes(finding.suggested_action)) actions.push(finding.suggested_action);
9413
+ }
9414
+ if (skills.length === 0) actions.push("Install reusable skills with `kaddo add skills`.");
9415
+ actions.push("Run `kaddo guard` before committing to catch knowledge drift.");
9416
+ const summary = [];
9417
+ if (completedWis.length > 0) {
9418
+ summary.push(`Delivery evidence: ${completedWis.length} completed; ${verifiedWorkItems} validation passed; ${notRecordedValidationWorkItems} not confirmed by persisted validation.`);
9419
+ }
9420
+ if (total > 0) summary.push(`${withOwnership}/${total} Work Items include code ownership.`);
9421
+ if (g.available) summary.push(`The knowledge graph is ${g.quality} with ${g.nodes} nodes and ${g.edges} edges (${g.scope} scope).`);
9422
+ else summary.push("The knowledge graph has not been exported yet.");
9423
+ if (g.available) summary.push(g.hints === 0 ? "No graph hints are currently open." : `${g.hints} graph hint(s) are open.`);
9424
+ if (exp.roadmap.present) summary.push(`Delivery: ${exp.roadmap.materialized} materialized, ${exp.roadmap.remaining} roadmap candidate(s) remaining.`);
9425
+ summary.push(`Context readiness: ${ctxLevel}.`);
9426
+ return {
9427
+ generated_at: now.toISOString(),
9428
+ project: exp.project.name,
9429
+ project_context: projectContext,
9430
+ evidence: [
9431
+ ...["Business", "Product", "Tech", "Delivery"].map((layer) => knowledgeLayerEvidence(projectContext, layer, layerStatus(layer) !== "Missing")),
9432
+ { id: "work-items.lifecycle", label: "Work Item lifecycle", classification: total > 0 ? "observed" : "unknown", reason: total > 0 ? `${total} Work Item artifact(s) were discovered.` : "No Work Item artifacts were discovered." },
9433
+ { id: "delivery.verification", label: "Verified delivery outcomes", classification: verifiedWorkItems > 0 ? "observed" : "unknown", reason: verifiedWorkItems > 0 ? `${verifiedWorkItems} Work Item(s) have persisted validation_status: passed.` : "Acceptance Criteria and Definition of Done sections show declared intent, not completed verification evidence." },
9434
+ ...deliveryCapabilityEvidence(dir, projectContext),
9435
+ { id: "guard-history", label: "Guard consistency history", classification: guardHistory.available ? "observed" : "unknown", reason: guardHistory.available ? "Recorded Guard runs provide current consistency evidence." : "No recorded Guard history is available." }
9436
+ ],
9437
+ scope: g.scope,
9438
+ default_scope: "all",
9439
+ scope_source: scopeSource,
9440
+ executive_summary: summary,
9441
+ delivery_evidence: {
9442
+ completed: completedWis.length,
9443
+ validation_passed: verifiedWorkItems,
9444
+ validation_failed: failedValidationWorkItems,
9445
+ validation_pending: pendingValidationWorkItems,
9446
+ validation_not_recorded: notRecordedValidationWorkItems,
9447
+ completion_with_passed_validation_percent: completedWis.length > 0 ? Math.round(verifiedWorkItems / completedWis.length * 1e3) / 10 : null
9448
+ },
9449
+ findings,
9450
+ knowledge_health,
9451
+ knowledge_coverage,
9452
+ ownership_coverage: {
9453
+ coverage_percent: total > 0 ? Math.round(withOwnership / total * 100) : 0,
9454
+ work_items_with_ownership: `${withOwnership}/${total}`,
9455
+ owned_code_paths: ownedCodePaths,
9456
+ broad_globs: broadGlobs,
9457
+ ownership_overlaps: ownershipOverlaps
9458
+ },
9459
+ traceability: {
9460
+ roadmap_candidates: exp.roadmap.candidates,
9461
+ materialized_work_items: exp.roadmap.materialized,
9462
+ remaining_candidates: exp.roadmap.remaining,
9463
+ completed_work_items: byState.completed,
9464
+ work_items_connected_to_roadmap: `${connectedRoadmap}/${total}`,
9465
+ work_items_connected_to_code: `${withOwnership}/${total}`,
9466
+ graph_quality: g.available ? g.quality : "not available",
9467
+ graph_nodes: g.available ? g.nodes : null,
9468
+ graph_edges: g.available ? g.edges : null,
9469
+ graph_hints: g.available ? g.hints : null
9470
+ },
9471
+ context_readiness: { level: ctxLevel, reasons: ctxReasons },
9472
+ work_item_readiness: {
9473
+ draft: byState.draft,
9474
+ ready: byState.ready,
9475
+ in_progress: byState["in-progress"],
9476
+ blocked: byState.blocked,
9477
+ completed: byState.completed,
9478
+ ready_quality: byState.ready > 0 ? `${byState.ready} ready` : "not applicable"
9479
+ },
9480
+ graph_quality: g.available ? { available: true, scope: g.scope, quality: g.quality, nodes: g.nodes, edges: g.edges, hints: g.hints, reason: g.scopeReason, last_exported: g.generatedAt } : { available: false, suggestion: "Run `kaddo graph export --scope all`." },
9481
+ guard_activity: (() => {
9482
+ const gh = guardHistory;
9483
+ return gh.available ? { available: true, runs_recorded: gh.total_runs, detected: gh.detected, open: gh.open, resolved: gh.resolved, resolution_rate: gh.resolution_rate } : { available: false, note: "Guard history is not persisted. Run `kaddo guard --record` to record runs for trend analysis." };
9484
+ })(),
9485
+ impact_signals,
9486
+ actionable_gaps: gaps,
9487
+ score,
9488
+ score_breakdown,
9489
+ suggested_actions: actions
9490
+ };
9491
+ }
9492
+ function ratio(have, total) {
9493
+ return `${have}/${total}`;
9494
+ }
9495
+ function renderImpactMarkdown(r, opts = {}) {
9496
+ const L = [];
9497
+ L.push("# Kaddo Knowledge Impact Report", "");
9498
+ L.push(`Generated at: ${r.generated_at}`);
9499
+ L.push(`Project: ${r.project}`);
9500
+ L.push(`Project context: state=${r.project_context.state}; mode=${r.project_context.mode}; repositories=${r.project_context.repository_structure}`);
9501
+ L.push(`Scope: ${r.scope}`);
9502
+ if (r.score !== null) L.push(`Legacy Knowledge Impact Score: ${r.score}/100 (deprecated; use Evidence and Applicability)`);
9503
+ else L.push("Legacy Knowledge Impact Score: not available");
9504
+ if (r.scope_source === "default") {
9505
+ L.push("Scope note: Impact reports use `all` by default to measure accumulated knowledge impact.");
9506
+ } else if (r.scope === "active" && r.graph_quality.available === false) {
9507
+ L.push("Tip: Run `kaddo impact --scope all` to inspect accumulated knowledge impact.");
9508
+ }
9509
+ L.push("");
9510
+ L.push("## Executive Summary", "");
9511
+ for (const s2 of r.executive_summary) L.push(`- ${s2}`);
9512
+ L.push("");
9513
+ L.push("## Key Findings", "");
9514
+ if (r.findings.length === 0) L.push("No current findings detected by the executed deterministic checks.");
9515
+ if (r.findings.length > 0) {
9516
+ const cell = (value) => value.replace(/\|/g, "\\|").replace(/\r?\n/g, " ");
9517
+ L.push("| Classification | Priority | Status | Source | Affected | Finding | Suggested action |");
9518
+ L.push("|---|---|---|---|---|---|---|");
9519
+ for (const finding of r.findings) {
9520
+ L.push(`| ${finding.classification} | ${finding.priority} | ${finding.resolution_status} | ${cell(finding.source)} | ${cell(finding.affected_artifacts.join(", ") || "not available")} | ${cell(finding.explanation)} Evidence: ${cell(finding.evidence)} | ${cell(finding.suggested_action)} |`);
9521
+ }
9522
+ }
9523
+ L.push("");
9524
+ L.push("## Delivery Evidence", "");
9525
+ const de = r.delivery_evidence;
9526
+ L.push(`- Completed Work Items: ${de.completed}`);
9527
+ L.push(`- Validation passed: ${de.validation_passed}`);
9528
+ L.push(`- Validation failed: ${de.validation_failed}`);
9529
+ L.push(`- Validation pending: ${de.validation_pending}`);
9530
+ L.push(`- Validation not recorded: ${de.validation_not_recorded}`);
9531
+ L.push(`- Completion with passed validation: ${de.completion_with_passed_validation_percent === null ? "not available" : `${de.completion_with_passed_validation_percent}%`}`);
9532
+ L.push("- \u201CNot recorded\u201D means persisted evidence is absent; it does not prove validation never happened.");
9533
+ L.push("");
9534
+ L.push("## Evidence and Applicability", "");
9535
+ for (const item of r.evidence) L.push(`- ${item.label}: ${item.classification} \u2014 ${item.reason}`);
9536
+ L.push("");
9537
+ L.push("## Knowledge Health", "");
9538
+ for (const [k, v] of Object.entries(r.knowledge_health)) L.push(`- ${k}: ${v}`);
9539
+ L.push("");
9540
+ L.push("## Knowledge Coverage", "");
9541
+ for (const c of r.knowledge_coverage) L.push(`- ${c.label}: ${ratio(c.have, c.total)}`);
9542
+ L.push("");
9543
+ L.push("## Ownership Coverage", "");
9544
+ L.push(`- Coverage: ${r.ownership_coverage.coverage_percent}%`);
9545
+ L.push(`- Work Items with code ownership: ${r.ownership_coverage.work_items_with_ownership}`);
9546
+ L.push(`- Owned code paths: ${r.ownership_coverage.owned_code_paths}`);
9547
+ L.push(`- Broad globs detected: ${r.ownership_coverage.broad_globs}`);
9548
+ L.push(`- Ownership overlaps: ${r.ownership_coverage.ownership_overlaps}`);
9549
+ L.push("");
9550
+ L.push("## Traceability", "");
9551
+ const t = r.traceability;
9552
+ L.push(`- Roadmap candidates: ${t.roadmap_candidates}`);
9553
+ L.push(`- Materialized Work Items: ${t.materialized_work_items}`);
9554
+ L.push(`- Remaining candidates: ${t.remaining_candidates}`);
9555
+ L.push(`- Completed Work Items: ${t.completed_work_items}`);
9556
+ L.push(`- Work Items connected to roadmap: ${t.work_items_connected_to_roadmap}`);
9557
+ L.push(`- Work Items connected to code: ${t.work_items_connected_to_code}`);
9558
+ L.push(`- Graph quality: ${t.graph_quality}`);
9559
+ if (t.graph_nodes !== null) L.push(`- Graph nodes: ${t.graph_nodes}`);
9560
+ if (t.graph_edges !== null) L.push(`- Graph edges: ${t.graph_edges}`);
9561
+ if (t.graph_hints !== null) L.push(`- Graph hints: ${t.graph_hints}`);
9562
+ L.push("");
9563
+ L.push("## Context Readiness", "");
9564
+ L.push(`Context Readiness: ${r.context_readiness.level}`);
9565
+ if (r.context_readiness.reasons.length > 0) {
9566
+ L.push("", "Reason:");
9567
+ for (const reason of r.context_readiness.reasons) L.push(`- ${reason}`);
9568
+ }
9569
+ L.push("");
9570
+ L.push("## Work Item Readiness", "");
9571
+ const w = r.work_item_readiness;
9572
+ L.push(`- Draft: ${w.draft}`);
9573
+ L.push(`- Ready: ${w.ready}`);
9574
+ L.push(`- In Progress: ${w.in_progress}`);
9575
+ L.push(`- Blocked: ${w.blocked}`);
9576
+ L.push(`- Completed: ${w.completed}`);
9577
+ L.push(`- Ready quality: ${w.ready_quality}`);
9578
+ L.push("");
9579
+ L.push("## Graph Quality", "");
9580
+ if (r.graph_quality.available) {
9581
+ const gq = r.graph_quality;
9582
+ L.push(`- Scope: ${gq.scope}`);
9583
+ L.push(`- Quality: ${gq.quality}`);
9584
+ L.push(`- Nodes: ${gq.nodes}`);
9585
+ L.push(`- Edges: ${gq.edges}`);
9586
+ L.push(`- Hints: ${gq.hints}`);
9587
+ if (gq.reason) L.push(`- Reason: ${gq.reason}`);
9588
+ if (gq.last_exported) L.push(`- Last exported: ${gq.last_exported}`);
9589
+ if (gq.scope === "active" && gq.quality === "empty") {
9590
+ L.push("- Tip: Run `kaddo impact --scope all` to inspect accumulated knowledge impact.");
9591
+ }
9592
+ } else {
9593
+ L.push("- Graph data not available.");
9594
+ L.push(`- Tip: ${r.graph_quality.suggestion}`);
9595
+ }
9596
+ L.push("");
9597
+ L.push("## Guard Activity", "");
9598
+ if (r.guard_activity.available) {
9599
+ const ga = r.guard_activity;
9600
+ L.push("- Guard history: available");
9601
+ L.push(`- Guard runs recorded: ${ga.runs_recorded}`);
9602
+ L.push(`- Drift warnings detected: ${ga.detected}`);
9603
+ L.push(`- Open warnings: ${ga.open}`);
9604
+ L.push(`- Resolved warnings: ${ga.resolved}`);
9605
+ L.push(`- Resolution rate: ${ga.resolution_rate}%`);
9606
+ } else {
9607
+ L.push("- Guard history: not available");
9608
+ L.push(`- Note: ${r.guard_activity.note}`);
9609
+ }
9610
+ L.push("");
9611
+ L.push("## Impact Signals", "");
9612
+ const s = r.impact_signals;
9613
+ L.push(`- Ambiguity reduction: ${s.ambiguity_reduction}`);
9614
+ L.push(`- Drift prevention evidence: ${s.drift_prevention}`);
9615
+ L.push(`- Onboarding support: ${s.onboarding_support}`);
9616
+ L.push(`- Delivery traceability: ${s.delivery_traceability}`);
9617
+ L.push(`- AI context readiness: ${s.ai_context_readiness}`);
9618
+ L.push(`- Maintenance readiness: ${s.maintenance_readiness}`);
9619
+ L.push("");
9620
+ L.push("## Actionable Gaps", "");
9621
+ const gp = r.actionable_gaps;
9622
+ const gapSection = (title, items) => {
9623
+ if (items.length === 0) return;
9624
+ L.push(`### ${title}`, "");
9625
+ for (const it of items) {
9626
+ L.push(`- ${it.id} \u2014 ${it.title}`);
9627
+ L.push(` - Path: ${it.path}`);
9628
+ L.push(` - Suggested action: ${it.suggested_action}`);
9629
+ }
9630
+ L.push("");
9631
+ };
9632
+ if (opts.details) gapSection("Work Items missing source", gp.missing_source);
9633
+ if (opts.details) gapSection("Work Items missing code ownership", gp.missing_code_ownership);
9634
+ if (opts.details && gp.broad_ownership_globs.length > 0) {
9635
+ L.push("### Broad ownership globs", "");
9636
+ for (const b of gp.broad_ownership_globs) {
9637
+ L.push(`- ${b.id} \u2014 ${b.title}`);
9638
+ L.push(` - Glob: \`${b.glob}\``);
9639
+ L.push(` - Suggested action: ${b.suggested_action}`);
9640
+ }
9641
+ L.push("");
9642
+ }
9643
+ if (gp.ownership_overlaps.length > 0) {
9644
+ L.push("### Shared code-path history (review only)", "");
9645
+ if (opts.details) {
9646
+ for (const o of gp.ownership_overlaps) {
9647
+ L.push(`- \`${o.code_path}\``);
9648
+ L.push(` - Owned by: ${o.work_items.join(", ")}`);
9649
+ L.push(` - Suggested action: ${o.suggested_action}`);
9650
+ }
9651
+ } else {
9652
+ L.push(`- ${gp.ownership_overlaps.length} shared path declaration(s) detected. These are historical relationships, not necessarily ownership conflicts.`);
9653
+ const areas = gp.ownership_overlaps.slice(0, 3).map((o) => `\`${o.code_path}\``);
9654
+ if (areas.length > 0) L.push(`- Most involved paths: ${areas.join(", ")}.`);
9655
+ L.push("- Run `kaddo impact --details` for the complete shared-path inventory.");
9656
+ }
9657
+ L.push("");
9658
+ }
9659
+ const anyGaps = gp.missing_source.length + gp.missing_code_ownership.length + gp.broad_ownership_globs.length;
9660
+ if (anyGaps === 0) {
9661
+ L.push("No actionable knowledge gaps detected. \u{1F389}", "");
9662
+ } else if (!opts.details) {
9663
+ L.push("- Current actionable items are listed in Key Findings. Run `kaddo impact --details` for the full artifact inventory.");
9664
+ L.push("");
9665
+ }
9666
+ const historical = [
9667
+ ["knowledge level", gp.missing_knowledge_level],
9668
+ ["Acceptance Criteria", gp.missing_acceptance_criteria],
9669
+ ["Definition of Done", gp.missing_definition_of_done],
9670
+ ["validation section", gp.missing_validation]
9671
+ ];
9672
+ L.push("## Historical Documentation Completeness", "");
9673
+ for (const [label, items] of historical) {
9674
+ const completed = items.filter((item) => item.status === "completed");
9675
+ if (completed.length > 0) L.push(`- Completed Work Items without detected ${label}: ${completed.length}`);
9676
+ }
9677
+ if (!historical.some(([, items]) => items.some((item) => item.status === "completed"))) {
9678
+ L.push("No historical documentation completeness gaps were detected.");
9679
+ }
9680
+ L.push("- This is an inventory for review, not a recommendation to rewrite historical Work Items merely to increase a metric.");
9681
+ L.push("");
9682
+ if (r.score_breakdown) {
9683
+ L.push("## Score Breakdown", "");
9684
+ const b = r.score_breakdown;
9685
+ L.push(`- Knowledge Health: ${b.knowledge_health.points}/${b.knowledge_health.max}`);
9686
+ L.push(`- Knowledge Coverage: ${b.knowledge_coverage.points}/${b.knowledge_coverage.max}`);
9687
+ L.push(`- Ownership Coverage: ${b.ownership_coverage.points}/${b.ownership_coverage.max}`);
9688
+ L.push(`- Traceability: ${b.traceability.points}/${b.traceability.max}`);
9689
+ L.push(`- Graph Quality: ${b.graph_quality.points}/${b.graph_quality.max}`);
9690
+ L.push(`- Context Readiness: ${b.context_readiness.points}/${b.context_readiness.max}`);
9691
+ L.push("");
9692
+ }
9693
+ L.push("## Suggested Actions", "");
9694
+ r.suggested_actions.forEach((a, i) => L.push(`${i + 1}. ${a}`));
9695
+ L.push("");
9696
+ return L.join("\n");
9697
+ }
9698
+ function serializeImpactJson(r) {
9699
+ return JSON.stringify(r, null, 2) + "\n";
9700
+ }
9701
+
9702
+ // src/core/drift-report.ts
9703
+ function buildDriftReport(dir, now = /* @__PURE__ */ new Date()) {
9704
+ const h = buildGuardHistory(dir);
9705
+ const project = loadConfig(dir)?.project.name ?? "unknown";
9706
+ const projectContext = reportingProjectContext(dir);
9707
+ const workItems = discoverWorkItems(dir);
9708
+ const verificationEvidence = workItems.filter((wi) => wi.validationStatus && wi.validationStatus !== "not-started");
9709
+ const plans = getDeprecationPlans(dir);
9710
+ const planDetails = plans.map((plan) => getDeprecationPlan(dir, plan.id)).filter((plan) => plan !== null);
9711
+ const plansWithoutTargets = planDetails.filter((plan) => plan.targets.length === 0);
9712
+ const plansWithTargets = planDetails.filter((plan) => plan.targets.length > 0);
9713
+ const targetFindingsByPlan = new Map(plansWithTargets.map((plan) => [
9714
+ plan.id,
9715
+ plan.targets.flatMap(validateTarget)
9716
+ ]));
9717
+ const deprecationFindings = [...targetFindingsByPlan.values()].flat();
9718
+ const plansWithoutStructuralFindings = plansWithTargets.filter((plan) => (targetFindingsByPlan.get(plan.id) ?? []).length === 0);
9719
+ const config = loadConfig(dir);
9720
+ const topology = config ? buildGraph(dir, config, { scope: "all" }, now) : null;
9721
+ const graphHints = topology ? buildGraphHints(dir, topology, now) : null;
9722
+ const topologyHints = graphHints?.summary.hints ?? null;
9723
+ const currentConsistencyFindings = [
9724
+ ...graphHints?.hints.map(graphHintFinding) ?? [],
9725
+ ...deprecationFindings.map((finding, index) => ({
9726
+ id: `deprecation-target:${index + 1}`,
9727
+ category: "consistency",
9728
+ classification: "consistency_violation",
9729
+ resolution_status: "open",
9730
+ source: "deprecation-target-validation",
9731
+ affected_artifacts: finding.target ? [finding.target] : [],
9732
+ priority: finding.severity === "error" ? "high" : "medium",
9733
+ evidence: finding.message,
9734
+ explanation: "A deterministic deprecation target consistency check reported a finding.",
9735
+ suggested_action: "Review the affected deprecation target and its declared lifecycle evidence."
9736
+ })),
9737
+ ...h.available && h.total_runs >= 2 ? h.threads.filter((thread) => thread.status === "open").map((thread) => ({
9738
+ id: `guard-history:${thread.code_path}`,
9739
+ category: "consistency",
9740
+ classification: "historical_drift",
9741
+ resolution_status: "open",
9742
+ source: "guard-history",
9743
+ affected_artifacts: [thread.code_path, ...thread.related_artifacts],
9744
+ priority: "medium",
9745
+ evidence: `Recorded Guard observations from ${thread.first_detected} through ${thread.last_seen} remain unresolved.`,
9746
+ explanation: "Comparable Guard runs observed a possible code/knowledge drift thread over time.",
9747
+ suggested_action: "Review the recorded drift thread and update the relevant knowledge or ownership evidence."
9748
+ })) : []
9749
+ ];
9750
+ const actions = [];
9751
+ if (!h.available) {
9752
+ actions.push("Start recording Guard runs at relevant delivery checkpoints with `kaddo guard --record`; one run creates an observation, while multiple comparable runs are needed for a historical trend.");
9753
+ } else {
9754
+ if (h.open > 0) actions.push("Review open drift warnings and update related Work Items or ownership.");
9755
+ actions.push("Run `kaddo guard --record` before important commits.");
9756
+ actions.push("Use this report to calibrate estimated drift-prevention savings.");
9757
+ }
9758
+ return {
9759
+ generated_at: now.toISOString(),
9760
+ project,
9761
+ project_context: projectContext,
9762
+ consistency_evidence: [
9763
+ { id: "guard-current-consistency", label: "Current Guard consistency", classification: h.available ? "observed" : "unknown", reason: h.available ? `${h.total_runs} recorded Guard run(s) provide deterministic consistency evidence.` : "No recorded Guard history is available." },
9764
+ { id: "lifecycle-consistency", label: "Lifecycle evidence consistency", classification: verificationEvidence.length > 0 ? "observed" : "unknown", reason: verificationEvidence.length > 0 ? `${verificationEvidence.length} Work Item(s) persist an implementation validation status.` : "No persisted Work Item validation status is available." },
9765
+ { id: "deprecation-consistency", label: "Deprecation consistency", classification: plans.length === 0 ? "not_applicable" : plansWithTargets.length === 0 ? "unknown" : deprecationFindings.length === 0 ? "derived" : "observed", reason: plans.length === 0 ? "No deprecation plans exist in this project." : plansWithTargets.length === 0 ? `${plansWithoutTargets.length} plan(s) have no targets, so target consistency was not evaluated.` : deprecationFindings.length === 0 ? `${plansWithTargets.length} plan(s) with targets passed deterministic target consistency checks; ${plansWithoutTargets.length} plan(s) remain unevaluated because they have no targets.` : `${deprecationFindings.length} deterministic deprecation consistency finding(s) were detected.` },
9766
+ { id: "topology-consistency", label: "Knowledge topology consistency", classification: topology === null ? "unknown" : topologyHints === 0 ? "derived" : "observed", reason: topology === null ? "No project configuration is available to construct the topology." : topologyHints === 0 ? `The in-memory topology has ${topology.nodes.length} node(s) and no open deterministic hints.` : `The in-memory topology has ${topologyHints} open deterministic hint(s).` }
9767
+ ],
9768
+ current_consistency_findings: currentConsistencyFindings,
9769
+ structural_consistency: {
9770
+ deprecation_target_checks: plans.length === 0 ? "not_applicable" : plansWithTargets.length === 0 ? "not_evaluated" : deprecationFindings.length === 0 ? "passed" : "findings_detected",
9771
+ plans_discovered: plans.length,
9772
+ plans_without_targets: plansWithoutTargets.length,
9773
+ plans_with_targets_evaluated: plansWithTargets.length,
9774
+ structural_findings: deprecationFindings.length,
9775
+ plans_without_structural_findings: plansWithoutStructuralFindings.length,
9776
+ note: plans.length === 0 ? "No deprecation plans exist in this project." : "Target consistency checks validate declared structural state only; they do not verify operational removal from infrastructure, production or external consumers."
9777
+ },
9778
+ guard_history: {
9779
+ available: h.available,
9780
+ total_runs: h.total_runs,
9781
+ first_run: h.first_run,
9782
+ last_run: h.last_run,
9783
+ runs_with_warnings: h.runs_with_warnings,
9784
+ runs_clean: h.runs_clean
9785
+ },
9786
+ drift_warnings: { detected: h.detected, open: h.open, resolved: h.resolved, resolution_rate: h.resolution_rate },
9787
+ hotspots: h.hotspots,
9788
+ trend: h.trend,
9789
+ threads: h.threads,
9790
+ suggested_actions: actions
9791
+ };
9792
+ }
9793
+ function renderDriftMarkdown(r) {
9794
+ const L = [];
9795
+ L.push("# Kaddo Drift Trend Report", "");
9796
+ L.push(`Generated at: ${r.generated_at}`);
9797
+ L.push(`Project: ${r.project}`);
9798
+ L.push(`Project context: state=${r.project_context.state}; mode=${r.project_context.mode}; repositories=${r.project_context.repository_structure}`);
9799
+ L.push("");
9800
+ L.push("## Consistency Evidence", "");
9801
+ for (const item of r.consistency_evidence) L.push(`- ${item.label}: ${item.classification} \u2014 ${item.reason}`);
9802
+ L.push("");
9803
+ const findingGroups = [
9804
+ { classification: "consistency_violation", title: "Consistency Violations" },
9805
+ { classification: "coverage_gap", title: "Coverage Gaps" },
9806
+ { classification: "review_hint", title: "Review Hints" },
9807
+ { classification: "historical_drift", title: "Historical Drift" }
9808
+ ];
9809
+ L.push("## Current Findings Summary", "");
9810
+ for (const group of findingGroups) {
9811
+ const count = r.current_consistency_findings.filter((finding) => finding.classification === group.classification).length;
9812
+ const unavailable = group.classification === "historical_drift" && !r.guard_history.available;
9813
+ L.push(`- ${group.title}: ${unavailable ? "not available \u2014 no recorded Guard runs" : count}`);
9814
+ }
9815
+ L.push("");
9816
+ L.push("## Current Consistency Findings", "");
9817
+ if (r.current_consistency_findings.length === 0) L.push("No findings detected by the executed consistency checks.", "");
9818
+ const cell = (value) => value.replace(/\|/g, "\\|").replace(/\r?\n/g, " ");
9819
+ for (const group of findingGroups) {
9820
+ const findings = r.current_consistency_findings.filter((finding) => finding.classification === group.classification);
9821
+ if (findings.length === 0) continue;
9822
+ L.push(`### ${group.title}`, "");
9823
+ L.push("| Classification | Priority | Status | Source | Affected | Finding | Suggested action |");
9824
+ L.push("|---|---|---|---|---|---|---|");
9825
+ for (const finding of findings) {
9826
+ L.push(`| ${finding.classification} | ${finding.priority} | ${finding.resolution_status} | ${cell(finding.source)} | ${cell(finding.affected_artifacts.join(", ") || "not available")} | ${cell(finding.explanation)} Evidence: ${cell(finding.evidence)} | ${cell(finding.suggested_action)} |`);
9827
+ }
9828
+ L.push("");
9829
+ }
9830
+ L.push("## Structural Consistency Boundaries", "");
9831
+ L.push(`- Deprecation target checks: ${r.structural_consistency.deprecation_target_checks}`);
9832
+ L.push(`- Plans discovered: ${r.structural_consistency.plans_discovered}`);
9833
+ L.push(`- Plans without targets: ${r.structural_consistency.plans_without_targets}`);
9834
+ L.push(`- Plans with targets evaluated: ${r.structural_consistency.plans_with_targets_evaluated}`);
9835
+ L.push(`- Structural findings: ${r.structural_consistency.structural_findings}`);
9836
+ L.push(`- Plans without structural findings: ${r.structural_consistency.plans_without_structural_findings}`);
9837
+ if (r.structural_consistency.plans_without_targets > 0) L.push("- Target consistency for plans without targets: not evaluated \u2014 no targets defined.");
9838
+ L.push(`- Note: ${r.structural_consistency.note}`);
9839
+ L.push("");
9840
+ if (!r.guard_history.available) {
9841
+ L.push("## Guard History", "");
9842
+ L.push("No guard history recorded yet.");
9843
+ L.push("");
9844
+ L.push("## Historical Drift Trend", "");
9845
+ L.push("Not available \u2014 no recorded Guard runs.");
9846
+ L.push("");
9847
+ L.push("Run `kaddo guard --record` to start recording drift evidence.");
9848
+ L.push("");
9849
+ L.push("## Suggested Actions", "");
9850
+ r.suggested_actions.forEach((a, i) => L.push(`${i + 1}. ${a}`));
9851
+ L.push("");
9852
+ return L.join("\n");
9853
+ }
9854
+ const w = r.drift_warnings;
9855
+ L.push("## Executive Summary", "");
9856
+ L.push(`- Guard runs recorded: ${r.guard_history.total_runs}`);
9857
+ L.push(`- Drift warnings detected: ${w.detected}`);
9858
+ L.push(`- Open warnings: ${w.open}`);
9859
+ L.push(`- Resolved warnings: ${w.resolved}`);
9860
+ L.push(`- Resolution rate: ${w.resolution_rate}%`);
9861
+ if (r.hotspots.length > 0) L.push(`- Most affected area: ${r.hotspots[0].path}`);
9862
+ L.push("");
9863
+ L.push("## Guard History", "");
9864
+ L.push(`- First run: ${r.guard_history.first_run}`);
9865
+ L.push(`- Last run: ${r.guard_history.last_run}`);
9866
+ L.push(`- Runs with warnings: ${r.guard_history.runs_with_warnings}/${r.guard_history.total_runs}`);
9867
+ L.push(`- Runs clean: ${r.guard_history.runs_clean}/${r.guard_history.total_runs}`);
9868
+ L.push("");
9869
+ L.push("## Drift Warnings", "");
9870
+ const open = r.threads.filter((t) => t.status === "open");
9871
+ const resolved = r.threads.filter((t) => t.status === "resolved");
9872
+ L.push("### Open", "");
9873
+ if (open.length === 0) L.push("_None._", "");
9874
+ for (const t of open) {
9875
+ L.push(`- ${t.code_path}`);
9876
+ L.push(` - Related artifacts: ${t.related_artifacts.join(", ") || "\u2014"}`);
9877
+ L.push(` - First detected: ${t.first_detected}`);
9878
+ L.push(` - Last seen: ${t.last_seen}`);
9879
+ L.push(" - Status: open");
9880
+ }
9881
+ L.push("");
9882
+ L.push("### Resolved", "");
9883
+ if (resolved.length === 0) L.push("_None._", "");
9884
+ for (const t of resolved) {
9885
+ L.push(`- ${t.code_path}`);
9886
+ L.push(` - Related artifacts: ${t.related_artifacts.join(", ") || "\u2014"}`);
9887
+ L.push(` - First detected: ${t.first_detected}`);
9888
+ L.push(` - Resolved at: ${t.resolved_at}`);
9889
+ L.push(" - Status: resolved");
9890
+ }
9891
+ L.push("");
9892
+ L.push("## Hotspots", "");
9893
+ if (r.hotspots.length === 0) L.push("_None._");
9894
+ for (const h of r.hotspots) L.push(`- ${h.path}: ${h.warnings} warning(s)`);
9895
+ L.push("");
9896
+ L.push("## Trend", "");
9897
+ L.push(`- Recent direction: ${r.trend.direction}`);
9898
+ L.push(`- Reason: ${r.trend.reason}`);
9899
+ L.push("");
9900
+ L.push("## Suggested Actions", "");
9901
+ r.suggested_actions.forEach((a, i) => L.push(`${i + 1}. ${a}`));
9902
+ L.push("");
9903
+ return L.join("\n");
9904
+ }
9905
+ function serializeDriftJson(r) {
9906
+ const out = {
9907
+ generated_at: r.generated_at,
9908
+ project: r.project,
9909
+ project_context: r.project_context,
9910
+ consistency_evidence: r.consistency_evidence,
9911
+ current_consistency_findings: r.current_consistency_findings,
9912
+ structural_consistency: r.structural_consistency,
9913
+ guard_history: r.guard_history,
9914
+ drift_warnings: r.drift_warnings,
9915
+ hotspots: r.hotspots,
9916
+ trend: r.trend,
9917
+ threads: r.threads,
9918
+ suggested_actions: r.suggested_actions
9919
+ };
9920
+ return JSON.stringify(out, null, 2) + "\n";
9921
+ }
9922
+
9923
+ // src/core/savings.ts
9924
+ import { parse as parseYaml8 } from "yaml";
9925
+ var DEFAULT_ASSUMPTIONS = {
9926
+ currency: "USD",
9927
+ hourly_cost: 40,
9928
+ context_preparation_minutes_saved_per_work_item: 30,
9929
+ rework_hours_avoided_per_resolved_drift: 2,
9930
+ onboarding_hours_saved_per_new_contributor: 4,
9931
+ review_minutes_saved_per_work_item_with_ownership: 20,
9932
+ clarification_minutes_saved_per_ready_work_item: 25,
9933
+ architecture_discovery_hours_saved_when_graph_good: 3,
9934
+ expected_new_contributors_per_month: 1,
9935
+ expected_work_items_per_month: 8
9936
+ };
9937
+ var SAVINGS_PATH = ".kaddo/savings.yml";
9938
+ function loadAssumptions(dir) {
9939
+ const p = join(dir, SAVINGS_PATH);
9940
+ if (!exists(p)) return { assumptions: { ...DEFAULT_ASSUMPTIONS }, source: "default" };
9941
+ try {
9942
+ const raw = parseYaml8(readFile(p));
9943
+ const a = raw?.assumptions ?? {};
9944
+ const t = raw?.team ?? {};
9945
+ const num = (v, d) => typeof v === "number" && Number.isFinite(v) ? v : d;
9946
+ return {
9947
+ source: "file",
9948
+ assumptions: {
9949
+ currency: raw?.currency ?? DEFAULT_ASSUMPTIONS.currency,
9950
+ ...typeof raw?.calibrated_at === "string" && raw.calibrated_at.trim() ? { calibrated_at: raw.calibrated_at.trim() } : {},
9951
+ hourly_cost: num(raw?.hourly_cost, DEFAULT_ASSUMPTIONS.hourly_cost),
9952
+ context_preparation_minutes_saved_per_work_item: num(a.context_preparation_minutes_saved_per_work_item, DEFAULT_ASSUMPTIONS.context_preparation_minutes_saved_per_work_item),
9953
+ rework_hours_avoided_per_resolved_drift: num(a.rework_hours_avoided_per_resolved_drift, DEFAULT_ASSUMPTIONS.rework_hours_avoided_per_resolved_drift),
9954
+ onboarding_hours_saved_per_new_contributor: num(a.onboarding_hours_saved_per_new_contributor, DEFAULT_ASSUMPTIONS.onboarding_hours_saved_per_new_contributor),
9955
+ review_minutes_saved_per_work_item_with_ownership: num(a.review_minutes_saved_per_work_item_with_ownership, DEFAULT_ASSUMPTIONS.review_minutes_saved_per_work_item_with_ownership),
9956
+ clarification_minutes_saved_per_ready_work_item: num(a.clarification_minutes_saved_per_ready_work_item, DEFAULT_ASSUMPTIONS.clarification_minutes_saved_per_ready_work_item),
9957
+ architecture_discovery_hours_saved_when_graph_good: num(a.architecture_discovery_hours_saved_when_graph_good, DEFAULT_ASSUMPTIONS.architecture_discovery_hours_saved_when_graph_good),
9958
+ expected_new_contributors_per_month: num(t.expected_new_contributors_per_month, DEFAULT_ASSUMPTIONS.expected_new_contributors_per_month),
9959
+ expected_work_items_per_month: num(t.expected_work_items_per_month, DEFAULT_ASSUMPTIONS.expected_work_items_per_month)
9960
+ }
9961
+ };
9962
+ } catch {
9963
+ return { assumptions: { ...DEFAULT_ASSUMPTIONS }, source: "default" };
9964
+ }
9965
+ }
9966
+ var READINESS_MULT = { Low: 0.25, Medium: 0.5, High: 0.75, "Very High": 1 };
9967
+ var GRAPH_MULT = { empty: 0, sparse: 0.25, partial: 0.6, good: 1, unknown: 0 };
9968
+ var round2 = (n) => Math.round(n * 100) / 100;
9969
+ function parseRatioNumerator(s) {
9970
+ const m = s.match(/^(\d+)/);
9971
+ return m ? Number(m[1]) : 0;
9972
+ }
9973
+ var SAVINGS_DISCLAIMER = "These are evidence-based estimates, not exact ROI. Adjust assumptions with real team data.";
9974
+ function buildSavingsReport(dir, opts = {}, now = /* @__PURE__ */ new Date()) {
9975
+ const { assumptions: a, source: source2 } = loadAssumptions(dir);
9976
+ const impact = buildImpactReport(dir, { scope: opts.scope, scopeSource: opts.scopeSource }, now);
9977
+ const projectContext = reportingProjectContext(dir);
9978
+ const completed = impact.traceability.completed_work_items;
9979
+ const wiWithOwnership = parseRatioNumerator(impact.traceability.work_items_connected_to_code);
9980
+ const acceptanceCov = impact.knowledge_coverage.find((c) => c.label.toLowerCase().includes("acceptance"));
9981
+ const wiWithAcceptance = acceptanceCov?.have ?? 0;
9982
+ const graphQuality = impact.graph_quality.available ? impact.graph_quality.quality : "unknown";
9983
+ const readiness = impact.context_readiness.level;
9984
+ const ctxPrepH = round2(completed * a.context_preparation_minutes_saved_per_work_item / 60);
9985
+ const reviewH = round2(wiWithOwnership * a.review_minutes_saved_per_work_item_with_ownership / 60);
9986
+ const clarH = round2(wiWithAcceptance * a.clarification_minutes_saved_per_ready_work_item / 60);
9987
+ const readinessMult = READINESS_MULT[readiness] ?? 0.5;
9988
+ const onboardH = round2(a.expected_new_contributors_per_month * a.onboarding_hours_saved_per_new_contributor * readinessMult);
9989
+ const graphMult = GRAPH_MULT[graphQuality] ?? 0;
9990
+ const archH = round2(a.architecture_discovery_hours_saved_when_graph_good * graphMult);
9991
+ const guard = buildGuardHistory(dir);
9992
+ let driftSavings;
9993
+ if (!guard.available) {
9994
+ driftSavings = { available: false, hours: 0, reason: "Guard history is not persisted yet." };
9995
+ } else if (guard.resolved > 0) {
9996
+ driftSavings = {
9997
+ available: true,
9998
+ hours: round2(guard.resolved * a.rework_hours_avoided_per_resolved_drift),
9999
+ formula: `${guard.resolved} resolved drift warnings \xD7 ${a.rework_hours_avoided_per_resolved_drift} h`
10000
+ };
10001
+ } else {
10002
+ driftSavings = {
10003
+ available: true,
10004
+ hours: 0,
10005
+ formula: `0 resolved drift warnings \xD7 ${a.rework_hours_avoided_per_resolved_drift} h`,
10006
+ reason: "Guard history exists, but no resolved drift warnings have been recorded yet."
10007
+ };
10008
+ }
10009
+ const observedHours = round2(ctxPrepH + reviewH + clarH + driftSavings.hours);
10010
+ const projectedHours = round2(onboardH + archH);
10011
+ const observedValue = Math.round(observedHours * a.hourly_cost);
10012
+ const projectedValue = Math.round(projectedHours * a.hourly_cost);
10013
+ const reasons = [];
10014
+ let level;
10015
+ const verifiedDelivery = impact.evidence.some((item) => item.id === "delivery.verification" && item.classification === "observed");
10016
+ const evidenceStrong = graphQuality === "good" && impact.ownership_coverage.coverage_percent >= 70 && verifiedDelivery;
10017
+ if (!evidenceStrong || graphQuality === "empty") {
10018
+ level = "Low";
10019
+ reasons.push("Delivery, ownership or graph evidence is insufficient for a reliable estimate.");
10020
+ } else if (evidenceStrong && source2 === "file" && Boolean(a.calibrated_at) && guard.available && guard.resolved > 0) {
10021
+ level = "High";
10022
+ reasons.push("Strong evidence, calibrated assumptions and recorded drift resolution.");
10023
+ } else {
10024
+ level = "Medium";
10025
+ reasons.push("Strong knowledge and graph evidence.");
10026
+ }
10027
+ if (!a.calibrated_at && level === "High") {
10028
+ level = "Medium";
10029
+ reasons.push("Uncalibrated assumptions cannot support High confidence.");
10030
+ }
10031
+ if (!guard.available) {
10032
+ reasons.push("Guard history is not persisted yet \u2014 avoided rework is not estimated.");
10033
+ } else if (guard.resolved > 0) {
10034
+ reasons.push(`Guard history available (${guard.resolved} resolved drift warning(s)).`);
10035
+ } else {
10036
+ reasons.push("Guard history available, but no resolved drift warnings have been recorded yet.");
10037
+ }
10038
+ reasons.push(source2 === "file" ? "Assumptions come from `.kaddo/savings.yml`." : "Savings assumptions are defaults and should be calibrated.");
10039
+ const actions = [];
10040
+ if (source2 === "default") actions.push("Run `kaddo savings init` to customize assumptions.");
10041
+ actions.push("Calibrate hourly cost and team assumptions with real team data.");
10042
+ actions.push("Run `kaddo impact` to verify the underlying evidence quality.");
10043
+ actions.push("Use this report as directional evidence, not accounting data.");
10044
+ if (!guard.available) {
10045
+ actions.push("Future: persist Guard history to estimate avoided rework.");
10046
+ } else if (guard.resolved === 0) {
10047
+ actions.push("Continue running `kaddo guard --record` before important commits to capture resolved drift warnings.");
10048
+ if (guard.open > 0) actions.push("Review open drift warnings with `kaddo drift`.");
10049
+ } else {
10050
+ actions.push("Use drift history to calibrate `rework_hours_avoided_per_resolved_drift`.");
10051
+ }
10052
+ const calibrationOpportunities = !a.calibrated_at ? {
10053
+ available: true,
10054
+ reason: source2 === "default" ? "Default assumptions are uncalibrated estimates." : "Project assumptions are not marked as calibrated.",
10055
+ opportunities: [
10056
+ { area: "Context preparation", suggested_evidence: "Compare preparation effort on comparable tasks before and after using the knowledge artifacts." },
10057
+ { area: "Review effort", suggested_evidence: "Record a baseline for comparable reviews with similar ownership coverage." },
10058
+ { area: "Clarification reduction", suggested_evidence: "Estimate effort spent resolving repeated scope or context questions." },
10059
+ { area: "Architecture discovery", suggested_evidence: "Compare discovery time for similar dependency or relationship analyses." }
10060
+ ]
10061
+ } : { available: false, reason: `Assumptions are marked as calibrated on ${a.calibrated_at}.`, opportunities: [] };
10062
+ return {
10063
+ generated_at: now.toISOString(),
10064
+ project: impact.project,
10065
+ project_context: projectContext,
10066
+ scope: impact.scope,
10067
+ reporting_period: { observed: "all recorded project history", projected: "per month", note: "Historical estimates and future monthly projections are intentionally not added together." },
10068
+ evidence_classification: [
10069
+ { id: "completed-work-items", label: "Completed Work Items", classification: completed > 0 ? "observed" : "unknown", reason: completed > 0 ? "Lifecycle state is recorded in Work Items." : "No completed Work Items were recorded." },
10070
+ { id: "guard-resolution", label: "Resolved drift warnings", classification: guard.available ? "observed" : "unknown", reason: guard.available ? "Derived from recorded Guard history." : "No Guard history was recorded." },
10071
+ { id: "assumptions", label: "Savings assumptions", classification: "estimated", reason: a.calibrated_at ? `Project assumptions were calibrated on ${a.calibrated_at}.` : source2 === "file" ? "Project-provided assumptions are not marked as calibrated." : "Defaults are uncalibrated estimates." },
10072
+ { id: "team-expectations", label: "Future team activity", classification: "projected", reason: "Monthly contributor and Work Item expectations model a future scenario." }
10073
+ ],
10074
+ currency: a.currency,
10075
+ disclaimer: SAVINGS_DISCLAIMER,
10076
+ assumptions_source: source2,
10077
+ assumptions: {
10078
+ hourly_cost: a.hourly_cost,
10079
+ context_preparation_minutes_saved_per_work_item: a.context_preparation_minutes_saved_per_work_item,
10080
+ review_minutes_saved_per_work_item_with_ownership: a.review_minutes_saved_per_work_item_with_ownership,
10081
+ clarification_minutes_saved_per_ready_work_item: a.clarification_minutes_saved_per_ready_work_item,
10082
+ onboarding_hours_saved_per_new_contributor: a.onboarding_hours_saved_per_new_contributor,
10083
+ expected_new_contributors_per_month: a.expected_new_contributors_per_month,
10084
+ architecture_discovery_hours_saved_when_graph_good: a.architecture_discovery_hours_saved_when_graph_good
10085
+ },
10086
+ evidence: {
10087
+ knowledge_impact_score: impact.score,
10088
+ completed_work_items: completed,
10089
+ ownership_coverage_percent: impact.ownership_coverage.coverage_percent,
10090
+ work_items_with_acceptance_criteria: acceptanceCov ? `${acceptanceCov.have}/${acceptanceCov.total}` : "0/0",
10091
+ graph_quality: graphQuality,
10092
+ graph_nodes: impact.graph_quality.available ? impact.graph_quality.nodes : null,
10093
+ graph_edges: impact.graph_quality.available ? impact.graph_quality.edges : null,
10094
+ context_readiness: readiness,
10095
+ guard_history_available: guard.available,
10096
+ guard_runs_recorded: guard.total_runs,
10097
+ resolved_drift_warnings: guard.resolved
10098
+ },
10099
+ estimated_savings: {
10100
+ context_preparation: { hours: ctxPrepH, formula: `${completed} Work Items \xD7 ${a.context_preparation_minutes_saved_per_work_item} min` },
10101
+ review_effort: { hours: reviewH, formula: `${wiWithOwnership} Work Items with ownership \xD7 ${a.review_minutes_saved_per_work_item_with_ownership} min` },
10102
+ clarification_reduction: { hours: clarH, formula: `${wiWithAcceptance} Work Items with Acceptance Criteria \xD7 ${a.clarification_minutes_saved_per_ready_work_item} min` },
10103
+ onboarding: { hours: onboardH, formula: `${a.expected_new_contributors_per_month} contributor \xD7 ${a.onboarding_hours_saved_per_new_contributor} h \xD7 ${readinessMult.toFixed(2)} readiness multiplier` },
10104
+ architecture_discovery: { hours: archH, formula: `${a.architecture_discovery_hours_saved_when_graph_good} h \xD7 ${graphMult.toFixed(2)} graph multiplier` },
10105
+ drift_prevention: driftSavings
10106
+ },
10107
+ totals: {
10108
+ observed_history_estimate: { estimated_hours: observedHours, estimated_value: observedValue, currency: a.currency },
10109
+ monthly_projection: { estimated_hours: projectedHours, estimated_value: projectedValue, currency: a.currency }
10110
+ },
10111
+ total: { estimated_hours_saved: observedHours, estimated_value: observedValue, currency: a.currency },
10112
+ confidence: { level, reasons },
10113
+ calibration_opportunities: calibrationOpportunities,
10114
+ suggested_actions: actions
10115
+ };
10116
+ }
10117
+ function renderSavingsMarkdown(r) {
10118
+ const L = [];
10119
+ L.push("# Kaddo Estimated Savings Report", "");
10120
+ L.push(`Generated at: ${r.generated_at}`);
10121
+ L.push(`Project: ${r.project}`);
10122
+ L.push(`Project context: state=${r.project_context.state}; mode=${r.project_context.mode}; repositories=${r.project_context.repository_structure}`);
10123
+ L.push(`Scope: ${r.scope}`);
10124
+ L.push(`Currency: ${r.currency}`);
10125
+ L.push("");
10126
+ L.push("## Disclaimer", "");
10127
+ L.push(r.disclaimer, "");
10128
+ L.push("## Evidence Classification", "");
10129
+ for (const item of r.evidence_classification) L.push(`- ${item.label}: ${item.classification} \u2014 ${item.reason}`);
10130
+ L.push("");
10131
+ L.push("## Executive Summary", "");
10132
+ L.push(`- Historical estimate: ${r.totals.observed_history_estimate.estimated_hours} hours`);
10133
+ L.push(`- Monthly projection: ${r.totals.monthly_projection.estimated_hours} hours`);
10134
+ L.push(`- Confidence: ${r.confidence.level}`);
10135
+ if (r.assumptions_source === "default") L.push("- Using default assumptions. Run `kaddo savings init` to customize them.");
10136
+ L.push("");
10137
+ L.push("## Assumptions", "");
10138
+ L.push(`- Hourly cost: ${r.assumptions.hourly_cost} ${r.currency}`);
10139
+ L.push(`- Context preparation saved per Work Item: ${r.assumptions.context_preparation_minutes_saved_per_work_item} min`);
10140
+ L.push(`- Review saved per Work Item with ownership: ${r.assumptions.review_minutes_saved_per_work_item_with_ownership} min`);
10141
+ L.push(`- Clarification saved per Work Item with acceptance criteria: ${r.assumptions.clarification_minutes_saved_per_ready_work_item} min`);
10142
+ L.push(`- Onboarding saved per new contributor: ${r.assumptions.onboarding_hours_saved_per_new_contributor} h`);
10143
+ L.push(`- Expected new contributors per month: ${r.assumptions.expected_new_contributors_per_month}`);
10144
+ L.push(`- Architecture discovery saved when graph is good: ${r.assumptions.architecture_discovery_hours_saved_when_graph_good} h`);
10145
+ L.push("");
10146
+ L.push("## Evidence Used", "");
10147
+ const e = r.evidence;
10148
+ L.push(`- Legacy Knowledge Impact Score: ${e.knowledge_impact_score ?? "not available"}${e.knowledge_impact_score !== null ? "/100" : ""} (deprecated; informational only and not used for confidence)`);
10149
+ L.push(`- Completed Work Items: ${e.completed_work_items}`);
10150
+ L.push(`- Ownership coverage: ${e.ownership_coverage_percent}%`);
10151
+ L.push(`- Work Items with Acceptance Criteria: ${e.work_items_with_acceptance_criteria}`);
10152
+ L.push(`- Graph quality: ${e.graph_quality}`);
10153
+ if (e.graph_nodes !== null) L.push(`- Graph nodes: ${e.graph_nodes}`);
10154
+ if (e.graph_edges !== null) L.push(`- Graph edges: ${e.graph_edges}`);
10155
+ L.push(`- Context readiness: ${e.context_readiness}`);
10156
+ if (e.guard_history_available) {
10157
+ L.push("- Guard history: available");
10158
+ L.push(`- Guard runs recorded: ${e.guard_runs_recorded}`);
10159
+ L.push(`- Resolved drift warnings: ${e.resolved_drift_warnings}`);
10160
+ } else {
10161
+ L.push("- Guard history: not available");
10162
+ }
10163
+ L.push("");
10164
+ L.push("## Estimated Savings", "");
10165
+ const s = r.estimated_savings;
10166
+ const line = (title, l) => {
10167
+ L.push(`### ${title}`, "");
10168
+ L.push(`- Formula: ${l.formula}`);
10169
+ L.push(`- Estimated: ${l.hours} h`, "");
10170
+ };
10171
+ line("Context Preparation", s.context_preparation);
10172
+ line("Review Effort", s.review_effort);
10173
+ line("Clarification Reduction", s.clarification_reduction);
10174
+ line("Onboarding", s.onboarding);
10175
+ line("Architecture Discovery", s.architecture_discovery);
10176
+ L.push("### Drift Prevention", "");
10177
+ if (s.drift_prevention.available) {
10178
+ L.push(`- Formula: ${s.drift_prevention.formula}`);
10179
+ L.push(`- Estimated: ${s.drift_prevention.hours} h`);
10180
+ if (s.drift_prevention.reason) L.push(`- Reason: ${s.drift_prevention.reason}`);
10181
+ L.push("");
10182
+ } else {
10183
+ L.push("- Not available yet.");
10184
+ L.push(`- Reason: ${s.drift_prevention.reason}`, "");
10185
+ }
10186
+ L.push("## Total (Period-separated)", "");
10187
+ L.push(`- Historical estimate (all recorded project history): ${r.totals.observed_history_estimate.estimated_hours} h / ${r.totals.observed_history_estimate.estimated_value} ${r.currency}`);
10188
+ L.push(`- Monthly projection: ${r.totals.monthly_projection.estimated_hours} h / ${r.totals.monthly_projection.estimated_value} ${r.currency}`);
10189
+ L.push(`- Note: ${r.reporting_period.note}`);
10190
+ L.push("");
10191
+ L.push("## Confidence", "");
10192
+ L.push(`Confidence: ${r.confidence.level}`, "", "Reason:");
10193
+ for (const reason of r.confidence.reasons) L.push(`- ${reason}`);
10194
+ L.push("");
10195
+ L.push("## Calibration Opportunities", "");
10196
+ if (!r.calibration_opportunities.available) {
10197
+ L.push(`- ${r.calibration_opportunities.reason}`);
10198
+ } else {
10199
+ L.push(`- ${r.calibration_opportunities.reason}`);
10200
+ L.push("- Use external, aggregate project observations; do not collect or store personal data.");
10201
+ for (const opportunity of r.calibration_opportunities.opportunities) {
10202
+ L.push(`- ${opportunity.area}: ${opportunity.suggested_evidence}`);
10203
+ }
10204
+ }
10205
+ L.push("");
10206
+ L.push("## Suggested Actions", "");
10207
+ r.suggested_actions.forEach((act, i) => L.push(`${i + 1}. ${act}`));
10208
+ L.push("");
10209
+ return L.join("\n");
10210
+ }
10211
+ function serializeSavingsJson(r) {
10212
+ return JSON.stringify(r, null, 2) + "\n";
10213
+ }
10214
+
8962
10215
  // src/core/resource-write.ts
8963
10216
  import fs2 from "fs";
8964
10217
  import path2 from "path";
8965
- import matter10 from "gray-matter";
10218
+ import matter11 from "gray-matter";
8966
10219
  var RESOURCES_DIR = "knowledge/tech/resources";
8967
10220
  var ResourceWriteError = class extends Error {
8968
10221
  constructor(code, message) {
@@ -9042,7 +10295,7 @@ function buildFrontmatter(id, input, base = {}) {
9042
10295
  return data;
9043
10296
  }
9044
10297
  function serialize(data, body) {
9045
- return matter10.stringify(`
10298
+ return matter11.stringify(`
9046
10299
  ${body.trim()}
9047
10300
  `, data);
9048
10301
  }
@@ -9082,7 +10335,7 @@ function updateResource(dir, id, input) {
9082
10335
  throw new ResourceWriteError("VALIDATION_FAILED", findings.filter((f) => f.level === "error").map((f) => f.message).join("; "));
9083
10336
  }
9084
10337
  const raw = readFile(match.filePath);
9085
- const parsed = matter10(raw);
10338
+ const parsed = matter11(raw);
9086
10339
  const base = parsed.data ?? {};
9087
10340
  const data = buildFrontmatter(match.id || id, input, base);
9088
10341
  let body = parsed.content.trim();
@@ -9353,10 +10606,10 @@ function analyzeCrossRepoEvidence(input) {
9353
10606
  }
9354
10607
 
9355
10608
  // src/core/work-items.ts
9356
- import matter11 from "gray-matter";
10609
+ import matter12 from "gray-matter";
9357
10610
 
9358
10611
  // src/core/system-topology.ts
9359
- import { parse as parseYaml8, stringify as stringifyYaml5 } from "yaml";
10612
+ import { parse as parseYaml9, stringify as stringifyYaml5 } from "yaml";
9360
10613
  import fs3 from "fs";
9361
10614
  import path3 from "path";
9362
10615
  import crypto from "crypto";
@@ -9403,7 +10656,7 @@ function loadSystemTopology(dir) {
9403
10656
  function parseTopologyContent(raw, dir) {
9404
10657
  let parsed;
9405
10658
  try {
9406
- parsed = parseYaml8(raw) ?? {};
10659
+ parsed = parseYaml9(raw) ?? {};
9407
10660
  } catch {
9408
10661
  return { entities: [], relationships: [], findings: [{ level: "blocking", message: "The topology could not be parsed." }] };
9409
10662
  }
@@ -9735,8 +10988,8 @@ function parseGraphReason(v) {
9735
10988
  if (!v || typeof v !== "object") return null;
9736
10989
  const o = v;
9737
10990
  const relationship = typeof o.relationship === "string" && o.relationship.trim() ? o.relationship.trim() : null;
9738
- const path6 = Array.isArray(o.path) ? o.path.map(String).filter(Boolean) : [];
9739
- return relationship || path6.length ? { relationship, path: path6 } : null;
10991
+ const path8 = Array.isArray(o.path) ? o.path.map(String).filter(Boolean) : [];
10992
+ return relationship || path8.length ? { relationship, path: path8 } : null;
9740
10993
  }
9741
10994
  function parseExplain(o) {
9742
10995
  const refs = Array.isArray(o.evidence) ? o.evidence : Array.isArray(o.evidence_refs) ? o.evidence_refs : [];
@@ -9791,7 +11044,7 @@ function parseOriginalSnapshot(fm) {
9791
11044
  function readBody(filePath) {
9792
11045
  try {
9793
11046
  const raw = readFile(filePath);
9794
- return matter11(raw).content;
11047
+ return matter12(raw).content;
9795
11048
  } catch {
9796
11049
  return "";
9797
11050
  }
@@ -9958,7 +11211,7 @@ function parseRelatedKnowledge(fm, knowledgeById) {
9958
11211
  import fs4 from "fs";
9959
11212
  import path4 from "path";
9960
11213
  import crypto2 from "crypto";
9961
- import matter12 from "gray-matter";
11214
+ import matter13 from "gray-matter";
9962
11215
 
9963
11216
  // src/core/knowledge-levels.ts
9964
11217
  var WORK_ITEM_TYPES2 = ["feature", "bugfix", "hotfix", "spike", "chore"];
@@ -10168,7 +11421,7 @@ function slugify2(s) {
10168
11421
  function nextWorkItemId(dir) {
10169
11422
  const wiDir = join(dir, WORK_ITEMS_DIR);
10170
11423
  let max = 0;
10171
- const walk = (d) => {
11424
+ const walk2 = (d) => {
10172
11425
  if (!exists(d)) return;
10173
11426
  for (const entry of fs4.readdirSync(d)) {
10174
11427
  const full = join(d, entry);
@@ -10176,11 +11429,11 @@ function nextWorkItemId(dir) {
10176
11429
  const m = entry.match(/WI-(\d+)/);
10177
11430
  if (m) max = Math.max(max, parseInt(m[1], 10));
10178
11431
  } else if (!entry.startsWith(".")) {
10179
- walk(full);
11432
+ walk2(full);
10180
11433
  }
10181
11434
  }
10182
11435
  };
10183
- walk(wiDir);
11436
+ walk2(wiDir);
10184
11437
  return `WI-${String(max + 1).padStart(3, "0")}`;
10185
11438
  }
10186
11439
  function atomicWrite3(filePath, content) {
@@ -10365,7 +11618,7 @@ function applyFrontmatter(data, input) {
10365
11618
  return next;
10366
11619
  }
10367
11620
  function serialize2(data, body) {
10368
- return matter12.stringify(`
11621
+ return matter13.stringify(`
10369
11622
  ${body.trim()}
10370
11623
  `, data);
10371
11624
  }
@@ -10424,7 +11677,7 @@ function toInput(data, content) {
10424
11677
  function getWorkItemForEdit(dir, id) {
10425
11678
  const { filePath, relPath } = findArtifact(dir, id);
10426
11679
  const raw = readFile(filePath);
10427
- const { data, content } = matter12(raw);
11680
+ const { data, content } = matter13(raw);
10428
11681
  const status = lifecycleStateOf({ status: String(data.status ?? ""), filePath });
10429
11682
  const input = toInput(data, content);
10430
11683
  const editable = EDITABLE_STATES.includes(status);
@@ -10517,7 +11770,7 @@ function updateWorkItem(dir, id, input, expectedRevision) {
10517
11770
  if (revisionOf(raw) !== expectedRevision) {
10518
11771
  throw new WorkItemWriteError("WORK_ITEM_CONFLICT", "This Work Item changed outside Kaddo Admin. Reload the latest version before saving.");
10519
11772
  }
10520
- const { data, content } = matter12(raw);
11773
+ const { data, content } = matter13(raw);
10521
11774
  const status = lifecycleStateOf({ status: String(data.status ?? ""), filePath });
10522
11775
  if (!EDITABLE_STATES.includes(status)) {
10523
11776
  throw new WorkItemWriteError("WORK_ITEM_NOT_EDITABLE", `A ${status} Work Item cannot be edited. Reopen it as Draft first.`);
@@ -10531,7 +11784,7 @@ function updateWorkItem(dir, id, input, expectedRevision) {
10531
11784
  function validateWorkItem(dir, id) {
10532
11785
  const { filePath } = findArtifact(dir, id);
10533
11786
  const raw = readFile(filePath);
10534
- const { data, content } = matter12(raw);
11787
+ const { data, content } = matter13(raw);
10535
11788
  const input = toInput(data, content);
10536
11789
  const findings = [];
10537
11790
  const modules = validModuleIds(dir);
@@ -10584,7 +11837,7 @@ function transitionWorkItem(dir, id, to, expectedRevision) {
10584
11837
  if (revisionOf(raw) !== expectedRevision) {
10585
11838
  throw new WorkItemWriteError("WORK_ITEM_CONFLICT", "This Work Item changed outside Kaddo Admin. Reload the latest version before continuing.");
10586
11839
  }
10587
- const { data, content } = matter12(raw);
11840
+ const { data, content } = matter13(raw);
10588
11841
  const from = lifecycleStateOf({ status: String(data.status ?? ""), filePath });
10589
11842
  if (!(ALLOWED[from] ?? []).includes(to)) {
10590
11843
  throw new WorkItemWriteError("INVALID_TRANSITION", `Cannot transition a ${from} Work Item to ${to}.`);
@@ -10850,19 +12103,19 @@ function findSystemPaths(dir, source2, target, opts = {}) {
10850
12103
  out.get(r.source).push(r.target);
10851
12104
  }
10852
12105
  const paths = [];
10853
- const walk = (node, path6) => {
12106
+ const walk2 = (node, path8) => {
10854
12107
  if (paths.length >= 20) return;
10855
- if (node === target && path6.length > 1) {
10856
- paths.push([...path6]);
12108
+ if (node === target && path8.length > 1) {
12109
+ paths.push([...path8]);
10857
12110
  return;
10858
12111
  }
10859
- if (path6.length > maxDepth) return;
12112
+ if (path8.length > maxDepth) return;
10860
12113
  for (const nxt of out.get(node) ?? []) {
10861
- if (path6.includes(nxt)) continue;
10862
- walk(nxt, [...path6, nxt]);
12114
+ if (path8.includes(nxt)) continue;
12115
+ walk2(nxt, [...path8, nxt]);
10863
12116
  }
10864
12117
  };
10865
- walk(source2, [source2]);
12118
+ walk2(source2, [source2]);
10866
12119
  return paths;
10867
12120
  }
10868
12121
  function getImpactCandidates(dir, seedIds, opts = {}) {
@@ -10884,14 +12137,14 @@ function getImpactCandidates(dir, seedIds, opts = {}) {
10884
12137
  existing.reason.push(reason);
10885
12138
  continue;
10886
12139
  }
10887
- const path6 = findSystemPaths(dir, seed, n.id, { maxDepth: opts.maxDepth ?? DEFAULT_MAX_DEPTH })[0];
12140
+ const path8 = findSystemPaths(dir, seed, n.id, { maxDepth: opts.maxDepth ?? DEFAULT_MAX_DEPTH })[0];
10888
12141
  candidates.set(n.id, {
10889
12142
  nodeId: n.id,
10890
12143
  label: n.label,
10891
12144
  kind: n.type,
10892
12145
  ...n.moduleId ? { moduleId: n.moduleId } : {},
10893
12146
  reason: [reason],
10894
- ...path6 ? { graphPath: path6.map((id) => byId.get(id)?.label ?? id) } : {},
12147
+ ...path8 ? { graphPath: path8.map((id) => byId.get(id)?.label ?? id) } : {},
10895
12148
  ...n.implementationRefs?.length ? { implementationRefs: n.implementationRefs } : {},
10896
12149
  ...n.knowledgeRefs?.length ? { knowledgeRefs: n.knowledgeRefs } : {},
10897
12150
  status: "candidate",
@@ -11760,7 +13013,7 @@ function deriveImplementationStatus(repos) {
11760
13013
  // src/core/work-item-import.ts
11761
13014
  import crypto3 from "crypto";
11762
13015
  import fs5 from "fs";
11763
- import matter13 from "gray-matter";
13016
+ import matter14 from "gray-matter";
11764
13017
  var MAX_INPUT_BYTES = 102400;
11765
13018
  var LIFECYCLE_FIELDS = /* @__PURE__ */ new Set([
11766
13019
  "id",
@@ -11782,7 +13035,7 @@ function detectFormat(raw) {
11782
13035
  if (!trimmed) throw new ImportError("EMPTY_INPUT", "Import content is empty.");
11783
13036
  if (trimmed.startsWith("---")) {
11784
13037
  try {
11785
- const { data } = matter13(trimmed);
13038
+ const { data } = matter14(trimmed);
11786
13039
  if (data && typeof data === "object" && Object.keys(data).length > 0) {
11787
13040
  const d = data;
11788
13041
  if (d.type === "work-item" || d.id && typeof d.id === "string" && /^WI-\d+/.test(d.id)) {
@@ -11804,7 +13057,7 @@ function parseContent(raw) {
11804
13057
  let bodyText = trimmed;
11805
13058
  if (format === "kaddo-frontmatter" || format === "markdown-frontmatter") {
11806
13059
  try {
11807
- const parsed = matter13(trimmed);
13060
+ const parsed = matter14(trimmed);
11808
13061
  frontmatterFields = parsed.data ?? {};
11809
13062
  bodyText = parsed.content.trim();
11810
13063
  } catch {
@@ -11901,7 +13154,7 @@ function findDuplicateByHash(dir, hash) {
11901
13154
  const raw = readFile(item.filePath);
11902
13155
  if (!raw) continue;
11903
13156
  try {
11904
- const { data } = matter13(raw);
13157
+ const { data } = matter14(raw);
11905
13158
  const source2 = data?.source;
11906
13159
  if (source2 && typeof source2 === "object" && !Array.isArray(source2)) {
11907
13160
  const s = source2;
@@ -12010,8 +13263,8 @@ var ImportError = class extends Error {
12010
13263
  };
12011
13264
 
12012
13265
  // src/services/integrations.ts
12013
- import matter14 from "gray-matter";
12014
- import { parse as parseYaml9, stringify as stringifyYaml6 } from "yaml";
13266
+ import matter15 from "gray-matter";
13267
+ import { parse as parseYaml10, stringify as stringifyYaml6 } from "yaml";
12015
13268
 
12016
13269
  // ../integrations/src/errors.ts
12017
13270
  var RETRYABLE = /* @__PURE__ */ new Set([
@@ -12779,8 +14032,8 @@ async function handleJiraResponse(res) {
12779
14032
  }
12780
14033
  return await res.json();
12781
14034
  }
12782
- async function jiraFetch(baseUrl, path6, auth, timeoutMs, params) {
12783
- const url = new URL(path6, baseUrl + "/");
14035
+ async function jiraFetch(baseUrl, path8, auth, timeoutMs, params) {
14036
+ const url = new URL(path8, baseUrl + "/");
12784
14037
  if (params) for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
12785
14038
  const controller = new AbortController();
12786
14039
  const timer = setTimeout(() => controller.abort(), timeoutMs);
@@ -12798,8 +14051,8 @@ async function jiraFetch(baseUrl, path6, auth, timeoutMs, params) {
12798
14051
  clearTimeout(timer);
12799
14052
  }
12800
14053
  }
12801
- async function jiraPost(baseUrl, path6, auth, timeoutMs, body) {
12802
- const url = new URL(path6, baseUrl + "/");
14054
+ async function jiraPost(baseUrl, path8, auth, timeoutMs, body) {
14055
+ const url = new URL(path8, baseUrl + "/");
12803
14056
  const controller = new AbortController();
12804
14057
  const timer = setTimeout(() => controller.abort(), timeoutMs);
12805
14058
  try {
@@ -12989,7 +14242,7 @@ function loadRaw(dir) {
12989
14242
  const abs = join(dir, INTEGRATIONS_FILE);
12990
14243
  if (!exists(abs)) return { integrations: [] };
12991
14244
  try {
12992
- return parseYaml9(readFile(abs)) ?? { integrations: [] };
14245
+ return parseYaml10(readFile(abs)) ?? { integrations: [] };
12993
14246
  } catch {
12994
14247
  return { integrations: [] };
12995
14248
  }
@@ -13352,7 +14605,7 @@ function findLinkedWorkItem(dir, integrationId, externalId) {
13352
14605
  for (const art of discoverWorkItems(dir)) {
13353
14606
  let data;
13354
14607
  try {
13355
- data = matter14(readFile(art.filePath)).data;
14608
+ data = matter15(readFile(art.filePath)).data;
13356
14609
  } catch {
13357
14610
  continue;
13358
14611
  }
@@ -13368,7 +14621,7 @@ function buildImportIndex(dir) {
13368
14621
  for (const art of discoverWorkItems(dir)) {
13369
14622
  let data;
13370
14623
  try {
13371
- data = matter14(readFile(art.filePath)).data;
14624
+ data = matter15(readFile(art.filePath)).data;
13372
14625
  } catch {
13373
14626
  continue;
13374
14627
  }
@@ -13433,7 +14686,7 @@ ${item.description}` : item.title;
13433
14686
  }
13434
14687
 
13435
14688
  // src/core/telemetry-consent.ts
13436
- import { parse as parseYaml10, stringify as stringifyYaml7 } from "yaml";
14689
+ import { parse as parseYaml11, stringify as stringifyYaml7 } from "yaml";
13437
14690
  var CURRENT_CONSENT_VERSION = 1;
13438
14691
  var DEFERRAL_DURATION_MS = 24 * 60 * 60 * 1e3;
13439
14692
  function getConsentState(config) {
@@ -13458,7 +14711,7 @@ function persistConsent(dir, consent) {
13458
14711
  const configPath = join(dir, ".kaddo", "config.yml");
13459
14712
  if (!exists(configPath)) return;
13460
14713
  const raw = readFile(configPath);
13461
- const doc = parseYaml10(raw) ?? {};
14714
+ const doc = parseYaml11(raw) ?? {};
13462
14715
  const prev = doc.telemetry ?? {};
13463
14716
  delete prev.enabled;
13464
14717
  doc.telemetry = { ...prev, consent, consentVersion: CURRENT_CONSENT_VERSION };
@@ -13544,7 +14797,7 @@ function getStatus(dir) {
13544
14797
  }
13545
14798
 
13546
14799
  // src/core/initiative-write.ts
13547
- import matter15 from "gray-matter";
14800
+ import matter16 from "gray-matter";
13548
14801
  var WORK_ITEMS_DIR2 = "knowledge/delivery/work-items";
13549
14802
  var DRAFT_DIR = `${WORK_ITEMS_DIR2}/draft`;
13550
14803
  var ROADMAP_PATH2 = "knowledge/delivery/roadmap.md";
@@ -13657,7 +14910,7 @@ function buildInitiativeContent(id, input) {
13657
14910
  if (input.priority) data.priority = input.priority;
13658
14911
  if (input.source) data.source = input.source;
13659
14912
  if (input.sourceId) data.source_id = input.sourceId;
13660
- return matter15.stringify("\n" + (input.body ?? defaultBody(input.title.trim())), data);
14913
+ return matter16.stringify("\n" + (input.body ?? defaultBody(input.title.trim())), data);
13661
14914
  }
13662
14915
  function createInitiative(dir, input) {
13663
14916
  if (!input.title?.trim()) throw new InitiativeWriteError("Initiative title is required.");
@@ -13681,10 +14934,10 @@ function transitionInitiative(dir, id, to) {
13681
14934
  throw new InitiativeWriteError(`Invalid transition ${ini.status} \u2192 ${to}.`);
13682
14935
  }
13683
14936
  const raw = readFile(ini.filePath);
13684
- const { data, content } = matter15(raw, {});
14937
+ const { data, content } = matter16(raw, {});
13685
14938
  data.status = to;
13686
14939
  if (to === "completed") data.completed_at = today();
13687
- const newContent = matter15.stringify(content, data);
14940
+ const newContent = matter16.stringify(content, data);
13688
14941
  writeFile(ini.filePath, newContent);
13689
14942
  const updated = parseInitiative(dir, ini.filePath, newContent);
13690
14943
  if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after transition.");
@@ -13694,7 +14947,7 @@ function addCandidate(dir, id, candidate) {
13694
14947
  const ini = getInitiative(dir, id);
13695
14948
  if (!ini) throw new InitiativeWriteError(`Initiative ${id} not found.`);
13696
14949
  const raw = readFile(ini.filePath);
13697
- const { data, content } = matter15(raw, {});
14950
+ const { data, content } = matter16(raw, {});
13698
14951
  const existing = Array.isArray(data.candidates) ? data.candidates : [];
13699
14952
  const fallbackId = `WI-CANDIDATE-${String(existing.length + 1).padStart(3, "0")}`;
13700
14953
  const normalized = normalizeCandidate(candidate, fallbackId);
@@ -13702,7 +14955,7 @@ function addCandidate(dir, id, candidate) {
13702
14955
  throw new InitiativeWriteError(`Candidate ${normalized.id} already exists in ${id}.`);
13703
14956
  }
13704
14957
  data.candidates = [...existing, candidateToData(normalized)];
13705
- const newContent = matter15.stringify(content, data);
14958
+ const newContent = matter16.stringify(content, data);
13706
14959
  writeFile(ini.filePath, newContent);
13707
14960
  const updated = parseInitiative(dir, ini.filePath, newContent);
13708
14961
  if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after adding a candidate.");
@@ -13712,7 +14965,7 @@ function updateInitiative(dir, id, patch) {
13712
14965
  const ini = getInitiative(dir, id);
13713
14966
  if (!ini) throw new InitiativeWriteError(`Initiative ${id} not found.`);
13714
14967
  const raw = readFile(ini.filePath);
13715
- const { data, content } = matter15(raw, {});
14968
+ const { data, content } = matter16(raw, {});
13716
14969
  if (patch.title !== void 0) {
13717
14970
  if (!patch.title.trim()) throw new InitiativeWriteError("Initiative title cannot be empty.");
13718
14971
  data.title = patch.title.trim();
@@ -13722,7 +14975,7 @@ function updateInitiative(dir, id, patch) {
13722
14975
  if (patch.knowledgeLevel !== void 0) data.knowledge_level = patch.knowledgeLevel;
13723
14976
  if (patch.domains !== void 0) data.domains = patch.domains;
13724
14977
  if (patch.relatedCapabilities !== void 0) data.related_capabilities = patch.relatedCapabilities;
13725
- const newContent = matter15.stringify(content, data);
14978
+ const newContent = matter16.stringify(content, data);
13726
14979
  writeFile(ini.filePath, newContent);
13727
14980
  const updated = parseInitiative(dir, ini.filePath, newContent);
13728
14981
  if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after update.");
@@ -13740,10 +14993,10 @@ function addExternalLink(dir, id, link) {
13740
14993
  throw new InitiativeWriteError(`External link ${link.integration}:${link.externalId} already exists on ${id}.`);
13741
14994
  }
13742
14995
  const raw = readFile(ini.filePath);
13743
- const { data, content } = matter15(raw, {});
14996
+ const { data, content } = matter16(raw, {});
13744
14997
  const existing = Array.isArray(data.external_links) ? data.external_links : [];
13745
14998
  data.external_links = [...existing, externalLinkToData(link)];
13746
- const newContent = matter15.stringify(content, data);
14999
+ const newContent = matter16.stringify(content, data);
13747
15000
  writeFile(ini.filePath, newContent);
13748
15001
  const updated = parseInitiative(dir, ini.filePath, newContent);
13749
15002
  if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after adding an external link.");
@@ -13752,7 +15005,7 @@ function addExternalLink(dir, id, link) {
13752
15005
  function nextWorkItemId2(dir) {
13753
15006
  const wiDir = join(dir, WORK_ITEMS_DIR2);
13754
15007
  let max = 0;
13755
- const walk = (d) => {
15008
+ const walk2 = (d) => {
13756
15009
  if (!exists(d)) return;
13757
15010
  for (const entry of readDir(d)) {
13758
15011
  const full = join(d, entry);
@@ -13760,11 +15013,11 @@ function nextWorkItemId2(dir) {
13760
15013
  const m = entry.match(/WI-(\d+)/);
13761
15014
  if (m) max = Math.max(max, parseInt(m[1], 10));
13762
15015
  } else if (!entry.startsWith(".")) {
13763
- walk(full);
15016
+ walk2(full);
13764
15017
  }
13765
15018
  }
13766
15019
  };
13767
- walk(wiDir);
15020
+ walk2(wiDir);
13768
15021
  return `WI-${String(max + 1).padStart(3, "0")}`;
13769
15022
  }
13770
15023
  function buildWorkItemContent(wiId, iniId, candidate) {
@@ -13812,7 +15065,7 @@ function buildWorkItemContent(wiId, iniId, candidate) {
13812
15065
  "_What did we learn? Update after completion._",
13813
15066
  ""
13814
15067
  ].join("\n");
13815
- return matter15.stringify("\n" + body, data);
15068
+ return matter16.stringify("\n" + body, data);
13816
15069
  }
13817
15070
  function materializeCandidate(dir, id, candidateId) {
13818
15071
  const ini = getInitiative(dir, id);
@@ -13829,13 +15082,13 @@ function materializeCandidate(dir, id, candidateId) {
13829
15082
  ensureDir(join(dir, DRAFT_DIR));
13830
15083
  writeFile(join(dir, DRAFT_DIR, fileName), buildWorkItemContent(wiId, ini.id, candidate));
13831
15084
  const raw = readFile(ini.filePath);
13832
- const { data, content } = matter15(raw, {});
15085
+ const { data, content } = matter16(raw, {});
13833
15086
  const cands = Array.isArray(data.candidates) ? data.candidates : [];
13834
15087
  for (const c of cands) {
13835
15088
  if (c && typeof c === "object" && String(c.id) === candidateId) c.materialized_as = wiId;
13836
15089
  }
13837
15090
  data.candidates = cands;
13838
- const newContent = matter15.stringify(content, data);
15091
+ const newContent = matter16.stringify(content, data);
13839
15092
  writeFile(ini.filePath, newContent);
13840
15093
  const updated = parseInitiative(dir, ini.filePath, newContent);
13841
15094
  if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after materialization.");
@@ -13986,7 +15239,7 @@ function evaluateInitiativeCompletion(dir, ini) {
13986
15239
  // src/core/deprecation-write.ts
13987
15240
  import fs6 from "fs";
13988
15241
  import path5 from "path";
13989
- import matter16 from "gray-matter";
15242
+ import matter17 from "gray-matter";
13990
15243
  var DeprecationWriteError = class extends Error {
13991
15244
  constructor(code, message) {
13992
15245
  super(message);
@@ -14004,7 +15257,7 @@ function atomicWrite4(filePath, content) {
14004
15257
  fs6.renameSync(tmp, filePath);
14005
15258
  }
14006
15259
  function serialize3(data, body) {
14007
- return matter16.stringify(`
15260
+ return matter17.stringify(`
14008
15261
  ${body.trim()}
14009
15262
  `, data);
14010
15263
  }
@@ -14070,7 +15323,7 @@ function validateTargetInput(dir, raw) {
14070
15323
  function loadPlanRaw(dir, planId) {
14071
15324
  const match = allPlanArtifacts(dir).find((a) => a.id === planId || a.title === planId);
14072
15325
  if (!match) throw new DeprecationWriteError("NOT_FOUND", `Deprecation Plan "${planId}" not found.`);
14073
- const parsed = matter16(readFile(match.filePath));
15326
+ const parsed = matter17(readFile(match.filePath));
14074
15327
  const data = { ...parsed.data ?? {} };
14075
15328
  return { filePath: match.filePath, data, body: parsed.content.trim() };
14076
15329
  }
@@ -14153,7 +15406,7 @@ function removeTarget(dir, planId, targetId, opts = {}) {
14153
15406
  }
14154
15407
 
14155
15408
  // src/core/deprecation-runbook.ts
14156
- import matter17 from "gray-matter";
15409
+ import matter18 from "gray-matter";
14157
15410
  var PRODUCTION_RUNBOOK_ARTIFACT_TYPE = "production-runbook";
14158
15411
  var PRODUCTION_RUNBOOKS_DIR = "knowledge/delivery/runbooks";
14159
15412
  var RUNBOOK_SECTIONS = [
@@ -14232,7 +15485,7 @@ function buildProductionRunbookContext(dir, planId, targetId) {
14232
15485
  blockers.push(`Dependency ${dependency.id} is not retired (current: ${dependency.lifecycle}).`);
14233
15486
  }
14234
15487
  }
14235
- const path6 = runbookPath(dir, target);
15488
+ const path8 = runbookPath(dir, target);
14236
15489
  return {
14237
15490
  eligible: blockers.length === 0,
14238
15491
  plan: { id: plan.id, title: plan.title, purpose: plan.purpose },
@@ -14240,7 +15493,7 @@ function buildProductionRunbookContext(dir, planId, targetId) {
14240
15493
  resource: target.resource ? getResource(dir, target.resource) : null,
14241
15494
  dependencies,
14242
15495
  blockers,
14243
- nextPath: path6,
15496
+ nextPath: path8,
14244
15497
  nextStep: blockers.length > 0 ? "Resolve the listed safeguards; no production proposal can be persisted yet." : "Review the generated proposal, obtain human approval, execute manually, then record evidence and validate the observation window."
14245
15498
  };
14246
15499
  }
@@ -14333,9 +15586,9 @@ function renderRunbook(context) {
14333
15586
  function createProductionRunbook(dir, planId, targetId) {
14334
15587
  const context = buildProductionRunbookContext(dir, planId, targetId);
14335
15588
  if (!context.eligible) throw new ProductionRunbookError(context.blockers.join(" "));
14336
- const path6 = context.nextPath;
14337
- const id = path6.split("/").pop()?.match(/^(RB-\d+)-/)?.[1] ?? "";
14338
- const content = matter17.stringify(renderRunbook(context), {
15589
+ const path8 = context.nextPath;
15590
+ const id = path8.split("/").pop()?.match(/^(RB-\d+)-/)?.[1] ?? "";
15591
+ const content = matter18.stringify(renderRunbook(context), {
14339
15592
  id,
14340
15593
  type: PRODUCTION_RUNBOOK_ARTIFACT_TYPE,
14341
15594
  title: `Production runbook \u2014 ${context.target.title ?? context.target.id}`,
@@ -14344,13 +15597,13 @@ function createProductionRunbook(dir, planId, targetId) {
14344
15597
  resource: context.target.resource,
14345
15598
  approval: { required: true, status: "pending", approved_by: null, approved_at: null }
14346
15599
  });
14347
- const absolute = join(dir, path6);
14348
- if (exists(absolute)) throw new ProductionRunbookError(`Runbook already exists: ${path6}`);
15600
+ const absolute = join(dir, path8);
15601
+ if (exists(absolute)) throw new ProductionRunbookError(`Runbook already exists: ${path8}`);
14349
15602
  writeFile(absolute, content);
14350
15603
  return {
14351
15604
  id,
14352
15605
  title: `Production runbook \u2014 ${context.target.title ?? context.target.id}`,
14353
- path: path6,
15606
+ path: path8,
14354
15607
  planId: context.plan.id,
14355
15608
  targetId: context.target.id,
14356
15609
  approval: { required: true, status: "pending", approvedBy: null, approvedAt: null },
@@ -14361,14 +15614,14 @@ function getProductionRunbook(dir, id) {
14361
15614
  const root = join(dir, PRODUCTION_RUNBOOKS_DIR);
14362
15615
  for (const name of readDir(root)) {
14363
15616
  if (!name.toLowerCase().startsWith(`${id.toLowerCase()}-`) || !name.endsWith(".md")) continue;
14364
- const path6 = `${PRODUCTION_RUNBOOKS_DIR}/${name}`;
14365
- const parsed = matter17(readFile(join(dir, path6)));
15617
+ const path8 = `${PRODUCTION_RUNBOOKS_DIR}/${name}`;
15618
+ const parsed = matter18(readFile(join(dir, path8)));
14366
15619
  const data = parsed.data;
14367
15620
  if (data.type !== PRODUCTION_RUNBOOK_ARTIFACT_TYPE) continue;
14368
15621
  return {
14369
15622
  id: stringValue(data.id) ?? id,
14370
15623
  title: stringValue(data.title) ?? id,
14371
- path: path6,
15624
+ path: path8,
14372
15625
  planId: stringValue(data.deprecation_plan) ?? "",
14373
15626
  targetId: stringValue(data.deprecation_target) ?? "",
14374
15627
  approval: parseApproval(data.approval),
@@ -14390,6 +15643,438 @@ function validateProductionRunbook(runbook) {
14390
15643
  if (destructive.length > 0) findings.push({ level: "warning", message: "Destructive commands are documentation only; Kaddo will never execute them." });
14391
15644
  return findings;
14392
15645
  }
15646
+
15647
+ // src/core/okf/export.ts
15648
+ import fs7 from "fs";
15649
+ import path6 from "path";
15650
+
15651
+ // src/core/okf/mapping.ts
15652
+ var OKF_TYPE_TABLE = {
15653
+ "business-knowledge": "Business Knowledge",
15654
+ "product-knowledge": "Product Knowledge",
15655
+ "technical-knowledge": "Technical Knowledge",
15656
+ capability: "Capability",
15657
+ decision: "Architecture Decision",
15658
+ adr: "Architecture Decision",
15659
+ "project-resource": "Project Resource",
15660
+ "deprecation-plan": "Deprecation Plan",
15661
+ initiative: "Initiative",
15662
+ capsule: "Knowledge Reference",
15663
+ "knowledge-capsule": "Knowledge Reference",
15664
+ "current-state": "Technical Knowledge",
15665
+ roadmap: "Delivery Knowledge"
15666
+ };
15667
+ var WORK_ITEM_TYPES3 = /* @__PURE__ */ new Set(["feature", "bugfix", "hotfix", "spike", "chore"]);
15668
+ var REPORT_TYPES = /* @__PURE__ */ new Set(["impact-report", "drift-report", "savings-report", "poc-report"]);
15669
+ function okfConceptType(a) {
15670
+ if (a.isWorkItem) return "Work Item";
15671
+ const t = (a.type || "").toLowerCase();
15672
+ if (OKF_TYPE_TABLE[t]) return OKF_TYPE_TABLE[t];
15673
+ if (REPORT_TYPES.has(t)) return "Report";
15674
+ if (WORK_ITEM_TYPES3.has(t)) return "Work Item";
15675
+ if (a.layer === "business") return "Business Knowledge";
15676
+ if (a.layer === "product") return "Product Knowledge";
15677
+ if (a.layer === "tech" || a.layer === "module") return "Technical Knowledge";
15678
+ if (a.layer === "delivery") return "Delivery Knowledge";
15679
+ return t ? t.replace(/(^|[-_ ])(\w)/g, (_, s, c) => (s ? " " : "") + c.toUpperCase()) : "Knowledge";
15680
+ }
15681
+ function str3(v) {
15682
+ return typeof v === "string" && v.trim() ? v.trim() : null;
15683
+ }
15684
+ function strArray3(v) {
15685
+ return Array.isArray(v) ? v.map((x) => String(x).trim()).filter(Boolean) : [];
15686
+ }
15687
+ function conceptBundlePath(a, id) {
15688
+ const file = `${id}.md`;
15689
+ if (a.isWorkItem) return `delivery/work-items/${file}`;
15690
+ const t = (a.type || "").toLowerCase();
15691
+ if (t === "deprecation-plan") return `delivery/deprecations/${file}`;
15692
+ if (t === "production-runbook") return `delivery/runbooks/${file}`;
15693
+ if (t === "project-resource") return `resources/${file}`;
15694
+ if (t === "knowledge-capsule" || t === "capsule") return `external/${file}`;
15695
+ switch (a.layer) {
15696
+ case "business":
15697
+ return `business/${file}`;
15698
+ case "product":
15699
+ return `product/${file}`;
15700
+ case "tech":
15701
+ return `tech/${file}`;
15702
+ case "module":
15703
+ return `tech/modules/${file}`;
15704
+ case "delivery":
15705
+ return `delivery/${file}`;
15706
+ default:
15707
+ return `misc/${file}`;
15708
+ }
15709
+ }
15710
+ function workItemRelations(fm) {
15711
+ const out = [];
15712
+ const resources = fm.resources;
15713
+ if (Array.isArray(resources)) {
15714
+ for (const r of resources) {
15715
+ if (r && typeof r === "object") {
15716
+ const id = str3(r.id);
15717
+ if (id) out.push({ id, role: str3(r.role) ?? "uses" });
15718
+ }
15719
+ }
15720
+ }
15721
+ const dep = fm.deprecation_targets;
15722
+ if (Array.isArray(dep)) {
15723
+ for (const d of dep) {
15724
+ const s = typeof d === "string" ? d : d && typeof d === "object" ? str3(d.plan) : null;
15725
+ if (s) out.push({ id: s.includes("/") ? s.split("/")[0] : s, role: "deprecates-via" });
15726
+ }
15727
+ }
15728
+ const parent = str3(fm.parent);
15729
+ if (parent) out.push({ id: parent, role: "child-of" });
15730
+ for (const dId of strArray3(fm.decisions)) out.push({ id: dId, role: "decided-by" });
15731
+ return out;
15732
+ }
15733
+ function slugify4(s) {
15734
+ return s.toLowerCase().trim().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60);
15735
+ }
15736
+ function conceptId(a) {
15737
+ if (a.id) return a.id;
15738
+ if (a.title) return slugify4(a.title);
15739
+ const base = a.relPath.split("/").pop() ?? "";
15740
+ return slugify4(base.replace(/\.md$/, "")) || slugify4(a.relPath);
15741
+ }
15742
+ function buildConcept(a) {
15743
+ const id = conceptId(a);
15744
+ if (!id) return null;
15745
+ const rawFm = a.rawFrontmatter ?? {};
15746
+ return {
15747
+ id,
15748
+ type: okfConceptType(a),
15749
+ title: a.title || id,
15750
+ description: str3(a.summary),
15751
+ tags: a.domains.map((d) => String(d).toLowerCase()),
15752
+ path: conceptBundlePath(a, id),
15753
+ sourcePath: a.relPath,
15754
+ related: a.isWorkItem ? workItemRelations(rawFm) : [],
15755
+ body: null
15756
+ };
15757
+ }
15758
+
15759
+ // src/core/okf/extras.ts
15760
+ function reportConcepts(dir, now = /* @__PURE__ */ new Date()) {
15761
+ const concepts = [];
15762
+ const warnings = [];
15763
+ const at = now.toISOString();
15764
+ const add = (id, title, description, build) => {
15765
+ try {
15766
+ const body = build();
15767
+ concepts.push({
15768
+ id,
15769
+ type: "Report",
15770
+ title,
15771
+ description,
15772
+ tags: ["report"],
15773
+ path: `reports/${id}.md`,
15774
+ sourcePath: null,
15775
+ generatedAt: at,
15776
+ related: [],
15777
+ body
15778
+ });
15779
+ } catch (e) {
15780
+ warnings.push(`Report "${id}" skipped: ${e instanceof Error ? e.message : String(e)}`);
15781
+ }
15782
+ };
15783
+ add(
15784
+ "report-impact",
15785
+ "Impact Report",
15786
+ "Knowledge-code impact, derived from evidence.",
15787
+ () => renderImpactMarkdown(buildImpactReport(dir, {}, now), { details: true })
15788
+ );
15789
+ add(
15790
+ "report-drift",
15791
+ "Drift Report",
15792
+ "Drift trend across code, knowledge, Work Items and architecture.",
15793
+ () => renderDriftMarkdown(buildDriftReport(dir, now))
15794
+ );
15795
+ add(
15796
+ "report-savings",
15797
+ "Savings Report",
15798
+ "Evidence-based savings estimates (not exact ROI).",
15799
+ () => renderSavingsMarkdown(buildSavingsReport(dir, {}, now))
15800
+ );
15801
+ return { concepts, warnings };
15802
+ }
15803
+ function externalCapsuleConcepts(dir) {
15804
+ return loadExternalRegistry(dir).map((e) => {
15805
+ const lines = [
15806
+ `# ${e.id}`,
15807
+ "",
15808
+ "External Knowledge Reference. Access is limited to its source system; its private sources are not",
15809
+ "included in this bundle and no operational access to the origin system is implied.",
15810
+ "",
15811
+ `- Source: \`${e.path}\``,
15812
+ ...e.owner ? [`- Owner: ${e.owner}`] : [],
15813
+ ...e.lastImportedAt ? [`- Last imported: ${e.lastImportedAt}`] : []
15814
+ ];
15815
+ return {
15816
+ id: e.id,
15817
+ type: "Knowledge Reference",
15818
+ title: e.id,
15819
+ description: "External knowledge reference (capsule).",
15820
+ tags: ["reference", "external"],
15821
+ path: `external/${e.id}.md`,
15822
+ sourcePath: e.path,
15823
+ related: [],
15824
+ body: lines.join("\n")
15825
+ };
15826
+ });
15827
+ }
15828
+
15829
+ // src/core/okf/types.ts
15830
+ var OKF_VERSION = "0.2";
15831
+ var OKF_RESERVED_FILES = ["index.md", "log.md"];
15832
+
15833
+ // src/core/okf/export.ts
15834
+ var OKF_DEFAULT_OUTPUT = ".kaddo/okf";
15835
+ function frontmatter(data) {
15836
+ const lines = ["---"];
15837
+ for (const [k, v] of Object.entries(data)) {
15838
+ if (v == null) continue;
15839
+ if (Array.isArray(v)) {
15840
+ if (v.length === 0) continue;
15841
+ lines.push(`${k}:`);
15842
+ for (const item of v) {
15843
+ if (item && typeof item === "object") {
15844
+ const entries = Object.entries(item).filter(([, x]) => x != null);
15845
+ if (entries.length === 0) continue;
15846
+ lines.push(` - ${entries.map(([ik, iv]) => `${ik}: ${JSON.stringify(iv)}`).join("\n ")}`);
15847
+ } else {
15848
+ lines.push(` - ${JSON.stringify(item)}`);
15849
+ }
15850
+ }
15851
+ } else {
15852
+ lines.push(`${k}: ${JSON.stringify(v)}`);
15853
+ }
15854
+ }
15855
+ lines.push("---");
15856
+ return lines.join("\n");
15857
+ }
15858
+ function relLink(fromPath, toPath) {
15859
+ const rel = path6.posix.relative(path6.posix.dirname(fromPath), toPath);
15860
+ return rel.startsWith(".") ? rel : `./${rel}`;
15861
+ }
15862
+ function renderConcept(c, byId) {
15863
+ const data = {
15864
+ type: c.type,
15865
+ title: c.title,
15866
+ description: c.description,
15867
+ tags: c.tags,
15868
+ kaddo_id: c.id
15869
+ };
15870
+ if (c.sourcePath) data.sources = [{ resource: c.sourcePath }];
15871
+ if (c.generatedAt) data.generated = { at: c.generatedAt };
15872
+ const parts = [frontmatter(data)];
15873
+ if (c.body) {
15874
+ parts.push("", c.body.trim());
15875
+ } else {
15876
+ parts.push("", `# ${c.title}`);
15877
+ if (c.description) parts.push("", c.description);
15878
+ }
15879
+ const resolved = c.related.filter((r) => byId.has(r.id));
15880
+ if (resolved.length > 0) {
15881
+ parts.push("", "## Related");
15882
+ for (const r of resolved) {
15883
+ const target = byId.get(r.id);
15884
+ parts.push(`- [${target.title}](${relLink(c.path, target.path)}) \u2014 ${r.role}`);
15885
+ }
15886
+ }
15887
+ return parts.join("\n") + "\n";
15888
+ }
15889
+ function renderIndex(title, concepts, fromPath, root) {
15890
+ const data = { type: "Index", title };
15891
+ if (root) data.okf_version = OKF_VERSION;
15892
+ const parts = [frontmatter(data), "", `# ${title}`, ""];
15893
+ if (root) parts.push(
15894
+ `Open Knowledge Format bundle \u2014 version ${OKF_VERSION}. A portable projection of`,
15895
+ "Kaddo knowledge. Kaddo remains the source of truth.",
15896
+ ""
15897
+ );
15898
+ const byType = /* @__PURE__ */ new Map();
15899
+ for (const c of concepts) {
15900
+ const l = byType.get(c.type) ?? [];
15901
+ l.push(c);
15902
+ byType.set(c.type, l);
15903
+ }
15904
+ for (const type of [...byType.keys()].sort()) {
15905
+ parts.push(`## ${type}`);
15906
+ for (const c of byType.get(type).sort((a, b) => a.id.localeCompare(b.id))) {
15907
+ parts.push(`- [${c.title}](${relLink(fromPath, c.path)})`);
15908
+ }
15909
+ parts.push("");
15910
+ }
15911
+ return parts.join("\n");
15912
+ }
15913
+ function atomicWrite5(file, content) {
15914
+ fs7.mkdirSync(path6.dirname(file), { recursive: true });
15915
+ fs7.writeFileSync(file, content, "utf-8");
15916
+ }
15917
+ var SENSITIVE_PATTERNS = [
15918
+ { re: /-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/, label: "private key block" },
15919
+ { re: /\bAKIA[0-9A-Z]{16}\b/, label: "AWS access key id" },
15920
+ { re: /\bgh[pousr]_[A-Za-z0-9]{20,}\b/, label: "GitHub token" },
15921
+ { re: /\b(?:password|secret|api[_-]?key|access[_-]?token)\b\s*[:=]\s*["']?[A-Za-z0-9+/_\-]{12,}/i, label: "inline credential" }
15922
+ ];
15923
+ function scanSensitive(renderedPath, content) {
15924
+ const hits = SENSITIVE_PATTERNS.filter((p) => p.re.test(content)).map((p) => p.label);
15925
+ return hits.length > 0 ? [`${renderedPath}: possible ${[...new Set(hits)].join(", ")} \u2014 review before sharing.`] : [];
15926
+ }
15927
+ function exportOkf(dir, opts = {}) {
15928
+ const outRel = opts.output ?? OKF_DEFAULT_OUTPUT;
15929
+ const outputDir = path6.isAbsolute(outRel) ? outRel : path6.join(dir, outRel);
15930
+ const extraWarnings = [];
15931
+ const artifacts = discoverKnowledge(dir);
15932
+ const concepts = [];
15933
+ const seen = /* @__PURE__ */ new Set();
15934
+ const omittedCounts = /* @__PURE__ */ new Map();
15935
+ const addConcept = (c) => {
15936
+ if (!c || seen.has(c.id)) return;
15937
+ seen.add(c.id);
15938
+ concepts.push(c);
15939
+ };
15940
+ for (const a of artifacts) {
15941
+ const c = buildConcept(a);
15942
+ if (!c) {
15943
+ omittedCounts.set(a.type || "unknown", (omittedCounts.get(a.type || "unknown") ?? 0) + 1);
15944
+ continue;
15945
+ }
15946
+ addConcept(c);
15947
+ }
15948
+ for (const c of externalCapsuleConcepts(dir)) addConcept(c);
15949
+ if (opts.withReports) {
15950
+ const { concepts: reports, warnings: warnings2 } = reportConcepts(dir, opts.now ?? /* @__PURE__ */ new Date());
15951
+ for (const c of reports) addConcept(c);
15952
+ extraWarnings.push(...warnings2);
15953
+ }
15954
+ concepts.sort((a, b) => a.id.localeCompare(b.id));
15955
+ const byId = new Map(concepts.map((c) => [c.id, c]));
15956
+ const layerOf = (p) => p.split("/")[0];
15957
+ const byLayer = /* @__PURE__ */ new Map();
15958
+ for (const c of concepts) {
15959
+ const l = byLayer.get(layerOf(c.path)) ?? [];
15960
+ l.push(c);
15961
+ byLayer.set(layerOf(c.path), l);
15962
+ }
15963
+ fs7.rmSync(outputDir, { recursive: true, force: true });
15964
+ fs7.mkdirSync(outputDir, { recursive: true });
15965
+ const written = [];
15966
+ const warnings = [];
15967
+ const write = (bundlePath, content) => {
15968
+ atomicWrite5(path6.join(outputDir, bundlePath), content);
15969
+ written.push(bundlePath);
15970
+ warnings.push(...scanSensitive(bundlePath, content));
15971
+ };
15972
+ for (const c of concepts) write(c.path, renderConcept(c, byId));
15973
+ for (const layer of [...byLayer.keys()].sort()) {
15974
+ const title = layer.charAt(0).toUpperCase() + layer.slice(1);
15975
+ write(`${layer}/index.md`, renderIndex(`${title} Knowledge`, byLayer.get(layer), `${layer}/index.md`, false));
15976
+ }
15977
+ write("index.md", renderIndex("Knowledge bundle", concepts, "index.md", true));
15978
+ written.sort();
15979
+ return {
15980
+ outputDir,
15981
+ conceptCount: concepts.length,
15982
+ indexCount: byLayer.size + 1,
15983
+ omitted: [...omittedCounts.entries()].map(([type, count]) => ({ type, count })).sort((a, b) => a.type.localeCompare(b.type)),
15984
+ warnings: [...warnings, ...extraWarnings].sort(),
15985
+ files: written
15986
+ };
15987
+ }
15988
+
15989
+ // src/core/okf/validate.ts
15990
+ import fs8 from "fs";
15991
+ import path7 from "path";
15992
+ import matter19 from "gray-matter";
15993
+ function walk(root) {
15994
+ const out = [];
15995
+ const rec = (d) => {
15996
+ for (const entry of fs8.readdirSync(d)) {
15997
+ const full = path7.join(d, entry);
15998
+ const st = fs8.statSync(full);
15999
+ if (st.isDirectory()) rec(full);
16000
+ else if (entry.endsWith(".md")) out.push(full);
16001
+ }
16002
+ };
16003
+ if (fs8.existsSync(root)) rec(root);
16004
+ return out.sort();
16005
+ }
16006
+ function internalLinks(body) {
16007
+ const out = [];
16008
+ const re = /\]\(([^)]+)\)/g;
16009
+ let m;
16010
+ while (m = re.exec(body)) {
16011
+ const href = m[1].trim().split("#")[0].split(" ")[0];
16012
+ if (!href || /^(https?:|mailto:|\/)/.test(href)) continue;
16013
+ out.push(href);
16014
+ }
16015
+ return out;
16016
+ }
16017
+ function validateOkf(dir, opts = {}) {
16018
+ const loc = opts.location ?? OKF_DEFAULT_OUTPUT;
16019
+ const bundleDir = path7.isAbsolute(loc) ? loc : path7.join(dir, loc);
16020
+ const findings = [];
16021
+ if (!fs8.existsSync(bundleDir)) {
16022
+ findings.push({ level: "conformance", message: `OKF bundle directory not found: ${loc}. Run \`kaddo okf export\` first.` });
16023
+ return { dir: bundleDir, conformant: false, conceptCount: 0, findings, counts: { conformance: 1, warning: 0, info: 0 } };
16024
+ }
16025
+ const files = walk(bundleDir);
16026
+ const rel = (f) => path7.relative(bundleDir, f).split(path7.sep).join("/");
16027
+ const present = new Set(files.map(rel));
16028
+ const idToFile = /* @__PURE__ */ new Map();
16029
+ let conceptCount = 0;
16030
+ const rootIndex = path7.join(bundleDir, "index.md");
16031
+ if (!fs8.existsSync(rootIndex)) {
16032
+ findings.push({ level: "warning", message: "No root index.md \u2014 the bundle has no top-level navigation entry." });
16033
+ }
16034
+ for (const file of files) {
16035
+ const r = rel(file);
16036
+ const isIndex = path7.basename(file) === "index.md";
16037
+ let data = {};
16038
+ try {
16039
+ data = matter19(fs8.readFileSync(file, "utf-8")).data ?? {};
16040
+ } catch {
16041
+ findings.push({ level: "conformance", file: r, message: "Invalid YAML frontmatter." });
16042
+ continue;
16043
+ }
16044
+ const type = typeof data.type === "string" ? data.type.trim() : "";
16045
+ if (!type) {
16046
+ findings.push(isIndex ? { level: "warning", file: r, message: "Index has no type." } : { level: "conformance", file: r, message: "Concept has no non-empty `type`." });
16047
+ }
16048
+ if (!isIndex) conceptCount++;
16049
+ if (r === "index.md") {
16050
+ const v = typeof data.okf_version === "string" ? data.okf_version : data.okf_version != null ? String(data.okf_version) : "";
16051
+ if (!v) findings.push({ level: "warning", file: r, message: "Root index does not declare okf_version." });
16052
+ else if (v !== OKF_VERSION) findings.push({ level: "info", file: r, message: `Bundle declares okf_version "${v}" (validator targets ${OKF_VERSION}).` });
16053
+ }
16054
+ const kid = typeof data.kaddo_id === "string" ? data.kaddo_id : "";
16055
+ if (kid) {
16056
+ if (idToFile.has(kid)) findings.push({ level: "conformance", file: r, message: `Duplicate concept id "${kid}" (also in ${idToFile.get(kid)}).` });
16057
+ else idToFile.set(kid, r);
16058
+ }
16059
+ const body = (() => {
16060
+ try {
16061
+ return matter19(fs8.readFileSync(file, "utf-8")).content;
16062
+ } catch {
16063
+ return "";
16064
+ }
16065
+ })();
16066
+ for (const href of internalLinks(body)) {
16067
+ const resolved = path7.posix.normalize(path7.posix.join(path7.posix.dirname(r), href));
16068
+ if (!present.has(resolved)) findings.push({ level: "info", file: r, message: `Internal link not resolvable yet: ${href}` });
16069
+ }
16070
+ }
16071
+ const counts = {
16072
+ conformance: findings.filter((f) => f.level === "conformance").length,
16073
+ warning: findings.filter((f) => f.level === "warning").length,
16074
+ info: findings.filter((f) => f.level === "info").length
16075
+ };
16076
+ return { dir: bundleDir, conformant: counts.conformance === 0, conceptCount, findings, counts };
16077
+ }
14393
16078
  export {
14394
16079
  CANDIDATE_DISCOVERY_GUIDANCE,
14395
16080
  CURRENT_CONSENT_VERSION,
@@ -14411,6 +16096,10 @@ export {
14411
16096
  IntegrationServiceError,
14412
16097
  LIFECYCLE_STATES2 as LIFECYCLE_STATES,
14413
16098
  LIFECYCLE_TRANSITIONS,
16099
+ OKF_DEFAULT_OUTPUT,
16100
+ OKF_RESERVED_FILES,
16101
+ OKF_TYPE_TABLE,
16102
+ OKF_VERSION,
14414
16103
  POC_ARTIFACT_PATH,
14415
16104
  POC_REPORT_PREFIX,
14416
16105
  PRODUCTION_RUNBOOKS_DIR,
@@ -14438,6 +16127,9 @@ export {
14438
16127
  analyzeScopeCoverage,
14439
16128
  applyTopologyProposal,
14440
16129
  associatedWorkItems,
16130
+ buildConcept,
16131
+ buildDriftReport,
16132
+ buildImpactReport,
14441
16133
  buildImplementationHandoff,
14442
16134
  buildImportIndex,
14443
16135
  buildPocReportContext,
@@ -14446,11 +16138,13 @@ export {
14446
16138
  buildProjectRoute,
14447
16139
  buildReadinessReport,
14448
16140
  buildRefinementHandoff,
16141
+ buildSavingsReport,
14449
16142
  buildTopologyEnrichmentHandoff,
14450
16143
  collectImplementationEvidence,
14451
16144
  computeContentHash,
14452
16145
  computeInitiativeProgress,
14453
16146
  computeRefinementStatus,
16147
+ conceptBundlePath,
14454
16148
  consentNotice,
14455
16149
  createInitiative,
14456
16150
  createIntegration,
@@ -14475,6 +16169,7 @@ export {
14475
16169
  evaluateCompletion,
14476
16170
  evaluateInitiativeCompletion,
14477
16171
  exists,
16172
+ exportOkf,
14478
16173
  filterSecretPaths,
14479
16174
  findDuplicateByHash,
14480
16175
  findExistingById,
@@ -14535,6 +16230,7 @@ export {
14535
16230
  nextPlanId,
14536
16231
  nextTargetId,
14537
16232
  observationStatus,
16233
+ okfConceptType,
14538
16234
  parseContent,
14539
16235
  parseInitiative,
14540
16236
  parseScope,
@@ -14556,7 +16252,13 @@ export {
14556
16252
  redactSecrets,
14557
16253
  removeIntegrationSecret,
14558
16254
  removeTarget,
16255
+ renderDriftMarkdown,
16256
+ renderImpactMarkdown,
16257
+ renderSavingsMarkdown,
14559
16258
  searchSystemNodes,
16259
+ serializeDriftJson,
16260
+ serializeImpactJson,
16261
+ serializeSavingsJson,
14560
16262
  setIntegrationSecret,
14561
16263
  setProjectMode,
14562
16264
  suggestInitiativesForExternalItem,
@@ -14572,6 +16274,7 @@ export {
14572
16274
  updateTarget,
14573
16275
  updateWorkItem,
14574
16276
  validateConfigAgainstSchema,
16277
+ validateOkf,
14575
16278
  validatePlan,
14576
16279
  validateProductionRunbook,
14577
16280
  validateResource,