@haposoft/cafekit 0.14.0 → 0.14.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +27 -3
  2. package/bin/__tests__/installer-safety.test.js +145 -0
  3. package/bin/install.js +9 -1
  4. package/bin/lib/backup.js +60 -16
  5. package/bin/lib/context.js +1 -1
  6. package/bin/phases/claude-runtime.js +57 -4
  7. package/bin/phases/post-install.js +39 -26
  8. package/bin/phases/root-config.js +24 -5
  9. package/bin/phases/select-platform.js +14 -9
  10. package/package.json +1 -1
  11. package/src/claude/CLAUDE.md +1 -1
  12. package/src/claude/agents/code-auditor.md +1 -1
  13. package/src/claude/agents/debugger.md +1 -0
  14. package/src/claude/agents/god-developer.md +10 -1
  15. package/src/claude/agents/inspector.md +1 -0
  16. package/src/claude/agents/spec-maker.md +1 -1
  17. package/src/claude/agents/test-runner.md +2 -2
  18. package/src/claude/gitignore +11 -4
  19. package/src/claude/hooks/__tests__/privacy-block.test.js +50 -10
  20. package/src/claude/hooks/__tests__/spec-gate.test.js +75 -1
  21. package/src/claude/hooks/__tests__/state.test.js +65 -0
  22. package/src/claude/hooks/docs-sync.cjs +15 -21
  23. package/src/claude/hooks/inspect-block.cjs +1 -1
  24. package/src/claude/hooks/lib/config.cjs +0 -5
  25. package/src/claude/hooks/privacy-block.cjs +39 -62
  26. package/src/claude/hooks/spec-gate.cjs +18 -7
  27. package/src/claude/hooks/spec-state.cjs +4 -0
  28. package/src/claude/hooks/state.cjs +13 -3
  29. package/src/claude/hooks/usage.cjs +6 -0
  30. package/src/claude/migration-manifest.json +1 -0
  31. package/src/claude/rules/orchestrator.md +2 -2
  32. package/src/claude/rules/skill-domain-routing.md +27 -86
  33. package/src/claude/rules/skill-workflow-routing.md +11 -74
  34. package/src/claude/rules/state-sync.md +1 -1
  35. package/src/claude/runtime.json +7 -7
  36. package/src/claude/scripts/validate-spec-output.cjs +6 -0
  37. package/src/claude/skills/code-review/references/spec-compliance-review.md +1 -1
  38. package/src/claude/skills/delegate/SKILL.md +124 -0
  39. package/src/claude/skills/delegate/references/codex-delegation.md +71 -0
  40. package/src/claude/skills/delegate/references/grok-delegation.md +84 -0
  41. package/src/claude/skills/develop/SKILL.md +26 -5
  42. package/src/claude/skills/develop/references/parallel-waves.md +112 -0
  43. package/src/claude/skills/develop/references/quality-gate.md +10 -2
  44. package/src/claude/skills/hotfix/references/parallel-patterns.md +1 -1
  45. package/src/claude/skills/inspect/SKILL.md +42 -113
  46. package/src/claude/skills/inspect/references/internal-inspection.md +16 -135
  47. package/src/claude/skills/specs/SKILL.md +134 -386
  48. package/src/claude/skills/specs/rules/tasks-generation.md +1 -1
  49. package/src/claude/skills/specs/templates/task.md +3 -1
  50. package/src/claude/skills/sync/SKILL.md +2 -2
  51. package/src/claude/skills/sync/references/sync-protocols.md +4 -4
  52. package/src/claude/skills/test/SKILL.md +1 -1
  53. package/src/claude/status.cjs +9 -6
  54. package/src/opencode/plugins/docs-sync.ts +10 -16
  55. package/src/claude/archive-command/code/SKILL.md +0 -55
  56. package/src/claude/archive-command/code/references/execution-loop.md +0 -21
  57. package/src/claude/archive-command/code.md +0 -17
  58. package/src/claude/archive-command/docs.md +0 -609
  59. package/src/claude/archive-command/review/codebase/parallel.md +0 -76
  60. package/src/claude/archive-command/spec-design.md +0 -247
  61. package/src/claude/archive-command/spec-init.md +0 -120
  62. package/src/claude/archive-command/spec-requirements.md +0 -138
  63. package/src/claude/archive-command/spec-status.md +0 -98
  64. package/src/claude/archive-command/spec-tasks.md +0 -173
  65. package/src/claude/archive-command/spec-validate.md +0 -118
  66. package/src/claude/archive-command/test.md +0 -8
@@ -84,11 +84,12 @@ try {
84
84
  const newlyDone = Object.keys(taskRegistry).filter((tp) =>
85
85
  (taskRegistry[tp]?.status || 'pending') === 'done' && featureCache[tp] !== 'done'
86
86
  );
87
- if (newlyDone.length === 0) process.exit(0);
88
-
89
87
  // /m so ^ matches line starts (Evidence is never at byte 0 of the file).
88
+ // legacy heading aliases: read-compat only, no longer advertised
90
89
  const EVID_RE = /^#{2,3}\s+(Evidence|Task Test Plan & Verification Evidence|Verification & Evidence)\b/m;
91
- const PROOF_RE = /(PASS|FAIL|exit code|passed|✓)/;
90
+ const PASS_MARKER_RE = /^\s*Verification:\s*PASS\s*$/m;
91
+ const LEGACY_SUCCESS_RE = /^\s*(?:PASS(?:ED)?|✓)(?:\s*:|$)|exit\s+code\s*[:=]?\s*0\b/im;
92
+ const EXPLICIT_FAILURE_RE = /\bFAIL(?:ED|URE|URES|ING)?\b|tests?\s+failed|exit\s+code\s*[:=]?\s*[1-9]\d*|\b0\s+tests?\b/i;
92
93
 
93
94
  /** Body of first Evidence heading until next same-or-higher heading. */
94
95
  function evidenceBody(text) {
@@ -122,12 +123,20 @@ try {
122
123
  const body = evidenceBody(text);
123
124
  if (body === null || !EVID_RE.test(text)) {
124
125
  fails.push('b');
125
- } else if (/\{\{[^}]+\}\}/.test(body) || !(/```/.test(body) || PROOF_RE.test(body))) {
126
+ } else if (
127
+ /\{\{[^}]+\}\}/.test(body) ||
128
+ EXPLICIT_FAILURE_RE.test(body) ||
129
+ !(PASS_MARKER_RE.test(body) || LEGACY_SUCCESS_RE.test(body))
130
+ ) {
126
131
  fails.push('c');
127
132
  }
128
133
 
129
134
  const at = taskRegistry[taskPath]?.completed_at;
130
- if (typeof at !== 'string' || at.trim() === '') fails.push('d');
135
+ if (
136
+ typeof at !== 'string' ||
137
+ !/^\d{4}-\d{2}-\d{2}T/.test(at) ||
138
+ Number.isNaN(Date.parse(at))
139
+ ) fails.push('d');
131
140
  return fails;
132
141
  }
133
142
 
@@ -135,7 +144,8 @@ try {
135
144
  .map((tp) => ({ taskPath: tp, fails: checkReceipt(tp) }))
136
145
  .filter((f) => f.fails.length > 0);
137
146
 
138
- // Leave failing newly-done at old cache status so the gate re-fires next Stop.
147
+ // Always persist status transitions, including done → pending. Leave failing
148
+ // newly-done tasks at their old status so the gate re-fires next Stop.
139
149
  try {
140
150
  const nextFeature = { ...featureCache, ...currentStatuses };
141
151
  for (const { taskPath } of failures) {
@@ -147,6 +157,7 @@ try {
147
157
  fs.writeFileSync(cacheFile, JSON.stringify(cache));
148
158
  } catch { /* fail-open */ }
149
159
 
160
+ if (newlyDone.length === 0) process.exit(0);
150
161
  if (failures.length === 0) process.exit(0);
151
162
 
152
163
  const lines = [
@@ -155,7 +166,7 @@ try {
155
166
  for (const { taskPath, fails } of failures) {
156
167
  lines.push(`- \`${taskPath}\`: failed check(s) ${fails.join(', ')}`);
157
168
  lines.push(
158
- ` Fix: add a verification receipt to \`## Evidence\` in \`specs/${featureName}/${taskPath}\`: commands run + outcomes, then re-sync spec.json`
169
+ ` Fix: add \`Verification: PASS\` plus commands and successful outcomes to \`## Evidence\` in \`specs/${featureName}/${taskPath}\`, then re-sync spec.json`
159
170
  );
160
171
  }
161
172
  process.stdout.write(JSON.stringify({ decision: 'block', reason: lines.slice(0, 8).join('\n') }) + '\n');
@@ -30,6 +30,10 @@ try {
30
30
  if (fs.existsSync(p)) runtime = JSON.parse(fs.readFileSync(p, 'utf8'));
31
31
  } catch { /* ignore */ }
32
32
 
33
+ // Reminder toggle — same key the OpenCode spec-state plugin honors.
34
+ // (The Stop completion gate has its own toggle: spec.completion_gate.)
35
+ if (runtime.spec && runtime.spec.tollgate === false) process.exit(0);
36
+
33
37
  const baseDir = process.env.PROJECT_ROOT || cwd;
34
38
  const specsPath = path.join(baseDir, runtime.paths?.specs || 'specs');
35
39
 
@@ -120,19 +120,29 @@ try {
120
120
  }
121
121
  }
122
122
 
123
+ const changed = [];
123
124
  try {
124
125
  const diff = execSync('git diff --name-only HEAD', {
125
126
  encoding: 'utf8',
126
127
  timeout: 3000,
127
128
  stdio: ['pipe', 'pipe', 'pipe']
128
129
  }).trim();
130
+ if (diff) changed.push(...diff.split('\n'));
131
+ } catch {
132
+ // A repository without HEAD can still report untracked files below.
133
+ }
129
134
 
130
- if (diff) {
131
- data.modifiedFiles = diff.split('\n').slice(0, MAX_MODIFIED_FILES_DISPLAY);
132
- }
135
+ try {
136
+ const untracked = execSync('git ls-files --others --exclude-standard', {
137
+ encoding: 'utf8',
138
+ timeout: 3000,
139
+ stdio: ['pipe', 'pipe', 'pipe']
140
+ }).trim();
141
+ if (untracked) changed.push(...untracked.split('\n'));
133
142
  } catch {
134
143
  // fail-open
135
144
  }
145
+ data.modifiedFiles = [...new Set(changed)].slice(0, MAX_MODIFIED_FILES_DISPLAY);
136
146
 
137
147
  return data;
138
148
  }
@@ -8,6 +8,12 @@
8
8
  * Fetches Claude Code usage limits from Anthropic OAuth API and writes to cache.
9
9
  * Cache is read by status.cjs for statusline display.
10
10
  *
11
+ * ⚠ EXPERIMENTAL / UNDOCUMENTED API: api.anthropic.com/api/oauth/usage with the
12
+ * "oauth-2025-04-20" beta header is not a public contract and may break or
13
+ * change shape without notice. Every failure path degrades to
14
+ * status:"unavailable" (statusline hides the segment) — never block on it.
15
+ * Disable entirely with "usage": { "enabled": false } if it misbehaves.
16
+ *
11
17
  * Features:
12
18
  * - Cross-platform credential retrieval (macOS Keychain, file-based)
13
19
  * - Throttled API calls: 1 min (prompt) / 5 min (tool use)
@@ -13,6 +13,7 @@
13
13
  "chrome-devtools",
14
14
  "code-review",
15
15
  "debug",
16
+ "delegate",
16
17
  "develop",
17
18
  "devops",
18
19
  "docs",
@@ -23,7 +23,7 @@ Example prompt:
23
23
  ## Resource Constraints
24
24
 
25
25
  - Each subagent has a **200K token context window** — scope tasks to fit comfortably within it
26
- - Spawning many parallel agents degrades system performance — check available CPU/memory before scaling out
26
+ - Spawning many parallel agents degrades system performance — check available CPU/memory before scaling out. For parallel implementation waves the cap is 3 concurrent agents by default, never more than 5 (each agent carries the 200K budget above)
27
27
  - Prefer fewer, well-scoped agents over many overlapping ones
28
28
  - Include system resource info (from hook injection) when delegating tasks so subagents can self-regulate
29
29
 
@@ -48,7 +48,7 @@ For implementation tasks, keep the chain explicit:
48
48
  2. Verify with `test-runner` using task files and exact evidence commands.
49
49
  3. Review with `code-auditor` using task files, design contracts, and the diff.
50
50
 
51
- Do not dispatch multiple implementation agents against the same files or same task. Parallelize only independent scopes with distinct file ownership.
51
+ Do not dispatch multiple implementation agents against the same files or same task **within the same working tree**. Parallelize only independent scopes with distinct file ownership — the sanctioned pattern for parallel implementation is **worktree isolation** (one agent per task, each in its own git worktree) with a **single writer per file per wave** and orchestrator-only spec-state writes, per `skills/develop/references/parallel-waves.md`.
52
52
 
53
53
  ### Parallel (independent tasks)
54
54
 
@@ -1,88 +1,29 @@
1
1
  # Skill Domain Routing
2
2
 
3
- Use this decision tree to choose domain skills from the installed CafeKit skill set. This is advisory routing, not an automatic hook.
4
-
5
- ## Frontend And UI
6
-
7
- ```text
8
- User wants to...
9
- ├── choose style, color, layout, UX, design system -> /hapo:frontend-design
10
- ├── build React/TypeScript UI components -> /hapo:frontend-development
11
- ├── optimize React/Next.js performance or rerenders -> /hapo:react-best-practices
12
- ├── apply deep UI/UX intelligence, visual polish -> /hapo:ui-ux-pro-max
13
- └── test UI in browser -> /hapo:web-testing or /hapo:agent-browser
14
- ```
15
-
16
- Use `/hapo:react-best-practices` for performance/re-render patterns. Use `/hapo:frontend-development` for normal implementation.
17
-
18
- ## Backend, Data, And Infrastructure
19
-
20
- ```text
21
- User wants to...
22
- ├── API, service, auth, database-backed feature -> /hapo:backend-development
23
- ├── deployment, Docker, Kubernetes, Cloudflare, CI/CD -> /hapo:devops
24
- └── mobile apps, iOS, Android, React Native, Flutter -> /hapo:mobile-development
25
- ```
26
-
27
- ## Codebase Understanding
28
-
29
- ```text
30
- User wants to...
31
- ├── answer questions from source code/docs/specs/config -> /hapo:question
32
- ├── find files, locate code, scan project structure -> /hapo:inspect
33
- ├── diagnose an error or failing check -> /hapo:debug
34
- ├── understand possible side effects -> /hapo:inspect
35
- └── compare external approaches or best practices -> /hapo:research
36
- ```
37
-
38
- Local source truth comes from `/hapo:inspect`; external/current knowledge comes from `/hapo:research`.
39
-
40
- ## Documentation
41
-
42
- ```text
43
- User wants to...
44
- ├── ask/answer documentation questions from source -> /hapo:question
45
- ├── create missing project docs -> /hapo:docs --init
46
- ├── update docs after source changes -> /hapo:docs --update
47
- ├── summarize codebase quickly -> /hapo:docs --summarize
48
- ├── reconstruct as-is docs from legacy source code -> /hapo:docs --reconstruct <scope>
49
- └── create a future feature spec -> /hapo:specs
50
- ```
51
-
52
- Keep as-is reconstruction separate from future requirements. Reconstructed docs document current behavior; specs define requested changes.
53
-
54
- ## Testing And Browser
55
-
56
- ```text
57
- User wants to...
58
- ├── run test suites, coverage, scoped verification -> /hapo:test
59
- ├── E2E/unit/integration/load/security/a11y strategy -> /hapo:web-testing
60
- ├── drive a browser with snapshots or Browserbase -> /hapo:agent-browser
61
- └── Chrome DevTools/Puppeteer evidence -> /hapo:chrome-devtools
62
- ```
63
-
64
- ## Documents And Media
65
-
66
- ```text
67
- User wants to...
68
- ├── PowerPoint/slides -> /hapo:pptx
69
- ├── Word documents -> /hapo:docx
70
- ├── PDFs -> /hapo:pdf
71
- ├── spreadsheets/CSV/XLSX -> /hapo:xlsx
72
- └── image/audio/video/document multimodal analysis -> /hapo:ai-multimodal
73
- ```
74
-
75
- ## Git And Release
76
-
77
- ```text
78
- User wants to...
79
- ├── commit, branch, tag, push, release prep -> /hapo:git
80
- └── review before release -> /hapo:code-review
81
- ```
82
-
83
- ## Usage Notes
84
-
85
- - Read the selected skill's `SKILL.md` before acting.
86
- - Do not activate a skill only because one keyword appears. Use the whole user intent.
87
- - If a task spans multiple domains, name the primary skill and mention the secondary skill in the plan.
88
- - If no domain skill fits, use the core CafeKit workflow in `skill-workflow-routing.md`.
3
+ Advisory routing for installed domain skills (not an automatic hook). Read the selected skill's `SKILL.md` before acting.
4
+
5
+ | Domain / intent | Skill |
6
+ |---|---|
7
+ | answer questions from source code/docs/specs/config | `/hapo:question` |
8
+ | file discovery, structure, blast radius | `/hapo:inspect` |
9
+ | style / layout / design system | `/hapo:frontend-design` |
10
+ | React/TypeScript UI implementation | `/hapo:frontend-development` |
11
+ | React/Next performance / re-renders | `/hapo:react-best-practices` |
12
+ | deep UI/UX polish | `/hapo:ui-ux-pro-max` |
13
+ | API, service, auth, database | `/hapo:backend-development` |
14
+ | deploy / Docker / K8s / Cloudflare / CI | `/hapo:devops` |
15
+ | mobile (RN / Flutter / iOS / Android) | `/hapo:mobile-development` |
16
+ | docs init / update / summarize | `/hapo:docs --init` / `--update` / `--summarize` |
17
+ | as-is reconstruction from legacy code | `/hapo:docs --reconstruct <scope>` |
18
+ | future feature requirements | `/hapo:specs` |
19
+ | run suites / scoped verification | `/hapo:test` |
20
+ | E2E / load / a11y strategy | `/hapo:web-testing` |
21
+ | browser snapshots / Browserbase | `/hapo:agent-browser` |
22
+ | Chrome DevTools evidence | `/hapo:chrome-devtools` |
23
+ | diagnose error / CI failure | `/hapo:debug` |
24
+ | external best practices / tool compare | `/hapo:research` |
25
+ | pptx / docx / pdf / xlsx / multimodal | `/hapo:pptx` / `docx` / `pdf` / `xlsx` / `ai-multimodal` |
26
+ | commit / branch / release prep | `/hapo:git` |
27
+ | review before release | `/hapo:code-review` |
28
+
29
+ Pick one primary domain skill; name a secondary only when it changes execution. If none fit, use `skill-workflow-routing.md`.
@@ -4,84 +4,21 @@ Use this rule instead of automatic prompt routing. Read the user's intent, choos
4
4
 
5
5
  Do not inject or force a skill when the user explicitly asks for a direct answer, a specific command, or a different workflow.
6
6
 
7
- ## Core Specification Workflow
7
+ Claude Code selects skills from frontmatter descriptions; trust it for clear intents.
8
8
 
9
- ```text
10
- /hapo:question -> /hapo:brainstorm -> /hapo:specs -> /hapo:develop -> /hapo:test -> /hapo:code-review -> /hapo:git
11
- ```
12
-
13
- | User intent | Suggested start |
14
- |---|---|
15
- | ask about source code, docs, specs, config, dependencies, or external/current technical facts | `/hapo:question` |
16
- | vague request, missing acceptance criteria, unclear scope, stakeholder questions | ask one clarification or use `/hapo:brainstorm` |
17
- | unclear idea, possible approaches, scope tradeoffs | `/hapo:brainstorm` |
18
- | create requirements, design, task breakdown, validate spec | `/hapo:specs` |
19
- | implement an approved spec or a specific task file | `/hapo:develop` |
20
- | run tests, QA, runtime verification | `/hapo:test` |
21
- | review code quality, security, regressions, maintainability | `/hapo:code-review` |
22
- | commit, tag, push, branch, release prep | `/hapo:git` |
23
-
24
- ## Bug And Incident Workflow
25
-
26
- ```text
27
- /hapo:debug -> /hapo:hotfix -> /hapo:test -> /hapo:code-review
28
- ```
29
-
30
- | User intent | Suggested start |
31
- |---|---|
32
- | diagnose why something fails, find root cause, inspect CI/logs | `/hapo:debug` |
33
- | fix a known bug after diagnosis, urgent regression, production issue | `/hapo:hotfix` |
34
- | verify the fix and affected behavior | `/hapo:test` |
35
- | check side effects before closeout | `/hapo:code-review` |
36
-
37
- `/hapo:debug` is diagnostic-only. Do not edit product code there. Use `/hapo:hotfix` when the user asks to fix.
38
-
39
- ## Existing System Documentation Workflow
9
+ ## Core chain
40
10
 
41
11
  ```text
42
- /hapo:inspect -> /hapo:docs --reconstruct -> human review -> /hapo:specs -> /hapo:develop
43
- ```
44
-
45
- | User intent | Suggested start |
46
- |---|---|
47
- | understand source structure or locate implementation areas | `/hapo:inspect` |
48
- | rebuild as-is docs/requirements from a legacy codebase | `/hapo:docs --reconstruct <scope>` |
49
- | update normal project docs | `/hapo:docs --update` |
50
- | initialize missing docs | `/hapo:docs --init` |
51
- | summarize a codebase without full docs work | `/hapo:docs --summarize` |
52
-
53
- Do not turn reconstructed docs directly into implementation. Human review must approve the as-is docs before `/hapo:specs` defines future changes.
54
-
55
- ## Research And Analysis Workflow
56
-
57
- ```text
58
- /hapo:inspect -> /hapo:research
12
+ /hapo:question -> /hapo:brainstorm -> /hapo:specs -> /hapo:develop -> /hapo:test -> /hapo:code-review -> /hapo:git
59
13
  ```
60
14
 
61
- | User intent | Suggested start |
62
- |---|---|
63
- | file discovery, codebase structure, source scouting | `/hapo:inspect` |
64
- | affected files, blast radius, dependency impact, side effects | `/hapo:inspect` |
65
- | external best practices, tool comparison, technical investigation | `/hapo:research` |
66
-
67
- Use `/hapo:research` for external knowledge. Use `/hapo:inspect` for local source truth.
68
-
69
- ## Output Artifact Workflow
70
-
71
- | User intent | Suggested skill |
72
- |---|---|
73
- | PowerPoint or slide deck creation/editing | `/hapo:pptx` |
74
- | Word documents | `/hapo:docx` |
75
- | PDF processing | `/hapo:pdf` |
76
- | spreadsheets | `/hapo:xlsx` |
77
- | screenshots, images, audio, video, OCR, multimodal understanding | `/hapo:ai-multimodal` |
15
+ Bug path: `/hapo:debug -> /hapo:hotfix` then test/review. As-is docs: `/hapo:inspect` → `/hapo:docs --reconstruct <scope>` → human review → specs → develop. Delegate implementation to an external agent CLI: `/hapo:delegate`.
78
16
 
79
- ## Selection Rules
17
+ ## Ambiguous cases
80
18
 
81
- - Pick one primary workflow first.
82
- - Add a secondary skill only when it materially changes execution.
83
- - Prefer explicit user commands over this table.
84
- - If two workflows conflict, ask one concise clarification.
85
- - If the user asks a factual or project question before workflow selection, use `/hapo:question`.
86
- - If missing information blocks workflow selection, ask one concise clarification or use `/hapo:brainstorm`.
87
- - If the user asks to "fix" and root cause is unknown, start with `/hapo:debug` unless the issue is trivial and local.
19
+ | Ambiguity | Prefer | Not when |
20
+ |---|---|---|
21
+ | debug-vs-hotfix | `/hapo:debug` first when root cause unknown | Root cause is known / trivial local fix → `/hapo:hotfix` |
22
+ | question-vs-research | `/hapo:question` to ask about source code, docs, specs, config, dependencies, or project facts | External best-practice comparison / multi-source investigation → `/hapo:research` |
23
+ | question-vs-brainstorm | `/hapo:question` for factual answers with evidence | Vague idea, missing acceptance criteria, unclear scope, multi-approach tradeoffs → `/hapo:brainstorm` |
24
+ | specs-vs-brainstorm | `/hapo:specs` when intent and acceptance are concrete enough | Unclear idea / architecture choices still open → `/hapo:brainstorm` first |
@@ -28,4 +28,4 @@ Before returning control to the user or orchestrator, the agent **MUST**:
28
28
 
29
29
  ### Completion gate (Stop)
30
30
 
31
- Marking a task `done` is now machine-gated on the **Stop** hook (`spec-gate.cjs`), not only reminded on each prompt. When a turn ends with *newly-done* tasks, the gate requires a verification receipt in each task markdown: `Status: done`, an Evidence section (or legacy `Task Test Plan & Verification Evidence` / `Verification & Evidence`) with real proof (no `{{...}}` placeholders; at least one fenced command block or PASS/FAIL line), and a non-empty `task_registry[path].completed_at`. First adoption (no cache yet) seeds history without blocking. Escape hatch for humans: `"spec": { "completion_gate": false }` in `.claude/runtime.json` (missing key keeps the gate ON).
31
+ Marking a task `done` is now machine-gated on the **Stop** hook (`spec-gate.cjs`), not only reminded on each prompt. When a turn ends with *newly-done* tasks, the gate requires a verification receipt in each task markdown: `Status: done`, `## Evidence` (legacy heading aliases still parse) with real proof (no `{{...}}` placeholders; at least one fenced command block or PASS/FAIL line), and a non-empty `task_registry[path].completed_at`. First adoption (no cache yet) seeds history without blocking. Escape hatch for humans: `"spec": { "completion_gate": false }` in `.claude/runtime.json` (missing key keeps the gate ON).
@@ -13,21 +13,21 @@
13
13
  },
14
14
  "paths": {
15
15
  "docs": "docs",
16
- "specs": "specs"
16
+ "specs": "specs",
17
+ "plans": "plans"
17
18
  },
18
19
  "spec": {
19
20
  "scaffold_guard": true,
20
- "completion_gate": true
21
+ "completion_gate": true,
22
+ "tollgate": true
23
+ },
24
+ "develop": {
25
+ "parallel": true
21
26
  },
22
27
  "locale": {
23
28
  "thinkingLanguage": null,
24
29
  "responseLanguage": null
25
30
  },
26
- "skills": {
27
- "research": {
28
- "useGemini": true
29
- }
30
- },
31
31
  "usage": {
32
32
  "enabled": true
33
33
  },
@@ -113,6 +113,7 @@ function validateTaskSections(taskPath, content, errors) {
113
113
  hasHeading(content, 'Requirements') || /_Requirements:\s*[^_\n]+_/i.test(content);
114
114
  const hasRelatedFiles = hasHeading(content, 'Related Files');
115
115
  const hasCompletionCriteria = hasHeading(content, 'Completion Criteria');
116
+ // legacy heading aliases: read-compat only, no longer advertised
116
117
  const hasEvidence =
117
118
  hasHeading(content, 'Evidence') ||
118
119
  hasHeading(content, 'Task Test Plan & Verification Evidence') ||
@@ -365,6 +366,11 @@ function validateSpec(specDir) {
365
366
  const contractDefs = fs.existsSync(designPath)
366
367
  ? extractContractDefs(fs.readFileSync(designPath, 'utf8'))
367
368
  : new Map();
369
+ if (taskFiles.length >= 5 && contractDefs.size === 0) {
370
+ warnings.push(
371
+ 'design.md declares no contract blocks; specs spanning BE/FE must declare shared shapes (<!-- contract:NAME -->)',
372
+ );
373
+ }
368
374
  for (const taskFile of taskFiles) {
369
375
  const fullPath = path.join(specDir, taskFile);
370
376
  const content = fs.readFileSync(fullPath, 'utf8');
@@ -24,7 +24,7 @@ Do not attempt a standard text-based review if the project includes Visual Specs
24
24
  3. If NO (Markdown Spec only): Read the spec directly and extract:
25
25
  - requirement bullets
26
26
  - task `Completion Criteria`
27
- - task `Evidence` (or `Task Test Plan & Verification Evidence` / legacy `Verification & Evidence`)
27
+ - task `## Evidence` (legacy heading aliases still parse)
28
28
  - canonical contracts/invariants from `design.md`
29
29
  Then verify the changed files against those concrete obligations.
30
30
 
@@ -0,0 +1,124 @@
1
+ ---
2
+ name: hapo:delegate
3
+ description: "Delegate implementation tasks from Claude Code to external CLI agents (Codex or Grok). Covers task-brief authoring, non-interactive dispatch, permission setup, background monitoring, resume, and independent verification of the returned work."
4
+ user-invocable: true
5
+ when_to_use: "Invoke when the user asks to assign/offload a coding task to codex or grok, or to run work on an external agent CLI."
6
+ category: orchestration
7
+ keywords: [delegate, codex, grok, external-agent, offload, assign]
8
+ argument-hint: "<codex|grok> <task-description | path/to/task-brief.md>"
9
+ metadata:
10
+ author: haposoft
11
+ version: "1.0.0"
12
+ ---
13
+ # Delegate to External Agents (Codex / Grok)
14
+
15
+ Dispatch a well-scoped implementation task to an external agentic CLI — **Codex** (OpenAI) or **Grok** (xAI Grok Build) — from a Claude Code session acting as orchestrator. Claude Code stays responsible for: writing the task brief, choosing safe permissions, monitoring, and **independently verifying** the result before reporting completion.
16
+
17
+ **Mantra:** Brief precisely, sandbox tightly, verify independently.
18
+
19
+ ## When to Use
20
+
21
+ - User explicitly asks to hand a task to codex/grok ("giao cho codex", "assign to grok").
22
+ - Parallel workstreams: Claude Code keeps orchestrating while an external agent implements a scoped task.
23
+ - Cross-checking: a second model implements or reviews independently.
24
+
25
+ Do NOT delegate: tasks touching secrets/`.env`, deploys to shared environments, destructive migrations on live data, or tasks whose scope is still unclear (clarify first — a vague brief wastes an entire agent run).
26
+
27
+ ## Workflow
28
+
29
+ ### 1. Write the task brief (mandatory, file-based)
30
+
31
+ External agents run **fresh-context** — they see none of your conversation. Write the brief to a file (convention: `plans/<slug>-task.md` in the target repo), never inline-only. Follow the orchestrator prompt rules (`.claude/rules/orchestrator.md`): the brief must be self-contained.
32
+
33
+ Required sections:
34
+
35
+ ```markdown
36
+ # Task: <title>
37
+
38
+ > Self-contained brief for a fresh-context agent. Date: <YYYY-MM-DD>.
39
+ > FOUNDATION: <state of the working tree the agent builds on — branch,
40
+ > uncommitted changes it must NOT revert, verified test/build status>
41
+
42
+ ## Context — project, architecture, why this task exists
43
+ ## Scope — numbered work items with exact file paths
44
+ ## Constraints — what must NOT be touched (staging data, .env, deploys,
45
+ unrelated refactors); repo rules to obey (CLAUDE.md)
46
+ ## Completion Criteria — verifiable, numbered
47
+ ## Evidence required — exact commands whose output proves completion
48
+ ```
49
+
50
+ Rules of thumb:
51
+ - Name exact files and line-level anchors where known; agents burn tokens rediscovering what you already know.
52
+ - State dependency order explicitly if this task builds on another agent's uncommitted work ("do NOT revert/stash existing changes").
53
+ - Put user-pending decisions in Constraints as forbidden actions (e.g. "do NOT touch staging rows until user confirms").
54
+
55
+ ### 2. Protect the working tree
56
+
57
+ Before dispatch, snapshot state you cannot afford to lose:
58
+
59
+ ```bash
60
+ git stash push -u -m "backup: <reason>" && git stash apply -q # snapshot, keep tree intact
61
+ ```
62
+
63
+ Prefer isolation when the task is risky or parallel to other edits:
64
+ - Grok: `--worktree=<name>` (built-in).
65
+ - Codex: run with `-C <worktree-dir>` after creating a git worktree yourself.
66
+
67
+ If the agent must build on uncommitted changes, isolation is not possible — use the stash-backup pattern above and say so in the brief.
68
+
69
+ ### 3. Dispatch
70
+
71
+ Load the matching reference for exact flags, permission model, and pitfalls:
72
+ - **Codex:** `./references/codex-delegation.md`
73
+ - **Grok:** `./references/grok-delegation.md`
74
+
75
+ Common principles:
76
+ - Run non-interactive/headless mode in a **background** shell; both CLIs stream progress to stdout.
77
+ - Grant the **minimum** permission set that lets the agent write code and run its Evidence commands (npm/node). Never grant full-access/bypass modes for routine tasks.
78
+ - Model/effort overrides: pass explicitly rather than relying on user config, so the run is reproducible.
79
+ - Capture the output file path; check progress after ~20–30s to confirm the agent actually started (auth errors, bad flags, and permission blocks surface early).
80
+
81
+ ### 4. Monitor
82
+
83
+ - Poll the background output periodically; look for permission-block messages — both CLIs degrade to "design-only" output instead of failing loudly when a write tool is blocked.
84
+ - If blocked on permissions: **resume the same session** with corrected flags (both CLIs support resume; see references) — context is preserved, work continues instead of restarting.
85
+ - Apply the 3-strike rule from `.claude/rules/orchestrator.md`: same failure 3+ times → stop, escalate to user with evidence.
86
+
87
+ ### 5. Verify independently (non-negotiable)
88
+
89
+ External-agent claims are **not** evidence (CLAUDE.md: no completion claim without fresh proof from the current run). After the agent reports done:
90
+
91
+ 1. `git status` / `git diff` — confirm the changed file set matches the brief's Scope; flag out-of-scope edits.
92
+ 2. Run the brief's Evidence commands yourself (tests, build). The agent's transcript of a test run does not count.
93
+ 3. Check Completion Criteria one by one.
94
+ 4. Report to user: what was delegated, what came back, verification results, and any deviations.
95
+
96
+ ### 6. Sync
97
+
98
+ - Keep the brief file updated (checklist ticks / blockers) so it doubles as task state.
99
+ - If a spec (`specs/<slug>/`) governs the work, follow the Tollgate Protocol (`.claude/rules/state-sync.md`): update `spec.json` + task files only after verification passes.
100
+ - The user decides commit/merge/deploy — delegation ends at verified working-tree changes unless told otherwise.
101
+
102
+ ## Choosing Codex vs Grok
103
+
104
+ Both are capable general coding agents; prefer the one the user names. If unspecified:
105
+
106
+ | Factor | Codex | Grok |
107
+ |---|---|---|
108
+ | Isolation | manual git worktree + `-C` | built-in `--worktree=<name>` |
109
+ | Structured output | `--output-schema` (JSON Schema) | `--json-schema` |
110
+ | Self-verification | ask in the brief | `--check` flag appends a verify loop |
111
+ | Resume | `codex exec resume <id>` | `grok --resume <id>` |
112
+
113
+ ## Rules
114
+
115
+ - Never grant `--dangerously-bypass-approvals-and-sandbox` (codex) or `bypassPermissions` (grok) for routine delegation.
116
+ - Never let an external agent touch `.env`, secrets, staging/production data, or run deploys.
117
+ - Never report the agent's own success claim as completion — verify first.
118
+ - Never re-dispatch a blocked task unchanged (BLOCKED ≠ retry; fix the cause: permissions, context, or scope).
119
+ - One writer per file set: don't run two agents (or an agent + yourself) editing the same files concurrently.
120
+
121
+ ## References
122
+
123
+ - `./references/codex-delegation.md` — Codex CLI: exec mode, sandbox/approval model, resume, pitfalls
124
+ - `./references/grok-delegation.md` — Grok CLI: headless mode, worktree, permission rules, resume, pitfalls
@@ -0,0 +1,71 @@
1
+ # Delegating to Codex CLI
2
+
3
+ Verified against codex-cli 0.144.4 (2026-07). Re-check `codex exec --help` if flags fail — the CLI evolves quickly.
4
+
5
+ ## Preflight
6
+
7
+ ```bash
8
+ which codex && codex --version # installed?
9
+ codex doctor # auth + runtime health (slow; run only when suspicious)
10
+ ```
11
+
12
+ User-level defaults live in `~/.codex/config.toml` (`model`, `model_reasoning_effort`, agents, MCP servers). Overrides via `-m` and `-c key=value` beat config — pass them explicitly for reproducible runs.
13
+
14
+ ## Non-interactive dispatch: `codex exec`
15
+
16
+ Reads the prompt from an argument, or from **stdin** when the argument is `-`. Prefer stdin + brief file:
17
+
18
+ ```bash
19
+ codex exec \
20
+ -m gpt-5.6-terra \
21
+ -c model_reasoning_effort='"max"' \
22
+ --sandbox workspace-write \
23
+ -o /tmp/codex-last-message.txt \
24
+ - < plans/<slug>-task.md
25
+ ```
26
+
27
+ Run it in a background shell and poll the output.
28
+
29
+ ### Key flags
30
+
31
+ | Flag | Notes |
32
+ |---|---|
33
+ | `-m <model>` | model ID, e.g. `gpt-5.6-terra` (note spelling: *terra*) |
34
+ | `-c model_reasoning_effort='"max"'` | TOML-parsed value — keep the inner quotes |
35
+ | `--sandbox <mode>` | `read-only` \| `workspace-write` \| `danger-full-access` |
36
+ | `-o <file>` | write the agent's final message to a file — easiest completion check |
37
+ | `-C <dir>` | working root (use for delegating into a git worktree) |
38
+ | `--add-dir <dir>` | extra writable dirs alongside the workspace |
39
+ | `--output-schema <file>` | JSON Schema constraining the final response |
40
+ | `--json` | JSONL event stream on stdout (machine parsing) |
41
+ | `--ephemeral` | don't persist session files |
42
+
43
+ ### Pitfalls
44
+
45
+ - **`-a` / `--ask-for-approval` is TUI-only.** `codex exec` rejects it (`error: unexpected argument '-a' found`). Exec mode is implicitly `approval: never` — sandbox mode is your only control there.
46
+ - **`workspace-write` limits writes, not reads**, to: workdir, `/tmp`, `$TMPDIR`. Network is available. Commands needing writes outside (global installs) will fail — keep Evidence commands repo-local.
47
+ - **Effort value is TOML**: `-c model_reasoning_effort='"max"'` (double-quoted inside single quotes). Bare `max` may parse as a literal string too, but the quoted form is unambiguous.
48
+ - Startup banner echoes `model:`, `reasoning effort:`, `sandbox:` — **verify these lines** ~20s after dispatch instead of assuming flags took effect.
49
+ - User config may define agents/hooks/MCP servers that activate automatically; `--ignore-user-config` gives a clean run if they interfere.
50
+
51
+ ## Monitor & verify liveness
52
+
53
+ ```bash
54
+ # ~20-30s after dispatch: banner shows model/sandbox; then agent narration follows
55
+ head -c 1200 <output-file>
56
+ tail -c 1500 <output-file> # progress
57
+ cat /tmp/codex-last-message.txt # exists → run finished; content = final report
58
+ ```
59
+
60
+ ## Resume
61
+
62
+ ```bash
63
+ codex exec resume --last "<follow-up>" # most recent session
64
+ codex exec resume <SESSION_ID> "<follow-up>" # by id (session id printed in banner)
65
+ ```
66
+
67
+ Use resume (not a fresh dispatch) when: permission-blocked mid-run, follow-up fixes after your verification failed, or continuing a design into implementation.
68
+
69
+ ## Review mode
70
+
71
+ `codex review` (or `codex exec review`) runs a non-interactive code review of the current repo — useful as an independent second-opinion pass on another agent's diff.