@kaddo/cli 3.91.0 → 3.94.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/core.js +477 -11
  2. package/dist/index.js +566 -15
  3. package/package.json +1 -1
package/dist/core.js CHANGED
@@ -2973,6 +2973,9 @@ function buildTechDecisions(dir) {
2973
2973
  candidates_both_exist: resolved.bothExist
2974
2974
  };
2975
2975
  }
2976
+ function hasUnmaterializedDecisions(td) {
2977
+ return td.candidates > 0 && td.adrs === 0;
2978
+ }
2976
2979
 
2977
2980
  // src/core/next-step.ts
2978
2981
  function buildDeliveryState(dir) {
@@ -3880,7 +3883,8 @@ var IMPLEMENTATION_PLANNING = skill(
3880
3883
 
3881
3884
  ## Purpose
3882
3885
 
3883
- Standardize the plan produced before implementation starts.
3886
+ Standardize the plan produced before implementation starts and ensure design deliberation is
3887
+ explicit before coding begins.
3884
3888
 
3885
3889
  ## When to use
3886
3890
 
@@ -3888,33 +3892,96 @@ Before writing code for a ready Work Item.
3888
3892
 
3889
3893
  ## Inputs
3890
3894
 
3891
- The context pack and the ready Work Item.
3895
+ Assemble context proportionally from the Build Contract's five sources:
3896
+
3897
+ 1. **Work Item:** outcome, acceptance criteria, constraints, out-of-scope, affected_modules, domains.
3898
+ 2. **Knowledge:** business, product, tech and delivery knowledge relevant to the Work Item's domains.
3899
+ 3. **System Context:** topology, module dependencies, system graph when available.
3900
+ 4. **Repository Context:** existing patterns, file structure, test conventions in affected modules.
3901
+ 5. **Related Work Items:** dependencies (depends_on), completed related Work Items for precedent.
3902
+
3903
+ ## Context assembly
3904
+
3905
+ Assemble proportionally to scope. A single-module bugfix needs the affected module's codebase
3906
+ and tests. A cross-cutting feature needs topology, multiple modules, and business context.
3907
+ Do not load everything \u2014 load what the scope demands.
3892
3908
 
3893
3909
  ## Output
3894
3910
 
3895
- A plan with: technical scope, expected files, risks, validations, out of scope, implementation
3896
- steps, and stop criteria (when to pause and ask).
3911
+ A plan covering the template below, ending with a confirmation gate.
3912
+
3913
+ ### Output template
3914
+
3915
+ \`\`\`markdown
3916
+ # Implementation Plan \u2014 <WI id>
3917
+
3918
+ ## Context Summary
3919
+ <!-- Relevant knowledge, system context, and repository observations assembled for this WI. -->
3920
+
3921
+ ## Design Deliberation
3922
+
3923
+ ### Technical Approach
3924
+ <!-- How this will be implemented. Be specific about patterns, modules, layers involved. -->
3925
+
3926
+ ### Rationale
3927
+ <!-- Why this approach. Reference existing patterns, constraints, or WI requirements. -->
3928
+
3929
+ ### Alternatives Considered
3930
+ <!-- When the change is non-trivial. May be omitted for trivial/obvious changes with a note. -->
3931
+
3932
+ ### Trade-offs
3933
+ <!-- When alternatives exist. Explicitly state what is gained and lost. -->
3934
+
3935
+ ### ADR Recommendation
3936
+ <!-- When the decision is architecturally significant: recommend materializing as ADR
3937
+ via adr-writing skill. Remove this section if not applicable. -->
3938
+
3939
+ ## Affected Areas
3940
+ <!-- Modules, files, surfaces impacted by this change. -->
3941
+
3942
+ ## Implementation Steps
3943
+ <!-- Numbered steps with expected files per step. -->
3944
+
3945
+ ## Validation Plan
3946
+ <!-- How to verify: test commands, manual steps, AC verification. -->
3947
+
3948
+ ## Stop Criteria
3949
+ <!-- When to pause and ask: scope expansion, contradictions, missing knowledge,
3950
+ architectural uncertainty. -->
3951
+
3952
+ ## Confirmation Gate
3953
+ Do not start coding without explicit human confirmation of this plan.
3954
+ \`\`\`
3897
3955
 
3898
3956
  ## Rules
3899
3957
 
3958
+ - Document Technical Approach and Rationale before listing implementation steps.
3900
3959
  - Do not start coding without confirmation.
3901
3960
  - Do not expand scope without updating the Work Item.
3902
3961
  - Never make commits or push \u2014 suggest only.
3903
3962
  - Review scope coverage before planning: check that expected result, current/target behavior,
3904
3963
  module coverage, and acceptance criteria are consistent. Flag contradictions (e.g., user-facing
3905
3964
  change with unassessed frontend module).
3965
+ - When you discover an architecturally significant decision during planning, recommend the
3966
+ adr-writing skill and pause.
3967
+ - When alternatives exist, document them. For trivial or obvious changes, Alternatives and
3968
+ Trade-offs may be omitted with a note explaining why.
3969
+ - Context assembly is proportional: do not load all project knowledge for a small fix.
3906
3970
 
3907
3971
  ## Quality checklist
3908
3972
 
3909
3973
  - Pre-implementation scope review is documented.
3974
+ - Technical Approach is documented with specific patterns and modules.
3975
+ - Rationale references WI requirements or existing project patterns.
3976
+ - Alternatives documented when non-trivial, or explicitly noted as not applicable.
3977
+ - ADR recommendation present when the decision is architecturally significant.
3978
+ - Context sources consulted are listed in Context Summary.
3910
3979
  - Scope and expected files are explicit.
3911
3980
  - Risks and validations are listed.
3981
+ - Validation plan includes how to verify each AC.
3912
3982
  - Stop criteria are defined.
3913
3983
  - Module coverage aligns with planned changes.
3914
-
3915
- ## Example output
3916
-
3917
- A numbered plan covering the sections above, ending with a request to confirm before coding.
3984
+ - Confirmation gate is present.
3918
3985
  `
3919
3986
  );
3920
3987
  var MODULE_CONTEXT_REFINEMENT = skill(
@@ -3969,6 +4036,56 @@ A refined \`module-context.md\` with real, project-specific content in all secti
3969
4036
  A \`module-context.md\` with all placeholder sections filled in.
3970
4037
  `
3971
4038
  );
4039
+ var EVIDENCE_VERIFICATION = skill(
4040
+ "evidence-verification",
4041
+ "Evidence Verification Skill",
4042
+ "delivery",
4043
+ ["implementation-agent", "guard-agent"],
4044
+ `
4045
+ # Evidence Verification Skill
4046
+
4047
+ ## Purpose
4048
+
4049
+ Estandarizar la recolecci\xF3n de evidencia de implementaci\xF3n y la verificaci\xF3n de Criterios de
4050
+ Aceptaci\xF3n antes de completar un Work Item.
4051
+
4052
+ ## When to use
4053
+
4054
+ Despu\xE9s de que la implementaci\xF3n y las pruebas de un Work Item terminan, antes de llamar
4055
+ \`kaddo learn\`.
4056
+
4057
+ ## Inputs
4058
+
4059
+ - El Work Item (id, ACs, affected_modules, release_gates, completion_exceptions).
4060
+ - El diff o lista de archivos modificados.
4061
+ - Resultados de pruebas y validaciones.
4062
+ - Excepciones propuestas con categor\xEDa e impacto.
4063
+
4064
+ ## Output
4065
+
4066
+ Un reporte de verificaci\xF3n: estado por AC, release gates, excepciones, desviaciones planned vs
4067
+ actual, y decisi\xF3n de completitud (READY_TO_COMPLETE | NEEDS_WORK | BLOCKED | READY_WITH_EXCEPTIONS).
4068
+
4069
+ ## Rules
4070
+
4071
+ - Nunca marcar un AC como passed sin evidencia concreta.
4072
+ - Nunca omitir un release gate fallido sin registrar una excepci\xF3n aceptada.
4073
+ - No incluir rutas de secretos en changed_paths.
4074
+ - Usar \`kaddo verify\` o MCP tools \`kaddo_collect_evidence\`/\`kaddo_verify_work_item\`.
4075
+
4076
+ ## Quality checklist
4077
+
4078
+ - Cada AC tiene un status expl\xEDcito.
4079
+ - Los release gates fallidos tienen blocker documentado.
4080
+ - Las excepciones aceptadas tienen approved_by y raz\xF3n.
4081
+ - No hay rutas de secretos en la evidencia.
4082
+ - La decisi\xF3n de completitud es coherente con ACs y gates.
4083
+
4084
+ ## Example output
4085
+
4086
+ Un reporte de verificaci\xF3n con ACs, gates, excepciones y decisi\xF3n de completitud.
4087
+ `
4088
+ );
3972
4089
  var SKILLS = [
3973
4090
  ADR_WRITING,
3974
4091
  WORK_ITEM_REFINEMENT,
@@ -3977,10 +4094,11 @@ var SKILLS = [
3977
4094
  CAPSULE_WRITING,
3978
4095
  LEARNING_CAPTURE,
3979
4096
  IMPLEMENTATION_PLANNING,
3980
- MODULE_CONTEXT_REFINEMENT
4097
+ MODULE_CONTEXT_REFINEMENT,
4098
+ EVIDENCE_VERIFICATION
3981
4099
  ];
3982
4100
  var SKILL_GROUPS = {
3983
- delivery: ["work-item-refinement", "implementation-planning", "learning-capture"],
4101
+ delivery: ["work-item-refinement", "implementation-planning", "learning-capture", "evidence-verification"],
3984
4102
  tech: ["adr-writing", "ownership-suggestion", "graph-metadata-review", "module-context-refinement"],
3985
4103
  integration: ["capsule-writing"]
3986
4104
  };
@@ -9396,6 +9514,347 @@ function buildRefinementHandoff(dir, workItemId) {
9396
9514
  };
9397
9515
  }
9398
9516
 
9517
+ // src/core/implementation-handoff.ts
9518
+ var WorkItemNotReadyError = class extends Error {
9519
+ constructor(workItemId, actualState) {
9520
+ super(`Work Item "${workItemId}" must be in "ready" state to produce an Implementation Handoff, but is "${actualState}".`);
9521
+ this.workItemId = workItemId;
9522
+ this.actualState = actualState;
9523
+ this.name = "WorkItemNotReadyError";
9524
+ }
9525
+ workItemId;
9526
+ actualState;
9527
+ };
9528
+ var RECOMMENDED_AGENT2 = "implementation-agent";
9529
+ var RECOMMENDED_SKILL2 = "implementation-planning";
9530
+ function buildImplementationHandoff(dir, workItemId) {
9531
+ const artifacts = discoverWorkItems(dir);
9532
+ const match = artifacts.find((a) => (a.id || a.title) === workItemId);
9533
+ if (!match) throw new WorkItemNotFoundError(workItemId);
9534
+ const lifecycle = lifecycleStateOf({ status: match.status, filePath: match.filePath });
9535
+ if (lifecycle !== "ready") throw new WorkItemNotReadyError(workItemId, lifecycle);
9536
+ const config = loadConfig(dir);
9537
+ const projectName = config?.project.name ?? "this project";
9538
+ const mappedModules = loadMappedModules(dir).map((m) => m.id);
9539
+ const multirepo = mappedModules.length > 0;
9540
+ const techDecisions = buildTechDecisions(dir);
9541
+ const unmaterialized = hasUnmaterializedDecisions(techDecisions);
9542
+ const wiId = match.id || match.title;
9543
+ const wiTitle = match.title || match.id;
9544
+ const affectedModules = match.affectedModules;
9545
+ const domains = match.domains;
9546
+ const scopeConfidence = match.scopeConfidence;
9547
+ const lines = [
9548
+ `Implement Work Item ${wiId} \u2014 "${wiTitle}" \u2014 in project "${projectName}" using Kaddo.`,
9549
+ "",
9550
+ `Use the canonical ${RECOMMENDED_AGENT2} and the ${RECOMMENDED_SKILL2} skill (via Kaddo MCP or skills),`,
9551
+ "with access to this repository.",
9552
+ "",
9553
+ "--- Context Assembly ---",
9554
+ "",
9555
+ "Before planning, assemble context proportionally from these sources:",
9556
+ "",
9557
+ "1. Work Item: outcome, acceptance criteria, constraints, out-of-scope, affected modules, domains.",
9558
+ "2. Knowledge: business, product, tech and delivery knowledge relevant to the Work Item domains.",
9559
+ "3. System Context: topology, module dependencies, system graph when available.",
9560
+ "4. Repository Context: existing patterns, file structure, test conventions in affected modules.",
9561
+ "5. Related Work Items: dependencies (depends_on), completed related Work Items for precedent.",
9562
+ "",
9563
+ "Assemble proportionally: a single-module bugfix needs the affected module and its tests.",
9564
+ "A cross-cutting feature needs topology, multiple modules, and business context.",
9565
+ "",
9566
+ "--- Design Deliberation ---",
9567
+ "",
9568
+ "Before writing code, document:",
9569
+ "",
9570
+ "- Technical Approach: how this will be implemented \u2014 patterns, modules, layers involved.",
9571
+ "- Rationale: why this approach \u2014 reference existing patterns, constraints, or WI requirements.",
9572
+ "- Alternatives Considered: when the change is non-trivial, document alternative approaches.",
9573
+ "- Trade-offs: when alternatives exist, state what is gained and lost with the chosen approach.",
9574
+ "",
9575
+ "For trivial or obvious changes, Alternatives and Trade-offs may be omitted with a note explaining why."
9576
+ ];
9577
+ if (unmaterialized) {
9578
+ lines.push(
9579
+ "",
9580
+ "--- ADR Recommendation ---",
9581
+ "",
9582
+ "This project has unmaterialized decision candidates. When the implementation involves an",
9583
+ "architecturally significant decision, use the adr-writing skill to formalize it as an ADR",
9584
+ "before implementing. Check knowledge/tech/discovery/decision-candidates.md for candidates."
9585
+ );
9586
+ }
9587
+ if (multirepo) {
9588
+ lines.push(
9589
+ "",
9590
+ `This is a multirepo project. Evaluate the scope across all relevant mapped modules (${mappedModules.join(", ")})`,
9591
+ "before finalizing the implementation plan."
9592
+ );
9593
+ }
9594
+ const topology = getSystemMapProjection(dir).metadata.topologyStatus;
9595
+ if (topology !== "unavailable") {
9596
+ lines.push(
9597
+ "",
9598
+ `The semantic system Graph is ${topology}. When semantic system topology is available:`,
9599
+ "1. identify the relevant system entry points;",
9600
+ "2. query the Kaddo Graph (search / neighbors / paths) for connected entities;",
9601
+ "3. treat Graph results as impact candidates, not confirmed scope;",
9602
+ "4. inspect the actual implementation in the repository for each candidate."
9603
+ );
9604
+ }
9605
+ lines.push(
9606
+ "",
9607
+ "--- Implementation Plan ---",
9608
+ "",
9609
+ "Produce a plan with:",
9610
+ "- Context Summary: what you assembled and consulted.",
9611
+ "- Design Deliberation: Technical Approach, Rationale, and when relevant, Alternatives and Trade-offs.",
9612
+ "- Affected Areas: modules, files, surfaces impacted.",
9613
+ "- Implementation Steps: numbered steps with expected files per step.",
9614
+ "- Validation Plan: how to verify \u2014 test commands, manual steps, AC verification.",
9615
+ "- Stop Criteria: when to pause and ask \u2014 scope expansion, contradictions, missing knowledge.",
9616
+ "",
9617
+ "Do not start coding without explicit human confirmation of this plan."
9618
+ );
9619
+ return {
9620
+ workItemId: wiId,
9621
+ title: wiTitle,
9622
+ projectName,
9623
+ lifecycle,
9624
+ affectedModules,
9625
+ domains,
9626
+ scopeConfidence,
9627
+ hasUnmaterializedDecisions: unmaterialized,
9628
+ recommendedAgent: RECOMMENDED_AGENT2,
9629
+ recommendedSkill: RECOMMENDED_SKILL2,
9630
+ text: lines.join("\n")
9631
+ };
9632
+ }
9633
+
9634
+ // src/core/implementation-evidence.ts
9635
+ var WorkItemNotInProgressError = class extends Error {
9636
+ constructor(workItemId, actualState) {
9637
+ super(`Work Item "${workItemId}" must be in "in-progress" state for verification, but is "${actualState}".`);
9638
+ this.workItemId = workItemId;
9639
+ this.actualState = actualState;
9640
+ this.name = "WorkItemNotInProgressError";
9641
+ }
9642
+ workItemId;
9643
+ actualState;
9644
+ };
9645
+ var SECRET_PATTERNS = [
9646
+ /\.env($|\.)/i,
9647
+ /credential/i,
9648
+ /secret/i,
9649
+ /token/i,
9650
+ /\.key$/i,
9651
+ /\.pem$/i,
9652
+ /\.p12$/i,
9653
+ /\.pfx$/i
9654
+ ];
9655
+ function filterSecretPaths(paths) {
9656
+ return paths.filter((p2) => !SECRET_PATTERNS.some((re) => re.test(p2)));
9657
+ }
9658
+ function collectImplementationEvidence(dir, workItemId, input) {
9659
+ const artifacts = discoverWorkItems(dir);
9660
+ const match = artifacts.find((a) => (a.id || a.title) === workItemId);
9661
+ if (!match) throw new WorkItemNotFoundError(workItemId);
9662
+ const lifecycle = lifecycleStateOf({ status: match.status, filePath: match.filePath });
9663
+ if (lifecycle !== "in-progress") throw new WorkItemNotInProgressError(workItemId, lifecycle);
9664
+ const repositories = {};
9665
+ for (const repo of input.repos) {
9666
+ repositories[repo.repoId] = {
9667
+ role: repo.role ?? (repo.repoId === "core" ? "core" : "module"),
9668
+ status: deriveRepoStatus(repo),
9669
+ changed_paths: filterSecretPaths(repo.changedPaths),
9670
+ validations: repo.validations.map((v) => ({
9671
+ command: v.command,
9672
+ status: v.status,
9673
+ ...v.reason ? { reason: v.reason } : {}
9674
+ })),
9675
+ ...repo.migrations?.length ? {
9676
+ migrations: repo.migrations.map((m) => ({
9677
+ id: m.id,
9678
+ environment: m.environment,
9679
+ status: m.status,
9680
+ ...m.reason ? { reason: m.reason } : {}
9681
+ }))
9682
+ } : {}
9683
+ };
9684
+ }
9685
+ return { repositories };
9686
+ }
9687
+ function verifyWorkItem(dir, workItemId, input) {
9688
+ const evidence = collectImplementationEvidence(dir, workItemId, input);
9689
+ const artifacts = discoverWorkItems(dir);
9690
+ const match = artifacts.find((a) => (a.id || a.title) === workItemId);
9691
+ const lifecycle = lifecycleStateOf({ status: match.status, filePath: match.filePath });
9692
+ const fm = match.rawFrontmatter;
9693
+ const acVerifications = mapACVerifications(input.acVerifications);
9694
+ const acSummary = computeACSummary(acVerifications);
9695
+ const releaseGates = Array.isArray(fm.release_gates) ? fm.release_gates : [];
9696
+ const completionExceptions = Array.isArray(fm.completion_exceptions) ? fm.completion_exceptions : [];
9697
+ const plannedVsActual = computePlannedVsActual(match.affectedModules, input.repos);
9698
+ const registeredModuleIds = loadMappedModules(dir).map((m) => m.id);
9699
+ const modifiedRepoIds = input.repos.map((r) => r.repoId);
9700
+ const crossRepo = analyzeCrossRepoEvidence({
9701
+ id: workItemId,
9702
+ lifecycle,
9703
+ implementationStatus: match.implementationStatus || "not-started",
9704
+ validationStatus: match.validationStatus || "not-started",
9705
+ releaseStatus: match.releaseStatus || "not-assessed",
9706
+ affectedModules: match.affectedModules,
9707
+ rawFrontmatter: fm,
9708
+ registeredModuleIds,
9709
+ modifiedRepoIds
9710
+ });
9711
+ const validationStatus = deriveValidationStatus(input.repos, acVerifications, completionExceptions);
9712
+ const implementationStatus = deriveImplementationStatus(input.repos);
9713
+ return {
9714
+ workItemId,
9715
+ lifecycle,
9716
+ implementationEvidence: evidence,
9717
+ acVerifications,
9718
+ acSummary,
9719
+ releaseGates,
9720
+ completionExceptions,
9721
+ findings: crossRepo.findings,
9722
+ plannedVsActual,
9723
+ validationStatus,
9724
+ implementationStatus
9725
+ };
9726
+ }
9727
+ function evaluateCompletion(verification) {
9728
+ const blockers = [];
9729
+ const warnings = [];
9730
+ const reasons = [];
9731
+ for (const gate of verification.releaseGates) {
9732
+ if (gate.status === "failed" || gate.status === "blocked") {
9733
+ blockers.push(`Release gate "${gate.id}" is ${gate.status}${gate.reason ? ": " + gate.reason : ""}.`);
9734
+ } else if (gate.status === "pending") {
9735
+ warnings.push(`Release gate "${gate.id}" is still pending.`);
9736
+ }
9737
+ }
9738
+ for (const ex of verification.completionExceptions) {
9739
+ if (ex.status === "rejected") {
9740
+ blockers.push(`Completion exception "${ex.id}" was rejected${ex.reason ? ": " + ex.reason : ""}.`);
9741
+ } else if (ex.status === "proposed") {
9742
+ warnings.push(`Completion exception "${ex.id}" is still proposed (not yet accepted).`);
9743
+ }
9744
+ }
9745
+ if (verification.acSummary.failed > 0) {
9746
+ const failedACs = verification.acVerifications.filter((ac) => ac.status === "failed");
9747
+ for (const ac of failedACs) {
9748
+ blockers.push(`AC failed: "${ac.criterion}".`);
9749
+ }
9750
+ }
9751
+ const blockingFindings = verification.findings.filter((f) => f.severity === "blocking");
9752
+ for (const f of blockingFindings) {
9753
+ blockers.push(f.message);
9754
+ }
9755
+ if (verification.acSummary.manualReview > 0) {
9756
+ warnings.push(`${verification.acSummary.manualReview} AC(s) require manual review.`);
9757
+ }
9758
+ if (verification.acSummary.notVerified > 0) {
9759
+ warnings.push(`${verification.acSummary.notVerified} AC(s) not yet verified.`);
9760
+ }
9761
+ const warningFindings = verification.findings.filter((f) => f.severity === "warning");
9762
+ for (const f of warningFindings) {
9763
+ warnings.push(f.message);
9764
+ }
9765
+ if (verification.plannedVsActual) {
9766
+ const pva = verification.plannedVsActual;
9767
+ if (pva.missingModules.length > 0) {
9768
+ warnings.push(`Planned modules not touched: ${pva.missingModules.join(", ")}.`);
9769
+ }
9770
+ if (pva.addedModules.length > 0) {
9771
+ warnings.push(`Unplanned modules modified: ${pva.addedModules.join(", ")}.`);
9772
+ }
9773
+ }
9774
+ let readiness;
9775
+ if (blockers.length > 0) {
9776
+ const hasOnlyACFailures = blockers.every((b) => b.startsWith("AC failed:"));
9777
+ if (hasOnlyACFailures) {
9778
+ readiness = "NEEDS_WORK";
9779
+ reasons.push("Acceptance criteria have failures that must be addressed.");
9780
+ } else {
9781
+ readiness = "BLOCKED";
9782
+ reasons.push("Blocking conditions prevent completion.");
9783
+ }
9784
+ } else {
9785
+ const hasAcceptedExceptions = verification.completionExceptions.some((e) => e.status === "accepted");
9786
+ if (hasAcceptedExceptions) {
9787
+ readiness = "READY_WITH_EXCEPTIONS";
9788
+ reasons.push("All required criteria pass. Accepted exceptions are documented.");
9789
+ } else {
9790
+ readiness = "READY_TO_COMPLETE";
9791
+ reasons.push("All acceptance criteria pass. No blocking conditions.");
9792
+ }
9793
+ }
9794
+ return { readiness, reasons, blockers, warnings };
9795
+ }
9796
+ function deriveRepoStatus(repo) {
9797
+ if (repo.validations.length === 0 && repo.changedPaths.length === 0) return "not-started";
9798
+ const hasFailure = repo.validations.some((v) => v.status === "failed" || v.status === "error");
9799
+ if (hasFailure) return "failed";
9800
+ const allPassed = repo.validations.length > 0 && repo.validations.every((v) => v.status === "passed" || v.status === "skipped");
9801
+ if (allPassed) return "completed";
9802
+ return "in-progress";
9803
+ }
9804
+ function mapACVerifications(verifications) {
9805
+ return verifications.map((v) => ({ ...v }));
9806
+ }
9807
+ function computeACSummary(verifications) {
9808
+ return {
9809
+ total: verifications.length,
9810
+ passed: verifications.filter((v) => v.status === "passed").length,
9811
+ failed: verifications.filter((v) => v.status === "failed").length,
9812
+ notVerified: verifications.filter((v) => v.status === "not-verified").length,
9813
+ manualReview: verifications.filter((v) => v.status === "manual-review-required").length
9814
+ };
9815
+ }
9816
+ function computePlannedVsActual(affectedModules, repos) {
9817
+ if (affectedModules.length === 0) return null;
9818
+ const actualModules = [...new Set(repos.map((r) => r.repoId))];
9819
+ const plannedSet = new Set(affectedModules);
9820
+ const actualSet = new Set(actualModules);
9821
+ return {
9822
+ hasHandoff: true,
9823
+ plannedModules: affectedModules,
9824
+ actualModules,
9825
+ addedModules: actualModules.filter((m) => !plannedSet.has(m)),
9826
+ missingModules: affectedModules.filter((m) => !actualSet.has(m))
9827
+ };
9828
+ }
9829
+ function deriveValidationStatus(repos, acVerifications, completionExceptions) {
9830
+ const allValidations = repos.flatMap((r) => r.validations);
9831
+ if (allValidations.length === 0 && acVerifications.length === 0) return "not-started";
9832
+ const hasFailed = allValidations.some((v) => v.status === "failed" || v.status === "error") || acVerifications.some((v) => v.status === "failed");
9833
+ if (hasFailed) {
9834
+ const hasAccepted = completionExceptions.some((e) => e.status === "accepted");
9835
+ if (hasAccepted) return "accepted-with-exceptions";
9836
+ return "failed";
9837
+ }
9838
+ const hasBlocked = allValidations.some((v) => v.status === "error");
9839
+ if (hasBlocked) return "blocked";
9840
+ const allComplete = allValidations.every((v) => v.status === "passed" || v.status === "skipped") && acVerifications.every((v) => v.status === "passed" || v.status === "not-verified");
9841
+ if (allComplete && allValidations.length > 0) return "passed";
9842
+ return "in-progress";
9843
+ }
9844
+ function deriveImplementationStatus(repos) {
9845
+ if (repos.length === 0) return "not-started";
9846
+ const hasChanges = repos.some((r) => r.changedPaths.length > 0);
9847
+ if (!hasChanges) return "not-started";
9848
+ const allComplete = repos.every((r) => {
9849
+ const status = deriveRepoStatus(r);
9850
+ return status === "completed";
9851
+ });
9852
+ if (allComplete) return "completed";
9853
+ const hasFailed = repos.some((r) => deriveRepoStatus(r) === "failed");
9854
+ if (hasFailed) return "partial";
9855
+ return "in-progress";
9856
+ }
9857
+
9399
9858
  // src/core/work-item-import.ts
9400
9859
  import crypto3 from "crypto";
9401
9860
  import fs4 from "fs";
@@ -11070,16 +11529,20 @@ export {
11070
11529
  TOPOLOGY_FILE,
11071
11530
  TopologyWriteError,
11072
11531
  WorkItemNotFoundError,
11532
+ WorkItemNotInProgressError,
11533
+ WorkItemNotReadyError,
11073
11534
  WorkItemWriteError,
11074
11535
  analyzeCrossRepoEvidence,
11075
11536
  analyzeScopeCoverage,
11076
11537
  applyTopologyProposal,
11538
+ buildImplementationHandoff,
11077
11539
  buildImportIndex,
11078
11540
  buildProjectExplanation,
11079
11541
  buildProjectRoute,
11080
11542
  buildReadinessReport,
11081
11543
  buildRefinementHandoff,
11082
11544
  buildTopologyEnrichmentHandoff,
11545
+ collectImplementationEvidence,
11083
11546
  computeContentHash,
11084
11547
  computeRefinementStatus,
11085
11548
  createIntegration,
@@ -11092,7 +11555,9 @@ export {
11092
11555
  discoverKnowledge,
11093
11556
  discoverWorkItems,
11094
11557
  enableIntegration,
11558
+ evaluateCompletion,
11095
11559
  exists,
11560
+ filterSecretPaths,
11096
11561
  findDuplicateByHash,
11097
11562
  findExistingById,
11098
11563
  findLinkedWorkItem,
@@ -11140,5 +11605,6 @@ export {
11140
11605
  validateSystemTopology,
11141
11606
  validateTopologyProposal,
11142
11607
  validateWorkItem,
11143
- verifyIntegration
11608
+ verifyIntegration,
11609
+ verifyWorkItem
11144
11610
  };
package/dist/index.js CHANGED
@@ -2698,7 +2698,8 @@ var IMPLEMENTATION_PLANNING = skill(
2698
2698
 
2699
2699
  ## Purpose
2700
2700
 
2701
- Standardize the plan produced before implementation starts.
2701
+ Standardize the plan produced before implementation starts and ensure design deliberation is
2702
+ explicit before coding begins.
2702
2703
 
2703
2704
  ## When to use
2704
2705
 
@@ -2706,33 +2707,96 @@ Before writing code for a ready Work Item.
2706
2707
 
2707
2708
  ## Inputs
2708
2709
 
2709
- The context pack and the ready Work Item.
2710
+ Assemble context proportionally from the Build Contract's five sources:
2711
+
2712
+ 1. **Work Item:** outcome, acceptance criteria, constraints, out-of-scope, affected_modules, domains.
2713
+ 2. **Knowledge:** business, product, tech and delivery knowledge relevant to the Work Item's domains.
2714
+ 3. **System Context:** topology, module dependencies, system graph when available.
2715
+ 4. **Repository Context:** existing patterns, file structure, test conventions in affected modules.
2716
+ 5. **Related Work Items:** dependencies (depends_on), completed related Work Items for precedent.
2717
+
2718
+ ## Context assembly
2719
+
2720
+ Assemble proportionally to scope. A single-module bugfix needs the affected module's codebase
2721
+ and tests. A cross-cutting feature needs topology, multiple modules, and business context.
2722
+ Do not load everything \u2014 load what the scope demands.
2710
2723
 
2711
2724
  ## Output
2712
2725
 
2713
- A plan with: technical scope, expected files, risks, validations, out of scope, implementation
2714
- steps, and stop criteria (when to pause and ask).
2726
+ A plan covering the template below, ending with a confirmation gate.
2727
+
2728
+ ### Output template
2729
+
2730
+ \`\`\`markdown
2731
+ # Implementation Plan \u2014 <WI id>
2732
+
2733
+ ## Context Summary
2734
+ <!-- Relevant knowledge, system context, and repository observations assembled for this WI. -->
2735
+
2736
+ ## Design Deliberation
2737
+
2738
+ ### Technical Approach
2739
+ <!-- How this will be implemented. Be specific about patterns, modules, layers involved. -->
2740
+
2741
+ ### Rationale
2742
+ <!-- Why this approach. Reference existing patterns, constraints, or WI requirements. -->
2743
+
2744
+ ### Alternatives Considered
2745
+ <!-- When the change is non-trivial. May be omitted for trivial/obvious changes with a note. -->
2746
+
2747
+ ### Trade-offs
2748
+ <!-- When alternatives exist. Explicitly state what is gained and lost. -->
2749
+
2750
+ ### ADR Recommendation
2751
+ <!-- When the decision is architecturally significant: recommend materializing as ADR
2752
+ via adr-writing skill. Remove this section if not applicable. -->
2753
+
2754
+ ## Affected Areas
2755
+ <!-- Modules, files, surfaces impacted by this change. -->
2756
+
2757
+ ## Implementation Steps
2758
+ <!-- Numbered steps with expected files per step. -->
2759
+
2760
+ ## Validation Plan
2761
+ <!-- How to verify: test commands, manual steps, AC verification. -->
2762
+
2763
+ ## Stop Criteria
2764
+ <!-- When to pause and ask: scope expansion, contradictions, missing knowledge,
2765
+ architectural uncertainty. -->
2766
+
2767
+ ## Confirmation Gate
2768
+ Do not start coding without explicit human confirmation of this plan.
2769
+ \`\`\`
2715
2770
 
2716
2771
  ## Rules
2717
2772
 
2773
+ - Document Technical Approach and Rationale before listing implementation steps.
2718
2774
  - Do not start coding without confirmation.
2719
2775
  - Do not expand scope without updating the Work Item.
2720
2776
  - Never make commits or push \u2014 suggest only.
2721
2777
  - Review scope coverage before planning: check that expected result, current/target behavior,
2722
2778
  module coverage, and acceptance criteria are consistent. Flag contradictions (e.g., user-facing
2723
2779
  change with unassessed frontend module).
2780
+ - When you discover an architecturally significant decision during planning, recommend the
2781
+ adr-writing skill and pause.
2782
+ - When alternatives exist, document them. For trivial or obvious changes, Alternatives and
2783
+ Trade-offs may be omitted with a note explaining why.
2784
+ - Context assembly is proportional: do not load all project knowledge for a small fix.
2724
2785
 
2725
2786
  ## Quality checklist
2726
2787
 
2727
2788
  - Pre-implementation scope review is documented.
2789
+ - Technical Approach is documented with specific patterns and modules.
2790
+ - Rationale references WI requirements or existing project patterns.
2791
+ - Alternatives documented when non-trivial, or explicitly noted as not applicable.
2792
+ - ADR recommendation present when the decision is architecturally significant.
2793
+ - Context sources consulted are listed in Context Summary.
2728
2794
  - Scope and expected files are explicit.
2729
2795
  - Risks and validations are listed.
2796
+ - Validation plan includes how to verify each AC.
2730
2797
  - Stop criteria are defined.
2731
2798
  - Module coverage aligns with planned changes.
2732
-
2733
- ## Example output
2734
-
2735
- A numbered plan covering the sections above, ending with a request to confirm before coding.
2799
+ - Confirmation gate is present.
2736
2800
  `
2737
2801
  );
2738
2802
  var MODULE_CONTEXT_REFINEMENT = skill(
@@ -2787,6 +2851,56 @@ A refined \`module-context.md\` with real, project-specific content in all secti
2787
2851
  A \`module-context.md\` with all placeholder sections filled in.
2788
2852
  `
2789
2853
  );
2854
+ var EVIDENCE_VERIFICATION = skill(
2855
+ "evidence-verification",
2856
+ "Evidence Verification Skill",
2857
+ "delivery",
2858
+ ["implementation-agent", "guard-agent"],
2859
+ `
2860
+ # Evidence Verification Skill
2861
+
2862
+ ## Purpose
2863
+
2864
+ Estandarizar la recolecci\xF3n de evidencia de implementaci\xF3n y la verificaci\xF3n de Criterios de
2865
+ Aceptaci\xF3n antes de completar un Work Item.
2866
+
2867
+ ## When to use
2868
+
2869
+ Despu\xE9s de que la implementaci\xF3n y las pruebas de un Work Item terminan, antes de llamar
2870
+ \`kaddo learn\`.
2871
+
2872
+ ## Inputs
2873
+
2874
+ - El Work Item (id, ACs, affected_modules, release_gates, completion_exceptions).
2875
+ - El diff o lista de archivos modificados.
2876
+ - Resultados de pruebas y validaciones.
2877
+ - Excepciones propuestas con categor\xEDa e impacto.
2878
+
2879
+ ## Output
2880
+
2881
+ Un reporte de verificaci\xF3n: estado por AC, release gates, excepciones, desviaciones planned vs
2882
+ actual, y decisi\xF3n de completitud (READY_TO_COMPLETE | NEEDS_WORK | BLOCKED | READY_WITH_EXCEPTIONS).
2883
+
2884
+ ## Rules
2885
+
2886
+ - Nunca marcar un AC como passed sin evidencia concreta.
2887
+ - Nunca omitir un release gate fallido sin registrar una excepci\xF3n aceptada.
2888
+ - No incluir rutas de secretos en changed_paths.
2889
+ - Usar \`kaddo verify\` o MCP tools \`kaddo_collect_evidence\`/\`kaddo_verify_work_item\`.
2890
+
2891
+ ## Quality checklist
2892
+
2893
+ - Cada AC tiene un status expl\xEDcito.
2894
+ - Los release gates fallidos tienen blocker documentado.
2895
+ - Las excepciones aceptadas tienen approved_by y raz\xF3n.
2896
+ - No hay rutas de secretos en la evidencia.
2897
+ - La decisi\xF3n de completitud es coherente con ACs y gates.
2898
+
2899
+ ## Example output
2900
+
2901
+ Un reporte de verificaci\xF3n con ACs, gates, excepciones y decisi\xF3n de completitud.
2902
+ `
2903
+ );
2790
2904
  var SKILLS = [
2791
2905
  ADR_WRITING,
2792
2906
  WORK_ITEM_REFINEMENT,
@@ -2795,10 +2909,11 @@ var SKILLS = [
2795
2909
  CAPSULE_WRITING,
2796
2910
  LEARNING_CAPTURE,
2797
2911
  IMPLEMENTATION_PLANNING,
2798
- MODULE_CONTEXT_REFINEMENT
2912
+ MODULE_CONTEXT_REFINEMENT,
2913
+ EVIDENCE_VERIFICATION
2799
2914
  ];
2800
2915
  var SKILL_GROUPS = {
2801
- delivery: ["work-item-refinement", "implementation-planning", "learning-capture"],
2916
+ delivery: ["work-item-refinement", "implementation-planning", "learning-capture", "evidence-verification"],
2802
2917
  tech: ["adr-writing", "ownership-suggestion", "graph-metadata-review", "module-context-refinement"],
2803
2918
  integration: ["capsule-writing"]
2804
2919
  };
@@ -15901,7 +16016,7 @@ ${learning.trim()}
15901
16016
  const newRaw = matter8.stringify(updatedContent, data);
15902
16017
  writeFile(filePath, newRaw);
15903
16018
  }
15904
- async function runLearn(artifactId) {
16019
+ async function runLearn(artifactId, opts = {}) {
15905
16020
  const dir = cwd();
15906
16021
  if (!exists(join(dir, ARCH_DIR9))) {
15907
16022
  console.error("No knowledge/ directory found. Run `kaddo init` first.");
@@ -15938,13 +16053,38 @@ async function runLearn(artifactId) {
15938
16053
  log2.error(`Work item "${targetId}" not found in ${WORK_ITEMS_DIR2}/`);
15939
16054
  process.exit(1);
15940
16055
  }
16056
+ const wiRaw = readFile(filePath);
16057
+ const wiData = matter8(wiRaw).data;
16058
+ if (!opts.force) {
16059
+ const completionBlockers = [];
16060
+ const releaseGates = Array.isArray(wiData.release_gates) ? wiData.release_gates : [];
16061
+ for (const gate of releaseGates) {
16062
+ if (gate.status === "failed" || gate.status === "blocked") {
16063
+ completionBlockers.push(`Release gate "${gate.id}" is ${gate.status}${gate.reason ? ": " + gate.reason : ""}.`);
16064
+ }
16065
+ }
16066
+ const completionExceptions = Array.isArray(wiData.completion_exceptions) ? wiData.completion_exceptions : [];
16067
+ for (const ex of completionExceptions) {
16068
+ if (ex.status === "rejected") {
16069
+ completionBlockers.push(`Completion exception "${ex.id}" was rejected${ex.reason ? ": " + ex.reason : ""}.`);
16070
+ }
16071
+ }
16072
+ if (wiData.validation_status === "failed") {
16073
+ completionBlockers.push('Validation status is "failed".');
16074
+ }
16075
+ if (completionBlockers.length > 0) {
16076
+ log2.error("Completion blocked:");
16077
+ for (const b of completionBlockers) log2.error(` \u2717 ${b}`);
16078
+ log2.info("Run `kaddo verify` to review evidence, or use `kaddo learn --force` to override.");
16079
+ outro2("Cannot complete Work Item.");
16080
+ return;
16081
+ }
16082
+ }
15941
16083
  const learning = await text2({
15942
16084
  message: "What did you learn from this change?",
15943
16085
  placeholder: "e.g. The retry logic needed a separate queue to avoid blocking the main flow",
15944
16086
  validate: (v) => v.trim().length === 0 ? "Learning is required." : void 0
15945
16087
  });
15946
- const wiRaw = readFile(filePath);
15947
- const wiData = matter8(wiRaw).data;
15948
16088
  const hasExceptions = wiData.validation_status === "accepted-with-exceptions" || Array.isArray(wiData.completion_exceptions) && wiData.completion_exceptions.length > 0;
15949
16089
  const releaseBlocked = wiData.release_status === "blocked";
15950
16090
  let enrichedLearning = learning.trim();
@@ -21189,6 +21329,414 @@ async function runWorkItemImport(dir, fileOrText, opts) {
21189
21329
  }
21190
21330
  }
21191
21331
 
21332
+ // src/commands/verify.ts
21333
+ import matter16 from "gray-matter";
21334
+
21335
+ // src/core/implementation-evidence.ts
21336
+ var WorkItemNotInProgressError = class extends Error {
21337
+ constructor(workItemId, actualState) {
21338
+ super(`Work Item "${workItemId}" must be in "in-progress" state for verification, but is "${actualState}".`);
21339
+ this.workItemId = workItemId;
21340
+ this.actualState = actualState;
21341
+ this.name = "WorkItemNotInProgressError";
21342
+ }
21343
+ workItemId;
21344
+ actualState;
21345
+ };
21346
+ var SECRET_PATTERNS = [
21347
+ /\.env($|\.)/i,
21348
+ /credential/i,
21349
+ /secret/i,
21350
+ /token/i,
21351
+ /\.key$/i,
21352
+ /\.pem$/i,
21353
+ /\.p12$/i,
21354
+ /\.pfx$/i
21355
+ ];
21356
+ function filterSecretPaths(paths) {
21357
+ return paths.filter((p2) => !SECRET_PATTERNS.some((re) => re.test(p2)));
21358
+ }
21359
+ function collectImplementationEvidence(dir, workItemId, input) {
21360
+ const artifacts = discoverWorkItems(dir);
21361
+ const match = artifacts.find((a) => (a.id || a.title) === workItemId);
21362
+ if (!match) throw new WorkItemNotFoundError(workItemId);
21363
+ const lifecycle = lifecycleStateOf({ status: match.status, filePath: match.filePath });
21364
+ if (lifecycle !== "in-progress") throw new WorkItemNotInProgressError(workItemId, lifecycle);
21365
+ const repositories = {};
21366
+ for (const repo of input.repos) {
21367
+ repositories[repo.repoId] = {
21368
+ role: repo.role ?? (repo.repoId === "core" ? "core" : "module"),
21369
+ status: deriveRepoStatus(repo),
21370
+ changed_paths: filterSecretPaths(repo.changedPaths),
21371
+ validations: repo.validations.map((v) => ({
21372
+ command: v.command,
21373
+ status: v.status,
21374
+ ...v.reason ? { reason: v.reason } : {}
21375
+ })),
21376
+ ...repo.migrations?.length ? {
21377
+ migrations: repo.migrations.map((m) => ({
21378
+ id: m.id,
21379
+ environment: m.environment,
21380
+ status: m.status,
21381
+ ...m.reason ? { reason: m.reason } : {}
21382
+ }))
21383
+ } : {}
21384
+ };
21385
+ }
21386
+ return { repositories };
21387
+ }
21388
+ function verifyWorkItem(dir, workItemId, input) {
21389
+ const evidence = collectImplementationEvidence(dir, workItemId, input);
21390
+ const artifacts = discoverWorkItems(dir);
21391
+ const match = artifacts.find((a) => (a.id || a.title) === workItemId);
21392
+ const lifecycle = lifecycleStateOf({ status: match.status, filePath: match.filePath });
21393
+ const fm2 = match.rawFrontmatter;
21394
+ const acVerifications = mapACVerifications(input.acVerifications);
21395
+ const acSummary = computeACSummary(acVerifications);
21396
+ const releaseGates = Array.isArray(fm2.release_gates) ? fm2.release_gates : [];
21397
+ const completionExceptions = Array.isArray(fm2.completion_exceptions) ? fm2.completion_exceptions : [];
21398
+ const plannedVsActual = computePlannedVsActual(match.affectedModules, input.repos);
21399
+ const registeredModuleIds = loadMappedModules(dir).map((m) => m.id);
21400
+ const modifiedRepoIds = input.repos.map((r) => r.repoId);
21401
+ const crossRepo = analyzeCrossRepoEvidence({
21402
+ id: workItemId,
21403
+ lifecycle,
21404
+ implementationStatus: match.implementationStatus || "not-started",
21405
+ validationStatus: match.validationStatus || "not-started",
21406
+ releaseStatus: match.releaseStatus || "not-assessed",
21407
+ affectedModules: match.affectedModules,
21408
+ rawFrontmatter: fm2,
21409
+ registeredModuleIds,
21410
+ modifiedRepoIds
21411
+ });
21412
+ const validationStatus = deriveValidationStatus(input.repos, acVerifications, completionExceptions);
21413
+ const implementationStatus = deriveImplementationStatus(input.repos);
21414
+ return {
21415
+ workItemId,
21416
+ lifecycle,
21417
+ implementationEvidence: evidence,
21418
+ acVerifications,
21419
+ acSummary,
21420
+ releaseGates,
21421
+ completionExceptions,
21422
+ findings: crossRepo.findings,
21423
+ plannedVsActual,
21424
+ validationStatus,
21425
+ implementationStatus
21426
+ };
21427
+ }
21428
+ function evaluateCompletion(verification) {
21429
+ const blockers = [];
21430
+ const warnings = [];
21431
+ const reasons = [];
21432
+ for (const gate of verification.releaseGates) {
21433
+ if (gate.status === "failed" || gate.status === "blocked") {
21434
+ blockers.push(`Release gate "${gate.id}" is ${gate.status}${gate.reason ? ": " + gate.reason : ""}.`);
21435
+ } else if (gate.status === "pending") {
21436
+ warnings.push(`Release gate "${gate.id}" is still pending.`);
21437
+ }
21438
+ }
21439
+ for (const ex of verification.completionExceptions) {
21440
+ if (ex.status === "rejected") {
21441
+ blockers.push(`Completion exception "${ex.id}" was rejected${ex.reason ? ": " + ex.reason : ""}.`);
21442
+ } else if (ex.status === "proposed") {
21443
+ warnings.push(`Completion exception "${ex.id}" is still proposed (not yet accepted).`);
21444
+ }
21445
+ }
21446
+ if (verification.acSummary.failed > 0) {
21447
+ const failedACs = verification.acVerifications.filter((ac) => ac.status === "failed");
21448
+ for (const ac of failedACs) {
21449
+ blockers.push(`AC failed: "${ac.criterion}".`);
21450
+ }
21451
+ }
21452
+ const blockingFindings = verification.findings.filter((f) => f.severity === "blocking");
21453
+ for (const f of blockingFindings) {
21454
+ blockers.push(f.message);
21455
+ }
21456
+ if (verification.acSummary.manualReview > 0) {
21457
+ warnings.push(`${verification.acSummary.manualReview} AC(s) require manual review.`);
21458
+ }
21459
+ if (verification.acSummary.notVerified > 0) {
21460
+ warnings.push(`${verification.acSummary.notVerified} AC(s) not yet verified.`);
21461
+ }
21462
+ const warningFindings = verification.findings.filter((f) => f.severity === "warning");
21463
+ for (const f of warningFindings) {
21464
+ warnings.push(f.message);
21465
+ }
21466
+ if (verification.plannedVsActual) {
21467
+ const pva = verification.plannedVsActual;
21468
+ if (pva.missingModules.length > 0) {
21469
+ warnings.push(`Planned modules not touched: ${pva.missingModules.join(", ")}.`);
21470
+ }
21471
+ if (pva.addedModules.length > 0) {
21472
+ warnings.push(`Unplanned modules modified: ${pva.addedModules.join(", ")}.`);
21473
+ }
21474
+ }
21475
+ let readiness;
21476
+ if (blockers.length > 0) {
21477
+ const hasOnlyACFailures = blockers.every((b) => b.startsWith("AC failed:"));
21478
+ if (hasOnlyACFailures) {
21479
+ readiness = "NEEDS_WORK";
21480
+ reasons.push("Acceptance criteria have failures that must be addressed.");
21481
+ } else {
21482
+ readiness = "BLOCKED";
21483
+ reasons.push("Blocking conditions prevent completion.");
21484
+ }
21485
+ } else {
21486
+ const hasAcceptedExceptions = verification.completionExceptions.some((e) => e.status === "accepted");
21487
+ if (hasAcceptedExceptions) {
21488
+ readiness = "READY_WITH_EXCEPTIONS";
21489
+ reasons.push("All required criteria pass. Accepted exceptions are documented.");
21490
+ } else {
21491
+ readiness = "READY_TO_COMPLETE";
21492
+ reasons.push("All acceptance criteria pass. No blocking conditions.");
21493
+ }
21494
+ }
21495
+ return { readiness, reasons, blockers, warnings };
21496
+ }
21497
+ function deriveRepoStatus(repo) {
21498
+ if (repo.validations.length === 0 && repo.changedPaths.length === 0) return "not-started";
21499
+ const hasFailure = repo.validations.some((v) => v.status === "failed" || v.status === "error");
21500
+ if (hasFailure) return "failed";
21501
+ const allPassed = repo.validations.length > 0 && repo.validations.every((v) => v.status === "passed" || v.status === "skipped");
21502
+ if (allPassed) return "completed";
21503
+ return "in-progress";
21504
+ }
21505
+ function mapACVerifications(verifications) {
21506
+ return verifications.map((v) => ({ ...v }));
21507
+ }
21508
+ function computeACSummary(verifications) {
21509
+ return {
21510
+ total: verifications.length,
21511
+ passed: verifications.filter((v) => v.status === "passed").length,
21512
+ failed: verifications.filter((v) => v.status === "failed").length,
21513
+ notVerified: verifications.filter((v) => v.status === "not-verified").length,
21514
+ manualReview: verifications.filter((v) => v.status === "manual-review-required").length
21515
+ };
21516
+ }
21517
+ function computePlannedVsActual(affectedModules, repos) {
21518
+ if (affectedModules.length === 0) return null;
21519
+ const actualModules = [...new Set(repos.map((r) => r.repoId))];
21520
+ const plannedSet = new Set(affectedModules);
21521
+ const actualSet = new Set(actualModules);
21522
+ return {
21523
+ hasHandoff: true,
21524
+ plannedModules: affectedModules,
21525
+ actualModules,
21526
+ addedModules: actualModules.filter((m) => !plannedSet.has(m)),
21527
+ missingModules: affectedModules.filter((m) => !actualSet.has(m))
21528
+ };
21529
+ }
21530
+ function deriveValidationStatus(repos, acVerifications, completionExceptions) {
21531
+ const allValidations = repos.flatMap((r) => r.validations);
21532
+ if (allValidations.length === 0 && acVerifications.length === 0) return "not-started";
21533
+ const hasFailed = allValidations.some((v) => v.status === "failed" || v.status === "error") || acVerifications.some((v) => v.status === "failed");
21534
+ if (hasFailed) {
21535
+ const hasAccepted = completionExceptions.some((e) => e.status === "accepted");
21536
+ if (hasAccepted) return "accepted-with-exceptions";
21537
+ return "failed";
21538
+ }
21539
+ const hasBlocked = allValidations.some((v) => v.status === "error");
21540
+ if (hasBlocked) return "blocked";
21541
+ const allComplete = allValidations.every((v) => v.status === "passed" || v.status === "skipped") && acVerifications.every((v) => v.status === "passed" || v.status === "not-verified");
21542
+ if (allComplete && allValidations.length > 0) return "passed";
21543
+ return "in-progress";
21544
+ }
21545
+ function deriveImplementationStatus(repos) {
21546
+ if (repos.length === 0) return "not-started";
21547
+ const hasChanges = repos.some((r) => r.changedPaths.length > 0);
21548
+ if (!hasChanges) return "not-started";
21549
+ const allComplete = repos.every((r) => {
21550
+ const status = deriveRepoStatus(r);
21551
+ return status === "completed";
21552
+ });
21553
+ if (allComplete) return "completed";
21554
+ const hasFailed = repos.some((r) => deriveRepoStatus(r) === "failed");
21555
+ if (hasFailed) return "partial";
21556
+ return "in-progress";
21557
+ }
21558
+
21559
+ // src/commands/verify.ts
21560
+ function extractACsFromBody(body) {
21561
+ const lines = body.split(/\r?\n/);
21562
+ let inAC = false;
21563
+ const acs = [];
21564
+ for (const line of lines) {
21565
+ if (/^#{1,6}\s+acceptance\s+criteria/i.test(line)) {
21566
+ inAC = true;
21567
+ continue;
21568
+ }
21569
+ if (inAC && /^#{1,6}\s+/.test(line)) break;
21570
+ if (inAC) {
21571
+ const m = line.match(/^\s*[-*+]\s+(?:\[[ xX]\]\s*)?(.+)$/);
21572
+ if (m) {
21573
+ const text3 = m[1].trim();
21574
+ if (text3 && !/^_.*_$/.test(text3) && !/^tbd$/i.test(text3)) {
21575
+ acs.push(text3);
21576
+ }
21577
+ }
21578
+ }
21579
+ }
21580
+ return acs;
21581
+ }
21582
+ async function runVerify(workItemId, opts = {}) {
21583
+ const dir = cwd();
21584
+ if (!exists(join(dir, "knowledge"))) {
21585
+ console.error("No knowledge/ directory found. Run `kaddo init` first.");
21586
+ process.exit(1);
21587
+ }
21588
+ if (!opts.json) intro2("kaddo verify");
21589
+ const artifacts = discoverWorkItems(dir);
21590
+ const match = artifacts.find((a) => (a.id || a.title) === workItemId);
21591
+ if (!match) {
21592
+ if (opts.json) {
21593
+ console.log(JSON.stringify({ error: `Work Item "${workItemId}" not found.` }));
21594
+ } else {
21595
+ log2.error(`Work Item "${workItemId}" not found.`);
21596
+ }
21597
+ process.exit(1);
21598
+ }
21599
+ const lifecycle = lifecycleStateOf({ status: match.status, filePath: match.filePath });
21600
+ if (lifecycle !== "in-progress") {
21601
+ if (opts.json) {
21602
+ console.log(JSON.stringify({ error: `Work Item "${workItemId}" is "${lifecycle}", expected "in-progress".` }));
21603
+ } else {
21604
+ log2.error(`Work Item "${workItemId}" is "${lifecycle}". Only in-progress Work Items can be verified.`);
21605
+ }
21606
+ process.exit(1);
21607
+ }
21608
+ const changedPaths = await getModifiedFiles("head");
21609
+ const raw = readFile(match.filePath);
21610
+ const parsed = matter16(raw);
21611
+ const fm2 = parsed.data;
21612
+ const acs = extractACsFromBody(parsed.content);
21613
+ const existingEvidence = fm2.implementation_evidence;
21614
+ const existingRepos = existingEvidence?.repositories ?? {};
21615
+ const repos = Object.keys(existingRepos).length > 0 ? Object.entries(existingRepos).map(([repoId, data]) => {
21616
+ const d = data;
21617
+ return {
21618
+ repoId,
21619
+ role: typeof d.role === "string" ? d.role : void 0,
21620
+ changedPaths: Array.isArray(d.changed_paths) ? d.changed_paths.map(String) : [],
21621
+ validations: Array.isArray(d.validations) ? d.validations.map((v) => ({
21622
+ command: String(v.command ?? ""),
21623
+ status: String(v.status ?? "passed"),
21624
+ ...v.reason ? { reason: String(v.reason) } : {}
21625
+ })) : [],
21626
+ migrations: Array.isArray(d.migrations) ? d.migrations.map((m) => ({
21627
+ id: String(m.id ?? ""),
21628
+ environment: String(m.environment ?? ""),
21629
+ status: String(m.status ?? "unknown"),
21630
+ ...m.reason ? { reason: String(m.reason) } : {}
21631
+ })) : void 0
21632
+ };
21633
+ }) : [{ repoId: "core", changedPaths, validations: [] }];
21634
+ const acVerifications = acs.map((ac) => ({
21635
+ criterion: ac,
21636
+ status: "not-verified"
21637
+ }));
21638
+ const input = {
21639
+ repos,
21640
+ acVerifications
21641
+ };
21642
+ let verification;
21643
+ try {
21644
+ verification = verifyWorkItem(dir, workItemId, input);
21645
+ } catch (e) {
21646
+ if (e instanceof WorkItemNotFoundError || e instanceof WorkItemNotInProgressError) {
21647
+ if (opts.json) {
21648
+ console.log(JSON.stringify({ error: e.message }));
21649
+ } else {
21650
+ log2.error(e.message);
21651
+ }
21652
+ process.exit(1);
21653
+ }
21654
+ throw e;
21655
+ }
21656
+ const evaluation = evaluateCompletion(verification);
21657
+ if (opts.json) {
21658
+ console.log(JSON.stringify({ verification, evaluation }, null, 2));
21659
+ return;
21660
+ }
21661
+ log2.info(`Work Item: ${workItemId}`);
21662
+ log2.info(`Lifecycle: ${verification.lifecycle}`);
21663
+ log2.info(`Implementation: ${verification.implementationStatus}`);
21664
+ log2.info(`Validation: ${verification.validationStatus}`);
21665
+ console.log("");
21666
+ if (verification.acVerifications.length > 0) {
21667
+ console.log("Acceptance Criteria:");
21668
+ for (const ac of verification.acVerifications) {
21669
+ const icon = ac.status === "passed" ? "\u2713" : ac.status === "failed" ? "\u2717" : ac.status === "manual-review-required" ? "?" : "\xB7";
21670
+ console.log(` ${icon} [${ac.status}] ${ac.criterion}`);
21671
+ }
21672
+ console.log(` Summary: ${verification.acSummary.passed}/${verification.acSummary.total} passed`);
21673
+ console.log("");
21674
+ }
21675
+ if (verification.releaseGates.length > 0) {
21676
+ console.log("Release Gates:");
21677
+ for (const gate of verification.releaseGates) {
21678
+ const icon = gate.status === "passed" ? "\u2713" : gate.status === "failed" || gate.status === "blocked" ? "\u2717" : "\xB7";
21679
+ console.log(` ${icon} [${gate.status}] ${gate.id}${gate.reason ? " \u2014 " + gate.reason : ""}`);
21680
+ }
21681
+ console.log("");
21682
+ }
21683
+ if (verification.completionExceptions.length > 0) {
21684
+ console.log("Completion Exceptions:");
21685
+ for (const ex of verification.completionExceptions) {
21686
+ const icon = ex.status === "accepted" || ex.status === "resolved" ? "\u2713" : ex.status === "rejected" ? "\u2717" : "\xB7";
21687
+ console.log(` ${icon} [${ex.status}] ${ex.id}${ex.reason ? " \u2014 " + ex.reason : ""}`);
21688
+ }
21689
+ console.log("");
21690
+ }
21691
+ if (verification.findings.length > 0) {
21692
+ console.log("Findings:");
21693
+ for (const f of verification.findings) {
21694
+ const icon = f.severity === "blocking" ? "\u2717" : f.severity === "warning" ? "!" : "\xB7";
21695
+ console.log(` ${icon} [${f.severity}] ${f.message}`);
21696
+ }
21697
+ console.log("");
21698
+ }
21699
+ if (verification.plannedVsActual) {
21700
+ const pva = verification.plannedVsActual;
21701
+ if (pva.addedModules.length > 0 || pva.missingModules.length > 0) {
21702
+ console.log("Planned vs Actual:");
21703
+ if (pva.addedModules.length > 0) console.log(` Added: ${pva.addedModules.join(", ")}`);
21704
+ if (pva.missingModules.length > 0) console.log(` Missing: ${pva.missingModules.join(", ")}`);
21705
+ console.log("");
21706
+ }
21707
+ }
21708
+ const readinessIcon = evaluation.readiness === "READY_TO_COMPLETE" ? "\u2713" : evaluation.readiness === "READY_WITH_EXCEPTIONS" ? "!" : "\u2717";
21709
+ console.log(`Completion Decision: ${readinessIcon} ${evaluation.readiness}`);
21710
+ for (const r of evaluation.reasons) console.log(` ${r}`);
21711
+ if (evaluation.blockers.length > 0) {
21712
+ console.log(" Blockers:");
21713
+ for (const b of evaluation.blockers) console.log(` \u2717 ${b}`);
21714
+ }
21715
+ if (evaluation.warnings.length > 0) {
21716
+ console.log(" Warnings:");
21717
+ for (const w of evaluation.warnings) console.log(` ! ${w}`);
21718
+ }
21719
+ console.log("");
21720
+ const shouldPersist = opts.yes || await confirm2({
21721
+ message: "Update Work Item frontmatter with verification evidence?",
21722
+ initialValue: true
21723
+ });
21724
+ if (shouldPersist) {
21725
+ const filePath = match.filePath;
21726
+ const wiRaw = readFile(filePath);
21727
+ const wiParsed = matter16(wiRaw);
21728
+ const data = wiParsed.data;
21729
+ data.implementation_evidence = verification.implementationEvidence;
21730
+ data.implementation_status = verification.implementationStatus;
21731
+ data.validation_status = verification.validationStatus;
21732
+ data.verified_at = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
21733
+ const newRaw = matter16.stringify(wiParsed.content, data);
21734
+ writeFile(filePath, newRaw);
21735
+ log2.success("Work Item frontmatter updated with verification evidence.");
21736
+ }
21737
+ if (!opts.json) outro2("Verification complete.");
21738
+ }
21739
+
21192
21740
  // src/index.ts
21193
21741
  var require2 = createRequire(import.meta.url);
21194
21742
  var { version } = require2("../package.json");
@@ -21324,8 +21872,11 @@ program.command("understand").description("Guide the CLI \u2192 LLM handoff: ref
21324
21872
  program.command("status").description("Show the current state of the Knowledge Repository").action(() => {
21325
21873
  runStatus();
21326
21874
  });
21327
- program.command("learn [artifact-id]").description("Close a work item and record what was learned").action(async (artifactId) => {
21328
- await runLearn(artifactId);
21875
+ program.command("learn [artifact-id]").description("Close a work item and record what was learned").option("--force", "Force completion despite blocking conditions").action(async (artifactId, opts) => {
21876
+ await runLearn(artifactId, opts);
21877
+ });
21878
+ program.command("verify <id>").description("Verify implementation evidence and acceptance criteria for a Work Item").option("--json", "Output JSON").option("-y, --yes", "Skip confirmation prompt").action(async (id, opts) => {
21879
+ await runVerify(id, opts);
21329
21880
  });
21330
21881
  program.command("history").description("List work items with optional filters").option("--domain <domain>", "Filter by domain").option("--type <type>", "Filter by type (feature, bugfix, hotfix, spike...)").option("--status <status>", "Filter by status (in-progress, done, cancelled)").option("--limit <n>", "Limit number of results", parseInt).action((opts) => {
21331
21882
  runHistory(opts);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kaddo/cli",
3
- "version": "3.91.0",
3
+ "version": "3.94.0",
4
4
  "description": "Knowledge Driven Development toolkit",
5
5
  "license": "MIT",
6
6
  "repository": {