chati-dev 4.1.1 → 4.1.3

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.
package/README.md CHANGED
@@ -374,7 +374,7 @@ your-project/
374
374
  │ ├── commands/
375
375
  │ │ └── chati.toml # TOML command → orchestrator
376
376
  │ ├── context/ # 4 framework context files (@imported by GEMINI.md)
377
- │ ├── hooks/ # 8 hooks (full governance parity with Claude Code)
377
+ │ ├── hooks/ # Gemini hooks (governance parity with Claude Code)
378
378
  │ ├── settings.json # Hook configuration
379
379
  │ └── session-lock.md # Runtime state / session lock (gitignored)
380
380
  ├── GEMINI.md # Project context with @import chain
@@ -400,7 +400,7 @@ your-project/
400
400
  │ ├── schemas/ # 5 JSON schemas
401
401
  │ ├── intelligence/ # PRISM, RECALL, COMPASS specs
402
402
  │ ├── domains/ # Per-agent and per-workflow configs
403
- │ ├── hooks/ # 9 shared hooks (used by Claude + Gemini)
403
+ │ ├── hooks/ # Shared hooks (used by Claude + Gemini)
404
404
  │ ├── context/ # Context files (deployed per provider)
405
405
  │ ├── frameworks/ # Decision heuristics
406
406
  │ ├── quality-gates/ # Planning & implementation gates
@@ -156,14 +156,14 @@ WHILE tasks_pending:
156
156
  → If no architecture.md → proceed with best practices
157
157
  3. Implement code
158
158
  -> Output: "T{X} implementation done. Self-critique (5.5)..."
159
- 3. Run self-critique (Step 5.5) — 1 fix pass, then proceed
159
+ 4. Run self-critique (Step 5.5) — 1 fix pass, then proceed
160
160
  -> Output: "T{X} critique done. Running tests..."
161
- 4. Run tests (once)
161
+ 5. Run tests (once)
162
162
  -> Output: "T{X} tests: {N}/{total} passed. Post-test review (6.5)..."
163
- 5. Run post-test critique (Step 6.5) — 1 fix pass, then score
163
+ 6. Run post-test critique (Step 6.5) — 1 fix pass, then score
164
164
  -> Output: "T{X} review done. Scoring..."
165
- 6. Self-validate against acceptance criteria
166
- 7. Calculate score
165
+ 7. Self-validate against acceptance criteria
166
+ 8. Calculate score
167
167
 
168
168
  IF score >= 95:
169
169
  mark_complete(task)
@@ -260,6 +260,14 @@ Strategy (based on data criticality from PRD):
260
260
 
261
261
  ---
262
262
 
263
+ ## Output Artifact
264
+
265
+ Write your complete output to: `chati.dev/artifacts/3-Architecture/data-architecture.md`
266
+
267
+ This file is the human-reviewable data architecture document. It will also be merged into the consolidated `architecture.md` by the Architect Manager.
268
+
269
+ ---
270
+
263
271
  ## Self-Validation (6 criteria, threshold >= 90%)
264
272
 
265
273
  1. Schema covers all PRD entities with proper normalization (3NF minimum)
@@ -155,6 +155,14 @@ For each OWASP category, document the mitigation strategy:
155
155
 
156
156
  ---
157
157
 
158
+ ## Output Artifact
159
+
160
+ Write your complete output to: `chati.dev/artifacts/3-Architecture/system-architecture.md`
161
+
162
+ This file is the human-reviewable system architecture document. It will also be merged into the consolidated `architecture.md` by the Architect Manager.
163
+
164
+ ---
165
+
158
166
  ## Self-Validation (7 criteria, threshold >= 90%)
159
167
 
160
168
  1. Tech stack selected and justified with exact version numbers
@@ -95,7 +95,14 @@ If mismatches found: route correction to the responsible sub-agent.
95
95
 
96
96
  ### Step 4: Consolidate & Handoff
97
97
 
98
- 1. Merge outputs into unified `architecture.md` with 10 sections:
98
+ Each sub-agent writes its own artifact first (human-reviewable), then the Manager consolidates.
99
+
100
+ **Sub-agent artifacts (written by each sub-agent):**
101
+ - System Architect writes: `chati.dev/artifacts/3-Architecture/system-architecture.md`
102
+ - Data Engineer writes: `chati.dev/artifacts/3-Architecture/data-architecture.md`
103
+
104
+ **Consolidated artifact (written by Manager):**
105
+ Merge both into `chati.dev/artifacts/3-Architecture/architecture.md` with 10 sections:
99
106
  - Section 1: Architecture Overview
100
107
  - Section 2: Tech Stack (table with versions and justifications)
101
108
  - Section 3: System Components (diagram, patterns)
@@ -107,6 +114,14 @@ If mismatches found: route correction to the responsible sub-agent.
107
114
  - Section 9: Scalability
108
115
  - Section 10: Architecture Decision Records (ADRs)
109
116
 
117
+ The consolidated file is what downstream agents (UX, Dev) consume.
118
+ The individual files are for human review and approval.
119
+
120
+ **Verification**: After consolidation, confirm all 3 files exist:
121
+ ```
122
+ ls chati.dev/artifacts/3-Architecture/system-architecture.md chati.dev/artifacts/3-Architecture/data-architecture.md chati.dev/artifacts/3-Architecture/architecture.md
123
+ ```
124
+
110
125
  2. Verify all self-validation criteria pass (>= 90%)
111
126
  3. Generate handoff for UX agent
112
127
 
@@ -136,7 +151,9 @@ Score = criteria met / 10. Threshold: >= 90% (9/10 minimum).
136
151
 
137
152
  | Artifact | Owner | Mandatory |
138
153
  |----------|-------|-----------|
139
- | `chati.dev/artifacts/3-Architecture/architecture.md` | All (consolidated by Manager) | Yes |
154
+ | `chati.dev/artifacts/3-Architecture/system-architecture.md` | System Architect | Yes |
155
+ | `chati.dev/artifacts/3-Architecture/data-architecture.md` | Data Engineer | Yes |
156
+ | `chati.dev/artifacts/3-Architecture/architecture.md` | Manager (consolidated) | Yes |
140
157
 
141
158
  ---
142
159
 
@@ -98,7 +98,9 @@ Output: `chati.dev/artifacts/4-UX/reference-analysis.md`
98
98
  ### Brandbook Outputs
99
99
 
100
100
  Output: `chati.dev/artifacts/4-UX/brandbook.md`
101
- Output: `chati.dev/artifacts/4-UX/brandbook.html` (MANDATORY)
101
+ Output: `chati.dev/artifacts/4-UX/brandbook.html` (MANDATORY — BLOCKS HANDOFF IF MISSING)
102
+
103
+ **CRITICAL: The brandbook.html is NOT optional.** Without it, the brandbook is just text describing colors — the user cannot visually validate the design system. This file MUST be written to disk before self-validation. If you skip it, the handoff WILL fail.
102
104
 
103
105
  The brandbook.html is a standalone visual style guide with all CSS inline.
104
106
  It MUST render all design tokens visually across 14 sections:
@@ -115,6 +117,12 @@ Requirements:
115
117
  - Uses ONLY the design tokens defined in brandbook.md
116
118
  - No emojis, no placeholder content
117
119
 
120
+ **Verification**: After writing, confirm the file exists:
121
+ ```
122
+ ls chati.dev/artifacts/4-UX/brandbook.html
123
+ ```
124
+ If the file does not exist, you have NOT completed this phase. Write it before proceeding.
125
+
118
126
  ---
119
127
 
120
128
  ## Phase 4: Design System Definition
@@ -203,7 +211,7 @@ Hardcoded values are never acceptable, even in prototyping.
203
211
  5. Tokenization coverage >= 95%
204
212
  6. Reference benchmarking completed (5 permanent + user-provided)
205
213
  7. Visual direction unique (font, color, layout archetype differ from references)
206
- 8. Brandbook HTML produced as standalone file with all 14 sections
214
+ 8. **[BLOCKER]** Brandbook HTML file exists at `chati.dev/artifacts/4-UX/brandbook.html` with all 14 sections rendered visually. If this file does not exist on disk, score is capped at 0% regardless of other criteria.
207
215
  9. No placeholders in any output
208
216
 
209
217
  ---
@@ -1,8 +1,8 @@
1
1
  # chati.dev Configuration
2
- version: "4.1.1"
2
+ version: "4.1.3"
3
3
  installed_at: "2026-02-07T10:00:00Z"
4
- updated_at: "2026-04-04T00:00:00Z"
5
- installer_version: "4.1.1"
4
+ updated_at: "2026-04-06T00:00:00Z"
5
+ installer_version: "4.1.3"
6
6
  project_type: greenfield
7
7
  language: en
8
8
  ides: [claude-code]
@@ -276,11 +276,11 @@ The pipeline operates in three execution modes that control agent permissions. M
276
276
 
277
277
  1. The orchestrator SHALL calculate the context bracket (FRESH, MODERATE, DEPLETED, CRITICAL) before every agent interaction.
278
278
 
279
- 2. Context injection layers SHALL be reduced according to bracket level:
280
- - FRESH: All 6 layers (L0-L5)
281
- - MODERATE: L0 + L1 + L2 + L3 + L5 (skip L4 task detail)
282
- - DEPLETED: L0 (Constitution) + L1 (Mode) + L2 (Agent) only
283
- - CRITICAL: L0 (Constitution) + L1 (Mode) only
279
+ 2. Context injection layers SHALL INCREASE as context depletes (Progressive Reinforcement):
280
+ - FRESH: L0 (Constitution) + L1 (Global) only — model has full memory, minimal reinforcement
281
+ - MODERATE: L0 + L1 + L2 (Agent) + L3 (Workflow) model starting to forget
282
+ - DEPLETED: All 6 layers (L0-L5) significant context loss, full reinforcement
283
+ - CRITICAL: All 6 layers (L0-L5) + forced handoff — maximum reinforcement, do not accept degraded output
284
284
 
285
285
  3. Context recovery uses a two-level autonomous strategy:
286
286
  a. Level 1 (Smart Continuation): When context is compacted, the orchestrator SHALL automatically capture a digest, persist memories, and rebuild context post-compact. The user experiences zero interruption.
@@ -424,11 +424,13 @@ The system SHALL support two execution modes that govern the degree of human inv
424
424
  - **brief**: Requirements extraction requires human validation
425
425
  - **orchestrator (deviation protocol)**: Deviations from the plan always need human approval
426
426
 
427
- 5. Safety net triggers SHALL pause autonomous execution when dangerous conditions are detected: consecutive failures, circular approaches, resource limits, or destructive operations.
427
+ 5. **Terminology Note:** "Autonomous" in this article controls WHO evaluates gates (system vs human). Article XVIII's "autonomous" profile controls WHETHER confirmation is required for writes. Both must be satisfied for fully autonomous operation: this article's mode active AND Article XVIII cumulative gate score >= 95%.
428
428
 
429
- 6. Circuit breaker pattern: After 3 consecutive gate failures at the same pipeline point, the system SHALL pause and escalate to human review regardless of mode.
429
+ 6. Safety net triggers SHALL pause autonomous execution when dangerous conditions are detected: consecutive failures, circular approaches, resource limits, or destructive operations.
430
430
 
431
- 7. Mode transitions are logged in session.yaml under `mode_transitions[]` for audit trail.
431
+ 7. Circuit breaker pattern: After 3 consecutive gate failures at the same pipeline point, the system SHALL pause and escalate to human review regardless of mode.
432
+
433
+ 8. Mode transitions are logged in session.yaml under `mode_transitions[]` for audit trail.
432
434
 
433
435
  **Enforcement: STRICT** — Autonomous mode MUST NOT bypass quality gates. All agents MUST respect the configured thresholds.
434
436
 
@@ -487,5 +489,5 @@ When multiple CLI providers are enabled, the system SHALL coordinate agent execu
487
489
 
488
490
  ---
489
491
 
490
- *Chati.dev Constitution v4.1.1 — 19 Articles + Preamble*
492
+ *Chati.dev Constitution v4.1.3 — 19 Articles + Preamble*
491
493
  *All agents are bound by this Constitution. Violations are enforced per article.*
@@ -1,7 +1,7 @@
1
1
  # Chati.dev System Context
2
2
 
3
3
  ## Framework
4
- - **Version**: 4.1.1
4
+ - **Version**: 4.1.3
5
5
  - **Agents**: Specialized agents across DISCOVER, PLAN, BUILD, DEPLOY phases
6
6
  - **Constitution**: 19 Articles + Preamble
7
7
  - **Quality**: 5 pipeline gates + 3-tier verdicts (APPROVED / NEEDS_REVISION / BLOCKED)
@@ -3,8 +3,8 @@
3
3
  # and by the Health Check for system integrity validation.
4
4
 
5
5
  metadata:
6
- version: "4.1.0"
7
- last_updated: "2026-04-02T00:00:00Z"
6
+ version: "4.1.3"
7
+ last_updated: "2026-04-06T00:00:00Z"
8
8
  entity_count: 62
9
9
  checksum_algorithm: sha256
10
10
 
@@ -79,10 +79,10 @@ modes:
79
79
 
80
80
  brackets:
81
81
  FRESH:
82
- behavior: "Moderate context injection. All layers active but model is warming up. Budget lower than MODERATE."
82
+ behavior: "Minimal reinforcement. L0+L1 only. Model has full memory, no need to re-inject context."
83
83
  MODERATE:
84
- behavior: "Peak context injection. Maximum token budget. Model has context and needs maximum reinforcement."
84
+ behavior: "Growing reinforcement. L0-L3 active. Model starting to forget initial instructions."
85
85
  DEPLETED:
86
- behavior: "Reduced injection. Only L0+L1+L2. Use rule IDs instead of full text."
86
+ behavior: "Full reinforcement. All 6 layers (L0-L5) active. Significant context loss, compensate with maximum injection."
87
87
  CRITICAL:
88
- behavior: "Emergency. L0+L1 only. Trigger handoff advisory. Preserve essential state."
88
+ behavior: "Emergency reinforcement. All 6 layers (L0-L5) active. Trigger handoff. Do not accept degraded output."
@@ -140,7 +140,7 @@ const SHELL_INJECTION_CHECKS = [
140
140
  { id: 'JQ_SYSTEM_FUNCTION', pattern: /jq\b.*\bsystem\s*\(/i, severity: 'critical' },
141
141
  { id: 'JQ_FILE_ARGUMENTS', pattern: /jq\b.*--from-file|jq\b.*-f\s+[^|&;]+/i, severity: 'high' },
142
142
  { id: 'OBFUSCATED_FLAGS', pattern: /\$[({].*[)}].*-/, severity: 'high' },
143
- { id: 'SHELL_METACHARACTERS', pattern: /[`]|(?:\$\((?!.*\becho\b))/, severity: 'critical' },
143
+ { id: 'SHELL_METACHARACTERS', pattern: /[`]|\$\(/, severity: 'critical' },
144
144
  { id: 'DANGEROUS_VARIABLES', pattern: /(?:^|\s)(?:PATH|LD_PRELOAD|LD_LIBRARY_PATH|DYLD_INSERT_LIBRARIES|PYTHONPATH|NODE_PATH|RUBYLIB|PERL5LIB)\s*=/, severity: 'critical' },
145
145
  { id: 'NEWLINES', pattern: /(?<!\\)\n.*(?:rm|curl|wget|chmod|chown|sudo|eval|exec)/, severity: 'high' },
146
146
  { id: 'BACKSLASH_ESCAPED_WHITESPACE', pattern: /\\\s+(?:-|\/)/,severity: 'medium' },
@@ -79,16 +79,17 @@ async function main() {
79
79
  return 200_000;
80
80
  }
81
81
 
82
+ // Primary: turn-count tracks cumulative context consumption across the session.
83
+ // Fallback: prompt-length for first turn or missing session data.
82
84
  let remainingPercent;
83
- const promptText = event.prompt || '';
84
- if (promptText.length > 0) {
85
+ const maxTurns = 40;
86
+ if (session.turnCount > 0) {
87
+ remainingPercent = Math.max(0, Math.round((1 - session.turnCount / maxTurns) * 100));
88
+ } else {
89
+ const promptText = event.prompt || '';
85
90
  const estimatedTokens = Math.ceil(promptText.length / 4);
86
91
  const contextLimit = hookResolveLimit(inferredModel, session.provider);
87
92
  remainingPercent = Math.max(0, Math.round((1 - estimatedTokens / contextLimit) * 100));
88
- } else {
89
- // Fallback to turn-count heuristic when prompt text unavailable
90
- const maxTurns = 40;
91
- remainingPercent = Math.max(0, Math.round((1 - session.turnCount / maxTurns) * 100));
92
93
  }
93
94
 
94
95
  // Determine bracket
@@ -12,10 +12,10 @@ Four brackets define behavior based on remaining context:
12
12
 
13
13
  | Bracket | Context Remaining | Behavior |
14
14
  |---------|-------------------|----------|
15
- | **FRESH** | 60-100% | All 6 layers active. Minimal reinforcement (1.5%) — context is plentiful. No memory injection. |
16
- | **MODERATE** | 40-60% | 5 layers (skip L4). Growing reinforcement (2.5%) — model starting to forget. Metadata memory. |
17
- | **DEPLETED** | 25-40% | 3 layers (L0-L2). Heavy reinforcement (4.0%) — significant context loss. Chunk memory recovery. |
18
- | **CRITICAL** | <25% | 2 layers (L0-L1). Maximum reinforcement (5.0%) — last interactions before handoff. Full memory dump. |
15
+ | **FRESH** | 60-100% | 2 layers (L0-L1). Minimal reinforcement (1.5%) — model has full memory, no need to re-inject. |
16
+ | **MODERATE** | 40-60% | 4 layers (L0-L3). Growing reinforcement (2.5%) — model starting to forget. |
17
+ | **DEPLETED** | 25-40% | All 6 layers (L0-L5). Heavy reinforcement (4.0%) — significant context loss, full re-injection. |
18
+ | **CRITICAL** | <25% | All 6 layers (L0-L5). Maximum reinforcement (5.0%) — forced handoff, do not accept degraded output. |
19
19
 
20
20
  ### Static/Dynamic PRISM Boundary
21
21
 
@@ -38,18 +38,18 @@ The orchestrator injects context through 6 hierarchical layers:
38
38
  | **L2** | Agent Scope | `chati.dev/agents/{agent}/` — mission, inputs, outputs, criteria | When agent is active |
39
39
  | **L3** | Pipeline State | `.chati/session.yaml` — pipeline position, scores, backlog | When session is active |
40
40
  | **L4** | Task Context | Active artifact + previous agent's handoff | When task is active |
41
- | **L5** | Keywords | `chati.dev/domains/keywords/` — dynamic rules from user prompt | FRESH + MODERATE only |
41
+ | **L5** | Keywords | `chati.dev/domains/keywords/` — dynamic rules from user prompt | DEPLETED + CRITICAL only |
42
42
 
43
43
  ### Layer Activation by Bracket
44
44
 
45
45
  | Bracket | Active Layers | Budget Ratio | Claude (200K) | Gemini (1M) | Codex (128K) |
46
46
  |---------|--------------|-------------|---------------|-------------|--------------|
47
- | FRESH | L0, L1, L2, L3, L4, L5 | 1.5% | 3,000 | 15,000 | 1,920 |
48
- | MODERATE | L0, L1, L2, L3, L5 | 2.5% | 5,000 | 25,000 | 3,200 |
49
- | DEPLETED | L0, L1, L2 | 4.0% | 8,000 | 40,000 | 5,120 |
50
- | CRITICAL | L0, L1 | 5.0% | 10,000 | 50,000 | 6,400 |
47
+ | FRESH | L0, L1 | 1.5% | 3,000 | 15,000 | 1,920 |
48
+ | MODERATE | L0, L1, L2, L3 | 2.5% | 5,000 | 25,000 | 3,200 |
49
+ | DEPLETED | L0, L1, L2, L3, L4, L5 | 4.0% | 8,000 | 40,000 | 5,120 |
50
+ | CRITICAL | L0, L1, L2, L3, L4, L5 | 5.0% | 10,000 | 50,000 | 6,400 |
51
51
 
52
- Budgets are proportional to the provider's context window. As context degrades, fewer layers are active (focus) but each active layer receives MORE reinforcement tokens (strength).
52
+ Progressive Reinforcement: as context depletes, BOTH budget AND layers increase. The model forgets initial instructions and needs more reinforcement, not less.
53
53
 
54
54
  ---
55
55
 
@@ -182,7 +182,7 @@ Memory injection follows the same progressive reinforcement principle: as contex
182
182
 
183
183
  ## Constitution Reference
184
184
 
185
- **Article XII: Context Bracket Governance** — Brackets are calculated automatically. In CRITICAL, only L0+L1 are injected. Handoff is mandatory when context < 15%.
185
+ **Article XII: Context Bracket Governance** — Brackets are calculated automatically. In CRITICAL, all 6 layers (L0-L5) are injected for maximum reinforcement. Handoff is mandatory when context < 15%.
186
186
 
187
187
  ---
188
188
 
@@ -0,0 +1,321 @@
1
+ # /chati-update — Evolution Advisor with Self-Validated Implementation
2
+
3
+ You are the **Chati Update Agent**, a specialized evolution advisor for the chati.dev framework. Your mission is to analyze an external repo/project, perform exhaustive cross-comparison with chati.dev's current state, propose improvements, and implement approved changes with ralph-wiggum self-validation at 95% threshold.
4
+
5
+ **Input:** $ARGUMENTS (path to local repo OR GitHub URL)
6
+
7
+ ---
8
+
9
+ ## CRITICAL RULES
10
+
11
+ 1. **NEVER copy blindly** — Adapt concepts to chati.dev's identity and patterns
12
+ 2. **NEVER break existing tests** — All 989+ tests must continue passing
13
+ 3. **NEVER violate the constitution** — 19 articles are sacred
14
+ 4. **NEVER skip comparison** — Every finding MUST be validated against current state
15
+ 5. **ALWAYS present options** — Numbered 1, 2, 3 format before any implementation
16
+ 6. **ALWAYS use sub-agents** — Parallelize SCAN and COMPARE for throughput
17
+ 7. **ORIGINALITY 100%** — Zero copies, zero external framework references in code/docs
18
+
19
+ ---
20
+
21
+ ## Phase 0: PREPARE — Resolve Input
22
+
23
+ ```
24
+ IF $ARGUMENTS is empty:
25
+ → Ask user: "Which repo do you want me to analyze? Provide a local path or GitHub URL."
26
+ → STOP and wait
27
+
28
+ IF $ARGUMENTS is a GitHub URL (https://github.com/...):
29
+ → Clone to /tmp/chati-update-ref/ using: git clone --depth 1 <URL> /tmp/chati-update-ref
30
+ → Set REF_PATH = /tmp/chati-update-ref
31
+
32
+ IF $ARGUMENTS is a local path:
33
+ → Verify path exists
34
+ → Set REF_PATH = $ARGUMENTS
35
+
36
+ IF $ARGUMENTS is a GitHub shorthand (owner/repo):
37
+ → Clone to /tmp/chati-update-ref/ using: git clone --depth 1 https://github.com/$ARGUMENTS /tmp/chati-update-ref
38
+ → Set REF_PATH = /tmp/chati-update-ref
39
+ ```
40
+
41
+ ---
42
+
43
+ ## Phase 1: SCAN — Deep Analysis of Reference Repo (Sub-Agent)
44
+
45
+ Launch a **Task agent (subagent_type=Explore, thoroughness=very thorough)** to analyze the reference repo at REF_PATH.
46
+
47
+ ### SCAN Agent Instructions:
48
+
49
+ ```
50
+ Analyze the repo at <REF_PATH> exhaustively. You must produce a comprehensive report covering:
51
+
52
+ 1. **PROJECT OVERVIEW**
53
+ - What does this project do?
54
+ - Tech stack, language, framework
55
+ - Project maturity (commits, stars, contributors if visible)
56
+ - License
57
+
58
+ 2. **ARCHITECTURE PATTERNS**
59
+ - Folder structure and organization philosophy
60
+ - Module/plugin/agent system (if any)
61
+ - Configuration patterns (YAML, JSON, env)
62
+ - CLI patterns and entry points
63
+
64
+ 3. **INTERESTING CONCEPTS** (the gold — be thorough)
65
+ - Novel patterns not commonly seen
66
+ - Quality gates, validation systems
67
+ - Context management strategies
68
+ - Agent/AI orchestration patterns
69
+ - Pipeline/workflow patterns
70
+ - Memory/state management
71
+ - Error handling patterns
72
+ - Testing strategies
73
+ - Documentation patterns
74
+ - Hook/plugin systems
75
+ - CI/CD patterns
76
+
77
+ 4. **CODE QUALITY SIGNALS**
78
+ - Test coverage approach
79
+ - Linting/formatting standards
80
+ - Type safety patterns
81
+ - Security patterns
82
+
83
+ 5. **SPECIFIC ARTIFACTS** — For each interesting file/pattern:
84
+ - File path
85
+ - What it does
86
+ - Why it's interesting
87
+ - Key code snippets (actual content, not summaries)
88
+
89
+ Be EXHAUSTIVE. Read every important file. Don't summarize — extract actual patterns with code.
90
+ Minimum 30 files analyzed. No laziness.
91
+ ```
92
+
93
+ ---
94
+
95
+ ## Phase 2: COMPARE — Cross-Reference with Chati.dev (Sub-Agent)
96
+
97
+ Launch **in parallel** with Phase 1 a **Task agent (subagent_type=Explore, thoroughness=very thorough)** to map chati.dev's current state.
98
+
99
+ ### COMPARE Baseline Agent Instructions:
100
+
101
+ ```
102
+ Map the COMPLETE current state of chati.dev. Analyze:
103
+
104
+ 1. **CONSTITUTION** — Read chati.dev/constitution.md fully. Extract:
105
+ - All 19 articles with key rules
106
+ - Quality thresholds
107
+ - Governance patterns
108
+
109
+ 2. **ALL AGENTS** — Read every file in chati.dev/agents/**/*.md:
110
+ - Agent identity, role, pipeline position
111
+ - Input/output contracts
112
+ - Acceptance criteria
113
+ - Key patterns each agent uses
114
+
115
+ 3. **ORCHESTRATOR** — Read chati.dev/orchestrator/chati.md fully:
116
+ - Routing logic
117
+ - Session management
118
+ - Deviation handling
119
+
120
+ 4. **WORKFLOWS** — Read chati.dev/workflows/*.yaml:
121
+ - Workflow definitions
122
+ - Step sequences
123
+ - Gate conditions
124
+
125
+ 5. **SCHEMAS** — Read chati.dev/schemas/*.json:
126
+ - Session schema
127
+ - Handoff schema
128
+ - Config schema
129
+
130
+ 6. **HOOKS** — Read packages/chati-dev/src/**/*:
131
+ - All 6 hooks
132
+ - PRISM engine
133
+ - Mode governance
134
+ - Build loop / autonomy system
135
+
136
+ 7. **TESTS** — Map test structure:
137
+ - Test organization
138
+ - Coverage patterns
139
+ - Key test utilities
140
+
141
+ 8. **CONFIG** — Read chati.dev/config.yaml, package.json:
142
+ - Version info
143
+ - Dependencies
144
+ - Scripts
145
+
146
+ Produce a COMPLETE inventory. Every file, every pattern, every decision.
147
+ This is the baseline for comparison. Be thorough.
148
+ ```
149
+
150
+ ---
151
+
152
+ ## Phase 3: CROSS-ANALYZE — Merge Findings
153
+
154
+ Once both sub-agents complete, YOU (main agent) perform the cross-analysis:
155
+
156
+ ### For EACH finding from the SCAN:
157
+
158
+ ```yaml
159
+ finding: <name>
160
+ source_repo: <file path in reference repo>
161
+ category: architecture | quality | testing | docs | patterns | tooling | governance
162
+ classification: ADOPT | ADAPT | IGNORE | ALREADY_EXISTS
163
+ reasoning: <why this classification>
164
+ chati_equivalent: <existing chati.dev file/pattern if any, or "none">
165
+ impact: high | medium | low
166
+ effort: high | medium | low
167
+ priority_score: <impact * inverse_effort, 1-10>
168
+ implementation_notes: <how to implement in chati.dev context>
169
+ constitution_check: <which articles are relevant, any conflicts>
170
+ ```
171
+
172
+ ### Classification Rules:
173
+ - **ADOPT**: Novel concept, no equivalent in chati.dev, high value, no conflicts
174
+ - **ADAPT**: Similar concept exists but reference has better implementation
175
+ - **IGNORE**: Not relevant, conflicts with constitution, or low value
176
+ - **ALREADY_EXISTS**: Chati.dev already has this (possibly better)
177
+
178
+ ---
179
+
180
+ ## Phase 4: PROPOSE — Present to User
181
+
182
+ Generate a structured report for the user:
183
+
184
+ ```markdown
185
+ # Chati Update Report: <repo-name>
186
+
187
+ ## Summary
188
+ - Findings analyzed: N
189
+ - ADOPT: N items
190
+ - ADAPT: N items
191
+ - ALREADY_EXISTS: N items
192
+ - IGNORE: N items
193
+
194
+ ## Recommendations (sorted by priority_score desc)
195
+
196
+ ### ADOPT — New Concepts Worth Adding
197
+
198
+ 1. **<Finding Name>** (Priority: X/10)
199
+ - **What**: <description>
200
+ - **Why**: <value to chati.dev>
201
+ - **Where**: <which chati.dev files would change>
202
+ - **Effort**: <high/medium/low>
203
+ - **Constitution**: <compatible with articles X, Y>
204
+
205
+ 2. ...
206
+
207
+ ### ADAPT — Existing Concepts Worth Improving
208
+
209
+ 1. **<Finding Name>** (Priority: X/10)
210
+ - **Current**: <how chati.dev does it today>
211
+ - **Improvement**: <what the reference does better>
212
+ - **Where**: <which files to modify>
213
+ - **Effort**: <high/medium/low>
214
+
215
+ 2. ...
216
+
217
+ ### ALREADY_EXISTS — Chati.dev Already Has This
218
+ (brief list for transparency)
219
+
220
+ ### IGNORE — Not Applicable
221
+ (brief list with reasons)
222
+ ```
223
+
224
+ Then ask the user:
225
+ > "Which items do you want me to implement? Give me the numbers (e.g., 'ADOPT 1, 3' and 'ADAPT 2') or say 'all ADOPT' / 'all'."
226
+
227
+ ---
228
+
229
+ ## Phase 5: APPLY + RALPH — Self-Validated Implementation
230
+
231
+ For the approved changes, enter ralph-wiggum mode:
232
+
233
+ ### Pre-Ralph Checklist:
234
+ 1. Run current tests: `npm test` — record baseline (must be green)
235
+ 2. Run lint: `npm run lint` — record baseline
236
+ 3. Git status — ensure clean working directory
237
+ 4. Create branch: `git checkout -b chati-update/<repo-name>-<date>`
238
+
239
+ ### Ralph Loop Activation:
240
+
241
+ Use `/ralph-loop` with the following prompt structure:
242
+
243
+ ```
244
+ /ralph-loop "Implement the following approved chati-update changes:
245
+
246
+ <LIST OF APPROVED CHANGES WITH FULL DETAILS>
247
+
248
+ REQUIREMENTS:
249
+ 1. Implement each change following chati.dev patterns and conventions
250
+ 2. Respect the constitution (19 articles) — especially originality
251
+ 3. Update relevant tests for each change
252
+ 4. Run full test suite after each change — ALL must pass
253
+ 5. Run lint after each change — must be clean
254
+ 6. Validate against constitution rules
255
+ 7. Each change must score >= 95% on self-validation
256
+
257
+ SELF-VALIDATION CHECKLIST (must ALL be true):
258
+ - [ ] All existing tests pass (989+)
259
+ - [ ] New tests added for new functionality
260
+ - [ ] Lint passes with zero errors
261
+ - [ ] No external framework references (originality 100%)
262
+ - [ ] Constitution articles respected
263
+ - [ ] No regressions in any agent definitions
264
+ - [ ] Handoff format maintained
265
+ - [ ] PRISM layers intact
266
+ - [ ] Config/schemas updated if needed
267
+ - [ ] CHANGELOG updated
268
+
269
+ When ALL items are validated at >= 95%, output:
270
+ <promise>ALL CHANGES VALIDATED AT 95%</promise>" --completion-promise "ALL CHANGES VALIDATED AT 95%" --max-iterations 15
271
+ ```
272
+
273
+ ---
274
+
275
+ ## Phase 6: REPORT — Final Summary
276
+
277
+ After ralph-wiggum completes, generate final report:
278
+
279
+ ```markdown
280
+ # Chati Update Complete
281
+
282
+ ## Changes Applied
283
+ - <list of implemented changes with file paths>
284
+
285
+ ## Validation Results
286
+ - Tests: X passing (was Y before)
287
+ - Lint: clean
288
+ - Constitution: no violations
289
+ - Self-validation score: X%
290
+
291
+ ## Files Modified
292
+ - <file list with brief description of changes>
293
+
294
+ ## Files Created
295
+ - <if any>
296
+
297
+ ## Next Steps
298
+ - <any follow-up recommendations>
299
+ ```
300
+
301
+ ---
302
+
303
+ ## Error Handling
304
+
305
+ - **Clone fails**: Ask user for correct URL/path, suggest alternatives
306
+ - **Tests fail at baseline**: STOP — do not proceed with changes on a broken baseline. Report to user.
307
+ - **Ralph stuck (> 10 iterations without progress)**: Break loop, report what was achieved, ask user for guidance
308
+ - **Constitution conflict detected**: STOP that specific change, report conflict, ask user for deviation approval
309
+ - **Sub-agent returns incomplete data**: Re-run that specific sub-agent with more specific instructions
310
+
311
+ ---
312
+
313
+ ## Anti-Patterns (NEVER do these)
314
+
315
+ - Don't copy code verbatim from reference repo
316
+ - Don't rename chati.dev concepts to match reference repo naming
317
+ - Don't add dependencies from reference repo without explicit approval
318
+ - Don't modify the constitution
319
+ - Don't skip the comparison phase ("it looks good, let's just add it")
320
+ - Don't implement without user approval of the proposal
321
+ - Don't rush — thoroughness > speed
@@ -94,51 +94,40 @@ CRITICAL → "Context: CRITICAL ({remaining}%) — Initiating handoff protocol"
94
94
 
95
95
  ## Action: Setup
96
96
 
97
- The user is starting a new project.
97
+ The user is starting a new project. The orchestrator handles all setup decisions automatically — the user should NOT be asked to choose workflows, pipelines, or technical options. They just describe what they want to build.
98
98
 
99
- ### Quick Flow Auto-Detection
99
+ ### Automatic Detection
100
100
 
101
- Before asking for workflow, check if this is a quick-flow candidate:
102
- ```
103
- Run: node packages/chati-dev/bin/chati.js orchestrate detect-flow --message "{user_first_message}"
104
- ```
105
-
106
- If `recommended` is `quick` (confidence >= 0.8):
107
- → Present: "This looks like a quick task. I can use Quick Flow (fast-track):
108
- Brief (quick) → Dev → QA → Deploy
109
- 1. Use Quick Flow (Recommended)
110
- 2. Use full pipeline instead"
111
-
112
- If `recommended` is `standard`:
113
- → Present: "This looks like a medium feature. Standard Flow recommended:
114
- Brief → Detail → Architect → Tasks → QA-Planning → Dev → QA → Deploy
115
- 1. Use Standard Flow (Recommended)
116
- 2. Use full pipeline instead"
117
-
118
- ### Project Setup
119
-
120
- 1. **Project type**: Does an existing codebase exist?
101
+ 1. **Project type**: Detect automatically.
121
102
  - Check for `package.json`, `src/`, `.git`, etc.
122
103
  - If exists → `brownfield`. If not → `greenfield`.
123
- - If ambiguous, ask: "Is this a new project or an existing one?"
104
+ - Only ask if truly ambiguous (no signals at all).
124
105
 
125
106
  2. **Language**: Detect from user's message language.
126
107
  - Supported: `en`, `pt`, `es`, `fr`. Default: `en`.
127
108
 
128
- 3. **Workflow**: Use auto-detected or ask user:
109
+ 3. **Workflow**: Decide automatically based on context. NEVER present workflow options to the user.
129
110
  ```
130
- 1. Full Pipeline (Recommended for new features, greenfield)
131
- 2. Quick Flow (Bug fixes, small changes, hotfixes)
132
- 3. Standard Flow (Medium features, no UX/architecture needed)
111
+ Run: node packages/chati-dev/bin/chati.js orchestrate detect-flow --message "{user_first_message}"
133
112
  ```
113
+ Use the `recommended` field directly:
114
+ - `quick` (confidence >= 0.8) → workflow = `quick`
115
+ - `standard` (confidence >= 0.8) → workflow = `standard`
116
+ - Otherwise → workflow = `full`
117
+
118
+ 4. **Project name**: Extract from user's message or directory name. Only ask if undetectable.
119
+
120
+ ### Initialize
134
121
 
135
- Then run via Bash:
122
+ Run via Bash:
136
123
  ```
137
- node packages/chati-dev/bin/chati.js orchestrate init --type greenfield --language pt --name "project-name" --workflow full
124
+ node packages/chati-dev/bin/chati.js orchestrate init --type {detected_type} --language {detected_lang} --name "{detected_name}" --workflow {detected_workflow}
138
125
  ```
139
126
 
140
127
  Parse JSON → read `first_agent_file` → activate that agent immediately (go to **Action: Interactive Agent**).
141
128
 
129
+ The user should experience a smooth start: they describe their project, the orchestrator confirms what it detected, and the first agent begins immediately.
130
+
142
131
  ---
143
132
 
144
133
  ## Action: Interactive Agent
@@ -154,11 +143,61 @@ These agents (greenfield-wu, brownfield-wu, brief) run in the same conversation.
154
143
  3. Load its full content and **become** that agent
155
144
  4. Follow the agent's instructions — the user interacts with you directly
156
145
  5. When the agent completes its work and self-validates, extract the score
157
- 6. Run via Bash:
146
+ 6. Present **Completion Options** (see below) — wait for user choice before advancing
147
+ 7. On user approval, run via Bash:
158
148
  ```
159
149
  node packages/chati-dev/bin/chati.js orchestrate advance --agent {name} --score {score}
160
150
  ```
161
- 7. Parse JSON → the `next` field contains the next action → follow it
151
+ 8. Parse JSON → the `next` field contains the next action → follow it
152
+
153
+ ---
154
+
155
+ ## Completion Options (Protocol 3 — Guided Options)
156
+
157
+ After EVERY agent completes (interactive or autonomous), present exactly 3 numbered options. The user should never have to figure out "what now" — always offer clear next steps with a recommendation.
158
+
159
+ ### Standard Completion (score >= threshold)
160
+ ```
161
+ {agent} completed with score {score}%.
162
+
163
+ 1. Approve and continue to {next_agent} (Recommended)
164
+ 2. Review the artifacts before proceeding
165
+ 3. Revise — go back and adjust specific points
166
+ ```
167
+
168
+ ### Low Score Completion (score < threshold but not blocking)
169
+ ```
170
+ {agent} completed with score {score}% (below {threshold}% threshold).
171
+
172
+ 1. Revise — re-run {agent} to improve quality (Recommended)
173
+ 2. Approve anyway and continue to {next_agent}
174
+ 3. Review the artifacts and decide
175
+ ```
176
+
177
+ ### Parallel Group Completion
178
+ ```
179
+ Parallel group completed: {agents with scores}.
180
+
181
+ 1. Approve all and continue to {next_agent} (Recommended)
182
+ 2. Review artifacts from a specific agent
183
+ 3. Re-run a specific agent for improvements
184
+ ```
185
+
186
+ ### Pipeline Milestone (after QA-Planning or QA-Implementation)
187
+ ```
188
+ Quality gate passed: {score}%.
189
+
190
+ 1. Approve and advance to {next_phase} (Recommended)
191
+ 2. View detailed QA report
192
+ 3. Request additional review on specific areas
193
+ ```
194
+
195
+ **Rules:**
196
+ - ALWAYS present options — never leave the user without a clear next step
197
+ - ALWAYS mark one option as "(Recommended)"
198
+ - User can respond with just the number (1, 2, or 3)
199
+ - If user responds with free text instead of a number, interpret their intent and act accordingly
200
+ - Keep options in the user's language
162
201
 
163
202
  ---
164
203
 
@@ -179,7 +218,7 @@ These agents run in separate Claude Code processes.
179
218
  - If `true`: display "Context check: OK — handoff verified"
180
219
  3. Execute `spawn_command` via Bash tool (the full command is in the JSON)
181
220
  4. Wait for JSON output from the spawned process. Handle `status`:
182
- - `"complete"` → Run `orchestrate advance --agent {name} --score {score}`
221
+ - `"complete"` → Present **Completion Options** (see above) → on approval, run `orchestrate advance --agent {name} --score {score}`
183
222
  - `"needs_input"` → Read `needs_input_question`, present to user in their language, then re-run spawn with `--additional-context "{user_response}"` (max 3 relay cycles)
184
223
  - `"error"` → Apply Recovery Protocol (see below)
185
224
 
@@ -201,8 +240,9 @@ Planning phase agents (detail, architect, ux) run simultaneously.
201
240
  1. Display: "Spawning parallel group: {agents}"
202
241
  2. Execute `parallel_spawn_command` via Bash tool
203
242
  3. Parse consolidated JSON output
204
- 4. For each completed agent, run `orchestrate advance --agent {name} --score {score}`
205
- 5. If partial failure:
243
+ 4. Present **Completion Options** (Parallel Group variant) wait for user choice
244
+ 5. On approval, for each completed agent, run `orchestrate advance --agent {name} --score {score}`
245
+ 6. If partial failure:
206
246
  ```
207
247
  1. Retry failed agents only
208
248
  2. Continue with partial results
@@ -389,6 +429,8 @@ interactive (default):
389
429
  → All 8 universal protocols apply.
390
430
 
391
431
  autonomous (Ralph Wiggum mode):
432
+ → Requires: most recent QA gate score >= 95% (Article XVIII prerequisite).
433
+ → If quality gate not met, inform user and suggest guided mode instead.
392
434
  → Agent executes without asking unless blocker encountered.
393
435
  → Primarily for Dev agent during BUILD phase.
394
436
  → QA gates always run regardless of mode.
@@ -19,7 +19,7 @@
19
19
  },
20
20
  "agent": {
21
21
  "type": "object",
22
- "description": "Active agent scope information (L2 layer, active when bracket >= DEPLETED)",
22
+ "description": "Active agent scope information (L2 layer, active when bracket >= MODERATE)",
23
23
  "required": ["name", "mission"],
24
24
  "properties": {
25
25
  "name": { "type": "string", "description": "Agent identifier" },
@@ -32,14 +32,15 @@
32
32
  "pipeline": {
33
33
  "type": "string",
34
34
  "description": "Pipeline state string showing agent progression (L3 layer, active when bracket >= MODERATE)"
35
+
35
36
  },
36
37
  "task": {
37
38
  "type": "string",
38
- "description": "Current task description (L4 layer, active when bracket >= MODERATE)"
39
+ "description": "Current task description (L4 layer, active when bracket = DEPLETED or CRITICAL)"
39
40
  },
40
41
  "handoff": {
41
42
  "type": "object",
42
- "description": "Previous agent handoff summary (L4 layer, active when bracket >= MODERATE)",
43
+ "description": "Previous agent handoff summary (L4 layer, active when bracket = DEPLETED or CRITICAL)",
43
44
  "properties": {
44
45
  "from": { "type": "string", "description": "Source agent name" },
45
46
  "score": { "type": "number", "minimum": 0, "maximum": 100, "description": "Source agent final score" },
@@ -83,7 +84,7 @@
83
84
  "injection_budget": {
84
85
  "type": "integer",
85
86
  "minimum": 0,
86
- "description": "Token budget for context injection (FRESH: 2500, MODERATE: 2000, DEPLETED: 1500, CRITICAL: 800)"
87
+ "description": "Token budget for context injection — Progressive Reinforcement: FRESH 1.5%, MODERATE 2.5%, DEPLETED 4.0%, CRITICAL 5.0% of provider context window"
87
88
  }
88
89
  }
89
90
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "chati-dev",
3
- "version": "4.1.1",
3
+ "version": "4.1.3",
4
4
  "description": "AI-Powered Multi-Agent Orchestration System — Structured vibe coding for Full Stack Development",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,21 +1,20 @@
1
1
  /**
2
2
  * Bracket Tracker — Pure arithmetic for context window management.
3
3
  *
4
- * Brackets determine how much context to inject:
5
- * FRESH (60-100%) → All 6 layers active (L0-L5)
6
- * MODERATE (40-60%) → L0 + L1 + L2 + L3 + L5 (skip L4 task detail)
7
- * DEPLETED (25-40%) → L0 + L1 + L2 only
8
- * CRITICAL (<25%) → L0 + L1 only (handoff mandatory)
4
+ * Brackets determine how much context to inject (Progressive Reinforcement):
5
+ * FRESH (60-100%) → L0 + L1 only (model has full memory, minimal reinforcement)
6
+ * MODERATE (40-60%) → L0 + L1 + L2 + L3 (model starting to forget)
7
+ * DEPLETED (25-40%) → All 6 layers L0-L5 (significant context loss, full reinforcement)
8
+ * CRITICAL (<25%) → All 6 layers L0-L5 + handoff mandatory (maximum reinforcement)
9
9
  *
10
- * Progressive Reinforcement Model (v4.0):
11
- * As context window depletes, the model forgets initial instructions
12
- * and needs MORE reinforcement, not less. Budget expressed as percentage
13
- * of the provider's total context window — proportional across providers.
10
+ * Progressive Reinforcement Model (v4.1.2):
11
+ * As context depletes, BOTH budget AND layers INCREASE.
12
+ * The model forgets initial instructions and needs MORE reinforcement.
14
13
  *
15
- * FRESH = 1.5% minimal reinforcement (context is plentiful)
16
- * MODERATE = 2.5% → growing reinforcement (model starting to forget)
17
- * DEPLETED = 4.0% → heavy reinforcement (significant context loss)
18
- * CRITICAL = 5.0% → maximum reinforcement (last interactions before handoff)
14
+ * FRESH = 1.5% budget, 2 layers context intact, no need to re-inject
15
+ * MODERATE = 2.5% budget, 4 layers → growing reinforcement
16
+ * DEPLETED = 4.0% budget, 6 layers full layer injection to compensate loss
17
+ * CRITICAL = 5.0% budget, 6 layers → maximum reinforcement + forced handoff
19
18
  */
20
19
 
21
20
  import { resolveContextLimit } from '../utils/provider-limits.js';
@@ -54,8 +54,9 @@ export function formatContext(options) {
54
54
 
55
55
  // Insert STATIC_BOUNDARY between static (L0+L1) and dynamic (L2-L5) sections.
56
56
  // This enables prompt cache reuse for the stable prefix (Claude Code pattern).
57
- const staticSections = sections.slice(0, l1 ? 2 : (l0 ? 1 : 0));
58
- const dynamicSections = sections.slice(staticSections.length);
57
+ const staticCount = l1 ? 2 : (l0 ? 1 : 0);
58
+ const staticSections = sections.slice(0, staticCount);
59
+ const dynamicSections = sections.slice(staticCount);
59
60
 
60
61
  let body;
61
62
  if (dynamicSections.length > 0) {
@@ -69,7 +70,7 @@ export function formatContext(options) {
69
70
  // Truncate if over budget (rough estimate: 1 token ≈ 4 chars)
70
71
  const maxChars = tokenBudget * 4;
71
72
  if (body.length > maxChars) {
72
- body = truncateByPriority(sections, maxChars);
73
+ body = truncateByPriority(sections, maxChars, staticCount);
73
74
  }
74
75
 
75
76
  return `<chati-context bracket="${bracket}">\n${body}\n</chati-context>`;
@@ -190,14 +191,28 @@ function formatKeywords(l5) {
190
191
  * Truncate sections by removing lower-priority layers first (L4 → L3 → L2).
191
192
  * L0 and L1 are never truncated.
192
193
  */
193
- function truncateByPriority(sections, maxChars) {
194
- let result = sections.join('\n\n');
195
- // Remove from end (lowest priority) until within budget
194
+ function truncateByPriority(sections, maxChars, staticCount = 2) {
195
+ const boundaryMarker = '\n\n <!-- STATIC_BOUNDARY -->\n\n';
196
196
  const trimmed = [...sections];
197
- while (trimmed.length > 2 && result.length > maxChars) {
197
+ const hasDynamic = () => trimmed.length > staticCount;
198
+ const overhead = hasDynamic() ? boundaryMarker.length : 0;
199
+ const adjustedMax = maxChars - overhead;
200
+
201
+ // Remove from end (lowest priority) until within budget
202
+ while (trimmed.length > staticCount && trimmed.join('\n\n').length > adjustedMax) {
198
203
  trimmed.pop();
204
+ }
205
+
206
+ // Re-insert boundary if we still have both static and dynamic sections
207
+ let result;
208
+ if (hasDynamic()) {
209
+ result = trimmed.slice(0, staticCount).join('\n\n') +
210
+ boundaryMarker +
211
+ trimmed.slice(staticCount).join('\n\n');
212
+ } else {
199
213
  result = trimmed.join('\n\n');
200
214
  }
215
+
201
216
  // If still over, hard truncate
202
217
  if (result.length > maxChars) {
203
218
  result = result.slice(0, maxChars) + '\n <!-- truncated -->';
@@ -6,7 +6,7 @@
6
6
  * L0-L4 handle WHO (agent) and WHERE (workflow/task)
7
7
  * L5 handles WHAT (topic detection from user prompt)
8
8
  *
9
- * Only active in FRESH and MODERATE brackets (expensive layer).
9
+ * Only active in DEPLETED and CRITICAL brackets (reinforcement layer).
10
10
  */
11
11
 
12
12
  import { loadKeywordDomains } from '../domain-loader.js';
@@ -45,6 +45,14 @@ export function runDreamConsolidation(projectDir) {
45
45
  // Phase 4: Prune
46
46
  report.phase4 = prune(projectDir, report.phase3.consolidated);
47
47
 
48
+ // Write consolidated memories to disk
49
+ try {
50
+ const sharedDir = join(projectDir, '.chati', 'memories', 'shared');
51
+ mkdirSync(sharedDir, { recursive: true });
52
+ const consolidatedPath = join(sharedDir, 'consolidated.json');
53
+ writeFileSync(consolidatedPath, JSON.stringify(report.phase4.entries, null, 2), 'utf-8');
54
+ } catch (err) { process.stderr.write(`[chati] dream write consolidated: ${err.message}\n`); }
55
+
48
56
  // Summary
49
57
  report.summary = {
50
58
  merged: report.phase3.mergedCount,
@@ -198,6 +206,7 @@ function prune(projectDir, consolidated) {
198
206
  prunedCount: 0,
199
207
  archivedCount: 0,
200
208
  remaining: consolidated.length,
209
+ entries: consolidated,
201
210
  };
202
211
  }
203
212
 
@@ -238,6 +247,7 @@ function prune(projectDir, consolidated) {
238
247
  prunedCount: toRemove.length,
239
248
  archivedCount,
240
249
  remaining: toKeep.length,
250
+ entries: toKeep,
241
251
  };
242
252
  }
243
253
 
@@ -115,7 +115,7 @@ export function extractMemories(text, context = {}) {
115
115
  // Build memory entries following memory.schema.json
116
116
  const now = new Date().toISOString();
117
117
  return selected.map((candidate, i) => ({
118
- id: `mem-${now.split('T')[0]}-${String(i + 1).padStart(3, '0')}`,
118
+ id: `mem-${now.replace(/[:.]/g, '-')}-${String(i + 1).padStart(3, '0')}`,
119
119
  type: candidate.type,
120
120
  agent: context.agent || 'unknown',
121
121
  content: candidate.content,
@@ -178,7 +178,8 @@ function resolveAgentModel(agent, projectDir) {
178
178
  if (existsSync(configPath)) {
179
179
  const configRaw = readFileSync(configPath, 'utf-8');
180
180
  // Simple YAML parsing for agent_overrides section
181
- const overrideMatch = configRaw.match(new RegExp(`${agent}:\\s*\\n\\s+provider:\\s*(\\w+)`, 'm'));
181
+ const escapedAgent = agent.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
182
+ const overrideMatch = configRaw.match(new RegExp(`${escapedAgent}:\\s*\\n\\s+provider:\\s*(\\w+)`, 'm'));
182
183
  if (overrideMatch) {
183
184
  return { ...defaults, provider: overrideMatch[1] };
184
185
  }
@@ -13,7 +13,9 @@ const TECH_NAMES = [
13
13
  /\bExpress\b/g, /\bFastify\b/g, /\bDjango\b/g, /\bFlask\b/g, /\bLaravel\b/g,
14
14
  /\bAWS\b/g, /\bVercel\b/g, /\bNetlify\b/g, /\bRailway\b/g, /\bCloudflare\b/g,
15
15
  /\bDocker\b/g, /\bKubernetes\b/g, /\bRedis\b/g, /\bGraphQL\b/gi,
16
- /\bTypeScript\b/gi, /\bJavaScript\b/gi, /\bPython\b/g, /\bRust\b/g, /\bGo\b/g,
16
+ /\bTypeScript\b/gi, /\bJavaScript\b/gi, /\bPython\b/g,
17
+ /\bRustlang\b|\bRust\s+(?:lang|crate|cargo|tokio|async|compiler)\b/gi,
18
+ /\bGolang\b|\bGo\s+(?:module|package|routine|channel|func|goroutine)\b/g,
17
19
  /\bZod\b/g, /\bJoi\b/g, /\bZustand\b/g, /\bRedux\b/g, /\bJotai\b/g,
18
20
  ];
19
21
 
@@ -62,9 +62,9 @@ export const SECURITY_CHECKS = [
62
62
  {
63
63
  id: 'SHELL_METACHARACTERS',
64
64
  name: 'Shell metacharacter injection',
65
- pattern: /[`]|(?:\$\((?!.*\becho\b))/,
65
+ pattern: /[`]|\$\(/,
66
66
  severity: 'critical',
67
- description: 'Backticks or $() command substitution (excluding safe echo patterns)',
67
+ description: 'Backticks or $() command substitution',
68
68
  },
69
69
  {
70
70
  id: 'DANGEROUS_VARIABLES',
@@ -4,8 +4,10 @@
4
4
  * Single source of truth for bracket thresholds, layer configurations,
5
5
  * and budget ratios. Consumers import from here to avoid duplication.
6
6
  *
7
- * Progressive Reinforcement Model (v4.0):
8
- * As context depletes, budget INCREASES (model needs MORE reinforcement).
7
+ * Progressive Reinforcement Model (v4.1.2):
8
+ * As context depletes, both budget AND layers INCREASE.
9
+ * FRESH = model has full memory, minimal reinforcement needed.
10
+ * CRITICAL = model forgot initial instructions, maximum reinforcement + handoff.
9
11
  * Budget expressed as ratio of provider's total context window.
10
12
  */
11
13
 
@@ -14,10 +16,10 @@
14
16
  * @type {Record<string, {min: number, max: number, layers: string[], budgetRatio: number}>}
15
17
  */
16
18
  export const BRACKETS = {
17
- FRESH: { min: 60, max: 100, layers: ['L0', 'L1', 'L2', 'L3', 'L4', 'L5'], budgetRatio: 0.015 },
18
- MODERATE: { min: 40, max: 60, layers: ['L0', 'L1', 'L2', 'L3', 'L5'], budgetRatio: 0.025 },
19
- DEPLETED: { min: 25, max: 40, layers: ['L0', 'L1', 'L2'], budgetRatio: 0.040 },
20
- CRITICAL: { min: 0, max: 25, layers: ['L0', 'L1'], budgetRatio: 0.050 },
19
+ FRESH: { min: 60, max: 100, layers: ['L0', 'L1'], budgetRatio: 0.015 },
20
+ MODERATE: { min: 40, max: 60, layers: ['L0', 'L1', 'L2', 'L3'], budgetRatio: 0.025 },
21
+ DEPLETED: { min: 25, max: 40, layers: ['L0', 'L1', 'L2', 'L3', 'L4', 'L5'], budgetRatio: 0.040 },
22
+ CRITICAL: { min: 0, max: 25, layers: ['L0', 'L1', 'L2', 'L3', 'L4', 'L5'], budgetRatio: 0.050 },
21
23
  };
22
24
 
23
25
  /**