@kaddo/cli 3.128.0 → 3.129.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/core.js +736 -52
  2. package/dist/index.js +777 -68
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -818,8 +818,8 @@ function emptySignals() {
818
818
  environment: []
819
819
  };
820
820
  }
821
- function sig(type, label, confidence, evidence, extra) {
822
- return { type, label, confidence, evidence, ...extra };
821
+ function sig(type, label2, confidence, evidence, extra) {
822
+ return { type, label: label2, confidence, evidence, ...extra };
823
823
  }
824
824
  function readDeps(dir) {
825
825
  const pkgPath = join(dir, "package.json");
@@ -898,10 +898,10 @@ function detectAuth(dir, deps, codeDirs, signals) {
898
898
  ["@aws-amplify/auth", "AWS Amplify Auth"]
899
899
  ];
900
900
  const seen = /* @__PURE__ */ new Set();
901
- for (const [dep, label] of authDeps) {
902
- if (dep in deps && !seen.has(label)) {
903
- seen.add(label);
904
- signals.auth.push(sig("auth", label, "high", ["package.json"]));
901
+ for (const [dep, label2] of authDeps) {
902
+ if (dep in deps && !seen.has(label2)) {
903
+ seen.add(label2);
904
+ signals.auth.push(sig("auth", label2, "high", ["package.json"]));
905
905
  }
906
906
  }
907
907
  const authPaths = findPathsContaining(dir, codeDirs, ["auth", "login", "register", "signin", "signup", "session"], 3);
@@ -922,10 +922,10 @@ function detectPayments(dir, deps, codeDirs, signals) {
922
922
  ["square", "Square"]
923
923
  ];
924
924
  const seen = /* @__PURE__ */ new Set();
925
- for (const [dep, label] of payDeps) {
926
- if (dep in deps && !seen.has(label)) {
927
- seen.add(label);
928
- signals.payments.push(sig("payments", label, "high", ["package.json"]));
925
+ for (const [dep, label2] of payDeps) {
926
+ if (dep in deps && !seen.has(label2)) {
927
+ seen.add(label2);
928
+ signals.payments.push(sig("payments", label2, "high", ["package.json"]));
929
929
  }
930
930
  }
931
931
  const payPaths = findPathsContaining(dir, codeDirs, ["payment", "checkout", "billing", "invoice", "subscription", "pricing"], 3);
@@ -953,10 +953,10 @@ function detectStorage(dir, deps, codeDirs, signals) {
953
953
  ["@azure/storage-blob", "Azure Blob Storage"]
954
954
  ];
955
955
  const seen = /* @__PURE__ */ new Set();
956
- for (const [dep, label] of storageDeps) {
957
- if (dep in deps && !seen.has(label)) {
958
- seen.add(label);
959
- signals.storage.push(sig("storage", label, "high", ["package.json"]));
956
+ for (const [dep, label2] of storageDeps) {
957
+ if (dep in deps && !seen.has(label2)) {
958
+ seen.add(label2);
959
+ signals.storage.push(sig("storage", label2, "high", ["package.json"]));
960
960
  }
961
961
  }
962
962
  const storagePaths = findPathsContaining(dir, codeDirs, ["upload", "storage", "bucket"], 3);
@@ -975,9 +975,9 @@ function detectBackgroundJobs(dir, deps, codeDirs, signals) {
975
975
  ["node-cron", "Node-cron"],
976
976
  ["cron", "Cron"]
977
977
  ];
978
- for (const [dep, label] of jobDeps) {
978
+ for (const [dep, label2] of jobDeps) {
979
979
  if (dep in deps) {
980
- signals.background_jobs.push(sig("background_jobs", label, "high", ["package.json"]));
980
+ signals.background_jobs.push(sig("background_jobs", label2, "high", ["package.json"]));
981
981
  }
982
982
  }
983
983
  if (isDir(join(dir, "supabase", "functions"))) {
@@ -1013,9 +1013,9 @@ function detectEmail(dir, deps, signals) {
1013
1013
  ["mailgun-js", "Mailgun"],
1014
1014
  ["@mailchimp/mailchimp_transactional", "Mailchimp Transactional"]
1015
1015
  ];
1016
- for (const [dep, label] of emailDeps) {
1016
+ for (const [dep, label2] of emailDeps) {
1017
1017
  if (dep in deps) {
1018
- signals.email.push(sig("email", label, "high", ["package.json"]));
1018
+ signals.email.push(sig("email", label2, "high", ["package.json"]));
1019
1019
  }
1020
1020
  }
1021
1021
  }
@@ -1038,10 +1038,10 @@ function detectDatabase(dir, deps, signals) {
1038
1038
  ["@libsql/client", "Turso (LibSQL)"]
1039
1039
  ];
1040
1040
  const seen = /* @__PURE__ */ new Set();
1041
- for (const [dep, label] of dbDeps) {
1042
- if (dep in deps && !seen.has(label)) {
1043
- seen.add(label);
1044
- signals.database.push(sig("database", label, "high", ["package.json"]));
1041
+ for (const [dep, label2] of dbDeps) {
1042
+ if (dep in deps && !seen.has(label2)) {
1043
+ seen.add(label2);
1044
+ signals.database.push(sig("database", label2, "high", ["package.json"]));
1045
1045
  }
1046
1046
  }
1047
1047
  }
@@ -1088,9 +1088,9 @@ function detectTests(dir, testDirs, deps, signals) {
1088
1088
  ["mocha", "Mocha"],
1089
1089
  ["ava", "AVA"]
1090
1090
  ];
1091
- for (const [dep, label] of testFrameworks) {
1091
+ for (const [dep, label2] of testFrameworks) {
1092
1092
  if (dep in deps) {
1093
- signals.tests.push(sig("tests", label, "high", ["package.json"]));
1093
+ signals.tests.push(sig("tests", label2, "high", ["package.json"]));
1094
1094
  }
1095
1095
  }
1096
1096
  if (testDirs.length > 0) {
@@ -1110,9 +1110,9 @@ function detectSecurity(dir, deps, codeDirs, envVarNames, signals) {
1110
1110
  ["express-rate-limit", "Rate limiting"],
1111
1111
  ["@upstash/ratelimit", "Upstash Rate Limiting"]
1112
1112
  ];
1113
- for (const [dep, label] of secDeps) {
1113
+ for (const [dep, label2] of secDeps) {
1114
1114
  if (dep in deps) {
1115
- signals.security.push(sig("security", label, "high", ["package.json"]));
1115
+ signals.security.push(sig("security", label2, "high", ["package.json"]));
1116
1116
  }
1117
1117
  }
1118
1118
  const middlewarePaths = findPathsContaining(dir, codeDirs, ["middleware"], 2);
@@ -1138,8 +1138,8 @@ function detectSecurity(dir, deps, codeDirs, envVarNames, signals) {
1138
1138
  }
1139
1139
  function detectInfrastructure(dir, infraFiles, signals) {
1140
1140
  for (const f of infraFiles) {
1141
- const label = inferInfraLabel(f);
1142
- signals.infrastructure.push(sig("infrastructure", label, "high", [f]));
1141
+ const label2 = inferInfraLabel(f);
1142
+ signals.infrastructure.push(sig("infrastructure", label2, "high", [f]));
1143
1143
  }
1144
1144
  }
1145
1145
  function inferInfraLabel(f) {
@@ -1186,10 +1186,10 @@ function detectExternalIntegrations(deps, signals) {
1186
1186
  ["ioredis", "Redis"]
1187
1187
  ];
1188
1188
  const seen = /* @__PURE__ */ new Set();
1189
- for (const [dep, label] of integrations) {
1190
- if (dep in deps && !seen.has(label)) {
1191
- seen.add(label);
1192
- signals.external_integrations.push(sig("external_integrations", label, "high", ["package.json"]));
1189
+ for (const [dep, label2] of integrations) {
1190
+ if (dep in deps && !seen.has(label2)) {
1191
+ seen.add(label2);
1192
+ signals.external_integrations.push(sig("external_integrations", label2, "high", ["package.json"]));
1193
1193
  }
1194
1194
  }
1195
1195
  }
@@ -1267,13 +1267,13 @@ function renderSignalsCompact(signals) {
1267
1267
  ["external_integrations", "External integrations"],
1268
1268
  ["environment", "Environment"]
1269
1269
  ];
1270
- for (const [key, label] of CATEGORIES) {
1270
+ for (const [key, label2] of CATEGORIES) {
1271
1271
  const arr = signals[key];
1272
1272
  if (arr.length === 0) continue;
1273
1273
  if (arr.length === 1) {
1274
- lines.push(`- ${label}: ${arr[0].label}`);
1274
+ lines.push(`- ${label2}: ${arr[0].label}`);
1275
1275
  } else {
1276
- lines.push(`- ${label}: ${arr.length}`);
1276
+ lines.push(`- ${label2}: ${arr.length}`);
1277
1277
  }
1278
1278
  }
1279
1279
  return lines.length > 0 ? lines.join("\n") + "\n" : "No signals detected.\n";
@@ -1296,10 +1296,10 @@ function renderSignalsInventory(signals) {
1296
1296
  ["external_integrations", "External Integrations"],
1297
1297
  ["environment", "Environment"]
1298
1298
  ];
1299
- for (const [key, label] of CATEGORIES) {
1299
+ for (const [key, label2] of CATEGORIES) {
1300
1300
  const arr = signals[key];
1301
1301
  if (arr.length === 0) continue;
1302
- parts.push(`### ${label}
1302
+ parts.push(`### ${label2}
1303
1303
  `);
1304
1304
  for (const s of arr) {
1305
1305
  parts.push(`- ${s.label} \u2014 confidence: ${s.confidence}`);
@@ -1332,14 +1332,14 @@ function renderSignalsConsole(signals) {
1332
1332
  ["external_integrations", "Integrations"],
1333
1333
  ["environment", "Environment"]
1334
1334
  ];
1335
- for (const [key, label] of CATEGORIES) {
1335
+ for (const [key, label2] of CATEGORIES) {
1336
1336
  const arr = signals[key];
1337
1337
  if (arr.length === 0) continue;
1338
1338
  if (arr.length === 1) {
1339
1339
  const warning = arr[0].label.toLowerCase().includes("no test") ? " \u26A0" : "";
1340
- lines.push(` ${label}: ${arr[0].label}${warning}`);
1340
+ lines.push(` ${label2}: ${arr[0].label}${warning}`);
1341
1341
  } else {
1342
- lines.push(` ${label}: ${arr.map((s) => s.label).join(", ")}`);
1342
+ lines.push(` ${label2}: ${arr.map((s) => s.label).join(", ")}`);
1343
1343
  }
1344
1344
  }
1345
1345
  return lines;
@@ -3276,6 +3276,69 @@ After a POC has a canonical conclusion and Core has prepared its deterministic r
3276
3276
  15. Traceability and Sources
3277
3277
  `
3278
3278
  );
3279
+ var KNOWLEDGE_CONSOLIDATION = skill(
3280
+ "knowledge-consolidation",
3281
+ "Knowledge Consolidation Skill",
3282
+ "delivery",
3283
+ ["knowledge-consolidation-agent", "work-item-agent", "architecture-agent"],
3284
+ `
3285
+ # Knowledge Consolidation Skill
3286
+
3287
+ ## Purpose
3288
+
3289
+ Standardize the SEMANTIC review of a deterministic Consolidation Plan so canonical knowledge becomes
3290
+ more precise, connected, consistent and retrievable \u2014 without losing history, decisions or evidence.
3291
+
3292
+ ## When to use
3293
+
3294
+ After \`kaddo knowledge consolidate\` (or the \`kaddo_generate_consolidation_plan\` tool) has produced
3295
+ \`.kaddo/consolidation-plan.{md,json}\`, and a human or agent wants to review the opportunities and
3296
+ prepare refinements. Never as an autonomous rewrite of \`knowledge/\`.
3297
+
3298
+ ## Inputs
3299
+
3300
+ The Consolidation Plan (\`.kaddo/consolidation-plan.json\`), the referenced source artifacts, and the
3301
+ context pack. Each opportunity carries: category, classification, confidence, source/target, evidence,
3302
+ rationale, suggested action, and \`requires_semantic_review\`.
3303
+
3304
+ ## Output
3305
+
3306
+ For each opportunity the agent chooses to act on: a reviewable proposal that states what would change,
3307
+ what content is added/moved/summarized, what must be preserved, and which claims still need
3308
+ confirmation \u2014 with a diff or equivalent. No canonical file is edited by this skill; application goes
3309
+ through the existing controlled-edit flows after human approval.
3310
+
3311
+ ## Rules
3312
+
3313
+ - Distinguish \`observed\` (verifiable fact) from \`suggested\` (a candidate needing judgement). Never
3314
+ present a \`suggested\` candidate as a verified conclusion.
3315
+ - Classify every claim as Observed / Derived / Suggested / Unknown.
3316
+ - Do not merge Business/Product/Tech just because they share a topic \u2014 preserve layer responsibilities.
3317
+ - Do not move every historical learning into current knowledge; incorporate only live rules, WITH a
3318
+ reference back to the originating Work Item. Never summarize or delete the Work Item.
3319
+ - Do not invent relationships, decisions or business rules; a missing optional relationship is an
3320
+ opportunity, not an error.
3321
+ - For a potential inconsistency, present BOTH sources and say whether the conflict is verified or
3322
+ potential. Never pick a winner arbitrarily.
3323
+ - Preserve critical constraints, decisions and reasons, exceptions, known risks, technical contracts,
3324
+ implementation evidence, provenance and necessary history.
3325
+ - Never reveal secret values or resolve secret references; never connect to a Project Resource.
3326
+ - Do not commit, push or release automatically.
3327
+
3328
+ ## Quality checklist
3329
+
3330
+ - Every proposal cites its source artifact(s) and evidence.
3331
+ - Facts are separated from interpretations.
3332
+ - Preserved information is named explicitly.
3333
+ - Claims needing confirmation are flagged.
3334
+ - No canonical artifact was modified by the analysis or the review.
3335
+
3336
+ ## Example output
3337
+
3338
+ A short set of proposals, each with evidence, a before/after (or diff) and an explicit list of what
3339
+ must be preserved, ready for human approval.
3340
+ `
3341
+ );
3279
3342
  var SKILLS = [
3280
3343
  ADR_WRITING,
3281
3344
  WORK_ITEM_REFINEMENT,
@@ -3287,10 +3350,11 @@ var SKILLS = [
3287
3350
  MODULE_CONTEXT_REFINEMENT,
3288
3351
  EVIDENCE_VERIFICATION,
3289
3352
  LEGACY_RISK_ASSESSMENT,
3290
- POC_REPORT_WRITING
3353
+ POC_REPORT_WRITING,
3354
+ KNOWLEDGE_CONSOLIDATION
3291
3355
  ];
3292
3356
  var SKILL_GROUPS = {
3293
- delivery: ["work-item-refinement", "implementation-planning", "learning-capture", "evidence-verification", "legacy-risk-assessment", "poc-report-writing"],
3357
+ delivery: ["work-item-refinement", "implementation-planning", "learning-capture", "evidence-verification", "legacy-risk-assessment", "poc-report-writing", "knowledge-consolidation"],
3294
3358
  tech: ["adr-writing", "ownership-suggestion", "graph-metadata-review", "module-context-refinement"],
3295
3359
  integration: ["capsule-writing"]
3296
3360
  };
@@ -3502,6 +3566,24 @@ var RESPONSIBILITY_MATRIX = {
3502
3566
  ],
3503
3567
  next: ["kaddo graph export"]
3504
3568
  },
3569
+ "knowledge-consolidation-agent": {
3570
+ agent: "knowledge-consolidation-agent",
3571
+ responsibleFor: [
3572
+ "Semantic review of the deterministic Consolidation Plan",
3573
+ "Preparing reviewable knowledge refinements"
3574
+ ],
3575
+ produces: ["proposed refinements (before/after) for human approval"],
3576
+ canSuggest: ["kaddo knowledge consolidate"],
3577
+ cannotSuggest: [
3578
+ "code",
3579
+ "git",
3580
+ "commits",
3581
+ "modifying canonical knowledge without confirmation",
3582
+ "inventing facts or relationships",
3583
+ "deleting history"
3584
+ ],
3585
+ next: ["kaddo knowledge consolidate"]
3586
+ },
3505
3587
  "ownership-agent": {
3506
3588
  agent: "ownership-agent",
3507
3589
  responsibleFor: ["Precise code: ownership for Work Items and artifacts"],
@@ -5662,6 +5744,78 @@ ADRs) and re-runs \`kaddo graph export\`.
5662
5744
  - No files were modified; no Git was run.
5663
5745
  - The human is asked to confirm and re-export the graph.
5664
5746
  `;
5747
+ var KNOWLEDGE_CONSOLIDATION_AGENT = `# Knowledge Consolidation Agent
5748
+
5749
+ ## Role
5750
+
5751
+ You are the Kaddo Knowledge Consolidation Agent. Your job is to perform the **semantic review** of
5752
+ the deterministic **Consolidation Plan** produced by \`kaddo knowledge consolidate\`, and to prepare
5753
+ **reviewable refinements** that make canonical knowledge more precise, connected, consistent and
5754
+ retrievable \u2014 without losing history, decisions or evidence.
5755
+
5756
+ You do not write code, you do not modify canonical files, and you never run Git. You propose; a human
5757
+ confirms, and application goes through Kaddo's existing controlled-edit flows.
5758
+
5759
+ ## When to Use
5760
+
5761
+ Use this agent after \`kaddo knowledge consolidate\` (or the \`kaddo_generate_consolidation_plan\`
5762
+ tool) has produced \`.kaddo/consolidation-plan.md\` and \`.kaddo/consolidation-plan.json\`, and the
5763
+ plan contains opportunities flagged \`requires_semantic_review\`.
5764
+
5765
+ ## Input Required
5766
+
5767
+ Provide \`.kaddo/context-pack.md\` and \`.kaddo/consolidation-plan.json\` as the primary inputs, plus
5768
+ the source artifacts each opportunity references under \`knowledge/\` (and completed Work Items under
5769
+ \`knowledge/delivery/work-items/completed/\` for learning opportunities).
5770
+
5771
+ ## Expected Output
5772
+
5773
+ For each opportunity you choose to act on, a proposal that states what would change, what content is
5774
+ added / moved / summarized, what must be preserved, and which claims still need confirmation \u2014 with a
5775
+ diff or equivalent before/after.
5776
+
5777
+ ## Instructions
5778
+
5779
+ 1. Read the plan and work one opportunity at a time, highest-signal first.
5780
+ 2. Separate what you **observe** in the files from what you **suggest** \u2014 never present a suggested
5781
+ candidate as a verified conclusion.
5782
+ 3. For possible redundancy, compare the actual sections; propose a single reference location only if
5783
+ one genuinely restates the other. Preserve layer separation (Business / Product / Tech / Delivery).
5784
+ 4. For an unincorporated learning, decide whether it is a live rule; if so, propose incorporating it
5785
+ into the right Tech artifact **with a reference back to the originating Work Item**. Never summarize
5786
+ or delete the Work Item.
5787
+ 5. For a relationship opportunity, propose the relationship only when existing knowledge justifies it;
5788
+ a missing optional relationship is an opportunity, not an error.
5789
+ 6. For a potential inconsistency, present **both** sources and say whether the conflict is verified or
5790
+ potential. Do not pick a winner arbitrarily.
5791
+ 7. Classify every claim as Observed / Derived / Suggested / Unknown, and mark what needs confirmation.
5792
+
5793
+ ## Constraints
5794
+
5795
+ - Do **not** modify canonical files \u2014 propose changes for a human to apply.
5796
+ - Do **not** invent facts, relationships, decisions or business rules.
5797
+ - Do **not** delete historical information, change Work Item states, or alter verification results.
5798
+ - Do **not** reveal secret values or resolve secret references; do **not** connect to a Project Resource.
5799
+ - Do **not** run Git, commit, push or release.
5800
+
5801
+ ## Output Format
5802
+
5803
+ Per opportunity: the opportunity id, classification and confidence, the proposed before/after (or
5804
+ diff), the explicit list of what must be preserved, and the open questions that need confirmation.
5805
+
5806
+ ## Where to Save the Result
5807
+
5808
+ Nothing is saved automatically. The human reviews the proposals and applies the approved ones through
5809
+ Kaddo's existing controlled-edit flows. Re-run \`kaddo knowledge consolidate\` afterwards to confirm.
5810
+
5811
+ ## Quality Checklist
5812
+
5813
+ - Every proposal cites its source artifact(s) and evidence from the plan.
5814
+ - Facts are separated from interpretations; suggested candidates are never asserted as fact.
5815
+ - Preserved information (constraints, decisions, exceptions, risks, contracts, provenance) is named.
5816
+ - No canonical artifact was modified; no Git was run.
5817
+ - The human is asked to confirm before anything is applied.
5818
+ `;
5665
5819
  var AGENT_PROMPTS = [
5666
5820
  { fileName: "capability-agent.md", content: CAPABILITY_AGENT },
5667
5821
  { fileName: "architecture-agent.md", content: ARCHITECTURE_AGENT },
@@ -5688,7 +5842,9 @@ var AGENT_PROMPTS = [
5688
5842
  // Knowledge Capsule refinement (external context — VS-054)
5689
5843
  { fileName: "capsule-agent.md", content: CAPSULE_AGENT },
5690
5844
  // Graph relationship quality (metadata hints → precise front matter — VS-056)
5691
- { fileName: "graph-agent.md", content: GRAPH_AGENT }
5845
+ { fileName: "graph-agent.md", content: GRAPH_AGENT },
5846
+ // Knowledge Consolidation semantic review (deterministic plan → reviewable refinements — WI-070)
5847
+ { fileName: "knowledge-consolidation-agent.md", content: KNOWLEDGE_CONSOLIDATION_AGENT }
5692
5848
  // Every official prompt ends with its responsibility boundaries + Agent Trace footer.
5693
5849
  ].map((p) => ({ fileName: p.fileName, content: withResponsibilityTrace(p.fileName, p.content) }));
5694
5850
 
@@ -5714,7 +5870,8 @@ var AGENT_GROUPS = {
5714
5870
  "work-item-agent.md",
5715
5871
  "implementation-agent.md",
5716
5872
  "ownership-agent.md",
5717
- "git-strategy-agent.md"
5873
+ "git-strategy-agent.md",
5874
+ "knowledge-consolidation-agent.md"
5718
5875
  ],
5719
5876
  utilities: ["legacy-agent.md"]
5720
5877
  };
@@ -8322,15 +8479,15 @@ function printCIJson(dir, touchedFiles, activeMatches, ignoredCount, pluginSigna
8322
8479
  plugin_signals: pluginSignals,
8323
8480
  domain_owners: affectedOwners,
8324
8481
  findings: activeMatches.map((m) => {
8325
- const label = artifactLabel(m.artifact, dir);
8482
+ const label2 = artifactLabel(m.artifact, dir);
8326
8483
  return {
8327
- artifact_id: label,
8484
+ artifact_id: label2,
8328
8485
  artifact_type: m.artifact.type,
8329
8486
  knowledge_level: m.artifact.knowledgeLevel,
8330
8487
  matched_files: m.matchedFiles,
8331
8488
  ownership: m.artifact.codeGlobs,
8332
8489
  evidence: m.evidence.signals,
8333
- message: `${label} was not modified in this diff`
8490
+ message: `${label2} was not modified in this diff`
8334
8491
  };
8335
8492
  })
8336
8493
  };
@@ -13911,7 +14068,7 @@ var KNOWLEDGE_FILES2 = [
13911
14068
  function buildReadinessReport(dir, now = /* @__PURE__ */ new Date()) {
13912
14069
  const config = loadConfig(dir);
13913
14070
  const rec = resolveNextStep(dir, now);
13914
- const stub = (overall2, label, command) => ({
14071
+ const stub = (overall2, label2, command) => ({
13915
14072
  project_name: config?.project.name ?? "unknown",
13916
14073
  project_type: config?.project.state ?? "unknown",
13917
14074
  overall: overall2,
@@ -13934,7 +14091,7 @@ function buildReadinessReport(dir, now = /* @__PURE__ */ new Date()) {
13934
14091
  resolved_questions: 0,
13935
14092
  deferred_questions: 0
13936
14093
  },
13937
- recommended_next_step: { label, ...command ? { command } : {} },
14094
+ recommended_next_step: { label: label2, ...command ? { command } : {} },
13938
14095
  nextStepRecommendation: rec
13939
14096
  });
13940
14097
  if (!config) return stub("not-initialized", rec.label, rec.command);
@@ -14114,9 +14271,9 @@ function installedAssetsSummary(dir) {
14114
14271
  // src/core/roadmap-quality.ts
14115
14272
  var ROADMAP_PATH2 = "knowledge/delivery/roadmap.md";
14116
14273
  var INITIATIVE_RE2 = /^#{2,4}\s+(RM-[\w.-]+)\s*[:\-–]?\s*(.*)$/;
14117
- function fieldPresent(lines, label) {
14274
+ function fieldPresent(lines, label2) {
14118
14275
  for (let i = 0; i < lines.length; i++) {
14119
- const m = lines[i].match(new RegExp(`^\\s*[-*]?\\s*(?:\\*\\*)?\\s*(${label.source})\\s*(?:\\*\\*)?\\s*:\\s*(.*)$`, "i"));
14276
+ const m = lines[i].match(new RegExp(`^\\s*[-*]?\\s*(?:\\*\\*)?\\s*(${label2.source})\\s*(?:\\*\\*)?\\s*:\\s*(.*)$`, "i"));
14120
14277
  if (!m) continue;
14121
14278
  const inline = m[2].trim();
14122
14279
  if (inline) return true;
@@ -16304,11 +16461,11 @@ function renderContextPack(pack) {
16304
16461
  if (mixEntries.length > 0) {
16305
16462
  parts.push("## Delivery Mix\n");
16306
16463
  parts.push("Active Work Items by type:\n");
16307
- const label = (t) => {
16464
+ const label2 = (t) => {
16308
16465
  const c = t.charAt(0).toUpperCase() + t.slice(1);
16309
16466
  return c.endsWith("s") ? c : `${c}s`;
16310
16467
  };
16311
- parts.push(mixEntries.map(([t, n]) => `- ${label(t)}: ${n}`).join("\n") + "\n");
16468
+ parts.push(mixEntries.map(([t, n]) => `- ${label2(t)}: ${n}`).join("\n") + "\n");
16312
16469
  }
16313
16470
  parts.push("## Artifacts and Ownership\n");
16314
16471
  if (knowledge.artifacts.length > 0) {
@@ -17666,18 +17823,18 @@ function readProjectState(dir) {
17666
17823
  }
17667
17824
  }
17668
17825
  function selectAgentModuleFiles(files, opts, state) {
17669
- const { files: names, label } = selectAgentFiles({ all: opts.all, group: opts.group, state });
17826
+ const { files: names, label: label2 } = selectAgentFiles({ all: opts.all, group: opts.group, state });
17670
17827
  const wanted = new Set(names);
17671
17828
  const selected = files.filter(
17672
17829
  (f) => f.path.endsWith("README.md") || names.some((n) => f.path.endsWith(n)) || wanted.has(f.path)
17673
17830
  );
17674
- return { files: selected, label };
17831
+ return { files: selected, label: label2 };
17675
17832
  }
17676
17833
  function selectSkillModuleFiles(files, opts) {
17677
- const { ids, label } = selectSkills({ all: opts.all, group: opts.group });
17834
+ const { ids, label: label2 } = selectSkills({ all: opts.all, group: opts.group });
17678
17835
  const wanted = new Set(ids.map((id) => skillInstallPath(id)));
17679
17836
  const selected = files.filter((f) => f.path.endsWith("README.md") || wanted.has(f.path));
17680
- return { files: selected, label };
17837
+ return { files: selected, label: label2 };
17681
17838
  }
17682
17839
  function markModuleInstalled(dir, configKey, moduleName) {
17683
17840
  const configPath = join(dir, CONFIG_PATH7);
@@ -19420,8 +19577,8 @@ function runResourcesGet(id, dir = cwd(), opts = {}) {
19420
19577
  console.log(" Access interfaces:");
19421
19578
  for (const i of r.interfaces) {
19422
19579
  const tool = i.tool ?? i.provider ?? "";
19423
- const label = tool ? `${i.type} (${tool})` : i.type;
19424
- console.log(` - ${label}`);
19580
+ const label2 = tool ? `${i.type} (${tool})` : i.type;
19581
+ console.log(` - ${label2}`);
19425
19582
  if (i.purpose) console.log(` purpose: ${i.purpose}`);
19426
19583
  if (i.operations.length > 0) console.log(` operations: ${i.operations.join(", ")}`);
19427
19584
  if (i.environments.length > 0) console.log(` environments: ${i.environments.join(", ")}`);
@@ -21238,9 +21395,9 @@ function renderImpactMarkdown(r, opts = {}) {
21238
21395
  ["validation section", gp.missing_validation]
21239
21396
  ];
21240
21397
  L.push("## Historical Documentation Completeness", "");
21241
- for (const [label, items] of historical) {
21398
+ for (const [label2, items] of historical) {
21242
21399
  const completed = items.filter((item) => item.status === "completed");
21243
- if (completed.length > 0) L.push(`- Completed Work Items without detected ${label}: ${completed.length}`);
21400
+ if (completed.length > 0) L.push(`- Completed Work Items without detected ${label2}: ${completed.length}`);
21244
21401
  }
21245
21402
  if (!historical.some(([, items]) => items.some((item) => item.status === "completed"))) {
21246
21403
  L.push("No historical documentation completeness gaps were detected.");
@@ -25781,6 +25938,554 @@ async function runVerify(workItemId, opts = {}) {
25781
25938
  if (!opts.json) outro("Verification complete.");
25782
25939
  }
25783
25940
 
25941
+ // src/core/knowledge-consolidation.ts
25942
+ import { createHash as createHash2 } from "crypto";
25943
+ import matter26 from "gray-matter";
25944
+ var KNOWLEDGE6 = "knowledge";
25945
+ var CONSOLIDATION_CATEGORIES = [
25946
+ "knowledge_redundancy",
25947
+ "unincorporated_learning",
25948
+ "knowledge_fragmentation",
25949
+ "relationship_opportunity",
25950
+ "potentially_outdated",
25951
+ "knowledge_organization"
25952
+ ];
25953
+ function toPosix7(p) {
25954
+ return p.replace(/\\/g, "/");
25955
+ }
25956
+ function relFromDir(dir, filePath) {
25957
+ const d = toPosix7(dir).replace(/\/+$/, "");
25958
+ const f = toPosix7(filePath);
25959
+ return f.startsWith(d + "/") ? f.slice(d.length + 1) : f;
25960
+ }
25961
+ function sha256(content) {
25962
+ return createHash2("sha256").update(content, "utf-8").digest("hex");
25963
+ }
25964
+ var SHINGLE_SIZE = 6;
25965
+ var MIN_SHARED_RUN = 6;
25966
+ function contentWords(body) {
25967
+ const words = [];
25968
+ let inFence = false;
25969
+ for (const raw of body.split(/\r?\n/)) {
25970
+ const t = raw.trim();
25971
+ if (/^```/.test(t)) {
25972
+ inFence = !inFence;
25973
+ continue;
25974
+ }
25975
+ if (inFence) continue;
25976
+ if (/^#{1,6}\s/.test(t)) continue;
25977
+ if (/^>/.test(t)) continue;
25978
+ const text2 = t.replace(/^([-*+]\s+|\d+\.\s+)/, "");
25979
+ const matched = text2.toLowerCase().match(/[a-záéíóúñü0-9]+/gi);
25980
+ if (matched) words.push(...matched);
25981
+ }
25982
+ return words;
25983
+ }
25984
+ function buildShingles(body) {
25985
+ const words = contentWords(body);
25986
+ const keys = [];
25987
+ const set = /* @__PURE__ */ new Set();
25988
+ for (let i = 0; i + SHINGLE_SIZE <= words.length; i++) {
25989
+ const key = words.slice(i, i + SHINGLE_SIZE).join(" ");
25990
+ keys.push(key);
25991
+ set.add(key);
25992
+ }
25993
+ return { words, keys, set };
25994
+ }
25995
+ function longestSharedRun(a, b) {
25996
+ let best = 0;
25997
+ let bestStart = -1;
25998
+ let run = 0;
25999
+ let runStart = 0;
26000
+ for (let i = 0; i < a.keys.length; i++) {
26001
+ if (b.set.has(a.keys[i])) {
26002
+ if (run === 0) runStart = i;
26003
+ run += 1;
26004
+ if (run > best) {
26005
+ best = run;
26006
+ bestStart = runStart;
26007
+ }
26008
+ } else {
26009
+ run = 0;
26010
+ }
26011
+ }
26012
+ if (best === 0) return { length: 0, snippet: "" };
26013
+ const snippet = a.words.slice(bestStart, bestStart + SHINGLE_SIZE + best - 1).join(" ");
26014
+ return { length: best, snippet };
26015
+ }
26016
+ var NORMATIVE_RE = /(^|[^a-záéíóúñü])(must|should|shall|debe[ns]?|deber[ií]a[ns]?|se\s+debe|hay\s+que|requiere[ns]?|require[sd]?|no\s+debe|invariant[e]?|invariants|restricci[oó]n|constraint|regla|obligatori[oa])([^a-záéíóúñü]|$)/i;
26017
+ var PAST_RESULT_RE = /(compil[aoeéó]\w*|compiled|benchmark\w*|passed|succeed\w*|succeeded|ran\s+successfully|ejecut\w*|resultad\w*|crates?\b|ns\/op|µs\b|throughput|latenc\w*|baseline|measured|medid\w*|\d+\s*%|\bx\d|faster|slower)/i;
26018
+ var TEST_RE = /(\btest\w*|\bpruebas?\b|coverage|cobertura|verde[s]?|green\b|assert\w*)/i;
26019
+ var BENCH_RE = /(benchmark\w*|ns\/op|µs\b|throughput|latenc\w*|ops\/s|\d+\s*%|faster|slower|baseline)/i;
26020
+ var EXPERIMENT_RE = /(experiment\w*|experiment[oa]\w*|prototyp\w*|prototip\w*|spike\b|probamos|probé|intentamos)/i;
26021
+ function splitSentences(text2) {
26022
+ return text2.replace(/\s+/g, " ").split(/(?<=[.!?;])\s+/).map((s) => s.trim()).filter(Boolean);
26023
+ }
26024
+ function classifyLearningSentence(sentence) {
26025
+ const s = sentence.trim();
26026
+ if (!s) return "none";
26027
+ const normative = NORMATIVE_RE.test(s);
26028
+ const pastResult = PAST_RESULT_RE.test(s);
26029
+ if (normative && !pastResult) return "durable-rule";
26030
+ if (BENCH_RE.test(s)) return "benchmark-evidence";
26031
+ if (pastResult) return "historical-result";
26032
+ if (TEST_RE.test(s)) return "test-observation";
26033
+ if (EXPERIMENT_RE.test(s)) return "experimental-result";
26034
+ return "none";
26035
+ }
26036
+ function firstRuleFragment(learning) {
26037
+ for (const sentence of splitSentences(learning)) {
26038
+ if (classifyLearningSentence(sentence) === "durable-rule") return sentence;
26039
+ }
26040
+ return null;
26041
+ }
26042
+ function sectionBody(body, titles) {
26043
+ const lines = body.split(/\r?\n/);
26044
+ const re = new RegExp(`^#{1,3}\\s+(${titles.join("|")})\\s*$`, "i");
26045
+ const start = lines.findIndex((l) => re.test(l));
26046
+ if (start < 0) return null;
26047
+ const collected = [];
26048
+ for (let i = start + 1; i < lines.length; i++) {
26049
+ if (/^#{1,3}\s+/.test(lines[i])) break;
26050
+ collected.push(lines[i]);
26051
+ }
26052
+ const text2 = collected.join("\n").trim();
26053
+ return text2.length > 0 ? text2 : null;
26054
+ }
26055
+ function stableOpportunityId(category, sources) {
26056
+ const key = [category, ...[...sources].sort()].join("|");
26057
+ return `${category}:${sha256(key).slice(0, 12)}`;
26058
+ }
26059
+ function layerOf(a) {
26060
+ const byType = layerForType(a.type);
26061
+ if (byType) return byType;
26062
+ const p = toPosix7(a.filePath);
26063
+ if (p.includes(`/${KNOWLEDGE6}/business/`)) return "Business";
26064
+ if (p.includes(`/${KNOWLEDGE6}/product/`)) return "Product";
26065
+ if (p.includes(`/${KNOWLEDGE6}/tech/`)) return "Tech";
26066
+ if (p.includes(`/${KNOWLEDGE6}/delivery/`)) return "Delivery";
26067
+ return null;
26068
+ }
26069
+ function inScope(la, scope) {
26070
+ if (scope.kind === "all") return true;
26071
+ if (scope.kind === "layer") return la.layer === scope.layer;
26072
+ return la.artifact.affectedModules.includes(scope.module);
26073
+ }
26074
+ function label(la) {
26075
+ return la.artifact.id || la.rel;
26076
+ }
26077
+ function buildConsolidationPlan(dir, opts = {}) {
26078
+ requireConfig(dir);
26079
+ const scope = opts.scope ?? { kind: "all" };
26080
+ const now = opts.now ?? /* @__PURE__ */ new Date();
26081
+ const archDir = join(dir, KNOWLEDGE6);
26082
+ const rawArtifacts = exists(archDir) ? readArtifacts(archDir) : [];
26083
+ const loaded = rawArtifacts.map((a) => {
26084
+ let body = "";
26085
+ try {
26086
+ body = matter26(readFile(a.filePath)).content;
26087
+ } catch {
26088
+ body = "";
26089
+ }
26090
+ return { artifact: a, rel: relFromDir(dir, a.filePath), body, layer: layerOf(a) };
26091
+ });
26092
+ const scoped = loaded.filter((la) => inScope(la, scope));
26093
+ const scopedRels = new Set(scoped.map((la) => la.rel));
26094
+ const knownIds = new Set(loaded.map((la) => la.artifact.id).filter(Boolean));
26095
+ const opportunities = [];
26096
+ try {
26097
+ const config = requireConfig(dir);
26098
+ const graph = buildGraph(dir, config, { scope: "all" }, now);
26099
+ const hints = buildGraphHints(dir, graph, now);
26100
+ for (const hint of hints.hints) {
26101
+ if (!hintInScope(hint, scoped)) continue;
26102
+ opportunities.push(relationshipOpportunityFromHint(hint));
26103
+ }
26104
+ } catch {
26105
+ }
26106
+ for (const la of scoped) {
26107
+ const dangling = la.artifact.decisions.filter((d) => d && !knownIds.has(d) && !decisionFileExists(dir, d));
26108
+ if (dangling.length === 0) continue;
26109
+ opportunities.push({
26110
+ id: stableOpportunityId("potentially_outdated", [label(la), ...dangling]),
26111
+ category: "potentially_outdated",
26112
+ classification: "observed",
26113
+ confidence: "requires-review",
26114
+ title: `${label(la)} references decision(s) that no longer exist`,
26115
+ source_artifacts: [label(la)],
26116
+ target_artifacts: [label(la)],
26117
+ evidence: dangling.map((d) => `Declared decision \`${d}\` has no matching artifact in the project.`),
26118
+ rationale: "A reference to a missing decision is a verifiable inconsistency: either the decision artifact was removed/renamed or the reference is stale.",
26119
+ possible_impact: "Broken traceability between a Work Item/artifact and its decisions.",
26120
+ suggested_action: "Review and update or remove the dangling decision reference.",
26121
+ requires_semantic_review: false
26122
+ });
26123
+ }
26124
+ const comparable = scoped.filter(isComparableKnowledge);
26125
+ const shingleIndex = /* @__PURE__ */ new Map();
26126
+ const shinglesByRel = /* @__PURE__ */ new Map();
26127
+ for (const la of comparable) {
26128
+ const shingles = buildShingles(la.body);
26129
+ shinglesByRel.set(la.rel, shingles);
26130
+ for (const key of shingles.set) {
26131
+ const arr = shingleIndex.get(key) ?? [];
26132
+ arr.push(la);
26133
+ shingleIndex.set(key, arr);
26134
+ }
26135
+ }
26136
+ const candidatePairs = /* @__PURE__ */ new Map();
26137
+ for (const arts of shingleIndex.values()) {
26138
+ if (arts.length < 2) continue;
26139
+ for (let i = 0; i < arts.length; i++) {
26140
+ for (let j = i + 1; j < arts.length; j++) {
26141
+ if (arts[i].rel === arts[j].rel) continue;
26142
+ const key = [arts[i].rel, arts[j].rel].sort().join("||");
26143
+ if (!candidatePairs.has(key)) candidatePairs.set(key, { a: arts[i], b: arts[j] });
26144
+ }
26145
+ }
26146
+ }
26147
+ for (const { a, b } of candidatePairs.values()) {
26148
+ const run = longestSharedRun(shinglesByRel.get(a.rel), shinglesByRel.get(b.rel));
26149
+ if (run.length < MIN_SHARED_RUN) continue;
26150
+ const passageWords = SHINGLE_SIZE + run.length - 1;
26151
+ opportunities.push({
26152
+ id: stableOpportunityId("knowledge_redundancy", [label(a), label(b)]),
26153
+ category: "knowledge_redundancy",
26154
+ classification: "suggested",
26155
+ confidence: "requires-review",
26156
+ title: `Possible overlapping content between ${label(a)} and ${label(b)}`,
26157
+ source_artifacts: [label(a), label(b)],
26158
+ target_artifacts: [label(a), label(b)],
26159
+ evidence: [
26160
+ `A ${passageWords}-word passage appears verbatim in both artifacts: "${redactSecrets2(run.snippet)}".`
26161
+ ],
26162
+ rationale: "A verbatim shared passage is a hint of potential duplication, NOT proof. Two documents can legitimately restate context from different layers/responsibilities; shared template structure alone was NOT used.",
26163
+ possible_impact: "If genuinely duplicated, the same fact can drift out of sync across files.",
26164
+ suggested_action: "Semantic review: compare the overlapping passage; if one restates the other, keep a single reference location and link the rest. Preserve layer separation.",
26165
+ requires_semantic_review: true
26166
+ });
26167
+ }
26168
+ for (const la of scoped) {
26169
+ if (!isCompletedWorkItem(la)) continue;
26170
+ const learning = sectionBody(la.body, ["Learning", "Aprendizaje", "Aprendizajes", "Learnings"]);
26171
+ if (!learning) continue;
26172
+ const ruleFragment = firstRuleFragment(learning);
26173
+ if (!ruleFragment) continue;
26174
+ opportunities.push({
26175
+ id: stableOpportunityId("unincorporated_learning", [label(la)]),
26176
+ category: "unincorporated_learning",
26177
+ classification: "suggested",
26178
+ confidence: "requires-review",
26179
+ title: `${label(la)} captured a learning that may belong in current knowledge`,
26180
+ source_artifacts: [label(la)],
26181
+ target_artifacts: [],
26182
+ // unresolved — determined in semantic review (never invent a destination)
26183
+ evidence: [`Completed Work Item records a rule-like learning (heuristic classification): "${redactSecrets2(ruleFragment)}"`],
26184
+ rationale: "A sentence phrased as a durable rule MAY represent live technical knowledge not yet reflected in current knowledge. The rule/result distinction is a heuristic, not a verified conclusion \u2014 this is a candidate, not a confirmed gap.",
26185
+ possible_impact: "A relevant constraint stays buried in delivery history instead of informing current work.",
26186
+ suggested_action: "Semantic review: confirm whether this is a live rule and determine the right destination artifact; if so, incorporate it WITH a reference back to the Work Item. Do not delete or summarize the Work Item.",
26187
+ requires_semantic_review: true
26188
+ });
26189
+ }
26190
+ const weakByFolder = /* @__PURE__ */ new Map();
26191
+ for (const la of scoped) {
26192
+ if (!isConsolidatableKnowledge(la)) continue;
26193
+ const quality = safeQuality(dir, la.rel);
26194
+ if (quality === "placeholder" || quality === "weak") {
26195
+ opportunities.push({
26196
+ id: stableOpportunityId("knowledge_organization", [la.rel]),
26197
+ category: "knowledge_organization",
26198
+ classification: "observed",
26199
+ confidence: "requires-review",
26200
+ title: `${label(la)} is ${quality} and may need consolidation or expansion`,
26201
+ source_artifacts: [label(la)],
26202
+ target_artifacts: [label(la)],
26203
+ evidence: [`Artifact quality analysis classifies this canonical knowledge artifact as "${quality}".`],
26204
+ rationale: "Observed: the quality heuristic rates this artifact low-signal. Whether it should be expanded, merged or cross-referenced is a judgement that needs semantic review \u2014 the quality signal alone does not decide it.",
26205
+ possible_impact: "Readers must open more files to assemble a complete picture.",
26206
+ suggested_action: "Semantic review: decide whether to expand, merge into a stronger artifact, or cross-reference it.",
26207
+ requires_semantic_review: true
26208
+ });
26209
+ const folder = la.rel.split("/").slice(0, -1).join("/");
26210
+ const arr = weakByFolder.get(folder) ?? [];
26211
+ arr.push(la);
26212
+ weakByFolder.set(folder, arr);
26213
+ }
26214
+ }
26215
+ for (const [folder, arts] of weakByFolder) {
26216
+ if (arts.length < 3) continue;
26217
+ opportunities.push({
26218
+ id: stableOpportunityId("knowledge_fragmentation", arts.map((a) => a.rel)),
26219
+ category: "knowledge_fragmentation",
26220
+ classification: "suggested",
26221
+ confidence: "requires-review",
26222
+ title: `${folder}/ holds ${arts.length} low-signal canonical artifacts \u2014 possible fragmentation`,
26223
+ source_artifacts: arts.map((a) => label(a)),
26224
+ target_artifacts: [folder],
26225
+ evidence: [`${arts.length} placeholder/weak canonical knowledge artifacts in the same folder: ${arts.map((a) => a.rel.split("/").pop()).join(", ")}.`],
26226
+ rationale: "Several thin canonical artifacts in one folder MAY be easier to consume if consolidated or cross-linked. Consolidation must preserve each distinct responsibility; Work Items and generated/lifecycle artifacts are not considered here.",
26227
+ possible_impact: "Related knowledge is spread across too many files to follow.",
26228
+ suggested_action: "Semantic review: evaluate whether cross-references or a consolidation would add clarity. Do not merge by file count alone.",
26229
+ requires_semantic_review: true
26230
+ });
26231
+ }
26232
+ opportunities.sort((x, y) => {
26233
+ const ci = CONSOLIDATION_CATEGORIES.indexOf(x.category) - CONSOLIDATION_CATEGORIES.indexOf(y.category);
26234
+ return ci !== 0 ? ci : x.id.localeCompare(y.id);
26235
+ });
26236
+ const seen = /* @__PURE__ */ new Set();
26237
+ const deduped = opportunities.filter((o) => seen.has(o.id) ? false : (seen.add(o.id), true));
26238
+ const layers = discoverLayers(dir);
26239
+ const layersEvaluated = scope.kind === "layer" ? [scope.layer] : layers.map((l) => l.layer);
26240
+ const workItemsEvaluated = scoped.filter(isWorkItem).length;
26241
+ const sourceFiles = [...scopedRels].sort().map((rel) => ({ path: rel, hash: sha256(readFileSafe(join(dir, rel))) }));
26242
+ const byCategory = Object.fromEntries(
26243
+ CONSOLIDATION_CATEGORIES.map((c) => [c, deduped.filter((o) => o.category === c).length])
26244
+ );
26245
+ return {
26246
+ generated_at: now.toISOString(),
26247
+ scope: describeScope(scope),
26248
+ project_context: reportingProjectContext(dir),
26249
+ coverage: {
26250
+ scope: describeScope(scope),
26251
+ layers_evaluated: layersEvaluated,
26252
+ artifacts_evaluated: scoped.length,
26253
+ work_items_evaluated: workItemsEvaluated,
26254
+ excluded_sources: scope.kind === "all" ? [] : [...loaded.map((l) => l.rel)].filter((r) => !scopedRels.has(r)).sort()
26255
+ },
26256
+ source_files: sourceFiles,
26257
+ opportunities: deduped,
26258
+ summary: {
26259
+ total: deduped.length,
26260
+ by_category: byCategory,
26261
+ requires_semantic_review: deduped.filter((o) => o.requires_semantic_review).length
26262
+ }
26263
+ };
26264
+ }
26265
+ var CATEGORY_LABELS = {
26266
+ knowledge_redundancy: "Possible redundancy",
26267
+ unincorporated_learning: "Learning integration opportunity",
26268
+ knowledge_fragmentation: "Possible fragmentation",
26269
+ relationship_opportunity: "Relationship review hint",
26270
+ potentially_outdated: "Potential inconsistency",
26271
+ knowledge_organization: "Organization opportunity"
26272
+ };
26273
+ function renderConsolidationMarkdown(plan) {
26274
+ const lines = [];
26275
+ lines.push("# Knowledge Consolidation Plan");
26276
+ lines.push("");
26277
+ lines.push("> Derived, review-only projection. No canonical knowledge was modified by this analysis.");
26278
+ lines.push("");
26279
+ lines.push(`- Generated at: ${plan.generated_at}`);
26280
+ lines.push(`- Scope: ${plan.scope}`);
26281
+ lines.push(`- Project: state=${plan.project_context.state}, mode=${plan.project_context.mode}, structure=${plan.project_context.repository_structure}`);
26282
+ lines.push("");
26283
+ lines.push("## Coverage");
26284
+ lines.push("");
26285
+ lines.push(`- Layers evaluated: ${plan.coverage.layers_evaluated.join(", ") || "\u2014"}`);
26286
+ lines.push(`- Artifacts evaluated: ${plan.coverage.artifacts_evaluated}`);
26287
+ lines.push(`- Work Items evaluated: ${plan.coverage.work_items_evaluated}`);
26288
+ if (plan.coverage.excluded_sources.length > 0) {
26289
+ lines.push(`- Excluded from this scope: ${plan.coverage.excluded_sources.length} artifact(s)`);
26290
+ }
26291
+ lines.push("");
26292
+ lines.push("## Findings");
26293
+ lines.push("");
26294
+ if (plan.summary.total === 0) {
26295
+ lines.push("No consolidation opportunities were detected by the available deterministic analyses within this scope.");
26296
+ lines.push("");
26297
+ lines.push("This is not a claim that the knowledge is perfect \u2014 only that no opportunity was found with the current signals.");
26298
+ lines.push("");
26299
+ return lines.join("\n") + "\n";
26300
+ }
26301
+ for (const cat of CONSOLIDATION_CATEGORIES) {
26302
+ const n = plan.summary.by_category[cat];
26303
+ if (n > 0) lines.push(`- ${n} \xD7 ${CATEGORY_LABELS[cat]}`);
26304
+ }
26305
+ lines.push("");
26306
+ lines.push(`${plan.summary.requires_semantic_review} finding(s) require semantic (agent/human) review before acting.`);
26307
+ lines.push("");
26308
+ lines.push("## Opportunities");
26309
+ lines.push("");
26310
+ for (const o of plan.opportunities) {
26311
+ lines.push(`### ${o.title}`);
26312
+ lines.push("");
26313
+ lines.push(`- Id: \`${o.id}\``);
26314
+ lines.push(`- Category: ${o.category}`);
26315
+ lines.push(`- Classification: **${o.classification}**${o.requires_semantic_review ? " (requires semantic review)" : ""}`);
26316
+ lines.push(`- Confidence: ${o.confidence}`);
26317
+ lines.push(`- Source: ${o.source_artifacts.join(", ") || "\u2014"}`);
26318
+ lines.push(
26319
+ `- Suggested target: ${o.target_artifacts.length > 0 ? o.target_artifacts.join(", ") : "(unresolved \u2014 to be determined in semantic review)"}`
26320
+ );
26321
+ lines.push(`- Evidence:`);
26322
+ for (const e of o.evidence) lines.push(` - ${e}`);
26323
+ lines.push(`- Rationale: ${o.rationale}`);
26324
+ lines.push(`- Possible impact: ${o.possible_impact}`);
26325
+ lines.push(`- Suggested action: ${o.suggested_action}`);
26326
+ lines.push("");
26327
+ }
26328
+ return lines.join("\n") + "\n";
26329
+ }
26330
+ function serializeConsolidationJson(plan) {
26331
+ return JSON.stringify(plan, null, 2) + "\n";
26332
+ }
26333
+ function describeScope(scope) {
26334
+ if (scope.kind === "all") return "all";
26335
+ if (scope.kind === "layer") return `layer:${scope.layer}`;
26336
+ return `module:${scope.module}`;
26337
+ }
26338
+ function isWorkItem(la) {
26339
+ return toPosix7(la.artifact.filePath).includes("/delivery/work-items/");
26340
+ }
26341
+ function isCompletedWorkItem(la) {
26342
+ const p = toPosix7(la.artifact.filePath);
26343
+ return p.includes("/delivery/work-items/completed/") || isWorkItem(la) && la.artifact.status === "completed";
26344
+ }
26345
+ function isScaffolding(la) {
26346
+ const p = toPosix7(la.artifact.filePath);
26347
+ return p.includes(`/${KNOWLEDGE6}/agents/`) || p.includes(`/${KNOWLEDGE6}/skills/`) || p.includes(`/${KNOWLEDGE6}/external/`) || la.artifact.type === "knowledge-capsule";
26348
+ }
26349
+ var NON_KNOWLEDGE_DOC_TYPES = /* @__PURE__ */ new Set([
26350
+ "roadmap",
26351
+ "initiative",
26352
+ "deprecation",
26353
+ "knowledge-capsule",
26354
+ "inventory",
26355
+ "project-resource"
26356
+ ]);
26357
+ function isComparableKnowledge(la) {
26358
+ return !isWorkItem(la) && la.artifact.type !== "roadmap" && !isScaffolding(la);
26359
+ }
26360
+ function isConsolidatableKnowledge(la) {
26361
+ if (isWorkItem(la) || isScaffolding(la)) return false;
26362
+ if (NON_KNOWLEDGE_DOC_TYPES.has(la.artifact.type)) return false;
26363
+ return la.layer === "Business" || la.layer === "Product" || la.layer === "Tech";
26364
+ }
26365
+ var SECRET_TOKEN_PATTERNS = [
26366
+ /\bgh[pours]_[A-Za-z0-9]{16,}\b/g,
26367
+ // GitHub tokens
26368
+ /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,
26369
+ // AWS access key ids
26370
+ /\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g,
26371
+ // Slack tokens
26372
+ /\bsk-[A-Za-z0-9]{16,}\b/g,
26373
+ // OpenAI-style keys
26374
+ /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/g,
26375
+ // JWTs
26376
+ /\b[A-Za-z0-9+/]{40,}={0,2}\b/g
26377
+ // long base64 / opaque blobs
26378
+ ];
26379
+ function redactSecrets2(text2) {
26380
+ let out = text2;
26381
+ for (const re of SECRET_TOKEN_PATTERNS) out = out.replace(re, "[redacted]");
26382
+ return out;
26383
+ }
26384
+ function safeQuality(dir, rel) {
26385
+ try {
26386
+ return analyzeKnowledgeArtifact(dir, rel);
26387
+ } catch {
26388
+ return "useful";
26389
+ }
26390
+ }
26391
+ function readFileSafe(abs) {
26392
+ try {
26393
+ return readFile(abs);
26394
+ } catch {
26395
+ return "";
26396
+ }
26397
+ }
26398
+ function decisionFileExists(dir, decisionId) {
26399
+ const decisionsDir = join(dir, KNOWLEDGE6, "tech", "decisions");
26400
+ if (!exists(decisionsDir)) return false;
26401
+ try {
26402
+ return readDir(decisionsDir).some((e) => {
26403
+ const full = join(decisionsDir, e);
26404
+ if (!isFile(full) || !e.endsWith(".md")) return false;
26405
+ return e.toLowerCase().includes(decisionId.toLowerCase());
26406
+ });
26407
+ } catch {
26408
+ return false;
26409
+ }
26410
+ }
26411
+ function hintInScope(hint, scoped) {
26412
+ if (scoped.length === 0) return false;
26413
+ return scoped.some(
26414
+ (la) => la.artifact.id === hint.artifact_id || hint.path && toPosix7(la.artifact.filePath).endsWith(toPosix7(hint.path))
26415
+ );
26416
+ }
26417
+ function relationshipOpportunityFromHint(hint) {
26418
+ const finding = graphHintFinding(hint);
26419
+ return {
26420
+ id: stableOpportunityId("relationship_opportunity", [hint.artifact_id, ...hint.missing]),
26421
+ category: "relationship_opportunity",
26422
+ classification: "observed",
26423
+ confidence: "requires-review",
26424
+ title: hint.message,
26425
+ source_artifacts: [hint.artifact_id],
26426
+ target_artifacts: [hint.artifact_id],
26427
+ evidence: [finding.evidence],
26428
+ rationale: "A missing OPTIONAL relationship is an opportunity to review, not an error or a verified inconsistency. Kaddo never invents the relationship.",
26429
+ possible_impact: "Weaker traceability in the knowledge graph.",
26430
+ suggested_action: finding.suggested_action,
26431
+ requires_semantic_review: false
26432
+ };
26433
+ }
26434
+
26435
+ // src/commands/knowledge.ts
26436
+ var LAYER_BY_FLAG = {
26437
+ business: "Business",
26438
+ product: "Product",
26439
+ tech: "Tech",
26440
+ delivery: "Delivery"
26441
+ };
26442
+ function resolveScope(opts) {
26443
+ if (opts.module) return { kind: "module", module: opts.module };
26444
+ if (opts.layer) {
26445
+ const layer2 = LAYER_BY_FLAG[opts.layer.toLowerCase()];
26446
+ if (!layer2) {
26447
+ throw new Error(`Unknown --layer "${opts.layer}". Use one of: business, product, tech, delivery.`);
26448
+ }
26449
+ return { kind: "layer", layer: layer2 };
26450
+ }
26451
+ return { kind: "all" };
26452
+ }
26453
+ function runKnowledgeConsolidate(opts = {}) {
26454
+ const dir = cwd();
26455
+ requireConfig(dir);
26456
+ intro("kaddo knowledge consolidate");
26457
+ if (opts.scope && opts.scope !== "all" && !opts.layer && !opts.module) {
26458
+ log.warn(`Unrecognized --scope "${opts.scope}"; analyzing the whole project. Use --layer or --module for a narrower scope.`);
26459
+ }
26460
+ const scope = resolveScope(opts);
26461
+ const plan = buildConsolidationPlan(dir, { scope });
26462
+ ensureDir(join(dir, ".kaddo"));
26463
+ const mdRel = join(".kaddo", "consolidation-plan.md");
26464
+ const jsonRel = join(".kaddo", "consolidation-plan.json");
26465
+ writeFile(join(dir, mdRel), renderConsolidationMarkdown(plan));
26466
+ writeFile(join(dir, jsonRel), serializeConsolidationJson(plan));
26467
+ log.success(`Consolidation analysis complete (scope: ${plan.scope}).`);
26468
+ log.info(
26469
+ `Artifacts evaluated: ${plan.coverage.artifacts_evaluated} \xB7 Work Items: ${plan.coverage.work_items_evaluated} \xB7 Opportunities: ${plan.summary.total}`
26470
+ );
26471
+ if (plan.summary.total === 0) {
26472
+ log.info("No consolidation opportunities detected within this scope by the available analyses.");
26473
+ log.info("This is not a claim of perfection \u2014 only that no opportunity surfaced with the current signals.");
26474
+ } else {
26475
+ for (const cat of CONSOLIDATION_CATEGORIES) {
26476
+ const n = plan.summary.by_category[cat];
26477
+ if (n > 0) log.info(`- ${n} \xD7 ${cat}`);
26478
+ }
26479
+ log.warn(
26480
+ `${plan.summary.requires_semantic_review} finding(s) require semantic review (agent/human) before acting \u2014 nothing was changed automatically.`
26481
+ );
26482
+ }
26483
+ log.info(`- ${mdRel.replace(/\\/g, "/")}`);
26484
+ log.info(`- ${jsonRel.replace(/\\/g, "/")}`);
26485
+ printCommandFooter("knowledge consolidate");
26486
+ outro("Consolidation Plan ready for review.");
26487
+ }
26488
+
25784
26489
  // src/core/telemetry.ts
25785
26490
  import crypto6 from "crypto";
25786
26491
 
@@ -26052,7 +26757,7 @@ function runTelemetryDisable() {
26052
26757
  }
26053
26758
 
26054
26759
  // src/core/initiative-write.ts
26055
- import matter26 from "gray-matter";
26760
+ import matter27 from "gray-matter";
26056
26761
  var WORK_ITEMS_DIR4 = "knowledge/delivery/work-items";
26057
26762
  var DRAFT_DIR2 = `${WORK_ITEMS_DIR4}/draft`;
26058
26763
  var InitiativeWriteError = class extends Error {
@@ -26164,7 +26869,7 @@ function buildInitiativeContent(id, input) {
26164
26869
  if (input.priority) data.priority = input.priority;
26165
26870
  if (input.source) data.source = input.source;
26166
26871
  if (input.sourceId) data.source_id = input.sourceId;
26167
- return matter26.stringify("\n" + (input.body ?? defaultBody(input.title.trim())), data);
26872
+ return matter27.stringify("\n" + (input.body ?? defaultBody(input.title.trim())), data);
26168
26873
  }
26169
26874
  function createInitiative(dir, input) {
26170
26875
  if (!input.title?.trim()) throw new InitiativeWriteError("Initiative title is required.");
@@ -26188,10 +26893,10 @@ function transitionInitiative(dir, id, to) {
26188
26893
  throw new InitiativeWriteError(`Invalid transition ${ini.status} \u2192 ${to}.`);
26189
26894
  }
26190
26895
  const raw = readFile(ini.filePath);
26191
- const { data, content } = matter26(raw, {});
26896
+ const { data, content } = matter27(raw, {});
26192
26897
  data.status = to;
26193
26898
  if (to === "completed") data.completed_at = today2();
26194
- const newContent = matter26.stringify(content, data);
26899
+ const newContent = matter27.stringify(content, data);
26195
26900
  writeFile(ini.filePath, newContent);
26196
26901
  const updated = parseInitiative(dir, ini.filePath, newContent);
26197
26902
  if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after transition.");
@@ -26260,7 +26965,7 @@ function buildWorkItemContent(wiId, iniId, candidate) {
26260
26965
  "_What did we learn? Update after completion._",
26261
26966
  ""
26262
26967
  ].join("\n");
26263
- return matter26.stringify("\n" + body, data);
26968
+ return matter27.stringify("\n" + body, data);
26264
26969
  }
26265
26970
  function materializeCandidate(dir, id, candidateId) {
26266
26971
  const ini = getInitiative(dir, id);
@@ -26277,13 +26982,13 @@ function materializeCandidate(dir, id, candidateId) {
26277
26982
  ensureDir(join(dir, DRAFT_DIR2));
26278
26983
  writeFile(join(dir, DRAFT_DIR2, fileName), buildWorkItemContent(wiId, ini.id, candidate));
26279
26984
  const raw = readFile(ini.filePath);
26280
- const { data, content } = matter26(raw, {});
26985
+ const { data, content } = matter27(raw, {});
26281
26986
  const cands = Array.isArray(data.candidates) ? data.candidates : [];
26282
26987
  for (const c of cands) {
26283
26988
  if (c && typeof c === "object" && String(c.id) === candidateId) c.materialized_as = wiId;
26284
26989
  }
26285
26990
  data.candidates = cands;
26286
- const newContent = matter26.stringify(content, data);
26991
+ const newContent = matter27.stringify(content, data);
26287
26992
  writeFile(ini.filePath, newContent);
26288
26993
  const updated = parseInitiative(dir, ini.filePath, newContent);
26289
26994
  if (!updated) throw new InitiativeWriteError("Failed to parse the Initiative after materialization.");
@@ -26652,6 +27357,10 @@ var graphCmd = program.command("graph").description("Export the lightweight, fil
26652
27357
  graphCmd.command("export").description("Write the knowledge graph to .kaddo/graph.json and .kaddo/graph.mmd").option("--scope <scope>", "Graph scope: active (default) or all").option("--format <format>", "Output format: json, mermaid (default: both)").action((opts) => {
26653
27358
  runGraphExport(opts);
26654
27359
  });
27360
+ var knowledgeCmd = program.command("knowledge").description("Operate on the canonical knowledge base (consolidation analysis \u2014 read-only, no LLM)");
27361
+ knowledgeCmd.command("consolidate").description("Analyze canonical knowledge and write a reviewable Consolidation Plan to .kaddo/ (no changes to knowledge/)").option("--layer <layer>", "Limit the analysis to one layer: business, product, tech, delivery").option("--module <id>", "Limit the analysis to artifacts affecting one mapped module").option("--scope <scope>", "Analysis scope: all (default)").action((opts) => {
27362
+ runKnowledgeConsolidate(opts);
27363
+ });
26655
27364
  var topologyCmd = program.command("topology").description("Validate and apply a semantic system topology proposal (agent proposes, human confirms, Core applies)");
26656
27365
  topologyCmd.command("validate <file>").description("Validate a topology proposal file deterministically (no write)").action((file) => {
26657
27366
  runTopologyValidate(file);