devworkspace 0.3.0 → 0.3.2

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 (119) hide show
  1. package/CHANGELOG.md +42 -1
  2. package/README.md +8 -5
  3. package/dist/agents/claude/adapter.d.ts +3 -14
  4. package/dist/agents/claude/adapter.js +46 -49
  5. package/dist/agents/claude/adapter.js.map +1 -1
  6. package/dist/agents/codex/adapter.d.ts +2 -0
  7. package/dist/agents/codex/adapter.js +61 -0
  8. package/dist/agents/codex/adapter.js.map +1 -0
  9. package/dist/agents/copilot/adapter.d.ts +2 -0
  10. package/dist/agents/copilot/adapter.js +62 -0
  11. package/dist/agents/copilot/adapter.js.map +1 -0
  12. package/dist/agents/cursor/adapter.d.ts +2 -0
  13. package/dist/agents/cursor/adapter.js +127 -0
  14. package/dist/agents/cursor/adapter.js.map +1 -0
  15. package/dist/agents/index.d.ts +15 -0
  16. package/dist/agents/index.js +54 -0
  17. package/dist/agents/index.js.map +1 -0
  18. package/dist/agents/shared.d.ts +20 -0
  19. package/dist/agents/shared.js +76 -0
  20. package/dist/agents/shared.js.map +1 -0
  21. package/dist/agents/types.d.ts +16 -1
  22. package/dist/agents/types.js.map +1 -1
  23. package/dist/cli/args.d.ts +42 -0
  24. package/dist/cli/args.js +12 -0
  25. package/dist/cli/args.js.map +1 -1
  26. package/dist/cli/help.js +64 -10
  27. package/dist/cli/help.js.map +1 -1
  28. package/dist/cli/render.d.ts +12 -1
  29. package/dist/cli/render.js +188 -0
  30. package/dist/cli/render.js.map +1 -1
  31. package/dist/cli/run.js +100 -9
  32. package/dist/cli/run.js.map +1 -1
  33. package/dist/config/schemas.d.ts +6 -0
  34. package/dist/config/schemas.js +6 -0
  35. package/dist/config/schemas.js.map +1 -1
  36. package/dist/core/version.d.ts +7 -0
  37. package/dist/core/version.js +13 -0
  38. package/dist/core/version.js.map +1 -1
  39. package/dist/core/workspace.d.ts +1 -0
  40. package/dist/core/workspace.js +1 -0
  41. package/dist/core/workspace.js.map +1 -1
  42. package/dist/discovery/commands.d.ts +1 -0
  43. package/dist/discovery/commands.js +3 -1
  44. package/dist/discovery/commands.js.map +1 -1
  45. package/dist/features/schema.d.ts +3 -0
  46. package/dist/features/schema.js +79 -0
  47. package/dist/features/schema.js.map +1 -0
  48. package/dist/features/types.d.ts +77 -0
  49. package/dist/features/types.js +2 -0
  50. package/dist/features/types.js.map +1 -0
  51. package/dist/features/validate.d.ts +14 -0
  52. package/dist/features/validate.js +124 -0
  53. package/dist/features/validate.js.map +1 -0
  54. package/dist/index.d.ts +8 -2
  55. package/dist/index.js +4 -1
  56. package/dist/index.js.map +1 -1
  57. package/dist/integrations/adapters/claudePlugin.d.ts +12 -0
  58. package/dist/integrations/adapters/claudePlugin.js +37 -8
  59. package/dist/integrations/adapters/claudePlugin.js.map +1 -1
  60. package/dist/integrations/adapters/pluginSkill.js +5 -0
  61. package/dist/integrations/adapters/pluginSkill.js.map +1 -1
  62. package/dist/security/files.js +10 -2
  63. package/dist/security/files.js.map +1 -1
  64. package/dist/security/redact.js +1 -1
  65. package/dist/security/redact.js.map +1 -1
  66. package/dist/services/agent.d.ts +12 -2
  67. package/dist/services/agent.js +96 -14
  68. package/dist/services/agent.js.map +1 -1
  69. package/dist/services/analysis.js +3 -3
  70. package/dist/services/analysis.js.map +1 -1
  71. package/dist/services/doctor.js +65 -14
  72. package/dist/services/doctor.js.map +1 -1
  73. package/dist/services/drift.d.ts +21 -0
  74. package/dist/services/drift.js +89 -0
  75. package/dist/services/drift.js.map +1 -0
  76. package/dist/services/features.d.ts +22 -0
  77. package/dist/services/features.js +105 -0
  78. package/dist/services/features.js.map +1 -0
  79. package/dist/services/graph.d.ts +97 -0
  80. package/dist/services/graph.js +342 -0
  81. package/dist/services/graph.js.map +1 -0
  82. package/dist/services/refresh.js +15 -0
  83. package/dist/services/refresh.js.map +1 -1
  84. package/dist/services/reset.js +45 -5
  85. package/dist/services/reset.js.map +1 -1
  86. package/dist/services/setup.d.ts +56 -0
  87. package/dist/services/setup.js +116 -0
  88. package/dist/services/setup.js.map +1 -0
  89. package/dist/services/status.d.ts +8 -0
  90. package/dist/services/status.js +78 -10
  91. package/dist/services/status.js.map +1 -1
  92. package/dist/services/tasks.js +6 -1
  93. package/dist/services/tasks.js.map +1 -1
  94. package/dist/services/verify.d.ts +11 -0
  95. package/dist/services/verify.js +64 -2
  96. package/dist/services/verify.js.map +1 -1
  97. package/dist/tasks/routing.js +14 -10
  98. package/dist/tasks/routing.js.map +1 -1
  99. package/dist/tasks/task.js +6 -2
  100. package/dist/tasks/task.js.map +1 -1
  101. package/dist/verification/scope.js +1 -1
  102. package/dist/verification/scope.js.map +1 -1
  103. package/docs/agents.md +60 -0
  104. package/docs/architecture-report/01-executive-summary.md +168 -0
  105. package/docs/architecture-report/02-system-architecture.md +356 -0
  106. package/docs/architecture-report/03-tools-and-technologies.md +112 -0
  107. package/docs/architecture-report/04-execution-flows.md +257 -0
  108. package/docs/architecture-report/05-codebase-map.md +150 -0
  109. package/docs/architecture-report/06-command-reference.md +446 -0
  110. package/docs/architecture-report/07-data-flow-and-integrations.md +268 -0
  111. package/docs/architecture-report/08-build-test-deployment.md +185 -0
  112. package/docs/architecture-report/09-security-and-reliability.md +165 -0
  113. package/docs/architecture-report/10-feature-status.md +110 -0
  114. package/docs/architecture-report/11-glossary.md +97 -0
  115. package/docs/architecture-report/README.md +103 -0
  116. package/docs/architecture-report/diagrams.md +446 -0
  117. package/docs/architecture.md +2 -2
  118. package/docs/getting-started.md +38 -1
  119. package/package.json +1 -1
@@ -0,0 +1,257 @@
1
+ # Chapter 4: Execution Flows & Lifecycles
2
+
3
+ > **Step-by-step operational traces of CLI startup, project analysis, agent skills coordination, and task completion verification.**
4
+
5
+ ---
6
+
7
+ ## 1. Workflow A: CLI Startup and Dispatch
8
+
9
+ When a user or AI coding agent executes a DevWorkspace command in the terminal (e.g., `devworkspace status` or `npx devworkspace analyze`), the request flows through five distinct stages:
10
+
11
+ ```mermaid
12
+ sequenceDiagram
13
+ autonumber
14
+ actor User as Developer / Agent
15
+ participant OS as Operating System / Shell
16
+ participant Main as CLI Entry (src/cli/main.ts)
17
+ participant Parser as Arg Parser (src/cli/args.ts)
18
+ participant Dispatcher as Dispatcher (src/cli/run.ts)
19
+ participant Service as Service Function (src/services/*)
20
+ participant Renderer as Renderer (src/cli/render.ts)
21
+
22
+ User->>OS: Runs "devworkspace analyze --cwd . --json"
23
+ OS->>Main: Launches node dist/cli/main.js
24
+ Note over Main: Hooks SIGINT & SIGTERM<br/>to run cleanups & release locks
25
+ Main->>Dispatcher: run(process.argv.slice(2))
26
+ Dispatcher->>Parser: parseCli(argv)
27
+ Note over Parser: Strict validation using node:util<br/>Rejects unknown flags immediately
28
+ Parser-->>Dispatcher: ParsedArgs { values, positionals }
29
+ Dispatcher->>Dispatcher: Resolve command alias ("tasks" -> "task list")
30
+ Dispatcher->>Dispatcher: Initialize Ctx (logger, styles, stdout/stderr, cwd)
31
+ Dispatcher->>Service: Call handler (e.g. analyzeWorkspace(ws, svc))
32
+ Service-->>Dispatcher: Returns structured result object
33
+ Dispatcher->>Renderer: Format output (JSON or styled ANSI/ASCII text)
34
+ Renderer-->>Main: Write to stdout / stderr
35
+ Main->>OS: Set process.exitCode (0, 1, 2, 3, or 130)
36
+ OS-->>User: Process terminates with output
37
+ ```
38
+
39
+ ### Detailed Trace:
40
+ 1. **OS Invocation**: The shell resolves `devworkspace` via the `bin` field in `package.json` (`dist/cli/main.js`).
41
+ 2. **Signal Traps**: `src/cli/main.ts` immediately attaches listeners for `SIGINT` (Ctrl+C) and `SIGTERM`. If triggered, it calls `runCleanups()` to remove temporary lockfiles and exits with status 130.
42
+ 3. **Strict Argument Parsing**: `src/cli/args.ts` passes flags to `node:util/parseArgs`. If an unrecognized flag is passed (e.g., `--dr-run` instead of `--dry-run`), it throws a `DevWorkspaceError('USAGE')` with exit code 2.
43
+ 4. **Context Construction**: `src/cli/run.ts` constructs a `Ctx` object containing `args`, `svc` (`cwd`, `dryRun`, `env`, `runner`), styling helpers (`makeStyle`), and output functions.
44
+ 5. **Execution**: The handler calls the pure service function (e.g. `analyzeWorkspace()`), which returns a typed result object.
45
+ 6. **Output Rendering**:
46
+ - If `--json` was passed, the raw JavaScript object is serialized with `JSON.stringify(value, null, 2)` and printed to `stdout`.
47
+ - Otherwise, the appropriate rendering function from `src/cli/render.ts` formats the result with badges, colors, and tables.
48
+ 7. **Exit Code Propagation**: `process.exitCode` is set to the exit code determined by the handler (0 for success, 1 for failure, 2 for usage errors, 3 for strict mode warnings).
49
+
50
+ ---
51
+
52
+ ## 2. Workflow B: Project Analysis Workflow
53
+
54
+ Running `devworkspace analyze` scans the repository and creates the testing contract and onboarding prompt.
55
+
56
+ ```mermaid
57
+ flowchart TD
58
+ Start["devworkspace analyze"] --> CheckWs["Find .devworkspace/<br/>(src/core/workspace.ts)"]
59
+ CheckWs --> Lock["Acquire File Lock<br/>(.devworkspace/local/devworkspace.lock)"]
60
+
61
+ subgraph ScanningPhase["1. Bounded Filesystem Scan"]
62
+ Scan["scan.ts: readdirRecursive()<br/>• Max 10,000 files<br/>• Ignore node_modules, .git, dist<br/>• Detect symlinks (skip to prevent loops)"]
63
+ end
64
+
65
+ subgraph DetectionPhase["2. Deterministic Detection"]
66
+ DetectStack["detect.ts:<br/>• Language extensions (.ts, .py, .go)<br/>• Frameworks from manifests<br/>• Monorepo structure"]
67
+ DetectCommands["commands.ts:<br/>• Inspect scripts in package.json<br/>• Map typecheck, unit, integration, build<br/>• Record exact cwd per command"]
68
+ DetectDocs["docs.ts:<br/>• Identify READMEs, docs/, ADRs (max 25)"]
69
+ DetectEntry["entrypoints.ts:<br/>• Identify server.ts, workers, CLIs"]
70
+ DetectSens["files.ts:<br/>• Record names of .env files (never read content)"]
71
+ end
72
+
73
+ subgraph OutputPhase["3. State & Prompt Generation"]
74
+ WriteDiscovery[".devworkspace/analysis/discovery.json"]
75
+ WriteCommands[".devworkspace/context/commands.json"]
76
+ GenPrompt["prompts/onboarding.ts:<br/>Generate onboarding-prompt.md"]
77
+ ValidateReqs["prompts/requirements.ts:<br/>Validate prompt against 21 requirements"]
78
+ SaveFacts["knowledge/facts.ts:<br/>Record 10+ DETECTED facts in facts.json"]
79
+ end
80
+
81
+ Lock --> ScanningPhase
82
+ ScanningPhase --> DetectionPhase
83
+ DetectionPhase --> OutputPhase
84
+ OutputPhase --> ReleaseLock["Release File Lock"]
85
+ ReleaseLock --> Finish["Render Analysis Summary to stdout"]
86
+ ```
87
+
88
+ ### Detailed Trace:
89
+ 1. **Workspace Verification**: `requireWorkspace(cwd)` walks upwards looking for `.devworkspace/project.json`.
90
+ 2. **Mutual Exclusion**: `withLock` acquires an exclusive lock (`.devworkspace/local/devworkspace.lock`) so concurrent CLI commands do not collide.
91
+ 3. **Filesystem Scanning (`scan.ts`)**: Bounded recursive walk. Collects relative paths, sizes, and file extensions while skipping `node_modules/`, `.git/`, `dist/`, `build/`, `vendor/`, and ignored entries.
92
+ 4. **Deterministic Stack Detection (`detect.ts`)**:
93
+ - Inspects manifests safely using `safeReadText` (bounded read up to 1MB).
94
+ - Identifies monorepo packages (e.g. `backend` and `frontend`).
95
+ - Identifies framework dependencies (React, Fastify, Drizzle, etc.).
96
+ - Notes presence of sensitive files (`backend/.env`) without opening them.
97
+ 5. **Testing Contract Derivation (`commands.ts`)**:
98
+ - Maps scripts from each package into standardized check IDs (`typecheck`, `unit`, `integration`, `lint`, `build`).
99
+ - Flags mutative scripts (`format: "prettier --write"`) with `mutates: true`.
100
+ - Identifies working directory (`cwd: "backend"`, `cwd: "frontend"`).
101
+ 6. **Prompt Assembly & Validation (`onboarding.ts` & `requirements.ts`)**:
102
+ - Generates `.devworkspace/analysis/onboarding-prompt.md`.
103
+ - Validates that the generated prompt passes all 21 prompt safety requirements (untrusted data rules, secrets rules, git safety rules, etc.).
104
+ 7. **Atomic Persistence**: Writes `discovery.json`, `commands.json`, and initial `DETECTED` facts into `facts.json` using atomic temporary file renames.
105
+
106
+ ---
107
+
108
+ ## 3. Workflow C: Agent Skills & Integrations Lifecycle
109
+
110
+ Running `devworkspace setup --integrations` inspects external tools on the machine, checks their health, and plans their installation non-destructively:
111
+
112
+ ```mermaid
113
+ sequenceDiagram
114
+ autonumber
115
+ actor User as Developer / Agent
116
+ participant Svc as setupIntegrations()
117
+ participant Mgr as IntegrationManager (src/integrations/manager.ts)
118
+ participant Adapter as Adapter (Graphify / Agent Skills / Ponytail)
119
+ participant Exec as Process Runner (src/integrations/exec.ts)
120
+ participant Protect as Snapshot Guard (src/integrations/protect.ts)
121
+ participant FS as Local Filesystem
122
+
123
+ User->>Svc: devworkspace setup --integrations [--yes]
124
+ Svc->>Mgr: run(options)
125
+
126
+ loop For each adapter (Graphify, Agent Skills, Ponytail, OmniRoute)
127
+ Mgr->>Adapter: inspect(AdapterContext, deep=true)
128
+ Adapter->>Exec: which(toolName), run(tool --version)
129
+ Exec-->>Adapter: Tool status, version string
130
+ Adapter-->>Mgr: IntegrationReport { status: INSTALLED | NOT_INSTALLED | DEGRADED }
131
+
132
+ Mgr->>Adapter: plan(AdapterContext, targetScope)
133
+ Adapter-->>Mgr: PlanResult { steps, protectPaths, blockers }
134
+ end
135
+
136
+ alt Dry-Run or Missing --yes
137
+ Mgr-->>User: Output planned steps & require confirmation (Exit Code 2)
138
+ else User Confirmed (--yes)
139
+ loop For each planned step
140
+ Mgr->>Protect: Take snapshot of protectPaths (e.g. CLAUDE.md)
141
+ Mgr->>Exec: Run installation command (e.g. "graphify install --project")
142
+ Mgr->>Protect: Verify snapshot; rollback if user changes overwritten
143
+ Mgr->>Adapter: Re-inspect to verify successful installation
144
+ end
145
+ Mgr->>FS: Save state to .devworkspace/state/integrations.json
146
+ Mgr-->>User: Report outcomes (VERIFIED, RESTART_REQUIRED, or DEGRADED)
147
+ end
148
+ ```
149
+
150
+ ### Key Safety Invariant: Pre-Execution Snapshots
151
+ When an external tool modifies repository files (such as `graphify install --project` modifying `CLAUDE.md`), `src/integrations/protect.ts` records SHA-256 hashes of the files before running the tool. If the tool overwrites uncommitted user modifications outside its managed area, DevWorkspace immediately restores the snapshot and aborts with an error.
152
+
153
+ ---
154
+
155
+ ## 4. Workflow D: Task Lifecycle & The Completion Gate
156
+
157
+ The task engine prevents coding agents from prematurely declaring tasks finished:
158
+
159
+ ```mermaid
160
+ stateDiagram-v2
161
+ [*] --> IDEA: devworkspace task new "<description>"
162
+
163
+ IDEA --> SPECIFIED: Specify acceptance criteria (task update)
164
+ SPECIFIED --> PLANNED: Add implementation steps (task update)
165
+ PLANNED --> IN_PROGRESS: Start coding / take baseline
166
+
167
+ IN_PROGRESS --> TESTING: Code written; run test suite
168
+ TESTING --> REVIEW: Tests pass; review git diff
169
+
170
+ REVIEW --> COMPLETED: devworkspace task status COMPLETED
171
+
172
+ IN_PROGRESS --> BLOCKED: Unforeseen blocker / dependency
173
+ BLOCKED --> IN_PROGRESS: Blocker resolved
174
+
175
+ TESTING --> FAILED: Verification failed
176
+ FAILED --> IN_PROGRESS: Fix applied
177
+
178
+ COMPLETED --> [*]
179
+
180
+ note right of COMPLETED
181
+ evaluateGate() enforces:
182
+ 1. All required checks == PASS (or user-override)
183
+ 2. No test count regressions (passed >= baseline, failed <= baseline)
184
+ 3. Read-only tasks modified 0 files
185
+ 4. userWorkIntact == true
186
+ 5. knowledgeReviewed == true
187
+ 6. finalStateInspected == true
188
+ 7. completionSummary is present
189
+ end note
190
+ ```
191
+
192
+ ### Detailed Trace of a Task:
193
+ 1. **Creation (`task new`)**:
194
+ - The user prompt is classified via regex and keyword matching in `routing.ts` (e.g. `FEATURE`).
195
+ - `captureScope()` records a snapshot of current Git HEAD and currently dirty files. Any files already dirty before this task are marked as `baseline` and will not be blamed on the task.
196
+ - Initial verification checks are configured from the project testing contract.
197
+ 2. **Execution & Evidence Recording (`task run` / `task verify`)**:
198
+ - The agent executes contract commands safely using `devworkspace task run <id> <check>`.
199
+ - Results are recorded with exact exit code, duration, timestamp, and kind (`executed` vs `claimed`).
200
+ 3. **Baseline Comparison (`task tests`)**:
201
+ - For bug fixes and refactors, the agent records baseline tests (`task tests <id> --phase baseline --passed 100 --failed 1`).
202
+ - After the fix, the agent records final tests (`--phase after --passed 101 --failed 0`).
203
+ 4. **Mandatory Attestations (`task attest`)**:
204
+ - The agent must explicitly confirm:
205
+ - `--user-work-intact`: No pre-existing user code was overwritten.
206
+ - `--knowledge-reviewed`: Durable conventions or decisions were logged.
207
+ - `--final-state-inspected`: `git status` was checked before closing.
208
+ 5. **Completion Transition (`task status COMPLETED`)**:
209
+ - `transitionTask()` calls `evaluateGate()`. If even one required check is `PENDING` or `FAIL`, or if test regressions occurred, or if an attestation is missing, it **throws an error** and keeps the task open.
210
+
211
+ ---
212
+
213
+ ## 5. Workflow E: Knowledge Refresh & Staleness Detection
214
+
215
+ Running `devworkspace refresh` ensures project knowledge stays synchronized with the codebase:
216
+
217
+ ```mermaid
218
+ flowchart TD
219
+ Start["devworkspace refresh"] --> Load["Load facts from .devworkspace/context/facts.json"]
220
+
221
+ subgraph StalenessCheck["1. Inspect Evidence Files"]
222
+ CheckSource["For each fact: inspect its sources[] files"]
223
+ HashSource["Calculate current SHA-256 hash of source files"]
224
+ CompareHash{"Current hash ==<br/>Recorded hash?"}
225
+
226
+ CompareHash -- Yes --> Keep["Status remains VERIFIED / DETECTED"]
227
+ CompareHash -- No or Missing --> MarkStale["Mark fact status as STALE<br/>(Authority rank drops to 1)"]
228
+ end
229
+
230
+ subgraph ReDiscovery["2. Deterministic Re-Discovery"]
231
+ ReScan["Re-run detect.ts over manifests"]
232
+ MergeFacts["Merge new findings with existing facts<br/>(Higher authority rank wins)"]
233
+ end
234
+
235
+ subgraph Output["3. Refresh Prompt Generation"]
236
+ SaveUpdated["Save updated facts.json atomically"]
237
+ WriteRefreshPrompt["Generate .devworkspace/analysis/refresh-prompt.md<br/>Listing all STALE facts for agent review"]
238
+ end
239
+
240
+ Load --> StalenessCheck
241
+ StalenessCheck --> ReDiscovery
242
+ ReDiscovery --> Output
243
+ Output --> Done["Display refresh summary"]
244
+ ```
245
+
246
+ ### Authority Ranking Rule:
247
+ When merging new findings into existing facts, `authorityRank()` in `src/knowledge/facts.ts` enforces that a lower-ranked source can **never** silently overwrite a higher-ranked fact:
248
+ - **Rank 5**: `USER_DECISION` (Direct human command or decision)
249
+ - **Rank 4**: `DETECTED` (Extracted directly from package manifests)
250
+ - **Rank 3**: `VERIFIED` (Derived by an AI agent and verified against repository evidence)
251
+ - **Rank 2**: `INFERRED` (Heuristic guess)
252
+ - **Rank 1**: `STALE` / `UNKNOWN`
253
+
254
+ ---
255
+
256
+ *Continue to [Chapter 5: Codebase Map](./05-codebase-map.md) for the directory structure and module responsibility matrix.*
257
+
@@ -0,0 +1,150 @@
1
+ # Chapter 5: Codebase Map & Module Responsibilities
2
+
3
+ > **A comprehensive structural map of the DevWorkspace codebase, module directory boundaries, and source file responsibilities.**
4
+
5
+ ---
6
+
7
+ ## 1. Diagram 7: Repository Structure Map
8
+
9
+ ```mermaid
10
+ graph TD
11
+ Root["devworkspace/"]
12
+
13
+ subgraph Src["src/ (TypeScript Source Code)"]
14
+ CLI["cli/ - Entrypoints, argument parsing, command dispatch, and formatting"]
15
+ Services["services/ - Pure service orchestration layer (16 command handlers)"]
16
+ Discovery["discovery/ - Deterministic repository scanning and stack detection"]
17
+ Agents["agents/ - Multi-agent adapters (Claude, Codex, Cursor, Copilot)"]
18
+ Integrations["integrations/ - External tool management (Graphify, Skills, Ponytail)"]
19
+ Tasks["tasks/ - Task routing, state machines, and completion gates"]
20
+ Knowledge["knowledge/ - Facts engine, authority ranking, and staleness detection"]
21
+ Decisions["decisions/ - Architecture Decision Records (ADRs) management"]
22
+ Sessions["sessions/ - Compact engineering session handover logs"]
23
+ Verification["verification/ - Command safety checks and scope tracking"]
24
+ Security["security/ - Path traversal defense, symlink containment, secret redaction"]
25
+ Core["core/ - Workspace discovery, schema migrations, and versioning"]
26
+ Config["config/ - Type-safe data contracts and schema validators"]
27
+ Git["git/ - Read-only Git state and tracked file discovery"]
28
+ Prompts["prompts/ - Onboarding and refresh prompt generators and validators"]
29
+ Portability["portability/ - JSON export/import bundling and validation"]
30
+ Utils["utils/ - Atomic file operations, lockfiles, loggers, and cleanup"]
31
+ Errors["errors/ - Typed error hierarchy and exit code definitions"]
32
+ end
33
+
34
+ subgraph Scripts["scripts/ (Build & Release Automation)"]
35
+ Clean["clean.mjs - Build directory cleanup"]
36
+ ReleaseCheck["release-check.mjs - Pre-release quality gate"]
37
+ Smoke["smoke.mjs - Fresh-install smoke testing"]
38
+ Bench["bench.mjs - Performance and token usage benchmarking"]
39
+ end
40
+
41
+ subgraph Tests["tests/ (Automated Test Suites)"]
42
+ Unit["unit/ - 21 unit test suites for individual modules"]
43
+ Integration["integration/ - 5 integration suites testing full flows and shims"]
44
+ E2E["e2e/ - 2 end-to-end scenario suites testing real CLI execution"]
45
+ Helpers["helpers/ - Fake process runners and tool mocks"]
46
+ end
47
+
48
+ subgraph Docs["docs/ (Project Documentation)"]
49
+ UserDocs["User & Developer Guides (getting-started, architecture, security, etc.)"]
50
+ ReportDir["architecture-report/ - This comprehensive architecture documentation"]
51
+ ImplNotes["implementation/ - Internal design notes and historical ADRs"]
52
+ end
53
+
54
+ Root --> Src
55
+ Root --> Scripts
56
+ Root --> Tests
57
+ Root --> Docs
58
+ ```
59
+
60
+ ---
61
+
62
+ ## 2. Source Code Modules (`src/`) Directory Matrix
63
+
64
+ | Directory | Responsibility | Primary Files | Key Functions / Types |
65
+ |---|---|---|---|
66
+ | **`src/cli/`** | Presentation layer: argument parsing, signal trapping, command routing, and ANSI/ASCII rendering. | `main.ts`, `args.ts`, `run.ts`, `render.ts`, `help.ts` | `run()`, `parseCli()`, `defaultIO()`, `makeStyle()` |
67
+ | **`src/services/`** | Business logic layer: pure asynchronous functions coordinating workspace operations. | `init.ts`, `analysis.ts`, `status.ts`, `doctor.ts`, `agent.ts`, `tasks.ts`, `verify.ts`, `knowledge.ts`, `records.ts`, `portability.ts`, `reset.ts`, `migrate.ts` | `initWorkspace()`, `analyzeWorkspace()`, `getStatus()`, `runDoctor()`, `installAgent()`, `createTask()` |
68
+ | **`src/discovery/`** | Deterministic repository discovery without AI models. | `scan.ts`, `detect.ts`, `commands.ts`, `docs.ts`, `entrypoints.ts`, `ignore.ts`, `cache.ts` | `scanRepository()`, `detectProject()`, `buildContract()`, `detectDocs()`, `discoverEntryPoints()` |
69
+ | **`src/agents/`** | Multi-agent compatibility adapters for instruction files. | `index.ts`, `types.ts`, `shared.ts`, `claude/adapter.ts`, `codex/adapter.ts`, `cursor/adapter.ts`, `copilot/adapter.ts` | `AgentAdapter`, `mergeSection()`, `removeManagedSection()`, `getAgentAdapter()`, `detectAllAgentFiles()` |
70
+ | **`src/integrations/`** | Inspection, planning, and execution of external engineering tools. | `manager.ts`, `exec.ts`, `protect.ts`, `types.ts`, `adapters/agent-skills.ts`, `adapters/graphify.ts`, `adapters/ponytail.ts`, `adapters/omniroute.ts` | `IntegrationManager`, `inspectAll()`, `setupIntegrations()`, `findClaudeCli()`, `createSnapshot()` |
71
+ | **`src/tasks/`** | Task state machine, prompt classification, and completion gate evaluation. | `task.ts`, `routing.ts` | `Task`, `createTaskRecord()`, `transitionTask()`, `evaluateGate()`, `classifyRequest()`, `WORKFLOWS` |
72
+ | **`src/knowledge/`** | Project knowledge facts storage, authority ranking, and staleness validation. | `facts.ts` | `loadFacts()`, `saveFacts()`, `addFact()`, `authorityRank()`, `evaluateStaleness()` |
73
+ | **`src/decisions/`** | Architecture Decision Records (ADRs) in human-readable Markdown. | `decision.ts` | `Decision`, `renderDecision()`, `parseDecision()`, `listDecisions()`, `recordDecision()` |
74
+ | **`src/sessions/`** | Engineering session handoff records. | `session.ts` | `Session`, `saveSession()`, `listSessions()` |
75
+ | **`src/verification/`** | Pre-run safety classification, database protection, and package scoping. | `safety.ts`, `scope.ts` | `classifyCommand()`, `loadTestEnv()`, `captureScope()`, `dirtyFiles()`, `dirtyPackages()` |
76
+ | **`src/security/`** | Secrets redaction and filesystem containment. | `files.ts`, `redact.ts` | `safeReadText()`, `isSensitiveFile()`, `findSecrets()`, `redact()`, `SECRET_PATTERNS` |
77
+ | **`src/core/`** | Workspace discovery, versioned file read/write, and schema migrations. | `workspace.ts`, `versioned.ts`, `migrations.ts`, `version.ts` | `findWorkspaceRoot()`, `requireWorkspace()`, `wsPaths()`, `migrateData()`, `packageVersion()` |
78
+ | **`src/config/`** | Schemas and pure validation functions. | `schemas.ts`, `validate.ts` | `ProjectConfig`, `Fact`, `CommandEntry`, `validateProject()`, `validateFacts()`, `validateCommands()` |
79
+ | **`src/git/`** | Read-only Git state inspection and porcelain status parsing. | `git.ts` | `gitAvailable()`, `getGitState()`, `gitTrackedFiles()`, `parsePorcelainZ()` |
80
+ | **`src/prompts/`** | Generation and validation of onboarding and refresh prompts. | `onboarding.ts`, `refresh.ts`, `requirements.ts` | `buildOnboardingPrompt()`, `buildRefreshPrompt()`, `validatePrompt()`, `ONBOARDING_REQUIREMENTS` |
81
+ | **`src/portability/`** | Bundling and validating portable project knowledge for export/import. | `bundle.ts` | `Bundle`, `parseBundle()`, `isPortablePath()`, `isExportable()` |
82
+ | **`src/utils/`** | Utility layer for atomic I/O, lockfiles, path handling, and child processes. | `fs.ts`, `paths.ts`, `lock.ts`, `proc.ts`, `logger.ts`, `cleanup.ts` | `atomicWriteJson()`, `readTextBounded()`, `isInside()`, `assertNoSymlinkEscape()`, `withLock()` |
83
+ | **`src/errors/`** | Typed error hierarchy, exit code mapping, and user-facing formatting. | `index.ts` | `DevWorkspaceError`, `EXIT`, `formatError()`, `isDevWorkspaceError()` |
84
+
85
+ ---
86
+
87
+ ## 3. Automation Scripts (`scripts/`)
88
+
89
+ | Script | Purpose | Execution Mechanism | Invariant Enforced |
90
+ |---|---|---|---|
91
+ | **`clean.mjs`** | Deletes output directory (`dist/`) before compilation. | `node scripts/clean.mjs dist` | Ensures no stale `.js` or `.d.ts` files linger across builds. |
92
+ | **`release-check.mjs`** | Pre-publish verification gate that tests 12 criteria before release. | `node scripts/release-check.mjs` | Fails if Git tree is dirty, HEAD is untagged, coverage < 90%, docs are missing, or `TODO`/`FIXME`/`stub` markers exist in `src/`. |
93
+ | **`smoke.mjs`** | End-to-end packaging and fresh-install smoke test. | `node scripts/smoke.mjs` | Packs the tarball with `npm pack`, installs in clean temporary directories, tests global and npx invocations, and verifies that `.env` secrets are never leaked. |
94
+ | **`bench.mjs`** | Synthetic performance benchmark. | `node scripts/bench.mjs` | Generates a 3,000-file simulated monorepo and measures execution duration and estimated token counts for `analyze`, `refresh`, and `context`. |
95
+
96
+ ---
97
+
98
+ ## 4. Test Suite Structure (`tests/`)
99
+
100
+ The repository maintains **31 test files** covering 778 test cases:
101
+
102
+ ```
103
+ tests/
104
+ ├── unit/ # Fast, isolated tests for pure functions & domain logic
105
+ │ ├── agent-adapters.test.ts # Tests Claude, Codex, Cursor, and Copilot adapters
106
+ │ ├── agent-prompts.test.ts # Tests onboarding prompt generation & requirements
107
+ │ ├── aux-dirs.test.ts # Tests auxiliary and build folder filtering
108
+ │ ├── claude-plugin-list.test.ts # Tests Claude Code plugin JSON output parsing
109
+ │ ├── discovery-docs-entrypoints.test.ts # Tests doc & entry point discovery
110
+ │ ├── discovery-packages.test.ts # Tests monorepo & package manifest parsing
111
+ │ ├── docs.test.ts # Tests documentation scanning limits
112
+ │ ├── facts.test.ts # Tests authority ranking and fact storage
113
+ │ ├── fs-lock-migrations.test.ts # Tests lockfiles and schema migrations
114
+ │ ├── git-detect.test.ts # Tests git status and porcelain parsing
115
+ │ ├── ignore-scan.test.ts # Tests ignore patterns and directory walk
116
+ │ ├── integrations-core.test.ts # Tests integration manager planning & rollback
117
+ │ ├── integrations-graphify.test.ts # Tests Graphify inspection & version detection
118
+ │ ├── integrations-path.test.ts # Tests persistent PATH additions
119
+ │ ├── integrations-plugins.test.ts # Tests marketplace plugin verification
120
+ │ ├── paths.test.ts # Tests path containment & symlink traversal
121
+ │ ├── proc.test.ts # Tests child process execution & timeouts
122
+ │ ├── records-bundle.test.ts # Tests ADRs, sessions, and portability bundles
123
+ │ ├── release-hygiene.test.ts # Tests absence of TODO/FIXME markers in production
124
+ │ ├── routing.test.ts # Tests task request classification & workflows
125
+ │ ├── security.test.ts # Tests safeReadText, secret redaction, and symlinks
126
+ │ ├── staleness.test.ts # Tests fact staleness detection on file changes
127
+ │ ├── tasks.test.ts # Tests task lifecycle & completion gate
128
+ │ └── verification-gate.test.ts # Tests command safety & test environment gates
129
+ │
130
+ ├── integration/ # Multi-component flows using fake process runners
131
+ │ ├── acceptance-022.test.ts # End-to-end integration acceptance suite
132
+ │ ├── discovery-monorepo.test.ts # Tests complex monorepo discovery scenarios
133
+ │ ├── flows.test.ts # Tests full init -> analyze -> task -> status flows
134
+ │ ├── integrations-processes.test.ts # Tests integrations with simulated child processes
135
+ │ └── progressive-context.test.ts # Tests tiered context retrieval
136
+ │
137
+ ├── e2e/ # Real CLI invocations driving compiled dist/
138
+ │ ├── reset.test.ts # Tests reset safety, confirmation, and plans
139
+ │ └── scenarios.test.ts # Full lifecycle CLI scenarios in real temp projects
140
+ │
141
+ └── helpers/ # Reusable test harnesses
142
+ ├── fakeRunner.ts # Deterministic process mock runner
143
+ ├── fakeTools.ts # Mock implementations of claude, graphify, npm
144
+ └── index.ts # Temp workspace builders & test assertions
145
+ ```
146
+
147
+ ---
148
+
149
+ *Continue to [Chapter 6: Command Reference](./06-command-reference.md) for detailed documentation of all 16 CLI commands.*
150
+