toolflow 3.1.4

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 (49) hide show
  1. package/.github/workflows/ci.yml +31 -0
  2. package/README.md +106 -0
  3. package/README_zh.md +109 -0
  4. package/docs/reports/ADVANCED_EVOLUTION_REPORT.md +44 -0
  5. package/docs/reports/AUDIT_AND_OPTIMIZATION_REPORT.md +645 -0
  6. package/docs/reports/COLD_START_REVIEW_EVOLUTION.md +51 -0
  7. package/docs/reports/DEEP_ECOSYSTEM_EVOLUTION.md +43 -0
  8. package/docs/reports/MEMORY.md +18 -0
  9. package/docs/reports/MICHAEL_DISPATCH_RESULT.md +36 -0
  10. package/docs/reports/OPENSOURCE_INTEGRATION_REPORT.md +43 -0
  11. package/docs/reports/PHASE_1_OPTIMIZATION_REPORT.md +87 -0
  12. package/docs/reports/PHASE_2_OPTIMIZATION_REPORT.md +50 -0
  13. package/docs/reports/PHASE_3_OPTIMIZATION_REPORT.md +24 -0
  14. package/docs/reports/PHASE_4_OPTIMIZATION_REPORT.md +28 -0
  15. package/docs/reports/REPORT_TO_MICHAEL.md +101 -0
  16. package/docs/reports/SIGNOFF_AND_RELEASE_REPORT.md +85 -0
  17. package/docs/reports/STAFF_ASSIGNMENTS.md +26 -0
  18. package/docs/reports/TASK_ASSIGNMENTS.md +59 -0
  19. package/docs/reports/V1_6_0_EVOLUTION_REPORT.md +48 -0
  20. package/docs/reports/V1_9_0_HOTFIX_REPORT.md +30 -0
  21. package/docs/reports/V2_0_0_RELEASE_REPORT.md +18 -0
  22. package/docs/reports/V2_2_0_ZERO_SPECIALIZATION_REPORT.md +24 -0
  23. package/docs/reports/V2_3_0_EVOLUTION_REPORT.md +12 -0
  24. package/ecosystem_taxonomy.json +798 -0
  25. package/package.json +46 -0
  26. package/src/blast_radius.ts +302 -0
  27. package/src/deep_ecosystem.ts +523 -0
  28. package/src/degradation_matrix.ts +180 -0
  29. package/src/dehydrator.ts +532 -0
  30. package/src/ecosystem_taxonomy.json +803 -0
  31. package/src/engine.ts +1510 -0
  32. package/src/i18n.ts +89 -0
  33. package/src/index.ts +983 -0
  34. package/src/json_extractor.ts +57 -0
  35. package/src/memory.ts +151 -0
  36. package/src/prompts_manager.ts +262 -0
  37. package/src/review_isolation.ts +188 -0
  38. package/src/state.ts +810 -0
  39. package/src/taxonomy.ts +580 -0
  40. package/src/types.ts +341 -0
  41. package/src/ui.ts +1036 -0
  42. package/src/worker_orchestrator.ts +60 -0
  43. package/tests/challenger_stress_harness.ts +265 -0
  44. package/tests/monorepo_multilang_stress.ts +404 -0
  45. package/tests/sandbox_e2e.ts +167 -0
  46. package/tests/test_json_extractor.ts +44 -0
  47. package/tests/test_modules_1_to_4.ts +106 -0
  48. package/tests/test_suite.ts +1689 -0
  49. package/tsconfig.json +17 -0
@@ -0,0 +1,645 @@
1
+ # ToolFlow: Comprehensive Architectural Audit, Static/Runtime Risk Analysis & Optimization Roadmap
2
+
3
+ **Document Version**: 1.0.0 (Master Publication Release)
4
+ **Target Codebase**: `C:\Users\Jason\.pi\agent\extensions\toolflow`
5
+ **Auditor**: Lead Architectural Synthesis Worker (`teamwork_preview_worker`)
6
+ **Audit Date**: September 2026
7
+ **Integrity Level**: Full Static & Dynamic Verification (No Facades / Ground-Truth Primacy)
8
+
9
+ ---
10
+
11
+ ## 1. Executive Summary & Overall Architecture Health Score
12
+
13
+ ### 1.1 Executive Assessment
14
+ ToolFlow is an enterprise-grade orchestration and lifecycle management extension for the Pi Coding Agent ecosystem. Its architectural vision is uniquely ambitious: unifying a **4-Layer Capability Taxonomy** (Infrastructure, Perception, Orchestration, Review Guard), **Kahn Topological DAG Stage Planning**, **Blast Radius Sandbox Containment**, **Context Dehydration with SHA-256 Physical Gates**, and **Interactive Monospace TUI Navigation**.
15
+
16
+ However, a deep forensic static and runtime probe reveals substantial discrepancies between the conceptual architectural specification and the concrete TypeScript runtime implementation. Critical subsystem disconnections (e.g. `degradation_matrix.ts` and `memory.ts` existing as uninvoked dead code), catastrophic runtime property name typos in multi-agent dispatch (`worker_orchestrator.ts`), path matching bugs in sandbox enforcement (`blast_radius.ts`), side-effect state mutations in read-only query commands (`/sop`), and double-width CJK monospace alignment failures in ASCII receipt rendering collectively degrade the production readiness of the system.
17
+
18
+ ```
19
+ +-----------------------------------------------------------------------------------+
20
+ | OVERALL ARCHITECTURAL HEALTH |
21
+ | |
22
+ | Composite Health Score: 56.7 / 100 (Grade: C+) |
23
+ | Status: Action Required Before Release |
24
+ | |
25
+ | [!] Critical Vulnerabilities : 5 confirmed (P0 Hotfix Required) |
26
+ | [!] High-Severity Risks : 21 confirmed (P1 Next Sprint) |
27
+ | [~] Medium-Severity Defects : 24 confirmed (P2 Optimization) |
28
+ | [*] Low-Severity Polish Items: 6 confirmed (P3 Polish) |
29
+ | ----------------------------------------------------------------------------- |
30
+ | Total Cataloged Findings : 56 Verified Issues across 11 Core Modules |
31
+ +-----------------------------------------------------------------------------------+
32
+ ```
33
+
34
+ ---
35
+
36
+ ### 1.2 6-Dimensional Radar Breakdown
37
+
38
+ ```
39
+ [0-Token & Efficiency]
40
+ 5.5 / 10
41
+ / \
42
+ / \
43
+ / \
44
+ [Security & Containment]-------[TypeScript Type Safety]
45
+ 4.8 / 10 / \ 5.8 / 10
46
+ / \
47
+ / \
48
+ [Resilience & Recovery]-------------[Cross-Platform Parity]
49
+ 4.2 / 10 \ / 4.5 / 10
50
+ \ /
51
+ \ /
52
+ \ /
53
+ [UI/TUI Monospace]
54
+ 4.0 / 10
55
+ ```
56
+
57
+ | Dimension | Score | Primary Architectural Risk & Vulnerability Summary |
58
+ |---|:---:|---|
59
+ | **0-Token & Efficiency Compliance** | **5.5 / 10** | `memory.ts` lacks rolling window compaction, resulting in unbounded prompt ballooning. Global taxonomy paths hardcoded to `os.homedir()`. Stale cache invalidation ignores filesystem prompt changes. |
60
+ | **TypeScript Type Safety & Soundness** | **5.8 / 10** | `tsc --noEmit` fails out-of-the-box (`TS2304: Cannot find name 'CapabilityItem'`, `TS7006: implicit any`, `TS2339: missing properties`). Dual schema ambiguity (`expectedArtifact` vs `expectedArtifacts`). |
61
+ | **Cross-Platform & Windows Parity** | **4.5 / 10** | Windows case-sensitivity and drive letter casing mismatches cause false sandbox blocks. Git porcelain quotes non-ASCII Chinese paths. Hardcoded Windows `start` command fails on Linux/macOS. |
62
+ | **Resilience, Degradation & Self-Healing** | **4.2 / 10** | Querying `/sop` mutates `retryCount`, causing premature circuit breaks. `GracefulDegradationMatrix` is dead code. Incomplete rollback leaves orphan broken files on disk. `execSync` blocks event loop for 15s. |
63
+ | **Security & Blast Radius Containment** | **4.8 / 10** | Glob patterns (`src/**`) are stored in a JavaScript `Set` and checked via strict `Set.has()`, falsely blocking multi-file writes. Symlink and `..` traversals bypass `.git` protection. Shell tool calls (`bash`/`powershell`) are uninspected. |
64
+ | **UI/TUI Monospace Precision & Usability** | **4.0 / 10** | JavaScript `padEnd()` calculates UTF-16 code units rather than visible monospace columns, causing CJK double-width table skew (+13 columns). Top-right box corner offset by 1 column. Plan B toggle keybinding missing in navigator. |
65
+
66
+ ---
67
+
68
+ ## 2. 100% Core TypeScript Module Audit Breakdown
69
+
70
+ Every single core TypeScript module within `C:\Users\Jason\.pi\agent\extensions\toolflow` was subjected to line-by-line static inspection and execution tracing:
71
+
72
+ ```
73
+ ┌────────────────────────┬───────┬──────────────────────────────────────────┬────────────────────────┐
74
+ │ Module Name │ Lines │ Core Responsibility │ Audit Status │
75
+ ├────────────────────────┼───────┼──────────────────────────────────────────┼────────────────────────┤
76
+ │ engine.ts │ 1,132 │ Kahn DAG Planner, Blueprint Synthesizer │ 4 Findings (1 High) │
77
+ │ taxonomy.ts │ 486 │ 4-Layer Capability Taxonomy, Project Git │ 7 Findings (3 High) │
78
+ │ dehydrator.ts │ 152 │ Context Dehydration, AST Summaries │ 5 Findings (2 High) │
79
+ │ blast_radius.ts │ 102 │ Sandbox Boundary & Path Interception │ 7 Findings (1 Crit) │
80
+ │ degradation_matrix.ts │ 158 │ 3-Tier Tool Fallback Matrix │ 5 Findings (1 Crit) │
81
+ │ memory.ts │ 120 │ Architectural Episodic Memory Manager │ 4 Findings (1 Crit) │
82
+ │ ui.ts │ 680 │ Monospace TUI Navigator, DAG Visualizer │ 8 Findings (1 Crit) │
83
+ │ state.ts │ 528 │ Session State Machine & Physical Gates │ 6 Findings (2 High) │
84
+ │ types.ts │ 244 │ Data Contracts, Capability Enums │ 2 Findings (1 Med) │
85
+ │ index.ts │ 420 │ Extension Lifecycle & Hook Interceptor │ 4 Findings (2 High) │
86
+ │ worker_orchestrator.ts │ 45 │ Multi-Agent Wave Bundle Compiler │ 2 Findings (1 Crit) │
87
+ └────────────────────────┴───────┴──────────────────────────────────────────┴────────────────────────┘
88
+ ```
89
+
90
+ ### Module Breakdown Summary
91
+
92
+ 1. **`engine.ts`**:
93
+ - **Strengths**: Robust Kahn topological sorting implementation with degree calculation and wave decomposition. Rich keyword heuristics for project archetype detection.
94
+ - **Vulnerabilities**: Orphan/phantom dependencies are silently swallowed rather than rejected, causing downstream stages to run prematurely in Wave 0. Disconnected graph cycles cause total pipeline fallback to sequential raw array order without notifying callers. Missing `CapabilityItem` import breaks compilation.
95
+ 2. **`taxonomy.ts`**:
96
+ - **Strengths**: Innovative 4-tier hierarchy (Utility, Perception, Orchestration, Review Guard) with automatic ecosystem scanning.
97
+ - **Vulnerabilities**: Global paths hardcoded to `os.homedir()`. Cache invalidation only fingerprints `settings.json`, ignoring dynamic additions to `prompts/` and `node_modules/`. Regex keyword ordering misclassifies verification tools as perception tools. Clean repositories falsely report 3 active modified files.
98
+ 3. **`dehydrator.ts`**:
99
+ - **Strengths**: Compact AST symbol extraction and SHA-256 fingerprinting for clean context handoffs.
100
+ - **Vulnerabilities**: LRU run pruning relies on directory `mtimeMs` (which is stale on NTFS/ext4) and lacks byte-level disk quotas, risking active run deletion and disk exhaustion. Large payload synchronous writes risk V8 heap OOM. 4KB truncation misses tail exports.
101
+ 4. **`blast_radius.ts`**:
102
+ - **Strengths**: Multi-stage scope boundary tracking and sensitive file regex blacklists (`.env`, `package-lock.json`, `.git`).
103
+ - **Vulnerabilities**: Wildcard glob patterns (`src/**`) are checked via `Set.has(resolved)` strict string equality, causing 100% false blocks on multi-file implementation stages. Windows case-insensitivity and drive letter casing cause false rejections. Symlinks and `..` path traversal bypass `.git` restrictions. Shell commands (`bash`, `powershell`) bypass guardrails.
104
+ 5. **`degradation_matrix.ts`**:
105
+ - **Strengths**: Well-conceived 3-tier capability degradation matrix (Primary $\to$ Secondary $\to$ Minimal Native).
106
+ - **Vulnerabilities**: Completely disconnected from runtime (`index.ts` and `engine.ts` never invoke it). Design stage tool pruning blocks `write`, preventing the agent from creating `docs/design.md` (deadlock). Hardcoded `bash` fallback fails on Windows systems without Git Bash.
107
+ 6. **`memory.ts`**:
108
+ - **Strengths**: Clean episodic lesson persistence structure.
109
+ - **Vulnerabilities**: Completely orphaned at runtime (never called during task flow). Unbounded memory growth injects thousands of tokens per prompt. Stale lessons can conflict with live disk truth (ground-truth primacy violation). Non-atomic JSON writes risk data corruption.
110
+ 7. **`ui.ts`**:
111
+ - **Strengths**: Comprehensive TUI navigation with stage DAG rendering, interactive option selection, and delivery receipts.
112
+ - **Vulnerabilities**: Monospace string width calculation in `renderValueReceipt` uses `padEnd()`, causing severe CJK double-width box distortion (+13 column overflow). Top border arithmetic is off by 1 column. Plan B toggle keybinding is missing in navigator. Instruction footer is truncated on 80-column terminals. Backspace splits Unicode surrogate pairs.
113
+ 8. **`state.ts`**:
114
+ - **Strengths**: Physical gate verification via SHA-256 hashes, AST inspection, and deterministic command execution.
115
+ - **Vulnerabilities**: `verifyStageArtifacts` mutates `retryCount`, causing read-only status checks (`/sop`) to burn retries and trigger circuit breaking. Non-atomic file persistence risks corrupting `blueprint_state.json`. Incomplete rollback leaves orphan new files on disk. Synchronous `execSync` freezes the Node.js event loop for up to 15s.
116
+ 9. **`types.ts`**:
117
+ - **Strengths**: Exhaustive type definitions for stages, blueprints, taxonomies, and metrics.
118
+ - **Vulnerabilities**: `EcosystemTaxonomy` lacks fields for MCP tools and standalone tools. `ProjectType` and `PackageManager` unions omit Bun, Deno, Gradle, and Maven.
119
+ 10. **`index.ts`**:
120
+ - **Strengths**: Clean Pi extension lifecycle management with event hooks for `turn_end`, `tool_call`, and custom slash commands.
121
+ - **Vulnerabilities**: `turn_end` async handler lacks top-level `try...catch`, risking unhandled promise rejections. Tool scoping is not restored to baseline on rollback/reset. Disconnected degradation and memory subsystems.
122
+ 11. **`worker_orchestrator.ts`**:
123
+ - **Strengths**: Clean DAG wave decomposition for parallel multi-agent dispatch.
124
+ - **Vulnerabilities**: Uses `s.id` instead of `s.stageId` and `s.description` instead of `s.coreObjective`, causing subagent prompts to render with `"undefined"` and corrupting the stage map. Concurrency is unbounded, risking API rate limiting and git lock collisions.
125
+
126
+ ---
127
+
128
+ ## 3. Deep-Dive Edge-Case Vulnerability Matrix (4 Core Pillars)
129
+
130
+ ### Pillar 1: Blast Radius & Boundary Containment
131
+
132
+ ```
133
+ +----------------------------------------------------------------------------------------------------+
134
+ | BLAST RADIUS VULNERABILITY MATRIX |
135
+ +----------------------+----------------------------+------------------------------------------------+
136
+ | Vector | Vulnerable Code Pattern | Concrete Exploitation / Failure Scenario |
137
+ +----------------------+----------------------------+------------------------------------------------+
138
+ | Glob String Matching | Set.has(resolvedPath) | targetPatterns: ["src/**"] converts to literal |
139
+ | | | path string. Set.has("C:\repo\src\util.ts") is |
140
+ | | | false. Legitimate multi-file edits BLOCKED. |
141
+ +----------------------+----------------------------+------------------------------------------------+
142
+ | Windows Case & Drive | Set.has(exactCaseResolved) | C:\Repo vs c:\repo or src/Main.ts vs |
143
+ | | | src/main.ts evaluates to false. False blocks. |
144
+ +----------------------+----------------------------+------------------------------------------------+
145
+ | Symlink Traversal | path.resolve() lexical only| Symlink src/secret.txt -> .env. Base name is |
146
+ | | without fs.realpathSync | secret.txt; bypasses .env regex guard. |
147
+ +----------------------+----------------------------+------------------------------------------------+
148
+ | .. Path Traversal | /^\.git/ relative regex | Path src/../../.git/config produces relative |
149
+ | | | ..\..\.git\config. Regex fails. Bypassed. |
150
+ +----------------------+----------------------------+------------------------------------------------+
151
+ | NTFS 8.3 & ADS | /^package-lock\.json$/ | Writes to PACKAG~1.JSO or index.ts::$DATA |
152
+ | | regex exact match | bypass basename regex filters. |
153
+ +----------------------+----------------------------+------------------------------------------------+
154
+ | Shell Bypass | Intercepts write/edit only | Agent executes bash/powershell command |
155
+ | | | echo EVIL > .env. Guard completely bypassed. |
156
+ +----------------------+----------------------------+------------------------------------------------+
157
+ | Whitelist Override | Allowed paths checked | If expectedArtifact is .env, whitelist lookup |
158
+ | | before critical config | returns true, permitting overwrite of .env. |
159
+ +----------------------+----------------------------+------------------------------------------------+
160
+ ```
161
+
162
+ ---
163
+
164
+ ### Pillar 2: Context Dehydration & Storage Lifecycle
165
+
166
+ ```
167
+ +----------------------------------------------------------------------------------------------------+
168
+ | DEHYDRATION & STORAGE VULNERABILITY MATRIX |
169
+ +----------------------+----------------------------+------------------------------------------------+
170
+ | Vector | Vulnerable Code Pattern | Concrete Exploitation / Failure Scenario |
171
+ +----------------------+----------------------------+------------------------------------------------+
172
+ | LRU Run Eviction | fs.statSync(dir).mtimeMs | Modifying files inside a run directory does not|
173
+ | | with fixed maxAgeMs | update folder mtime. Active run deleted. |
174
+ +----------------------+----------------------------+------------------------------------------------+
175
+ | Disk Byte Quota | Directory count limit only | 10 runs with 500MB verbose logs consume 5GB+ |
176
+ | | (maxRuns = 10) | of disk space with no byte ceiling. |
177
+ +----------------------+----------------------------+------------------------------------------------+
178
+ | V8 Heap Exhaustion | Synchronous string writes | 500MB+ compiler output passed to writeFileSync |
179
+ | | of rawLogs payload | triggers ERR_STRING_TOO_LONG / heap OOM crash. |
180
+ +----------------------+----------------------------+------------------------------------------------+
181
+ | Silent Disk Errors | try { writeFileSync } | ENOSPC / EACCES errors swallowed; dehydrator |
182
+ | | catch (_) {} | returns valid path to non-existent file. |
183
+ +----------------------+----------------------------+------------------------------------------------+
184
+ | AST Truncation | content.slice(0, 4096) | Symbols and exports defined after line 100 |
185
+ | | and shallow regexes | are omitted from stage handoff summaries. |
186
+ +----------------------+----------------------------+------------------------------------------------+
187
+ ```
188
+
189
+ ---
190
+
191
+ ### Pillar 3: Degradation, Self-Healing & Concurrency
192
+
193
+ ```
194
+ +----------------------------------------------------------------------------------------------------+
195
+ | DEGRADATION & CONCURRENCY VULNERABILITY MATRIX |
196
+ +----------------------+----------------------------+------------------------------------------------+
197
+ | Vector | Vulnerable Code Pattern | Concrete Exploitation / Failure Scenario |
198
+ +----------------------+----------------------------+------------------------------------------------+
199
+ | Query Side Effects | verifyStageArtifacts() | User runs /sop twice to check progress. Each |
200
+ | | mutates state.retryCount | call increments retryCount. Trips breaker! |
201
+ +----------------------+----------------------------+------------------------------------------------+
202
+ | Subsystem Disconnect | Matrix & Memory never | GracefulDegradationMatrix and MemoryManager |
203
+ | | instantiated in index.ts | are dead code. Zero runtime resilience impact. |
204
+ +----------------------+----------------------------+------------------------------------------------+
205
+ | Kahn DAG Cycles | hasCycles returns fallback | Cycles pack all stages into wave 0. Pipeline |
206
+ | | single wave [stages] | executes broken cyclic stages with no warning. |
207
+ +----------------------+----------------------------+------------------------------------------------+
208
+ | Phantom Dependencies | Undefined stageId skipped | Dependent stage gets inDegree = 0, runs in |
209
+ | | in adjacency construction | Wave 0 before prerequisites exist. |
210
+ +----------------------+----------------------------+------------------------------------------------+
211
+ | Incomplete Rollback | Restores fileContents but | Newly created broken files are not deleted; |
212
+ | | does not unlink new files | corrupt subsequent compiler / test retries. |
213
+ +----------------------+----------------------------+------------------------------------------------+
214
+ | Event Loop Freezing | execSync() blocking with | Physical gate runs tests synchronously; Pi |
215
+ | | 15000ms timeout | TUI and terminal freeze for up to 15 seconds. |
216
+ +----------------------+----------------------------+------------------------------------------------+
217
+ ```
218
+
219
+ ---
220
+
221
+ ### Pillar 4: UI/TUI Display, Monospace Alignment & Usability
222
+
223
+ ```
224
+ +----------------------------------------------------------------------------------------------------+
225
+ | UI/TUI & USABILITY VULNERABILITY MATRIX |
226
+ +----------------------+----------------------------+------------------------------------------------+
227
+ | Vector | Vulnerable Code Pattern | Concrete Exploitation / Failure Scenario |
228
+ +----------------------+----------------------------+------------------------------------------------+
229
+ | CJK Monospace Skew | metrics.task.padEnd(46) | Chinese characters count as 1 code unit but 2 |
230
+ | | on string with CJK text | terminal columns. Border overflows by 13 cols. |
231
+ +----------------------+----------------------------+------------------------------------------------+
232
+ | Asymmetric Box Math | topBorder: innerWidth + 3 | Top right corner ╮ indented by 1 space |
233
+ | | botBorder: innerWidth + 4 | relative to vertical side border │. |
234
+ +----------------------+----------------------------+------------------------------------------------+
235
+ | Missing Plan B Key | Keys '1'/'2' map solely to | User cannot switch between Agile Plan A and |
236
+ | | slot option selection | Industrial Plan B in interactive navigator. |
237
+ +----------------------+----------------------------+------------------------------------------------+
238
+ | Viewport Truncation | 86-column footer on | [Enter] and [e] shortcuts truncated on |
239
+ | | 80-column standard viewports| standard 80x24 terminal windows. |
240
+ +----------------------+----------------------------+------------------------------------------------+
241
+ | Unicode Splitting | inputTask.slice(0, -1) | Backspacing an emoji splits surrogate pairs, |
242
+ | | on raw JS string | corrupting text with replacement chars . |
243
+ +----------------------+----------------------------+------------------------------------------------+
244
+ | ANSI Markdown Leaks | renderUnicodeDAG() embeds | Exported BLUEPRINT.md contains raw ^[[1m |
245
+ | | raw \x1b escapes in text | escape codes when viewed in external editors. |
246
+ +----------------------+----------------------------+------------------------------------------------+
247
+ ```
248
+
249
+ ---
250
+
251
+ ## 4. Comprehensive, Prioritized Finding Catalog (All 56 Findings)
252
+
253
+ ### Critical Findings (P0 - Immediate Hotfix)
254
+
255
+ ---
256
+
257
+ #### [CRIT-01] `worker_orchestrator.ts:22,33` - Runtime Property Name Typos in Multi-Agent Bundle Compilation
258
+ - **File & Lines**: `worker_orchestrator.ts:21-35`
259
+ - **Symbols**: `MultiAgentWorkerOrchestrator.compileWaveBundles`
260
+ - **Failure Scenario**:
261
+ `BlueprintStage` interface defines `stageId: string` and `coreObjective: string`. However, `compileWaveBundles` accesses `s.id` and `s.description`.
262
+ 1. `stageMap.set(s.id, s)` creates a Map with a single key `undefined`.
263
+ 2. `executionPrompt` formats as `"[Stage: Title] undefined -> 交付产物: ..."`.
264
+ All worker subagents receive broken prompts lacking their primary mission objective.
265
+ - **Trigger Input**:
266
+ `MultiAgentWorkerOrchestrator.compileWaveBundles(stages)`
267
+ - **Ready-to-Apply Code Diff**:
268
+ ```diff
269
+ --- a/worker_orchestrator.ts
270
+ +++ b/worker_orchestrator.ts
271
+ @@ -21,3 +21,3 @@ export class MultiAgentWorkerOrchestrator {
272
+ const stageMap = new Map<string, BlueprintStage>();
273
+ - stages.forEach(s => stageMap.set(s.id, s));
274
+ + stages.forEach(s => stageMap.set(s.stageId, s));
275
+
276
+ @@ -32,3 +32,3 @@ export class MultiAgentWorkerOrchestrator {
277
+ targetArtifacts: artifacts,
278
+ - executionPrompt: "[Stage: " + s.title + "] " + s.description + " -> 交付产物: " + artifacts.join(", ")
279
+ + executionPrompt: "[Stage: " + s.title + "] " + (s.coreObjective || s.title) + " -> 交付产物: " + artifacts.join(", ")
280
+ };
281
+ ```
282
+
283
+ ---
284
+
285
+ #### [CRIT-02] `blast_radius.ts:36-38, 78` - Wildcard Glob Matching Failure in Allowed Scope
286
+ - **File & Lines**: `blast_radius.ts:36-38, 78`
287
+ - **Symbols**: `BlastRadiusGuard.updateAllowedScope`, `BlastRadiusGuard.verifyToolCall`
288
+ - **Failure Scenario**:
289
+ `targetPatterns: ["src/**"]` is resolved via `path.resolve(cwd, "src/**")` into literal string `C:\repo\src\**` and stored in `this.allowedPaths: Set<string>`.
290
+ When the agent writes to `src/utils.ts`, `this.allowedPaths.has("C:\\repo\\src\\utils.ts")` executes strict string equality and returns `false`.
291
+ Legitimate multi-file implementation tasks are 100% blocked as unauthorized blast radius violations.
292
+ - **Trigger Input**:
293
+ Stage with `targetPatterns: ["src/**"]` attempting to write `src/utils.ts`.
294
+ - **Ready-to-Apply Code Diff**:
295
+ ```diff
296
+ --- a/blast_radius.ts
297
+ +++ b/blast_radius.ts
298
+ @@ -9,2 +9,3 @@ export class BlastRadiusGuard {
299
+ - private allowedPaths: Set<string> = new Set();
300
+ + private allowedExactPaths: Set<string> = new Set();
301
+ + private allowedGlobPatterns: string[] = [];
302
+ @@ -28,3 +29,4 @@ export class BlastRadiusGuard {
303
+ public updateAllowedScope(stage: BlueprintStage, cwd: string = process.cwd()) {
304
+ - this.allowedPaths.clear();
305
+ + this.allowedExactPaths.clear();
306
+ + this.allowedGlobPatterns = [];
307
+ if (stage.expectedArtifact) {
308
+ - this.allowedPaths.add(path.resolve(cwd, stage.expectedArtifact));
309
+ + this.allowedExactPaths.add(this.normalizePath(path.resolve(cwd, stage.expectedArtifact)));
310
+ }
311
+ if (stage.expectedArtifacts) {
312
+ - stage.expectedArtifacts.forEach(p => this.allowedPaths.add(path.resolve(cwd, p)));
313
+ + stage.expectedArtifacts.forEach(p => this.allowedExactPaths.add(this.normalizePath(path.resolve(cwd, p))));
314
+ }
315
+ if (stage.targetPatterns) {
316
+ - stage.targetPatterns.forEach(p => this.allowedPaths.add(path.resolve(cwd, p)));
317
+ + this.allowedGlobPatterns = stage.targetPatterns.map(p => p.replace(/\\/g, "/"));
318
+ }
319
+ }
320
+ @@ -78,1 +80,3 @@ export class BlastRadiusGuard {
321
+ - if (this.allowedPaths.size > 0 && !this.allowedPaths.has(resolved)) {
322
+ + const isAllowed = this.allowedExactPaths.has(resolved) ||
323
+ + this.allowedGlobPatterns.some(pattern => this.matchGlob(relative, pattern));
324
+ + if ((this.allowedExactPaths.size > 0 || this.allowedGlobPatterns.length > 0) && !isAllowed) {
325
+ ```
326
+
327
+ ---
328
+
329
+ #### [CRIT-03] `degradation_matrix.ts:1-158` - Graceful Degradation Matrix Runtime Dead Code
330
+ - **File & Lines**: `degradation_matrix.ts:1-158`, `index.ts:10`, `engine.ts:942`
331
+ - **Symbols**: `GracefulDegradationMatrix`
332
+ - **Failure Scenario**:
333
+ The entire degradation matrix is imported in `index.ts:10` but never instantiated or wired into stage execution. When tools fail or are absent in minimal environments (e.g. missing `edit` tool), the system crashes rather than degrading to `write`.
334
+ - **Trigger Input**:
335
+ Run ToolFlow in an environment lacking `edit` tool.
336
+ - **Ready-to-Apply Code Diff**:
337
+ ```diff
338
+ --- a/index.ts
339
+ +++ b/index.ts
340
+ @@ -10,1 +10,1 @@ import { GracefulDegradationMatrix } from "./degradation_matrix.js";
341
+ +const degradationMatrix = new GracefulDegradationMatrix();
342
+ @@ -345,2 +345,4 @@ export default function (pi: ExtensionContext) {
343
+ const nextStage = state.blueprint.stages[state.currentStageIndex];
344
+ + const prunedTools = degradationMatrix.resolvePrunedToolsForStage(nextStage.stageId, nextStage.allowedTools);
345
+ + applyToolScoping(prunedTools, pi);
346
+ ```
347
+
348
+ ---
349
+
350
+ #### [CRIT-04] `memory.ts:1-120` - Architectural Memory Manager Orphaned Subsystem
351
+ - **File & Lines**: `memory.ts:1-120`, `index.ts:1-420`, `engine.ts:1-1132`
352
+ - **Symbols**: `CodebaseMemoryManager`
353
+ - **Failure Scenario**:
354
+ `CodebaseMemoryManager` is never called by `index.ts` or `engine.ts`. Self-learning lessons, guardrails, and architectural conventions are never persisted or injected into prompt context.
355
+ - **Trigger Input**:
356
+ Run complete pipeline. `.pi/toolflow/memory/architecture_memory.json` is never generated.
357
+ - **Ready-to-Apply Code Diff**:
358
+ ```diff
359
+ --- a/index.ts
360
+ +++ b/index.ts
361
+ @@ -11,0 +11,1 @@
362
+ +import { CodebaseMemoryManager } from "./memory.js";
363
+ @@ -45,0 +46,1 @@
364
+ +const memoryManager = new CodebaseMemoryManager();
365
+ @@ -190,0 +192,3 @@
366
+ + const memoryContext = memoryManager.getPromptContextInjection();
367
+ + if (memoryContext) diagnosis.projectBackground += `\n${memoryContext}`;
368
+ ```
369
+
370
+ ---
371
+
372
+ #### [CRIT-05] `ui.ts:9-43` - CJK Monospace Distortion in Value Delivery Receipt
373
+ - **File & Lines**: `ui.ts:9-43`
374
+ - **Symbols**: `renderValueReceipt`
375
+ - **Failure Scenario**:
376
+ `metrics.task.slice(0, 44).padEnd(46)` calculates UTF-16 code units. In Chinese text, each character has display width 2. With 15 Chinese characters, visible length is 30, and `padEnd` appends 31 spaces, expanding total box width to 77 columns (+13 overflow) and destroying monospace border alignment.
377
+ - **Trigger Input**:
378
+ `renderValueReceipt({ task: "开发智能客户服务支持中心前端页面", ... })`
379
+ - **Ready-to-Apply Code Diff**:
380
+ ```diff
381
+ --- a/ui.ts
382
+ +++ b/ui.ts
383
+ @@ -2,1 +2,1 @@
384
+ -import { truncateToWidth } from "@earendil-works/pi-tui";
385
+ +import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
386
+ @@ -8,0 +8,7 @@
387
+ +function padToVisibleWidth(content: string, targetWidth: number): string {
388
+ + const truncated = truncateToWidth(content, targetWidth, "", true);
389
+ + const visW = visibleWidth(truncated);
390
+ + const padCount = Math.max(0, targetWidth - visW);
391
+ + return truncated + " ".repeat(padCount);
392
+ +}
393
+ +
394
+ @@ -28,5 +35,5 @@ export function renderValueReceipt(metrics: {
395
+ - rows.push(`| 任务目标 : ${metrics.task.slice(0, 44).padEnd(46)}|`);
396
+ - rows.push(`| 蓝图编号 : ${metrics.blueprintId.padEnd(46)}|`);
397
+ - rows.push(`| 阶段总数 : ${`${metrics.stageCount} 个阶段已全部闭环`.padEnd(46)}|`);
398
+ - rows.push(`| 交付耗时 : ${`${dur}s`.padEnd(46)}|`);
399
+ - rows.push(`| Token 效率 : ${`~${saved} 冗余已被裁剪`.padEnd(46)}|`);
400
+ + rows.push(`| ${padToVisibleWidth(`任务目标 : ${metrics.task}`, w - 2)} |`);
401
+ + rows.push(`| ${padToVisibleWidth(`蓝图编号 : ${metrics.blueprintId}`, w - 2)} |`);
402
+ + rows.push(`| ${padToVisibleWidth(`阶段总数 : ${metrics.stageCount} 个阶段已全部闭环`, w - 2)} |`);
403
+ + rows.push(`| ${padToVisibleWidth(`交付耗时 : ${dur}s`, w - 2)} |`);
404
+ + rows.push(`| ${padToVisibleWidth(`Token 效率 : ~${saved} 冗余已被裁剪`, w - 2)} |`);
405
+ ```
406
+
407
+ ---
408
+
409
+ ### High-Severity Findings (P1 - Core Remediation)
410
+
411
+ #### [HIGH-01] `engine.ts:153-156` - Kahn DAG Phantom Dependency Swallowing
412
+ - **File & Lines**: `engine.ts:153-156`
413
+ - **Symbols**: `planDAGWaves`
414
+ - **Mechanism**: When `s.dependsOn` references a non-existent or renamed stage, the dependency is silently skipped without incrementing in-degree. The dependent stage executes prematurely in Wave 0.
415
+ - **Remediation Diff**:
416
+ ```diff
417
+ --- a/engine.ts
418
+ +++ b/engine.ts
419
+ @@ -154,3 +154,4 @@ export function planDAGWaves(stages: BlueprintStage[]): DAGPlanResult {
420
+ for (const dep of deps) {
421
+ if (!stageMap.has(dep)) {
422
+ + throw new Error(`[ToolFlow DAG Error] Stage '${s.stageId}' depends on unknown stage '${dep}'`);
423
+ continue;
424
+ ```
425
+
426
+ #### [HIGH-02] `engine.ts:195-207` - Total Pipeline Degradation on Disconnected Cycles
427
+ - **File & Lines**: `engine.ts:195-207`
428
+ - **Symbols**: `planDAGWaves`
429
+ - **Mechanism**: On cycle detection, all stages are packed into a single fallback wave without halting or alerting `index.ts`.
430
+ - **Remediation**: Check `hasCycles` in `synthesizeBlueprint` and throw a descriptive validation error before state initialization.
431
+
432
+ #### [HIGH-03] `worker_orchestrator.ts:18-44` - Unbounded Worker Concurrency
433
+ - **File & Lines**: `worker_orchestrator.ts:18-44`
434
+ - **Symbols**: `MultiAgentWorkerOrchestrator`
435
+ - **Mechanism**: Waves with 10+ parallel tasks launch all subagents simultaneously, causing API rate limits and git lock collisions.
436
+ - **Remediation**: Add `maxConcurrency: number = 4` chunking in `WaveExecutionBundle`.
437
+
438
+ #### [HIGH-04] `state.ts:35-43` - Non-Atomic State Persistence
439
+ - **File & Lines**: `state.ts:35-43`
440
+ - **Symbols**: `saveSessionStateToFile`
441
+ - **Mechanism**: Direct `fs.writeFileSync` to `blueprint_state.json`. If killed mid-write, state is truncated to 0 bytes.
442
+ - **Remediation Diff**:
443
+ ```diff
444
+ --- a/state.ts
445
+ +++ b/state.ts
446
+ @@ -38,2 +38,4 @@ export function saveSessionStateToFile(cwd: string = process.cwd()): boolean {
447
+ - fs.writeFileSync(filePath, JSON.stringify(state, null, 2), "utf-8");
448
+ + const tempPath = `${filePath}.tmp.${process.pid}.${Date.now()}`;
449
+ + fs.writeFileSync(tempPath, JSON.stringify(state, null, 2), "utf-8");
450
+ + fs.renameSync(tempPath, filePath);
451
+ return true;
452
+ ```
453
+
454
+ #### [HIGH-05] `state.ts:249-273` - Incomplete Transaction Rollback (Orphan New Files)
455
+ - **File & Lines**: `state.ts:249-273`
456
+ - **Symbols**: `rollbackStage`
457
+ - **Mechanism**: Restores modified files from snapshot but does not delete newly created files, leaving broken code on disk.
458
+ - **Remediation**: Track `snapshot.createdFiles` and call `fs.unlinkSync` on rollback.
459
+
460
+ #### [HIGH-06] `engine.ts:313` - Missing `CapabilityItem` Import Breaks Build
461
+ - **File & Lines**: `engine.ts:2-13, 313`
462
+ - **Symbols**: `topEcosystemMatch: CapabilityItem | null`
463
+ - **Mechanism**: `CapabilityItem` is referenced on line 313 but not imported from `./types.js`, triggering `TS2304`.
464
+ - **Remediation Diff**:
465
+ ```diff
466
+ --- a/engine.ts
467
+ +++ b/engine.ts
468
+ @@ -3,2 +3,3 @@ import {
469
+ EcosystemTaxonomy,
470
+ + CapabilityItem,
471
+ TaskDiagnosis,
472
+ ```
473
+
474
+ #### [HIGH-07] `blast_radius.ts:31,61,78` - Windows Case & Drive Letter Mismatches
475
+ - **File & Lines**: `blast_radius.ts:31, 61, 78`
476
+ - **Symbols**: `BlastRadiusGuard.verifyToolCall`
477
+ - **Mechanism**: Case-sensitive JS Set lookup fails on Windows NTFS (`C:\Repo` vs `c:\repo`).
478
+ - **Remediation**: Normalize all lookup keys with `.toLowerCase().replace(/\\/g, "/")` on `win32`.
479
+
480
+ #### [HIGH-08] `blast_radius.ts:61-75` - Symlink & Traversal Bypasses of `.git`
481
+ - **File & Lines**: `blast_radius.ts:61-75`
482
+ - **Symbols**: `criticalConfigPatterns`
483
+ - **Mechanism**: `src/../../.git/config` yields relative `..\..\.git\config`, which fails `/^\.git/` regex check.
484
+ - **Remediation**: Inspect normalized path segments with `normalizedRelative.split("/").includes(".git")`.
485
+
486
+ #### [HIGH-09] `blast_radius.ts:55` - Shell & Non-Standard Tool Call Evasion
487
+ - **File & Lines**: `blast_radius.ts:55`
488
+ - **Symbols**: `verifyToolCall`
489
+ - **Mechanism**: Only intercepts `write` and `edit`. Tools `bash`, `powershell`, `exec` bypass all checks.
490
+ - **Remediation**: Intercept shell tool calls and parse command arguments for destructive redirect/removal operators.
491
+
492
+ #### [HIGH-10] `blast_radius.ts:68` - Critical Config Whitelist Override Flaw
493
+ - **File & Lines**: `blast_radius.ts:68`
494
+ - **Symbols**: `verifyToolCall`
495
+ - **Mechanism**: Allowed path check occurs before sensitive config check, allowing a malicious stage to overwrite `.env`.
496
+ - **Remediation**: Enforce critical config blacklist check unconditionally before checking allowed paths.
497
+
498
+ #### [HIGH-11] `dehydrator.ts:35-64` - Missing Disk Quota & Stale `mtime` in LRU Eviction
499
+ - **File & Lines**: `dehydrator.ts:35-64`
500
+ - **Symbols**: `ContextDehydrator.pruneOldRuns`
501
+ - **Mechanism**: Directory `mtimeMs` is stale on NTFS/ext4, causing active runs to be deleted. Lacks total byte limit.
502
+ - **Remediation**: Compute recursive folder stats, enforce 200MB quota, and exclude active `this.runsDir`.
503
+
504
+ #### [HIGH-12] `dehydrator.ts:69-81` - Large Payload Synchronous Write V8 Heap OOM
505
+ - **File & Lines**: `dehydrator.ts:69-81`
506
+ - **Symbols**: `dehydrateStageLog`
507
+ - **Mechanism**: 500MB+ logs passed to `fs.writeFileSync` crash V8 with heap exhaustion.
508
+ - **Remediation**: Enforce a 10MB head/tail truncation limit with warning banner before writing.
509
+
510
+ #### [HIGH-13] `state.ts:404` & `index.ts:338` - Query Side-Effect State Corruption in `/sop`
511
+ - **File & Lines**: `state.ts:404-418`, `index.ts:338-340`
512
+ - **Symbols**: `verifyStageArtifacts`, `state.retryCount`
513
+ - **Mechanism**: Calling `verifyStageArtifacts` during `/sop` query increments `retryCount`. Two queries trigger circuit breaker.
514
+ - **Remediation**: Add `incrementRetry: boolean = false` parameter to `verifyStageArtifacts`.
515
+
516
+ #### [HIGH-14] `degradation_matrix.ts:130-136` - Design Stage Tool Over-Pruning
517
+ - **File & Lines**: `degradation_matrix.ts:130-136`
518
+ - **Symbols**: `resolvePrunedToolsForStage("design")`
519
+ - **Mechanism**: Blocks `write` in design stage where `docs/design.md` must be created, causing guaranteed deadlock.
520
+ - **Remediation**: Allow `write` in design stages, scoped to `docs/**`.
521
+
522
+ #### [HIGH-15] `memory.ts:63-65` - Unbounded Memory Growth & Token Budget Blowout
523
+ - **File & Lines**: `memory.ts:63-65, 78-81`
524
+ - **Symbols**: `CodebaseMemoryManager.recordLesson`
525
+ - **Mechanism**: Unbounded lesson array grows indefinitely, injecting 3,000+ tokens on every turn.
526
+ - **Remediation**: Implement rolling window compaction limiting memory to top 15 lessons (<500 tokens).
527
+
528
+ #### [HIGH-16] `memory.ts:49-71` - Ground-Truth Primacy Conflict
529
+ - **File & Lines**: `memory.ts:49-71`
530
+ - **Symbols**: `CodebaseMemoryManager`
531
+ - **Mechanism**: Memory lessons are never reconciled against live disk state (`package.json`), injecting stale directives.
532
+ - **Remediation**: Add disk truth validation hooks before prompt injection.
533
+
534
+ #### [HIGH-17] `taxonomy.ts:7-10` - Global Path Hardcoding (`os.homedir()`)
535
+ - **File & Lines**: `taxonomy.ts:7-10`
536
+ - **Symbols**: `TAXONOMY_PATH`, `SETTINGS_PATH`
537
+ - **Mechanism**: Hardcoded to `~/.pi/agent`, failing in customized or containerized environments.
538
+ - **Remediation**: Support `PI_AGENT_DIR` environment variable and parameter override.
539
+
540
+ #### [HIGH-18] `taxonomy.ts:384-397` - Stale Cache Invalidation
541
+ - **File & Lines**: `taxonomy.ts:384-397`
542
+ - **Symbols**: `loadOrRefreshTaxonomy`
543
+ - **Mechanism**: Fingerprint only hashes `settings.json`, ignoring dynamic changes in `prompts/` and `npm/`.
544
+ - **Remediation**: Include folder `mtime` signatures of `prompts` and `npm/node_modules` in fingerprint hash.
545
+
546
+ #### [HIGH-19] `taxonomy.ts:441-447` - Dead Code in `deepAnalyzeTaxonomyWithLLM`
547
+ - **File & Lines**: `taxonomy.ts:441-447`
548
+ - **Symbols**: `deepAnalyzeTaxonomyWithLLM`
549
+ - **Mechanism**: Filters by `includes("动态通用")`, but metadata generator outputs `"动态识别组件"`. Array is always empty.
550
+ - **Remediation**: Fix string matching to check `"动态识别组件"` and `"基础通用能力"`.
551
+
552
+ #### [HIGH-20] `ui.ts:442-474` - Asymmetric Box Border Arithmetic in Navigator
553
+ - **File & Lines**: `ui.ts:442-474`
554
+ - **Symbols**: `openArchitectNavigator`
555
+ - **Mechanism**: Top border is `innerWidth + 3` columns while bottom border is `innerWidth + 4` columns, indenting top right corner `╮`.
556
+ - **Remediation**: Align top border filler math: `innerWidth + 2 - 2 - titleVisW`.
557
+
558
+ #### [HIGH-21] `ui.ts:317, 384, 541-555` - Impossible Plan B Selection in Navigator
559
+ - **File & Lines**: `ui.ts:317, 384, 541-555`
560
+ - **Symbols**: `handleInput`
561
+ - **Mechanism**: Keys `'1'` and `'2'` are consumed by slot option selection. No key exists to toggle between Plan A and Plan B.
562
+ - **Remediation**: Map `Tab` or `m` key to toggle `selectedPlan = selectedPlan === "A" ? "B" : "A"`.
563
+
564
+ ---
565
+
566
+ ### Medium-Severity Findings (P2 - Optimization & Robustness)
567
+
568
+ - **[MED-01] `engine.ts:151-160`**: Duplicate dependency entries in `s.dependsOn` inflate in-degree count. *Fix: `Array.from(new Set(s.dependsOn))`*.
569
+ - **[MED-02] `state.ts:183-196`**: Snapshot `fileContents` stored in `state.snapshots` inflates `blueprint_state.json` to 50MB+. *Fix: Save file contents in isolated disk directories `.pi/snapshots/`*.
570
+ - **[MED-03] `state.ts:404-418`**: Circuit breaker state machine never transitions to `"healing_failed_circuit_break"`. *Fix: Update `state.status` on retryCount >= 3*.
571
+ - **[MED-04] `state.ts:458`**: Synchronous `execSync` with 15s timeout blocks event loop and freezes TUI. *Fix: Wrap in async promise with `child_process.exec`*.
572
+ - **[MED-05] `index.ts:329-418`**: Async `turn_end` hook lacks outer `try...catch`, risking unhandled promise rejection crashes. *Fix: Enclose in `try...catch`*.
573
+ - **[MED-06] `index.ts:140-156`**: Tool permissions not restored to `BASELINE_TOOLS` on `/blueprint rollback` or `/blueprint reset`. *Fix: Call `applyToolScoping(BASELINE_TOOLS)`*.
574
+ - **[MED-07] `blast_radius.ts:11-22`**: Windows 8.3 short names (`PACKAG~1.JSO`) evade regex filters. *Fix: Add 8.3 regex aliases*.
575
+ - **[MED-08] `blast_radius.ts:61-67`**: NTFS Alternate Data Streams (`file::$DATA`) evade basename matching. *Fix: Forbid `:` in relative paths*.
576
+ - **[MED-09] `dehydrator.ts:79-81`**: Silent error swallowing on disk write failure returns phantom log path. *Fix: Return `rawLogStatus: "written" | "write_failed"`*.
577
+ - **[MED-10] `dehydrator.ts:86-100`**: AST regexes fail on `export async function`, `enum`, and multi-line imports. *Fix: Expand regex AST parser*.
578
+ - **[MED-11] `index.ts:413-416`**: Missing exponential backoff and jitter causes rapid retry depletion on transient locks. *Fix: Backoff $T = 1000 \times 2^{\text{retryCount}} + \text{jitter}$*.
579
+ - **[MED-12] `degradation_matrix.ts:36-118`**: Hardcoded `bash` tool fallback fails on Windows systems without Git Bash. *Fix: Fallback to `powershell` on `win32`*.
580
+ - **[MED-13] `memory.ts:49-70`**: Non-atomic memory file writes risk corruption in concurrent agent executions. *Fix: Use atomic temp file rename*.
581
+ - **[MED-14] `taxonomy.ts:252-286`**: L2 regex matches `read`/`api` before L4/L1, misclassifying git and review tools. *Fix: Reorder heuristics (L4 $\to$ L3 $\to$ L1 $\to$ L2)*.
582
+ - **[MED-15] `taxonomy.ts:145-168`**: Clean git repos falsely report 3 active modified files. *Fix: Query `git status --porcelain` for dirty files*.
583
+ - **[MED-16] `taxonomy.ts:16-25`**: `cleanName` strips `@scope/` causing package collisions (`@foo/log` vs `@bar/log`). *Fix: Replace `@scope/name` with `scope-name`*.
584
+ - **[MED-17] `ui.ts:380-386`**: Footer line is 86 columns wide, overflowing standard 80x24 viewports. *Fix: Responsive two-line footer on `< 88` columns*.
585
+ - **[MED-18] `ui.ts:495-501`**: Backspacing emoji splits surrogate pairs; bracketed paste sequences discarded. *Fix: Use `Array.from()` grapheme popping and strip bracketed paste headers*.
586
+ - **[MED-19] `ui.ts:57-60`**: Raw ANSI escapes embed into exported `BLUEPRINT.md`. *Fix: Add `plainText: true` option to `renderUnicodeDAG`*.
587
+ - **[MED-20] `types.ts:40-48`**: `EcosystemTaxonomy` lacks `mcps` and `tools` collections. *Fix: Add `mcps?: CapabilityItem[]` and `tools?: CapabilityItem[]`*.
588
+ - **[MED-21] `types.ts:17-38`**: `ProjectType` and `PackageManager` omit Bun, Deno, Gradle, Maven. *Fix: Expand union types*.
589
+ - **[MED-22] `engine.ts:113`**: Windows-only `start index.html` command generated for Linux/macOS. *Fix: `process.platform === "win32" ? "start" : process.platform === "darwin" ? "open" : "xdg-open"`*.
590
+ - **[MED-23] `state.ts:109-118`**: Git porcelain quoted non-ASCII paths (e.g. `"docs/设计.md"`) fail path lookup. *Fix: Strip quotes and normalize slashes*.
591
+ - **[MED-24] `ui.ts:189-592`**: Missing `TaskDiagnosis` import, implicit any parameters, and string property lookup errors fail strict TypeScript build. *Fix: Correct types in `ui.ts`*.
592
+
593
+ ---
594
+
595
+ ### Low-Severity Findings (P3 - Polish & Standards)
596
+
597
+ - **[LOW-01] `engine.ts:145-149`**: Duplicate `stageId` in input array shadows earlier entries, triggering false positive cycle detection. *Fix: Assert `stageId` uniqueness*.
598
+ - **[LOW-02] `types.ts:142-143`**: Ambiguity between `expectedArtifact` (string) and `expectedArtifacts` (string[]). *Fix: Normalize at stage synthesis*.
599
+ - **[LOW-03] `dehydrator.ts:121-123`**: Stale SHA-256 fingerprints in handoff prompt if files are modified after verification. *Fix: Recalculate hash on live disk*.
600
+ - **[LOW-04] `taxonomy.ts:358-372`**: Verbose `generateCapabilityCompactDigest` exceeds token budget on large ecosystems. *Fix: Group by layer `[INF] tool1, tool2 | [DOM] tool3`*.
601
+ - **[LOW-05] `ui.ts:604-608`**: `customEcosystem` hardcoded to return empty arrays in outline confirm callback. *Fix: Populate from `ecoToggles` state*.
602
+ - **[LOW-06] `ui.ts:57-60`**: Missing `NO_COLOR`, `CI`, and `TERM=dumb` environment variable checks. *Fix: Add `isColorSupported()` helper*.
603
+
604
+ ---
605
+
606
+ ## 5. Sequenced, Actionable Implementation & Refactoring Roadmap
607
+
608
+ ```
609
+ ┌────────────────────────────────────────────────────────────────────────────────────────┐
610
+ │ SEQUENCED REFACTORING IMPLEMENTATION ROADMAP │
611
+ ├───────────┬───────────────────────────────────┬──────────────────┬─────────────────────┤
612
+ │ Phase │ Focus Area │ Target Modules │ Success Gate │
613
+ ├───────────┼───────────────────────────────────┼──────────────────┼─────────────────────┤
614
+ │ Phase 0 │ TypeScript Compilation & Critical │ worker_orch.ts │ tsc --noEmit passes │
615
+ │ (P0) │ Runtime Typos & Glob Failures │ blast_radius.ts │ 0 compile errors │
616
+ │ │ (CRIT-01..05, HIGH-06) │ engine.ts, ui.ts │ Multi-file writes ok│
617
+ ├───────────┼───────────────────────────────────┼──────────────────┼─────────────────────┤
618
+ │ Phase 1 │ Security, Sandbox & Cross-Platform│ blast_radius.ts │ 100% path tests pass│
619
+ │ (P1) │ Traversal Hardening │ taxonomy.ts │ Case/symlink safe │
620
+ │ │ (HIGH-07..10, HIGH-17..19) │ state.ts │ No traversal leaks │
621
+ ├───────────┼───────────────────────────────────┼──────────────────┼─────────────────────┤
622
+ │ Phase 2 │ Self-Healing, State Machine & │ state.ts │ /sop read-only safe │
623
+ │ (P1) │ Subsystem Integration │ degradation.ts │ Matrix wired │
624
+ │ │ (HIGH-01..05, HIGH-13..16) │ memory.ts, index │ Memory 0-token safe │
625
+ ├───────────┼───────────────────────────────────┼──────────────────┼─────────────────────┤
626
+ │ Phase 3 │ LRU Quota, OOM Guard & AST Parser │ dehydrator.ts │ Max 200MB disk cap │
627
+ │ (P2) │ Robustness │ engine.ts │ No V8 heap OOM │
628
+ │ │ (HIGH-11, 12, MED-01..13) │ types.ts │ Full AST capture │
629
+ ├───────────┼───────────────────────────────────┼──────────────────┼─────────────────────┤
630
+ │ Phase 4 │ TUI Monospace Precision, CJK Width│ ui.ts │ Monospace receipts │
631
+ │ (P3) │ & Usability Polish │ index.ts │ Plan B selectable │
632
+ │ │ (MED-14..24, LOW-01..06) │ types.ts │ Clean Markdown exp │
633
+ └───────────┴───────────────────────────────────┴──────────────────┴─────────────────────┘
634
+ ```
635
+
636
+ ### Verification Test Matrix & Acceptance Gates
637
+
638
+ 1. **Compilation Gate**: `npx tsc --noEmit` exits with code `0`.
639
+ 2. **Blast Radius Sandbox Gate**: Unit tests verify glob matching (`src/**`), Windows case normalization (`c:\repo` vs `C:\Repo`), `.git` traversal blocks (`../../.git`), and NTFS stream blocking.
640
+ 3. **State Machine Gate**: Test running `/sop` 5 times in succession; verify `retryCount` remains unchanged and circuit breaker does not trip.
641
+ 4. **Dehydration Gate**: Test dehydrating a 50MB log file; verify head/tail truncation and zero V8 heap spikes. Test LRU eviction with 200MB byte cap.
642
+ 5. **TUI Monospace Gate**: Test `renderValueReceipt` with mixed English/Chinese tasks; verify visible monospace width across all rows equals exactly 64 columns.
643
+
644
+ ---
645
+ *Master Architectural Audit & Optimization Report compiled and certified for ToolFlow.*