codecartographer-pi 0.1.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 (75) hide show
  1. package/.codecarto/BACKLOG.md +192 -0
  2. package/.codecarto/CHANGELOG-2026-05-02-feedback-pass.md +118 -0
  3. package/.codecarto/CONTRIBUTING.md +56 -0
  4. package/.codecarto/GUIDE.md +298 -0
  5. package/.codecarto/LICENSE +21 -0
  6. package/.codecarto/NEW_THREAD_BLURB.md +47 -0
  7. package/.codecarto/README.md +39 -0
  8. package/.codecarto/THREAD_LOG.md +39 -0
  9. package/.codecarto/closeouts/2026-05-02-framework-feedback-pass.md +111 -0
  10. package/.codecarto/findings/architecture/README.md +3 -0
  11. package/.codecarto/findings/architecture/SKILL.md +102 -0
  12. package/.codecarto/findings/build-and-deploy/.gitkeep +0 -0
  13. package/.codecarto/findings/config-model/.gitkeep +0 -0
  14. package/.codecarto/findings/contracts/README.md +3 -0
  15. package/.codecarto/findings/contracts/SKILL.md +89 -0
  16. package/.codecarto/findings/defect-scan/README.md +18 -0
  17. package/.codecarto/findings/defect-scan/SKILL.md +87 -0
  18. package/.codecarto/findings/defect-scan/passes/01-logic-and-correctness.md +50 -0
  19. package/.codecarto/findings/defect-scan/passes/02-error-handling.md +55 -0
  20. package/.codecarto/findings/defect-scan/passes/03-concurrency-and-resources.md +54 -0
  21. package/.codecarto/findings/defect-scan/passes/04-security-and-trust.md +62 -0
  22. package/.codecarto/findings/defect-scan/passes/05-api-contract-violations.md +57 -0
  23. package/.codecarto/findings/defect-scan/passes/06-config-and-environment.md +58 -0
  24. package/.codecarto/findings/defect-scan-mechanical/README.md +17 -0
  25. package/.codecarto/findings/defect-scan-mechanical/SKILL.md +60 -0
  26. package/.codecarto/findings/defect-scan-semantic/README.md +17 -0
  27. package/.codecarto/findings/defect-scan-semantic/SKILL.md +54 -0
  28. package/.codecarto/findings/porting/README.md +3 -0
  29. package/.codecarto/findings/porting/SKILL.md +52 -0
  30. package/.codecarto/findings/protocols/README.md +3 -0
  31. package/.codecarto/findings/protocols/SKILL.md +87 -0
  32. package/.codecarto/findings/public-surfaces/README.md +3 -0
  33. package/.codecarto/findings/reimplementation-spec/README.md +3 -0
  34. package/.codecarto/findings/reimplementation-spec/SKILL.md +66 -0
  35. package/.codecarto/findings/runtime-lifecycle/README.md +3 -0
  36. package/.codecarto/findings/state-and-storage/README.md +3 -0
  37. package/.codecarto/scratch/.gitkeep +0 -0
  38. package/.codecarto/skills/spec-delta-application/SKILL.md +102 -0
  39. package/.codecarto/templates/architecture-map.md +143 -0
  40. package/.codecarto/templates/behavioral-contracts.md +134 -0
  41. package/.codecarto/templates/closeout-template.md +85 -0
  42. package/.codecarto/templates/conventions-template.md +65 -0
  43. package/.codecarto/templates/decisions-template.md +82 -0
  44. package/.codecarto/templates/defect-fix-tracker.md +77 -0
  45. package/.codecarto/templates/defect-report.md +116 -0
  46. package/.codecarto/templates/deltas-applied.md +71 -0
  47. package/.codecarto/templates/mechanical-defects.md +104 -0
  48. package/.codecarto/templates/protocols-and-state.md +126 -0
  49. package/.codecarto/templates/reimplementation-spec-opinionated.md +183 -0
  50. package/.codecarto/templates/reimplementation-spec.md +148 -0
  51. package/.codecarto/templates/reverse-engineering-bundle.md +141 -0
  52. package/.codecarto/templates/semantic-defects.md +109 -0
  53. package/.codecarto/templates/thread-log-entry-template.md +27 -0
  54. package/.codecarto/workflow/VALIDATE.md +81 -0
  55. package/.codecarto/workflow/pipeline-architecture-only.yaml +38 -0
  56. package/.codecarto/workflow/pipeline-defect-scan.yaml +61 -0
  57. package/.codecarto/workflow/pipeline-full-with-audit.yaml +188 -0
  58. package/.codecarto/workflow/pipeline-full-with-deep-audit.yaml +227 -0
  59. package/.codecarto/workflow/pipeline-lite.yaml +100 -0
  60. package/.codecarto/workflow/pipeline.yaml +163 -0
  61. package/.codecarto/workflow/status.yaml +64 -0
  62. package/LICENSE +21 -0
  63. package/README.md +356 -0
  64. package/core/index.ts +11 -0
  65. package/core/pipeline.ts +175 -0
  66. package/core/prompts.ts +183 -0
  67. package/core/status.ts +155 -0
  68. package/core/types.ts +96 -0
  69. package/core/utils.ts +52 -0
  70. package/core/workspace.ts +81 -0
  71. package/core/yaml.ts +256 -0
  72. package/extensions/codecarto/index.ts +446 -0
  73. package/mcp-server/bin.mjs +7 -0
  74. package/mcp-server/server.ts +497 -0
  75. package/package.json +52 -0
@@ -0,0 +1,102 @@
1
+ ---
2
+ name: map-project-architecture
3
+ description: Map a repository into layers, package boundaries, entrypoints, dependency direction, and shared abstractions. Use when you need to understand an unfamiliar codebase before porting, auditing, decomposing, or reimplementing it in another language, especially for monorepos, CLIs, SDKs, and multi-surface products.
4
+ ---
5
+
6
+ # Map Project Architecture
7
+
8
+ Build the map before analyzing implementation details.
9
+
10
+ Read the structural sources first:
11
+ - Root README and contribution docs.
12
+ - Root package/workspace manifest and top-level scripts.
13
+ - Package or module READMEs.
14
+ - Package manifests, `bin` entries, `exports`, and top-level entrypoints.
15
+
16
+ For a monorepo, create a package inventory with these columns:
17
+ - package or module name
18
+ - purpose
19
+ - public entrypoints
20
+ - key dependencies
21
+ - runtime surface
22
+ - likely ownership category
23
+
24
+ Classify each package or major module into one primary role:
25
+ - `core semantics`
26
+ - `protocol or normalization layer`
27
+ - `persistence or state`
28
+ - `UI or rendering`
29
+ - `integration adapter`
30
+ - `product shell`
31
+
32
+ Trace dependency direction instead of reading everything in file order:
33
+ - Identify what depends on what.
34
+ - Find the lowest stable layer that nothing inside the repo depends on.
35
+ - Call out cycles explicitly.
36
+ - Mark packages that are wrappers around shared internals rather than unique systems.
37
+
38
+ Identify public surfaces early:
39
+ - binaries and CLI commands
40
+ - exported libraries and public types
41
+ - network or RPC interfaces
42
+ - file formats and persistent artifacts
43
+ - user-facing screens or workflows
44
+
45
+ Record the project's durable state:
46
+ - config files
47
+ - environment variables
48
+ - auth material
49
+ - session files
50
+ - logs
51
+ - caches
52
+ - databases
53
+ - generated artifacts
54
+
55
+ Treat third-party SDKs as shaping forces, not architecture:
56
+ - Note where vendor APIs, terminal behavior, Slack, browser APIs, or cloud services impose constraints.
57
+ - Do not let those constraints define the port's module boundaries unless the behavior truly depends on them.
58
+
59
+ Document the build and packaging pipeline:
60
+ - Build tool(s) and scripts (make, npm, cargo, gradle, etc.).
61
+ - Multi-target or multi-stage builds.
62
+ - Output artifacts: binaries, containers, packages, bundles.
63
+ - CI/CD pipeline if visible from repo files (.github/workflows, Jenkinsfile, etc.).
64
+ - Platform-specific packaging or distribution.
65
+ - If the build pipeline is complex, use the secondary output at `findings/build-and-deploy/build-and-deploy.md`.
66
+
67
+ Document the concurrency model:
68
+ - Threading model: single-threaded, thread pool, async/await, actor model, goroutines, etc.
69
+ - Event loop or reactor pattern, if present.
70
+ - Shared state and synchronization primitives.
71
+ - Connection pooling and resource management.
72
+ - Rate limiting or backpressure mechanisms.
73
+ - Mark concurrency-related portability hazards explicitly — these rarely translate 1:1 across languages.
74
+
75
+ Write the output in seven sections:
76
+ 1. `System intent`
77
+ 2. `Layer map`
78
+ 3. `Public surfaces`
79
+ 4. `Runtime lifecycle`
80
+ 5. `Concurrency model`
81
+ 6. `Build and packaging`
82
+ 7. `Porting priorities`
83
+
84
+ Mark every conclusion with one of these evidence levels:
85
+ - `observed fact`: direct statement from docs, tests, schemas, types, or code.
86
+ - `strong inference`: architectural conclusion drawn from multiple facts.
87
+ - `portability hazard`: assumption tied to the source language, runtime, terminal, OS, or third-party SDKs.
88
+ - `open question`: missing or conflicting behavior that still needs evidence.
89
+
90
+ Test for common structural patterns:
91
+ - shared provider or protocol layer
92
+ - shared stateful agent or execution loop
93
+ - multiple delivery surfaces on top
94
+ - product-specific wrappers around a shared core
95
+ - plugin or extension architecture
96
+ - microservice or monorepo with service boundaries
97
+
98
+ Stop once the map is stable enough to explain where behavior lives. Only then move to contracts, protocols, or deep source reading.
99
+
100
+ Use the output template at `templates/architecture-map.md`.
101
+
102
+ The source code to analyze is in the parent directory (`../` relative to `.codecarto/`). This is the repository root.
File without changes
File without changes
@@ -0,0 +1,3 @@
1
+ # Contracts Findings
2
+
3
+ User-visible behavior, commands, configuration semantics, defaults, edge cases, and acceptance checks.
@@ -0,0 +1,89 @@
1
+ ---
2
+ name: extract-behavioral-contracts
3
+ description: Recover user-visible behavior, commands, configuration semantics, defaults, error expectations, and feature contracts from docs, tests, examples, and code. Use when you need a language-agnostic behavior spec for later reimplementation, parity planning, or regression testing.
4
+ ---
5
+
6
+ # Extract Behavioral Contracts
7
+
8
+ Recover what the system does from the outside in.
9
+
10
+ Prioritize sources in this order:
11
+ 1. READMEs, docs, and built-in help text
12
+ 2. examples, demos, screenshots, sample sessions
13
+ 3. tests and fixtures
14
+ 4. schemas, default settings, and changelogs
15
+ 5. source code for gaps and contradictions
16
+
17
+ Split the analysis by user-facing surface:
18
+ - CLI
19
+ - TUI
20
+ - web UI
21
+ - API or SDK
22
+ - bot or background worker
23
+ - storage or export formats
24
+
25
+ For each feature, capture a contract with these fields:
26
+ - `feature`
27
+ - `trigger or input`
28
+ - `defaults`
29
+ - `observable output`
30
+ - `side effects`
31
+ - `persisted state`
32
+ - `error behavior`
33
+ - `retry or recovery behavior`
34
+
35
+ Treat tests as executable contracts:
36
+ - Prefer them for edge cases, ordering, and failure handling.
37
+ - Compare them against docs to detect drift.
38
+ - Call out any doc/test conflict instead of silently picking one.
39
+
40
+ Separate essential behavior from source-specific ergonomics:
41
+ - Preserve user-visible semantics.
42
+ - Do not overfit to exact class names, file names, or UI implementation tricks.
43
+ - Keep keyboard shortcuts, command aliases, or display details only if they matter to parity.
44
+
45
+ Pay special attention to these high-value behaviors:
46
+ - cancellation and abort handling
47
+ - streaming and partial output
48
+ - queueing or follow-up behavior
49
+ - compaction and summarization
50
+ - persistence and resume flows
51
+ - tool execution and validation
52
+
53
+ Document the security and authorization model (if the system has one):
54
+ - Authentication method(s): OAuth, API keys, session tokens, SSO, etc.
55
+ - Authorization model: RBAC, ABAC, ACLs, capability-based, etc.
56
+ - Trust boundaries: what input is trusted vs untrusted.
57
+ - Permission checks: how and where permissions are enforced.
58
+ - Secret management: how tokens, keys, and credentials are stored and rotated.
59
+ - Session lifecycle: expiration, refresh, invalidation.
60
+ - Skip this area entirely if the system has no auth model (e.g., a pure library).
61
+
62
+ Document the configuration model:
63
+ - Config sources and their precedence (env vars > config file > defaults, etc.).
64
+ - Config file format, location, and discovery mechanism.
65
+ - Feature flags and how they are toggled.
66
+ - Environment-specific overrides (dev, staging, prod).
67
+ - Config validation and error handling for malformed config.
68
+ - If the config model is complex, use the secondary output at `findings/config-model/config-model.md`.
69
+
70
+ Map every contract back to its owner:
71
+ - package or module
72
+ - shared core vs surface wrapper
73
+ - platform-specific adapter, if any
74
+
75
+ End with a black-box acceptance list:
76
+ - Write scenario-style checks that another implementation can run without referencing the source.
77
+ - Favor exact preconditions and expected outcomes over vague quality statements.
78
+
79
+ Mark every finding with one of these evidence levels:
80
+ - `observed fact`: direct statement from docs, tests, schemas, types, or code.
81
+ - `strong inference`: behavioral conclusion drawn from multiple facts.
82
+ - `portability hazard`: assumption tied to the source language, runtime, terminal, OS, or third-party SDKs.
83
+ - `open question`: missing or conflicting behavior that still needs evidence.
84
+
85
+ If behavior is hard to infer from docs alone, read the companion protocol skill next. Many user-visible quirks are really protocol or state-machine rules.
86
+
87
+ Use the output template at `templates/behavioral-contracts.md`.
88
+
89
+ The source code to analyze is in the parent directory (`../` relative to `.codecarto/`). This is the repository root.
@@ -0,0 +1,18 @@
1
+ # Defect Scan
2
+
3
+ Multi-pass analysis of the source codebase for logic errors, error handling gaps, concurrency issues, security vulnerabilities, API contract violations, and configuration hazards.
4
+
5
+ **Primary output:** `defect-report.md`
6
+
7
+ **Depends on:** architecture phase (required). Optionally leverages contracts and protocols phases for spec-grounded analysis.
8
+
9
+ **Analysis passes** (executed sequentially):
10
+
11
+ 1. Logic and correctness
12
+ 2. Error handling and resilience
13
+ 3. Concurrency and resource management
14
+ 4. Security and trust boundaries
15
+ 5. API contract violations
16
+ 6. Configuration and environment hazards
17
+
18
+ See `SKILL.md` for full instructions. Pass-specific guidance is in `passes/`.
@@ -0,0 +1,87 @@
1
+ ---
2
+ name: scan-for-defects
3
+ description: Run a multi-pass defect scan across the source codebase, checking for logic errors, error handling gaps, concurrency bugs, security issues, API contract violations, and configuration hazards. Use after the architecture phase is complete. Optionally leverages contracts and protocols outputs for spec-grounded analysis.
4
+ ---
5
+
6
+ # Scan For Defects
7
+
8
+ This phase runs **six sequential analysis passes**, each focused on one category of defect. Read and execute the passes in the order listed below. Do not try to cover all categories at once — complete each pass before starting the next.
9
+
10
+ The source code to analyze is in the parent directory (`../` relative to `.codecarto/`). This is the repository root.
11
+
12
+ ## Prerequisites
13
+
14
+ **Required:** Read `findings/architecture/architecture-map.md` before starting. You need the layer map, public surfaces, and concurrency model to know where to focus.
15
+
16
+ **Optional but valuable:** If the following files exist, read them before starting passes 5 and 4 respectively. They provide the behavioral spec to compare code against:
17
+ - `findings/contracts/behavioral-contracts.md` — enables spec-grounded analysis in passes 4 and 5.
18
+ - `findings/protocols/protocols-and-state.md` — enables state machine violation detection in pass 5.
19
+
20
+ If these files do not exist, the passes still work — they fall back to comparing code against its own documentation (docstrings, type signatures, comments, README).
21
+
22
+ ## Pass Execution Order
23
+
24
+ Run these passes sequentially. Read the pass file, scan the source, record findings, then move to the next pass.
25
+
26
+ | Pass | File | Focus |
27
+ |------|------|-------|
28
+ | 1 | `findings/defect-scan/passes/01-logic-and-correctness.md` | Dead code, boundary errors, null handling, boolean logic, control flow |
29
+ | 2 | `findings/defect-scan/passes/02-error-handling.md` | Swallowed errors, missing cleanup, uncaught exceptions, retry gaps |
30
+ | 3 | `findings/defect-scan/passes/03-concurrency-and-resources.md` | Race conditions, lock issues, async pitfalls, resource leaks |
31
+ | 4 | `findings/defect-scan/passes/04-security-and-trust.md` | Input validation, auth gaps, secrets in code, trust boundaries |
32
+ | 5 | `findings/defect-scan/passes/05-api-contract-violations.md` | Spec vs. implementation drift, return type mismatches, state machine violations |
33
+ | 6 | `findings/defect-scan/passes/06-config-and-environment.md` | Hardcoded values, missing validation, dangerous defaults, OS assumptions |
34
+
35
+ ## Prioritization
36
+
37
+ Not every pass applies to every codebase. Use the architecture map to decide emphasis:
38
+ - **No concurrency model?** Skim pass 3, focus elsewhere.
39
+ - **No auth system?** Skip the auth sections of pass 4, still check input validation.
40
+ - **Pure library with no config?** Skim pass 6.
41
+ - **Heavy protocol/state machine system?** Spend extra time on pass 5.
42
+
43
+ ## Evidence Classification
44
+
45
+ Mark every finding with one of these evidence levels:
46
+ - `observed fact`: the defect is directly visible in the code.
47
+ - `strong inference`: the defect is highly likely based on multiple code observations.
48
+ - `open question`: the code is suspicious but would need runtime testing to confirm.
49
+
50
+ ## Severity Classification
51
+
52
+ Assign one severity per finding:
53
+ - `critical`: causes wrong results, data loss, or security exposure in normal operation.
54
+ - `high`: causes wrong results or failures in edge cases or under specific conditions.
55
+ - `medium`: latent risk, dead code, defense-in-depth gap, or poor error handling.
56
+ - `low`: style issue with correctness implications, stale docs, or minor inconsistency.
57
+
58
+ ## Action Classification
59
+
60
+ Tag each finding with a recommended action. Use the set that matches your pipeline:
61
+
62
+ **Pre-porting pipelines** (full-with-audit, full-with-deep-audit):
63
+ - `fix before porting`: the defect would carry into a new implementation if not addressed first.
64
+ - `port differently`: the new implementation should handle this case differently by design.
65
+ - `leave behind`: the defect is specific to the source implementation and won't survive porting.
66
+
67
+ **Maintenance pipelines** (defect-scan):
68
+ - `fix now`: the defect is actively causing or risking problems.
69
+ - `track`: the defect is real but low-urgency; add to backlog.
70
+ - `accept`: the defect is known and the team has decided to live with it.
71
+ - `investigate`: needs runtime testing or deeper analysis to confirm.
72
+
73
+ Determine which action set to use by checking the `pipeline` field in `workflow/status.yaml`.
74
+
75
+ ## Output
76
+
77
+ Write findings to the primary output using the template at `templates/defect-report.md`.
78
+
79
+ Organize findings by pass (one section per pass), then by severity within each section.
80
+
81
+ End with a summary table counting findings by severity and category, and a prioritized list of the top findings across all passes.
82
+
83
+ Use the output template at `templates/defect-report.md`.
84
+
85
+ ## Fix Tracking
86
+
87
+ After the defect report is complete, a fix tracker template is available at `templates/defect-fix-tracker.md`. Use it to track remediation progress when fixing the defects found in this scan. The tracker uses the same defect IDs from the report (D{pass}.{number}) so fixes map directly back to findings.
@@ -0,0 +1,50 @@
1
+ # Pass 1: Logic and Correctness
2
+
3
+ Scan for structural logic defects that produce wrong results, unreachable behavior, or silent failures.
4
+
5
+ ## What to look for
6
+
7
+ **Dead and unreachable code:**
8
+ - Functions or branches that no call path reaches.
9
+ - Feature flags or config gates that are always true/false.
10
+ - Catch blocks or error handlers for exceptions that are never thrown.
11
+ - Enum values or switch cases that are defined but never matched.
12
+
13
+ **Off-by-one and boundary errors:**
14
+ - Loop bounds that skip the first or last element.
15
+ - Slice/substring ranges that are off by one.
16
+ - Comparison operators that should be `<=` instead of `<` (or vice versa).
17
+ - Array/index access without bounds checking.
18
+
19
+ **Null, undefined, and type coercion hazards:**
20
+ - Variables used before assignment or after conditional nulling.
21
+ - Optional values unwrapped without a nil/null check.
22
+ - Implicit type coercion that changes behavior (e.g., string-to-number, falsy values).
23
+ - Functions that sometimes return a value and sometimes return nothing.
24
+
25
+ **Boolean and conditional logic:**
26
+ - Conditions that are always true or always false.
27
+ - Negation errors (e.g., `!a || !b` vs `!(a && b)` misuse).
28
+ - Short-circuit evaluation that skips necessary side effects.
29
+ - Nested conditionals where branches overlap or have gaps.
30
+
31
+ **Return and control flow:**
32
+ - Missing return statements in branches.
33
+ - Early returns that skip cleanup or finalization.
34
+ - Fall-through in switch/match without explicit intent.
35
+ - Functions with inconsistent return types across branches.
36
+
37
+ ## How to report
38
+
39
+ For each finding, record:
40
+ - **Location**: file path and function/method name.
41
+ - **Defect**: what is wrong, in one sentence.
42
+ - **Evidence**: what you observed that proves or strongly suggests the defect.
43
+ - **Severity**: critical (incorrect results in normal use), high (incorrect results in edge cases), medium (dead code or latent risk), low (style issue with correctness implications).
44
+ - **Evidence level**: observed fact / strong inference / open question.
45
+
46
+ ## What to skip
47
+
48
+ - Style preferences (naming, formatting, comment density).
49
+ - Performance concerns (covered in other passes).
50
+ - Anything that requires runtime testing to confirm — mark those as open questions instead.
@@ -0,0 +1,55 @@
1
+ # Pass 2: Error Handling and Resilience
2
+
3
+ Scan for gaps in how the system detects, propagates, and recovers from errors.
4
+
5
+ ## What to look for
6
+
7
+ **Swallowed errors:**
8
+ - Empty catch/except blocks.
9
+ - Catch blocks that log but don't re-raise or propagate.
10
+ - Error callbacks that are registered but do nothing.
11
+ - Promise/future chains with missing `.catch` or error handlers.
12
+
13
+ **Inconsistent error propagation:**
14
+ - Functions that throw in some error paths but return error codes in others.
15
+ - Mixed error strategies within the same module (exceptions vs. result types vs. error codes).
16
+ - Error types that lose context when re-wrapped (original cause discarded).
17
+ - Errors that silently convert to default values instead of surfacing.
18
+
19
+ **Missing cleanup in error paths:**
20
+ - Resources (files, connections, locks) opened before a try block but not closed in the finally/error path.
21
+ - Temporary state mutations that aren't rolled back on failure.
22
+ - Partial writes that leave data in an inconsistent state.
23
+ - Transaction-like operations without rollback on failure.
24
+
25
+ **Uncaught exception paths:**
26
+ - Async operations without error handlers.
27
+ - Background tasks or worker threads with no top-level catch.
28
+ - Event handlers that can throw but aren't wrapped.
29
+ - Constructors or init methods that throw without cleanup.
30
+
31
+ **Retry and recovery gaps:**
32
+ - Network or I/O operations with no retry logic where transient failures are expected.
33
+ - Retry loops with no backoff, no jitter, or no max-attempts cap.
34
+ - Recovery paths that retry the exact same operation without fixing the underlying condition.
35
+ - Circuit breaker patterns that are partially implemented (open state but no half-open recovery).
36
+
37
+ **Error reporting and observability:**
38
+ - Errors that are caught but not logged anywhere.
39
+ - Log messages that omit the error type, message, or stack trace.
40
+ - Errors that surface to users as generic "something went wrong" without actionable detail.
41
+ - Health checks or monitoring that don't cover known failure modes.
42
+
43
+ ## How to report
44
+
45
+ For each finding, record:
46
+ - **Location**: file path and function/method name.
47
+ - **Defect**: what error scenario is mishandled.
48
+ - **Evidence**: the specific code pattern or path that demonstrates the gap.
49
+ - **Severity**: critical (data loss or corruption on failure), high (silent failure in normal operations), medium (poor error messages or missing cleanup), low (observability gap).
50
+ - **Evidence level**: observed fact / strong inference / open question.
51
+
52
+ ## What to skip
53
+
54
+ - Error handling style preferences (exceptions vs. result types) — unless the inconsistency within a module creates actual bugs.
55
+ - Logging format choices — unless errors are genuinely unobservable.
@@ -0,0 +1,54 @@
1
+ # Pass 3: Concurrency and Resource Management
2
+
3
+ Scan for race conditions, synchronization gaps, and resource leaks.
4
+
5
+ Read the concurrency model section from `findings/architecture/architecture-map.md` first to understand the system's threading model, async patterns, and synchronization approach.
6
+
7
+ ## What to look for
8
+
9
+ **Race conditions and data races:**
10
+ - Shared mutable state accessed from multiple threads/goroutines/tasks without synchronization.
11
+ - Read-modify-write sequences that aren't atomic.
12
+ - Check-then-act patterns where the condition can change between the check and the action.
13
+ - Event handlers that mutate shared state without coordination.
14
+ - Counters or accumulators updated from concurrent contexts without atomic operations.
15
+
16
+ **Lock and synchronization issues:**
17
+ - Lock acquisition order that differs across call sites (deadlock risk).
18
+ - Locks held across I/O operations or await points (starvation risk).
19
+ - Missing locks on data structures documented as shared.
20
+ - Locks that protect the wrong scope (too narrow or too broad).
21
+
22
+ **Async and event-loop pitfalls:**
23
+ - Blocking calls inside async functions (blocking the event loop).
24
+ - `await` on operations that can hang indefinitely without timeout.
25
+ - Fire-and-forget async operations with no error handling.
26
+ - Callback-based APIs mixed with promise/async-await without proper bridging.
27
+ - Unbounded task/goroutine spawning without backpressure.
28
+
29
+ **Resource leaks:**
30
+ - File handles, sockets, or database connections opened without corresponding close.
31
+ - Resources acquired in constructors but not released in destructors/finalizers.
32
+ - Connection pools that grow without bounds or don't return connections on error.
33
+ - Temporary files created but not cleaned up on exit or failure.
34
+ - Event listeners or subscriptions registered but never unregistered.
35
+
36
+ **Timeout and cancellation:**
37
+ - Network or I/O operations with no timeout.
38
+ - Long-running operations with no cancellation mechanism.
39
+ - Cancellation tokens or contexts that are passed through but never checked.
40
+ - Graceful shutdown paths that don't drain in-flight work.
41
+
42
+ ## How to report
43
+
44
+ For each finding, record:
45
+ - **Location**: file path and function/method name.
46
+ - **Defect**: what concurrent or resource scenario is mishandled.
47
+ - **Evidence**: the specific shared state, missing synchronization, or unclosed resource.
48
+ - **Severity**: critical (data corruption or deadlock in normal operation), high (race condition in common paths), medium (resource leak under error conditions), low (theoretical race in rarely-exercised path).
49
+ - **Evidence level**: observed fact / strong inference / open question.
50
+
51
+ ## What to skip
52
+
53
+ - Single-threaded code with no async — this pass is irrelevant if the architecture has no concurrency.
54
+ - Performance-only concerns (slow locks, suboptimal pool sizes) — unless they cause correctness issues.
@@ -0,0 +1,62 @@
1
+ # Pass 4: Security and Trust Boundaries
2
+
3
+ Scan for vulnerabilities in input validation, authentication, authorization, secret handling, and trust boundary enforcement.
4
+
5
+ If `findings/contracts/behavioral-contracts.md` exists, read the Security and Authorization section first — it documents the intended auth model. Compare what you find in code against what the contracts say should happen.
6
+
7
+ ## What to look for
8
+
9
+ **Input validation gaps:**
10
+ - User input passed to database queries, shell commands, file paths, or template engines without sanitization.
11
+ - Missing length limits on string inputs (buffer-adjacent risks, DoS vectors).
12
+ - File upload paths without extension/type/size validation.
13
+ - URL or redirect parameters that accept arbitrary destinations (open redirect).
14
+ - Deserialization of untrusted input without schema validation.
15
+
16
+ **Authentication weaknesses:**
17
+ - Endpoints or functions that should require authentication but don't check.
18
+ - Token validation that checks expiry but not signature (or vice versa).
19
+ - Password comparison using non-constant-time equality.
20
+ - Session tokens with insufficient entropy or predictable generation.
21
+ - Auth bypass via parameter manipulation (e.g., changing user ID in request).
22
+
23
+ **Authorization gaps:**
24
+ - Actions that check "is user logged in" but not "is user allowed to do this."
25
+ - Horizontal privilege escalation: user A can access user B's resources by changing an ID.
26
+ - Vertical privilege escalation: non-admin can reach admin-only functionality.
27
+ - Missing authorization checks on state-changing operations (writes, deletes) even when reads are protected.
28
+ - Role or permission checks that happen in the UI but not in the backend.
29
+
30
+ **Secret management issues:**
31
+ - API keys, tokens, passwords, or connection strings hardcoded in source.
32
+ - Secrets logged in plaintext (in log statements, error messages, or debug output).
33
+ - Secrets passed via URL query parameters (visible in logs, referrer headers, browser history).
34
+ - `.env` files, credential files, or key files not in `.gitignore`.
35
+ - Secrets with no rotation mechanism or expiry.
36
+
37
+ **Trust boundary violations:**
38
+ - Internal APIs that accept data from external sources without re-validation.
39
+ - Client-side validation without server-side enforcement.
40
+ - Inter-service communication without mutual authentication.
41
+ - Data from one tenant accessible to another (multi-tenancy isolation failures).
42
+
43
+ **Web security (if applicable):**
44
+ - Missing CORS restrictions or overly permissive CORS headers.
45
+ - Missing Content-Security-Policy headers.
46
+ - Cross-site scripting (XSS) via unescaped user content in HTML output.
47
+ - Cross-site request forgery (CSRF) on state-changing endpoints without token verification.
48
+ - Missing rate limiting on authentication endpoints.
49
+
50
+ ## How to report
51
+
52
+ For each finding, record:
53
+ - **Location**: file path and function/method name.
54
+ - **Defect**: what security property is violated.
55
+ - **Evidence**: the specific code path, missing check, or exposed secret.
56
+ - **Severity**: critical (actively exploitable, data exposure, auth bypass), high (exploitable with some effort or preconditions), medium (defense-in-depth gap, hardcoded non-production secret), low (missing header, informational disclosure).
57
+ - **Evidence level**: observed fact / strong inference / open question.
58
+
59
+ ## What to skip
60
+
61
+ - Dependency vulnerability scanning (CVEs in third-party packages) — that's a tooling concern, not a code analysis task.
62
+ - Cryptographic algorithm choices — unless they're demonstrably broken (e.g., MD5 for password hashing).
@@ -0,0 +1,57 @@
1
+ # Pass 5: API Contract Violations
2
+
3
+ Scan for functions, endpoints, and interfaces whose implementation doesn't match their documented or declared behavior.
4
+
5
+ This pass is most powerful when `findings/contracts/behavioral-contracts.md` and `findings/protocols/protocols-and-state.md` exist. If available, read them first and use them as the spec to compare against. If not available, use the code's own documentation (docstrings, comments, type signatures, README) as the spec.
6
+
7
+ ## What to look for
8
+
9
+ **Return type inconsistencies:**
10
+ - Functions whose docstring or type signature says they return X, but some branches return Y or nothing.
11
+ - APIs documented to return a specific shape, but error cases return a different shape.
12
+ - Nullable returns from functions not marked as nullable/optional.
13
+ - Collection-returning functions that sometimes return null instead of empty.
14
+
15
+ **Documented behavior vs. actual behavior:**
16
+ - Parameters documented as required that have silent defaults in implementation.
17
+ - Side effects (writes, network calls, state mutations) not mentioned in docs or type signatures.
18
+ - Functions documented as pure/idempotent that actually mutate state.
19
+ - Default values documented in one place but implemented differently.
20
+ - Error behavior documented as "throws X" but actually throws Y or returns an error code.
21
+
22
+ **Interface contract breaks:**
23
+ - Classes or modules that implement an interface but skip or stub required methods.
24
+ - Event emitters that document events but never emit some of them.
25
+ - Callback signatures that don't match what callers pass.
26
+ - Middleware or plugin hooks with undocumented ordering dependencies.
27
+
28
+ **State machine violations (spec-grounded):**
29
+ - If protocols phase output is available: transitions that the implementation allows but the state machine says shouldn't happen.
30
+ - State that can be entered but has no exit transition.
31
+ - Guards documented as required but not enforced in code.
32
+ - Side effects that should only fire on specific transitions but fire unconditionally.
33
+
34
+ **Behavioral contract drift:**
35
+ - If contracts phase output is available: features whose trigger/defaults/output/error-behavior in code differs from what the contracts document.
36
+ - Black-box acceptance scenarios from the contracts that the code would fail.
37
+ - Features documented as available on a surface (CLI, API, etc.) but missing or broken in the implementation for that surface.
38
+
39
+ **Version and compatibility:**
40
+ - APIs that changed behavior between versions without documentation.
41
+ - Deprecation warnings that reference alternatives that don't exist yet.
42
+ - Backward-compatibility promises broken by recent changes.
43
+
44
+ ## How to report
45
+
46
+ For each finding, record:
47
+ - **Location**: file path and function/method name.
48
+ - **Defect**: what contract is violated and how.
49
+ - **Spec source**: where the expected behavior is documented (docstring, type signature, contracts phase, protocols phase, README).
50
+ - **Evidence**: the specific divergence between spec and implementation.
51
+ - **Severity**: critical (public API returns wrong results), high (documented behavior incorrect in edge cases), medium (internal API inconsistency), low (stale docs, minor parameter mismatch).
52
+ - **Evidence level**: observed fact / strong inference / open question.
53
+
54
+ ## What to skip
55
+
56
+ - Style-level doc issues (typos, formatting) — unless they make the documented behavior ambiguous.
57
+ - Test coverage gaps — unless a specific contract has no tests AND the implementation looks suspicious.
@@ -0,0 +1,58 @@
1
+ # Pass 6: Configuration and Environment Hazards
2
+
3
+ Scan for hardcoded values, missing validation, dangerous defaults, and environment assumptions that cause failures in deployment or operation.
4
+
5
+ If `findings/contracts/behavioral-contracts.md` exists, read the Configuration Model section first.
6
+
7
+ ## What to look for
8
+
9
+ **Hardcoded values that should be configurable:**
10
+ - URLs, hostnames, ports, or IP addresses embedded in source code.
11
+ - Timeouts, retry counts, or buffer sizes that are magic numbers.
12
+ - Feature behavior gated on string comparisons against environment names (e.g., `if env == "production"`).
13
+ - File paths that assume a specific OS or directory structure.
14
+ - Locale, timezone, or encoding assumptions baked into code.
15
+
16
+ **Missing configuration validation:**
17
+ - Config loaded at startup with no schema validation (malformed config silently produces wrong behavior).
18
+ - Numeric config values with no range checks (negative timeouts, zero-size pools).
19
+ - String config values used in security-sensitive contexts without sanitization (e.g., config-driven SQL, file paths).
20
+ - Required config keys that are silently absent, falling back to dangerous defaults.
21
+
22
+ **Dangerous defaults:**
23
+ - Debug mode, verbose logging, or development-only features enabled by default.
24
+ - Security features (auth, TLS, rate limiting) disabled unless explicitly turned on.
25
+ - Default credentials or tokens that ship with the code.
26
+ - Default config that works in development but fails or is unsafe in production.
27
+
28
+ **Environment coupling:**
29
+ - Code that assumes a specific OS (path separators, shell commands, temp directories).
30
+ - Network assumptions (localhost availability, DNS resolution, specific ports being free).
31
+ - Filesystem assumptions (case sensitivity, symlink support, file locking behavior).
32
+ - Runtime version assumptions not enforced by manifests or checks.
33
+
34
+ **Configuration propagation issues:**
35
+ - Config changes that require a restart but aren't documented as such.
36
+ - Config values read once at startup and cached, ignoring later changes.
37
+ - Environment variables that override config files in undocumented ways.
38
+ - Config inheritance chains where a middle layer silently drops values.
39
+
40
+ **Deployment and operational hazards:**
41
+ - Migrations or schema changes that run automatically without confirmation.
42
+ - Startup sequences that fail silently if a dependency is unavailable.
43
+ - Health checks that report healthy when critical subsystems are down.
44
+ - Log output that contains sensitive config values (secrets, connection strings).
45
+
46
+ ## How to report
47
+
48
+ For each finding, record:
49
+ - **Location**: file path and function/method name.
50
+ - **Defect**: what configuration or environment hazard exists.
51
+ - **Evidence**: the specific hardcoded value, missing validation, or dangerous default.
52
+ - **Severity**: critical (security exposure in default config, data loss on misconfiguration), high (production failure from missing validation), medium (hardcoded value that will break in a different environment), low (undocumented config behavior).
53
+ - **Evidence level**: observed fact / strong inference / open question.
54
+
55
+ ## What to skip
56
+
57
+ - Config file format preferences (YAML vs TOML vs JSON) — unless the format causes actual parsing ambiguity.
58
+ - Deployment orchestration choices (Docker vs bare metal) — unless the code assumes one and breaks on the other.