knowzcode 0.3.7 → 0.4.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 (79) hide show
  1. package/.claude-plugin/marketplace.json +61 -61
  2. package/.claude-plugin/plugin.json +8 -8
  3. package/LICENSE +121 -121
  4. package/README.md +354 -320
  5. package/agents/analyst.md +114 -114
  6. package/agents/architect.md +200 -200
  7. package/agents/builder.md +104 -104
  8. package/agents/closer.md +177 -177
  9. package/agents/context-scout.md +54 -54
  10. package/agents/knowledge-migrator.md +349 -349
  11. package/agents/knowz-scout.md +83 -83
  12. package/agents/knowz-scribe.md +180 -180
  13. package/agents/microfix-specialist.md +135 -135
  14. package/agents/project-advisor.md +111 -111
  15. package/agents/reviewer.md +172 -172
  16. package/agents/security-officer.md +194 -194
  17. package/agents/test-advisor.md +162 -162
  18. package/agents/update-coordinator.md +394 -394
  19. package/bin/knowzcode.mjs +1199 -956
  20. package/commands/audit.md +328 -328
  21. package/commands/connect-mcp.md +549 -549
  22. package/commands/fix.md +107 -107
  23. package/commands/init.md +500 -439
  24. package/commands/learn.md +332 -332
  25. package/commands/plan.md +272 -272
  26. package/commands/register.md +733 -733
  27. package/commands/status.md +309 -309
  28. package/commands/telemetry-setup.md +368 -368
  29. package/commands/telemetry.md +188 -188
  30. package/commands/work.md +1204 -1202
  31. package/knowzcode/automation_manifest.md +59 -59
  32. package/knowzcode/claude_code_execution.md +431 -420
  33. package/knowzcode/copilot_execution.md +231 -231
  34. package/knowzcode/enterprise/compliance_manifest.md +137 -137
  35. package/knowzcode/enterprise/compliance_status.md +30 -30
  36. package/knowzcode/enterprise/guidelines/code-quality.md +67 -67
  37. package/knowzcode/enterprise/guidelines/security.md +355 -355
  38. package/knowzcode/enterprise/templates/guideline-template.md +55 -55
  39. package/knowzcode/gitignore.template +13 -13
  40. package/knowzcode/knowzcode_architecture.md +51 -51
  41. package/knowzcode/knowzcode_log.md +142 -142
  42. package/knowzcode/knowzcode_loop.md +596 -596
  43. package/knowzcode/knowzcode_orchestration.md +66 -66
  44. package/knowzcode/knowzcode_project.md +48 -48
  45. package/knowzcode/knowzcode_tracker.md +40 -40
  46. package/knowzcode/knowzcode_vaults.md +257 -257
  47. package/knowzcode/mcp_config.md +191 -191
  48. package/knowzcode/planning/Readme.md +6 -6
  49. package/knowzcode/platform_adapters.md +1260 -1047
  50. package/knowzcode/prompts/Execute_Micro_Fix.md +57 -57
  51. package/knowzcode/prompts/Investigate_Codebase.md +227 -227
  52. package/knowzcode/prompts/Migrate_Knowledge.md +301 -301
  53. package/knowzcode/prompts/Refactor_Node.md +72 -72
  54. package/knowzcode/prompts/Spec_Verification_Checkpoint.md +59 -59
  55. package/knowzcode/prompts/[LOOP_1A]__Propose_Change_Set.md +52 -52
  56. package/knowzcode/prompts/[LOOP_1B]__Draft_Specs.md +75 -75
  57. package/knowzcode/prompts/[LOOP_2A]__Implement_Change_Set.md +55 -55
  58. package/knowzcode/prompts/[LOOP_2B]__Verify_Implementation.md +72 -72
  59. package/knowzcode/prompts/[LOOP_3]__Finalize_And_Commit.md +67 -67
  60. package/knowzcode/specs/Readme.md +10 -10
  61. package/knowzcode/telemetry_config.md +89 -89
  62. package/knowzcode/user_preferences.md +120 -120
  63. package/package.json +53 -53
  64. package/skills/alias-resolver.json +1 -1
  65. package/skills/architecture-diff.json +1 -1
  66. package/skills/check-installation-status.json +1 -1
  67. package/skills/continue.md +126 -126
  68. package/skills/environment-guard.json +1 -1
  69. package/skills/generate-workgroup-id.json +1 -1
  70. package/skills/install-knowzcode.json +1 -1
  71. package/skills/load-core-context.json +1 -1
  72. package/skills/log-entry-builder.json +1 -1
  73. package/skills/spec-quality-check.json +1 -1
  74. package/skills/spec-template.json +1 -1
  75. package/skills/spec-validator.json +1 -1
  76. package/skills/start-work.md +224 -224
  77. package/skills/tracker-scan.json +1 -1
  78. package/skills/tracker-update.json +1 -1
  79. package/skills/validate-installation.json +1 -1
package/commands/work.md CHANGED
@@ -1,1202 +1,1204 @@
1
- ---
2
- description: "Start a new KnowzCode development workflow with TDD, quality gates, and structured phases"
3
- argument-hint: "[feature_description]"
4
- ---
5
-
6
- # Work on New Feature
7
-
8
- Start a new KnowzCode development workflow session.
9
-
10
- **Usage**: `/kc:work "feature description"`
11
- **Example**: `/kc:work "Build user authentication with JWT"`
12
-
13
- **Primary Goal**: $ARGUMENTS
14
-
15
- ---
16
-
17
- ## Step 0: Prerequisite Check
18
-
19
- Verify KnowzCode is initialized:
20
- 1. Check if `knowzcode/` directory exists
21
- 2. Check required files exist: `knowzcode_loop.md`, `knowzcode_tracker.md`, `knowzcode_project.md`, `knowzcode_architecture.md`
22
-
23
- If missing: inform user to run `/kc:init` first. STOP.
24
-
25
- ## Step 1: Generate WorkGroup ID
26
-
27
- **Format**: `kc-{type}-{slug}-YYYYMMDD-HHMMSS`
28
-
29
- - `{type}`: feat, fix, refactor, or issue
30
- - `{slug}`: 2-4 word kebab-case from goal (remove common words: build, add, create, implement, the, a, with, for)
31
- - Truncate slug to max 25 characters
32
-
33
- ## Step 2: Select Execution Mode
34
-
35
- Determine the execution mode using try-then-fallback:
36
-
37
- 1. Note user preferences from `$ARGUMENTS`:
38
- - `--sequential` → prefer Sequential Teams
39
- - `--subagent` → force Subagent Delegation (skip team creation attempt)
40
-
41
- 2. **If `--subagent` NOT specified**, attempt `TeamCreate(team_name="kc-{wgid}")`:
42
- - **If TeamCreate succeeds** → Agent Teams is available. Choose mode:
43
- - `--sequential` or Tier 2 → **Sequential Teams**: `**Execution Mode: Sequential Teams** — created team kc-{wgid}`
44
- - Otherwise → **Parallel Teams** (default for Tier 3): `**Execution Mode: Parallel Teams** — created team kc-{wgid}`
45
- - **If TeamCreate fails** (error, unrecognized tool, timeout) → **Subagent Delegation**: `**Execution Mode: Subagent Delegation** — Agent Teams not available, using Task() fallback`
46
-
47
- 3. **If `--subagent` specified** → **Subagent Delegation** directly (no TeamCreate attempt):
48
- - Announce: `**Execution Mode: Subagent Delegation** — per user request`
49
-
50
- For all Agent Teams modes (Sequential and Parallel):
51
- - You are the **team lead** in delegate mode — you coordinate phases, present quality gates, and manage the workflow. You NEVER write code, specs, or project files directly. All work is done by teammates. (Tip: the user can press Shift+Tab to system-enforce delegate mode.)
52
- - After completion or if the user cancels, shut down all active teammates and clean up the team (see Cleanup section)
53
-
54
- For Subagent Delegation:
55
- - For each phase, delegate via `Task()` with the parameters specified in phase sections below
56
-
57
- The user MUST see the execution mode announcement before any phase work begins. The phases, quality gates, and interactions are identical across all paths.
58
-
59
- > **Note:** Agent Teams is experimental and the API may change.
60
-
61
- ## Step 2.4: Load Orchestration Config (Optional)
62
-
63
- If `knowzcode/knowzcode_orchestration.md` exists, parse its YAML blocks:
64
-
65
- 1. `MAX_BUILDERS` = `max_builders` value (default: 5, clamp to 1-5)
66
- 2. `SCOUT_MODE` = `scout_mode` value (default: "full")
67
- 3. `DEFAULT_SPECIALISTS` = `default_specialists` value (default: [])
68
- 4. `MCP_AGENTS_ENABLED` = `mcp_agents_enabled` value (default: true)
69
- 5. `CODEBASE_SCANNER_ENABLED` = `codebase_scanner_enabled` value (default: true)
70
- 6. `PARALLEL_SPEC_THRESHOLD` = `parallel_spec_threshold` value (default: 3, clamp to 2-10)
71
-
72
- Apply flag overrides (flags win over config):
73
- - `--max-builders=N` in `$ARGUMENTS` → override `MAX_BUILDERS`
74
- - `--no-scouts` in `$ARGUMENTS` → override `SCOUT_MODE = "none"`
75
- - `--no-mcp` in `$ARGUMENTS` → override `MCP_AGENTS_ENABLED = false`
76
- - `--no-scanners` in `$ARGUMENTS` → override `CODEBASE_SCANNER_ENABLED = false`
77
- - `--no-parallel-specs` in `$ARGUMENTS` → override `PARALLEL_SPEC_THRESHOLD = 999` (effectively disabled)
78
-
79
- If the file doesn't exist, use hardcoded defaults (current behavior).
80
-
81
- ## Step 2.5: Autonomous Mode Detection
82
-
83
- Set `AUTONOMOUS_MODE = true` if ANY of these match:
84
-
85
- a. **Flags**: `$ARGUMENTS` contains `--autonomous` or `--auto`
86
-
87
- b. **Natural language** (case-insensitive match in `$ARGUMENTS` OR the user's preceding conversation message):
88
- - Approval intent: "approve all", "pre-approve", "preapprove", "auto-approve"
89
- - Mode intent: "autonomous mode", "autonomous", "unattended", "hands off", "hands-off"
90
- - Proceed intent: "don't stop to ask", "don't ask me", "no approval needed", "just run through", "run it all", "run straight through", "proceed without asking", "skip the gates", "go all the way through"
91
- - Delegation intent: "I trust your judgement", "use your best judgement", "defer to your judgement", "you decide"
92
-
93
- c. **Contextual** — if the user's message conveys clear intent for the lead to operate without stopping (even if none of the exact phrases above match), interpret that as autonomous mode. The spirit of the instruction matters more than exact phrasing.
94
-
95
- Default: `AUTONOMOUS_MODE = false`
96
-
97
- If `AUTONOMOUS_MODE = true`, announce after the execution mode announcement:
98
- > **Autonomous Mode: ACTIVE** — Gates presented for transparency but auto-approved.
99
- > Safety exceptions still pause: critical blockers, HIGH/CRITICAL security findings, >3 same-phase failures, complex architecture discrepancies, >3 gap-fix iterations per partition.
100
-
101
- ## Step 2.6: Specialist Detection
102
-
103
- Set `SPECIALISTS_ENABLED = []` (empty list).
104
-
105
- If `DEFAULT_SPECIALISTS` is non-empty (from Step 2.4), initialize:
106
- `SPECIALISTS_ENABLED = DEFAULT_SPECIALISTS`
107
-
108
- Determine which specialists to activate (flags and natural language add to or override the baseline):
109
- - `--specialists` → enable all 3: `[security-officer, test-advisor, project-advisor]`
110
- - `--specialists=csv` → enable specific subset (comma-separated, e.g., `--specialists=security,test`):
111
- - `security` → `security-officer`
112
- - `test` → `test-advisor`
113
- - `project` → `project-advisor`
114
- - `--no-specialists` → explicit opt-out, `SPECIALISTS_ENABLED = []`
115
-
116
- **Natural language detection** (case-insensitive match in `$ARGUMENTS` OR the user's preceding conversation message):
117
- - All specialists: "with specialists", "with officers", "full specialist panel"
118
- - security-officer: "security review", "threat model", "vulnerability scan", "pentest"
119
- - test-advisor: "test quality", "TDD enforcement", "test coverage", "test rigor"
120
- - project-advisor: "backlog", "future work", "brainstorm", "ideas"
121
-
122
- **Mode constraints:**
123
- - Tier 3 Parallel Teams: Full support (Group C)
124
- - Tier 3 Subagent Delegation: Supported via parallel `Task()` calls
125
- - Sequential Teams / Tier 2: Not supported — if specialists were detected, announce: `> **Specialists: SKIPPED** — not supported in {Sequential Teams / Tier 2} mode.`
126
-
127
- Default: `SPECIALISTS_ENABLED = []` (specialists are opt-in).
128
-
129
- If `SPECIALISTS_ENABLED` is non-empty, announce after the autonomous mode announcement (or after the execution mode announcement if autonomous is not active):
130
- > **Specialists: ACTIVE** — {comma-separated list of enabled specialists}
131
-
132
- ## Step 3: Load Context Files (ONCE)
133
-
134
- Read these files ONCE (do NOT re-read between phases):
135
- - `knowzcode/knowzcode_loop.md`
136
- - `knowzcode/knowzcode_tracker.md`
137
- - `knowzcode/knowzcode_project.md`
138
- - `knowzcode/knowzcode_architecture.md`
139
-
140
- ## Step 3.5: Pull Team Standards (MCP — Optional)
141
-
142
- If MCP is configured and enterprise compliance is enabled:
143
- 1. Check `knowzcode/enterprise/compliance_manifest.md` for `mcp_compliance_enabled: true`
144
- 2. If enabled: Read `knowzcode/knowzcode_vaults.md` to find vault matching type "enterprise", then `ask_question({resolved_enterprise_vault_id}, "team standards for {project_type}")`
145
- 3. Merge returned standards into WorkGroup context for quality gate criteria
146
-
147
- If MCP is not configured or enterprise is not enabled, skip this step.
148
-
149
- ## Step 4: Create WorkGroup File
150
-
151
- Create `knowzcode/workgroups/{WorkGroupID}.md`:
152
- ```markdown
153
- # WorkGroup: {WorkGroupID}
154
-
155
- **Primary Goal**: {$ARGUMENTS}
156
- **Created**: {timestamp}
157
- **Status**: Active
158
- **Current Phase**: 1A - Impact Analysis
159
- **Autonomous Mode**: Active/Inactive
160
-
161
- ## Change Set
162
- (Populated after Phase 1A)
163
-
164
- ## Todos
165
- - KnowzCode: Initialize WorkGroup
166
- - KnowzCode: Complete Phase 1A impact analysis
167
-
168
- ## Phase History
169
- | Phase | Status | Timestamp |
170
- |-------|--------|-----------|
171
- | 1A | In Progress | {timestamp} |
172
- ```
173
-
174
- ## Step 5: Input Classification
175
-
176
- **Question indicators** (suggest `/kc:plan` instead): starts with is/does/how/why/what/should, contains `?`, phrased as inquiry.
177
-
178
- **Implementation indicators** (proceed): starts with build/add/create/implement/fix/refactor, action-oriented verbs.
179
-
180
- If ambiguous, proceed with implementation.
181
-
182
- ## Step 5.5: Complexity Classification
183
-
184
- Assess the goal against the codebase to determine the appropriate workflow tier.
185
-
186
- ### Tier 1: Micro → redirect to `/kc:fix`
187
- - Single file, <50 lines, no ripple effects
188
-
189
- ### Tier 2: Light (2-phase workflow)
190
-
191
- > **Note:** Light mode does not use orchestration config — single builder, no scouts, no specialists.
192
-
193
- ALL must be true:
194
- - ≤3 files touched
195
- - Single NodeID (1 new capability)
196
- - No architectural changes
197
- - No security-sensitive components (auth, payments, PII)
198
- - No external API integrations
199
- - Estimated <200 lines of change
200
-
201
- ### Tier 3: Full (5-phase workflow)
202
- ANY triggers full:
203
- - >3 files or >1 NodeID
204
- - Architectural impact
205
- - Security-sensitive scope
206
- - External integrations
207
- - User explicitly requests: `--tier full`
208
-
209
- **Announce the detected tier to the user.** User can override:
210
- - "use full" or `--tier full` → Tier 3
211
- - "use light" or `--tier light` → Tier 2
212
-
213
- If `$ARGUMENTS` contains `--tier light`, force Tier 2. If `--tier full`, force Tier 3.
214
-
215
- ---
216
-
217
- ## Tier 2: Light Workflow (2-phase fast path)
218
-
219
- When Tier 2 is selected, execute this streamlined workflow instead of the 5-phase Tier 3 below.
220
-
221
- ### Light Phase 1 (Inline — lead does this, no agent)
222
-
223
- 1. Quick impact scan: grep for related files, check existing specs
224
- 2. Propose a Change Set (typically 1 NodeID)
225
- 3. Draft a lightweight spec (or reference existing spec if found) — use the 4-section format from `knowzcode_loop.md` section 3.2. Minimum: 1 Rule, 1 Interface, 2 `VERIFY:` statements.
226
- 4. Present combined Change Set + Spec for approval:
227
-
228
- ```markdown
229
- ## Light Mode: Change Set + Spec Approval
230
-
231
- **WorkGroupID**: {wgid}
232
- **Tier**: 2 (Light)
233
- **NodeID**: {NodeID} — {description}
234
- **Affected Files**: {list}
235
-
236
- **Spec Summary**:
237
- - Rules: {key decisions}
238
- - Interfaces: {public contracts}
239
- - VERIFY: {criteria list}
240
-
241
- Approve Change Set and spec to proceed to implementation?
242
- ```
243
-
244
- 5. **Autonomous Mode**: If `AUTONOMOUS_MODE = true`, log `[AUTO-APPROVED] Light mode gate` and proceed directly to implementation.
245
- If `AUTONOMOUS_MODE = false`: If rejected — adjust based on feedback and re-present. If approved:
246
- - Update `knowzcode_tracker.md` with NodeID status `[WIP]`
247
- - Pre-implementation commit: `git add knowzcode/ && git commit -m "KnowzCode: Light spec approved for {wgid}"`
248
-
249
- ### Light Phase 2A: Implementation (Builder agent)
250
-
251
- Spawn the builder using the standard Phase 2A prompt below (same for both tiers).
252
-
253
- The builder self-verifies against spec VERIFY criteria — no separate audit phase.
254
-
255
- ### Light Phase 3 (Inline — lead does this, no agent)
256
-
257
- After builder completes successfully:
258
- 1. Update spec to As-Built status
259
- 2. Update `knowzcode_tracker.md`: NodeID status `[WIP]` → `[VERIFIED]`
260
- 3. Write a brief log entry to `knowzcode_log.md`:
261
- ```markdown
262
- ---
263
- **Type:** ARC-Completion
264
- **Timestamp:** [timestamp]
265
- **WorkGroupID:** [ID]
266
- **NodeID(s):** [list]
267
- **Logged By:** AI-Agent
268
- **Details:** Light mode (Tier 2). {brief summary of implementation}.
269
- ---
270
- ```
271
- 4. Final commit: `git add knowzcode/ <changed files> && git commit -m "feat: {goal} (WorkGroup {wgid})"`
272
- 5. Report completion.
273
-
274
- **DONE** — 3 agents skipped (analyst, architect, reviewer, closer).
275
-
276
- ---
277
-
278
- ## Tier 3: Full Workflow (5-phase)
279
-
280
- The standard 5-phase workflow. Used when complexity warrants full analysis, specification, audit, and finalization.
281
-
282
- Tier 3 supports three execution modes (determined in Step 2):
283
- - **Parallel Teams** (default) Stage 0-3 orchestration with concurrent agents
284
- - **Sequential Teams** (`--sequential`) — one agent per phase, spawned and shut down sequentially
285
- - **Subagent Delegation** — Task() calls, no persistent agents
286
-
287
- ## Step 6: Spec Detection (Optional Optimization)
288
-
289
- Check for existing specs covering this work:
290
- 1. Extract key terms from goal
291
- 2. Search `knowzcode/specs/*.md` for matching specs
292
- 3. If comprehensive matching specs found, offer:
293
- - **A) Quick Path** skip discovery, use existing specs
294
- - **B) Validation Path** (recommended) quick check specs match codebase
295
- - **C) Full Workflow** — complete Phase 1A discovery
296
-
297
- If no matches found, proceed to Phase 1A.
298
-
299
- ### Refactor Task Check
300
-
301
- Scan `knowzcode/knowzcode_tracker.md` for outstanding `REFACTOR_` tasks that overlap with the current goal's scope. If found, mention them to the user during Phase 1A so the analyst can factor them into the Change Set.
302
-
303
- ---
304
-
305
- ## Parallel Teams Orchestration (Tier 3 Default)
306
-
307
- When Parallel Teams mode is active, follow these 4 stages instead of spawning one agent per phase sequentially. The same phase spawn prompts (defined in the Phase Reference sections below) are reused — what changes is WHEN agents are spawned and HOW MANY run concurrently.
308
-
309
- ### Stage 0: Team Creation + Parallel Discovery
310
-
311
- 1. Create team `kc-{wgid}`
312
- 2. Read knowzcode context files (lead does initial load for spawn prompts)
313
- 3. **MCP Probe** determine vault availability BEFORE spawning:
314
- a. Read `knowzcode/knowzcode_vaults.md`partition entries into CONFIGURED (non-empty ID) and UNCREATED (empty ID)
315
- b. Call `list_vaults(includeStats=true)` **always** regardless of whether any IDs exist in the file
316
- c. If `list_vaults()` fails:
317
- - Check if `knowzcode/knowzcode_vaults.md` has any CONFIGURED entries (non-empty ID)
318
- - **If CONFIGURED entries exist**: Set `MCP_ACTIVE = true`, `VAULTS_CONFIGURED = true` vault agents will verify connectivity independently via their Startup Verification. Announce `**MCP Status: Lead probe failed — delegating verification to vault agents**`. Proceed to Step 4.
319
- - **If no CONFIGURED entries** (all empty IDs or no file): Set `MCP_ACTIVE = false`, announce `**MCP Status: Not connected**`, skip Group B spawn
320
- d. If `list_vaults()` succeeds AND UNCREATED list is non-empty present the **Vault Creation Prompt**:
321
-
322
- ```markdown
323
- ## Vault Setup
324
-
325
- Your Knowz API key is valid and MCP is connected, but {N} default vault(s) haven't been created yet.
326
- Creating vaults enables knowledge capture throughout the workflow:
327
-
328
- | Vault | Type | Description | Written During |
329
- |-------|------|-------------|----------------|
330
- ```
331
-
332
- Build table rows dynamically from the UNCREATED entries only. For each uncreated vault, derive the "Written During" column from its Write Conditions field in `knowzcode_vaults.md`. Example rows:
333
- - `| Code Patterns | code | Learnings, gotchas, and architecture insights from the codebase | Phase 2A (implementation patterns), Phase 3 (workarounds, performance) |`
334
- - `| Ecosystem Knowledge | ecosystem | Business rules, conventions, decisions, and cross-system details | Phase 1A (scope decisions), Phase 2B (security, quality), Phase 3 (conventions) |`
335
- - `| Finalizations | finalizations | Final summaries documenting complete execution and outcomes | Phase 3 (completion record) |`
336
-
337
- Then present options:
338
- ```
339
- Options:
340
- **A) Create all {N} vaults** (recommended)
341
- **B) Select which to create**
342
- **C) Skip** proceed without vaults (can create later with `/kc:connect-mcp --configure-vaults`)
343
- ```
344
-
345
- e. Handle user selection:
346
- - **A**: For each UNCREATED entry, call MCP `create_vault(name, description)`. If `create_vault` is not available, fall back to matching by name against `list_vaults()` results. Update `knowzcode_vaults.md`: fill the ID field with the server-returned vault ID and change the H3 heading from `(not created)` to the vault ID. If creation fails for some vaults, update only successful ones, report failures, and let user decide.
347
- - **B**: Ask which vaults to create, then create only selected ones using the same process as A.
348
- - **C**: Log `"Vault creation skipped knowledge capture disabled."` Continue.
349
- f. After resolution, set:
350
- - `MCP_ACTIVE = true` (MCP works regardless of vault creation outcome)
351
- - `VAULTS_CONFIGURED = true` if at least 1 vault now has a valid ID, else `false`
352
- - Announce: `**MCP Status: Connected N vault(s) available**` or `**MCP Status: Connected no vaults configured (knowledge capture disabled)**`
353
- 4. **Spawn Group A**:
354
- Create tasks first, pre-assign, then spawn with task IDs:
355
- - If `SCOUT_MODE = "full"` (default): spawn 3 context scouts (specs, workgroups, backlog) + analyst + architect (5 agents):
356
- - `TaskCreate("Scout: specs context")` → `TaskUpdate(owner: "context-scout-specs")`
357
- - `TaskCreate("Scout: workgroups context")` → `TaskUpdate(owner: "context-scout-workgroups")`
358
- - `TaskCreate("Scout: backlog context")` → `TaskUpdate(owner: "context-scout-backlog")`
359
- - If `SCOUT_MODE = "minimal"`: spawn 1 context-scout (combined scan) + analyst + architect (3 agents):
360
- - `TaskCreate("Scout: combined context")` `TaskUpdate(owner: "context-scout")`
361
- - If `SCOUT_MODE = "none"`: spawn analyst + architect only (2 agents). Analyst and architect scan the codebase independently without pre-loaded scout context.
362
- - Always:
363
- - `TaskCreate("Phase 1A: Impact analysis for {goal}")` → `TaskUpdate(owner: "analyst")`
364
- - `TaskCreate("Pre-load architecture context and speculative research")` → `TaskUpdate(owner: "architect")`
365
- - If `CODEBASE_SCANNER_ENABLED = true` (default):
366
- - Derive two search focuses from the goal:
367
- - **Scanner-Direct**: source code search grep for goal keywords, read affected code paths
368
- - **Scanner-Tests**: test discovery search test directories for tests covering the goal area
369
- - `TaskCreate("Scanner: direct codebase scan for {goal}")` `TaskUpdate(owner: "scanner-direct")`
370
- - `TaskCreate("Scanner: test coverage scan for {goal}")` → `TaskUpdate(owner: "scanner-tests")`
371
- Spawn all Group A agents with their `{task-id}` in the spawn prompt (use spawn prompts from Phase Prompt Reference below).
372
- 5. **Spawn Group B** (MCP agents same turn as Group A): If `VAULTS_CONFIGURED = true` AND `MCP_AGENTS_ENABLED = true`:
373
- Create tasks first, pre-assign, then spawn with task IDs:
374
- - `TaskCreate("Knowz-scout: vault queries")` `TaskUpdate(owner: "knowz-scout")`
375
- - `TaskCreate("Knowz-scribe: listen")` → `TaskUpdate(owner: "knowz-scribe")`
376
- Spawn both agents with their `{task-id}` in the spawn prompt.
377
- If `VAULTS_CONFIGURED = false` or `MCP_AGENTS_ENABLED = false`, skip Group B and log: `Vault agents skipped no vaults configured` or `Vault agents skipped MCP agents disabled in orchestration config.`
378
- 6. **Spawn Group C** (specialist agents same turn as Groups A and B): If `SPECIALISTS_ENABLED` is non-empty:
379
- Create tasks first, pre-assign, then spawn with task IDs:
380
- - If `security-officer` in list: `TaskCreate("Security officer: initial threat scan")` → `TaskUpdate(owner: "security-officer")`
381
- - If `test-advisor` in list: `TaskCreate("Test advisor: coverage baseline")` → `TaskUpdate(owner: "test-advisor")`
382
- - If `project-advisor` in list: `TaskCreate("Project advisor: backlog context")` → `TaskUpdate(owner: "project-advisor")`
383
- Spawn each enabled specialist with its `{task-id}` in the spawn prompt (use spawn prompts from Specialist Spawn Prompts section below).
384
- If `SPECIALISTS_ENABLED` is empty, skip Group C.
385
- 7. **Roster confirmation** — lead lists every spawned agent by name to the user. Include scanners and Group C specialists if active. If `VAULTS_CONFIGURED` was true but knowz-scout or knowz-scribe is missing from the roster, STOP and re-spawn the missing agent(s) before continuing.
386
- 8. All spawned agents work immediately in parallel (context scouts are cheap Sonnet read-only agents; scanners are lightweight general-purpose agents; knowz-scribe is a cheap Haiku agent; specialists are Sonnet read-only agents). Agent count depends on orchestration config: 2-12 agents at Stage 0.
387
- 9. Scouts broadcast findings analyst and architect consume as messages. Specialists work independently on their Stage 0 tasks.
388
-
389
- **Key**: The analyst does NOT wait for scouts, scanners, or specialists to finish. It starts scanning the codebase immediately. Scout and scanner findings arrive as messages and enrich the analyst's work as they arrive. The analyst also streams `[PRELIMINARY]` NodeID findings to the architect as it discovers them (see Preliminary Findings Protocol). Specialist findings are consumed by the lead at gates.
390
-
391
- ### Stage 1: Analysis + Specification
392
-
393
- 1. Analyst completes Change Set (includes dependency map — see `agents/analyst.md`)
394
- 2. Lead reads analyst's task summary
395
- 3. Shut down scanners (scanner-direct, scanner-tests) if they were spawned — no longer needed after analysis
396
- 3. **Specialist Change Set reviews** (if `SPECIALISTS_ENABLED` non-empty): Create review tasks blocked on analysis:
397
- - If `security-officer` active: `TaskCreate("Security officer: Change Set review", addBlockedBy: [analysis-task-id])``TaskUpdate(owner: "security-officer")`. DM security-officer: `"**New Task**: #{task-id} Review Change Set for security risk. Rate each NodeID."`
398
- - If `test-advisor` active: `TaskCreate("Test advisor: Change Set test strategy", addBlockedBy: [analysis-task-id])` → `TaskUpdate(owner: "test-advisor")`. DM test-advisor: `"**New Task**: #{task-id} — Recommend test types per NodeID."`
399
- 4. Lead presents **Quality Gate #1** to user:
400
- - Change Set with NodeIDs, descriptions, affected files
401
- - Dependency map showing which NodeIDs can be implemented in parallel
402
- - Risk assessment
403
- - Specialist Reports (if active — see gate template below)
404
- 5. User approves (or rejects re-run analyst with feedback)
405
- 6. Lead sends DM to architect with the approved Change Set
406
- 7. **Spec Drafting** choose path based on NodeID count and `PARALLEL_SPEC_THRESHOLD`:
407
-
408
- **Path A: Standard (fewer than PARALLEL_SPEC_THRESHOLD NodeIDs)**
409
- - Lead creates spec-drafting tasks for architect (1 task per NodeID, `addBlockedBy: [analysis-task-id]`):
410
- - `TaskCreate("Spec: NodeID-X")` `TaskUpdate(taskId, owner: "architect")`
411
- - DM architect with task IDs: `"**New Tasks**: #{id-1} Spec: NodeID-A, #{id-2} Spec: NodeID-B. Approved Change Set: {summary}"`
412
- - Architect is already warm (pre-loaded + speculative research during Stage 0) specs drafted FAST
413
- - If Gate #1 rejected: shut down architect, re-run analyst with feedback, re-spawn architect after
414
-
415
- **Path B: Parallel Spec Drafting (PARALLEL_SPEC_THRESHOLD or more NodeIDs)**
416
- - Lead DMs architect the full approved Change Set and asks for a partition plan (see `agents/architect.md` Parallel Spec Coordination)
417
- - Architect proposes NodeID partitions (1-2 NodeIDs each, max 3 partitions, respecting same-spec and interface constraints)
418
- - Lead spawns spec-drafter agents one per partition:
419
- - Spec-drafters use the `architect` agent definition with a scoped spawn prompt
420
- - Each drafter gets: its NodeID partition, architect's research findings, cross-NodeID interface constraints, consolidation instructions
421
- - `TaskCreate("Spec draft: NodeID-A, NodeID-B")` `TaskUpdate(owner: "spec-drafter-1")`
422
- - Max 3 spec-drafters: `ceil(NodeID_count / 2)`, capped at 3
423
- - Spec-drafters draft specs in parallel
424
- - After all spec-drafters complete: architect runs consistency review (cross-spec alignment, naming, VERIFY coverage)
425
- - Shut down spec-drafters after consistency review
426
- - If Gate #1 rejected: shut down architect and any spec-drafters, re-run analyst with feedback, re-spawn architect after
427
-
428
- 8. Architect completes specs (Path A) or architect completes consistency review (Path B)
429
- 9. **Test-advisor spec review** (if `test-advisor` in `SPECIALISTS_ENABLED`): After specs drafted, create spec testability review task:
430
- - `TaskCreate("Test advisor: spec testability review", addBlockedBy: [spec-task-id])` `TaskUpdate(owner: "test-advisor")`
431
- - DM test-advisor: `"**New Task**: #{task-id} Review specs for testability. Check VERIFY criteria are automatable."`
432
- 10. Lead presents **Quality Gate #2** to user:
433
- - Spec summaries with VERIFY criteria
434
- - Specialist Reports (if active — see gate template below)
435
- 11. User approves (or rejects architect revises)
436
- 12. Pre-implementation commit: `git add knowzcode/ && git commit -m "KnowzCode: Specs approved for {wgid}"`
437
- 13. Shut down context-scouts (no longer needed after specs approved). Keep knowz-scout alive for vault queries during implementation.
438
- 14. Keep analyst alive briefly (available for scope questions during early implementation)
439
- 15. Keep architect alive through Stage 2 (consultative role — spec clarifications for builders, no code or spec edits)
440
-
441
- ### Stage 2: Parallel Implementation + Incremental Review
442
-
443
- 1. Lead examines dependency map from analyst:
444
- - Group NodeIDs into independent partitions (no shared files between groups)
445
- - Determine builder count: 1 builder per independent group, max `MAX_BUILDERS` (default 5, configurable in `knowzcode_orchestration.md`)
446
-
447
- 2. Create builder tasks and spawn:
448
- - `TaskCreate("Implement NodeIDs [A, B]", addBlockedBy: [spec-task-id])` → `TaskUpdate(owner: "builder-1")`
449
- - `TaskCreate("Implement NodeIDs [C]", addBlockedBy: [spec-task-id])` → `TaskUpdate(owner: "builder-2")`
450
- - `TaskCreate("Implement NodeIDs [D, E]", addBlockedBy: [spec-task-id])` → `TaskUpdate(owner: "builder-3")`
451
- Spawn each builder with its `{task-id}` in the spawn prompt.
452
- Each builder gets its partition's specs + affected files list.
453
- **NO TWO BUILDERS TOUCH THE SAME FILE**
454
-
455
- 3. Notify architect of builder spawn:
456
- - Lead DMs architect: `"Builders spawned for Stage 2. Introduce yourself to: {builder-1, builder-2, ...}"`
457
- - Architect sends brief availability message to each builder (see `agents/architect.md` Proactive Availability)
458
-
459
- 4. Each builder creates subtasks per NodeID in the task list:
460
- - `"TDD: NodeID-A tests"` `"TDD: NodeID-A implementation"` `"TDD: NodeID-A verify"`
461
- - Builder works through subtasks, marks each complete with summary
462
-
463
- 5. Create reviewer tasks and spawn — one per builder partition:
464
- - `TaskCreate("Audit partition 1: NodeIDs [A, B]", addBlockedBy: [implement-A-task-id])` `TaskUpdate(owner: "reviewer-1")`
465
- - `TaskCreate("Audit partition 2: NodeIDs [C]", addBlockedBy: [implement-C-task-id])` → `TaskUpdate(owner: "reviewer-2")`
466
- - `TaskCreate("Audit partition 3: NodeIDs [D, E]", addBlockedBy: [implement-D-task-id])` → `TaskUpdate(owner: "reviewer-3")`
467
- Spawn each reviewer with its `{task-id}` + partition's specs + VERIFY criteria.
468
- Reviewer stays idle until its paired builder marks first NodeID implementation complete.
469
- Each reviewer audits incrementally within its partition.
470
-
471
- 6. **Specialist implementation reviews** (if `SPECIALISTS_ENABLED` non-empty): Create specialist review tasks alongside reviewer audit tasks, same `addBlockedBy`:
472
- - If `security-officer` active one task per partition (runs parallel to reviewer):
473
- `TaskCreate("Security officer: review partition {N}", addBlockedBy: [implement-X-task-id])` `TaskUpdate(owner: "security-officer")`
474
- DM security-officer: `"**New Task**: #{task-id} Vulnerability scan for partition {N}. NodeIDs: {list}."`
475
- - If `test-advisor` active one task per partition:
476
- `TaskCreate("Test advisor: review partition {N} tests", addBlockedBy: [implement-X-task-id])` `TaskUpdate(owner: "test-advisor")`
477
- DM test-advisor: `"**New Task**: #{task-id} — Test quality review for partition {N}. NodeIDs: {list}."`
478
- - If `project-advisor` activeone observation task (not per-partition):
479
- `TaskCreate("Project advisor: observe implementation")` `TaskUpdate(owner: "project-advisor")`
480
- DM project-advisor: `"**New Task**: #{task-id} — Observe builder progress, note patterns and ideas. Deliver backlog proposals before gap loop."`
481
- **Gate #3 is NOT blocked by specialists.** If a specialist hasn't finished, gate shows `[Pending: {specialist}]`. Lead proceeds.
482
- **Project-advisor early shutdown**: After project-advisor delivers backlog proposals, shut it down (before the gap loop begins).
483
-
484
- 7. Gap flow (per-partition, parallel — persistent agents, DM messaging):
485
- a. Each reviewer marks audit task complete with structured gap report in summary
486
- b. Lead creates fix task and pre-assigns:
487
- `TaskCreate("Fix gaps: NodeID-A", addBlockedBy: [audit-task-id])` `TaskUpdate(owner: "builder-N")`
488
- c. Lead sends DM to builder with task ID and gap details:
489
- > **New Task**: #{fix-task-id} Fix gaps: NodeID-A
490
- > **Gaps**: {file path, VERIFY criterion not met, expected vs actual}
491
- > Fix each gap, re-run affected tests, report completion.
492
- d. Builder claims fix task, fixes gaps, re-runs tests, marks fix task complete
493
- e. Lead creates re-audit task and pre-assigns:
494
- `TaskCreate("Re-audit: NodeID-A", addBlockedBy: [gap-fix-task-id])` `TaskUpdate(owner: "reviewer-N")`
495
- f. Lead sends DM to reviewer: `"**New Task**: #{reaudit-task-id} Re-audit: NodeID-A. {gap list}"`
496
- g. Each builder-reviewer pair repeats independently until cleanno cross-partition blocking
497
- All builders and reviewers stay alive through the entire gap loop (no respawning)
498
-
499
- 8. Enterprise compliance (if enabled):
500
- - Lead creates parallel compliance task for each reviewer (scoped to their partition)
501
- - Reviewer checks compliance requirements from knowz-scout findings
502
- - Runs alongside ARC audits
503
-
504
- 9. Inter-agent communication during Stage 2:
505
- - builder architect: Spec clarification requests (direct messages)
506
- - architectbuilder: Design guidance and spec intent responses (direct messages)
507
- - builder builder: Dependency coordination (direct messages "I changed the User interface, FYI")
508
- - builder reviewer (same partition): Implementation complete notifications (via task system)
509
- - reviewerlead: Gap reports per partition (structured format via task summaries)
510
- - leadbuilder: Fix tasks (via task creation + DM)
511
- - lead → reviewer: Re-audit requests (via task creation + DM)
512
- - security-officerbuilder-N: Security guidance for sensitive partitions (max 2 DMs per builder)
513
- - test-advisor → builder-N: Test improvement feedback (max 2 DMs per builder)
514
- - security-officer test-advisor: Cross-cutting test gaps in security paths (max 2 inter-specialist DMs)
515
- - project-advisor knowz-scribe: Idea captures for vault storage
516
- - project-advisor → lead: Backlog proposals (before gap loop)
517
-
518
- 10. After all NodeIDs implemented + audited across all partitions:
519
- - Lead consolidates audit results from all reviewers
520
- - Lead consolidates specialist reports (if `SPECIALISTS_ENABLED` non-empty — include even if some specialist tasks are still pending, noting `[Pending: {specialist}]`)
521
- - Lead presents **Quality Gate #3**:
522
- - Per-NodeID ARC completion % (from each partition's reviewer)
523
- - Combined security posture
524
- - Combined integration health
525
- - Enterprise compliance (if applicable)
526
- - Specialist Reports (if active — see gate template below)
527
- - User decides: proceed / fix gaps / modify specs / cancel
528
-
529
- 11. Shut down analyst, architect, all builders, and all reviewers
530
-
531
- ### Stage 3: Finalization
532
-
533
- 1. Shut down remaining specialists (security-officer, test-advisor) if still active. Project-advisor should already be shut down from mid-Stage 2.
534
- 2. `TaskCreate("Phase 3: Finalize {wgid}", addBlockedBy: [last-audit-task-id])` `TaskUpdate(owner: "closer")`
535
- Spawn `closer` with `{task-id}` in spawn prompt.
536
- 3. Closer tasks (can be parallel subtasks):
537
- - Update all specs to FINAL as-built
538
- - Update `knowzcode_tracker.md`: all NodeIDs `[WIP]` `[VERIFIED]`
539
- - Write ARC-Completion log entry
540
- - Review architecture docs for discrepancies
541
- - Schedule REFACTOR tasks for tech debt
542
- - Create capture task for knowz-scribe (if active): `TaskCreate("Scribe: Capture Phase 3")` → `TaskUpdate(owner: "knowz-scribe")`, then send DM with task ID: `"Capture Phase 3: {wgid}. Your task: #{task-id}"`. Knowz-scout remains available for vault queries during finalization.
543
- - Create final atomic commit
544
- 4. Lead presents completion summary
545
- 5. **Wait for scribe Phase 3 capture** (if knowz-scribe is active):
546
- - Check scribe capture task via `TaskGet(task-id)` — wait until status is `completed`
547
- - Also wait for scribe's Phase 3 confirmation DM
548
- - **Timeout**: If >2 minutes after closer completes and scribe task still not complete → DM scribe: `"Status check: Phase 3 capture for {wgid}?"`
549
- - **Hard timeout**: If another minute passes with no completion proceed with shutdown and log `WARNING: Scribe Phase 3 capture did not complete for {wgid}. Vault writes may be incomplete.`
550
- 6. Shutdown order: knowz-scout, knowz-scribe, closer, remaining agents
551
- 7. Delete team
552
-
553
- ### WorkGroup File Format (Parallel Mode)
554
-
555
- In Parallel Teams mode, the WorkGroup file uses per-NodeID phase tracking instead of a single `Current Phase`:
556
-
557
- ```markdown
558
- ## Change Set
559
- | NodeID | Phase | Builder | Status | Timestamp |
560
- |--------|-------|---------|--------|-----------|
561
- | Authentication | 2A | builder-1 | Implementing | ... |
562
- | UserProfile | 2B | builder-1 | Under review | ... |
563
- | LIB_DateFormat | 2A | builder-2 | Tests passing | ... |
564
-
565
- ## Autonomous Mode
566
- Active/Inactive
567
-
568
- ## Current Stage
569
- Stage 2: Parallel Implementation + Incremental Review
570
- ```
571
-
572
- ### Task Dependency Graph
573
-
574
- When creating tasks, model the dependency chain with `addBlockedBy` and pre-assign with `owner`:
575
-
576
- | Task | Blocked By | Owner |
577
- |------|-----------|-------|
578
- | Scout: specs context | (none) | context-scout-specs |
579
- | Scout: workgroups context | (none) | context-scout-workgroups |
580
- | Scout: backlog context | (none) | context-scout-backlog |
581
- | Knowz-scout: vault queries | (none — persistent) | knowz-scout |
582
- | Knowz-scribe: listen | (none — persistent) | knowz-scribe |
583
- | Scanner: direct codebase scan | (none) | scanner-direct |
584
- | Scanner: test coverage scan | (none) | scanner-tests |
585
- | Phase 1A analysis | (none — scouts + scanners enrich via broadcast) | analyst |
586
- | Architect pre-load + speculative research | (none — receives [PRELIMINARY] DMs from analyst) | architect |
587
- | Security officer: initial threat scan | (none — Group C) | security-officer |
588
- | Test advisor: coverage baseline | (none — Group C) | test-advisor |
589
- | Project advisor: backlog context | (none — Group C) | project-advisor |
590
- | Security officer: Change Set review | Phase 1A analysis | security-officer |
591
- | Test advisor: Change Set test strategy | Phase 1A analysis | test-advisor |
592
- | Spec: NodeID-X | Phase 1A (gate approval) | architect (Path A) or spec-drafter-N (Path B) |
593
- | Spec consistency review | All spec drafts complete (Path B only) | architect |
594
- | Test advisor: spec testability review | Spec: NodeID-X | test-advisor |
595
- | Implement: NodeID-X | Spec: NodeID-X | builder-N |
596
- | Audit: NodeID-X | Implement: NodeID-X | reviewer-N |
597
- | Security officer: review partition N | Implement: NodeID-X | security-officer |
598
- | Test advisor: review partition N tests | Implement: NodeID-X | test-advisor |
599
- | Project advisor: observe implementation | (none) | project-advisor |
600
- | Fix gaps: NodeID-X round N | Audit: NodeID-X (or re-audit N-1) | builder-N |
601
- | Re-audit: NodeID-X round N | Fix gaps round N | reviewer-N |
602
- | Phase 3 finalization | All audits approved | closer |
603
- | Scribe: Capture Phase 1A | Phase 1A (gate approval) | knowz-scribe |
604
- | Scribe: Capture Phase 2A | Implement: NodeID-X | knowz-scribe |
605
- | Scribe: Capture Phase 2B | All audits approved | knowz-scribe |
606
- | Scribe: Capture Phase 3 | Phase 3 finalization | knowz-scribe |
607
-
608
- ---
609
-
610
- ## Sequential Teams / Subagent Flow (Tier 3 Fallback)
611
-
612
- > **Note:** Sequential Teams does not use orchestration config settings except `MCP_AGENTS_ENABLED`.
613
-
614
- When using Sequential Teams (`--sequential`) or Subagent Delegation, follow the traditional one-agent-per-phase flow. For each phase below: spawn the agent, create a task, wait for completion, present quality gate, shut down agent, proceed to next phase.
615
-
616
- ### MCP Probe (Sequential/Subagent)
617
-
618
- Determine vault availability before Phase 1A:
619
-
620
- 1. Read `knowzcode/knowzcode_vaults.md` — check for CONFIGURED entries (non-empty ID)
621
- 2. Attempt `list_vaults(includeStats=true)`
622
- 3. If succeeds AND UNCREATED entries exist → present the **Vault Creation Prompt** (same as Parallel Teams Step 3d). Handle selection identically.
623
- 4. After resolution, announce MCP status to the user:
624
- - `list_vaults()` succeeded: `**MCP Status: Connected N vault(s) available**`
625
- - `list_vaults()` failed but configured vaults exist: `**MCP Status: Lead probe failed closer will verify at Phase 3**`
626
- - No configured vaults: `**MCP Status: Not configured**`
627
-
628
- The closer agent independently verifies MCP at Phase 3 regardless of this result (see `agents/closer.md` — Startup MCP Verification). This probe is for the user announcement and vault creation opportunity only.
629
-
630
- ---
631
-
632
- ## Phase Prompt Reference
633
-
634
- The spawn prompts below are shared by all execution modes. In Parallel Teams mode, the lead uses these prompts when spawning agents at the appropriate stage. In Sequential Teams / Subagent mode, agents are spawned one at a time in phase order.
635
-
636
- ## Stage 0: Context Scouts (3 instances)
637
-
638
- **Agent**: `context-scout` (x3) | Read-only local context researchers
639
-
640
- Three instances of the same agent, each focused on a different local folder group:
641
-
642
- **context-scout-specs spawn prompt**:
643
- > You are `context-scout-specs` for WorkGroup `{wgid}`.
644
- > Read `agents/context-scout.md` for your full role definition.
645
- > **Your Task**: #{task-id} — claim immediately (`TaskUpdate(status: "in_progress")`). Mark completed with summary when done.
646
- > **Focus area**: `knowzcode/specs/*.md` scan existing specifications.
647
- > **Goal**: {goal}
648
- > **READ-ONLY.** Do NOT modify any files.
649
- > **Deliverable**: Broadcast relevant spec findings (NodeIDs, status, VERIFY criteria overlapping with goal).
650
-
651
- **context-scout-workgroups spawn prompt**:
652
- > You are `context-scout-workgroups` for WorkGroup `{wgid}`.
653
- > Read `agents/context-scout.md` for your full role definition.
654
- > **Your Task**: #{task-id} — claim immediately (`TaskUpdate(status: "in_progress")`). Mark completed with summary when done.
655
- > **Focus area**: `knowzcode/workgroups/*.md` scan previous WorkGroups for similar goals.
656
- > **Goal**: {goal}
657
- > **READ-ONLY.** Do NOT modify any files.
658
- > **Deliverable**: Broadcast prior WorkGroup context (what was tried, what succeeded/failed, patterns).
659
-
660
- **context-scout-backlog spawn prompt**:
661
- > You are `context-scout-backlog` for WorkGroup `{wgid}`.
662
- > Read `agents/context-scout.md` for your full role definition.
663
- > **Your Task**: #{task-id} — claim immediately (`TaskUpdate(status: "in_progress")`). Mark completed with summary when done.
664
- > **Focus area**: `knowzcode/knowzcode_tracker.md`, `knowzcode/knowzcode_log.md`, `knowzcode/knowzcode_architecture.md`, `knowzcode/knowzcode_project.md`
665
- > **Goal**: {goal}
666
- > **READ-ONLY.** Do NOT modify any files.
667
- > **Deliverable**: Broadcast active WIP, REFACTOR tasks, architecture summary, and recent log patterns relevant to goal.
668
-
669
- **context-scout (combined) spawn prompt** (used when `SCOUT_MODE = "minimal"`):
670
- > You are `context-scout` for WorkGroup `{wgid}`.
671
- > Read `agents/context-scout.md` for your full role definition.
672
- > **Your Task**: #{task-id} — claim immediately. Mark completed with summary when done.
673
- > **Focus area**: ALL local context `knowzcode/specs/*.md`, `knowzcode/workgroups/*.md`, `knowzcode/knowzcode_tracker.md`, `knowzcode/knowzcode_log.md`, `knowzcode/knowzcode_architecture.md`, `knowzcode/knowzcode_project.md`
674
- > **Goal**: {goal}
675
- > **READ-ONLY.** Do NOT modify any files.
676
- > **Deliverable**: Broadcast consolidated findings covering specs, prior workgroups, active WIP, REFACTOR tasks, and architecture context.
677
-
678
- **Dispatch**:
679
- - *Parallel Teams*:
680
- - `SCOUT_MODE = "full"`: 3 context scouts spawned at Stage 0. Shut down after Gate #2.
681
- - `SCOUT_MODE = "minimal"`: 1 context-scout (combined) spawned at Stage 0. Shut down after Gate #2.
682
- - `SCOUT_MODE = "none"`: No scouts spawned.
683
- - *Sequential Teams*: Not applicable (scouts are Parallel Teams only).
684
- - *Subagent*:
685
- - `SCOUT_MODE = "full"`: 3 parallel `Task()` calls (specs, workgroups, backlog).
686
- - `SCOUT_MODE = "minimal"`: 1 `Task()` call with combined prompt.
687
- - `SCOUT_MODE = "none"`: Skip scout tasks.
688
-
689
- ---
690
-
691
- ## Stage 0: Codebase Scanners (2 instances — conditional)
692
-
693
- **Agent**: `general-purpose` (x2) | Lightweight codebase searchers (no agent definition file)
694
-
695
- Two temporary agents that scan the codebase in parallel with the analyst, broadcasting findings to accelerate impact analysis. Only spawned when `CODEBASE_SCANNER_ENABLED = true` (default).
696
-
697
- **scanner-direct spawn prompt**:
698
- > You are `scanner-direct` for WorkGroup `{wgid}`.
699
- > **Your Task**: #{task-id} claim immediately (`TaskUpdate(status: "in_progress")`). Mark completed with summary when done.
700
- > **Goal**: {goal}
701
- > **Focus**: Search source code for goal-related keywords and patterns.
702
- >
703
- > **Steps**:
704
- > 1. Grep for goal keywords across source files (exclude node_modules, dist, build, .git)
705
- > 2. Read the top 5-8 matching files to understand affected code paths
706
- > 3. Identify module boundaries and cross-module dependencies
707
- > 4. Note public APIs and interfaces that may need changes
708
- >
709
- > **READ-ONLY.** Do NOT modify any files.
710
- > **Deliverable**: Broadcast findings to all teammates — affected files, code paths, module boundaries, and interface patterns.
711
- > **Budget**: Complete within ~12 turns. Focus on breadth over depth.
712
-
713
- **scanner-tests spawn prompt**:
714
- > You are `scanner-tests` for WorkGroup `{wgid}`.
715
- > **Your Task**: #{task-id} claim immediately (`TaskUpdate(status: "in_progress")`). Mark completed with summary when done.
716
- > **Goal**: {goal}
717
- > **Focus**: Discover tests covering the goal area to understand test patterns and coverage shape.
718
- >
719
- > **Steps**:
720
- > 1. Glob for test files: `**/*.test.*`, `**/*.spec.*`, `**/test_*`, `**/tests/**`
721
- > 2. Grep test files for goal-related keywords
722
- > 3. Read 3-5 matching test files to understand testing patterns (test framework, mocking strategy, fixture patterns)
723
- > 4. Check for integration/e2e tests related to the goal area
724
- >
725
- > **READ-ONLY.** Do NOT modify any files.
726
- > **Deliverable**: Broadcast findings to all teammates — test file locations, testing patterns, coverage gaps, and fixture/mock patterns.
727
- > **Budget**: Complete within ~12 turns. Focus on breadth over depth.
728
-
729
- **Dispatch**:
730
- - *Parallel Teams*: Spawned at Stage 0 if `CODEBASE_SCANNER_ENABLED = true`. Use `subagent_type: "general-purpose"`, `maxTurns: 12`. Shut down after Stage 1 (analyst completes Change Set).
731
- - *Sequential Teams*: Not applicable (scanners are Parallel Teams only).
732
- - *Subagent*: `Task(subagent_type="general-purpose", description="Scan codebase for {focus}", maxTurns=12, prompt=<above>)` if `CODEBASE_SCANNER_ENABLED = true`.
733
-
734
- ---
735
-
736
- ## Stage 0: Knowz Scout
737
-
738
- **Agent**: `knowz-scout` | MCP vault researcher and knowledge agent
739
-
740
- **Spawn prompt**:
741
- > You are the **knowz-scout** for WorkGroup `{wgid}`.
742
- > Read `agents/knowz-scout.md` for your full role definition.
743
- > **Your Task**: #{task-id} — claim immediately (`TaskUpdate(status: "in_progress")`). Mark completed with summary when done.
744
- > **Goal**: {goal}
745
- > **Step 1**: Read `knowzcode/knowzcode_vaults.md` to discover configured vaults — their IDs, types, descriptions, and what knowledge each contains.
746
- > **Step 2**: For each configured vault, construct goal-relevant queries using the vault's description to guide what to ask. If a single vault covers all knowledge, consolidate queries there.
747
- > **Deliverable**: Broadcast vault knowledge findings to all teammates.
748
-
749
- **Dispatch**:
750
- - *Parallel Teams*: **Group B** — spawned at Stage 0 if `VAULTS_CONFIGURED = true`, no blockedBy. Persistent — stays alive through the entire workflow. Shut down after Phase 3 capture is complete.
751
- - *Sequential Teams*: Not applicable (scouts are Parallel Teams only).
752
- - *Subagent*: `Task(subagent_type="knowz-scout", description="Query vault for domain knowledge", prompt=<above>)` (only if MCP Probe passes)
753
-
754
- ---
755
-
756
- ## Stage 0: Knowz Scribe
757
-
758
- **Agent**: `knowz-scribe` | Persistent vault write agent (Haiku)
759
-
760
- **Spawn prompt**:
761
- > You are the **knowz-scribe** for WorkGroup `{wgid}`.
762
- > Read `agents/knowz-scribe.md` for your full role definition.
763
- > **Your Task**: #{task-id} — claim immediately (`TaskUpdate(status: "in_progress")`). Mark completed with summary when done.
764
- > **WorkGroup file**: `knowzcode/workgroups/{wgid}.md`
765
- > **Vault config**: Read `knowzcode/knowzcode_vaults.md` to discover configured vaults and resolve vault IDs by type.
766
- > **You are a message-driven agent.** Wait for capture messages from teammates (e.g., "Capture Phase 1A: {wgid}"). On each message, read the WorkGroup file, extract relevant learnings, and write to the appropriate vault.
767
- > **Do NOT read or modify source code.** You only read knowzcode/ files and write to MCP vaults.
768
-
769
- **Dispatch**:
770
- - *Parallel Teams*: **Group B** — spawned at Stage 0 if `VAULTS_CONFIGURED = true`, no blockedBy. Persistent — stays alive through the entire workflow. Shut down after Phase 3 capture is complete.
771
- - *Sequential Teams*: Not applicable (knowz-scribe is Parallel Teams only).
772
- - *Subagent*: Not applicable — vault writes in subagent mode are handled by the closer during Phase 3 finalization (see Direct Write Fallback in `agents/closer.md`).
773
-
774
- ---
775
-
776
- ## Specialist Spawn Prompts (Group C — opt-in via `--specialists`)
777
-
778
- The spawn prompts below are used when `SPECIALISTS_ENABLED` is non-empty. Specialists are spawned at Stage 0 alongside Groups A and B.
779
-
780
- **Dispatch** (all specialists):
781
- - *Parallel Teams*: Group C — spawned at Stage 0 if `SPECIALISTS_ENABLED` non-empty, no blockedBy. Security-officer and test-advisor persist through Gate #3. Project-advisor shuts down mid-Stage 2.
782
- - *Sequential Teams*: Not supportedannounce skip reason.
783
- - *Subagent*: `Task()` calls with spawn prompts below.
784
-
785
- ### Security Officer
786
-
787
- **Agent**: `security-officer` | Officer — CRITICAL/HIGH findings block gates
788
-
789
- **Spawn prompt**:
790
- > You are the **security-officer** for WorkGroup `{wgid}`.
791
- > Read `agents/security-officer.md` for your full role definition.
792
- > **Your Task**: #{task-id} — claim immediately (`TaskUpdate(status: "in_progress")`). Mark completed with summary when done.
793
- > **Goal**: {goal}
794
- > **READ-ONLY.** Do NOT modify any files. Bash is for read-only security scanning only.
795
- > **Stage 0 Deliverable**: Build STRIDE-lite threat model. Scan for auth/PII/crypto/session patterns. Broadcast initial threat assessment.
796
- > **Authority**: CRITICAL/HIGH findings use `[SECURITY-BLOCK]` tag lead MUST pause autonomous mode.
797
- > **Communication**: DM lead at gates. DM architect with security VERIFY criteria needs. DM builders in security-sensitive partitions (max 2 per builder). DM test-advisor for cross-cutting test gaps (max 2).
798
- > **Enterprise Compliance**: If `knowzcode/enterprise/compliance_manifest.md` exists and `compliance_enabled: true`, read active security guidelines and cross-reference findings with enterprise guideline IDs.
799
-
800
- ### Test Advisor
801
-
802
- **Agent**: `test-advisor` | Advisor — informational only
803
-
804
- **Spawn prompt**:
805
- > You are the **test-advisor** for WorkGroup `{wgid}`.
806
- > Read `agents/test-advisor.md` for your full role definition.
807
- > **Your Task**: #{task-id} — claim immediately (`TaskUpdate(status: "in_progress")`). Mark completed with summary when done.
808
- > **Goal**: {goal}
809
- > **READ-ONLY.** Do NOT modify any files. Bash is for read-only operations only (git log, coverage reports).
810
- > **Stage 0 Deliverable**: Establish test coverage baseline. Glob test files, run coverage if available. Broadcast baseline.
811
- > **Communication**: DM lead at gates. DM architect if VERIFY criteria aren't testable. DM builders with test improvement feedback (max 2 per builder). DM security-officer for cross-cutting security test gaps (max 2).
812
- > **Enterprise Compliance**: If `knowzcode/enterprise/compliance_manifest.md` exists and `compliance_enabled: true`, check enterprise ARC criteria for test coverage gaps.
813
-
814
- ### Project Advisor
815
-
816
- **Agent**: `project-advisor` | Advisor — informational only
817
-
818
- **Spawn prompt**:
819
- > You are the **project-advisor** for WorkGroup `{wgid}`.
820
- > Read `agents/project-advisor.md` for your full role definition.
821
- > **Your Task**: #{task-id} — claim immediately (`TaskUpdate(status: "in_progress")`). Mark completed with summary when done.
822
- > **Goal**: {goal}
823
- > **READ-ONLY.** Do NOT modify any files.
824
- > **Stage 0 Deliverable**: Read tracker for existing REFACTOR tasks and backlog context. DM lead with context summary.
825
- > **Lifecycle**: You shut down mid-Stage 2 after delivering backlog proposals before the gap loop.
826
- > **Communication**: DM lead with backlog context and proposals. DM knowz-scribe with idea captures (if active). Do NOT DM builders or other specialists.
827
- > **Enterprise Compliance**: If `knowzcode/enterprise/compliance_manifest.md` exists, note compliance configuration gaps in backlog proposals.
828
-
829
- ---
830
-
831
- ## Phase 1A: Impact Analysis
832
-
833
- **Agent**: `analyst` | **Loop.md**: Section 3.1
834
-
835
- **Spawn prompt**:
836
- > You are the **analyst** for WorkGroup `{wgid}`.
837
- > Read `agents/analyst.md` for your full role definition.
838
- >
839
- > **Goal**: {goal}
840
- > **Context files**: Read sections 1-2 and 3.1 of `knowzcode/knowzcode_loop.md` (skip other phases), `knowzcode/knowzcode_tracker.md`, `knowzcode/knowzcode_project.md`, `knowzcode/knowzcode_architecture.md`
841
- > **WorkGroup file**: `knowzcode/workgroups/{wgid}.md`
842
- >
843
- > **Your Task**: #{task-id} — claim immediately (`TaskUpdate(status: "in_progress")`). Mark completed with summary when done.
844
- > **Conventions**: Update WorkGroup file with results (prefix entries with `KnowzCode:`). If blocked, report blocker and notify lead.
845
- > **Codebase scanners**: Scanner agents are running in parallel their findings will arrive as broadcast messages. Incorporate them into your analysis but do NOT wait for them.
846
- > **Preliminary Findings Protocol**: As you discover high-confidence NodeIDs, DM the architect with `[PRELIMINARY]` messages (max 3 see `agents/analyst.md` for format). This lets the architect start speculative research early.
847
- > **Deliverable**: Change Set proposal written to the WorkGroup file. Include NodeIDs, descriptions, affected files, risk assessment, and dependency map (for Parallel Teams mode).
848
-
849
- **Dispatch**:
850
- - *Parallel Teams*: Spawned at Stage 0 alongside scouts, scanners, and architect. Starts immediately (no blockedBy).
851
- - *Sequential Teams*: Spawn teammate `analyst`, create task `Phase 1A: Impact analysis for "{goal}"`, wait for completion.
852
- - *Subagent*: `Task(subagent_type="analyst", description="Phase 1A impact analysis", prompt=<above>)`
853
-
854
- ### Quality Gate #1
855
-
856
- Present the Change Set for user approval:
857
-
858
- ```markdown
859
- ## Approval Gate #1: Change Set
860
-
861
- **WorkGroupID**: {wgid}
862
- **Proposed Change Set** ({N} nodes):
863
- {NodeIDs with descriptions}
864
-
865
- **Dependency Map** (Parallel Teams):
866
- {NodeID parallelism groups}
867
-
868
- **Risk Assessment**: {Low/Medium/High}
869
-
870
- ### Specialist Reports [only when SPECIALISTS_ENABLED non-empty]
871
- **Security Officer**: {risk assessment per NodeID, attack surface changes, threat model}
872
- **Architect**: {architecture impact, layer touch points, pattern alignment}
873
- **Test Advisor**: {coverage baseline, test strategy recommendations per NodeID}
874
-
875
- Approve this Change Set to proceed to specification?
876
- ```
877
-
878
- **Autonomous Mode**: If `AUTONOMOUS_MODE = true`, present gate info for transparency, log `[AUTO-APPROVED] Gate #1`, and proceed immediately.
879
- If `AUTONOMOUS_MODE = false`: If rejected re-run analyst with user feedback. If approved update tracker, proceed.
880
-
881
- ### MCP Learning Capture (Optional)
882
-
883
- If MCP is configured and knowz-scribe is active, after Change Set approval:
884
- - Create capture task: `TaskCreate("Scribe: Capture Phase 1A")` `TaskUpdate(owner: "knowz-scribe")`
885
- - Send message to **knowz-scribe** with task ID: `"Capture Phase 1A: {wgid}. Your task: #{task-id}"` — the scribe reads the WorkGroup file, extracts scope/risk/decision data, and writes to the appropriate vault
886
- - `search_knowledge({resolved_domain_vault_id}, "patterns for {domain}")` — pull relevant past learnings to inform specification
887
- - Share any relevant findings with the architect in the Phase 1B prompt
888
-
889
- ---
890
-
891
- ## Stage 0: Architect Pre-load (Parallel Teams)
892
-
893
- **Agent**: `architect` | Spawned at Stage 0 for context pre-loading and speculative research
894
-
895
- In Parallel Teams mode, the architect is spawned at Stage 0 (not at Phase 1B). It pre-loads architecture context and performs speculative research on `[PRELIMINARY]` NodeIDs from the analyst.
896
-
897
- **Stage 0 spawn prompt** (Parallel Teams only):
898
- > You are the **architect** for WorkGroup `{wgid}`.
899
- > Read `agents/architect.md` for your full role definition.
900
- >
901
- > **Goal**: {goal}
902
- > **Context files**: Read sections 1-2 and 3.2 of `knowzcode/knowzcode_loop.md` (skip other phases), `knowzcode/knowzcode_project.md`, `knowzcode/knowzcode_architecture.md`
903
- > **WorkGroup file**: `knowzcode/workgroups/{wgid}.md`
904
- > **Specs directory**: `knowzcode/specs/`
905
- >
906
- > **Your Task**: #{task-id} — claim immediately (`TaskUpdate(status: "in_progress")`). Mark completed with summary when done.
907
- > **Stage 0 Role**: Pre-load architecture context, then perform speculative research on any `[PRELIMINARY]` NodeID messages from the analyst (see Speculative Research Protocol in `agents/architect.md`). READ-ONLY research do NOT write specs yet.
908
- > **Lifecycle**: You persist through the entire workflow. After Gate #1, you will receive spec-drafting tasks via DM. After Gate #2, you shift to consultative role for builders.
909
-
910
- After Gate #1, the lead sends the approved Change Set via DM and creates spec-drafting tasks. For spec-drafting prompts, see Phase 1B below.
911
-
912
- ---
913
-
914
- ## Phase 1B: Specification
915
-
916
- **Agent**: `architect` | **Loop.md**: Section 3.2
917
-
918
- **Spec-drafting prompt** (sent via DM to already-warm architect in Parallel Teams, or as spawn prompt in Sequential/Subagent):
919
- > You are the **architect** for WorkGroup `{wgid}`.
920
- > Read `agents/architect.md` for your full role definition.
921
- >
922
- > **Goal**: {goal}
923
- > **Approved Change Set**: {NodeIDs from Gate #1}
924
- > **Context files**: Read sections 1-2 and 3.2 of `knowzcode/knowzcode_loop.md` (skip other phases), `knowzcode/knowzcode_project.md`, `knowzcode/knowzcode_architecture.md`
925
- > **WorkGroup file**: `knowzcode/workgroups/{wgid}.md`
926
- > **Specs directory**: `knowzcode/specs/`
927
- >
928
- > **Your Task**: #{task-id} — claim immediately (`TaskUpdate(status: "in_progress")`). Mark completed with summary when done.
929
- > **Conventions**: Update WorkGroup file with results (prefix entries with `KnowzCode:`). If blocked, report blocker and notify lead.
930
- > **Deliverable**: Finalized specs for all NodeIDs written to `knowzcode/specs/`.
931
-
932
- **Spec-drafter spawn prompt** (Path B — 3+ NodeIDs, Parallel Teams only):
933
- > You are `spec-drafter-{N}` for WorkGroup `{wgid}`.
934
- > Read `agents/architect.md` for your full role definition — you follow the same Spec Philosophy, Spec Format, and Consolidation Mandate.
935
- >
936
- > **Goal**: {goal}
937
- > **Your NodeIDs**: {partition — 1-2 NodeIDs assigned to this drafter}
938
- > **Architect Research**: {research findings from architect's speculative research for these NodeIDs}
939
- > **Cross-NodeID Constraints**: {interface dependencies, shared specs, naming conventions from architect}
940
- > **Context files**: Read sections 1-2 and 3.2 of `knowzcode/knowzcode_loop.md`, `knowzcode/knowzcode_project.md`, `knowzcode/knowzcode_architecture.md`
941
- > **WorkGroup file**: `knowzcode/workgroups/{wgid}.md`
942
- > **Specs directory**: `knowzcode/specs/`
943
- >
944
- > **Your Task**: #{task-id} — claim immediately (`TaskUpdate(status: "in_progress")`). Mark completed with summary when done.
945
- > **Deliverable**: Draft specs for your assigned NodeIDs written to `knowzcode/specs/`. The architect will review for consistency after all drafters finish.
946
-
947
- **Dispatch**:
948
- - *Parallel Teams*:
949
- - **Path A** (< PARALLEL_SPEC_THRESHOLD NodeIDs): Architect is already warm from Stage 0 pre-load + speculative research. Lead sends DM with approved Change Set, then creates spec-drafting tasks. **Plan approval enabled** — add to prompt: `Present your spec design for lead review BEFORE writing final specs. Wait for approval.` If `AUTONOMOUS_MODE = true`: auto-approve `plan_approval_request` immediately. Log `[AUTO-APPROVED] Architect plan`.
950
- - **Path B** (>= PARALLEL_SPEC_THRESHOLD NodeIDs): Lead asks architect for partition plan. Architect proposes partitions. Lead spawns spec-drafters (`subagent_type: "architect"`, `permissionMode: "acceptEdits"`, `maxTurns: 15`) with partition-scoped prompts. After all drafters complete, architect runs consistency review and reports to lead.
951
- - *Sequential Teams*: Spawn teammate `architect`, create task `Phase 1B: Draft specifications for {N} NodeIDs`. **Plan approval enabled** add to prompt: `Present your spec design for lead review BEFORE writing final specs. Wait for approval.` Wait for `plan_approval_request`, review, respond with `plan_approval_response`. If `AUTONOMOUS_MODE = true`: auto-approve immediately. Log `[AUTO-APPROVED] Architect plan`.
952
- - *Subagent*: `Task(subagent_type="architect", description="Phase 1B specification drafting", prompt=<above> + "Present your spec design in your output for lead review.")`
953
-
954
- > **Note:** Plan approval (agent pauses for lead review) only works in Agent Teams mode via `permissionMode: plan`. In subagent mode, the architect presents its design in the output for post-hoc review. Spec-drafters (Path B) do NOT use plan approval — they follow the architect's partition briefing directly.
955
-
956
- ### Quality Gate #2
957
-
958
- Present specs for batch approval:
959
-
960
- ```markdown
961
- ## Approval Gate #2: Specifications
962
-
963
- **Specs Drafted**: {count}
964
- | NodeID | File | Key VERIFY Criteria |
965
- |--------|------|---------------------|
966
- | ... | ... | ... |
967
-
968
- ### Specialist Reports [only when SPECIALISTS_ENABLED non-empty]
969
- **Architect**: {specs align with component map, drift concerns, pattern consistency}
970
- **Test Advisor**: {spec testability assessment, recommended test types per NodeID}
971
-
972
- Review specs and approve to proceed to implementation?
973
- ```
974
-
975
- **Autonomous Mode**: If `AUTONOMOUS_MODE = true`, present gate info for transparency, log `[AUTO-APPROVED] Gate #2`, and proceed immediately.
976
- If `AUTONOMOUS_MODE = false`: If rejected re-run specs needing revision. If approved pre-implementation commit, proceed.
977
-
978
- **Pre-Implementation Commit:**
979
- ```bash
980
- git add knowzcode/
981
- git commit -m "KnowzCode: Specs approved for {WorkGroupID}"
982
- ```
983
-
984
- ---
985
-
986
- ## Phase 2A: Implementation
987
-
988
- **Agent**: `builder` | **Loop.md**: Section 3.3
989
-
990
- **Spawn prompt**:
991
- > You are the **builder** for WorkGroup `{wgid}`.
992
- > Read `agents/builder.md` for your full role definition.
993
- >
994
- > **Goal**: {goal}
995
- > **Approved Change Set**: {NodeIDs}
996
- > **Specs**: {list of spec file paths from Phase 1B}
997
- > **Context files**: Read sections 1-2 and 3.3 of `knowzcode/knowzcode_loop.md` (skip other phases), `knowzcode/knowzcode_project.md`
998
- > **WorkGroup file**: `knowzcode/workgroups/{wgid}.md`
999
- >
1000
- > **Your Task**: #{task-id} — claim immediately (`TaskUpdate(status: "in_progress")`). Mark completed with summary when done.
1001
- > **Conventions**: Update WorkGroup file with results (prefix entries with `KnowzCode:`). If blocked, report blocker and notify lead.
1002
- > **TDD mandatory**: Write failing tests first, then implement, then refactor. Every NodeID must have tests.
1003
- > **Blocker protocol**: If you hit a blocker, document it as a Blocker Report in the WorkGroup file (see loop.md Section 11 format) and report to the lead immediately instead of guessing.
1004
- > **Deliverable**: All NodeIDs implemented with passing tests.
1005
-
1006
- **Dispatch**:
1007
- - *Parallel Teams*: Multiple builders spawned at Stage 2, one per partition from the dependency map. Each builder gets its partition's NodeIDs and specs. Builders create per-NodeID subtasks for visibility. **Plan approval enabled** — add to prompt: `Present your implementation approach for lead review BEFORE writing code. Wait for approval.` If `AUTONOMOUS_MODE = true`: auto-approve `plan_approval_request` immediately. Log `[AUTO-APPROVED] Builder plan`.
1008
- - *Sequential Teams*: Spawn teammate `builder`, create task `Phase 2A: Implement {N} NodeIDs with TDD`. **Plan approval enabled** — add to prompt: `Present your implementation approach for lead review BEFORE writing code. Wait for approval.` Wait for `plan_approval_request`, review, respond. If `AUTONOMOUS_MODE = true`: auto-approve immediately. Log `[AUTO-APPROVED] Builder plan`.
1009
- - *Subagent*: `Task(subagent_type="builder", description="Phase 2A TDD implementation", mode="bypassPermissions", prompt=<above>)`
1010
-
1011
- ### Phase 2A Output
1012
-
1013
- When complete, present implementation summary including files changed, tests written, and test results.
1014
-
1015
- ### MCP Learning Capture (Optional)
1016
-
1017
- If MCP is configured and knowz-scribe is active, after implementation completes:
1018
- - Create capture task: `TaskCreate("Scribe: Capture Phase 2A")` `TaskUpdate(owner: "knowz-scribe")`
1019
- - Send message to **knowz-scribe** with task ID: `"Capture Phase 2A: {wgid}. Your task: #{task-id}"` — the scribe reads implementation results from the WorkGroup file and captures patterns, workarounds, and performance optimizations to the `code` vault
1020
-
1021
- ---
1022
-
1023
- ## Phase 2B: Completeness Audit
1024
-
1025
- **Agent**: `reviewer` | **Loop.md**: Section 3.4
1026
-
1027
- **Spawn prompt**:
1028
- > You are the **reviewer** for WorkGroup `{wgid}`.
1029
- > Read `agents/reviewer.md` for your full role definition.
1030
- >
1031
- > **Goal**: {goal}
1032
- > **Change Set**: {NodeIDs}
1033
- > **Specs**: {list of spec file paths}
1034
- > **Context files**: Read sections 1-2 and 3.4 of `knowzcode/knowzcode_loop.md` (skip other phases), `knowzcode/knowzcode_project.md`, `knowzcode/knowzcode_architecture.md`
1035
- > **WorkGroup file**: `knowzcode/workgroups/{wgid}.md`
1036
- >
1037
- > **Your Task**: #{task-id} — claim immediately (`TaskUpdate(status: "in_progress")`). Mark completed with summary when done.
1038
- > **Conventions**: Update WorkGroup file with results (prefix entries with `KnowzCode:`). If blocked, report blocker and notify lead.
1039
- > **This is a READ-ONLY audit.** Do not modify any source code or test files.
1040
- > **Deliverable**: Audit report with ARC completion %, security posture, and gap list.
1041
-
1042
- **Dispatch**:
1043
- - *Parallel Teams*: One reviewer per builder partition, spawned at Stage 2. Each reviewer gets its partition's NodeIDs and specs. Audit tasks use `addBlockedBy` per implementation task. Each reviewer uses structured gap report format (see `agents/reviewer.md`).
1044
- - *Sequential Teams*: Spawn teammate `reviewer`, create task `Phase 2B: Completeness audit for {N} NodeIDs`, wait for completion.
1045
- - *Subagent*: `Task(subagent_type="reviewer", description="Phase 2B completeness audit", prompt=<above>)`
1046
-
1047
- ### Quality Gate #3
1048
-
1049
- Present audit results:
1050
-
1051
- ```markdown
1052
- ## Approval Gate #3: Audit Results
1053
-
1054
- **ARC Completion**: {X}%
1055
- **Security Posture**: {status}
1056
- **Gaps Found**: {count}
1057
-
1058
- ### Specialist Reports [only when SPECIALISTS_ENABLED non-empty]
1059
- **Security Officer**: Findings: {N} | Critical: {N} | High: {N} | {details or [Pending]}
1060
- **Architect**: Drift: {Yes/No} | Pattern Violations: {N} | {details}
1061
- **Test Advisor**: TDD Compliance: {%} | Missing Edge Cases: {N} | Quality: {Good/Adequate/Poor} | {details or [Pending]}
1062
- **Project Advisor**: New REFACTOR tasks: {N} | Ideas captured to vault: {N}
1063
-
1064
- **Recommendation**: {proceed / return to implementation}
1065
-
1066
- How would you like to proceed?
1067
- ```
1068
-
1069
- **Autonomous Mode**: If `AUTONOMOUS_MODE = true`:
1070
- - **Safety check**: If any security finding rated HIGH or CRITICAL (from reviewer OR security-officer `[SECURITY-BLOCK]`) **PAUSE** autonomous mode for this gate. Announce: `> **Autonomous Mode Paused** — HIGH/CRITICAL security finding requires manual review.`
1071
- - **Safety check**: If ARC completion < 50% → **PAUSE** autonomous mode for this gate. Announce: `> **Autonomous Mode Paused** — ARC completion below 50% requires manual review.`
1072
- - If safety checks pass and gaps foundlog `[AUTO-APPROVED] Gate #3proceeding to gap loop`, auto-proceed to gap loop.
1073
- - If safety checks pass and no gaps → log `[AUTO-APPROVED] Gate #3`, auto-proceed to Phase 3.
1074
-
1075
- If `AUTONOMOUS_MODE = false`: User decides — proceed / fix gaps / modify specs / cancel.
1076
-
1077
- ### Gap Loop (when user chooses to fix gaps)
1078
-
1079
- **Parallel Teams mode** (per-partition, persistent agents — no respawning):
1080
- 1. Lead reads each reviewer's structured gap report from task summary
1081
- 2. Lead creates fix task and pre-assigns:
1082
- `TaskCreate("Fix gaps: NodeID-X", addBlockedBy: [audit-task-id])` `TaskUpdate(owner: "builder-N")`
1083
- 3. Lead sends DM to builder with task ID and gap details:
1084
- `"**New Task**: #{fix-task-id} Fix gaps: NodeID-X. {file path, VERIFY criterion, expected vs actual}"`
1085
- 4. Builder claims fix task, fixes gaps, re-runs tests, marks fix task complete
1086
- 5. Lead creates re-audit task and pre-assigns:
1087
- `TaskCreate("Re-audit: NodeID-X", addBlockedBy: [gap-fix-task-id])` `TaskUpdate(owner: "reviewer-N")`
1088
- 6. Lead sends DM to reviewer: `"**New Task**: #{reaudit-task-id} Re-audit: NodeID-X. {gap list}"`
1089
- 7. Each builder-reviewer pair repeats independently until cleanno cross-partition blocking
1090
- 8. All builders and reviewers stay alive throughout
1091
- 9. **3-iteration cap per partition**: If a partition exceeds 3 gap-fix iterations without resolution, **PAUSE** autonomous mode for that partition (even if `AUTONOMOUS_MODE = true`). Announce: `> **Autonomous Mode Paused** — Partition {N} failed 3 gap-fix iterations. Manual review required.`
1092
-
1093
- **Sequential Teams mode**: Spawn a NEW `builder` with the standard Phase 2A prompt plus gap fix context. Then re-run Phase 2B (spawn a new reviewer). Repeat until user approves at Gate #3.
1094
-
1095
- **Subagent mode**: Launch parallel `Task()` calls — one for gap fix (builder), then one for re-audit (reviewer). Repeat as needed.
1096
-
1097
- ### MCP Learning Capture (Optional)
1098
-
1099
- If MCP is configured and knowz-scribe is active, after audit approval:
1100
- - Create capture task: `TaskCreate("Scribe: Capture Phase 2B")` `TaskUpdate(owner: "knowz-scribe")`
1101
- - Send message to **knowz-scribe** with task ID: `"Capture Phase 2B: {wgid}. Your task: #{task-id}"` — the scribe reads audit results from the WorkGroup file and writes findings to the appropriate vault
1102
-
1103
- ---
1104
-
1105
- ## Phase 3: Finalization
1106
-
1107
- **Agent**: `closer` | **Loop.md**: Section 3.5
1108
-
1109
- **Spawn prompt (Parallel Teams)**:
1110
- > You are the **closer** for WorkGroup `{wgid}`.
1111
- > Read `agents/closer.md` for your full role definition.
1112
- >
1113
- > **Goal**: {goal}
1114
- > **Change Set**: {NodeIDs}
1115
- > **Specs**: {list of spec file paths}
1116
- > **Context files**: Read sections 1-2, 3.5, 6, and 7 of `knowzcode/knowzcode_loop.md` (skip other phases), `knowzcode/knowzcode_tracker.md`, `knowzcode/knowzcode_project.md`, `knowzcode/knowzcode_architecture.md`, `knowzcode/knowzcode_log.md`
1117
- > **WorkGroup file**: `knowzcode/workgroups/{wgid}.md`
1118
- >
1119
- > **Your Task**: #{task-id} — claim immediately (`TaskUpdate(status: "in_progress")`). Mark completed with summary when done.
1120
- > **Conventions**: Update WorkGroup file with results (prefix entries with `KnowzCode:`). If blocked, report blocker and notify lead.
1121
- > **Vault writes**: Knowz-scribe is active. Create a capture task (`TaskCreate("Scribe: Capture Phase 3")` → `TaskUpdate(owner: "knowz-scribe")`), then send `"Capture Phase 3: {wgid}. Your task: #{task-id}"` to delegate learning capture and audit trail writes. Do NOT call `create_knowledge` directly.
1122
- > **Deliverable**: Atomic finalization update specs to FINAL, update tracker, write log entry, update architecture if needed, delegate learning capture to knowz-scribe, and create final commit.
1123
-
1124
- **Spawn prompt (Sequential Teams / Subagent)**:
1125
- > You are the **closer** for WorkGroup `{wgid}`.
1126
- > Read `agents/closer.md` for your full role definition.
1127
- >
1128
- > **Goal**: {goal}
1129
- > **Change Set**: {NodeIDs}
1130
- > **Specs**: {list of spec file paths}
1131
- > **Context files**: Read sections 1-2, 3.5, 6, and 7 of `knowzcode/knowzcode_loop.md` (skip other phases), `knowzcode/knowzcode_tracker.md`, `knowzcode/knowzcode_project.md`, `knowzcode/knowzcode_architecture.md`, `knowzcode/knowzcode_log.md`
1132
- > **WorkGroup file**: `knowzcode/workgroups/{wgid}.md`
1133
- >
1134
- > **Your Task**: #{task-id} — claim immediately (`TaskUpdate(status: "in_progress")`). Mark completed with summary when done.
1135
- > **Conventions**: Update WorkGroup file with results (prefix entries with `KnowzCode:`). If blocked, report blocker and notify lead.
1136
- > **Vault writes**: No knowz-scribe you own all vault writes. Follow the Direct Write Fallback in `agents/closer.md`.
1137
- > **Deliverable**: Atomic finalizationupdate specs to FINAL, update tracker, write log entry, update architecture if needed, write learnings to vaults, and create final commit.
1138
-
1139
- **Dispatch**:
1140
- - *Parallel Teams*: Spawned at Stage 3 (`addBlockedBy`: last audit/re-audit task). Use the **Parallel Teams** spawn prompt. All other agents shut down before closer starts, except knowz-scout and knowz-scribe (stay alive for Phase 3 capture).
1141
- - *Sequential Teams*: Spawn teammate `closer`, create task `Phase 3: Finalize WorkGroup {wgid}`, wait for completion. Use the **Sequential Teams / Subagent** spawn prompt.
1142
- - *Subagent*: `Task(subagent_type="closer", description="Phase 3 finalization", prompt=<Sequential/Subagent spawn prompt above>)`
1143
-
1144
- ### Phase 3 Output
1145
-
1146
- When complete, if MCP is configured and knowz-scribe is active:
1147
- - The closer creates a capture task (`TaskCreate("Scribe: Capture Phase 3")` → `TaskUpdate(owner: "knowz-scribe")`) and sends a message with the task ID: `"Capture Phase 3: {wgid}. Your task: #{task-id}"`. The lead waits for the scribe's capture task to complete before shutdown.
1148
-
1149
- Update workgroup to "Closed" and report:
1150
-
1151
- ```markdown
1152
- ## Workflow Complete
1153
-
1154
- **WorkGroupID**: {wgid}
1155
- **Primary Goal**: {$ARGUMENTS}
1156
- **Status**: VERIFIED and CLOSED
1157
-
1158
- - NodeIDs completed: {list}
1159
- - Specs finalized: {count}
1160
- - Tech debt scheduled: {count REFACTOR_ tasks}
1161
- ```
1162
-
1163
- ---
1164
-
1165
- ## Cleanup
1166
-
1167
- ### After Phase 3 Completes
1168
-
1169
- **Agent Teams Mode** (Parallel or Sequential):
1170
- 1. Shut down all active teammates. Wait for each to confirm shutdown.
1171
- 2. Once all teammates have shut down, clean up the team (delete the `kc-{wgid}` team).
1172
- No teammates or team resources should remain after the workflow ends.
1173
-
1174
- **Subagent Mode**: No cleanup needed `Task()` calls are self-contained.
1175
-
1176
- ### If User Cancels Mid-Workflow
1177
-
1178
- Follow the abandonment protocol from `knowzcode_loop.md` Section 12:
1179
-
1180
- 1. **Revert uncommitted changes** if implementation was in progress, revert source code changes (keep knowzcode files)
1181
- 2. **Update tracker** — set all affected NodeIDs back to their pre-WorkGroup status
1182
- 3. **Log abandonment** — create a log entry with type `WorkGroup-Abandoned` including the reason and phase at abandonment
1183
- 4. **Close WorkGroup file** — mark the WorkGroup as `Abandoned` with timestamp and reason
1184
- 5. **Preserve learnings** — if any useful patterns were discovered, capture them before closing
1185
- 6. **Team teardown** — (Agent Teams only) shut down all active teammates and delete the team
1186
- 7. **Parallel mode**: If cancelled mid-Stage-2, revert uncommitted code changes and mark WorkGroup abandoned
1187
-
1188
- The WorkGroup file remains in `knowzcode/workgroups/` for reference. It can be resumed later with `/kc:work` referencing the same goal.
1189
-
1190
- ---
1191
-
1192
- ## Handling Failures
1193
-
1194
- - Phase 1A rejected: re-run analyst with feedback
1195
- - Phase 1B rejected: re-run architect with specific issues (Parallel Teams: architect is already warm)
1196
- - Phase 2A blocker encountered: present Blocker Report (per loop.md Section 11) to user with 5 recovery options: (1) modify spec, (2) change approach, (3) split WorkGroup, (4) accept partial with documented gap, (5) cancel WorkGroup
1197
- - Phase 2B audit shows gaps: return to 2A with gap list (see Gap Loop above)
1198
- - If >3 failures on same phase: PAUSE and ask user for direction (applies even when `AUTONOMOUS_MODE = true` this is a safety exception)
1199
-
1200
- ## KnowzCode: Prefix Enforcement
1201
-
1202
- Every todo in workgroup files MUST start with `KnowzCode:`. Pass this to all agents.
1
+ ---
2
+ description: "Start a new KnowzCode development workflow with TDD, quality gates, and structured phases"
3
+ argument-hint: "[feature_description]"
4
+ ---
5
+
6
+ # Work on New Feature
7
+
8
+ Start a new KnowzCode development workflow session.
9
+
10
+ **Usage**: `/kc:work "feature description"`
11
+ **Example**: `/kc:work "Build user authentication with JWT"`
12
+
13
+ **Primary Goal**: $ARGUMENTS
14
+
15
+ ---
16
+
17
+ ## Step 0: Prerequisite Check
18
+
19
+ Verify KnowzCode is initialized:
20
+ 1. Check if `knowzcode/` directory exists
21
+ 2. Check required files exist: `knowzcode_loop.md`, `knowzcode_tracker.md`, `knowzcode_project.md`, `knowzcode_architecture.md`
22
+
23
+ If missing: inform user to run `/kc:init` first. STOP.
24
+
25
+ ## Step 1: Generate WorkGroup ID
26
+
27
+ **Format**: `kc-{type}-{slug}-YYYYMMDD-HHMMSS`
28
+
29
+ - `{type}`: feat, fix, refactor, or issue
30
+ - `{slug}`: 2-4 word kebab-case from goal (remove common words: build, add, create, implement, the, a, with, for)
31
+ - Truncate slug to max 25 characters
32
+
33
+ ## Step 2: Select Execution Mode
34
+
35
+ Determine the execution mode using try-then-fallback:
36
+
37
+ 1. Note user preferences from `$ARGUMENTS`:
38
+ - `--sequential` → prefer Sequential Teams
39
+ - `--subagent` → force Subagent Delegation (skip team creation attempt)
40
+
41
+ 2. **If `--subagent` NOT specified**, attempt `TeamCreate(team_name="kc-{wgid}")`:
42
+ - **If TeamCreate succeeds** → Agent Teams is available. Choose mode:
43
+ - `--sequential` or Tier 2 → **Sequential Teams**: `**Execution Mode: Sequential Teams** — created team kc-{wgid}`
44
+ - Otherwise → **Parallel Teams** (default for Tier 3): `**Execution Mode: Parallel Teams** — created team kc-{wgid}`
45
+ - **If TeamCreate fails** (error, unrecognized tool, timeout) → **Subagent Delegation**: `**Execution Mode: Subagent Delegation** — Agent Teams not available, using Task() fallback`
46
+
47
+ 3. **If `--subagent` specified** → **Subagent Delegation** directly (no TeamCreate attempt):
48
+ - Announce: `**Execution Mode: Subagent Delegation** — per user request`
49
+
50
+ For all Agent Teams modes (Sequential and Parallel):
51
+ - You are the **team lead** in delegate mode — you coordinate phases, present quality gates, and manage the workflow. You NEVER write code, specs, or project files directly. All work is done by teammates. (Tip: the user can press Shift+Tab to system-enforce delegate mode.)
52
+ - After completion or if the user cancels, shut down all active teammates and clean up the team (see Cleanup section)
53
+
54
+ For Subagent Delegation:
55
+ - For each phase, delegate via `Task()` with the parameters specified in phase sections below
56
+
57
+ The user MUST see the execution mode announcement before any phase work begins. The phases, quality gates, and interactions are identical across all paths.
58
+
59
+ > **Note:** Agent Teams is experimental and the API may change.
60
+
61
+ ## Step 2.4: Load Orchestration Config (Optional)
62
+
63
+ If `knowzcode/knowzcode_orchestration.md` exists, parse its YAML blocks:
64
+
65
+ 1. `MAX_BUILDERS` = `max_builders` value (default: 5, clamp to 1-5)
66
+ 2. `SCOUT_MODE` = `scout_mode` value (default: "full")
67
+ 3. `DEFAULT_SPECIALISTS` = `default_specialists` value (default: [])
68
+ 4. `MCP_AGENTS_ENABLED` = `mcp_agents_enabled` value (default: true)
69
+ 5. `CODEBASE_SCANNER_ENABLED` = `codebase_scanner_enabled` value (default: true)
70
+ 6. `PARALLEL_SPEC_THRESHOLD` = `parallel_spec_threshold` value (default: 3, clamp to 2-10)
71
+
72
+ Apply flag overrides (flags win over config):
73
+ - `--max-builders=N` in `$ARGUMENTS` → override `MAX_BUILDERS`
74
+ - `--no-scouts` in `$ARGUMENTS` → override `SCOUT_MODE = "none"`
75
+ - `--no-mcp` in `$ARGUMENTS` → override `MCP_AGENTS_ENABLED = false`
76
+ - `--no-scanners` in `$ARGUMENTS` → override `CODEBASE_SCANNER_ENABLED = false`
77
+ - `--no-parallel-specs` in `$ARGUMENTS` → override `PARALLEL_SPEC_THRESHOLD = 999` (effectively disabled)
78
+
79
+ If the file doesn't exist, use hardcoded defaults (current behavior).
80
+
81
+ ## Step 2.5: Autonomous Mode Detection
82
+
83
+ Set `AUTONOMOUS_MODE = true` if ANY of these match:
84
+
85
+ a. **Flags**: `$ARGUMENTS` contains `--autonomous` or `--auto`
86
+
87
+ b. **Natural language** (case-insensitive match in `$ARGUMENTS` OR the user's preceding conversation message):
88
+ - Approval intent: "approve all", "pre-approve", "preapprove", "auto-approve"
89
+ - Mode intent: "autonomous mode", "autonomous", "unattended", "hands off", "hands-off"
90
+ - Proceed intent: "don't stop to ask", "don't ask me", "no approval needed", "just run through", "run it all", "run straight through", "proceed without asking", "skip the gates", "go all the way through"
91
+ - Delegation intent: "I trust your judgement", "use your best judgement", "defer to your judgement", "you decide"
92
+
93
+ c. **Contextual** — if the user's message conveys clear intent for the lead to operate without stopping (even if none of the exact phrases above match), interpret that as autonomous mode. The spirit of the instruction matters more than exact phrasing.
94
+
95
+ Default: `AUTONOMOUS_MODE = false`
96
+
97
+ If `AUTONOMOUS_MODE = true`, announce after the execution mode announcement:
98
+ > **Autonomous Mode: ACTIVE** — Gates presented for transparency but auto-approved.
99
+ > Safety exceptions still pause: critical blockers, HIGH/CRITICAL security findings, >3 same-phase failures, complex architecture discrepancies, >3 gap-fix iterations per partition.
100
+
101
+ ## Step 2.6: Specialist Detection
102
+
103
+ Set `SPECIALISTS_ENABLED = []` (empty list).
104
+
105
+ If `DEFAULT_SPECIALISTS` is non-empty (from Step 2.4), initialize:
106
+ `SPECIALISTS_ENABLED = DEFAULT_SPECIALISTS`
107
+
108
+ Determine which specialists to activate (flags and natural language add to or override the baseline):
109
+ - `--specialists` → enable all 3: `[security-officer, test-advisor, project-advisor]`
110
+ - `--specialists=csv` → enable specific subset (comma-separated, e.g., `--specialists=security,test`):
111
+ - `security` → `security-officer`
112
+ - `test` → `test-advisor`
113
+ - `project` → `project-advisor`
114
+ - `--no-specialists` → explicit opt-out, `SPECIALISTS_ENABLED = []`
115
+
116
+ **Natural language detection** (case-insensitive match in `$ARGUMENTS` OR the user's preceding conversation message):
117
+ - All specialists: "with specialists", "with officers", "full specialist panel"
118
+ - security-officer: "security review", "threat model", "vulnerability scan", "pentest"
119
+ - test-advisor: "test quality", "TDD enforcement", "test coverage", "test rigor"
120
+ - project-advisor: "backlog", "future work", "brainstorm", "ideas"
121
+
122
+ **Mode constraints:**
123
+ - Tier 3 Parallel Teams: Full support (Group C)
124
+ - Tier 3 Subagent Delegation: Supported via parallel `Task()` calls
125
+ - Sequential Teams / Tier 2: Not supported — if specialists were detected, announce: `> **Specialists: SKIPPED** — not supported in {Sequential Teams / Tier 2} mode.`
126
+
127
+ Default: `SPECIALISTS_ENABLED = []` (specialists are opt-in).
128
+
129
+ If `SPECIALISTS_ENABLED` is non-empty, announce after the autonomous mode announcement (or after the execution mode announcement if autonomous is not active):
130
+ > **Specialists: ACTIVE** — {comma-separated list of enabled specialists}
131
+
132
+ ## Step 3: Load Context Files (ONCE)
133
+
134
+ Read these files ONCE (do NOT re-read between phases):
135
+ - `knowzcode/knowzcode_loop.md`
136
+ - `knowzcode/knowzcode_tracker.md`
137
+ - `knowzcode/knowzcode_project.md`
138
+ - `knowzcode/knowzcode_architecture.md`
139
+
140
+ ## Step 3.5: Pull Team Standards (MCP — Optional)
141
+
142
+ If MCP is configured and enterprise compliance is enabled:
143
+ 1. Check `knowzcode/enterprise/compliance_manifest.md` for `mcp_compliance_enabled: true`
144
+ 2. If enabled: Read `knowzcode/knowzcode_vaults.md` to find vault matching type "enterprise", then `ask_question({resolved_enterprise_vault_id}, "team standards for {project_type}")`
145
+ 3. Merge returned standards into WorkGroup context for quality gate criteria
146
+
147
+ If MCP is not configured or enterprise is not enabled, skip this step.
148
+
149
+ ## Step 4: Create WorkGroup File
150
+
151
+ Create `knowzcode/workgroups/{WorkGroupID}.md`:
152
+ ```markdown
153
+ # WorkGroup: {WorkGroupID}
154
+
155
+ **Primary Goal**: {$ARGUMENTS}
156
+ **Created**: {timestamp}
157
+ **Status**: Active
158
+ **Current Phase**: 1A - Impact Analysis
159
+ **Autonomous Mode**: Active/Inactive
160
+
161
+ ## Change Set
162
+ (Populated after Phase 1A)
163
+
164
+ ## Todos
165
+ - KnowzCode: Initialize WorkGroup
166
+ - KnowzCode: Complete Phase 1A impact analysis
167
+
168
+ ## Phase History
169
+ | Phase | Status | Timestamp |
170
+ |-------|--------|-----------|
171
+ | 1A | In Progress | {timestamp} |
172
+ ```
173
+
174
+ ## Step 5: Input Classification
175
+
176
+ **Question indicators** (suggest `/kc:plan` instead): starts with is/does/how/why/what/should, contains `?`, phrased as inquiry.
177
+
178
+ **Implementation indicators** (proceed): starts with build/add/create/implement/fix/refactor, action-oriented verbs.
179
+
180
+ If ambiguous, proceed with implementation.
181
+
182
+ ## Step 5.5: Complexity Classification
183
+
184
+ Assess the goal against the codebase to determine the appropriate workflow tier.
185
+
186
+ ### Tier 1: Micro → redirect to `/kc:fix`
187
+ - Single file, <50 lines, no ripple effects
188
+
189
+ ### Tier 2: Light (2-phase workflow)
190
+
191
+ > **Note:** Light mode does not use orchestration config — single builder, no scouts, no specialists.
192
+
193
+ ALL must be true:
194
+ - ≤3 files touched
195
+ - Single NodeID (1 new capability)
196
+ - No architectural changes
197
+ - No security-sensitive components (auth, payments, PII)
198
+ - No external API integrations
199
+ - Estimated <200 lines of change
200
+
201
+ ### Tier 3: Full (5-phase workflow)
202
+ ANY triggers full:
203
+ - >3 files or >1 NodeID
204
+ - Architectural impact
205
+ - Security-sensitive scope
206
+ - External integrations
207
+ - User explicitly requests: `--tier full`
208
+
209
+ **Announce the detected tier to the user.** User can override:
210
+ - "use full" or `--tier full` → Tier 3
211
+ - "use light" or `--tier light` → Tier 2
212
+
213
+ If `$ARGUMENTS` contains `--tier light`, force Tier 2. If `--tier full`, force Tier 3.
214
+
215
+ ---
216
+
217
+ ## Tier 2: Light Workflow (2-phase fast path)
218
+
219
+ When Tier 2 is selected, execute this streamlined workflow instead of the 5-phase Tier 3 below.
220
+
221
+ ### Light Phase 1 (Inline — lead does this, no agent)
222
+
223
+ 1. Quick impact scan: grep for related files, check existing specs
224
+ 2. Propose a Change Set (typically 1 NodeID)
225
+ 3. Draft a lightweight spec (or reference existing spec if found) — use the 4-section format from `knowzcode_loop.md` section 3.2. Minimum: 1 Rule, 1 Interface, 2 `VERIFY:` statements.
226
+ 4. Present combined Change Set + Spec for approval:
227
+
228
+ ```markdown
229
+ ## Light Mode: Change Set + Spec Approval
230
+
231
+ **WorkGroupID**: {wgid}
232
+ **Tier**: 2 (Light)
233
+ **NodeID**: {NodeID} — {description}
234
+ **Affected Files**: {list}
235
+
236
+ **Spec Summary**:
237
+ - Rules: {key decisions}
238
+ - Interfaces: {public contracts}
239
+ - VERIFY: {criteria list}
240
+
241
+ Approve Change Set and spec to proceed to implementation?
242
+ ```
243
+
244
+ 5. **Autonomous Mode**: If `AUTONOMOUS_MODE = true`, log `[AUTO-APPROVED] Light mode gate` and proceed directly to implementation.
245
+ If `AUTONOMOUS_MODE = false`: If rejected — adjust based on feedback and re-present. If approved:
246
+ - Update `knowzcode_tracker.md` with NodeID status `[WIP]`
247
+ - Pre-implementation commit: `git add knowzcode/ && git commit -m "KnowzCode: Light spec approved for {wgid}"`
248
+
249
+ ### Light Phase 2A: Implementation (Builder agent)
250
+
251
+ Spawn the builder using the standard Phase 2A prompt below (same for both tiers).
252
+
253
+ The builder self-verifies against spec VERIFY criteria — no separate audit phase.
254
+
255
+ ### Light Phase 3 (Inline — lead does this, no agent)
256
+
257
+ After builder completes successfully:
258
+ 1. Update spec to As-Built status
259
+ 2. Update `knowzcode_tracker.md`: NodeID status `[WIP]` → `[VERIFIED]`
260
+ 3. Write a brief log entry to `knowzcode_log.md`:
261
+ ```markdown
262
+ ---
263
+ **Type:** ARC-Completion
264
+ **Timestamp:** [timestamp]
265
+ **WorkGroupID:** [ID]
266
+ **NodeID(s):** [list]
267
+ **Logged By:** AI-Agent
268
+ **Details:** Light mode (Tier 2). {brief summary of implementation}.
269
+ ---
270
+ ```
271
+ 4. Final commit: `git add knowzcode/ <changed files> && git commit -m "feat: {goal} (WorkGroup {wgid})"`
272
+ 5. Report completion.
273
+ 6. **Progress capture** (if MCP is configured): Read `knowzcode/knowzcode_vaults.md`, resolve vault IDs. Write a brief scope-and-outcome learning to the ecosystem vault via `create_knowledge`. Check for duplicates first via `search_knowledge`.
274
+
275
+ **DONE** — 3 agents skipped (analyst, architect, reviewer, closer).
276
+
277
+ ---
278
+
279
+ ## Tier 3: Full Workflow (5-phase)
280
+
281
+ The standard 5-phase workflow. Used when complexity warrants full analysis, specification, audit, and finalization.
282
+
283
+ Tier 3 supports three execution modes (determined in Step 2):
284
+ - **Parallel Teams** (default) — Stage 0-3 orchestration with concurrent agents
285
+ - **Sequential Teams** (`--sequential`) — one agent per phase, spawned and shut down sequentially
286
+ - **Subagent Delegation** — Task() calls, no persistent agents
287
+
288
+ ## Step 6: Spec Detection (Optional Optimization)
289
+
290
+ Check for existing specs covering this work:
291
+ 1. Extract key terms from goal
292
+ 2. Search `knowzcode/specs/*.md` for matching specs
293
+ 3. If comprehensive matching specs found, offer:
294
+ - **A) Quick Path** — skip discovery, use existing specs
295
+ - **B) Validation Path** (recommended) quick check specs match codebase
296
+ - **C) Full Workflow** — complete Phase 1A discovery
297
+
298
+ If no matches found, proceed to Phase 1A.
299
+
300
+ ### Refactor Task Check
301
+
302
+ Scan `knowzcode/knowzcode_tracker.md` for outstanding `REFACTOR_` tasks that overlap with the current goal's scope. If found, mention them to the user during Phase 1A so the analyst can factor them into the Change Set.
303
+
304
+ ---
305
+
306
+ ## Parallel Teams Orchestration (Tier 3 Default)
307
+
308
+ When Parallel Teams mode is active, follow these 4 stages instead of spawning one agent per phase sequentially. The same phase spawn prompts (defined in the Phase Reference sections below) are reused — what changes is WHEN agents are spawned and HOW MANY run concurrently.
309
+
310
+ ### Stage 0: Team Creation + Parallel Discovery
311
+
312
+ 1. Create team `kc-{wgid}`
313
+ 2. Read knowzcode context files (lead does initial load for spawn prompts)
314
+ 3. **MCP Probe**determine vault availability BEFORE spawning:
315
+ a. Read `knowzcode/knowzcode_vaults.md` — partition entries into CONFIGURED (non-empty ID) and UNCREATED (empty ID)
316
+ b. Call `list_vaults(includeStats=true)` **always** — regardless of whether any IDs exist in the file
317
+ c. If `list_vaults()` fails:
318
+ - Check if `knowzcode/knowzcode_vaults.md` has any CONFIGURED entries (non-empty ID)
319
+ - **If CONFIGURED entries exist**: Set `MCP_ACTIVE = true`, `VAULTS_CONFIGURED = true` vault agents will verify connectivity independently via their Startup Verification. Announce `**MCP Status: Lead probe failed delegating verification to vault agents**`. Proceed to Step 4.
320
+ - **If no CONFIGURED entries** (all empty IDs or no file): Set `MCP_ACTIVE = false`, announce `**MCP Status: Not connected**`, skip Group B spawn
321
+ d. If `list_vaults()` succeeds AND UNCREATED list is non-empty → present the **Vault Creation Prompt**:
322
+
323
+ ```markdown
324
+ ## Vault Setup
325
+
326
+ Your Knowz API key is valid and MCP is connected, but {N} default vault(s) haven't been created yet.
327
+ Creating vaults enables knowledge capture throughout the workflow:
328
+
329
+ | Vault | Type | Description | Written During |
330
+ |-------|------|-------------|----------------|
331
+ ```
332
+
333
+ Build table rows dynamically from the UNCREATED entries only. For each uncreated vault, derive the "Written During" column from its Write Conditions field in `knowzcode_vaults.md`. Example rows:
334
+ - `| Code Patterns | code | Learnings, gotchas, and architecture insights from the codebase | Phase 2A (implementation patterns), Phase 3 (workarounds, performance) |`
335
+ - `| Ecosystem Knowledge | ecosystem | Business rules, conventions, decisions, and cross-system details | Phase 1A (scope decisions), Phase 2B (security, quality), Phase 3 (conventions) |`
336
+ - `| Finalizations | finalizations | Final summaries documenting complete execution and outcomes | Phase 3 (completion record) |`
337
+
338
+ Then present options:
339
+ ```
340
+ Options:
341
+ **A) Create all {N} vaults** (recommended)
342
+ **B) Select which to create**
343
+ **C) Skip** — proceed without vaults (can create later with `/kc:connect-mcp --configure-vaults`)
344
+ ```
345
+
346
+ e. Handle user selection:
347
+ - **A**: For each UNCREATED entry, call MCP `create_vault(name, description)`. If `create_vault` is not available, fall back to matching by name against `list_vaults()` results. Update `knowzcode_vaults.md`: fill the ID field with the server-returned vault ID and change the H3 heading from `(not created)` to the vault ID. If creation fails for some vaults, update only successful ones, report failures, and let user decide.
348
+ - **B**: Ask which vaults to create, then create only selected ones using the same process as A.
349
+ - **C**: Log `"Vault creation skipped — knowledge capture disabled."` Continue.
350
+ f. After resolution, set:
351
+ - `MCP_ACTIVE = true` (MCP works regardless of vault creation outcome)
352
+ - `VAULTS_CONFIGURED = true` if at least 1 vault now has a valid ID, else `false`
353
+ - Announce: `**MCP Status: Connected — N vault(s) available**` or `**MCP Status: Connected — no vaults configured (knowledge capture disabled)**`
354
+ 4. **Spawn Group A**:
355
+ Create tasks first, pre-assign, then spawn with task IDs:
356
+ - If `SCOUT_MODE = "full"` (default): spawn 3 context scouts (specs, workgroups, backlog) + analyst + architect (5 agents):
357
+ - `TaskCreate("Scout: specs context")` → `TaskUpdate(owner: "context-scout-specs")`
358
+ - `TaskCreate("Scout: workgroups context")` → `TaskUpdate(owner: "context-scout-workgroups")`
359
+ - `TaskCreate("Scout: backlog context")` `TaskUpdate(owner: "context-scout-backlog")`
360
+ - If `SCOUT_MODE = "minimal"`: spawn 1 context-scout (combined scan) + analyst + architect (3 agents):
361
+ - `TaskCreate("Scout: combined context")` `TaskUpdate(owner: "context-scout")`
362
+ - If `SCOUT_MODE = "none"`: spawn analyst + architect only (2 agents). Analyst and architect scan the codebase independently without pre-loaded scout context.
363
+ - Always:
364
+ - `TaskCreate("Phase 1A: Impact analysis for {goal}")` → `TaskUpdate(owner: "analyst")`
365
+ - `TaskCreate("Pre-load architecture context and speculative research")` `TaskUpdate(owner: "architect")`
366
+ - If `CODEBASE_SCANNER_ENABLED = true` (default):
367
+ - Derive two search focuses from the goal:
368
+ - **Scanner-Direct**: source code search grep for goal keywords, read affected code paths
369
+ - **Scanner-Tests**: test discovery search test directories for tests covering the goal area
370
+ - `TaskCreate("Scanner: direct codebase scan for {goal}")` → `TaskUpdate(owner: "scanner-direct")`
371
+ - `TaskCreate("Scanner: test coverage scan for {goal}")` `TaskUpdate(owner: "scanner-tests")`
372
+ Spawn all Group A agents with their `{task-id}` in the spawn prompt (use spawn prompts from Phase Prompt Reference below).
373
+ 5. **Spawn Group B** (MCP agents same turn as Group A): If `VAULTS_CONFIGURED = true` AND `MCP_AGENTS_ENABLED = true`:
374
+ Create tasks first, pre-assign, then spawn with task IDs:
375
+ - `TaskCreate("Knowz-scout: vault queries")` → `TaskUpdate(owner: "knowz-scout")`
376
+ - `TaskCreate("Knowz-scribe: listen")` `TaskUpdate(owner: "knowz-scribe")`
377
+ Spawn both agents with their `{task-id}` in the spawn prompt.
378
+ If `VAULTS_CONFIGURED = false` or `MCP_AGENTS_ENABLED = false`, skip Group B and log: `Vault agents skipped — no vaults configured` or `Vault agents skipped — MCP agents disabled in orchestration config.`
379
+ 6. **Spawn Group C** (specialist agents same turn as Groups A and B): If `SPECIALISTS_ENABLED` is non-empty:
380
+ Create tasks first, pre-assign, then spawn with task IDs:
381
+ - If `security-officer` in list: `TaskCreate("Security officer: initial threat scan")` → `TaskUpdate(owner: "security-officer")`
382
+ - If `test-advisor` in list: `TaskCreate("Test advisor: coverage baseline")` → `TaskUpdate(owner: "test-advisor")`
383
+ - If `project-advisor` in list: `TaskCreate("Project advisor: backlog context")` `TaskUpdate(owner: "project-advisor")`
384
+ Spawn each enabled specialist with its `{task-id}` in the spawn prompt (use spawn prompts from Specialist Spawn Prompts section below).
385
+ If `SPECIALISTS_ENABLED` is empty, skip Group C.
386
+ 7. **Roster confirmation** lead lists every spawned agent by name to the user. Include scanners and Group C specialists if active. If `VAULTS_CONFIGURED` was true but knowz-scout or knowz-scribe is missing from the roster, STOP and re-spawn the missing agent(s) before continuing.
387
+ 8. All spawned agents work immediately in parallel (context scouts are cheap Sonnet read-only agents; scanners are lightweight general-purpose agents; knowz-scribe is a cheap Haiku agent; specialists are Sonnet read-only agents). Agent count depends on orchestration config: 2-12 agents at Stage 0.
388
+ 9. Scouts broadcast findings → analyst and architect consume as messages. Specialists work independently on their Stage 0 tasks.
389
+
390
+ **Key**: The analyst does NOT wait for scouts, scanners, or specialists to finish. It starts scanning the codebase immediately. Scout and scanner findings arrive as messages and enrich the analyst's work as they arrive. The analyst also streams `[PRELIMINARY]` NodeID findings to the architect as it discovers them (see Preliminary Findings Protocol). Specialist findings are consumed by the lead at gates.
391
+
392
+ ### Stage 1: Analysis + Specification
393
+
394
+ 1. Analyst completes Change Set (includes dependency map — see `agents/analyst.md`)
395
+ 2. Lead reads analyst's task summary
396
+ 3. Shut down scanners (scanner-direct, scanner-tests) if they were spawned no longer needed after analysis
397
+ 3. **Specialist Change Set reviews** (if `SPECIALISTS_ENABLED` non-empty): Create review tasks blocked on analysis:
398
+ - If `security-officer` active: `TaskCreate("Security officer: Change Set review", addBlockedBy: [analysis-task-id])` → `TaskUpdate(owner: "security-officer")`. DM security-officer: `"**New Task**: #{task-id} — Review Change Set for security risk. Rate each NodeID."`
399
+ - If `test-advisor` active: `TaskCreate("Test advisor: Change Set test strategy", addBlockedBy: [analysis-task-id])` → `TaskUpdate(owner: "test-advisor")`. DM test-advisor: `"**New Task**: #{task-id} Recommend test types per NodeID."`
400
+ 4. Lead presents **Quality Gate #1** to user:
401
+ - Change Set with NodeIDs, descriptions, affected files
402
+ - Dependency map showing which NodeIDs can be implemented in parallel
403
+ - Risk assessment
404
+ - Specialist Reports (if active see gate template below)
405
+ 5. User approves (or rejects re-run analyst with feedback)
406
+ 6. Lead sends DM to architect with the approved Change Set
407
+ 7. **Spec Drafting** — choose path based on NodeID count and `PARALLEL_SPEC_THRESHOLD`:
408
+
409
+ **Path A: Standard (fewer than PARALLEL_SPEC_THRESHOLD NodeIDs)**
410
+ - Lead creates spec-drafting tasks for architect (1 task per NodeID, `addBlockedBy: [analysis-task-id]`):
411
+ - `TaskCreate("Spec: NodeID-X")` `TaskUpdate(taskId, owner: "architect")`
412
+ - DM architect with task IDs: `"**New Tasks**: #{id-1} Spec: NodeID-A, #{id-2} Spec: NodeID-B. Approved Change Set: {summary}"`
413
+ - Architect is already warm (pre-loaded + speculative research during Stage 0) specs drafted FAST
414
+ - If Gate #1 rejected: shut down architect, re-run analyst with feedback, re-spawn architect after
415
+
416
+ **Path B: Parallel Spec Drafting (PARALLEL_SPEC_THRESHOLD or more NodeIDs)**
417
+ - Lead DMs architect the full approved Change Set and asks for a partition plan (see `agents/architect.md` — Parallel Spec Coordination)
418
+ - Architect proposes NodeID partitions (1-2 NodeIDs each, max 3 partitions, respecting same-spec and interface constraints)
419
+ - Lead spawns spec-drafter agents one per partition:
420
+ - Spec-drafters use the `architect` agent definition with a scoped spawn prompt
421
+ - Each drafter gets: its NodeID partition, architect's research findings, cross-NodeID interface constraints, consolidation instructions
422
+ - `TaskCreate("Spec draft: NodeID-A, NodeID-B")` → `TaskUpdate(owner: "spec-drafter-1")`
423
+ - Max 3 spec-drafters: `ceil(NodeID_count / 2)`, capped at 3
424
+ - Spec-drafters draft specs in parallel
425
+ - After all spec-drafters complete: architect runs consistency review (cross-spec alignment, naming, VERIFY coverage)
426
+ - Shut down spec-drafters after consistency review
427
+ - If Gate #1 rejected: shut down architect and any spec-drafters, re-run analyst with feedback, re-spawn architect after
428
+
429
+ 8. Architect completes specs (Path A) or architect completes consistency review (Path B)
430
+ 9. **Test-advisor spec review** (if `test-advisor` in `SPECIALISTS_ENABLED`): After specs drafted, create spec testability review task:
431
+ - `TaskCreate("Test advisor: spec testability review", addBlockedBy: [spec-task-id])` `TaskUpdate(owner: "test-advisor")`
432
+ - DM test-advisor: `"**New Task**: #{task-id} Review specs for testability. Check VERIFY criteria are automatable."`
433
+ 10. Lead presents **Quality Gate #2** to user:
434
+ - Spec summaries with VERIFY criteria
435
+ - Specialist Reports (if active see gate template below)
436
+ 11. User approves (or rejects architect revises)
437
+ 12. Pre-implementation commit: `git add knowzcode/ && git commit -m "KnowzCode: Specs approved for {wgid}"`
438
+ 13. Shut down context-scouts (no longer needed after specs approved). Keep knowz-scout alive for vault queries during implementation.
439
+ 14. Keep analyst alive briefly (available for scope questions during early implementation)
440
+ 15. Keep architect alive through Stage 2 (consultative role — spec clarifications for builders, no code or spec edits)
441
+
442
+ ### Stage 2: Parallel Implementation + Incremental Review
443
+
444
+ 1. Lead examines dependency map from analyst:
445
+ - Group NodeIDs into independent partitions (no shared files between groups)
446
+ - Determine builder count: 1 builder per independent group, max `MAX_BUILDERS` (default 5, configurable in `knowzcode_orchestration.md`)
447
+
448
+ 2. Create builder tasks and spawn:
449
+ - `TaskCreate("Implement NodeIDs [A, B]", addBlockedBy: [spec-task-id])` → `TaskUpdate(owner: "builder-1")`
450
+ - `TaskCreate("Implement NodeIDs [C]", addBlockedBy: [spec-task-id])` → `TaskUpdate(owner: "builder-2")`
451
+ - `TaskCreate("Implement NodeIDs [D, E]", addBlockedBy: [spec-task-id])` `TaskUpdate(owner: "builder-3")`
452
+ Spawn each builder with its `{task-id}` in the spawn prompt.
453
+ Each builder gets its partition's specs + affected files list.
454
+ **NO TWO BUILDERS TOUCH THE SAME FILE**
455
+
456
+ 3. Notify architect of builder spawn:
457
+ - Lead DMs architect: `"Builders spawned for Stage 2. Introduce yourself to: {builder-1, builder-2, ...}"`
458
+ - Architect sends brief availability message to each builder (see `agents/architect.md` — Proactive Availability)
459
+
460
+ 4. Each builder creates subtasks per NodeID in the task list:
461
+ - `"TDD: NodeID-A tests"` `"TDD: NodeID-A implementation"` `"TDD: NodeID-A verify"`
462
+ - Builder works through subtasks, marks each complete with summary
463
+
464
+ 5. Create reviewer tasks and spawn one per builder partition:
465
+ - `TaskCreate("Audit partition 1: NodeIDs [A, B]", addBlockedBy: [implement-A-task-id])` → `TaskUpdate(owner: "reviewer-1")`
466
+ - `TaskCreate("Audit partition 2: NodeIDs [C]", addBlockedBy: [implement-C-task-id])` → `TaskUpdate(owner: "reviewer-2")`
467
+ - `TaskCreate("Audit partition 3: NodeIDs [D, E]", addBlockedBy: [implement-D-task-id])` `TaskUpdate(owner: "reviewer-3")`
468
+ Spawn each reviewer with its `{task-id}` + partition's specs + VERIFY criteria.
469
+ Reviewer stays idle until its paired builder marks first NodeID implementation complete.
470
+ Each reviewer audits incrementally within its partition.
471
+
472
+ 6. **Specialist implementation reviews** (if `SPECIALISTS_ENABLED` non-empty): Create specialist review tasks alongside reviewer audit tasks, same `addBlockedBy`:
473
+ - If `security-officer` active one task per partition (runs parallel to reviewer):
474
+ `TaskCreate("Security officer: review partition {N}", addBlockedBy: [implement-X-task-id])` `TaskUpdate(owner: "security-officer")`
475
+ DM security-officer: `"**New Task**: #{task-id}Vulnerability scan for partition {N}. NodeIDs: {list}."`
476
+ - If `test-advisor` active one task per partition:
477
+ `TaskCreate("Test advisor: review partition {N} tests", addBlockedBy: [implement-X-task-id])` → `TaskUpdate(owner: "test-advisor")`
478
+ DM test-advisor: `"**New Task**: #{task-id} Test quality review for partition {N}. NodeIDs: {list}."`
479
+ - If `project-advisor` active one observation task (not per-partition):
480
+ `TaskCreate("Project advisor: observe implementation")` `TaskUpdate(owner: "project-advisor")`
481
+ DM project-advisor: `"**New Task**: #{task-id} Observe builder progress, note patterns and ideas. Deliver backlog proposals before gap loop."`
482
+ **Gate #3 is NOT blocked by specialists.** If a specialist hasn't finished, gate shows `[Pending: {specialist}]`. Lead proceeds.
483
+ **Project-advisor early shutdown**: After project-advisor delivers backlog proposals, shut it down (before the gap loop begins).
484
+
485
+ 7. Gap flow (per-partition, parallel persistent agents, DM messaging):
486
+ a. Each reviewer marks audit task complete with structured gap report in summary
487
+ b. Lead creates fix task and pre-assigns:
488
+ `TaskCreate("Fix gaps: NodeID-A", addBlockedBy: [audit-task-id])` `TaskUpdate(owner: "builder-N")`
489
+ c. Lead sends DM to builder with task ID and gap details:
490
+ > **New Task**: #{fix-task-id} Fix gaps: NodeID-A
491
+ > **Gaps**: {file path, VERIFY criterion not met, expected vs actual}
492
+ > Fix each gap, re-run affected tests, report completion.
493
+ d. Builder claims fix task, fixes gaps, re-runs tests, marks fix task complete
494
+ e. Lead creates re-audit task and pre-assigns:
495
+ `TaskCreate("Re-audit: NodeID-A", addBlockedBy: [gap-fix-task-id])` `TaskUpdate(owner: "reviewer-N")`
496
+ f. Lead sends DM to reviewer: `"**New Task**: #{reaudit-task-id} Re-audit: NodeID-A. {gap list}"`
497
+ g. Each builder-reviewer pair repeats independently until clean no cross-partition blocking
498
+ — All builders and reviewers stay alive through the entire gap loop (no respawning)
499
+
500
+ 8. Enterprise compliance (if enabled):
501
+ - Lead creates parallel compliance task for each reviewer (scoped to their partition)
502
+ - Reviewer checks compliance requirements from knowz-scout findings
503
+ - Runs alongside ARC audits
504
+
505
+ 9. Inter-agent communication during Stage 2:
506
+ - builderarchitect: Spec clarification requests (direct messages)
507
+ - architect builder: Design guidance and spec intent responses (direct messages)
508
+ - builder builder: Dependency coordination (direct messages "I changed the User interface, FYI")
509
+ - builderreviewer (same partition): Implementation complete notifications (via task system)
510
+ - reviewerlead: Gap reports per partition (structured format via task summaries)
511
+ - lead → builder: Fix tasks (via task creation + DM)
512
+ - leadreviewer: Re-audit requests (via task creation + DM)
513
+ - security-officer → builder-N: Security guidance for sensitive partitions (max 2 DMs per builder)
514
+ - test-advisor builder-N: Test improvement feedback (max 2 DMs per builder)
515
+ - security-officer test-advisor: Cross-cutting test gaps in security paths (max 2 inter-specialist DMs)
516
+ - project-advisor → knowz-scribe: Idea captures for vault storage
517
+ - project-advisor → lead: Backlog proposals (before gap loop)
518
+
519
+ 10. After all NodeIDs implemented + audited across all partitions:
520
+ - Lead consolidates audit results from all reviewers
521
+ - Lead consolidates specialist reports (if `SPECIALISTS_ENABLED` non-empty — include even if some specialist tasks are still pending, noting `[Pending: {specialist}]`)
522
+ - Lead presents **Quality Gate #3**:
523
+ - Per-NodeID ARC completion % (from each partition's reviewer)
524
+ - Combined security posture
525
+ - Combined integration health
526
+ - Enterprise compliance (if applicable)
527
+ - Specialist Reports (if active see gate template below)
528
+ - User decides: proceed / fix gaps / modify specs / cancel
529
+
530
+ 11. Shut down analyst, architect, all builders, and all reviewers
531
+
532
+ ### Stage 3: Finalization
533
+
534
+ 1. Shut down remaining specialists (security-officer, test-advisor) if still active. Project-advisor should already be shut down from mid-Stage 2.
535
+ 2. `TaskCreate("Phase 3: Finalize {wgid}", addBlockedBy: [last-audit-task-id])` `TaskUpdate(owner: "closer")`
536
+ Spawn `closer` with `{task-id}` in spawn prompt.
537
+ 3. Closer tasks (can be parallel subtasks):
538
+ - Update all specs to FINAL as-built
539
+ - Update `knowzcode_tracker.md`: all NodeIDs `[WIP]` → `[VERIFIED]`
540
+ - Write ARC-Completion log entry
541
+ - Review architecture docs for discrepancies
542
+ - Schedule REFACTOR tasks for tech debt
543
+ - Create capture task for knowz-scribe (if active): `TaskCreate("Scribe: Capture Phase 3")` → `TaskUpdate(owner: "knowz-scribe")`, then send DM with task ID: `"Capture Phase 3: {wgid}. Your task: #{task-id}"`. Knowz-scout remains available for vault queries during finalization.
544
+ - Create final atomic commit
545
+ 4. Lead presents completion summary
546
+ 5. **Wait for scribe Phase 3 capture** (if knowz-scribe is active):
547
+ - Check scribe capture task via `TaskGet(task-id)` wait until status is `completed`
548
+ - Also wait for scribe's Phase 3 confirmation DM
549
+ - **Timeout**: If >2 minutes after closer completes and scribe task still not complete DM scribe: `"Status check: Phase 3 capture for {wgid}?"`
550
+ - **Hard timeout**: If another minute passes with no completion → proceed with shutdown and log `WARNING: Scribe Phase 3 capture did not complete for {wgid}. Vault writes may be incomplete.`
551
+ 6. Shutdown order: knowz-scout, knowz-scribe, closer, remaining agents
552
+ 7. Delete team
553
+
554
+ ### WorkGroup File Format (Parallel Mode)
555
+
556
+ In Parallel Teams mode, the WorkGroup file uses per-NodeID phase tracking instead of a single `Current Phase`:
557
+
558
+ ```markdown
559
+ ## Change Set
560
+ | NodeID | Phase | Builder | Status | Timestamp |
561
+ |--------|-------|---------|--------|-----------|
562
+ | Authentication | 2A | builder-1 | Implementing | ... |
563
+ | UserProfile | 2B | builder-1 | Under review | ... |
564
+ | LIB_DateFormat | 2A | builder-2 | Tests passing | ... |
565
+
566
+ ## Autonomous Mode
567
+ Active/Inactive
568
+
569
+ ## Current Stage
570
+ Stage 2: Parallel Implementation + Incremental Review
571
+ ```
572
+
573
+ ### Task Dependency Graph
574
+
575
+ When creating tasks, model the dependency chain with `addBlockedBy` and pre-assign with `owner`:
576
+
577
+ | Task | Blocked By | Owner |
578
+ |------|-----------|-------|
579
+ | Scout: specs context | (none) | context-scout-specs |
580
+ | Scout: workgroups context | (none) | context-scout-workgroups |
581
+ | Scout: backlog context | (none) | context-scout-backlog |
582
+ | Knowz-scout: vault queries | (none — persistent) | knowz-scout |
583
+ | Knowz-scribe: listen | (none — persistent) | knowz-scribe |
584
+ | Scanner: direct codebase scan | (none) | scanner-direct |
585
+ | Scanner: test coverage scan | (none) | scanner-tests |
586
+ | Phase 1A analysis | (none — scouts + scanners enrich via broadcast) | analyst |
587
+ | Architect pre-load + speculative research | (none — receives [PRELIMINARY] DMs from analyst) | architect |
588
+ | Security officer: initial threat scan | (none — Group C) | security-officer |
589
+ | Test advisor: coverage baseline | (none — Group C) | test-advisor |
590
+ | Project advisor: backlog context | (none Group C) | project-advisor |
591
+ | Security officer: Change Set review | Phase 1A analysis | security-officer |
592
+ | Test advisor: Change Set test strategy | Phase 1A analysis | test-advisor |
593
+ | Spec: NodeID-X | Phase 1A (gate approval) | architect (Path A) or spec-drafter-N (Path B) |
594
+ | Spec consistency review | All spec drafts complete (Path B only) | architect |
595
+ | Test advisor: spec testability review | Spec: NodeID-X | test-advisor |
596
+ | Implement: NodeID-X | Spec: NodeID-X | builder-N |
597
+ | Audit: NodeID-X | Implement: NodeID-X | reviewer-N |
598
+ | Security officer: review partition N | Implement: NodeID-X | security-officer |
599
+ | Test advisor: review partition N tests | Implement: NodeID-X | test-advisor |
600
+ | Project advisor: observe implementation | (none) | project-advisor |
601
+ | Fix gaps: NodeID-X round N | Audit: NodeID-X (or re-audit N-1) | builder-N |
602
+ | Re-audit: NodeID-X round N | Fix gaps round N | reviewer-N |
603
+ | Phase 3 finalization | All audits approved | closer |
604
+ | Scribe: Capture Phase 1A | Phase 1A (gate approval) | knowz-scribe |
605
+ | Scribe: Capture Phase 2A | Implement: NodeID-X | knowz-scribe |
606
+ | Scribe: Capture Phase 2B | All audits approved | knowz-scribe |
607
+ | Scribe: Capture Phase 3 | Phase 3 finalization | knowz-scribe |
608
+
609
+ ---
610
+
611
+ ## Sequential Teams / Subagent Flow (Tier 3 Fallback)
612
+
613
+ > **Note:** Sequential Teams does not use orchestration config settings except `MCP_AGENTS_ENABLED`.
614
+
615
+ When using Sequential Teams (`--sequential`) or Subagent Delegation, follow the traditional one-agent-per-phase flow. For each phase below: spawn the agent, create a task, wait for completion, present quality gate, shut down agent, proceed to next phase.
616
+
617
+ ### MCP Probe (Sequential/Subagent)
618
+
619
+ Determine vault availability before Phase 1A:
620
+
621
+ 1. Read `knowzcode/knowzcode_vaults.md` — check for CONFIGURED entries (non-empty ID)
622
+ 2. Attempt `list_vaults(includeStats=true)`
623
+ 3. If succeeds AND UNCREATED entries exist → present the **Vault Creation Prompt** (same as Parallel Teams Step 3d). Handle selection identically.
624
+ 4. After resolution, announce MCP status to the user:
625
+ - `list_vaults()` succeeded: `**MCP Status: ConnectedN vault(s) available**`
626
+ - `list_vaults()` failed but configured vaults exist: `**MCP Status: Lead probe failed — closer will verify at Phase 3**`
627
+ - No configured vaults: `**MCP Status: Not configured**`
628
+
629
+ The closer agent independently verifies MCP at Phase 3 regardless of this result (see `agents/closer.md` — Startup MCP Verification). This probe is for the user announcement and vault creation opportunity only.
630
+
631
+ ---
632
+
633
+ ## Phase Prompt Reference
634
+
635
+ The spawn prompts below are shared by all execution modes. In Parallel Teams mode, the lead uses these prompts when spawning agents at the appropriate stage. In Sequential Teams / Subagent mode, agents are spawned one at a time in phase order.
636
+
637
+ ## Stage 0: Context Scouts (3 instances)
638
+
639
+ **Agent**: `context-scout` (x3) | Read-only local context researchers
640
+
641
+ Three instances of the same agent, each focused on a different local folder group:
642
+
643
+ **context-scout-specs spawn prompt**:
644
+ > You are `context-scout-specs` for WorkGroup `{wgid}`.
645
+ > Read `agents/context-scout.md` for your full role definition.
646
+ > **Your Task**: #{task-id} — claim immediately (`TaskUpdate(status: "in_progress")`). Mark completed with summary when done.
647
+ > **Focus area**: `knowzcode/specs/*.md` — scan existing specifications.
648
+ > **Goal**: {goal}
649
+ > **READ-ONLY.** Do NOT modify any files.
650
+ > **Deliverable**: Broadcast relevant spec findings (NodeIDs, status, VERIFY criteria overlapping with goal).
651
+
652
+ **context-scout-workgroups spawn prompt**:
653
+ > You are `context-scout-workgroups` for WorkGroup `{wgid}`.
654
+ > Read `agents/context-scout.md` for your full role definition.
655
+ > **Your Task**: #{task-id} — claim immediately (`TaskUpdate(status: "in_progress")`). Mark completed with summary when done.
656
+ > **Focus area**: `knowzcode/workgroups/*.md` — scan previous WorkGroups for similar goals.
657
+ > **Goal**: {goal}
658
+ > **READ-ONLY.** Do NOT modify any files.
659
+ > **Deliverable**: Broadcast prior WorkGroup context (what was tried, what succeeded/failed, patterns).
660
+
661
+ **context-scout-backlog spawn prompt**:
662
+ > You are `context-scout-backlog` for WorkGroup `{wgid}`.
663
+ > Read `agents/context-scout.md` for your full role definition.
664
+ > **Your Task**: #{task-id} — claim immediately (`TaskUpdate(status: "in_progress")`). Mark completed with summary when done.
665
+ > **Focus area**: `knowzcode/knowzcode_tracker.md`, `knowzcode/knowzcode_log.md`, `knowzcode/knowzcode_architecture.md`, `knowzcode/knowzcode_project.md`
666
+ > **Goal**: {goal}
667
+ > **READ-ONLY.** Do NOT modify any files.
668
+ > **Deliverable**: Broadcast active WIP, REFACTOR tasks, architecture summary, and recent log patterns relevant to goal.
669
+
670
+ **context-scout (combined) spawn prompt** (used when `SCOUT_MODE = "minimal"`):
671
+ > You are `context-scout` for WorkGroup `{wgid}`.
672
+ > Read `agents/context-scout.md` for your full role definition.
673
+ > **Your Task**: #{task-id} claim immediately. Mark completed with summary when done.
674
+ > **Focus area**: ALL local context — `knowzcode/specs/*.md`, `knowzcode/workgroups/*.md`, `knowzcode/knowzcode_tracker.md`, `knowzcode/knowzcode_log.md`, `knowzcode/knowzcode_architecture.md`, `knowzcode/knowzcode_project.md`
675
+ > **Goal**: {goal}
676
+ > **READ-ONLY.** Do NOT modify any files.
677
+ > **Deliverable**: Broadcast consolidated findings covering specs, prior workgroups, active WIP, REFACTOR tasks, and architecture context.
678
+
679
+ **Dispatch**:
680
+ - *Parallel Teams*:
681
+ - `SCOUT_MODE = "full"`: 3 context scouts spawned at Stage 0. Shut down after Gate #2.
682
+ - `SCOUT_MODE = "minimal"`: 1 context-scout (combined) spawned at Stage 0. Shut down after Gate #2.
683
+ - `SCOUT_MODE = "none"`: No scouts spawned.
684
+ - *Sequential Teams*: Not applicable (scouts are Parallel Teams only).
685
+ - *Subagent*:
686
+ - `SCOUT_MODE = "full"`: 3 parallel `Task()` calls (specs, workgroups, backlog).
687
+ - `SCOUT_MODE = "minimal"`: 1 `Task()` call with combined prompt.
688
+ - `SCOUT_MODE = "none"`: Skip scout tasks.
689
+
690
+ ---
691
+
692
+ ## Stage 0: Codebase Scanners (2 instances — conditional)
693
+
694
+ **Agent**: `general-purpose` (x2) | Lightweight codebase searchers (no agent definition file)
695
+
696
+ Two temporary agents that scan the codebase in parallel with the analyst, broadcasting findings to accelerate impact analysis. Only spawned when `CODEBASE_SCANNER_ENABLED = true` (default).
697
+
698
+ **scanner-direct spawn prompt**:
699
+ > You are `scanner-direct` for WorkGroup `{wgid}`.
700
+ > **Your Task**: #{task-id} — claim immediately (`TaskUpdate(status: "in_progress")`). Mark completed with summary when done.
701
+ > **Goal**: {goal}
702
+ > **Focus**: Search source code for goal-related keywords and patterns.
703
+ >
704
+ > **Steps**:
705
+ > 1. Grep for goal keywords across source files (exclude node_modules, dist, build, .git)
706
+ > 2. Read the top 5-8 matching files to understand affected code paths
707
+ > 3. Identify module boundaries and cross-module dependencies
708
+ > 4. Note public APIs and interfaces that may need changes
709
+ >
710
+ > **READ-ONLY.** Do NOT modify any files.
711
+ > **Deliverable**: Broadcast findings to all teammates affected files, code paths, module boundaries, and interface patterns.
712
+ > **Budget**: Complete within ~12 turns. Focus on breadth over depth.
713
+
714
+ **scanner-tests spawn prompt**:
715
+ > You are `scanner-tests` for WorkGroup `{wgid}`.
716
+ > **Your Task**: #{task-id} — claim immediately (`TaskUpdate(status: "in_progress")`). Mark completed with summary when done.
717
+ > **Goal**: {goal}
718
+ > **Focus**: Discover tests covering the goal area to understand test patterns and coverage shape.
719
+ >
720
+ > **Steps**:
721
+ > 1. Glob for test files: `**/*.test.*`, `**/*.spec.*`, `**/test_*`, `**/tests/**`
722
+ > 2. Grep test files for goal-related keywords
723
+ > 3. Read 3-5 matching test files to understand testing patterns (test framework, mocking strategy, fixture patterns)
724
+ > 4. Check for integration/e2e tests related to the goal area
725
+ >
726
+ > **READ-ONLY.** Do NOT modify any files.
727
+ > **Deliverable**: Broadcast findings to all teammates test file locations, testing patterns, coverage gaps, and fixture/mock patterns.
728
+ > **Budget**: Complete within ~12 turns. Focus on breadth over depth.
729
+
730
+ **Dispatch**:
731
+ - *Parallel Teams*: Spawned at Stage 0 if `CODEBASE_SCANNER_ENABLED = true`. Use `subagent_type: "general-purpose"`, `maxTurns: 12`. Shut down after Stage 1 (analyst completes Change Set).
732
+ - *Sequential Teams*: Not applicable (scanners are Parallel Teams only).
733
+ - *Subagent*: `Task(subagent_type="general-purpose", description="Scan codebase for {focus}", maxTurns=12, prompt=<above>)` if `CODEBASE_SCANNER_ENABLED = true`.
734
+
735
+ ---
736
+
737
+ ## Stage 0: Knowz Scout
738
+
739
+ **Agent**: `knowz-scout` | MCP vault researcher and knowledge agent
740
+
741
+ **Spawn prompt**:
742
+ > You are the **knowz-scout** for WorkGroup `{wgid}`.
743
+ > Read `agents/knowz-scout.md` for your full role definition.
744
+ > **Your Task**: #{task-id} — claim immediately (`TaskUpdate(status: "in_progress")`). Mark completed with summary when done.
745
+ > **Goal**: {goal}
746
+ > **Step 1**: Read `knowzcode/knowzcode_vaults.md` to discover configured vaults their IDs, types, descriptions, and what knowledge each contains.
747
+ > **Step 2**: For each configured vault, construct goal-relevant queries using the vault's description to guide what to ask. If a single vault covers all knowledge, consolidate queries there.
748
+ > **Deliverable**: Broadcast vault knowledge findings to all teammates.
749
+
750
+ **Dispatch**:
751
+ - *Parallel Teams*: **Group B** spawned at Stage 0 if `VAULTS_CONFIGURED = true`, no blockedBy. Persistent — stays alive through the entire workflow. Shut down after Phase 3 capture is complete.
752
+ - *Sequential Teams*: Not applicable (scouts are Parallel Teams only).
753
+ - *Subagent*: `Task(subagent_type="knowz-scout", description="Query vault for domain knowledge", prompt=<above>)` (only if MCP Probe passes)
754
+
755
+ ---
756
+
757
+ ## Stage 0: Knowz Scribe
758
+
759
+ **Agent**: `knowz-scribe` | Persistent vault write agent (Haiku)
760
+
761
+ **Spawn prompt**:
762
+ > You are the **knowz-scribe** for WorkGroup `{wgid}`.
763
+ > Read `agents/knowz-scribe.md` for your full role definition.
764
+ > **Your Task**: #{task-id} — claim immediately (`TaskUpdate(status: "in_progress")`). Mark completed with summary when done.
765
+ > **WorkGroup file**: `knowzcode/workgroups/{wgid}.md`
766
+ > **Vault config**: Read `knowzcode/knowzcode_vaults.md` to discover configured vaults and resolve vault IDs by type.
767
+ > **You are a message-driven agent.** Wait for capture messages from teammates (e.g., "Capture Phase 1A: {wgid}"). On each message, read the WorkGroup file, extract relevant learnings, and write to the appropriate vault.
768
+ > **Do NOT read or modify source code.** You only read knowzcode/ files and write to MCP vaults.
769
+
770
+ **Dispatch**:
771
+ - *Parallel Teams*: **Group B** spawned at Stage 0 if `VAULTS_CONFIGURED = true`, no blockedBy. Persistent — stays alive through the entire workflow. Shut down after Phase 3 capture is complete.
772
+ - *Sequential Teams*: Not applicable (knowz-scribe is Parallel Teams only).
773
+ - *Subagent*: Not applicable — vault writes in subagent mode are handled by the closer during Phase 3 finalization (see Direct Write Fallback in `agents/closer.md`).
774
+
775
+ ---
776
+
777
+ ## Specialist Spawn Prompts (Group C — opt-in via `--specialists`)
778
+
779
+ The spawn prompts below are used when `SPECIALISTS_ENABLED` is non-empty. Specialists are spawned at Stage 0 alongside Groups A and B.
780
+
781
+ **Dispatch** (all specialists):
782
+ - *Parallel Teams*: Group Cspawned at Stage 0 if `SPECIALISTS_ENABLED` non-empty, no blockedBy. Security-officer and test-advisor persist through Gate #3. Project-advisor shuts down mid-Stage 2.
783
+ - *Sequential Teams*: Not supported announce skip reason.
784
+ - *Subagent*: `Task()` calls with spawn prompts below.
785
+
786
+ ### Security Officer
787
+
788
+ **Agent**: `security-officer` | Officer — CRITICAL/HIGH findings block gates
789
+
790
+ **Spawn prompt**:
791
+ > You are the **security-officer** for WorkGroup `{wgid}`.
792
+ > Read `agents/security-officer.md` for your full role definition.
793
+ > **Your Task**: #{task-id} — claim immediately (`TaskUpdate(status: "in_progress")`). Mark completed with summary when done.
794
+ > **Goal**: {goal}
795
+ > **READ-ONLY.** Do NOT modify any files. Bash is for read-only security scanning only.
796
+ > **Stage 0 Deliverable**: Build STRIDE-lite threat model. Scan for auth/PII/crypto/session patterns. Broadcast initial threat assessment.
797
+ > **Authority**: CRITICAL/HIGH findings use `[SECURITY-BLOCK]` tag lead MUST pause autonomous mode.
798
+ > **Communication**: DM lead at gates. DM architect with security VERIFY criteria needs. DM builders in security-sensitive partitions (max 2 per builder). DM test-advisor for cross-cutting test gaps (max 2).
799
+ > **Enterprise Compliance**: If `knowzcode/enterprise/compliance_manifest.md` exists and `compliance_enabled: true`, read active security guidelines and cross-reference findings with enterprise guideline IDs.
800
+
801
+ ### Test Advisor
802
+
803
+ **Agent**: `test-advisor` | Advisor — informational only
804
+
805
+ **Spawn prompt**:
806
+ > You are the **test-advisor** for WorkGroup `{wgid}`.
807
+ > Read `agents/test-advisor.md` for your full role definition.
808
+ > **Your Task**: #{task-id} — claim immediately (`TaskUpdate(status: "in_progress")`). Mark completed with summary when done.
809
+ > **Goal**: {goal}
810
+ > **READ-ONLY.** Do NOT modify any files. Bash is for read-only operations only (git log, coverage reports).
811
+ > **Stage 0 Deliverable**: Establish test coverage baseline. Glob test files, run coverage if available. Broadcast baseline.
812
+ > **Communication**: DM lead at gates. DM architect if VERIFY criteria aren't testable. DM builders with test improvement feedback (max 2 per builder). DM security-officer for cross-cutting security test gaps (max 2).
813
+ > **Enterprise Compliance**: If `knowzcode/enterprise/compliance_manifest.md` exists and `compliance_enabled: true`, check enterprise ARC criteria for test coverage gaps.
814
+
815
+ ### Project Advisor
816
+
817
+ **Agent**: `project-advisor` | Advisor — informational only
818
+
819
+ **Spawn prompt**:
820
+ > You are the **project-advisor** for WorkGroup `{wgid}`.
821
+ > Read `agents/project-advisor.md` for your full role definition.
822
+ > **Your Task**: #{task-id} — claim immediately (`TaskUpdate(status: "in_progress")`). Mark completed with summary when done.
823
+ > **Goal**: {goal}
824
+ > **READ-ONLY.** Do NOT modify any files.
825
+ > **Stage 0 Deliverable**: Read tracker for existing REFACTOR tasks and backlog context. DM lead with context summary.
826
+ > **Lifecycle**: You shut down mid-Stage 2 after delivering backlog proposals before the gap loop.
827
+ > **Communication**: DM lead with backlog context and proposals. DM knowz-scribe with idea captures (if active). Do NOT DM builders or other specialists.
828
+ > **Enterprise Compliance**: If `knowzcode/enterprise/compliance_manifest.md` exists, note compliance configuration gaps in backlog proposals.
829
+
830
+ ---
831
+
832
+ ## Phase 1A: Impact Analysis
833
+
834
+ **Agent**: `analyst` | **Loop.md**: Section 3.1
835
+
836
+ **Spawn prompt**:
837
+ > You are the **analyst** for WorkGroup `{wgid}`.
838
+ > Read `agents/analyst.md` for your full role definition.
839
+ >
840
+ > **Goal**: {goal}
841
+ > **Context files**: Read sections 1-2 and 3.1 of `knowzcode/knowzcode_loop.md` (skip other phases), `knowzcode/knowzcode_tracker.md`, `knowzcode/knowzcode_project.md`, `knowzcode/knowzcode_architecture.md`
842
+ > **WorkGroup file**: `knowzcode/workgroups/{wgid}.md`
843
+ >
844
+ > **Your Task**: #{task-id} claim immediately (`TaskUpdate(status: "in_progress")`). Mark completed with summary when done.
845
+ > **Conventions**: Update WorkGroup file with results (prefix entries with `KnowzCode:`). If blocked, report blocker and notify lead.
846
+ > **Codebase scanners**: Scanner agents are running in parallel their findings will arrive as broadcast messages. Incorporate them into your analysis but do NOT wait for them.
847
+ > **Preliminary Findings Protocol**: As you discover high-confidence NodeIDs, DM the architect with `[PRELIMINARY]` messages (max 3 see `agents/analyst.md` for format). This lets the architect start speculative research early.
848
+ > **Deliverable**: Change Set proposal written to the WorkGroup file. Include NodeIDs, descriptions, affected files, risk assessment, and dependency map (for Parallel Teams mode).
849
+
850
+ **Dispatch**:
851
+ - *Parallel Teams*: Spawned at Stage 0 alongside scouts, scanners, and architect. Starts immediately (no blockedBy).
852
+ - *Sequential Teams*: Spawn teammate `analyst`, create task `Phase 1A: Impact analysis for "{goal}"`, wait for completion.
853
+ - *Subagent*: `Task(subagent_type="analyst", description="Phase 1A impact analysis", prompt=<above>)`
854
+
855
+ ### Quality Gate #1
856
+
857
+ Present the Change Set for user approval:
858
+
859
+ ```markdown
860
+ ## Approval Gate #1: Change Set
861
+
862
+ **WorkGroupID**: {wgid}
863
+ **Proposed Change Set** ({N} nodes):
864
+ {NodeIDs with descriptions}
865
+
866
+ **Dependency Map** (Parallel Teams):
867
+ {NodeID parallelism groups}
868
+
869
+ **Risk Assessment**: {Low/Medium/High}
870
+
871
+ ### Specialist Reports [only when SPECIALISTS_ENABLED non-empty]
872
+ **Security Officer**: {risk assessment per NodeID, attack surface changes, threat model}
873
+ **Architect**: {architecture impact, layer touch points, pattern alignment}
874
+ **Test Advisor**: {coverage baseline, test strategy recommendations per NodeID}
875
+
876
+ Approve this Change Set to proceed to specification?
877
+ ```
878
+
879
+ **Autonomous Mode**: If `AUTONOMOUS_MODE = true`, present gate info for transparency, log `[AUTO-APPROVED] Gate #1`, and proceed immediately.
880
+ If `AUTONOMOUS_MODE = false`: If rejected — re-run analyst with user feedback. If approved — update tracker, proceed.
881
+
882
+ ### Lead Responsibility: Progress Capture
883
+
884
+ **Lead responsibility.** After gate approval, the lead triggers progress capture. If knowz-scribe is active (Parallel Teams with vaults configured):
885
+ - Create capture task: `TaskCreate("Scribe: Capture Phase 1A")` `TaskUpdate(owner: "knowz-scribe")`
886
+ - Send message to **knowz-scribe** with task ID: `"Capture Phase 1A: {wgid}. Your task: #{task-id}"` — the scribe reads the WorkGroup file, extracts scope/risk/decision data, and writes to the appropriate vault
887
+ - `search_knowledge({resolved_domain_vault_id}, "patterns for {domain}")` pull relevant past learnings to inform specification
888
+ - Share any relevant findings with the architect in the Phase 1B prompt
889
+
890
+ ---
891
+
892
+ ## Stage 0: Architect Pre-load (Parallel Teams)
893
+
894
+ **Agent**: `architect` | Spawned at Stage 0 for context pre-loading and speculative research
895
+
896
+ In Parallel Teams mode, the architect is spawned at Stage 0 (not at Phase 1B). It pre-loads architecture context and performs speculative research on `[PRELIMINARY]` NodeIDs from the analyst.
897
+
898
+ **Stage 0 spawn prompt** (Parallel Teams only):
899
+ > You are the **architect** for WorkGroup `{wgid}`.
900
+ > Read `agents/architect.md` for your full role definition.
901
+ >
902
+ > **Goal**: {goal}
903
+ > **Context files**: Read sections 1-2 and 3.2 of `knowzcode/knowzcode_loop.md` (skip other phases), `knowzcode/knowzcode_project.md`, `knowzcode/knowzcode_architecture.md`
904
+ > **WorkGroup file**: `knowzcode/workgroups/{wgid}.md`
905
+ > **Specs directory**: `knowzcode/specs/`
906
+ >
907
+ > **Your Task**: #{task-id} claim immediately (`TaskUpdate(status: "in_progress")`). Mark completed with summary when done.
908
+ > **Stage 0 Role**: Pre-load architecture context, then perform speculative research on any `[PRELIMINARY]` NodeID messages from the analyst (see Speculative Research Protocol in `agents/architect.md`). READ-ONLY research do NOT write specs yet.
909
+ > **Lifecycle**: You persist through the entire workflow. After Gate #1, you will receive spec-drafting tasks via DM. After Gate #2, you shift to consultative role for builders.
910
+
911
+ After Gate #1, the lead sends the approved Change Set via DM and creates spec-drafting tasks. For spec-drafting prompts, see Phase 1B below.
912
+
913
+ ---
914
+
915
+ ## Phase 1B: Specification
916
+
917
+ **Agent**: `architect` | **Loop.md**: Section 3.2
918
+
919
+ **Spec-drafting prompt** (sent via DM to already-warm architect in Parallel Teams, or as spawn prompt in Sequential/Subagent):
920
+ > You are the **architect** for WorkGroup `{wgid}`.
921
+ > Read `agents/architect.md` for your full role definition.
922
+ >
923
+ > **Goal**: {goal}
924
+ > **Approved Change Set**: {NodeIDs from Gate #1}
925
+ > **Context files**: Read sections 1-2 and 3.2 of `knowzcode/knowzcode_loop.md` (skip other phases), `knowzcode/knowzcode_project.md`, `knowzcode/knowzcode_architecture.md`
926
+ > **WorkGroup file**: `knowzcode/workgroups/{wgid}.md`
927
+ > **Specs directory**: `knowzcode/specs/`
928
+ >
929
+ > **Your Task**: #{task-id} claim immediately (`TaskUpdate(status: "in_progress")`). Mark completed with summary when done.
930
+ > **Conventions**: Update WorkGroup file with results (prefix entries with `KnowzCode:`). If blocked, report blocker and notify lead.
931
+ > **Deliverable**: Finalized specs for all NodeIDs written to `knowzcode/specs/`.
932
+
933
+ **Spec-drafter spawn prompt** (Path B 3+ NodeIDs, Parallel Teams only):
934
+ > You are `spec-drafter-{N}` for WorkGroup `{wgid}`.
935
+ > Read `agents/architect.md` for your full role definition — you follow the same Spec Philosophy, Spec Format, and Consolidation Mandate.
936
+ >
937
+ > **Goal**: {goal}
938
+ > **Your NodeIDs**: {partition 1-2 NodeIDs assigned to this drafter}
939
+ > **Architect Research**: {research findings from architect's speculative research for these NodeIDs}
940
+ > **Cross-NodeID Constraints**: {interface dependencies, shared specs, naming conventions from architect}
941
+ > **Context files**: Read sections 1-2 and 3.2 of `knowzcode/knowzcode_loop.md`, `knowzcode/knowzcode_project.md`, `knowzcode/knowzcode_architecture.md`
942
+ > **WorkGroup file**: `knowzcode/workgroups/{wgid}.md`
943
+ > **Specs directory**: `knowzcode/specs/`
944
+ >
945
+ > **Your Task**: #{task-id} claim immediately (`TaskUpdate(status: "in_progress")`). Mark completed with summary when done.
946
+ > **Deliverable**: Draft specs for your assigned NodeIDs written to `knowzcode/specs/`. The architect will review for consistency after all drafters finish.
947
+
948
+ **Dispatch**:
949
+ - *Parallel Teams*:
950
+ - **Path A** (< PARALLEL_SPEC_THRESHOLD NodeIDs): Architect is already warm from Stage 0 pre-load + speculative research. Lead sends DM with approved Change Set, then creates spec-drafting tasks. **Plan approval enabled** — add to prompt: `Present your spec design for lead review BEFORE writing final specs. Wait for approval.` If `AUTONOMOUS_MODE = true`: auto-approve `plan_approval_request` immediately. Log `[AUTO-APPROVED] Architect plan`.
951
+ - **Path B** (>= PARALLEL_SPEC_THRESHOLD NodeIDs): Lead asks architect for partition plan. Architect proposes partitions. Lead spawns spec-drafters (`subagent_type: "architect"`, `permissionMode: "acceptEdits"`, `maxTurns: 15`) with partition-scoped prompts. After all drafters complete, architect runs consistency review and reports to lead.
952
+ - *Sequential Teams*: Spawn teammate `architect`, create task `Phase 1B: Draft specifications for {N} NodeIDs`. **Plan approval enabled** — add to prompt: `Present your spec design for lead review BEFORE writing final specs. Wait for approval.` Wait for `plan_approval_request`, review, respond with `plan_approval_response`. If `AUTONOMOUS_MODE = true`: auto-approve immediately. Log `[AUTO-APPROVED] Architect plan`.
953
+ - *Subagent*: `Task(subagent_type="architect", description="Phase 1B specification drafting", prompt=<above> + "Present your spec design in your output for lead review.")`
954
+
955
+ > **Note:** Plan approval (agent pauses for lead review) only works in Agent Teams mode via `permissionMode: plan`. In subagent mode, the architect presents its design in the output for post-hoc review. Spec-drafters (Path B) do NOT use plan approval — they follow the architect's partition briefing directly.
956
+
957
+ ### Quality Gate #2
958
+
959
+ Present specs for batch approval:
960
+
961
+ ```markdown
962
+ ## Approval Gate #2: Specifications
963
+
964
+ **Specs Drafted**: {count}
965
+ | NodeID | File | Key VERIFY Criteria |
966
+ |--------|------|---------------------|
967
+ | ... | ... | ... |
968
+
969
+ ### Specialist Reports [only when SPECIALISTS_ENABLED non-empty]
970
+ **Architect**: {specs align with component map, drift concerns, pattern consistency}
971
+ **Test Advisor**: {spec testability assessment, recommended test types per NodeID}
972
+
973
+ Review specs and approve to proceed to implementation?
974
+ ```
975
+
976
+ **Autonomous Mode**: If `AUTONOMOUS_MODE = true`, present gate info for transparency, log `[AUTO-APPROVED] Gate #2`, and proceed immediately.
977
+ If `AUTONOMOUS_MODE = false`: If rejected — re-run specs needing revision. If approved — pre-implementation commit, proceed.
978
+
979
+ **Pre-Implementation Commit:**
980
+ ```bash
981
+ git add knowzcode/
982
+ git commit -m "KnowzCode: Specs approved for {WorkGroupID}"
983
+ ```
984
+
985
+ ---
986
+
987
+ ## Phase 2A: Implementation
988
+
989
+ **Agent**: `builder` | **Loop.md**: Section 3.3
990
+
991
+ **Spawn prompt**:
992
+ > You are the **builder** for WorkGroup `{wgid}`.
993
+ > Read `agents/builder.md` for your full role definition.
994
+ >
995
+ > **Goal**: {goal}
996
+ > **Approved Change Set**: {NodeIDs}
997
+ > **Specs**: {list of spec file paths from Phase 1B}
998
+ > **Context files**: Read sections 1-2 and 3.3 of `knowzcode/knowzcode_loop.md` (skip other phases), `knowzcode/knowzcode_project.md`
999
+ > **WorkGroup file**: `knowzcode/workgroups/{wgid}.md`
1000
+ >
1001
+ > **Your Task**: #{task-id} claim immediately (`TaskUpdate(status: "in_progress")`). Mark completed with summary when done.
1002
+ > **Conventions**: Update WorkGroup file with results (prefix entries with `KnowzCode:`). If blocked, report blocker and notify lead.
1003
+ > **TDD mandatory**: Write failing tests first, then implement, then refactor. Every NodeID must have tests.
1004
+ > **Blocker protocol**: If you hit a blocker, document it as a Blocker Report in the WorkGroup file (see loop.md Section 11 format) and report to the lead immediately instead of guessing.
1005
+ > **Deliverable**: All NodeIDs implemented with passing tests.
1006
+
1007
+ **Dispatch**:
1008
+ - *Parallel Teams*: Multiple builders spawned at Stage 2, one per partition from the dependency map. Each builder gets its partition's NodeIDs and specs. Builders create per-NodeID subtasks for visibility. **Plan approval enabled** — add to prompt: `Present your implementation approach for lead review BEFORE writing code. Wait for approval.` If `AUTONOMOUS_MODE = true`: auto-approve `plan_approval_request` immediately. Log `[AUTO-APPROVED] Builder plan`.
1009
+ - *Sequential Teams*: Spawn teammate `builder`, create task `Phase 2A: Implement {N} NodeIDs with TDD`. **Plan approval enabled** — add to prompt: `Present your implementation approach for lead review BEFORE writing code. Wait for approval.` Wait for `plan_approval_request`, review, respond. If `AUTONOMOUS_MODE = true`: auto-approve immediately. Log `[AUTO-APPROVED] Builder plan`.
1010
+ - *Subagent*: `Task(subagent_type="builder", description="Phase 2A TDD implementation", mode="bypassPermissions", prompt=<above>)`
1011
+
1012
+ ### Phase 2A Output
1013
+
1014
+ When complete, present implementation summary including files changed, tests written, and test results.
1015
+
1016
+ ### Lead Responsibility: Progress Capture
1017
+
1018
+ **Lead responsibility.** After gate approval, the lead triggers progress capture. If knowz-scribe is active (Parallel Teams with vaults configured):
1019
+ - Create capture task: `TaskCreate("Scribe: Capture Phase 2A")` `TaskUpdate(owner: "knowz-scribe")`
1020
+ - Send message to **knowz-scribe** with task ID: `"Capture Phase 2A: {wgid}. Your task: #{task-id}"` — the scribe reads implementation results from the WorkGroup file and captures patterns, workarounds, and performance optimizations to the `code` vault
1021
+
1022
+ ---
1023
+
1024
+ ## Phase 2B: Completeness Audit
1025
+
1026
+ **Agent**: `reviewer` | **Loop.md**: Section 3.4
1027
+
1028
+ **Spawn prompt**:
1029
+ > You are the **reviewer** for WorkGroup `{wgid}`.
1030
+ > Read `agents/reviewer.md` for your full role definition.
1031
+ >
1032
+ > **Goal**: {goal}
1033
+ > **Change Set**: {NodeIDs}
1034
+ > **Specs**: {list of spec file paths}
1035
+ > **Context files**: Read sections 1-2 and 3.4 of `knowzcode/knowzcode_loop.md` (skip other phases), `knowzcode/knowzcode_project.md`, `knowzcode/knowzcode_architecture.md`
1036
+ > **WorkGroup file**: `knowzcode/workgroups/{wgid}.md`
1037
+ >
1038
+ > **Your Task**: #{task-id} claim immediately (`TaskUpdate(status: "in_progress")`). Mark completed with summary when done.
1039
+ > **Conventions**: Update WorkGroup file with results (prefix entries with `KnowzCode:`). If blocked, report blocker and notify lead.
1040
+ > **This is a READ-ONLY audit.** Do not modify any source code or test files.
1041
+ > **Deliverable**: Audit report with ARC completion %, security posture, and gap list.
1042
+
1043
+ **Dispatch**:
1044
+ - *Parallel Teams*: One reviewer per builder partition, spawned at Stage 2. Each reviewer gets its partition's NodeIDs and specs. Audit tasks use `addBlockedBy` per implementation task. Each reviewer uses structured gap report format (see `agents/reviewer.md`).
1045
+ - *Sequential Teams*: Spawn teammate `reviewer`, create task `Phase 2B: Completeness audit for {N} NodeIDs`, wait for completion.
1046
+ - *Subagent*: `Task(subagent_type="reviewer", description="Phase 2B completeness audit", prompt=<above>)`
1047
+
1048
+ ### Quality Gate #3
1049
+
1050
+ Present audit results:
1051
+
1052
+ ```markdown
1053
+ ## Approval Gate #3: Audit Results
1054
+
1055
+ **ARC Completion**: {X}%
1056
+ **Security Posture**: {status}
1057
+ **Gaps Found**: {count}
1058
+
1059
+ ### Specialist Reports [only when SPECIALISTS_ENABLED non-empty]
1060
+ **Security Officer**: Findings: {N} | Critical: {N} | High: {N} | {details or [Pending]}
1061
+ **Architect**: Drift: {Yes/No} | Pattern Violations: {N} | {details}
1062
+ **Test Advisor**: TDD Compliance: {%} | Missing Edge Cases: {N} | Quality: {Good/Adequate/Poor} | {details or [Pending]}
1063
+ **Project Advisor**: New REFACTOR tasks: {N} | Ideas captured to vault: {N}
1064
+
1065
+ **Recommendation**: {proceed / return to implementation}
1066
+
1067
+ How would you like to proceed?
1068
+ ```
1069
+
1070
+ **Autonomous Mode**: If `AUTONOMOUS_MODE = true`:
1071
+ - **Safety check**: If any security finding rated HIGH or CRITICAL (from reviewer OR security-officer `[SECURITY-BLOCK]`) → **PAUSE** autonomous mode for this gate. Announce: `> **Autonomous Mode Paused** — HIGH/CRITICAL security finding requires manual review.`
1072
+ - **Safety check**: If ARC completion < 50%**PAUSE** autonomous mode for this gate. Announce: `> **Autonomous Mode Paused** ARC completion below 50% requires manual review.`
1073
+ - If safety checks pass and gaps found → log `[AUTO-APPROVED] Gate #3 — proceeding to gap loop`, auto-proceed to gap loop.
1074
+ - If safety checks pass and no gaps → log `[AUTO-APPROVED] Gate #3`, auto-proceed to Phase 3.
1075
+
1076
+ If `AUTONOMOUS_MODE = false`: User decides — proceed / fix gaps / modify specs / cancel.
1077
+
1078
+ ### Gap Loop (when user chooses to fix gaps)
1079
+
1080
+ **Parallel Teams mode** (per-partition, persistent agents no respawning):
1081
+ 1. Lead reads each reviewer's structured gap report from task summary
1082
+ 2. Lead creates fix task and pre-assigns:
1083
+ `TaskCreate("Fix gaps: NodeID-X", addBlockedBy: [audit-task-id])` `TaskUpdate(owner: "builder-N")`
1084
+ 3. Lead sends DM to builder with task ID and gap details:
1085
+ `"**New Task**: #{fix-task-id} Fix gaps: NodeID-X. {file path, VERIFY criterion, expected vs actual}"`
1086
+ 4. Builder claims fix task, fixes gaps, re-runs tests, marks fix task complete
1087
+ 5. Lead creates re-audit task and pre-assigns:
1088
+ `TaskCreate("Re-audit: NodeID-X", addBlockedBy: [gap-fix-task-id])` `TaskUpdate(owner: "reviewer-N")`
1089
+ 6. Lead sends DM to reviewer: `"**New Task**: #{reaudit-task-id} Re-audit: NodeID-X. {gap list}"`
1090
+ 7. Each builder-reviewer pair repeats independently until clean — no cross-partition blocking
1091
+ 8. All builders and reviewers stay alive throughout
1092
+ 9. **3-iteration cap per partition**: If a partition exceeds 3 gap-fix iterations without resolution, **PAUSE** autonomous mode for that partition (even if `AUTONOMOUS_MODE = true`). Announce: `> **Autonomous Mode Paused** — Partition {N} failed 3 gap-fix iterations. Manual review required.`
1093
+
1094
+ **Sequential Teams mode**: Spawn a NEW `builder` with the standard Phase 2A prompt plus gap fix context. Then re-run Phase 2B (spawn a new reviewer). Repeat until user approves at Gate #3.
1095
+
1096
+ **Subagent mode**: Launch parallel `Task()` calls — one for gap fix (builder), then one for re-audit (reviewer). Repeat as needed.
1097
+
1098
+ ### Lead Responsibility: Progress Capture
1099
+
1100
+ **Lead responsibility.** After gate approval, the lead triggers progress capture. If knowz-scribe is active (Parallel Teams with vaults configured):
1101
+ - Create capture task: `TaskCreate("Scribe: Capture Phase 2B")` `TaskUpdate(owner: "knowz-scribe")`
1102
+ - Send message to **knowz-scribe** with task ID: `"Capture Phase 2B: {wgid}. Your task: #{task-id}"` — the scribe reads audit results from the WorkGroup file and writes findings to the appropriate vault
1103
+
1104
+ ---
1105
+
1106
+ ## Phase 3: Finalization
1107
+
1108
+ **Agent**: `closer` | **Loop.md**: Section 3.5
1109
+
1110
+ **Spawn prompt (Parallel Teams)**:
1111
+ > You are the **closer** for WorkGroup `{wgid}`.
1112
+ > Read `agents/closer.md` for your full role definition.
1113
+ >
1114
+ > **Goal**: {goal}
1115
+ > **Change Set**: {NodeIDs}
1116
+ > **Specs**: {list of spec file paths}
1117
+ > **Context files**: Read sections 1-2, 3.5, 6, and 7 of `knowzcode/knowzcode_loop.md` (skip other phases), `knowzcode/knowzcode_tracker.md`, `knowzcode/knowzcode_project.md`, `knowzcode/knowzcode_architecture.md`, `knowzcode/knowzcode_log.md`
1118
+ > **WorkGroup file**: `knowzcode/workgroups/{wgid}.md`
1119
+ >
1120
+ > **Your Task**: #{task-id} claim immediately (`TaskUpdate(status: "in_progress")`). Mark completed with summary when done.
1121
+ > **Conventions**: Update WorkGroup file with results (prefix entries with `KnowzCode:`). If blocked, report blocker and notify lead.
1122
+ > **Vault writes**: Knowz-scribe is active. Create a capture task (`TaskCreate("Scribe: Capture Phase 3")` → `TaskUpdate(owner: "knowz-scribe")`), then send `"Capture Phase 3: {wgid}. Your task: #{task-id}"` to delegate learning capture and audit trail writes. Do NOT call `create_knowledge` directly.
1123
+ > **Deliverable**: Atomic finalization — update specs to FINAL, update tracker, write log entry, update architecture if needed, delegate learning capture to knowz-scribe, and create final commit.
1124
+
1125
+ **Spawn prompt (Sequential Teams / Subagent)**:
1126
+ > You are the **closer** for WorkGroup `{wgid}`.
1127
+ > Read `agents/closer.md` for your full role definition.
1128
+ >
1129
+ > **Goal**: {goal}
1130
+ > **Change Set**: {NodeIDs}
1131
+ > **Specs**: {list of spec file paths}
1132
+ > **Context files**: Read sections 1-2, 3.5, 6, and 7 of `knowzcode/knowzcode_loop.md` (skip other phases), `knowzcode/knowzcode_tracker.md`, `knowzcode/knowzcode_project.md`, `knowzcode/knowzcode_architecture.md`, `knowzcode/knowzcode_log.md`
1133
+ > **WorkGroup file**: `knowzcode/workgroups/{wgid}.md`
1134
+ >
1135
+ > **Your Task**: #{task-id} claim immediately (`TaskUpdate(status: "in_progress")`). Mark completed with summary when done.
1136
+ > **Conventions**: Update WorkGroup file with results (prefix entries with `KnowzCode:`). If blocked, report blocker and notify lead.
1137
+ > **Vault writes**: No knowz-scribeyou own all vault writes. Follow the Direct Write Fallback in `agents/closer.md`.
1138
+ > **MCP Status**: {MCP_ACTIVE} — Vaults configured: {VAULTS_CONFIGURED}. Vault config: `knowzcode/knowzcode_vaults.md`.
1139
+ > **Deliverable**: Atomic finalization — update specs to FINAL, update tracker, write log entry, update architecture if needed, write learnings to vaults, and create final commit.
1140
+
1141
+ **Dispatch**:
1142
+ - *Parallel Teams*: Spawned at Stage 3 (`addBlockedBy`: last audit/re-audit task). Use the **Parallel Teams** spawn prompt. All other agents shut down before closer starts, except knowz-scout and knowz-scribe (stay alive for Phase 3 capture).
1143
+ - *Sequential Teams*: Spawn teammate `closer`, create task `Phase 3: Finalize WorkGroup {wgid}`, wait for completion. Use the **Sequential Teams / Subagent** spawn prompt.
1144
+ - *Subagent*: `Task(subagent_type="closer", description="Phase 3 finalization", prompt=<Sequential/Subagent spawn prompt above>)`
1145
+
1146
+ ### Phase 3 Output
1147
+
1148
+ When complete, if MCP is configured and knowz-scribe is active:
1149
+ - The closer creates a capture task (`TaskCreate("Scribe: Capture Phase 3")` → `TaskUpdate(owner: "knowz-scribe")`) and sends a message with the task ID: `"Capture Phase 3: {wgid}. Your task: #{task-id}"`. The lead waits for the scribe's capture task to complete before shutdown.
1150
+
1151
+ Update workgroup to "Closed" and report:
1152
+
1153
+ ```markdown
1154
+ ## Workflow Complete
1155
+
1156
+ **WorkGroupID**: {wgid}
1157
+ **Primary Goal**: {$ARGUMENTS}
1158
+ **Status**: VERIFIED and CLOSED
1159
+
1160
+ - NodeIDs completed: {list}
1161
+ - Specs finalized: {count}
1162
+ - Tech debt scheduled: {count REFACTOR_ tasks}
1163
+ ```
1164
+
1165
+ ---
1166
+
1167
+ ## Cleanup
1168
+
1169
+ ### After Phase 3 Completes
1170
+
1171
+ **Agent Teams Mode** (Parallel or Sequential):
1172
+ 1. Shut down all active teammates. Wait for each to confirm shutdown.
1173
+ 2. Once all teammates have shut down, clean up the team (delete the `kc-{wgid}` team).
1174
+ No teammates or team resources should remain after the workflow ends.
1175
+
1176
+ **Subagent Mode**: No cleanup needed — `Task()` calls are self-contained.
1177
+
1178
+ ### If User Cancels Mid-Workflow
1179
+
1180
+ Follow the abandonment protocol from `knowzcode_loop.md` Section 12:
1181
+
1182
+ 1. **Revert uncommitted changes** — if implementation was in progress, revert source code changes (keep knowzcode files)
1183
+ 2. **Update tracker** — set all affected NodeIDs back to their pre-WorkGroup status
1184
+ 3. **Log abandonment** — create a log entry with type `WorkGroup-Abandoned` including the reason and phase at abandonment
1185
+ 4. **Close WorkGroup file** — mark the WorkGroup as `Abandoned` with timestamp and reason
1186
+ 5. **Preserve learnings** if any useful patterns were discovered, capture them before closing
1187
+ 6. **Team teardown** — (Agent Teams only) shut down all active teammates and delete the team
1188
+ 7. **Parallel mode**: If cancelled mid-Stage-2, revert uncommitted code changes and mark WorkGroup abandoned
1189
+
1190
+ The WorkGroup file remains in `knowzcode/workgroups/` for reference. It can be resumed later with `/kc:work` referencing the same goal.
1191
+
1192
+ ---
1193
+
1194
+ ## Handling Failures
1195
+
1196
+ - Phase 1A rejected: re-run analyst with feedback
1197
+ - Phase 1B rejected: re-run architect with specific issues (Parallel Teams: architect is already warm)
1198
+ - Phase 2A blocker encountered: present Blocker Report (per loop.md Section 11) to user with 5 recovery options: (1) modify spec, (2) change approach, (3) split WorkGroup, (4) accept partial with documented gap, (5) cancel WorkGroup
1199
+ - Phase 2B audit shows gaps: return to 2A with gap list (see Gap Loop above)
1200
+ - If >3 failures on same phase: PAUSE and ask user for direction (applies even when `AUTONOMOUS_MODE = true` — this is a safety exception)
1201
+
1202
+ ## KnowzCode: Prefix Enforcement
1203
+
1204
+ Every todo in workgroup files MUST start with `KnowzCode:`. Pass this to all agents.