cyc-stack 0.0.0-stage → 0.6.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 (112) hide show
  1. package/.agents/plugins/marketplace.json +12 -0
  2. package/.claude-plugin/marketplace.json +14 -0
  3. package/.claude-plugin/plugin.json +17 -0
  4. package/.codex-plugin/plugin.json +33 -0
  5. package/.cursor-plugin/marketplace.json +13 -0
  6. package/.cursor-plugin/plugin.json +19 -0
  7. package/INSTALL.md +108 -0
  8. package/LICENSE +21 -0
  9. package/README.md +359 -2
  10. package/bin/cyc.mjs +285 -0
  11. package/catalog/playbooks.json +20 -0
  12. package/docs/README.md +30 -0
  13. package/docs/assets/cyc-method-library.svg +39 -0
  14. package/docs/assets/cyc-overview.svg +44 -0
  15. package/docs/assets/cyc-readme-banner-mobile.svg +31 -0
  16. package/docs/assets/cyc-readme-banner.svg +39 -0
  17. package/docs/assets/cyc-workflow-diagram.svg +415 -0
  18. package/docs/code-quality.md +42 -0
  19. package/docs/context.md +40 -0
  20. package/docs/cyc-method-map.md +58 -0
  21. package/docs/cyc-workflow.md +188 -0
  22. package/docs/engineering/code-standards.md +103 -0
  23. package/docs/engineering/domain-design.md +81 -0
  24. package/docs/engineering/failure-handling.md +99 -0
  25. package/docs/impact-analysis.md +70 -0
  26. package/docs/installation.md +196 -0
  27. package/docs/onboarding-recovery.md +75 -0
  28. package/docs/principles.md +49 -0
  29. package/docs/project-tools.md +108 -0
  30. package/docs/response-standard.md +202 -0
  31. package/docs/runtime.md +247 -0
  32. package/docs/skill-contract.md +70 -0
  33. package/docs/skill-craft.md +23 -0
  34. package/docs/validation.md +39 -0
  35. package/docs/work-assessments.md +102 -0
  36. package/hooks/claude.json +10 -0
  37. package/hooks/codex.json +28 -0
  38. package/hooks/cursor.json +8 -0
  39. package/methods/cyc-build/SKILL.md +65 -0
  40. package/methods/cyc-build/references/file-writes.md +11 -0
  41. package/methods/cyc-challenge/SKILL.md +48 -0
  42. package/methods/cyc-context/SKILL.md +76 -0
  43. package/methods/cyc-context/references/evidence.md +27 -0
  44. package/methods/cyc-context/references/templates.md +54 -0
  45. package/methods/cyc-context/scripts/evidence.mjs +61 -0
  46. package/methods/cyc-correct/SKILL.md +43 -0
  47. package/methods/cyc-deliver/SKILL.md +52 -0
  48. package/methods/cyc-design/SKILL.md +50 -0
  49. package/methods/cyc-design/frontend-design/SKILL.md +43 -0
  50. package/methods/cyc-design/frontend-design/references/color.md +77 -0
  51. package/methods/cyc-design/frontend-design/references/craft-rules.md +61 -0
  52. package/methods/cyc-design/frontend-design/references/decision-sheet.md +110 -0
  53. package/methods/cyc-design/frontend-design/references/experience-review.md +58 -0
  54. package/methods/cyc-design/frontend-design/references/generic-tells.md +76 -0
  55. package/methods/cyc-design/frontend-design/references/layout-archetypes.md +188 -0
  56. package/methods/cyc-design/frontend-design/references/reference-standards.md +38 -0
  57. package/methods/cyc-design/frontend-design/references/typography.md +51 -0
  58. package/methods/cyc-design/frontend-design/references/ux-foundations.md +45 -0
  59. package/methods/cyc-design/frontend-design/references/visual-material.md +42 -0
  60. package/methods/cyc-error-ledger/SKILL.md +53 -0
  61. package/methods/cyc-error-ledger/references/entry-format.md +38 -0
  62. package/methods/cyc-explore/SKILL.md +41 -0
  63. package/methods/cyc-frame/SKILL.md +49 -0
  64. package/methods/cyc-impact/SKILL.md +64 -0
  65. package/methods/cyc-reflect/SKILL.md +48 -0
  66. package/methods/cyc-remember/SKILL.md +53 -0
  67. package/methods/cyc-scout/SKILL.md +67 -0
  68. package/methods/cyc-setup/SKILL.md +60 -0
  69. package/methods/cyc-teach/SKILL.md +40 -0
  70. package/methods/cyc-understand/SKILL.md +40 -0
  71. package/methods/cyc-understand/references/diagnose.md +53 -0
  72. package/methods/cyc-verify/SKILL.md +84 -0
  73. package/methods/cyc-verify/references/recipe.md +53 -0
  74. package/package.json +93 -4
  75. package/plugin.json +40 -0
  76. package/rules/cyc-delivery.mdc +33 -0
  77. package/scripts/baseline-worker.mjs +10 -0
  78. package/scripts/catalog.mjs +29 -0
  79. package/scripts/check-response.mjs +13 -0
  80. package/scripts/claude-project-hook.mjs +12 -0
  81. package/scripts/context-review.mjs +600 -0
  82. package/scripts/host-activation.mjs +66 -0
  83. package/scripts/install.mjs +387 -0
  84. package/scripts/onboarding.mjs +110 -0
  85. package/scripts/packet.mjs +107 -0
  86. package/scripts/project-tools.mjs +196 -0
  87. package/scripts/recovery.mjs +66 -0
  88. package/scripts/response-gate.mjs +105 -0
  89. package/scripts/response-hook.mjs +237 -0
  90. package/scripts/response-mode.mjs +12 -0
  91. package/scripts/run-gate.mjs +264 -0
  92. package/scripts/runtime.mjs +1723 -0
  93. package/scripts/source-hash-worker.mjs +5 -0
  94. package/scripts/source-snapshot.mjs +405 -0
  95. package/scripts/test-output.mjs +258 -0
  96. package/scripts/work-review.mjs +257 -0
  97. package/skills/cyc/SKILL.md +130 -0
  98. package/skills/cyc/references/playbooks/bug-fix.md +13 -0
  99. package/skills/cyc/references/playbooks/evaluate.md +13 -0
  100. package/skills/cyc/references/playbooks/experience.md +7 -0
  101. package/skills/cyc/references/playbooks/explore.md +9 -0
  102. package/skills/cyc/references/playbooks/feature.md +14 -0
  103. package/skills/cyc/references/playbooks/handoff.md +11 -0
  104. package/skills/cyc/references/playbooks/investigation.md +7 -0
  105. package/skills/cyc/references/playbooks/performance.md +7 -0
  106. package/skills/cyc/references/playbooks/plan.md +11 -0
  107. package/skills/cyc/references/playbooks/refactor.md +12 -0
  108. package/skills/cyc/references/playbooks/reflect.md +11 -0
  109. package/skills/cyc/references/playbooks/resume.md +11 -0
  110. package/skills/cyc/references/playbooks/review.md +9 -0
  111. package/skills/cyc/references/playbooks/teach.md +11 -0
  112. package/skills/cyc/references/playbooks/verify.md +7 -0
@@ -0,0 +1,40 @@
1
+ # Project context
2
+
3
+ CYC keeps useful project knowledge in the repository so a fresh chat or teammate can find the relevant reasoning without replaying the original conversation. The agent selects and interprets that knowledge; structural validation does not establish that every recorded claim is correct.
4
+
5
+ ## What belongs in context
6
+
7
+ Keep decisions and their reasons, integration constraints, failed approaches worth avoiding, and checks that protect the behavior. Reference the supporting source or observed result. Separate verified facts from proposals and assumptions. Update a current view when the implementation changes; retain historical entries as history.
8
+
9
+ Use one index at `docs/context/INDEX.md`, with path coverage and links to the relevant component notes. Read the matching notes and error-ledger entries for the task. Do not load every component or the entire run history by default.
10
+
11
+ The [Context method](../methods/cyc-context/SKILL.md) defines the component layout and retention procedure. [Work assessments](work-assessments.md) describe learning dispositions and the distinction between technical evidence and adopted decisions.
12
+
13
+ ## Inspect and maintain context
14
+
15
+ From the CYC source checkout:
16
+
17
+ ```sh
18
+ node bin/cyc.mjs investigate --path src/orders
19
+ node bin/cyc.mjs context lint
20
+ node bin/cyc.mjs context review
21
+ node bin/cyc.mjs context measure --path src/orders
22
+ ```
23
+
24
+ Replace `src/orders` with the paths relevant to the task. In an installed application, use `node .cyc/engine/bin/cyc.mjs` instead. These inspection commands do not run the project's verification recipes.
25
+
26
+ `context lint` checks document/index structure and evidence freshness where supported. A valid index can still contain an incorrect or unhelpful explanation. Recheck consequential statements against current code and dependencies.
27
+
28
+ `context review` proposes entries from recorded completed work. Review the proposed retention before using `--write`; keep changes within the authorized scope. Existing records and reference rows are handled according to the [project-tools contract](project-tools.md).
29
+
30
+ ## Interpret reading-size measurements
31
+
32
+ `context measure` reports the current index and matching linked documents, the wider context folder, and available local run records. It counts matching local documents once, including multiple links in a row, and avoids counting the index twice. Repeated links do not increase the selected size.
33
+
34
+ Character counts are Unicode code points. Estimated tokens use approximately four characters per token; no model tokenizer is run. Controller run records are not chat transcripts. A source-only machine may have history that a teammate's checkout does not contain.
35
+
36
+ These are file-size measurements. They do not establish provider billing, tokens saved, faster work or successful context reuse. Rerun the measurement for the current files rather than relying on historical figures.
37
+
38
+ ## Check that knowledge transfers
39
+
40
+ Complete one bounded task and retain the useful constraint with its evidence. Then use a fresh chat or teammate, without the original conversation, for a related change. Observe whether the relevant record is found, read, revalidated and used. Run the new task's real checks and inspect the result. Record missed or stale guidance honestly.
@@ -0,0 +1,58 @@
1
+ # How CYC's full method library relates to its workflow
2
+
3
+ CYC currently has **one orchestrator (`cyc`), 17 supporting methods and 15 playbooks**. The familiar Scout → Build → Verify → Deliver chain is the recorded route for feature, bug-fix, refactor and performance work. It is not the entire skill library or the route for every task.
4
+
5
+ Open the [complete method-selection map](assets/cyc-method-library.svg). The [connected implementation flow](cyc-workflow.md) explains forward work, recovery and knowledge handoffs. The selection map's arrows mean “choose methods relevant to this need”; its rows group responsibilities and do not establish an execution order. The runtime distribution includes compact vector diagrams; development bitmap/HTML exports stay in the source checkout.
6
+
7
+ ## Why the earlier view looked like only four skills
8
+
9
+ The diagram centered the four recorded stages and nested much of the engineering inside Scout. Its previous annotations actually named 12 methods, but omitted Setup, Remember, Explore, Correct and Reflect. That omitted setup, continuity, option comparison, feedback correction and method improvement from the picture.
10
+
11
+ The instructions also encourage this compression. The [orchestrator](../skills/cyc/SKILL.md) presents a fast Scout/build/verify/deliver flow; [Scout](../methods/cyc-scout/SKILL.md) calls Understand, Impact and Design reference material for when something is genuinely unclear and says not to read them by default.
12
+
13
+ This creates an instruction tension worth fixing: [Impact](../methods/cyc-impact/SKILL.md) calls for use before substantive changes and when shared state, storage or interfaces are involved. [Design](../methods/cyc-design/SKILL.md) calls for use when adding state, changing a data shape/interface or spanning several files. Those are concrete properties of the task, even when the agent feels confident. This source review establishes the conflicting guidance; it does not measure how often a live agent actually skips a method.
14
+
15
+ The recommended routing rule is to select a method from its task, risk and evidence triggers, with depth proportional to the change. A small task can need only a few methods; a cross-component change may need many. A stage label should not substitute for performing the applicable method. This diagram update documents the issue; it does not modify orchestration, skill instructions or controller enforcement.
16
+
17
+ ## Every supporting method has a distinct job
18
+
19
+ Examples below are illustrative, not results from an implemented export feature.
20
+
21
+ | Method | When it enters | Example and output |
22
+ | --- | --- | --- |
23
+ | [Setup](../methods/cyc-setup/SKILL.md) | Project configuration or activation is needed | Discover real CI commands, configure the chosen checks and report their initial results and hook status. |
24
+ | [Scout](../methods/cyc-scout/SKILL.md) | A bounded engineering task starts | Locate the export path, relevant history, affected consumers and checks; produce the initial plan. |
25
+ | [Remember](../methods/cyc-remember/SKILL.md) | Consequential decisions, checkpoints or resumed work | Record why a query was chosen; reconstruct the next step and check drift after interruption. |
26
+ | [Teach](../methods/cyc-teach/SKILL.md) | The engineer requests a lesson or practice | Explain pagination using their export code, with practice if appropriate. Ordinary engineering updates remain required without invoking Teach. |
27
+ | [Frame](../methods/cyc-frame/SKILL.md) | The outcome, scope or success criteria are unclear | Define “all authorized filtered records across pages” as the target, rather than merely producing a download. |
28
+ | [Understand](../methods/cyc-understand/SKILL.md) | Existing behavior or a failure needs explanation | Trace the request through pagination and the query; establish the cause from evidence. |
29
+ | [Explore](../methods/cyc-explore/SKILL.md) | An open decision needs distinct options | Compare paged fetch, streaming and queued export against the same criteria; recommend an approach and disclose prototype limits. |
30
+ | [Impact](../methods/cyc-impact/SKILL.md) | A substantive change affects data or dependent behavior | Find permission and count consumers sharing the query; name risks, supporting facts and checks. |
31
+ | [Design](../methods/cyc-design/SKILL.md) | State, interfaces or the shape of a change need design | Define the export/query boundary and error contract, compare alternatives or cite an established pattern, and plan evaluable slices. |
32
+ | [Challenge](../methods/cyc-challenge/SKILL.md) | A consequential plan, review or claim needs scrutiny | Question whether the proposed export bypasses access filtering or whether a download test proves record completeness. |
33
+ | [Build](../methods/cyc-build/SKILL.md) | The selected approach needs implementation | Repair retrieval in small tested slices and inspect the resulting diff. |
34
+ | [Verify](../methods/cyc-verify/SKILL.md) | A behavior claim needs current evidence | Check exported membership, duplicate handling, access rules and the CSV consumer; retain results and limits. |
35
+ | [Deliver](../methods/cyc-deliver/SKILL.md) | The result needs a reviewable handoff | Explain the changed query path, identify checks and disclose unmeasured scale or other remaining limitations. |
36
+ | [Context](../methods/cyc-context/SKILL.md) | Before component work and when retaining useful findings | Retrieve and revalidate history; retain verified facts with evidence and limits, identify adopted decisions only with actual acceptance, and label undecided proposals. |
37
+ | [Error Ledger](../methods/cyc-error-ledger/SKILL.md) | Before debugging and immediately after failed attempts | Record that a paging fix duplicated rows, its hypothesis and check evidence; preserve the next hypothesis and confirmed resolution. |
38
+ | [Correct](../methods/cyc-correct/SKILL.md) | User feedback or repeated misses reveal a missing criterion | “Not just the visible page” changes the target; repair the responsible work and recheck existing as well as newly clarified criteria. |
39
+ | [Reflect](../methods/cyc-reflect/SKILL.md) | Outcomes support a reusable method/check improvement | Propose a multi-page check after a repeated omission, with evidence and a counter-case. Apply changes only within authorized scope. |
40
+
41
+ Context, Remember and Reflect are different: Context preserves component knowledge; Remember preserves decisions and continuity of the task; Reflect proposes improvements to how future work is done. Error Ledger supplies failure history to both investigation and later learning. Correct addresses the current miss and can supply evidence for a later Reflect proposal.
42
+
43
+ ## Routes can use more than four recorded stages
44
+
45
+ These examples are copied from the current [playbook catalog](../catalog/playbooks.json):
46
+
47
+ | Playbook | Recorded sequence |
48
+ | --- | --- |
49
+ | Feature / bug-fix / refactor / performance | Scout → Build → Verify → Deliver |
50
+ | Plan | Frame → Understand → Impact → Design → Challenge → Deliver |
51
+ | Explore | Frame → Understand → Explore → Challenge → Deliver |
52
+ | Experience | Scout → Explore → Build → Verify → Deliver |
53
+ | Teach | Frame → Understand → Teach → Deliver |
54
+ | Resume | Remember → Understand → Deliver |
55
+ | Reflect | Remember → Reflect → Deliver |
56
+ | Evaluate | Frame → Understand → Explore → Verify → Reflect → Deliver |
57
+
58
+ The catalog defines recorded sequences. The active host agent reads and performs the methods; the controller does not automatically invoke them. Some supporting methods are used within stages or across the task rather than appearing as catalog stage names. The present diagram therefore establishes where skills fit, not proof of their invocation or substantive quality in a live run.
@@ -0,0 +1,188 @@
1
+ # CYC engineering workflow: decisions, evidence, and recovery
2
+
3
+ Open the [connected workflow diagram](assets/cyc-workflow-diagram.svg) for the responsibilities, recovery arrows, project knowledge, and separate delivery outcomes. The sections below explain the steps. A [quick overview](assets/cyc-overview.svg) is also available. The runtime distribution uses compact vector diagrams; bitmap and interactive HTML exports stay in the source checkout.
4
+
5
+ Skill labels inside the numbered steps and recovery cards show where existing CYC methods help. Open a numbered step for its selection trigger, a worked CSV-export example, direct method links and the evidence it passes forward. These placements describe agent-selected methods, not automatic dispatch or additional controller stages. Ordinary engineering explanation belongs throughout the work; Teach adds a lesson only when requested.
6
+
7
+ The common implementation route does not show the entire library. See the [full map of all 17 methods](assets/cyc-method-library.svg) and [method roles, examples and routing limitations](cyc-method-map.md), including Setup, Remember, Explore, Correct and Reflect. CYC has 15 playbooks; planning, exploration, teaching, resumption and evaluation use other recorded sequences.
8
+
9
+ CYC moves work forward when the next stage has usable evidence. A failure sends work back to the earliest affected decision, so the agent can repair the cause and regenerate the conclusions that depended on it. The engineer should be able to inspect both the change and the reasoning for taking that route.
10
+
11
+ This document describes the current local implementation and its method instructions for the common feature, bug-fix, and refactor routes. The controller records **Scout → Build → Verify → Deliver**. The twelve responsibilities below occur inside those stages; they are not twelve machine-enforced states. Other routes use the [playbook catalog](../catalog/playbooks.json).
12
+
13
+ **Read the boundaries literally:** the agent investigates, explains, chooses checks, and judges meaning. The controller validates recorded fields, stage identity, covered file state, configured command results, and budgets. A required evidence field does not prove the evidence is true.
14
+
15
+ ## 1. The engineering path
16
+
17
+ Each box describes work and the evidence it produces. The separate recovery map below explains backward movement; those returns are deliberately not repeated across this entire diagram.
18
+
19
+ ```mermaid
20
+ flowchart TB
21
+ subgraph SC["SCOUT — establish what must change and what must remain true"]
22
+ S1["1. Define observable success<br/>Goal, constraints, acceptance criteria"]
23
+ S2["2. Select route and risk treatment<br/>Choose the playbook and applicable verification"]
24
+ S3["3. Retrieve matched project history<br/>Component decisions, known failures, existing capabilities"]
25
+ S4["4. Revalidate that history<br/>Compare claims with current code and working changes"]
26
+ S5["5. Trace impact and choose a design<br/>Writers, readers, contracts, checks, trade-offs"]
27
+ S6["6. Explain the causal path and settle key decisions<br/>Current behavior, proposed mechanism, preserved behavior"]
28
+ S7["7. Plan slices and challenge consequential assumptions<br/>Each slice has an observable outcome and check"]
29
+ S1 --> S2 --> S3 --> S4 --> S5 --> S6 --> S7
30
+ end
31
+ SG{"Scout assessment usable?<br/>Alignment settled; consumers and checks named"}
32
+ S7 --> SG
33
+ SG -->|"Yes: record Scout"| B8
34
+ SG -->|"Missing evidence or consequential answer"| HOLD["Investigate the specific gap or record a blocker<br/>No passing handoff on an unresolved decision"]
35
+
36
+ subgraph BU["BUILD — implement the chosen behavior with focused feedback"]
37
+ B8["8. Implement a tested slice<br/>Reproduce the defect or pin required behavior; inspect the diff"]
38
+ BG{"Slice preserves its required behavior?"}
39
+ B9["9. Retain useful project knowledge<br/>Update docs and index when useful; retain evidence and limits"]
40
+ B8 --> BG
41
+ BG -->|"Yes: finish planned slices"| B9
42
+ end
43
+ BG -->|"No: use recovery map"| REC["Diagnose evidence and route the repair"]
44
+ B9 -->|"Record Build when its work is usable"| V10
45
+
46
+ subgraph VE["VERIFY — evaluate the actual candidate against the promised outcome"]
47
+ V10["10. Prove tests and verify behavior<br/>Original-code proof where required; journey and configured checks on stable files"]
48
+ VG{"Required checks support every criterion?<br/>Configured commands pass; source remains stable"}
49
+ V11["11. Review the meaning of the change<br/>Intent, consumers, conventions; resolve or justify findings"]
50
+ RG{"Consumer evidence complete?<br/>No unresolved review findings"}
51
+ V10 --> VG
52
+ VG -->|"Yes"| V11 --> RG
53
+ end
54
+ VG -->|"No"| REC
55
+ RG -->|"No"| REC
56
+ RG -->|"Yes: record Verify against this file state"| D12
57
+
58
+ subgraph DE["DELIVER — hand over inspectable evidence"]
59
+ D12["12. Account for outcomes and retained knowledge<br/>Criteria, limits, learning disposition, ledger, shared review"]
60
+ DC["Record Deliver and request run complete<br/>Controller rechecks completion conditions and current evidence"]
61
+ D12 --> DC
62
+ end
63
+ DC --> OUT["Ready handoff when completion and delivery checks pass<br/>Team review and publication follow project authorization"]
64
+ ```
65
+
66
+ Steps 8 and 9 can interleave: record attempts when they happen, not after reconstructing the whole run. Step 9 can finish during Verify preparation, but covered documentation edits must precede the final executable checks. Missing evidence is repaired; an unavailable prerequisite is disclosed as a blocker.
67
+
68
+ ### Scout: why these seven responsibilities precede implementation
69
+
70
+ **1. Define observable success.** Translate the request into outcomes that a reviewer could distinguish from a plausible-looking implementation. For an export, “a CSV downloads” is weaker than “all matching records are exported and existing access restrictions still apply.” Preserve constraints and exclusions. Explicit criteria give verification a stable target; the controller requires each configured criterion ID to survive handoffs. The agent still owns whether those criteria describe the right product behavior. Explain the difference between a working control and the promised outcome.
71
+
72
+ **2. Select the route and risk treatment.** Choose a playbook before starting the tracked run. Investigation, teaching, verification, and implementation have different work requirements. Identify consequential permissions, stored-data changes, public interfaces, or other risk in this task. Configure meaningful project checks before the run; configuration is captured and protected during it. Explain why the selected checks and review depth match the changed behavior. A high-risk plan gets a focused Challenge pass; ordinary work proceeds without that extra pass.
73
+
74
+ **3. Retrieve matched history.** Read relevant component context, the capability index if present, and the selected error ledger. Look for the reason an interface behaves as it does, the existing implementation to reuse, and approaches already shown to fail. Produce references to the matched material or an honest account of no relevant history. This changes the starting hypothesis and can avoid repeating investigation; it does not establish a measured token or dollar saving. Explain which prior decision affects today's change.
75
+
76
+ **4. Revalidate history against the working project.** Compare recorded claims with the actual covered components, relevant revisions, and uncommitted changes. A note may describe an old design even when the note itself is readable. Confirm useful claims and label contradictions or uncertainty. The assessment records freshness reasoning and fingerprints referenced files; the agent must actually perform the comparison. Explain any outdated assumption before using a new one.
77
+
78
+ **5. Trace impact and choose the design.** Follow the affected input through state, services, interfaces, persistence, and readers that exist in the project. Name the consumers whose behavior must remain consistent, then select reuse, extension, repair, or new construction with a reason. Pair each consumer with a behavior check. An affected area is a verification concern, not permission to broaden the feature. Explain where the change belongs and why an alternative would create a consequential cost or risk.
79
+
80
+ **6. Explain the causal path and resolve decisions.** Connect observed behavior to the mechanism producing it, then explain what will change and what must remain true. Ask only when an unresolved answer changes the solution. A settled request can be recorded as clear; confirmed alignment requires actual confirmation. The controller rejects a passing Scout assessment marked needs-input. Supplying an explanation does not establish comprehension, and silence does not establish approval.
81
+
82
+ **7. Plan slices that can be evaluated.** Sequence implementation around observable behavior, not a list of arbitrary files. Identify how the first slice can fail, how later slices depend on it, and what broader checks will cover the result. For high-risk work, challenge consequential assumptions and revise the plan if evidence defeats them. This is method guidance inside Scout; the runtime does not independently judge the plan or enforce a separate Challenge state for the fast routes. Explain the dependency that determines the sequence.
83
+
84
+ ### Build: keep changes and explanations connected
85
+
86
+ **8. Implement a tested slice.** For a bug, reproduce the defect before claiming a repair; for a refactor, preserve a behavior check; for a feature, exercise the intended new outcome. Confirm that a new regression check can detect the original defect, then implement the change and inspect its effect on named consumers. Existing checks or a justified skip can cover work with no new testable behavior. Focused failures trigger diagnosis, not blind repetition. Record failed attempts in the selected ledger and explain the affected state or interface, why the repair belongs there, and what the focused result establishes. These actions are method responsibilities; CYC cannot see an unreported attempt.
87
+
88
+ **9. Retain useful project knowledge.** For affected components or areas with reusable knowledge, create or update `docs/context/<area>.md` and its path-matched row in `docs/context/INDEX.md`. Name the document for the component or area, not the task or conversation. Append a dated entry preserving verified facts, actual adopted decisions, rejected alternatives, dead ends with evidence, non-obvious dependencies or gotchas, verification references, and open issues. Record covered paths and the reviewed revision; for a dirty checkout, include the base commit plus covered-file evidence. Explicitly supersede outdated entries while retaining their history.
89
+
90
+ This step produces inspectable component knowledge, not just a delivery summary:
91
+
92
+ | Output | What it preserves | How subsequent work uses it |
93
+ | --- | --- | --- |
94
+ | `docs/context/<area>.md` | Why the component behaves this way, what failed, dependencies, checks and known limits | Step 3 retrieves the matching document; step 4 checks its freshness against the current code |
95
+ | `docs/context/INDEX.md` | Component/area, covered paths, document location, reviewed revision and a short summary | Locates relevant history from the files being changed |
96
+ | Selected error ledger | Failed attempts, observed results and confirmed causes | Supplies failure evidence that component entries can reference without duplicating the entire log |
97
+
98
+ For example, an export-component entry could preserve why exports query all authorized matching records rather than the current UI page, the failed page-state approach and its evidence, and the regression check covering pagination. This is an illustrative entry, not a claim about this project's components.
99
+
100
+ Finish authorized durable context/index and ledger edits before final verification because those files belong to the candidate being checked. Retain useful verified technical facts with their evidence and limits. Keep unverified hypotheses and undecided proposals explicitly pending; mark a decision adopted only with actual acceptance. Do not create filler documents when there is no reusable finding. Explain the retained reasoning and how a future engineer would locate and revalidate it. Deliver records this disposition; it is not a second opportunity to mutate verified source. The existing component-context method and templates define this responsibility; the diagram does not add a new runtime state or claim the controller proves documentation quality.
101
+
102
+ ### Verify: require both executed behavior and explained judgment
103
+
104
+ **10. Prove tests and exercise the promised behavior.** The controller runs required original-code proof when it is missing or outdated: changed tests for feature and bug-fix runs must fail on the original code; refactor tests must pass there. An explicit exemption records its actual reason and limits. Run relevant journey or recipe checks and every configured command. Map results to acceptance criteria and identified consumers; include rejected cases where they protect the requirement. The controller retains command arguments, exit status, output, and a covered source fingerprint. It rejects a passing receipt when commands fail or covered source changes during execution. It does not know whether a zero-exit command meaningfully tested the product. Explain which path each consequential check exercises and what remains outside its coverage.
105
+
106
+ **11. Review whether the implementation means the right thing.** Review the current diff for intent, affected consumers, and project conventions. Tests can pass while encoding an incomplete assumption, missing a consumer, or accepting the wrong behavior. Record findings as resolved or dismissed with evidence; open findings prevent a passing assessment. Every consumer named in Scout needs passing evidence; newly discovered consumers also belong in the review. Label self-review and peer review accurately. Explain the consequence of a finding and why its resolution addresses that consequence. Required fields make the judgment inspectable, not independently true.
107
+
108
+ ### Deliver: expose the basis for acceptance
109
+
110
+ **12. Account for the result and make it maintainable.** Record every criterion's outcome, material limits, retained-learning disposition, and error-history evidence. Bug-fix runs and runs with recorded failures require the selected ledger. Reuse the generated review, which refreshes throughout recorded mutations. A passing Deliver handoff needs current executable evidence where required and a current semantic assessment; run complete rechecks final conditions and artifact hashes. The developer receives the before/after mechanism, important trade-offs, checks, and locations needed for maintenance. Project review and publication require the applicable authorization.
111
+
112
+ The host delivery hook, when active, separately checks response readiness and relevant session runs. A ready handoff requires completed runs; a recorded blocked or exhausted outcome permits an honest blocked handoff. An actively running unfinished run cannot be concealed by a polished final answer. Codex and Claude provide the response through their native Stop event; Cursor requires the exact response in its packet. Finish-generated records can therefore omit a copied response in Codex and Claude. Formatting rules follow the project's settings. The hook does not establish that the engineer understands the work.
113
+
114
+ These are responsibilities, not separate required tool calls. On the ordinary successful path, `run start` can record Scout and `run finish` can combine Build recording, original-code proof, configured verification, Verify and Deliver records, and completion. The assistant performs the engineering and interprets findings; the controller validates records and runs project commands. Generated run evidence is local by default. Teams share useful context and review evidence through their own authorized project workflow.
115
+
116
+ ## 2. Why the process loops, and why the return destination matters
117
+
118
+ A verification failure is new evidence about the implementation, the design, the requirements, or the check itself. Those are different problems. Repeating implementation without distinguishing them can preserve the original error and accumulate patches.
119
+
120
+ ```mermaid
121
+ flowchart TB
122
+ F["Focused check, full verification, or review reveals a problem"] --> OBS["Preserve the observed result<br/>Confirm the check used the intended build, data, and behavior"]
123
+ OBS --> WHY{"What does the evidence invalidate?"}
124
+ WHY -->|"Implementation violates a still-valid design"| B["Repair the code in Build<br/>Keep the requirement; exercise the failing case"]
125
+ WHY -->|"Missed consumer, stale context, or false design premise"| S["Revisit Scout impact and design<br/>Update the affected paths, plan, and consumer checks"]
126
+ WHY -->|"Candidate changed after a passing review"| V["Return to Verify<br/>Rerun checks and review the changed file state"]
127
+ WHY -->|"Check observes the wrong thing"| T["Correct the observation with a stated reason<br/>Preserve failed evidence and the intended requirement"]
128
+ WHY -->|"Missing access or decision; exhausted budget"| STOP["Record the blocked or exhausted outcome<br/>Keep findings; state what prevents completion"]
129
+ B --> RE["Re-establish affected evidence before delivery"]
130
+ S --> RE
131
+ V --> RE
132
+ T --> RE
133
+ ```
134
+
135
+ The diagram shows the **engineering destination**, not a mandatory restart for every failure. A defect discovered before a passing Verify handoff can be repaired within the active stage. When returning to a recorded earlier stage is necessary, run retry rewinds there and invalidates dependent later handoffs and executable verification. Changes after a passing Verify handoff require returning to Verify, fresh checks, and a current semantic review. Fast routes map detailed impact/design destinations back to Scout.
136
+
137
+ | Evidence that changes the route | Why the return is necessary | What must be established again |
138
+ | --- | --- | --- |
139
+ | A correctly specified export omits the last page because its loop stops early | The design still works; a local implementation violates it | The failing pagination case, affected consumers, current configured checks and review |
140
+ | Export reuses a UI-only filter while server access rules differ | The design relied on the wrong source of truth; another patch to pagination cannot repair that premise | Relevant context and impact, design rationale, access consumers, implementation and verification |
141
+ | A passing review is followed by another covered source edit | The old result describes different bytes | Executed checks and semantic review for the new candidate |
142
+ | A check hits an old build or asserts the wrong requirement | The observation cannot support the intended conclusion | Correct target or justified assertion and a fresh result; do not simply lower the threshold |
143
+ | A required service or decision is unavailable | More code cannot supply the missing prerequisite | An honest blocker and the smallest needed input; verification after work resumes |
144
+
145
+ When a legitimate correction requires changing protected verification configuration or run criteria, explain it and start a new authorized run while retaining the old outcome. Do not weaken the current run to pass.
146
+
147
+ Controller guard checks at record, verification, retry, resume, and completion detect protected or out-of-scope file changes. A detected violation sets the run to **halted** and preserves the files for review; it does not automatically roll them back. Halted and exhausted runs are terminal. A blocked run may resume after its prerequisite is resolved, subject to guard checks and the remaining budget. A halted run requires resolving scope or authorization before starting a new run. This is a guard at controller operations, not continuous filesystem monitoring.
148
+
149
+ Recovery uses a shared configurable failure budget across stages: defaults are three recorded failures and two repeated unchanged failure signatures. A stage return does not reset the allowance. The no-progress signature is a heuristic. Focused agent activity between controller calls is not continuously monitored, and the controller cannot count concealed attempts. Instructions require recording those attempts; the bounded runtime checks occur at controller operations.
150
+
151
+ ### A worked example: why going back to Scout is sometimes essential
152
+
153
+ This is illustrative, not a report of a CYC repository defect.
154
+
155
+ The request is to export every order matching the dashboard filters while preserving access restrictions. The initial plan assumes the browser holds the complete filtered result. A multiple-page test shows that only the visible page reaches the export.
156
+
157
+ If the server already provides the correct complete query and the export loop stops early, the repair belongs in implementation. If the browser only ever receives one page and applies different filtering from the server, the assumption behind the design is false. Return to Scout, inspect the authoritative query and access boundary, revise the impact map, and choose the correct data path before rebuilding.
158
+
159
+ The explanation to the engineer should identify that distinction: “The browser only has one page, so formatting its rows cannot produce the requested export. We need the server's filtered query, with the same access restriction, and checks for both multiple pages and denied access.” The ledger retains the failed browser-only attempt and its evidence so the next task does not repeat it.
160
+
161
+ ## 3. What an engineering team can inspect before trusting a result
162
+
163
+ Trust should be attached to a particular claim and supporting evidence. CYC makes that relationship inspectable and rejects several unsupported completion paths.
164
+
165
+ | Claim presented to the team | Current mechanism and inspectable record | Boundary of that assurance |
166
+ | --- | --- | --- |
167
+ | The delivered change addresses the agreed criteria | Every handoff preserves criterion IDs; passing Verify and Deliver require all criterion results passed with evidence | The agent and engineer must choose meaningful criteria and judge the supplied evidence |
168
+ | The result still covers the candidate being handed over | Covered source fingerprints, referenced artifact hashes, verification receipts, and a semantic-review source snapshot are rechecked | Coverage has documented exclusions; external services and omitted dependencies are not frozen by a file hash |
169
+ | Green commands cannot replace reviewing the change | Required intent/consumer/convention assessment; open findings and missing Scout consumer checks reject a passing handoff | Review and consumer evidence are agent-reported; this is not automatic dependency discovery or independent approval |
170
+ | A failed attempt cannot be silently turned into completed work through ordinary controller operations | Shared failure budget, retry history, invalidated dependent handoffs, stage/attempt identity, terminal outcomes | Local records are editable; unreported agent actions are invisible to the controller |
171
+ | The reasoning remains available after the conversation | Matched context references, selected error ledger, pending/recorded learning disposition, generated review | The agent must write accurate history, and acceptance must be real |
172
+ | The engineer can follow and maintain the change | Stage-specific explanation responsibilities and qualitative delivery review | This is instruction-level behavior; there is no automated comprehension measurement |
173
+
174
+ The useful question for a reviewer is: **“What evidence supports this claim, does it still describe these files, and what has not been established?”** A diagram, an agent's confidence, or a successful exit code alone cannot answer that.
175
+
176
+ For the implementation behind these claims, inspect [assessment validation](../scripts/work-review.mjs), [runtime transitions and source checks](../scripts/runtime.mjs), [source coverage](../scripts/source-snapshot.mjs), and [session run delivery rules](../scripts/run-gate.mjs). In a CYC source checkout, relevant regression checks are `test/work-review.test.mjs` and `test/runtime-adversarial.test.mjs`; repository tests are not included in the installed `.cyc/engine`. Test existence alone is not a test result.
177
+
178
+ ## Regenerating the diagram
179
+
180
+ In the source checkout, run `npm install` (or `npm ci` with the lockfile), then `npm run build:workflow`. The generator uses the development-only `sharp` package to render the compact overview, detailed workflow and method-library PNGs before refreshing the exports. It writes the SVGs, PNG previews and embedded HTML diagram together, and synchronizes all twelve explanation titles. A missing renderer or missing HTML marker/title fails before updating the exports. There is no separate manual PNG step. Font availability may affect rendering across machines; repeated builds on the same machine should produce identical files. CYC's installed runtime ships the compact SVGs and does not need this authoring dependency.
181
+
182
+ ## Supporting references and earlier overview
183
+
184
+ - [Runtime contract and configurable limits](runtime.md)
185
+ - [Assessment fields and learning lifecycle](work-assessments.md)
186
+ - [Impact investigation](impact-analysis.md)
187
+ - [Engineering explanation standard](response-standard.md#engineering-understanding-throughout-the-work)
188
+ - [Orchestrator](../skills/cyc/SKILL.md), [Build](../methods/cyc-build/SKILL.md), and [Verify](../methods/cyc-verify/SKILL.md)
@@ -0,0 +1,103 @@
1
+ # Code standards that improve the delivered change
2
+
3
+ Use these standards while implementing or reviewing code. Read the active project's instructions and applicable `code-standards.md`, design system, contribution guide and tool configuration first. Keep its established conventions unless the task calls for changing them. This guide supplies portable engineering criteria; it does not impose EventConvo's labels, colors, form library or React architecture on other projects.
4
+
5
+ Apply the relevant rules to the changed code and affected behavior. Fix related findings within scope; record unrelated cleanup separately. Do not turn an ordinary feature into a repository-wide standards migration.
6
+
7
+ ## Comments must carry information the code cannot
8
+
9
+ For each added or modified comment, ask: **what important fact would a maintainer lose if this comment disappeared?** Keep a comment that explains a constraint, rationale, non-obvious invariant, external contract, deliberate trade-off or supported workaround. If it only translates the next statement into English, remove it. If the code's names or structure cause the confusion, improve those first.
10
+
11
+ | Remove or improve | Keep when accurate and needed |
12
+ | --- | --- |
13
+ | `// Get the user` above `getUser()` | Why a lookup must use the historical owner rather than the current owner |
14
+ | `// Phase 3`, `// New v2 logic`, or a heading for a tiny obvious block | A compatibility constraint and the supported consumer that requires it |
15
+ | `// Intentional` inside an otherwise unexplained empty catch | The allowed loss, why the main operation may succeed and where failure is reported or deliberately discarded |
16
+ | A commented-out implementation or chat transcript | A concise explanation of a surprising decision, beside the affected code |
17
+ | A stale `TODO` or an unbounded promise to revisit | A concrete deferred limitation, tracked where project conventions require, without hiding unfinished acceptance criteria |
18
+
19
+ For example, `// Sort events` repeats the operation. `// Tie-break by ID so equal timestamps do not reorder across pages.` explains a constraint that a later simplification could violate. Keep the explanation only if the implementation and pagination contract actually support it.
20
+
21
+ Preserve license notices, required attribution, compiler/tool directives and meaningful public API documentation. Generated files follow their generator's conventions. Do not remove required text or useful explanations merely to achieve a comment count.
22
+
23
+ Public documentation should explain the caller's contract: valid input, result, meaningful effects, rejection and limitations that cannot be inferred from the signature. Do not require boilerplate documentation for every private function. A useful rationale can also belong in a named test, but a test elsewhere does not make a necessary local explanation redundant.
24
+
25
+ ## Make structure express responsibility
26
+
27
+ Choose names that reveal the domain, units and intent. Separate facts that can vary independently; derive redundant state where practical. Keep related behavior together and make the owner of an important rule discoverable. Follow the [architecture questions](../code-quality.md#choose-a-structure-that-protects-the-contract) when ownership or boundaries change.
28
+
29
+ Treat deep nesting, long files, many props and repeated syntax as investigation signals. They do not prove a defect or dictate a repair. Flatten control flow when that clarifies the same outcomes; preserve distinct unauthorized, unavailable, loading and failed states. Extract a function when it names a decision, hides complexity or supports real reuse, not just to move lines out of sight.
30
+
31
+ For component data flow, first inspect state ownership and composition. Passing a few explicit props can be clearer than introducing shared state. Context or a store is appropriate for a real shared lifetime or access need, not because a prop crossed a third layer. A custom hook can encapsulate access to shared state; two independent local-state hooks do not become shared merely because they have the same name. Group props only when they form a meaningful concept.
32
+
33
+ Remove unused imports, dead branches, debug residue and abandoned code introduced or made obsolete by the change. Before removing a wrapper or empty element, inspect layout, semantics, measurement, ref and integration use. A container that owns a layout or focus boundary is not useless because it has no text.
34
+
35
+ ## Types must describe facts, not wish them into existence
36
+
37
+ Derive types from the authoritative schema or existing domain model. Validate external and legacy data at the relevant boundary and preserve the established rejection path. Narrow types through actual checks. A type assertion, non-null assertion or relocation of a cast does not validate data.
38
+
39
+ For example, replacing three `payload as Profile` assertions with `const profile = payload as Profile` may reduce repetition while preserving the same unsupported assumption. Use the project's existing parser or prove the shape before treating an untrusted payload as a profile. Known trusted framework boundaries and generated adapters can justify a narrow assertion; keep the reason inspectable.
40
+
41
+ Do not add broad `any`, blanket type ignores, lint disables, optional chaining or fallback defaults just to make a diagnostic disappear. Fix the source of the uncertainty. A justified suppression should cover the smallest useful scope, explain the actual tool limitation and retain any project-required tracking or removal condition. Handle legitimate optional values and compatibility data explicitly; do not replace them with invented values.
42
+
43
+ ## Failure handling must preserve the outcome
44
+
45
+ A catch is justified by recovery, translation, cleanup or reporting that the caller needs. Remove a catch that only rethrows the same error and owns no other behavior. Preserve meaningful cleanup, rollback, diagnostic context and error causes. Do not remove a useful boundary merely because it eventually rethrows.
46
+
47
+ An empty catch needs an actual product contract permitting the lost effect; adding a comment cannot create that permission. An optional analytics event may be disposable. A failed save, access check or required audit record is not optional merely because the UI should keep moving. Avoid duplicate reporting at every layer and do not expose secrets or raw internal errors.
48
+
49
+ Do not turn a failed read into a plausible empty list, claim a successful save before it commits, or retry effects with unknown outcomes. For I/O, partial completion or retries, use [failure handling](failure-handling.md); for shared business rules, use [domain design](domain-design.md). Match the established error representation rather than inventing a taxonomy for every function.
50
+
51
+ ## Project conventions are explicit local choices
52
+
53
+ Reuse the project's established localization, styling, form, logging, validation and test approaches when they fit. A centralized labels file, a specific form library, token-only colors or solid buttons can be legitimate **project requirements**. They are not universal indicators of quality. Do not introduce these systems or ban an existing library solely because a reference project uses something different.
54
+
55
+ Use configured import ordering and formatting. Do not manually enforce a second style beside the project's formatter. Preserve established design tokens and reuse fitting input components; make a new reusable component when it owns a useful behavior or serves real consistency, rather than wrapping every one-off element.
56
+
57
+ Interactive work must expose the relevant loading, empty, validation, failure and success states truthfully. Use semantic controls and accessible names; preserve keyboard behavior, focus, applicable contrast and reflow requirements. Give informative images meaningful alternatives and decorative images empty alternative text. For visual design or a new page, follow the existing [frontend experience review](../../methods/cyc-design/frontend-design/references/experience-review.md).
58
+
59
+ ## Review the actual diff before delivery
60
+
61
+ Read the complete final diff, including deleted behavior and changed tests. Trace consequential values through input, ownership, changes, output and failure. Ask whether each new helper, comment, dependency and fallback earns its place. Review tests against the requested behavior; do not accept implementation-shaped expectations that merely confirm the chosen code.
62
+
63
+ Resolve each material finding with a specific repair and recheck, or a concrete reason it is not a defect. Do not manufacture findings or demand a minimum number of deletions. A checklist saying "reviewed" does not establish that the work is good. Identify the location and actual consequence when reporting an issue.
64
+
65
+ Review should catch both sides of a rule: remove the narration comment but keep the concurrency explanation; reject a silent save failure but allow documented optional telemetry loss; remove a forwarding wrapper but retain an adapter with a real contract. A comment keyword or file-size threshold cannot decide those cases reliably.
66
+
67
+ ## Make standards observable without pretending judgment is automated
68
+
69
+ Use three complementary layers:
70
+
71
+ ```text
72
+ Applicable instructions → working change → executable checks
73
+ ↓
74
+ semantic diff review
75
+ ↓
76
+ repair + fresh evidence
77
+ ```
78
+
79
+ | Concern | Suitable enforcement | Remaining judgment |
80
+ | --- | --- | --- |
81
+ | Formatting, configured import order, unused imports | Existing formatter and linter | Whether a dependency or abstraction is worthwhile |
82
+ | Invalid types and prohibited suppressions | Type checking and configured static rules | Whether a cast is justified and the boundary validates the right contract |
83
+ | Empty catches and trivial rethrows | Configured lint rules can flag candidates | Whether recovery or tolerated loss is legitimate |
84
+ | Redundant comments, fake abstractions, unclear ownership | Review the changed code and its callers | Whether information or responsibility is actually lost |
85
+ | Required behavior and failure cases | Observable tests and appropriate integration checks | Whether the checks cover the requested outcome |
86
+ | Visual quality and interaction | Rendered-page review plus applicable automated checks | Composition, clarity and completeness of the user's journey |
87
+
88
+ A host hook can supply the current standards or run configured checks when its supported event fires. That can reduce missed instructions and refuse observed machine-check failures. Loading a file, asking for an acknowledgment or finding a comment phrase does not prove that a model understood or obeyed it. Actual event support, trust, scope, invocation and refusal must be validated in the target host before claiming enforcement.
89
+
90
+ When adopting the standard in another project, identify the files, real commands and generated-file exclusions it uses. Integrate justified deterministic rules with the existing tooling and CI; do not install a generic bundle or modify host configuration as an incidental cleanup. Choose blocking checks deliberately, run them, and exercise both a legitimate case and a violation that must be refused. Keep baseline failures visible. Hooks and CI should check the same accepted contracts where feasible; a local model-authored review remains separate evidence.
91
+
92
+ In CYC, read the project's applicable standards during Scout/Build and carry them into Verify's semantic review. Existing configured executable checks and controller evidence retain their current meanings; this document adds no hook, parser, stage or machine-enforced comment-quality check. Record only checks actually run on the final candidate, and disclose material unverified behavior.
93
+
94
+ ## Changes from the supplied older standard
95
+
96
+ The supplied EventConvo example was inspected as evidence on 2026-11-02. Its specific labels path, design-system file, colors and form stack remain local project choices. The improvements here address these concrete weaknesses:
97
+
98
+ - **Comment count → information value.** Keep necessary rationale, notices and contracts while removing narration.
99
+ - **An annotated empty catch → an allowed failure contract.** A word such as "intentional" cannot justify hiding a failed operation.
100
+ - **Fewer assertions → supported types.** Moving an unsafe assertion does not make external data safe.
101
+ - **Depth/prop thresholds → visible responsibility.** Preserve distinct outcomes and avoid unnecessary shared state.
102
+ - **Universal frontend prescriptions → explicit project bindings.** Reuse local conventions without copying another product's stack or visual identity.
103
+ - **A forced read → checks plus accountable review.** Machine results and agent judgment are separate; neither guarantees defect-free output.
@@ -0,0 +1,81 @@
1
+ # Domain design in everyday changes
2
+
3
+ Read this when adding or changing a business rule, state transition, or public operation, or when several callers must agree on the same decision. Use the existing project model and conventions. The goal is a rule a maintainer can locate and change coherently; a domain framework, class hierarchy, or new service layer is not required.
4
+
5
+ ## Choose the owner before the shape
6
+
7
+ Start with one real operation and state its invariant: what must stay true before and after it? Find the authoritative data, every permitted writer, and readers whose behavior depends on that invariant. Choose the smallest existing operation that can own the decision.
8
+
9
+ | Trigger | Decision while building | Question during review |
10
+ | --- | --- | --- |
11
+ | Booking, an admin action, and a display repeat an availability condition | Derive the shared decision once; let each caller translate the result for its purpose. | Would adding one legitimate unavailable state require editing several rule implementations? |
12
+ | Flags can describe contradictory lifecycle states | Use the project's tagged state, enum, or transition operation; validate external/legacy representations at their boundary. | Can a valid caller create an impossible combination or skip a required transition? |
13
+ | Callers perform several internal mutations to complete one operation | Put the invariant-preserving operation at the owner; keep storage and transport adaptation outside its pure decision when practical. | Could a caller stop midway and expose inconsistent state? |
14
+ | A handler mixes domain choices with database or network calls | Extract the consequential calculation or decision into a plain function when that makes the rule reusable or inspectable. | Does the extraction own a meaningful decision, or merely forward arguments? |
15
+
16
+ Distinguish a shared business rule from similar syntax. Two roles may intentionally have different eligibility rules. Name that difference rather than merging their behavior to reduce line count.
17
+
18
+ ## Bad example repeated eligibility policy
19
+
20
+ Contract for this example: a closed window rejects bookings even with spare capacity; an open full window also rejects them. Input is already validated: `capacity` and `reserved` are nonnegative integers, with `reserved <= capacity`.
21
+
22
+ ```js
23
+ function book(window) {
24
+ if (window.closed || window.reserved >= window.capacity) {
25
+ return { ok: false };
26
+ }
27
+ window.reserved += 1;
28
+ return { ok: true };
29
+ }
30
+
31
+ function portalStatus(window) {
32
+ if (window.closed) return 'closed';
33
+ return window.reserved >= window.capacity ? 'full' : 'available';
34
+ }
35
+ ```
36
+
37
+ The current behavior can be correct. The maintainability problem is concrete: adding a maintenance hold requires updating the booking decision and the display decision together. Moving only the display expression into a helper leaves that coupling intact.
38
+
39
+ ## Good example one decision with distinct consumers
40
+
41
+ ```js
42
+ function availability(window) {
43
+ const remaining = window.capacity - window.reserved;
44
+ if (window.closed) return { kind: 'closed', remaining };
45
+ if (remaining === 0) return { kind: 'full', remaining };
46
+ return { kind: 'available', remaining };
47
+ }
48
+
49
+ function book(window) {
50
+ const state = availability(window);
51
+ if (state.kind !== 'available') {
52
+ return { ok: false };
53
+ }
54
+ window.reserved += 1;
55
+ return { ok: true };
56
+ }
57
+
58
+ function portalStatus(window) {
59
+ return availability(window).kind;
60
+ }
61
+ ```
62
+
63
+ The helper owns closure/capacity precedence; booking owns its mutation; the portal owns presentation. `remaining` is derived from authoritative counts, not a synchronized field to save separately. Both public functions preserve their previous return shapes. Adapt the internal decision to existing callers instead of changing their contract just to introduce a helper.
64
+
65
+ This example assumes one in-memory writer. It does **not** prevent two processes from booking the same last place. Where concurrent writes are legitimate, enforce the invariant in the existing transaction, conditional update, lock, or other storage consistency mechanism. A pure predicate cannot make a check followed by a write atomic. Do not silently clamp corrupt counts to hide a broken invariant.
66
+
67
+ For lifecycle data, apply the same ownership reasoning: a single `pending | running | succeeded | failed` state is useful when those states are mutually exclusive. Include the data each state needs and permit transitions through the existing owner. Do not collapse independently meaningful facts, such as `isArchived` and `isPaid`, into one lifecycle merely because both are booleans.
68
+
69
+ ## Legitimate exceptions
70
+
71
+ - A one-off local rule with one caller can stay inline. A new layer needs a meaningful decision, boundary, or reuse benefit.
72
+ - Read models, caches, and remote projections may deliberately duplicate derived state. Preserve their freshness, invalidation, and reconciliation contract; a display projection must not authorize a write using stale data.
73
+ - Different consumers may legitimately apply different policies. Reuse the common facts and explicitly name the varying policy; do not force one predicate onto distinct requirements.
74
+ - Existing callers or stored records can require compatibility adapters and old representations during migration. Translate at a clear boundary rather than deleting a supported path to obtain a cleaner model.
75
+ - A small application may keep policy and orchestration in one file. Separation of responsibilities does not require separation into files or services.
76
+
77
+ ## Apply during Build and review
78
+
79
+ While building, name the invariant and its owner in the existing plan or explanation, then trace the chosen operation through writers and readers. Inspect both the successful transition and a rejected transition for partial mutation. Keep the project's established types, errors, and return conventions.
80
+
81
+ During review, locate the rule and a plausible next change. If a finding is about duplicated policy, show the affected callers and coordinated edits it would require; identical syntax or a preference for another pattern is insufficient. If an exception fits, record that reason instead of demanding a redesign. Use the existing [finding dispositions](../code-quality.md#review-findings-before-turning-them-into-edits); this guide adds no assessment fields or approval step.
@@ -0,0 +1,99 @@
1
+ # Failure handling at real boundaries
2
+
3
+ Read this when an operation can reject input, fail during I/O, partially complete, or be retried. First inspect how callers already distinguish failures. Keep the project's existing result types, exception classes, and logging conventions; introduce a new taxonomy only when callers need a distinction they cannot currently express.
4
+
5
+ ## Decide what a failure means
6
+
7
+ | Trigger | Decision while building | Question during review |
8
+ | --- | --- | --- |
9
+ | A catch returns an empty collection, default, or success | Identify which failure is actually allowed to mean that value; propagate or represent the others. | Could a legitimate outage or corrupt record look like valid empty data? |
10
+ | Callers must handle expected rejection differently from an outage | Use an established error code/result variant or exception type; preserve unexpected failures and useful cause information. | Does a caller branch on a stable contract, or parse message text and guess? |
11
+ | An operation writes state and then performs another effect | Define what committed, what remains pending, and how it can be recovered. | Could a later failure invite the caller to repeat an already completed effect? |
12
+ | A caller adds a retry, timeout, or cancellation | Establish retry safety, attempt limits, deadline/cancellation ownership, and what happens to in-flight work. | Is the outcome known to have failed, or only unknown to this caller? |
13
+
14
+ Keep diagnostic causes available to the appropriate internal boundary without exposing secrets or raw storage/network errors to users. Wrap an error only when adding useful operation context, preserving its cause where supported. Log at the boundary that owns reporting; logging and rethrowing at every layer creates duplicates.
15
+
16
+ ## Bad example failure disguised as empty data
17
+
18
+ Contract for this example: configuration must be readable JSON containing an object with an `items` array. An empty array is valid; a missing/unreadable file, invalid JSON, or wrong shape is a failure. `readText` is the existing asynchronous storage adapter.
19
+
20
+ ```js
21
+ async function loadItems(readText) {
22
+ try {
23
+ return JSON.parse(await readText()).items;
24
+ } catch {
25
+ return [];
26
+ }
27
+ }
28
+ ```
29
+
30
+ A caller cannot distinguish an empty collection from lost access or corrupt data. The wrong shape can also escape as `undefined`. This can be especially damaging if a later save overwrites existing data with the fallback empty collection.
31
+
32
+ ## Good example classify only the failures you own
33
+
34
+ ```js
35
+ async function loadItems(readText) {
36
+ const text = await readText(); // Unexpected I/O failures retain their cause.
37
+ let data;
38
+ try {
39
+ data = JSON.parse(text);
40
+ } catch (cause) {
41
+ return { ok: false, error: { code: 'INVALID_JSON', cause } };
42
+ }
43
+ if (data === null || typeof data !== 'object' ||
44
+ Array.isArray(data) || !Array.isArray(data.items)) {
45
+ return { ok: false, error: { code: 'INVALID_SHAPE' } };
46
+ }
47
+ return { ok: true, value: data.items };
48
+ }
49
+ ```
50
+
51
+ Here invalid document content is an expected rejection; adapter failures reject the promise and reach the operation's existing reporting boundary. The caller must handle both the explicit rejection and unexpected exceptions. A project that uses typed exceptions for all failures should retain that convention instead of adopting this mixed style. Validate each item too when the actual domain contract requires an item schema; this example checks only the stated envelope.
52
+
53
+ The `cause` is internal diagnostic data. The outer handler maps stable codes to the existing user-facing error contract and logs appropriate detail without serializing the raw cause to a response.
54
+
55
+ ## Bad example retrying an entire partially completed operation
56
+
57
+ Contract for this example: `orders.insert` commits an order and allocates a new identifier on every call. Email happens after commit, and callers may retry a rejected request.
58
+
59
+ ```js
60
+ async function placeOrder(orders, mailer, input) {
61
+ const order = await orders.insert(input);
62
+ await mailer.sendConfirmation(order);
63
+ return { ok: true, order };
64
+ }
65
+ ```
66
+
67
+ If email fails, the promise rejects after the order exists. Retrying the whole request can create a second order. A `try/catch` that retries this function repeats the wrong boundary.
68
+
69
+ ## Good example report the committed result and pending effect
70
+
71
+ ```js
72
+ async function placeOrder(orders, mailer, input) {
73
+ const order = await orders.insert(input);
74
+ try {
75
+ await mailer.sendConfirmation(order);
76
+ return { ok: true, order, confirmation: 'sent' };
77
+ } catch (cause) {
78
+ return { ok: true, order, confirmation: 'unknown', cause };
79
+ }
80
+ }
81
+ ```
82
+
83
+ This is appropriate **only** if the product contract accepts order creation without confirmed email delivery. The caller must surface or report the unknown confirmation through an existing operational path; it must not present full completion. `unknown` is intentional: a timeout may occur after an email provider accepted the message. The internal cause is not part of a public response.
84
+
85
+ This minimal change does not guarantee eventual email delivery or make order creation safe after a lost response. If durable delivery is required, use the project's transactional intent/outbox and delivery worker; if request retry safety is required, enforce the same idempotency key with the order commit and reject incompatible reuse. A stable key alone does not make an operation idempotent. Retries need bounded attempts, appropriate backoff and cancellation/deadline handling, and an explicit owner of exhausted or uncertain work. Do not add this infrastructure to a local operation with no such requirement.
86
+
87
+ ## Legitimate exceptions
88
+
89
+ - A missing file may mean first-run defaults if that is the documented contract. Handle the adapter's specific not-found condition; permission errors and corrupt files do not automatically mean first run.
90
+ - A pure internal function may let programmer errors propagate. Blanket catches and a new error class for every function obscure the original fault.
91
+ - Optional telemetry or decoration may fail without failing the main operation. Document the allowed loss and use the established reporting path when needed; a required audit record is not optional telemetry.
92
+ - A transaction may roll back all related local writes. External side effects outside that transaction still need an explicit outcome and recovery contract.
93
+ - Result variants and typed exceptions are both valid. Match the caller and language, and preserve compatibility instead of forcing one representation across unrelated modules.
94
+
95
+ ## Apply during Build and review
96
+
97
+ While building, trace the failure from the boundary to its real caller: the stable distinction the caller needs, any mutations already committed, the reporting owner, and whether retry is safe. Make partial or unknown outcomes visible in the existing contract. Do not convert failure to success merely to satisfy a check.
98
+
99
+ During review, follow at least the consequential rejection or failure path as well as success. Flag swallowed errors, message-text branching, unconditional retries, or misleading completion only with a legitimate trigger and consequence. Check the proposed repair against the exception cases above. Resolve findings through the existing [review guidance](../code-quality.md#review-findings-before-turning-them-into-edits); use the controller's existing recovery rules for workflow failures.