cclaw-cli 0.6.0 → 0.7.1

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.
@@ -89,14 +89,44 @@ These skills live in \`.cclaw/skills/\` but have no slash commands. They activat
89
89
 
90
90
  **Activation rule:** When a contextual skill applies, read its SKILL.md and follow it as a supplementary lens alongside the current stage. Do not skip the stage workflow — the contextual skill adds depth, not a detour.
91
91
 
92
+ ### Opt-in language rule packs
93
+
94
+ cclaw stays language-agnostic by default. Projects that want language-specific
95
+ review lenses can enable opt-in rule packs in \`.cclaw/config.yaml\`:
96
+
97
+ \`\`\`yaml
98
+ languageRulePacks:
99
+ - typescript # → .cclaw/rules/lang/typescript.md
100
+ - python # → .cclaw/rules/lang/python.md
101
+ - go # → .cclaw/rules/lang/go.md
102
+ \`\`\`
103
+
104
+ After editing the list, run \`cclaw sync\` to materialize the enabled packs
105
+ under \`.cclaw/rules/lang/\` (one \`<language>.md\` file per pack, each with
106
+ YAML frontmatter declaring \`stages\` and \`triggers\`). Packs activate during
107
+ \`tdd\` and \`review\` when the diff touches files in their language. They are
108
+ additive lenses — Tier-1 rules block merge, Tier-2 rules require a named
109
+ follow-up. Never silently override them.
110
+
111
+ \`cclaw sync\` and \`cclaw doctor\` also refuse the legacy v0.7.0 location
112
+ \`.cclaw/skills/language-*/\` — if a project still has those folders,
113
+ \`sync\` removes them on the next run and \`doctor\` surfaces the drift until
114
+ they are gone.
115
+
92
116
  ## Custom Skills (project-owned, sync-safe)
93
117
 
94
118
  \`.cclaw/custom-skills/\` is a sync-safe directory. \`cclaw sync\` and \`cclaw upgrade\` **never overwrite** files there.
95
119
 
96
120
  Use it to add **project-specific** skills that complement the managed library:
97
121
 
98
- - Each skill: \`.cclaw/custom-skills/<folder>/SKILL.md\` with the same frontmatter format as managed skills (\`name\` + \`description\` triggering routing).
99
- - Activate by mentioning the skill name explicitly, or rely on semantic routing from the description.
122
+ - Each skill: \`.cclaw/custom-skills/<folder>/SKILL.md\` following the public-API frontmatter schema documented in \`.cclaw/custom-skills/README.md\`.
123
+ - The frontmatter public API is stable across cclaw releases: \`name\`, \`description\` (required), plus optional \`stages\`, \`triggers\`, \`hardGate\`, \`owners\`, \`version\`.
124
+ - Routing precedence when loading a stage:
125
+ 1. Active stage skill under \`.cclaw/skills/<stage>/\`.
126
+ 2. Managed utility skills whose trigger matches (\`landscape-check\`, \`security-audit\`, \`adversarial-review\`, etc.).
127
+ 3. **Custom skills** whose \`stages\` array includes the active stage (or is missing) AND whose \`description\` / \`triggers\` match the prompt.
128
+ - Custom skills are **never mandatory delegations** — they are opt-in lenses. If you need a mandatory dispatch, promote the skill upstream or add a managed specialist instead.
129
+ - Activate by mentioning the skill name explicitly, or rely on semantic routing from the description + triggers.
100
130
  - See \`.cclaw/custom-skills/README.md\` for the full convention and a starter template under \`.cclaw/custom-skills/example/\`.
101
131
 
102
132
  If a custom skill turns out to generalize (e.g. another project would want the same lens), promote it to a managed skill via a contribution to the cclaw repo — managed skills get versioning and maintenance.
@@ -129,13 +159,27 @@ When a stage requires user input (approval, choice, direction), use this structu
129
159
  2. **Present options** as labeled choices (A, B, C...) with:
130
160
  - One-line description of each option
131
161
  - Trade-off or consequence
162
+ - **\`Completeness: X/10\`** — how thoroughly does this option cover the dimensions the stage cares about (failure modes, data flow, blast radius, observability, rollback, etc. — pick the dimensions that matter for *this* decision and subtract for each gap). Force a numeric score; vague text scores ≤ 5.
132
163
  - Mark one as **(recommended)** with brief why
133
- 3. **Use the harness ask-user tool** when available:
164
+ 3. **Pick the highest-scoring option as the recommendation.** If scores tie, prefer the option with the smallest blast radius (review/ship), the lowest risk (design/spec), or the most reversible outcome (ship finalization).
165
+ 4. **Use the harness ask-user tool** when available:
134
166
  - Claude Code: \`AskUserQuestion\` tool
135
167
  - Cursor: \`AskQuestion\` tool with options array
136
168
  - Codex/OpenCode: numbered list in message (no native ask tool)
137
- 4. **Wait for response.** Do not proceed until the user picks.
138
- 5. **Commit to the choice.** Once decided, do not re-argue.
169
+ 5. **Wait for response.** Do not proceed until the user picks.
170
+ 6. **Commit to the choice.** Once decided, do not re-argue.
171
+
172
+ ### Completeness scoring rubric (apply per option)
173
+
174
+ | Score | Meaning |
175
+ |---|---|
176
+ | 9-10 | Closes the decision with no carry-over risk; covers every dimension stage cares about. |
177
+ | 7-8 | Closes the decision with a small named follow-up; one dimension partially covered. |
178
+ | 5-6 | Plausible but leaves at least one dimension visibly open; needs follow-up before next stage. |
179
+ | 3-4 | Workaround, not a solution; defers the real problem. |
180
+ | 0-2 | Wishful thinking; do not recommend. |
181
+
182
+ Always show the score next to the option label, e.g. \`(B) [Completeness: 8/10]\`.
139
183
 
140
184
  ### When to use structured asks vs conversational
141
185
  - **Structured (tool):** Architecture choices, scope decisions, approval gates, mode selection, scope boundary issues
@@ -152,10 +196,12 @@ Watch for these anti-patterns:
152
196
 
153
197
  ## Knowledge Integration
154
198
 
155
- At session start and stage transitions, check \`.cclaw/knowledge.md\` for project-specific knowledge:
156
- - Review recent entries and apply relevant rules/patterns to the current task
157
- - If you discover a non-obvious reusable rule or pattern, append a new entry with type \`rule\`, \`pattern\`, or \`lesson\`
199
+ At session start and stage transitions, stream \`.cclaw/knowledge.jsonl\` (the canonical strict-JSONL knowledge store) and apply relevant entries:
200
+ - Each line is one JSON object with fields \`type, trigger, action, confidence, domain, stage, created, project\`.
201
+ - Review recent entries and apply relevant rules/patterns to the current task.
202
+ - If you discover a non-obvious reusable rule or pattern, append one new JSON line via \`/cc-learn add\` with type \`rule\`, \`pattern\`, \`lesson\`, or \`compound\`.
158
203
 
159
- Knowledge capture is append-only and should preserve historical context rather than rewriting prior entries.
204
+ Knowledge capture is append-only and strict-schema. Never rewrite or delete
205
+ historical entries; corrections are new lines whose \`trigger\` supersedes the earlier one.
160
206
  `;
161
207
  }
@@ -26,7 +26,7 @@ These are prompt-discipline guidelines that complement the real hooks cclaw gene
26
26
  When a new session begins in any harness:
27
27
 
28
28
  1. **Read flow state:** Load \`.cclaw/state/flow-state.json\` to find the current stage and completed stages.
29
- 2. **Load knowledge:** Review recent entries from \`.cclaw/knowledge.md\` and surface the most relevant rules/patterns.
29
+ 2. **Load knowledge:** Stream the tail of \`.cclaw/knowledge.jsonl\` (strict JSONL store) and surface the most relevant rules/patterns.
30
30
  3. **Check for in-progress work:** If the last stage is incomplete, remind the user and offer to resume.
31
31
  4. **Load suggestion memory:** Read \`.cclaw/state/suggestion-memory.json\` and honor \`enabled=false\` opt-out.
32
32
  5. **Read AGENTS.md:** The cclaw block contains routing and rules — follow them.
@@ -45,7 +45,7 @@ Before ending a session or when context is full:
45
45
 
46
46
  1. **Verify no pending changes:** All modified files must be either committed or explicitly reverted.
47
47
  2. **Update flow state:** Mark the current stage as its actual status (DONE / DONE_WITH_CONCERNS / BLOCKED).
48
- 3. **Write knowledge:** If any non-obvious reusable insight appears, append to \`.cclaw/knowledge.md\` with type \`rule\`, \`pattern\`, or \`lesson\`.
48
+ 3. **Write knowledge:** If any non-obvious reusable insight appears, append one strict-schema JSON line to \`.cclaw/knowledge.jsonl\` with type \`rule\`, \`pattern\`, \`lesson\`, or \`compound\`.
49
49
  4. **Create checkpoint:** Write a brief status note to the current artifact or as a comment in flow-state.json.
50
50
 
51
51
  ### Stop conditions (agent must halt and report)
@@ -81,7 +81,7 @@ Before starting stage execution:
81
81
  2. Resolve active artifact root: \`.cclaw/artifacts/\`.
82
82
  3. Load upstream artifacts required by this stage:
83
83
  ${readLines}
84
- 4. Read \`.cclaw/knowledge.md\` and apply relevant entries before making decisions.
84
+ 4. Stream \`.cclaw/knowledge.jsonl\` (strict-JSONL knowledge store) and apply relevant entries before making decisions.
85
85
  `;
86
86
  }
87
87
  function whenNotToUseBlock(stage) {
@@ -236,7 +236,7 @@ function progressiveDisclosureBlock(stage) {
236
236
  - Primary stage procedure (this file): \`.cclaw/skills/${schema.skillFolder}/SKILL.md\`
237
237
  - Orchestrator contract (gate language and handoff): \`.cclaw/commands/${stage}.md\`
238
238
  - Artifact structure baseline: \`.cclaw/templates/${schema.artifactFile}\`
239
- - Runtime state truth source: \`.cclaw/state/flow-state.json\` + \`.cclaw/artifacts/\` + \`.cclaw/knowledge.md\`
239
+ - Runtime state truth source: \`.cclaw/state/flow-state.json\` + \`.cclaw/artifacts/\` + \`.cclaw/knowledge.jsonl\`
240
240
 
241
241
  ### See also
242
242
  - Meta routing and activation rules: \`.cclaw/skills/using-cclaw/SKILL.md\`
@@ -28,10 +28,25 @@ export interface ArtifactValidation {
28
28
  }
29
29
  export interface StageAutoSubagentDispatch {
30
30
  agent: "planner" | "spec-reviewer" | "code-reviewer" | "security-reviewer" | "test-author" | "doc-updater";
31
- mode: "mandatory" | "proactive";
31
+ /**
32
+ * - `mandatory` — must be dispatched (or explicitly waived) before stage transition.
33
+ * - `proactive` — should be dispatched automatically when context matches `when`.
34
+ * - `conditional` — dispatched only when `condition` evaluates true at runtime; counted as
35
+ * mandatory **only when the condition holds**.
36
+ */
37
+ mode: "mandatory" | "proactive" | "conditional";
32
38
  when: string;
33
39
  purpose: string;
34
40
  requiresUserGate: boolean;
41
+ /**
42
+ * Optional machine-friendly trigger expression for `conditional` rows.
43
+ * Supported predicates: `diff_lines_gt:<N>`, `files_touched_gt:<N>`,
44
+ * `trust_boundary_changed`, `release_blast_radius_high`.
45
+ * Multiple predicates joined by `||` mean ANY trigger satisfies the condition.
46
+ */
47
+ condition?: string;
48
+ /** Optional skill folder the dispatched agent should load as additional context. */
49
+ skill?: string;
35
50
  }
36
51
  export interface NamedAntiPattern {
37
52
  title: string;
@@ -80,6 +95,8 @@ export declare const QUESTION_FORMAT_SPEC: string;
80
95
  export declare const ERROR_BUDGET_SPEC: string;
81
96
  /** Transition guard: agents with `mode: "mandatory"` in auto-subagent dispatch for this stage. */
82
97
  export declare function mandatoryDelegationsForStage(stage: FlowStage): string[];
98
+ /** Conditional dispatches that become mandatory only when their `condition` predicate evaluates true. */
99
+ export declare function conditionalDispatchesForStage(stage: FlowStage): StageAutoSubagentDispatch[];
83
100
  export declare function stageSchema(stage: FlowStage): StageSchema;
84
101
  export declare function orderedStageSchemas(): StageSchema[];
85
102
  export declare function stageGateIds(stage: FlowStage): string[];
@@ -195,7 +195,7 @@ const SCOPE = {
195
195
  "**Error and Rescue Registry** — For each capability: what breaks, how detected, what fallback."
196
196
  ],
197
197
  interactionProtocol: [
198
- "For scope mode selection: use the Decision Protocol — present expand/selective/hold/reduce as labeled options with trade-offs and mark one as (recommended). Base your recommendation on default heuristics: greenfield -> expand, enhancement -> selective, bugfix/hotfix/refactor -> hold, broad blast radius -> reduce. If AskQuestion/AskUserQuestion is available, send exactly ONE question per call, validate fields against runtime schema, and on schema error immediately fall back to plain-text question instead of retrying guessed payloads.",
198
+ "For scope mode selection: use the Decision Protocol — present expand/selective/hold/reduce as labeled options with trade-offs and mark one as (recommended). **Score each option `Completeness: X/10`** (10 = covers every prime-directive failure mode, four data-flow paths, observability, and deferred handling for the in-scope set; subtract for each gap). Recommend the highest-scoring option; if scores tie, pick the lowest blast radius. Base your recommendation on default heuristics: greenfield -> expand, enhancement -> selective, bugfix/hotfix/refactor -> hold, broad blast radius -> reduce. If AskQuestion/AskUserQuestion is available, send exactly ONE question per call, validate fields against runtime schema, and on schema error immediately fall back to plain-text question instead of retrying guessed payloads.",
199
199
  "Walk through the scope checklist interactively. Each checklist item that surfaces a decision should be presented to the user as a question, not as a monologue. Do not dump all items at once.",
200
200
  "Challenge premise and verify the problem framing before anything else.",
201
201
  "Take a position on every scope decision. Avoid hedging phrases like 'this could work' or 'there are many ways'; state your recommendation and one concrete condition that would change it.",
@@ -405,7 +405,7 @@ const DESIGN = {
405
405
  interactionProtocol: [
406
406
  "Review architecture decisions section-by-section.",
407
407
  "For EACH issue found in a review section, present it ONE AT A TIME. Do NOT batch multiple issues.",
408
- "For each issue: use the Decision Protocol — describe concretely with file/line references, present labeled options (A/B/C) with trade-offs, effort estimate (S/M/L/XL), risk level (Low/Med/High), and mark one as (recommended). If AskQuestion/AskUserQuestion is available, send exactly ONE question per call, validate fields against runtime schema, and on schema error immediately fall back to plain-text question instead of retrying guessed payloads.",
408
+ "For each issue: use the Decision Protocol — describe concretely with file/line references, present labeled options (A/B/C) with trade-offs, effort estimate (S/M/L/XL), risk level (Low/Med/High), **`Completeness: X/10` per option** (10 = fully addresses architecture/data-flow/failure-modes/test+perf review concerns for the issue, subtract for each unaddressed dimension), and mark one as (recommended). Prefer the highest-scoring option; if scores tie, prefer the lower-risk one. If AskQuestion/AskUserQuestion is available, send exactly ONE question per call, validate fields against runtime schema, and on schema error immediately fall back to plain-text question instead of retrying guessed payloads.",
409
409
  "Only proceed to the next review section after ALL issues in the current section are resolved.",
410
410
  "If a section has no issues, say 'No issues found' and move on.",
411
411
  "Do not skip failure-mode mapping.",
@@ -1108,10 +1108,11 @@ const REVIEW = {
1108
1108
  checklist: [
1109
1109
  "Diff Scope — Run `git diff` against base branch. If no diff, exit early with APPROVED (no changes to review). Scope the review to changed files unless blast-radius analysis requires wider inspection.",
1110
1110
  "Change-Size Check — ~100 lines = normal. ~300 lines = consider splitting. ~1000+ lines = strongly recommend stacked PRs. Flag large diffs to the user.",
1111
+ "Adversarial Trigger Check — compute changed-line count (`git diff --shortstat <base>..HEAD`), files-touched count, and whether trust boundaries changed (auth/secrets/external inputs/permissions). If `lines > 100` OR `files > 10` OR `trust boundary changed`, **dispatch a SECOND code-reviewer agent with the `adversarial-review` skill loaded** and reconcile its findings into the review army (treat the conditional dispatch as mandatory whenever the trigger holds; record the trigger that fired in the dashboard).",
1111
1112
  "Load upstream evidence — read TDD artifact (RED + GREEN + REFACTOR), spec, and plan. Verify evidence chain is unbroken.",
1112
1113
  "Layer 1: Spec Compliance — check every acceptance criterion against implementation. Verdict: pass/fail per criterion.",
1113
1114
  "Layer 2a: Correctness — logic errors, race conditions, boundary violations, null handling.",
1114
- "Layer 2b: Security — input validation, auth boundaries, secrets exposure, injection vectors.",
1115
+ "Layer 2b: Security — input validation, auth boundaries, secrets exposure, injection vectors. **Mandatory:** also load and execute the `.cclaw/skills/security-audit/SKILL.md` utility skill (proactive pattern sweep across diff + touched modules, not just the diff itself) and merge findings into the review army. The Layer 2 security pass is not complete until the audit sweep records a finding count (0 acceptable) with file:line evidence for every Critical.",
1115
1116
  "Layer 2c: Performance — N+1 queries, memory leaks, missing caching, hot paths.",
1116
1117
  "Layer 2d: Architecture Fit — does the implementation match the locked design? Coupling, cohesion, interface contracts.",
1117
1118
  "Layer 2e: External Safety — SQL safety, concurrency, secrets in logs, enum completeness (grep outside diff), LLM trust boundaries.",
@@ -1124,7 +1125,7 @@ const REVIEW = {
1124
1125
  "Run Layer 1 (spec compliance) completely before starting Layer 2.",
1125
1126
  "In each review section, present findings ONE AT A TIME. Do NOT batch.",
1126
1127
  "Classify every finding as Critical, Important, or Suggestion.",
1127
- "For each Critical finding: use the Decision Protocol — present resolution options (A/B/C) with trade-offs and mark one as (recommended). If AskQuestion/AskUserQuestion is available, send exactly ONE question per call, validate fields against runtime schema, and on schema error immediately fall back to plain-text question instead of retrying guessed payloads.",
1128
+ "For each Critical finding: use the Decision Protocol — present resolution options (A/B/C) with trade-offs, **score each option `Completeness: X/10`** (10 = fully closes the finding with no carry-over risk; subtract for partial fixes, deferred follow-ups, or new risk introduced), and mark one as (recommended). Prefer the highest-scoring option; if scores tie, prefer the option with the smallest blast radius. If AskQuestion/AskUserQuestion is available, send exactly ONE question per call, validate fields against runtime schema, and on schema error immediately fall back to plain-text question instead of retrying guessed payloads.",
1128
1129
  "Resolve all critical blockers before ship.",
1129
1130
  "For final verdict: use AskQuestion/AskUserQuestion only if runtime schema is confirmed; otherwise collect verdict with a plain-text single-choice prompt (APPROVED / APPROVED_WITH_CONCERNS / BLOCKED).",
1130
1131
  "**STOP.** Do NOT proceed to ship until the user provides an explicit verdict."
@@ -1148,7 +1149,8 @@ const REVIEW = {
1148
1149
  { id: "review_severity_classified", description: "All findings are severity-tagged." },
1149
1150
  { id: "review_criticals_resolved", description: "No unresolved critical blockers remain." },
1150
1151
  { id: "review_army_json_valid", description: "07-review-army.json passes schema validation (validateReviewArmy)." },
1151
- { id: "review_completeness_scored", description: "Completeness score is computed and recorded (AC coverage, task coverage, slice coverage, adversarial pass)." }
1152
+ { id: "review_completeness_scored", description: "Completeness score is computed and recorded (AC coverage, task coverage, slice coverage, adversarial pass)." },
1153
+ { id: "review_security_audit_swept", description: "The security-audit utility skill was run against the diff scope and the modules it touches. Finding count (0 if clean) recorded in the review army with file:line evidence for every Critical." }
1152
1154
  ],
1153
1155
  requiredEvidence: [
1154
1156
  "Artifact written to `.cclaw/artifacts/07-review.md`.",
@@ -1289,7 +1291,7 @@ const REVIEW = {
1289
1291
  { section: "Layer 1 Verdict", required: true, validationRule: "Per-criterion pass/fail with references." },
1290
1292
  { section: "Layer 2 Findings", required: true, validationRule: "Each finding has severity, description, and resolution status." },
1291
1293
  { section: "Review Army Contract", required: true, validationRule: "Structured findings include id/severity/confidence/fingerprint/reportedBy/status with dedup reconciliation summary." },
1292
- { section: "Review Readiness Dashboard", required: true, validationRule: "At least 4 readiness checklist lines including blocker and recommendation status." },
1294
+ { section: "Review Readiness Dashboard", required: true, validationRule: "Includes a per-pass table (Layer 1 / Layer 2 / Adversarial / Schema) with a 'Completed at' column, a Delegation log snapshot block (path .cclaw/state/delegation-log.json with required/completed/waived/pending), a Staleness signal block (commit at last review pass and current commit), and a Headline with open critical blockers + ship recommendation. At minimum, the section text must contain the substrings 'Completed at', 'delegation-log.json', 'commit at last review pass', and 'Ship recommendation'." },
1293
1295
  { section: "Completeness Score", required: true, validationRule: "Records AC coverage, task coverage, test-slice coverage, and adversarial-review pass status as numeric or boolean values. At minimum, a line like 'AC coverage: N/M' or 'AC coverage: 100%'." },
1294
1296
  { section: "Severity Summary", required: true, validationRule: "Per-severity count lines for critical, important, and suggestion buckets." },
1295
1297
  { section: "Final Verdict", required: true, validationRule: "Exactly one of: APPROVED, APPROVED_WITH_CONCERNS, BLOCKED." }
@@ -1334,7 +1336,7 @@ const SHIP = {
1334
1336
  interactionProtocol: [
1335
1337
  "Run preflight checks before any release action.",
1336
1338
  "Document release notes and rollback plan explicitly.",
1337
- "For finalization mode: use the Decision Protocol — present modes as labeled options (A/B/C/D) with consequences and mark one as (recommended). If AskQuestion/AskUserQuestion is available, send exactly ONE question per call, validate fields against runtime schema, and on schema error immediately fall back to plain-text question instead of retrying guessed payloads.",
1339
+ "For finalization mode: use the Decision Protocol — present modes as labeled options (A/B/C/D) with consequences, **score each option `Completeness: X/10`** (10 = fully addresses release blast-radius, rollback readiness, observability, and stakeholder communication), and mark one as (recommended). Prefer the highest-scoring option; if scores tie, prefer the most reversible one. If AskQuestion/AskUserQuestion is available, send exactly ONE question per call, validate fields against runtime schema, and on schema error immediately fall back to plain-text question instead of retrying guessed payloads.",
1338
1340
  "Do not proceed if critical blockers remain from review.",
1339
1341
  "**STOP.** Present finalization options and wait for user selection before executing any finalization action."
1340
1342
  ],
@@ -1453,7 +1455,7 @@ const SHIP = {
1453
1455
  { section: "Monitoring", required: false, validationRule: "If applicable: what metrics/logs to watch post-deploy. Risk note if no monitoring." },
1454
1456
  { section: "Finalization", required: true, validationRule: "Exactly one finalization enum token selected. Execution result documented. Worktree cleaned if applicable." },
1455
1457
  { section: "Completion Status", required: false, validationRule: "If present: exactly one of SHIPPED, SHIPPED_WITH_EXCEPTIONS, BLOCKED. Exceptions documented when applicable." },
1456
- { section: "Compound Step", required: false, validationRule: "Optional retrospective: at least one bullet of the form 'Insight: ... | Action: append [compound] entry to .cclaw/knowledge.md', or an explicit 'No compound insight this run.' line." }
1458
+ { section: "Compound Step", required: false, validationRule: "Optional retrospective: at least one bullet of the form 'Insight: ... | Action: append [compound] entry to .cclaw/knowledge.jsonl', or an explicit 'No compound insight this run.' line." }
1457
1459
  ],
1458
1460
  namedAntiPattern: {
1459
1461
  title: "Green CI Means Safe to Merge",
@@ -1568,8 +1570,18 @@ const STAGE_AUTO_SUBAGENT_DISPATCH = {
1568
1570
  agent: "security-reviewer",
1569
1571
  mode: "mandatory",
1570
1572
  when: "Always in review stage. Even when no trust boundaries changed, produce an explicit 'no-change' security attestation.",
1571
- purpose: "Guarantee a dedicated security pass on every diff: auth, input validation, secrets, injection, privilege, and blast-radius review are never opt-in.",
1572
- requiresUserGate: false
1573
+ purpose: "Guarantee a dedicated security pass on every diff: auth, input validation, secrets, injection, privilege, and blast-radius review are never opt-in. MUST load the `security-audit` skill and run a pattern-based sweep across the diff scope and touched modules in addition to the per-diff Layer 2 security checklist.",
1574
+ requiresUserGate: false,
1575
+ skill: "security-audit"
1576
+ },
1577
+ {
1578
+ agent: "code-reviewer",
1579
+ mode: "conditional",
1580
+ condition: "diff_lines_gt:100||files_touched_gt:10||trust_boundary_changed",
1581
+ when: "When the diff exceeds 100 changed lines, touches more than 10 files, or modifies trust boundaries — dispatch a SECOND, independent code-reviewer with the adversarial-review skill loaded so the review army has at least two voices on a high-blast-radius change.",
1582
+ purpose: "Adversarial second-opinion review on large or trust-sensitive diffs. The second reviewer treats the implementation as hostile and tries to break it (hostile-user, future-maintainer, competitor lenses) instead of sympathetically explaining it.",
1583
+ requiresUserGate: false,
1584
+ skill: "adversarial-review"
1573
1585
  }
1574
1586
  ],
1575
1587
  ship: [
@@ -1595,6 +1607,10 @@ export function mandatoryDelegationsForStage(stage) {
1595
1607
  .filter((d) => d.mode === "mandatory")
1596
1608
  .map((d) => d.agent);
1597
1609
  }
1610
+ /** Conditional dispatches that become mandatory only when their `condition` predicate evaluates true. */
1611
+ export function conditionalDispatchesForStage(stage) {
1612
+ return STAGE_AUTO_SUBAGENT_DISPATCH[stage].filter((d) => d.mode === "conditional");
1613
+ }
1598
1614
  export function stageSchema(stage) {
1599
1615
  const base = STAGE_SCHEMA_MAP[stage];
1600
1616
  return {
@@ -33,10 +33,22 @@ This is the **recommended way to start** working with cclaw. Use \`/cc-next\` fo
33
33
 
34
34
  1. Read \`${flowPath}\`.
35
35
  2. If flow already has completed stages beyond brainstorm, warn the user that starting a new brainstorm will reset progress. Ask for confirmation before proceeding.
36
- 3. Write the prompt to \`.cclaw/artifacts/00-idea.md\` as the raw idea capture.
37
- 4. Set \`currentStage: "brainstorm"\` in flow state (reset if needed).
38
- 5. Load \`.cclaw/skills/brainstorming/SKILL.md\` and \`.cclaw/commands/brainstorm.md\`.
39
- 6. Execute brainstorm with the prompt as initial context.
36
+ 3. **Track heuristic** classify the idea text and **recommend** a track (the user can override before any state mutation):
37
+ - **quick** (\`spec → tdd → review → ship\`) single-purpose work where the spec is essentially already known.
38
+ Triggers (case-insensitive substring or close variant): \`bug\`, \`bugfix\`, \`fix\`, \`hotfix\`, \`patch\`, \`typo\`, \`regression\`, \`copy change\`, \`rename\`, \`bump\`, \`upgrade dep\`, \`config tweak\`, \`docs only\`, \`comment\`, \`lint\`, \`format\`, \`small\`, \`tiny\`, \`one-liner\`, \`revert\`.
39
+ - **standard** (full 8 stages default) anything that introduces a new capability, touches multiple modules, or has unclear scope.
40
+ Triggers: \`new feature\`, \`add\`, \`build\`, \`design\`, \`refactor\`, \`migration\`, \`platform\`, \`architecture\`, \`endpoint\`, \`schema\`, \`api\`, \`integrate\`, \`workflow\`, \`onboarding\`, or any prompt that does not match quick triggers.
41
+ - When triggers conflict (e.g. "small refactor that touches 5 modules") prefer **standard** — quick is opt-in and only safe when scope is genuinely tiny.
42
+ 4. Present the recommendation as a single decision with explicit options:
43
+ > \`Recommended track: <quick|standard>\` because \`<one-line reason citing matched triggers>\`.
44
+ > Override? (A) keep \`<recommended>\` (B) switch to \`<other>\` (C) cancel.
45
+ If \`AskQuestion\`/\`AskUserQuestion\` is available, send exactly ONE question; on schema error, fall back to plain text.
46
+ 5. Persist the chosen track to \`${flowPath}\` (\`track\` field). Compute \`skippedStages\` from the track and write that too. Use the **first stage of the chosen track** as \`currentStage\` (quick → \`spec\`, standard → \`brainstorm\`).
47
+ 6. Write the prompt to \`.cclaw/artifacts/00-idea.md\` as the raw idea capture, and append a \`Track:\` line referencing the chosen track and the matched heuristic.
48
+ 7. Load the **first-stage skill for the chosen track** and its command file:
49
+ - quick → \`.cclaw/skills/specification-authoring/SKILL.md\` + \`.cclaw/commands/spec.md\`
50
+ - standard → \`.cclaw/skills/brainstorming/SKILL.md\` + \`.cclaw/commands/brainstorm.md\`
51
+ 8. Execute that stage with the prompt as initial context.
40
52
 
41
53
  ### Without prompt (\`/cc\`)
42
54
 
@@ -81,9 +93,20 @@ Do **not** silently discard an existing flow when the user provides a prompt. If
81
93
  - Inform: "You have an active flow at stage **{currentStage}** with {N} completed stages. Starting a new brainstorm will reset progress."
82
94
  - Ask: "Continue with reset? (A) Yes, start fresh (B) No, resume current flow"
83
95
  - If (B) → switch to Path B behavior.
84
- 3. Write \`${RUNTIME_ROOT}/artifacts/00-idea.md\` with the user's prompt.
85
- 4. Update \`${flowPath}\`: set \`currentStage: "brainstorm"\`, clear \`completedStages\`, reset gate catalog.
86
- 5. Load and execute: \`${RUNTIME_ROOT}/skills/brainstorming/SKILL.md\` + \`${RUNTIME_ROOT}/commands/brainstorm.md\`.
96
+ 3. **Classify the idea** using the heuristic below and present a single track recommendation. Wait for explicit confirmation or override before mutating any state.
97
+
98
+ **Track heuristic** (lowercase substring match against the user prompt):
99
+
100
+ | Track | Triggers | Use when |
101
+ |---|---|---|
102
+ | \`quick\` | \`bug\`, \`bugfix\`, \`fix\`, \`hotfix\`, \`patch\`, \`typo\`, \`regression\`, \`rename\`, \`bump\`, \`upgrade dep\`, \`docs only\`, \`comment\`, \`lint\`, \`format\`, \`small\`, \`tiny\`, \`one-liner\`, \`revert\`, \`copy change\` | Single-purpose, spec is essentially known, low blast radius |
103
+ | \`standard\` | \`new feature\`, \`add\`, \`build\`, \`design\`, \`refactor\`, \`migration\`, \`platform\`, \`architecture\`, \`endpoint\`, \`schema\`, \`api\`, \`integrate\`, \`workflow\`, \`onboarding\` (or no quick trigger matched) | Anything new, multi-module, or unclear scope |
104
+
105
+ - On conflict, prefer \`standard\` (quick is opt-in for genuinely tiny work).
106
+ - Always state the recommendation as a one-line reason citing the matched trigger.
107
+ 4. Persist the chosen track in \`${flowPath}\` (\`track\` + \`skippedStages\`). Set \`currentStage\` to the first stage of the chosen track (\`quick\` → \`spec\`, \`standard\` → \`brainstorm\`). Reset gate catalog.
108
+ 5. Write \`${RUNTIME_ROOT}/artifacts/00-idea.md\` with the user's prompt and an explicit \`Track:\` line capturing the heuristic decision.
109
+ 6. Load and execute the **first stage skill of the chosen track** (\`brainstorming\` for standard, \`specification-authoring\` for quick) plus its matching command file.
87
110
 
88
111
  ### Path B: \`/cc\` (no arguments)
89
112
 
@@ -8,7 +8,16 @@ function delegationLogPath() {
8
8
  return `${RUNTIME_ROOT}/state/delegation-log.json`;
9
9
  }
10
10
  function knowledgePath() {
11
- return `${RUNTIME_ROOT}/knowledge.md`;
11
+ return `${RUNTIME_ROOT}/knowledge.jsonl`;
12
+ }
13
+ function contextModePath() {
14
+ return `${RUNTIME_ROOT}/state/context-mode.json`;
15
+ }
16
+ function checkpointPath() {
17
+ return `${RUNTIME_ROOT}/state/checkpoint.json`;
18
+ }
19
+ function stageActivityPath() {
20
+ return `${RUNTIME_ROOT}/state/stage-activity.jsonl`;
12
21
  }
13
22
  /**
14
23
  * Command contract for /cc-status — a read-only snapshot command.
@@ -39,9 +48,15 @@ time to answer "where are we?" without advancing the flow.
39
48
  \`skippedStages\`, and per-stage gate catalog.
40
49
  2. Read **\`${delegationPath}\`** — count delegated / completed / waived / pending entries
41
50
  for the current stage's \`mandatoryDelegations\`.
42
- 3. Read the top of **\`${knowledgePath}\`** — surface up to 3 most recent entries
51
+ 3. Read **\`${contextModePath()}\`** — surface \`activeMode\` (default if missing).
52
+ 4. Compute **time in current stage** from the most recent stage-entry signal:
53
+ - Prefer \`${checkpointPath()}\`'s \`timestamp\` when its \`stage\` matches \`currentStage\`.
54
+ - Otherwise scan \`${stageActivityPath()}\` from the end for the first entry whose \`stage\` matches \`currentStage\` and use its \`ts\`.
55
+ - Compute the duration as \`now - signalTimestamp\` and render compactly: \`<X>m\`, \`<X>h<Y>m\`, or \`<X>d<Y>h\`.
56
+ - If no signal exists, render \`(unknown)\`.
57
+ 5. Read the top of **\`${knowledgePath}\`** — surface up to 3 most recent entries
43
58
  (by trailing timestamp or source marker).
44
- 4. Emit the status block described below. Do **not** load any stage skill.
59
+ 6. Emit the status block described below. Do **not** load any stage skill.
45
60
 
46
61
  ## Status Block Format
47
62
 
@@ -49,6 +64,8 @@ time to answer "where are we?" without advancing the flow.
49
64
  cclaw status
50
65
  track: <quick|standard>
51
66
  current stage: <stage> (<N>/<total> in track)
67
+ time in stage: <Xd Yh | Yh Zm | Zm | unknown>
68
+ context mode: <activeMode> (default | execution | review | incident | …)
52
69
  completed stages: <list or "none">
53
70
  skipped stages: <list or "none">
54
71
 
@@ -109,11 +126,16 @@ a read-only command.
109
126
 
110
127
  1. Read \`${flowPath}\`. If missing → report **BLOCKED: flow state absent** and suggest \`cclaw init\`.
111
128
  2. Read \`${delegationPath}\`. Missing → treat all mandatory delegations as pending.
112
- 3. Read \`${RUNTIME_ROOT}/knowledge.md\`. If missing or empty knowledge highlights are \`(none recorded)\`.
113
- 4. For each gate in \`stageGateCatalog[currentStage].required\`:
129
+ 3. Read \`${contextModePath()}\` for \`activeMode\`. Missingrender \`activeMode = default\`.
130
+ 4. Compute **time in stage**:
131
+ - Prefer \`${checkpointPath()}\` when \`stage === currentStage\` and \`timestamp\` parses as ISO 8601.
132
+ - Else scan \`${stageActivityPath()}\` from tail for the most recent entry whose \`stage === currentStage\`; use its \`ts\`.
133
+ - Render \`<X>d<Y>h\`, \`<X>h<Y>m\`, \`<X>m\`, or \`(unknown)\`.
134
+ 5. Read \`${RUNTIME_ROOT}/knowledge.jsonl\`. If missing or empty → knowledge highlights are \`(none recorded)\`. Parse each line as JSON and surface its \`trigger\`/\`action\`.
135
+ 6. For each gate in \`stageGateCatalog[currentStage].required\`:
114
136
  - Satisfied if present in \`passed\` and absent from \`blocked\`.
115
- 5. Build and print the status block (see command contract for layout).
116
- 6. Suggest the next action:
137
+ 7. Build and print the status block (see command contract for layout).
138
+ 8. Suggest the next action:
117
139
  - If current stage has unmet gates → \`/cc-next\` to resume.
118
140
  - If current stage is complete → \`/cc-next\` to advance (or report "Flow complete" if terminal).
119
141
 
@@ -345,12 +345,34 @@ Execution rule: complete and verify each wave before starting the next wave.
345
345
  - Reconciliation summary:
346
346
 
347
347
  ## Review Readiness Dashboard
348
- - Layer 1 complete:
349
- - Layer 2 complete:
350
- - Review army schema valid:
351
- - Open critical blockers:
352
- - Adversarial review pass:
353
- - Ship recommendation:
348
+
349
+ | Pass | Status | Completed at (UTC) | Reviewer / source | Commit at review | Drift vs HEAD |
350
+ |---|---|---|---|---|---|
351
+ | Layer 1 — spec compliance | pass / fail / pending | <ISO 8601> | spec-reviewer | <short sha> | <files changed since> |
352
+ | Layer 2 — correctness | pass / fail / pending | <ISO 8601> | code-reviewer | <short sha> | <files changed since> |
353
+ | Layer 2 — security | pass / fail / pending | <ISO 8601> | security-reviewer | <short sha> | <files changed since> |
354
+ | Layer 2 — performance | pass / fail / pending | <ISO 8601> | code-reviewer | <short sha> | <files changed since> |
355
+ | Layer 2 — architecture | pass / fail / pending | <ISO 8601> | code-reviewer | <short sha> | <files changed since> |
356
+ | Adversarial review | pass / fail / n/a | <ISO 8601 or —> | adversarial-review skill | <short sha or —> | <drift or —> |
357
+ | Review army schema valid | pass / fail | <ISO 8601> | jsonschema | <short sha> | n/a |
358
+
359
+ ### Delegation log snapshot (current run, current stage)
360
+ - Path: \`.cclaw/state/delegation-log.json\`
361
+ - Required: <list of mandatory specialists>
362
+ - Completed: <list with timestamps>
363
+ - Waived (with reason): <list or "none">
364
+ - Pending: <list or "none">
365
+
366
+ ### Staleness signal
367
+ - Worktree commit at last review pass: \`<short sha>\`
368
+ - Worktree commit now: \`<short sha>\`
369
+ - Files changed since last review pass: \`<count>\` (run \`git diff --stat <sha>..HEAD\` to inspect)
370
+ - If drift > 0 lines, mark Layer 1 / Layer 2 results as **STALE — re-run before ship**.
371
+
372
+ ### Headline
373
+ - Open critical blockers: <count>
374
+ - Adversarial review pass: pass / fail / n/a
375
+ - Ship recommendation: APPROVED | APPROVED_WITH_CONCERNS | BLOCKED
354
376
 
355
377
  ## Completeness Score
356
378
  - AC coverage: <N>/<M> (<percent>%)
@@ -424,7 +446,7 @@ Execution rule: complete and verify each wave before starting the next wave.
424
446
  _Optional retrospective. The goal is to make the **next** feature faster, not to evaluate this one._
425
447
  _If you have nothing to add, write the explicit line: \`No compound insight this run.\`_
426
448
  - Insight: <one short line about what should accelerate the next run>
427
- - Action: append \`[compound]\` entry to \`.cclaw/knowledge.md\` capturing the insight
449
+ - Action: append one strict-schema JSON line with \`"type":"compound"\` to \`.cclaw/knowledge.jsonl\` capturing the insight (fields: type, trigger, action, confidence, domain, stage, created, project)
428
450
  `
429
451
  };
430
452
  export const RULEBOOK_MARKDOWN = `# Cclaw Rulebook
@@ -16,5 +16,32 @@ export declare function landscapeCheckSkill(): string;
16
16
  export declare function knowledgeCurationSkill(): string;
17
17
  export declare function securityAuditSkill(): string;
18
18
  export declare function adversarialReviewSkill(): string;
19
- export declare const UTILITY_SKILL_FOLDERS: readonly ["security", "debugging", "performance", "ci-cd", "docs", "executing-plans", "context-engineering", "source-driven-development", "frontend-accessibility", "landscape-check", "adversarial-review", "security-audit", "knowledge-curation"];
19
+ export declare function retrospectiveSkill(): string;
20
+ export declare function languageTypescriptSkill(): string;
21
+ export declare function languagePythonSkill(): string;
22
+ export declare function languageGoSkill(): string;
23
+ /**
24
+ * Language rule packs live under `.cclaw/rules/lang/<pack>.md`. They are NOT
25
+ * skills (no folder, no `SKILL.md`) — they are opt-in **rule files** that the
26
+ * meta-skill router and stage hooks consult when the corresponding language
27
+ * appears in a diff. The pack id doubles as the on-disk filename stem.
28
+ */
29
+ export declare const LANGUAGE_RULE_PACK_FILES: {
30
+ readonly typescript: "typescript.md";
31
+ readonly python: "python.md";
32
+ readonly go: "go.md";
33
+ };
34
+ /**
35
+ * Folder (relative to runtime root) that holds every enabled language rule
36
+ * pack. A single folder keeps discovery trivial for hooks and for `doctor`.
37
+ */
38
+ export declare const LANGUAGE_RULE_PACK_DIR: readonly ["rules", "lang"];
39
+ export declare const LANGUAGE_RULE_PACK_GENERATORS: Record<string, () => string>;
40
+ /**
41
+ * Legacy per-language folders under `.cclaw/skills/` used in v0.7.0. Listed
42
+ * here so `cclaw sync` and `doctor` can surface drift and the installer can
43
+ * clean them up after the move to `.cclaw/rules/lang/`.
44
+ */
45
+ export declare const LEGACY_LANGUAGE_RULE_PACK_FOLDERS: readonly ["language-typescript", "language-python", "language-go"];
46
+ export declare const UTILITY_SKILL_FOLDERS: readonly ["security", "debugging", "performance", "ci-cd", "docs", "executing-plans", "context-engineering", "source-driven-development", "frontend-accessibility", "landscape-check", "adversarial-review", "security-audit", "knowledge-curation", "retrospective"];
20
47
  export declare const UTILITY_SKILL_MAP: Record<string, () => string>;