Skip to content

Commit 21a6d29

Browse files
catlog22claude
andcommitted
feat: add json_builder tool with schema-aware JSON construction and validation
Unified tool replacing manual schema reading (cat schema) across all agents and skills. Supports 5 commands: init (skeleton), set (incremental field setting with instant validation), validate (full structural + semantic), merge (dedup multiple JSONs), info (compact schema summary). Registers 24 schemas in schema-registry.ts. Updates all agent/skill/command files to use json_builder info/init/validate instead of cat schema references. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
1 parent bbceef3 commit 21a6d29

16 files changed

Lines changed: 1147 additions & 112 deletions

File tree

.claude/agents/action-planning-agent.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -829,6 +829,12 @@ Generate at `.workflow/active/{session_id}/plan.json` following `plan-overview-b
829829
830830
**Generation Timing**: After all `.task/IMPL-*.json` files are generated, aggregate into plan.json.
831831
832+
**Validation**: After writing plan.json and task files, validate with json_builder:
833+
```bash
834+
ccw tool exec json_builder '{"cmd":"validate","target":"<session>/plan.json","schema":"plan"}'
835+
ccw tool exec json_builder '{"cmd":"validate","target":"<session>/.task/IMPL-001.json","schema":"task"}'
836+
```
837+
832838
### 2.3 IMPL_PLAN.md Structure
833839
834840
**Template-Based Generation**:

.claude/agents/cli-explore-agent.md

Lines changed: 63 additions & 77 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ description: |
55
Orchestrates 4-phase workflow: Task Understanding → Analysis Execution → Schema Validation → Output Generation.
66
Spawned by /explore command orchestrator.
77
tools: Read, Bash, Glob, Grep
8+
# json_builder available via: ccw tool exec json_builder '{"cmd":"..."}' (Bash)
89
color: yellow
910
---
1011

@@ -66,9 +67,9 @@ Phase 4: Output Generation
6667
Store result as `project_structure` for module-aware file discovery in Phase 2.
6768

6869
2. **Output Schema Loading** (if output file path specified in prompt):
69-
- Exploration output → `cat ~/.ccw/workflows/cli-templates/schemas/explore-json-schema.json`
70-
- Other schemas as specified in prompt
71-
Read and memorize schema requirements BEFORE any analysis begins (feeds Phase 3 validation).
70+
- Get schema summary: `ccw tool exec json_builder '{"cmd":"info","schema":"explore"}'` (or "diagnosis" for bug analysis)
71+
- Initialize output file: `ccw tool exec json_builder '{"cmd":"init","schema":"explore","output":"<output_path>"}'`
72+
- The tool returns requiredFields, arrayFields, and enumFields — memorize these for Phase 2.
7273

7374
3. **Project Context Loading** (from spec system):
7475
- Load exploration specs using: `ccw spec load --category exploration`
@@ -150,55 +151,56 @@ RULES: {from prompt, if template specified} | analysis=READ-ONLY
150151
---
151152

152153
<schema_validation>
153-
## Phase 3: Schema Validation
154+
## Phase 3: Incremental Build & Validation (via json_builder)
154155

155-
### CRITICAL: Schema Compliance Protocol
156+
**This phase replaces manual JSON writing + self-validation with tool-assisted construction.**
156157

157-
**This phase is MANDATORY when schema file is specified in prompt.**
158+
**Step 1: Set text fields** (discovered during Phase 2 analysis)
159+
```bash
160+
ccw tool exec json_builder '{"cmd":"set","target":"<output_path>","ops":[
161+
{"path":"project_structure","value":"..."},
162+
{"path":"patterns","value":"..."},
163+
{"path":"dependencies","value":"..."},
164+
{"path":"integration_points","value":"..."},
165+
{"path":"constraints","value":"..."}
166+
]}'
167+
```
168+
169+
**Step 2: Append file entries** (as discovered — one `set` per batch)
170+
```bash
171+
ccw tool exec json_builder '{"cmd":"set","target":"<output_path>","ops":[
172+
{"path":"relevant_files[+]","value":{"path":"src/auth.ts","relevance":0.9,"rationale":"Contains AuthService.login() entry point for JWT generation","role":"modify_target","discovery_source":"bash-scan","key_code":[{"symbol":"login()","location":"L45-78","description":"JWT token generation with bcrypt verification"}],"topic_relation":"Security target — JWT generation lacks token rotation"}},
173+
{"path":"relevant_files[+]","value":{...}}
174+
]}'
175+
```
158176

159-
**Step 1: Read Schema FIRST**
177+
The tool **automatically validates** each operation:
178+
- enum values (role, discovery_source) → rejects invalid
179+
- minLength (rationale >= 10) → rejects too short
180+
- type checking → rejects wrong types
181+
182+
**Step 3: Set metadata**
183+
```bash
184+
ccw tool exec json_builder '{"cmd":"set","target":"<output_path>","ops":[
185+
{"path":"_metadata.timestamp","value":"auto"},
186+
{"path":"_metadata.task_description","value":"..."},
187+
{"path":"_metadata.source","value":"cli-explore-agent"},
188+
{"path":"_metadata.exploration_angle","value":"..."},
189+
{"path":"_metadata.exploration_index","value":1},
190+
{"path":"_metadata.total_explorations","value":2}
191+
]}'
160192
```
161-
Read(schema_file_path)
193+
194+
**Step 4: Final validation**
195+
```bash
196+
ccw tool exec json_builder '{"cmd":"validate","target":"<output_path>"}'
162197
```
198+
Returns `{valid, errors, warnings, stats}`. If errors exist → fix with `set` → re-validate.
163199

164-
**Step 2: Extract Schema Requirements**
165-
166-
Parse and memorize:
167-
1. **Root structure** - Is it array `[...]` or object `{...}`?
168-
2. **Required fields** - List all `"required": [...]` arrays
169-
3. **Field names EXACTLY** - Copy character-by-character (case-sensitive)
170-
4. **Enum values** - Copy exact strings (e.g., `"critical"` not `"Critical"`)
171-
5. **Nested structures** - Note flat vs nested requirements
172-
173-
**Step 3: File Rationale Validation** (MANDATORY for relevant_files / affected_files)
174-
175-
Every file entry MUST have:
176-
- `rationale` (required, minLength 10): Specific reason tied to the exploration topic, NOT generic
177-
- GOOD: "Contains AuthService.login() which is the entry point for JWT token generation"
178-
- BAD: "Related to auth" or "Relevant file"
179-
- `role` (required, enum): Structural classification of why it was selected
180-
- `discovery_source` (optional but recommended): How the file was found
181-
- `key_code` (strongly recommended for relevance >= 0.7): Array of {symbol, location?, description}
182-
- GOOD: [{"symbol": "AuthService.login()", "location": "L45-L78", "description": "JWT token generation with bcrypt verification, returns token pair"}]
183-
- BAD: [{"symbol": "login", "description": "login function"}]
184-
- `topic_relation` (strongly recommended for relevance >= 0.7): Connection from exploration angle perspective
185-
- GOOD: "Security exploration targets this file because JWT generation lacks token rotation"
186-
- BAD: "Related to security"
187-
188-
**Step 4: Pre-Output Validation Checklist**
189-
190-
Before writing ANY JSON output, verify:
191-
192-
- [ ] Root structure matches schema (array vs object)
193-
- [ ] ALL required fields present at each level
194-
- [ ] Field names EXACTLY match schema (character-by-character)
195-
- [ ] Enum values EXACTLY match schema (case-sensitive)
196-
- [ ] Nested structures follow schema pattern (flat vs nested)
197-
- [ ] Data types correct (string, integer, array, object)
198-
- [ ] Every file in relevant_files has: path + relevance + rationale + role
199-
- [ ] Every rationale is specific (>10 chars, not generic)
200-
- [ ] Files with relevance >= 0.7 have key_code with symbol + description (minLength 10)
201-
- [ ] Files with relevance >= 0.7 have topic_relation explaining connection to angle (minLength 15)
200+
**Quality reminders** (enforced by tool, but be aware):
201+
- `rationale`: Must be specific, not generic ("Related to auth" → rejected by semantic check)
202+
- `key_code`: Strongly recommended for relevance >= 0.7 (warnings if missing)
203+
- `topic_relation`: Strongly recommended for relevance >= 0.7 (warnings if missing)
202204
</schema_validation>
203205

204206
---
@@ -212,16 +214,12 @@ Brief summary:
212214
- Task completion status
213215
- Key findings summary
214216
- Generated file paths (if any)
217+
- Validation result (from Phase 3 Step 4)
215218

216-
### File Output (as specified in prompt)
217-
218-
**MANDATORY WORKFLOW**:
219+
### File Output
219220

220-
1. `Read()` schema file BEFORE generating output
221-
2. Extract ALL field names from schema
222-
3. Build JSON using ONLY schema field names
223-
4. Validate against checklist before writing
224-
5. Write file with validated content
221+
File is already written by json_builder during Phase 3 (init + set operations).
222+
Phase 4 only verifies the final validation passed and returns the summary.
225223
</output_generation>
226224

227225
---
@@ -243,28 +241,19 @@ Brief summary:
243241

244242
**ALWAYS**:
245243
1. **Search Tool Priority**: ACE (`mcp__ace-tool__search_context`) → CCW (`mcp__ccw-tools__smart_search`) / Built-in (`Grep`, `Glob`, `Read`)
246-
2. Read schema file FIRST before generating any output (if schema specified)
247-
3. Copy field names EXACTLY from schema (case-sensitive)
248-
4. Verify root structure matches schema (array vs object)
249-
5. Match nested/flat structures as schema requires
250-
6. Use exact enum values from schema (case-sensitive)
251-
7. Include ALL required fields at every level
252-
8. Include file:line references in findings
253-
9. **Every file MUST have rationale**: Specific selection basis tied to the topic (not generic)
254-
10. **Every file MUST have role**: Classify as modify_target/dependency/pattern_reference/test_target/type_definition/integration_point/config/context_only
255-
11. **Track discovery source**: Record how each file was found (bash-scan/cli-analysis/ace-search/dependency-trace/manual)
256-
12. **Populate key_code for high-relevance files**: relevance >= 0.7 → key_code array with symbol, location, description
257-
13. **Populate topic_relation for high-relevance files**: relevance >= 0.7 → topic_relation explaining file-to-angle connection
244+
2. **Use json_builder** for all JSON output: `init``set` (incremental) → `validate`
245+
3. Include file:line references in findings
246+
4. **Every file MUST have rationale + role** (enforced by json_builder set validation)
247+
5. **Track discovery source**: Record how each file was found (bash-scan/cli-analysis/ace-search/dependency-trace/manual)
248+
6. **Populate key_code + topic_relation for high-relevance files** (relevance >= 0.7; json_builder warns if missing)
258249

259250
**Bash Tool**:
260251
- Use `run_in_background=false` for all Bash/CLI calls to ensure foreground execution
261252

262253
**NEVER**:
263-
1. Modify any files (read-only agent)
264-
2. Skip schema reading step when schema is specified
265-
3. Guess field names - ALWAYS copy from schema
266-
4. Assume structure - ALWAYS verify against schema
267-
5. Omit required fields
254+
1. Modify any source code files (read-only agent — json_builder writes only output JSON)
255+
2. Hand-write JSON output — always use json_builder
256+
3. Skip the `validate` step before returning
268257
</operational_rules>
269258

270259
<output_contract>
@@ -282,11 +271,8 @@ When exploration is complete, return one of:
282271

283272
Before returning, verify:
284273
- [ ] All 4 phases were executed (or skipped with justification)
285-
- [ ] Schema was read BEFORE output generation (if schema specified)
286-
- [ ] All field names match schema exactly (case-sensitive)
287-
- [ ] Every file entry has rationale (specific, >10 chars) and role
288-
- [ ] High-relevance files (>= 0.7) have key_code and topic_relation
274+
- [ ] json_builder `init` was called at start
275+
- [ ] json_builder `validate` returned `valid: true` (or all errors were fixed)
289276
- [ ] Discovery sources are tracked for all findings
290-
- [ ] No files were modified (read-only agent)
291-
- [ ] Output format matches schema root structure (array vs object)
277+
- [ ] No source code files were modified (read-only agent)
292278
</quality_gate>

.claude/agents/cli-lite-planning-agent.md

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -139,16 +139,15 @@ When `process_docs: true`, generate planning-context.md before sub-plan.json:
139139

140140
## Schema-Driven Output
141141

142-
**CRITICAL**: Read the schema reference first to determine output structure:
143-
- `plan-overview-base-schema.json` → Implementation plan with `approach`, `complexity`
144-
- `plan-overview-fix-schema.json` → Fix plan with `root_cause`, `severity`, `risk_level`
142+
**CRITICAL**: Get schema info via json_builder to determine output structure:
143+
- `ccw tool exec json_builder '{"cmd":"info","schema":"plan"}'` → Implementation plan with `approach`, `complexity`
144+
- `ccw tool exec json_builder '{"cmd":"info","schema":"plan-fix"}'` → Fix plan with `root_cause`, `severity`, `risk_level`
145145

146-
```javascript
147-
// Step 1: Always read schema first
148-
const schema = Bash(`cat ${schema_path}`)
149-
150-
// Step 2: Generate plan conforming to schema
151-
const planObject = generatePlanFromSchema(schema, context)
146+
After generating plan.json and .task/*.json, validate:
147+
```bash
148+
ccw tool exec json_builder '{"cmd":"validate","target":"<session>/plan.json","schema":"plan"}'
149+
# For each task file:
150+
ccw tool exec json_builder '{"cmd":"validate","target":"<session>/.task/TASK-001.json","schema":"task"}'
152151
```
153152

154153
</schema_driven_output>
@@ -863,7 +862,7 @@ function validateTask(task) {
863862
864863
**ALWAYS**:
865864
- **Search Tool Priority**: ACE (`mcp__ace-tool__search_context`) → CCW (`mcp__ccw-tools__smart_search`) / Built-in (`Grep`, `Glob`, `Read`)
866-
- **Read schema first** to determine output structure
865+
- **Get schema info via json_builder** to determine output structure
867866
- Generate task IDs (TASK-001/TASK-002 for plan, FIX-001/FIX-002 for fix-plan)
868867
- Include depends_on (even if empty [])
869868
- **Assign cli_execution_id** (`{sessionId}-{taskId}`)
@@ -981,7 +980,7 @@ Upon completion, return one of:
981980
982981
Before returning, verify:
983982
984-
- [ ] Schema reference was read and output structure matches schema type (base vs fix)
983+
- [ ] Schema info was obtained via json_builder and output structure matches schema type (base vs fix)
985984
- [ ] All tasks have valid IDs (TASK-NNN or FIX-NNN format)
986985
- [ ] All tasks have 2+ implementation steps
987986
- [ ] All convergence criteria are quantified and testable (no vague language)

.claude/agents/issue-plan-agent.md

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -348,7 +348,7 @@ Write({ file_path: filePath, content: newContent })
348348
.workflow/issues/solutions/{issue-id}.jsonl
349349
```
350350
351-
Each line is a solution JSON containing tasks. Schema: `cat ~/.ccw/workflows/cli-templates/schemas/solution-schema.json`
351+
Each line is a solution JSON containing tasks. Schema: `ccw tool exec json_builder '{"cmd":"info","schema":"solution"}'`
352352
353353
### 2.2 Return Summary
354354
@@ -388,7 +388,7 @@ Each line is a solution JSON containing tasks. Schema: `cat ~/.ccw/workflows/cli
388388
389389
**ALWAYS**:
390390
1. **Search Tool Priority**: ACE (`mcp__ace-tool__search_context`) → CCW (`mcp__ccw-tools__smart_search`) / Built-in (`Grep`, `Glob`, `Read`)
391-
2. Read schema first: `cat ~/.ccw/workflows/cli-templates/schemas/solution-schema.json`
391+
2. Get schema info: `ccw tool exec json_builder '{"cmd":"info","schema":"solution"}'` (replaces reading raw schema)
392392
3. Use ACE semantic search as PRIMARY exploration tool
393393
4. Fetch issue details via `ccw issue status <id> --json`
394394
5. **Analyze failure history**: Check `issue.feedback` for type='failure', stage='execute'
@@ -408,6 +408,11 @@ Each line is a solution JSON containing tasks. Schema: `cat ~/.ccw/workflows/cli
408408
4. **Dependency ordering**: If issues must touch same files, encode execution order via `depends_on`
409409
5. **Scope minimization**: Prefer smaller, focused modifications over broad refactoring
410410
411+
**VALIDATE**: After writing solution JSONL, validate each solution:
412+
```bash
413+
ccw tool exec json_builder '{"cmd":"validate","target":".workflow/issues/solutions/<issue-id>.jsonl","schema":"solution"}'
414+
```
415+
411416
**NEVER**:
412417
1. Execute implementation (return plan only)
413418
2. Use vague criteria ("works correctly", "good performance")

.claude/commands/workflow/spec/setup.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,7 @@ Task(
129129
Analyze project for workflow initialization and generate .workflow/project-tech.json.
130130
131131
## MANDATORY FIRST STEPS
132-
1. Execute: cat ~/.ccw/workflows/cli-templates/schemas/project-tech-schema.json (get schema reference)
132+
1. Execute: ccw tool exec json_builder '{"cmd":"info","schema":"tech"}' (get schema summary)
133133
2. Execute: ccw tool exec get_modules_by_depth '{}' (get project structure)
134134
135135
## Task

.claude/skills/review-cycle/phases/review-module.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -401,7 +401,7 @@ Task(
401401
1. Read review state: ${reviewStateJsonPath}
402402
2. Get target files: Read resolved_files from review-state.json
403403
3. Validate file access: bash(ls -la ${targetFiles.join(' ')})
404-
4. Execute: cat ~/.ccw/workflows/cli-templates/schemas/review-dimension-results-schema.json (get output schema reference)
404+
4. Execute: ccw tool exec json_builder '{"cmd":"info","schema":"review-dim"}' (get output schema summary)
405405
5. Read: .workflow/project-tech.json (technology stack and architecture context)
406406
6. Read: .workflow/specs/*.md (user-defined constraints and conventions to validate against)
407407
@@ -456,7 +456,7 @@ Task(
456456
${getDimensionGuidance(dimension)}
457457
458458
## Success Criteria
459-
- [ ] Schema obtained via cat review-dimension-results-schema.json
459+
- [ ] Schema obtained via json_builder info
460460
- [ ] All target files analyzed for ${dimension} concerns
461461
- [ ] All findings include file:line references with code snippets
462462
- [ ] Severity assessment follows established criteria (see reference)
@@ -505,7 +505,7 @@ Task(
505505
2. Read affected file: ${file}
506506
3. Identify related code: bash(grep -r "import.*${basename(file)}" ${projectDir}/src --include="*.ts")
507507
4. Read test files: bash(find ${projectDir}/tests -name "*${basename(file, '.ts')}*" -type f)
508-
5. Execute: cat ~/.ccw/workflows/cli-templates/schemas/review-deep-dive-results-schema.json (get output schema reference)
508+
5. Execute: ccw tool exec json_builder '{"cmd":"info","schema":"review-deep"}' (get output schema summary)
509509
6. Read: .workflow/project-tech.json (technology stack and architecture context)
510510
7. Read: .workflow/specs/*.md (user-defined constraints for remediation compliance)
511511
@@ -538,7 +538,7 @@ Task(
538538
- Impact assessment and rollback strategy
539539
540540
## Success Criteria
541-
- [ ] Schema obtained via cat review-deep-dive-results-schema.json
541+
- [ ] Schema obtained via json_builder info
542542
- [ ] Root cause clearly identified with supporting evidence
543543
- [ ] Remediation plan is step-by-step actionable with exact file:line references
544544
- [ ] Each step includes specific commands and validation tests

.claude/skills/review-cycle/phases/review-session.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -412,7 +412,7 @@ Task(
412412
2. Read completed task summaries: bash(find ${summariesDir} -name "IMPL-*.md" -type f)
413413
3. Get changed files: bash(cd ${workflowDir} && git log --since="${sessionCreatedAt}" --name-only --pretty=format: | sort -u)
414414
4. Read review state: ${reviewStateJsonPath}
415-
5. Execute: cat ~/.ccw/workflows/cli-templates/schemas/review-dimension-results-schema.json (get output schema reference)
415+
5. Execute: ccw tool exec json_builder '{"cmd":"info","schema":"review-dim"}' (get output schema summary)
416416
6. Read: .workflow/project-tech.json (technology stack and architecture context)
417417
7. Read: .workflow/specs/*.md (user-defined constraints and conventions to validate against)
418418
@@ -467,7 +467,7 @@ Task(
467467
${getDimensionGuidance(dimension)}
468468
469469
## Success Criteria
470-
- [ ] Schema obtained via cat review-dimension-results-schema.json
470+
- [ ] Schema obtained via json_builder info
471471
- [ ] All changed files analyzed for ${dimension} concerns
472472
- [ ] All findings include file:line references with code snippets
473473
- [ ] Severity assessment follows established criteria (see reference)
@@ -516,7 +516,7 @@ Task(
516516
2. Read affected file: ${file}
517517
3. Identify related code: bash(grep -r "import.*${basename(file)}" ${workflowDir}/src --include="*.ts")
518518
4. Read test files: bash(find ${workflowDir}/tests -name "*${basename(file, '.ts')}*" -type f)
519-
5. Execute: cat ~/.ccw/workflows/cli-templates/schemas/review-deep-dive-results-schema.json (get output schema reference)
519+
5. Execute: ccw tool exec json_builder '{"cmd":"info","schema":"review-deep"}' (get output schema summary)
520520
6. Read: .workflow/project-tech.json (technology stack and architecture context)
521521
7. Read: .workflow/specs/*.md (user-defined constraints for remediation compliance)
522522
@@ -550,7 +550,7 @@ Task(
550550
- Impact assessment and rollback strategy
551551
552552
## Success Criteria
553-
- [ ] Schema obtained via cat review-deep-dive-results-schema.json
553+
- [ ] Schema obtained via json_builder info
554554
- [ ] Root cause clearly identified with supporting evidence
555555
- [ ] Remediation plan is step-by-step actionable with exact file:line references
556556
- [ ] Each step includes specific commands and validation tests

.claude/skills/workflow-multi-cli-plan/SKILL.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -246,8 +246,8 @@ Agent({
246246
description: "Generate implementation plan",
247247
prompt: `
248248
## Schema Reference
249-
Execute: cat ~/.ccw/workflows/cli-templates/schemas/plan-overview-base-schema.json
250-
Execute: cat ~/.ccw/workflows/cli-templates/schemas/task-schema.json
249+
Execute: ccw tool exec json_builder '{"cmd":"info","schema":"plan"}'
250+
Execute: ccw tool exec json_builder '{"cmd":"info","schema":"task"}'
251251
252252
## Output Format: Two-Layer Structure
253253
- plan.json: Overview with task_ids[] referencing .task/ files (NO tasks[] array)

0 commit comments

Comments
 (0)