@sienklogic/plan-build-run 2.33.1 → 2.37.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 (140) hide show
  1. package/CHANGELOG.md +678 -0
  2. package/dashboard/public/css/command-center.css +152 -65
  3. package/dashboard/public/css/explorer.css +70 -41
  4. package/dashboard/public/css/layout.css +163 -2
  5. package/dashboard/public/css/settings.css +108 -110
  6. package/dashboard/public/css/timeline.css +2 -1
  7. package/dashboard/public/css/tokens.css +13 -0
  8. package/dashboard/public/js/sidebar-toggle.js +21 -7
  9. package/dashboard/src/components/Layout.tsx +51 -7
  10. package/dashboard/src/components/explorer/tabs/MilestonesTab.tsx +18 -2
  11. package/dashboard/src/components/explorer/tabs/PhasesTab.tsx +11 -1
  12. package/dashboard/src/components/explorer/tabs/TodosTab.tsx +25 -6
  13. package/dashboard/src/components/partials/AttentionPanel.tsx +7 -1
  14. package/dashboard/src/components/partials/CurrentPhaseCard.tsx +26 -24
  15. package/dashboard/src/components/partials/QuickActions.tsx +21 -11
  16. package/dashboard/src/components/partials/StatCardGrid.tsx +67 -0
  17. package/dashboard/src/components/partials/StatusHeader.tsx +2 -1
  18. package/dashboard/src/components/settings/LogEntryList.tsx +43 -5
  19. package/dashboard/src/routes/command-center.routes.tsx +8 -7
  20. package/dashboard/src/routes/index.routes.tsx +32 -29
  21. package/package.json +2 -2
  22. package/plugins/copilot-pbr/agents/audit.agent.md +128 -16
  23. package/plugins/copilot-pbr/agents/codebase-mapper.agent.md +48 -1
  24. package/plugins/copilot-pbr/agents/debugger.agent.md +47 -1
  25. package/plugins/copilot-pbr/agents/executor.agent.md +152 -8
  26. package/plugins/copilot-pbr/agents/general.agent.md +46 -1
  27. package/plugins/copilot-pbr/agents/integration-checker.agent.md +52 -2
  28. package/plugins/copilot-pbr/agents/plan-checker.agent.md +50 -2
  29. package/plugins/copilot-pbr/agents/planner.agent.md +54 -1
  30. package/plugins/copilot-pbr/agents/researcher.agent.md +47 -2
  31. package/plugins/copilot-pbr/agents/synthesizer.agent.md +49 -1
  32. package/plugins/copilot-pbr/agents/verifier.agent.md +86 -2
  33. package/plugins/copilot-pbr/hooks/hooks.json +11 -0
  34. package/plugins/copilot-pbr/plugin.json +1 -1
  35. package/plugins/copilot-pbr/references/agent-contracts.md +27 -0
  36. package/plugins/copilot-pbr/references/checkpoints.md +32 -1
  37. package/plugins/copilot-pbr/references/context-quality-tiers.md +45 -0
  38. package/plugins/copilot-pbr/references/pbr-tools-cli.md +115 -0
  39. package/plugins/copilot-pbr/references/questioning.md +21 -1
  40. package/plugins/copilot-pbr/references/verification-patterns.md +52 -1
  41. package/plugins/copilot-pbr/skills/audit/SKILL.md +19 -3
  42. package/plugins/copilot-pbr/skills/begin/SKILL.md +57 -4
  43. package/plugins/copilot-pbr/skills/build/SKILL.md +39 -2
  44. package/plugins/copilot-pbr/skills/debug/SKILL.md +12 -1
  45. package/plugins/copilot-pbr/skills/explore/SKILL.md +13 -2
  46. package/plugins/copilot-pbr/skills/import/SKILL.md +26 -1
  47. package/plugins/copilot-pbr/skills/milestone/SKILL.md +15 -3
  48. package/plugins/copilot-pbr/skills/plan/SKILL.md +50 -0
  49. package/plugins/copilot-pbr/skills/quick/SKILL.md +21 -0
  50. package/plugins/copilot-pbr/skills/review/SKILL.md +45 -0
  51. package/plugins/copilot-pbr/skills/scan/SKILL.md +20 -0
  52. package/plugins/copilot-pbr/templates/SUMMARY-complex.md.tmpl +95 -0
  53. package/plugins/copilot-pbr/templates/SUMMARY-minimal.md.tmpl +48 -0
  54. package/plugins/cursor-pbr/.cursor-plugin/plugin.json +1 -1
  55. package/plugins/cursor-pbr/agents/audit.md +51 -5
  56. package/plugins/cursor-pbr/agents/codebase-mapper.md +48 -1
  57. package/plugins/cursor-pbr/agents/debugger.md +47 -1
  58. package/plugins/cursor-pbr/agents/executor.md +152 -8
  59. package/plugins/cursor-pbr/agents/general.md +46 -1
  60. package/plugins/cursor-pbr/agents/integration-checker.md +51 -1
  61. package/plugins/cursor-pbr/agents/plan-checker.md +49 -1
  62. package/plugins/cursor-pbr/agents/planner.md +54 -1
  63. package/plugins/cursor-pbr/agents/researcher.md +46 -1
  64. package/plugins/cursor-pbr/agents/synthesizer.md +49 -1
  65. package/plugins/cursor-pbr/agents/verifier.md +85 -1
  66. package/plugins/cursor-pbr/hooks/hooks.json +9 -0
  67. package/plugins/cursor-pbr/references/agent-contracts.md +27 -0
  68. package/plugins/cursor-pbr/references/checkpoints.md +32 -1
  69. package/plugins/cursor-pbr/references/context-quality-tiers.md +45 -0
  70. package/plugins/cursor-pbr/references/pbr-tools-cli.md +115 -0
  71. package/plugins/cursor-pbr/references/questioning.md +21 -1
  72. package/plugins/cursor-pbr/references/verification-patterns.md +52 -1
  73. package/plugins/cursor-pbr/skills/audit/SKILL.md +19 -3
  74. package/plugins/cursor-pbr/skills/begin/SKILL.md +57 -4
  75. package/plugins/cursor-pbr/skills/build/SKILL.md +37 -2
  76. package/plugins/cursor-pbr/skills/debug/SKILL.md +12 -1
  77. package/plugins/cursor-pbr/skills/explore/SKILL.md +13 -2
  78. package/plugins/cursor-pbr/skills/import/SKILL.md +26 -1
  79. package/plugins/cursor-pbr/skills/milestone/SKILL.md +15 -3
  80. package/plugins/cursor-pbr/skills/plan/SKILL.md +50 -0
  81. package/plugins/cursor-pbr/skills/quick/SKILL.md +21 -0
  82. package/plugins/cursor-pbr/skills/review/SKILL.md +45 -0
  83. package/plugins/cursor-pbr/skills/scan/SKILL.md +20 -0
  84. package/plugins/cursor-pbr/templates/SUMMARY-complex.md.tmpl +95 -0
  85. package/plugins/cursor-pbr/templates/SUMMARY-minimal.md.tmpl +48 -0
  86. package/plugins/pbr/.claude-plugin/plugin.json +1 -1
  87. package/plugins/pbr/agents/audit.md +44 -0
  88. package/plugins/pbr/agents/codebase-mapper.md +47 -0
  89. package/plugins/pbr/agents/debugger.md +46 -0
  90. package/plugins/pbr/agents/executor.md +150 -6
  91. package/plugins/pbr/agents/general.md +45 -0
  92. package/plugins/pbr/agents/integration-checker.md +50 -0
  93. package/plugins/pbr/agents/plan-checker.md +48 -0
  94. package/plugins/pbr/agents/planner.md +51 -0
  95. package/plugins/pbr/agents/researcher.md +45 -0
  96. package/plugins/pbr/agents/synthesizer.md +48 -0
  97. package/plugins/pbr/agents/verifier.md +84 -0
  98. package/plugins/pbr/hooks/hooks.json +9 -0
  99. package/plugins/pbr/references/agent-contracts.md +27 -0
  100. package/plugins/pbr/references/checkpoints.md +32 -0
  101. package/plugins/pbr/references/context-quality-tiers.md +45 -0
  102. package/plugins/pbr/references/pbr-tools-cli.md +115 -0
  103. package/plugins/pbr/references/questioning.md +21 -0
  104. package/plugins/pbr/references/verification-patterns.md +52 -0
  105. package/plugins/pbr/scripts/check-plan-format.js +15 -3
  106. package/plugins/pbr/scripts/check-state-sync.js +26 -7
  107. package/plugins/pbr/scripts/check-subagent-output.js +30 -2
  108. package/plugins/pbr/scripts/config-schema.json +11 -1
  109. package/plugins/pbr/scripts/context-bridge.js +259 -0
  110. package/plugins/pbr/scripts/context-budget-check.js +2 -2
  111. package/plugins/pbr/scripts/lib/config.js +178 -0
  112. package/plugins/pbr/scripts/lib/core.js +578 -0
  113. package/plugins/pbr/scripts/lib/history.js +73 -0
  114. package/plugins/pbr/scripts/lib/init.js +166 -0
  115. package/plugins/pbr/scripts/lib/phase.js +364 -0
  116. package/plugins/pbr/scripts/lib/roadmap.js +175 -0
  117. package/plugins/pbr/scripts/lib/state.js +397 -0
  118. package/plugins/pbr/scripts/pbr-tools.js +346 -1235
  119. package/plugins/pbr/scripts/post-write-dispatch.js +5 -4
  120. package/plugins/pbr/scripts/post-write-quality.js +3 -3
  121. package/plugins/pbr/scripts/pre-write-dispatch.js +1 -1
  122. package/plugins/pbr/scripts/progress-tracker.js +1 -1
  123. package/plugins/pbr/scripts/suggest-compact.js +1 -1
  124. package/plugins/pbr/scripts/track-context-budget.js +53 -2
  125. package/plugins/pbr/scripts/validate-task.js +20 -28
  126. package/plugins/pbr/skills/audit/SKILL.md +19 -3
  127. package/plugins/pbr/skills/begin/SKILL.md +48 -2
  128. package/plugins/pbr/skills/build/SKILL.md +39 -2
  129. package/plugins/pbr/skills/debug/SKILL.md +12 -1
  130. package/plugins/pbr/skills/debug/templates/continuation-prompt.md.tmpl +12 -1
  131. package/plugins/pbr/skills/debug/templates/initial-investigation-prompt.md.tmpl +12 -5
  132. package/plugins/pbr/skills/explore/SKILL.md +13 -2
  133. package/plugins/pbr/skills/import/SKILL.md +26 -1
  134. package/plugins/pbr/skills/milestone/SKILL.md +15 -3
  135. package/plugins/pbr/skills/plan/SKILL.md +52 -2
  136. package/plugins/pbr/skills/quick/SKILL.md +21 -0
  137. package/plugins/pbr/skills/review/SKILL.md +46 -0
  138. package/plugins/pbr/skills/scan/SKILL.md +20 -0
  139. package/plugins/pbr/templates/SUMMARY-complex.md.tmpl +95 -0
  140. package/plugins/pbr/templates/SUMMARY-minimal.md.tmpl +48 -0
@@ -283,3 +283,118 @@ node ${CLAUDE_PLUGIN_ROOT}/scripts/pbr-tools.js event error hook-failure '{"scri
283
283
  **Output:** `{ "logged": true, "category": "build", "event": "plan-complete" }`
284
284
 
285
285
  If the JSON-details argument is not valid JSON, it's stored as `{ "raw": "<the string>" }`.
286
+
287
+ ---
288
+
289
+ ## Compound Init Commands
290
+
291
+ Compound commands that compose multiple data sources into a single JSON response.
292
+ Replace multi-step context loading in skills with a single CLI call.
293
+
294
+ ### `init execute-phase <phase>`
295
+
296
+ Everything an executor needs to start building a phase.
297
+
298
+ ```bash
299
+ node ${CLAUDE_PLUGIN_ROOT}/scripts/pbr-tools.js init execute-phase 3
300
+ ```
301
+
302
+ **Output:**
303
+ ```json
304
+ {
305
+ "executor_model": "sonnet",
306
+ "verifier_model": "sonnet",
307
+ "config": { "depth": "standard", "mode": "interactive", "parallelization": {}, "planning": {}, "gates": {}, "features": {} },
308
+ "phase": { "num": "3", "dir": "03-auth", "name": "auth", "goal": "...", "has_context": false, "status": "planned", "plan_count": 2, "completed": 0 },
309
+ "plans": [{ "file": "PLAN-01.md", "plan_id": "01", "wave": 1, "autonomous": true, "has_summary": false, "must_haves_count": 4, "depends_on": [] }],
310
+ "waves": { "wave_1": ["01", "02"] },
311
+ "branch_name": "main",
312
+ "git_clean": true
313
+ }
314
+ ```
315
+
316
+ ### `init plan-phase <phase>`
317
+
318
+ Everything a planner needs to start phase planning.
319
+
320
+ ```bash
321
+ node ${CLAUDE_PLUGIN_ROOT}/scripts/pbr-tools.js init plan-phase 3
322
+ ```
323
+
324
+ **Output:** `researcher_model`, `planner_model`, `checker_model`, `config` (depth profile, features, planning settings), `phase` (num, dir, goal, depends_on), `existing_artifacts`, `workflow` flags.
325
+
326
+ ### `init quick <description>`
327
+
328
+ Everything the quick skill needs: next task number, slug, directory path.
329
+
330
+ ```bash
331
+ node ${CLAUDE_PLUGIN_ROOT}/scripts/pbr-tools.js init quick "add search feature"
332
+ ```
333
+
334
+ **Output:** `next_task_number`, `slug`, `dir`, `dir_name`, `timestamp`, `config` subset.
335
+
336
+ ### `init verify-work <phase>`
337
+
338
+ Everything a verifier needs to start verification.
339
+
340
+ ```bash
341
+ node ${CLAUDE_PLUGIN_ROOT}/scripts/pbr-tools.js init verify-work 3
342
+ ```
343
+
344
+ **Output:** `verifier_model`, `phase` info, `has_verification`, `prior_attempts`, `prior_status`, `summaries`.
345
+
346
+ ### `init resume`
347
+
348
+ Detect interrupted state and suggest continuation.
349
+
350
+ ```bash
351
+ node ${CLAUDE_PLUGIN_ROOT}/scripts/pbr-tools.js init resume
352
+ ```
353
+
354
+ **Output:** `state`, `auto_next`, `continue_here`, `active_skill`, `current_phase`, `progress`.
355
+
356
+ ### `init progress`
357
+
358
+ All phases with status and completion data.
359
+
360
+ ```bash
361
+ node ${CLAUDE_PLUGIN_ROOT}/scripts/pbr-tools.js init progress
362
+ ```
363
+
364
+ **Output:** `current_phase`, `total_phases`, `status`, `phases` array, `total_plans`, `completed_plans`, `percentage`.
365
+
366
+ ---
367
+
368
+ ## State Mutation Extensions
369
+
370
+ ### `state patch <JSON>`
371
+
372
+ Multi-field atomic STATE.md update. Updates all fields in a single pass.
373
+
374
+ ```bash
375
+ node ${CLAUDE_PLUGIN_ROOT}/scripts/pbr-tools.js state patch '{"status":"executing","last_activity":"now"}'
376
+ ```
377
+
378
+ **Valid fields:** `current_phase`, `status`, `plans_complete`, `last_activity`, `progress_percent`, `phase_slug`, `total_phases`, `last_command`, `blockers`
379
+
380
+ **Output:** `{ "success": true, "updated": ["status", "last_activity"] }`
381
+
382
+ ### `state advance-plan`
383
+
384
+ Increment current plan number in STATE.md and update progress percentage.
385
+
386
+ ```bash
387
+ node ${CLAUDE_PLUGIN_ROOT}/scripts/pbr-tools.js state advance-plan
388
+ ```
389
+
390
+ **Output:** `{ "success": true, "previous_plan": 1, "current_plan": 2, "total_plans": 5, "progress_percent": 40 }`
391
+
392
+ ### `state record-metric [--duration Nm] [--plans-completed N]`
393
+
394
+ Record session/execution metrics. Appends to HISTORY.md and updates last_activity.
395
+
396
+ ```bash
397
+ node ${CLAUDE_PLUGIN_ROOT}/scripts/pbr-tools.js state record-metric --duration 15m --plans-completed 3
398
+ ```
399
+
400
+ **Output:** `{ "success": true, "duration_minutes": 15, "plans_completed": 3 }`
@@ -212,3 +212,24 @@ See **[skills/shared/domain-probes.md](../shared/domain-probes.md)** for technol
212
212
  9. **DO NOT** lead the user toward a particular solution
213
213
  10. **DO NOT** forget to summarize and confirm understanding
214
214
  11. **DO NOT** ask what you already know — track what the user has stated and never re-ask it. If they said "I'm using React", do not later ask "Are you using a frontend framework?" If they said "PostgreSQL", do not ask "What database are you using?" Redundant questions waste exchanges and erode trust. Instead, build on what you know: "You mentioned React — are you using Next.js or plain CRA?"
215
+
216
+ ---
217
+
218
+ ## Dream Extraction Philosophy
219
+
220
+ The goal of questioning is not to gather requirements — it's to extract the user's dream and make it buildable.
221
+
222
+ ### 4-Item Context Checklist
223
+ Before planning can begin, you must know:
224
+ 1. **What** are we building? (concrete deliverable, not abstract concept)
225
+ 2. **Why** does it exist? (the problem it solves, not the tech it uses)
226
+ 3. **Who** is it for? (specific users, not "everyone")
227
+ 4. **What does done look like?** (observable outcomes, not technical milestones)
228
+
229
+ ### Conversation Rules
230
+ - **Start open**: "Tell me about what you want to build"
231
+ - **Follow energy**: When they light up about something, dig deeper there
232
+ - **Challenge vagueness**: "You said 'user-friendly' — what does that mean specifically?"
233
+ - **Know when to stop**: When you have the 4 items above, move to planning
234
+ - **NEVER ask about technical experience**: It's irrelevant and condescending
235
+ - **NEVER present a menu of options**: Open questions reveal more than multiple choice
@@ -196,3 +196,55 @@ Bad: "Tests pass"
196
196
  Good: "All 5 auth middleware tests pass: valid token, expired token,
197
197
  missing token, malformed token, and correct user extraction"
198
198
  ```
199
+
200
+ ---
201
+
202
+ ## Wiring Verification Patterns
203
+
204
+ 4 concrete patterns for verifying components are actually connected, not just present.
205
+
206
+ ### Pattern 1: Component to API
207
+ 1. Find the fetch/axios call in the component
208
+ 2. Verify the call is NOT commented out
209
+ 3. Verify the response is assigned to state (not discarded)
210
+ 4. Verify error handling exists (try/catch or .catch)
211
+
212
+ ### Pattern 2: API to Database
213
+ 1. Find the database query in the route handler
214
+ 2. Verify `await` is present (not fire-and-forget)
215
+ 3. Verify the result is returned in the response (not discarded)
216
+ 4. Verify error cases return appropriate HTTP status codes
217
+
218
+ ### Pattern 3: Form to Handler
219
+ 1. Find the form's onSubmit handler
220
+ 2. Verify it calls an API function (not just preventDefault)
221
+ 3. Verify form validation runs before the API call
222
+ 4. Verify success/error feedback is shown to the user
223
+
224
+ ### Pattern 4: State to Render
225
+ 1. Find state variables (useState, store, etc.)
226
+ 2. Verify they appear in JSX/template via .map(), interpolation, or conditional rendering
227
+ 3. Verify loading/error states are rendered (not just success state)
228
+ 4. Verify empty state is handled (not just "no data" crash)
229
+
230
+ ### Quick Verification Checklists
231
+
232
+ **Component Checklist (8 items):**
233
+ - [ ] Component file exists and exports correctly
234
+ - [ ] Props/types are defined (not `any`)
235
+ - [ ] API calls use actual endpoints (not hardcoded data)
236
+ - [ ] Loading state renders something meaningful
237
+ - [ ] Error state renders something meaningful
238
+ - [ ] Empty state renders something meaningful
239
+ - [ ] User interactions trigger actual handlers
240
+ - [ ] Component is imported and rendered in parent
241
+
242
+ **API Route Checklist (8 items):**
243
+ - [ ] Route file exists and exports handler
244
+ - [ ] Route is registered in router/app
245
+ - [ ] Request validation exists (body, params, query)
246
+ - [ ] Database query uses parameterized inputs
247
+ - [ ] Success response includes expected data shape
248
+ - [ ] Error response includes status code and message
249
+ - [ ] Authentication/authorization check exists if needed
250
+ - [ ] Response matches what the frontend expects
@@ -24,7 +24,7 @@ const fs = require('fs');
24
24
  const path = require('path');
25
25
  const { logHook } = require('./hook-logger');
26
26
  const { logEvent } = require('./event-logger');
27
- const { atomicWrite } = require('./pbr-tools');
27
+ const { lockedFileUpdate } = require('./pbr-tools');
28
28
  const { resolveConfig } = require('./local-llm/health');
29
29
  const { classifyArtifact } = require('./local-llm/operations/classify-artifact');
30
30
 
@@ -194,7 +194,7 @@ function validatePlan(content, _filePath) {
194
194
 
195
195
  // Skip checkpoint tasks - they have different required elements
196
196
  const taskTag = taskTags[index] || '';
197
- if (taskTag.includes('checkpoint')) {
197
+ if (/\btype\s*=\s*["']?checkpoint/i.test(taskTag) || /\bcheckpoint\s*[:=]/i.test(taskTag)) {
198
198
  return; // Checkpoint tasks have different structure
199
199
  }
200
200
 
@@ -205,6 +205,18 @@ function validatePlan(content, _filePath) {
205
205
  }
206
206
  });
207
207
 
208
+ // Path traversal check: ensure <files> elements don't escape project root
209
+ const filesTags = content.match(/<files>([\s\S]*?)<\/files>/g) || [];
210
+ for (const filesTag of filesTags) {
211
+ const filesContent = filesTag.replace(/<\/?files>/g, '');
212
+ const paths = filesContent.split(/[\n,]/).map(p => p.trim()).filter(Boolean);
213
+ for (const p of paths) {
214
+ if (p.includes('..') || path.isAbsolute(p.replace(/^[A-Za-z]:/, ''))) {
215
+ warnings.push(`Path traversal risk in <files>: "${p}" — use relative paths without ".." segments`);
216
+ }
217
+ }
218
+ }
219
+
208
220
  return { errors, warnings };
209
221
  }
210
222
 
@@ -464,7 +476,7 @@ function syncStateBody(content, filePath) {
464
476
  if (!needsFix) return null;
465
477
 
466
478
  try {
467
- atomicWrite(filePath, updated);
479
+ lockedFileUpdate(filePath, () => updated);
468
480
  logHook('check-plan-format', 'PostToolUse', 'body-sync', {
469
481
  fromPhase: bodyPhaseMatch[1], toPhase: fmPhase
470
482
  });
@@ -26,7 +26,25 @@ const fs = require('fs');
26
26
  const path = require('path');
27
27
  const { logHook } = require('./hook-logger');
28
28
  const { logEvent } = require('./event-logger');
29
- const { atomicWrite } = require('./pbr-tools');
29
+
30
+ /**
31
+ * Write content to a file atomically using write-then-rename.
32
+ * Writes to a PID-stamped temp file, then renames over the original.
33
+ * If the rename fails, cleans up the temp file and re-throws.
34
+ *
35
+ * @param {string} filePath - Target file path
36
+ * @param {string} content - Content to write
37
+ */
38
+ function atomicWriteFile(filePath, content) {
39
+ const tmpPath = filePath + '.tmp.' + process.pid;
40
+ try {
41
+ fs.writeFileSync(tmpPath, content, 'utf8');
42
+ fs.renameSync(tmpPath, filePath);
43
+ } catch (e) {
44
+ try { fs.unlinkSync(tmpPath); } catch (_) { /* best effort cleanup */ }
45
+ throw e;
46
+ }
47
+ }
30
48
 
31
49
  /**
32
50
  * Extract phase number from a phase directory name.
@@ -326,7 +344,7 @@ function checkStateSync(data) {
326
344
  return null;
327
345
  }
328
346
 
329
- const cwd = process.cwd();
347
+ const cwd = process.env.PBR_PROJECT_ROOT || process.cwd();
330
348
  const planningDir = path.join(cwd, '.planning');
331
349
  const roadmapPath = path.join(planningDir, 'ROADMAP.md');
332
350
  const statePath = path.join(planningDir, 'STATE.md');
@@ -370,7 +388,7 @@ function checkStateSync(data) {
370
388
  } else {
371
389
  const updatedRoadmap = updateProgressTable(roadmapContent, phaseNum, plansComplete, newStatus, completedDate);
372
390
  if (updatedRoadmap !== roadmapContent) {
373
- atomicWrite(roadmapPath, updatedRoadmap);
391
+ atomicWriteFile(roadmapPath, updatedRoadmap);
374
392
  messages.push(`ROADMAP.md: Phase ${phaseNum} → ${plansComplete} plans, ${newStatus}`);
375
393
  }
376
394
  }
@@ -410,7 +428,7 @@ function checkStateSync(data) {
410
428
 
411
429
  const updatedState = updateStatePosition(stateContent, stateUpdates);
412
430
  if (updatedState !== stateContent) {
413
- atomicWrite(statePath, updatedState);
431
+ atomicWriteFile(statePath, updatedState);
414
432
  messages.push(`STATE.md: ${artifacts.completeSummaries}/${artifacts.plans} plans, ${overallPct}%`);
415
433
  }
416
434
  } catch (e) {
@@ -455,7 +473,7 @@ function checkStateSync(data) {
455
473
  } else {
456
474
  const updatedRoadmap = updateProgressTable(roadmapContent, phaseNum, plansComplete, roadmapStatus, completedDate);
457
475
  if (updatedRoadmap !== roadmapContent) {
458
- atomicWrite(roadmapPath, updatedRoadmap);
476
+ atomicWriteFile(roadmapPath, updatedRoadmap);
459
477
  messages.push(`ROADMAP.md: Phase ${phaseNum} → ${roadmapStatus}`);
460
478
  }
461
479
  }
@@ -493,7 +511,7 @@ function checkStateSync(data) {
493
511
 
494
512
  const updatedState = updateStatePosition(stateContent, stateUpdates);
495
513
  if (updatedState !== stateContent) {
496
- atomicWrite(statePath, updatedState);
514
+ atomicWriteFile(statePath, updatedState);
497
515
  messages.push(`STATE.md: ${stateStatus}, ${overallPct}%`);
498
516
  }
499
517
  } catch (e) {
@@ -543,7 +561,7 @@ function checkStateSync(data) {
543
561
  const plansComplete = `${artifacts.completeSummaries}/${artifacts.plans}`;
544
562
  const updatedRoadmap = updateProgressTable(roadmapContent, phaseNum, plansComplete, 'Planning', null);
545
563
  if (updatedRoadmap !== roadmapContent) {
546
- atomicWrite(roadmapPath, updatedRoadmap);
564
+ atomicWriteFile(roadmapPath, updatedRoadmap);
547
565
  messages.push(`ROADMAP.md: Phase ${phaseNum} → Planning`);
548
566
  }
549
567
  }
@@ -588,6 +606,7 @@ function main() {
588
606
 
589
607
  if (require.main === module || process.argv[1] === __filename) { main(); }
590
608
  module.exports = {
609
+ atomicWriteFile,
591
610
  extractPhaseNum,
592
611
  countPhaseArtifacts,
593
612
  updateProgressTable,
@@ -20,6 +20,7 @@
20
20
  const fs = require('fs');
21
21
  const path = require('path');
22
22
  const { logHook } = require('./hook-logger');
23
+ const { KNOWN_AGENTS } = require('./pbr-tools');
23
24
  const { resolveConfig } = require('./local-llm/health');
24
25
  const { classifyError } = require('./local-llm/operations/classify-error');
25
26
 
@@ -27,7 +28,7 @@ const { classifyError } = require('./local-llm/operations/classify-error');
27
28
  * Check if a file was modified recently (within thresholdMs).
28
29
  * Returns false if file doesn't exist or on error.
29
30
  */
30
- function isRecent(filePath, thresholdMs = 300000) {
31
+ function isRecent(filePath, thresholdMs = 1800000) {
31
32
  try {
32
33
  const stat = fs.statSync(filePath);
33
34
  return (Date.now() - stat.mtimeMs) < thresholdMs;
@@ -151,6 +152,25 @@ const AGENT_OUTPUTS = {
151
152
  description: 'advisory output (no file expected)',
152
153
  noFileExpected: true,
153
154
  check: () => []
155
+ },
156
+ 'pbr:audit': {
157
+ description: 'audit report in .planning/audits/',
158
+ check: (planningDir) => {
159
+ const auditsDir = path.join(planningDir, 'audits');
160
+ if (!fs.existsSync(auditsDir)) return [];
161
+ try {
162
+ return fs.readdirSync(auditsDir)
163
+ .filter(f => f.endsWith('.md'))
164
+ .map(f => path.join('audits', f));
165
+ } catch (_e) {
166
+ return [];
167
+ }
168
+ }
169
+ },
170
+ 'pbr:dev-sync': {
171
+ description: 'advisory output (no file expected)',
172
+ noFileExpected: true,
173
+ check: () => []
154
174
  }
155
175
  };
156
176
 
@@ -324,7 +344,7 @@ function loadLocalLlmConfig(cwd) {
324
344
 
325
345
  async function main() {
326
346
  const data = readStdin();
327
- const cwd = process.cwd();
347
+ const cwd = process.env.PBR_PROJECT_ROOT || process.cwd();
328
348
  const planningDir = path.join(cwd, '.planning');
329
349
 
330
350
  // Only relevant for Plan-Build-Run projects
@@ -338,6 +358,14 @@ async function main() {
338
358
  // Only check known Plan-Build-Run agent types
339
359
  const outputSpec = AGENT_OUTPUTS[agentType];
340
360
  if (!outputSpec) {
361
+ // Log when agent is in KNOWN_AGENTS but missing from AGENT_OUTPUTS
362
+ const shortName = agentType.startsWith('pbr:') ? agentType.slice(4) : agentType;
363
+ if (KNOWN_AGENTS && KNOWN_AGENTS.includes && KNOWN_AGENTS.includes(shortName)) {
364
+ logHook('check-subagent-output', 'PostToolUse', 'missing-output-spec', {
365
+ agent_type: agentType,
366
+ message: `Agent ${agentType} is in KNOWN_AGENTS but has no AGENT_OUTPUTS entry. Add one to check-subagent-output.js.`
367
+ });
368
+ }
341
369
  process.exit(0);
342
370
  }
343
371
 
@@ -4,7 +4,8 @@
4
4
  "description": "Configuration schema for .planning/config.json",
5
5
  "type": "object",
6
6
  "properties": {
7
- "version": { "type": "integer", "enum": [1, 2] },
7
+ "version": { "type": ["integer", "string"], "enum": [1, 2, "1", "2"], "description": "Planning format version. v2 is current." },
8
+ "schema_version": { "type": "integer", "enum": [1], "description": "Config schema version for migration detection. Increment when config structure changes." },
8
9
  "context_strategy": { "type": "string", "enum": ["aggressive", "conservative", "balanced"] },
9
10
  "mode": { "type": "string", "enum": ["interactive", "autonomous"] },
10
11
  "depth": { "type": "string", "enum": ["quick", "standard", "comprehensive"], "description": "Workflow depth: quick = budget mode (fewer spawns, skip optional stages), standard = balanced mode (conditional spawns), comprehensive = thorough mode (all spawns, current default)" },
@@ -131,6 +132,15 @@
131
132
  },
132
133
  "additionalProperties": false
133
134
  },
135
+ "timeouts": {
136
+ "type": "object",
137
+ "properties": {
138
+ "task_default_ms": { "type": "integer", "minimum": 30000, "description": "Default timeout per task in milliseconds (default: 300000 = 5 min)" },
139
+ "build_max_ms": { "type": "integer", "minimum": 60000, "description": "Maximum time for entire build command in milliseconds" },
140
+ "verify_max_ms": { "type": "integer", "minimum": 30000, "description": "Maximum time for verification in milliseconds" }
141
+ },
142
+ "additionalProperties": false
143
+ },
134
144
  "hooks": {
135
145
  "type": "object",
136
146
  "properties": {
@@ -0,0 +1,259 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * PostToolUse hook: Context monitor bridge.
5
+ *
6
+ * Replaces heuristic context budget estimation with real data when available.
7
+ * Writes context state to .planning/.context-budget.json for consumption by
8
+ * track-context-budget.js and suggest-compact.js.
9
+ *
10
+ * Context tiers:
11
+ * PEAK (0-30%) — no warnings
12
+ * GOOD (30-50%) — no warnings
13
+ * DEGRADING (50-70%) — suggest subagent delegation
14
+ * POOR (70%+) — recommend /pbr:pause
15
+ *
16
+ * Debounce: same-tier warnings suppressed for 5 tool calls.
17
+ * Tier escalation always warns immediately.
18
+ *
19
+ * Exit codes:
20
+ * 0 = always (PostToolUse hook, advisory only)
21
+ */
22
+
23
+ const fs = require('fs');
24
+ const path = require('path');
25
+ const { logHook } = require('./hook-logger');
26
+
27
+ const TIERS = [
28
+ { name: 'PEAK', min: 0, max: 30 },
29
+ { name: 'GOOD', min: 30, max: 50 },
30
+ { name: 'DEGRADING', min: 50, max: 70 },
31
+ { name: 'POOR', min: 70, max: 100 }
32
+ ];
33
+
34
+ const TIER_MESSAGES = {
35
+ DEGRADING: 'Context is filling. Consider delegating heavy work to subagents.',
36
+ POOR: 'Context critically low. Recommend /pbr:pause to save state.'
37
+ };
38
+
39
+ const DEBOUNCE_INTERVAL = 5; // tool calls between same-tier warnings
40
+
41
+ /**
42
+ * Determine the context tier for a given percentage.
43
+ * @param {number} percent - Context usage percentage (0-100)
44
+ * @returns {{ name: string, min: number, max: number }}
45
+ */
46
+ function getTier(percent) {
47
+ for (const tier of TIERS) {
48
+ if (percent < tier.max) return tier;
49
+ }
50
+ return TIERS[TIERS.length - 1];
51
+ }
52
+
53
+ /**
54
+ * Load the bridge state file.
55
+ * @param {string} bridgePath - Absolute path to .context-budget.json
56
+ * @returns {Object} Bridge state
57
+ */
58
+ function loadBridge(bridgePath) {
59
+ try {
60
+ const content = fs.readFileSync(bridgePath, 'utf8');
61
+ return JSON.parse(content);
62
+ } catch (_e) {
63
+ return null;
64
+ }
65
+ }
66
+
67
+ /**
68
+ * Save the bridge state file atomically.
69
+ * @param {string} bridgePath - Absolute path to .context-budget.json
70
+ * @param {Object} data - Bridge state to persist
71
+ */
72
+ function saveBridge(bridgePath, data) {
73
+ try {
74
+ const tmpPath = bridgePath + '.' + process.pid;
75
+ fs.writeFileSync(tmpPath, JSON.stringify(data, null, 2), 'utf8');
76
+ fs.renameSync(tmpPath, bridgePath);
77
+ } catch (_e) {
78
+ // Best-effort — clean up temp file if rename failed
79
+ try { fs.unlinkSync(bridgePath + '.' + process.pid); } catch (_e2) { /* best-effort */ }
80
+ }
81
+ }
82
+
83
+ /**
84
+ * Estimate context percentage from heuristic tracker data.
85
+ * Uses the .context-tracker file written by track-context-budget.js.
86
+ * Assumes 200k token context window (~800k chars).
87
+ *
88
+ * @param {string} planningDir - Path to .planning/
89
+ * @returns {number} Estimated context usage percentage (0-100)
90
+ */
91
+ function estimateFromHeuristic(planningDir) {
92
+ const trackerPath = path.join(planningDir, '.context-tracker');
93
+ try {
94
+ const content = fs.readFileSync(trackerPath, 'utf8');
95
+ const tracker = JSON.parse(content);
96
+ const totalChars = tracker.total_chars || 0;
97
+ // 200k tokens ~ 800k chars; use 800000 as denominator
98
+ const percent = Math.min(100, Math.round((totalChars / 800000) * 100));
99
+ return percent;
100
+ } catch (_e) {
101
+ return 0;
102
+ }
103
+ }
104
+
105
+ /**
106
+ * Check if a tier warning should fire, applying debounce logic.
107
+ *
108
+ * @param {Object} bridge - Current bridge state
109
+ * @param {string} tierName - Current tier name
110
+ * @returns {boolean} True if warning should fire
111
+ */
112
+ function shouldWarn(bridge, tierName) {
113
+ // No warning for PEAK or GOOD
114
+ if (tierName === 'PEAK' || tierName === 'GOOD') return false;
115
+
116
+ const prevTier = bridge.last_warned_tier || 'PEAK';
117
+ const callsSinceWarn = bridge.calls_since_warn || 0;
118
+
119
+ // Tier escalation — always warn
120
+ const tierOrder = { PEAK: 0, GOOD: 1, DEGRADING: 2, POOR: 3 };
121
+ if ((tierOrder[tierName] || 0) > (tierOrder[prevTier] || 0)) {
122
+ return true;
123
+ }
124
+
125
+ // Same tier — debounce
126
+ if (callsSinceWarn >= DEBOUNCE_INTERVAL) {
127
+ return true;
128
+ }
129
+
130
+ return false;
131
+ }
132
+
133
+ /**
134
+ * Core bridge logic: update bridge state, return warning if applicable.
135
+ *
136
+ * @param {string} planningDir - Path to .planning/
137
+ * @param {Object} stdinData - Parsed stdin JSON from Claude Code
138
+ * @returns {{ bridge: Object, output: Object|null }} Updated bridge and optional warning output
139
+ */
140
+ function updateBridge(planningDir, stdinData) {
141
+ const bridgePath = path.join(planningDir, '.context-budget.json');
142
+
143
+ // Check if Claude Code provides real context percentage in stdin
144
+ // Look for context_percent, usage_percent, context_usage, or similar fields
145
+ const contextPercent = stdinData.context_percent
146
+ || stdinData.usage_percent
147
+ || (stdinData.context && stdinData.context.percent)
148
+ || null;
149
+
150
+ const source = contextPercent !== null ? 'bridge' : 'heuristic';
151
+ const estimatedPercent = contextPercent !== null
152
+ ? Math.round(contextPercent)
153
+ : estimateFromHeuristic(planningDir);
154
+
155
+ // Load existing bridge state
156
+ let bridge = loadBridge(bridgePath) || {
157
+ timestamp: new Date().toISOString(),
158
+ estimated_percent: 0,
159
+ source: 'heuristic',
160
+ chars_read: 0,
161
+ warnings_issued: [],
162
+ last_warned_tier: 'PEAK',
163
+ calls_since_warn: 0,
164
+ tool_calls: 0
165
+ };
166
+
167
+ // Update bridge
168
+ bridge.timestamp = new Date().toISOString();
169
+ bridge.estimated_percent = estimatedPercent;
170
+ bridge.source = source;
171
+ bridge.tool_calls = (bridge.tool_calls || 0) + 1;
172
+ bridge.calls_since_warn = (bridge.calls_since_warn || 0) + 1;
173
+
174
+ // Read chars from tracker if available
175
+ const trackerPath = path.join(planningDir, '.context-tracker');
176
+ try {
177
+ const tracker = JSON.parse(fs.readFileSync(trackerPath, 'utf8'));
178
+ bridge.chars_read = tracker.total_chars || 0;
179
+ } catch (_e) {
180
+ // Keep existing value
181
+ }
182
+
183
+ const tier = getTier(estimatedPercent);
184
+ let output = null;
185
+
186
+ if (shouldWarn(bridge, tier.name)) {
187
+ const msg = TIER_MESSAGES[tier.name];
188
+ if (msg) {
189
+ bridge.last_warned_tier = tier.name;
190
+ bridge.calls_since_warn = 0;
191
+ bridge.warnings_issued = bridge.warnings_issued || [];
192
+ bridge.warnings_issued.push({
193
+ tier: tier.name,
194
+ percent: estimatedPercent,
195
+ timestamp: new Date().toISOString()
196
+ });
197
+
198
+ // Keep only last 20 warnings
199
+ if (bridge.warnings_issued.length > 20) {
200
+ bridge.warnings_issued = bridge.warnings_issued.slice(-20);
201
+ }
202
+
203
+ output = {
204
+ additionalContext: `[Context Monitor — ${tier.name}] ${estimatedPercent}% used (${source}). ${msg}`
205
+ };
206
+ }
207
+ }
208
+
209
+ // Save bridge state
210
+ saveBridge(bridgePath, bridge);
211
+
212
+ return { bridge, output };
213
+ }
214
+
215
+ function main() {
216
+ let input = '';
217
+
218
+ process.stdin.setEncoding('utf8');
219
+ process.stdin.on('data', (chunk) => { input += chunk; });
220
+ process.stdin.on('end', () => {
221
+ try {
222
+ const cwd = process.cwd();
223
+ const planningDir = path.join(cwd, '.planning');
224
+ if (!fs.existsSync(planningDir)) {
225
+ process.exit(0);
226
+ }
227
+
228
+ const data = input ? JSON.parse(input) : {};
229
+ const { output } = updateBridge(planningDir, data);
230
+
231
+ if (output) {
232
+ logHook('context-bridge', 'PostToolUse', 'warn', {
233
+ percent: output.additionalContext.match(/(\d+)%/)?.[1],
234
+ source: 'bridge'
235
+ });
236
+ process.stdout.write(JSON.stringify(output));
237
+ }
238
+
239
+ process.exit(0);
240
+ } catch (_e) {
241
+ // Never block on tracking errors
242
+ process.exit(0);
243
+ }
244
+ });
245
+ }
246
+
247
+ module.exports = {
248
+ getTier,
249
+ loadBridge,
250
+ saveBridge,
251
+ estimateFromHeuristic,
252
+ shouldWarn,
253
+ updateBridge,
254
+ TIERS,
255
+ TIER_MESSAGES,
256
+ DEBOUNCE_INTERVAL
257
+ };
258
+
259
+ if (require.main === module || process.argv[1] === __filename) { main(); }