@dzhechkov/p-replicator 1.5.6 → 1.5.7

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.
@@ -0,0 +1,337 @@
1
+ # 03. Admin Guide — конфигурация и тонкая настройка
2
+
3
+ Для тех, кто хочет понять и кастомизировать инфраструктуру `p-replicator`:
4
+ hooks, statusline, settings.json, insights, roadmap.
5
+
6
+ ## settings.json — главный конфиг
7
+
8
+ **Расположение:** `.claude/settings.json` в корне проекта.
9
+
10
+ **Структура (defaults после init):**
11
+
12
+ ```json
13
+ {
14
+ "$schema": "https://json.schemastore.org/claude-code-settings.json",
15
+ "_comment": "Default hooks + statusline shipped by @dzhechkov/p-replicator init.",
16
+ "statusLine": {
17
+ "type": "command",
18
+ "command": "node .claude/hooks/statusline.cjs"
19
+ },
20
+ "hooks": {
21
+ "SessionStart": [
22
+ {
23
+ "matcher": "*",
24
+ "hooks": [
25
+ { "type": "command", "command": "node .claude/hooks/session-insights.cjs", "timeout": 5 }
26
+ ]
27
+ }
28
+ ],
29
+ "Stop": [
30
+ {
31
+ "matcher": "*",
32
+ "hooks": [
33
+ { "type": "command", "command": "node .claude/hooks/autocommit-roadmap.cjs", "timeout": 10 },
34
+ { "type": "command", "command": "node .claude/hooks/autocommit-insights.cjs", "timeout": 10 },
35
+ { "type": "command", "command": "node .claude/hooks/autocommit-plans.cjs", "timeout": 10 }
36
+ ]
37
+ }
38
+ ]
39
+ }
40
+ }
41
+ ```
42
+
43
+ **Кастомизация:** добавляйте новые hooks или event types — они будут СОХРАНЕНЫ
44
+ при `init --force` или `update` благодаря merge-логике (`mergeSettingsJson` +
45
+ `removeOrphanHooks`).
46
+
47
+ **Полный сброс к defaults:**
48
+
49
+ ```bash
50
+ npx @dzhechkov/p-replicator init --force --reset-settings
51
+ ```
52
+
53
+ ---
54
+
55
+ ## Hooks — жизненный цикл
56
+
57
+ `p-replicator` shipped с **6 cross-platform Node-скриптами** в `.claude/hooks/`:
58
+
59
+ | Hook | Event | Что делает |
60
+ |---|---|---|
61
+ | `session-insights.cjs` | SessionStart | Инжектит 3 свежих insights из `.claude/insights/index.md` в stdout (Claude Code захватывает) |
62
+ | `autocommit-roadmap.cjs` | Stop | Auto-commit `.claude/feature-roadmap.json` если изменён |
63
+ | `autocommit-insights.cjs` | Stop | Auto-commit `.claude/insights/` если изменены |
64
+ | `autocommit-plans.cjs` | Stop | Auto-commit `docs/plans/` если изменены |
65
+ | `statusline.cjs` | (statusLine) | Multi-line dashboard над промптом |
66
+ | `state-update.cjs` | (utility) | Argv-driven helper для записи `.claude/.p-replicator-state.json` |
67
+
68
+ **Cross-platform discipline:** все 4 autocommit-скрипта используют
69
+ `execFileSync('git', [...])` (без shell-pipes, без `2>/dev/null`/`|| true` —
70
+ работает на Windows-cmd, bash, PowerShell идентично).
71
+
72
+ **Каждый скрипт defensive:** wrapped в try/catch, exit 0 always (best-effort,
73
+ не блокирует сессию).
74
+
75
+ ---
76
+
77
+ ## Statusline — приборная панель
78
+
79
+ **Что показывает (6 строк):**
80
+
81
+ ```
82
+ P-Replicator V1.5.0 ● user │ Sonnet 4.7
83
+ 🚀 Pipeline /<cmd> ▓▓▓░░░░ 50% │ Phase: VALIDATE (2/4) │ Last: /replicate
84
+ 🎯 Roadmap [●●●○○○○○] mvp 3/8 │ Done 5/12 │ ▶ auth-jwt │ Domain: banking
85
+ 📊 SPARC ●11/11 │ 🟢 78/100 │ Plans ●3 │ ADRs ●2 │ Harvest 2026-05-05
86
+ 🛠️ Toolkit Skills ●10/10 │ Cmds ●11/11 │ Agents ●4+3 │ Rules ●5+2 │ Hooks ●6/6
87
+ 💡 Insights ●12 (2026-05-06) │ Tests 85/85 ✓ │ MCP ●1/1 │ Settings ✓ │ 🧬 Keysarium ✓
88
+ ```
89
+
90
+ **Источники (heuristic + state-file):**
91
+
92
+ | Метрика | Откуда |
93
+ |---|---|
94
+ | Pipeline command + phase + progress | `.claude/.p-replicator-state.json` (state-file) |
95
+ | Roadmap progress | `.claude/feature-roadmap.json` |
96
+ | SPARC count | `docs/{PRD,Architecture,...}.md` files |
97
+ | Validation score | regex extract from `docs/validation-report.md` |
98
+ | Plans count | `docs/plans/*.md` |
99
+ | ADRs count | `docs/ADR.md` `## ADR-...` headings, или `docs/adr/*.md`, или `docs/ddd/adr/*.md` |
100
+ | Insights count + last date | `## YYYY-MM-DD` headings в `.claude/insights/index.md` |
101
+ | Toolkit counts | filesystem walk `.claude/{skills,commands,agents,rules,hooks}/` |
102
+ | Settings status | deep-equals current vs `manifest.shippedDefaults` → `defaults`/`merged` |
103
+ | MCP servers | `.mcp.json` |
104
+ | Domain | keyword grep `CLAUDE.md` (banking/retail/enterprise/healthcare) |
105
+ | Last harvest | `TOOLKIT_HARVEST.md` mtime |
106
+ | Last test | optional `.claude/.last-test.json` cache |
107
+
108
+ **Stale state file:** если `.p-replicator-state.json` старше 30 минут —
109
+ игнорируется (показывается `idle`).
110
+
111
+ **Защита от поломки:** каждая секция wrapped в `safeRun()` — error в одной
112
+ не убивает весь statusline.
113
+
114
+ **Отключить statusline:**
115
+
116
+ Удалите поле `statusLine` из `.claude/settings.json`. На следующем `update`
117
+ с merge-логикой удаление будет сохранено.
118
+
119
+ ---
120
+
121
+ ## State-file для live progress
122
+
123
+ `.claude/.p-replicator-state.json` — ephemeral state, обновляется командами
124
+ во время выполнения pipeline:
125
+
126
+ ```json
127
+ {
128
+ "currentCommand": "/feature",
129
+ "currentPhase": {
130
+ "name": "VALIDATE",
131
+ "index": 2,
132
+ "total": 4,
133
+ "progress": 0.5
134
+ },
135
+ "lastCommand": "/replicate",
136
+ "lastFeature": "auth-jwt",
137
+ "updatedAt": "2026-05-07T..."
138
+ }
139
+ ```
140
+
141
+ **Обновляется через `state-update.cjs`:**
142
+
143
+ ```bash
144
+ node .claude/hooks/state-update.cjs \
145
+ --command /feature \
146
+ --phase VALIDATE \
147
+ --index 2 \
148
+ --total 4 \
149
+ --progress 0.5
150
+ ```
151
+
152
+ Команды pipeline'а опционально вызывают этот скрипт через Bash tool, чтобы
153
+ statusline показывал реальный прогресс.
154
+
155
+ **⚠️ Известное ограничение:** этот файл не auto-gitignored. Рекомендуется
156
+ добавить вручную:
157
+
158
+ ```
159
+ echo ".claude/.p-replicator-state.json" >> .gitignore
160
+ echo ".claude/.last-test.json" >> .gitignore
161
+ ```
162
+
163
+ См. `KNOWN_LIMITATIONS.md` пункт L5.
164
+
165
+ ---
166
+
167
+ ## Insights system
168
+
169
+ **Storage:** `.claude/insights/index.md` (markdown лог).
170
+
171
+ **Формат entry:**
172
+
173
+ ```markdown
174
+ ## YYYY-MM-DD — короткий title
175
+
176
+ **Tags:** tag1, tag2, tag3
177
+
178
+ **Problem:**
179
+ Что произошло (1-3 предложения).
180
+
181
+ **Solution:**
182
+ Что починило (1-5 предложений с кодом если уместно).
183
+
184
+ **References:** file:line или commit hash или external link
185
+
186
+ ---
187
+ ```
188
+
189
+ **Жизненный цикл:**
190
+
191
+ - ≤ 50 entries → один `index.md`
192
+ - > 50 → split на archive `<YYYY-MM>.md` с `index.md` как TOC
193
+ - Никогда не удалять — only supersede через `**Status:** superseded by <link>`
194
+
195
+ **Tag-конвенции:**
196
+ - ✅ `prisma-migration`, `postgres-timezone`, `docker-compose-network`
197
+ - ❌ `bug`, `fix`, `important` (слишком generic — recall fail'ит)
198
+
199
+ **Auto-injection через SessionStart hook** — описано выше.
200
+
201
+ ---
202
+
203
+ ## Roadmap management
204
+
205
+ **Файл:** `.claude/feature-roadmap.json` (генерируется в `/replicate` Phase 3
206
+ из PRD MVP scope, или вручную).
207
+
208
+ **Schema (post v1.5.0):**
209
+
210
+ ```json
211
+ {
212
+ "version": "1.0",
213
+ "features": [
214
+ {
215
+ "id": "auth-jwt",
216
+ "number": 1,
217
+ "branch": "feature/001-auth-jwt",
218
+ "name": "JWT-based authentication",
219
+ "priority": "mvp",
220
+ "status": "next",
221
+ "complexity": "medium",
222
+ "estimated_hours": "2-4",
223
+ "blockers": [],
224
+ "expected_files": [
225
+ "packages/backend/src/auth/jwt.ts"
226
+ ],
227
+ "depends_on": []
228
+ }
229
+ ]
230
+ }
231
+ ```
232
+
233
+ **Lifecycle states:**
234
+ - `planned` → ещё не приоритетная
235
+ - `next` → следующая в очереди (берётся `/next`)
236
+ - `in_progress` → активно работают
237
+ - `done` → реализована
238
+ - `blocked` → ждёт `depends_on` или manual fix
239
+
240
+ **Поля `number` и `branch`** заполняются `--feature-branches` flag'ом в `/run`
241
+ или `/go`.
242
+
243
+ **Auto-commit** через `autocommit-roadmap.cjs` (Stop hook) при изменениях.
244
+
245
+ ---
246
+
247
+ ## Doctor + Verify — два разных инструмента
248
+
249
+ | Инструмент | Что проверяет | Когда |
250
+ |---|---|---|
251
+ | `npx @dzhechkov/p-replicator doctor` | Pre-shipped contract: 10 skills + 11 commands + 4 agents + 5 rules + settings.json + 6 hooks + git on PATH | После init / при подозрении что что-то сломалось |
252
+ | `npx @dzhechkov/p-replicator verify` | Pre-shipped + post-/replicate hints (CLAUDE.md, planner.md, security.md, feature-roadmap.json, и т.д.) | После каждого `/replicate` для уверенности |
253
+
254
+ **`doctor` exit codes:**
255
+ - `0` — всё в порядке
256
+ - `1` — что-то отсутствует из must-have (используйте `init --force` для repair)
257
+
258
+ **`verify` exit codes:**
259
+ - `0` — pre-shipped contract в порядке (могут быть warnings про project-specific)
260
+ - `1` — pre-shipped contract нарушен
261
+
262
+ ---
263
+
264
+ ## Update workflow
265
+
266
+ ```bash
267
+ # Безопасный upgrade с preserve user customizations:
268
+ npx @dzhechkov/p-replicator@latest update
269
+
270
+ # Или через init --force (тоже preserves customizations):
271
+ npx @dzhechkov/p-replicator@latest init --force
272
+
273
+ # Полный сброс settings.json к defaults:
274
+ npx @dzhechkov/p-replicator@latest init --force --reset-settings
275
+ ```
276
+
277
+ **Что делает merge-логика:**
278
+ 1. Читает `manifest.shippedDefaults['settings.json']` (что мы shipped в прошлый раз)
279
+ 2. Читает текущий `templates/.claude/settings.json` (новый template)
280
+ 3. Читает `.claude/settings.json` (user's current)
281
+ 4. **Orphan detection:** удаляет hooks, которые были в old template но НЕТ в new
282
+ 5. **Merge:** добавляет hooks из new template которых ЕЩЁ НЕТ в user's current
283
+ 6. User-added hooks (никогда не были в old template) — **СОХРАНЯЮТСЯ**
284
+
285
+ **Identity model:** hooks сравниваются по `command` string. User-modified
286
+ default (изменил command) → treated как user-added, preserved.
287
+
288
+ См. подробности алгоритма в [05_architecture.md](./05_architecture.md).
289
+
290
+ ---
291
+
292
+ ## MCP servers
293
+
294
+ **Файл:** `.mcp.json` (project-local).
295
+
296
+ ```json
297
+ {
298
+ "mcpServers": {
299
+ "filesystem": {
300
+ "command": "npx",
301
+ "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/dir"]
302
+ },
303
+ "github": {
304
+ "command": "npx",
305
+ "args": ["-y", "@modelcontextprotocol/server-github"],
306
+ "env": { "GITHUB_TOKEN": "..." }
307
+ }
308
+ }
309
+ }
310
+ ```
311
+
312
+ Statusline показывает количество MCP серверов в строке Status.
313
+
314
+ `/replicate` Phase 3 автоматически генерирует `.mcp.json` при detected
315
+ external integrations.
316
+
317
+ ---
318
+
319
+ ## Связь с Keysarium
320
+
321
+ Если в проекте обнаружен `.keysarium.json` (от соседнего пакета
322
+ `@dzhechkov/keysarium`):
323
+
324
+ - `init` показывает интеграционный banner
325
+ - Statusline показывает `🧬 Keysarium ✓`
326
+ - `/replicate` Phase 3 НЕ дублирует skills, которые уже предоставлены
327
+ Keysarium'ом
328
+
329
+ Документация Keysarium — в собственном пакете.
330
+
331
+ ---
332
+
333
+ ## Дальше
334
+
335
+ - [04_api_reference.md](./04_api_reference.md) — формальные схемы
336
+ - [05_architecture.md](./05_architecture.md) — внутреннее устройство
337
+ - [06_troubleshooting.md](./06_troubleshooting.md) — типичные проблемы
@@ -0,0 +1,333 @@
1
+ # 04. API Reference
2
+
3
+ Формальная справка: CLI-команды, флаги, схемы JSON-файлов.
4
+
5
+ ## CLI: `npx @dzhechkov/p-replicator`
6
+
7
+ ### Subcommands
8
+
9
+ | Subcommand | Назначение | Exit code |
10
+ |---|---|---|
11
+ | `init` (default) | Установка пакета в проект | `0` ok, `1` если уже установлен без `--force` |
12
+ | `update` | Обновление файлов до новой версии | `0` ok, `1` если не установлен |
13
+ | `remove` | Удаление package-tracked файлов | `0` ok, `1` если не установлен |
14
+ | `list` | Список установленных components | `0` |
15
+ | `doctor` | Health check pre-shipped contract | `0` ok, `1` если что-то не так |
16
+ | `verify` | Pre-shipped + post-/replicate проверка | `0` ok, `1` если pre-shipped contract нарушен |
17
+
18
+ ### Глобальные флаги
19
+
20
+ | Флаг | Где работает | Описание |
21
+ |---|---|---|
22
+ | `--force` | `init` | Перезаписать существующие файлы (с merge-логикой для settings.json) |
23
+ | `--dry-run` | `init`, `update`, `remove` | Preview без записи на диск |
24
+ | `--reset-settings` | `init --force`, `update` | Полный overwrite settings.json (отключает merge) |
25
+ | `--help`, `-h` | любой | Показать help |
26
+ | `--version`, `-v` | любой | Показать версию пакета |
27
+
28
+ ### Slash command флаги (внутри Claude Code)
29
+
30
+ | Флаг | Где работает | Описание |
31
+ |---|---|---|
32
+ | `--feature-branches` | `/run`, `/go` | Каждая фича в отдельной ветке `feature/{NNN}-{id}` |
33
+ | `--auto-merge` | `/run`, `/go` (с `--feature-branches`) | Автомердж feature-ветки в main после успеха |
34
+ | `--skip-tests` | `/start` | Пропустить генерацию тестов |
35
+ | `--skip-seed` | `/start` | Пропустить DB seeding |
36
+ | `--dry-run` | `/start`, `/replicate` | Preview без записи |
37
+
38
+ ---
39
+
40
+ ## Manifest schema (`.p-replicator.json`)
41
+
42
+ ```json
43
+ {
44
+ "version": "1.5.0",
45
+ "installedAt": "2026-05-07T12:00:00.000Z",
46
+ "components": ["agents", "commands", "hooks", "rules", "settings", "skills"],
47
+ "files": [
48
+ ".claude/agents/doc-validator.md",
49
+ ".claude/commands/replicate.md",
50
+ "...sorted list of all installed files..."
51
+ ],
52
+ "shippedDefaults": {
53
+ "settings.json": {
54
+ "hooks": { "SessionStart": [...], "Stop": [...] },
55
+ "statusLine": { "type": "command", "command": "..." }
56
+ }
57
+ }
58
+ }
59
+ ```
60
+
61
+ **Поля:**
62
+
63
+ | Поле | Тип | Назначение |
64
+ |---|---|---|
65
+ | `version` | semver | Версия pre-replicator при последнем install/update |
66
+ | `installedAt` | ISO-8601 | Timestamp последней установки |
67
+ | `components` | array of group keys | Pre-shipped группы (skills/commands/agents/rules/settings/hooks) |
68
+ | `files` | sorted array | Все package-tracked файлы (для `remove`) |
69
+ | `shippedDefaults` | optional map | Snapshot template'ов для orphan detection при upgrade |
70
+
71
+ **Backward compat:** manifest без `shippedDefaults` (pre-1.4.3) загружается
72
+ без ошибок — orphan detection skipped на первый upgrade.
73
+
74
+ ---
75
+
76
+ ## Roadmap schema (`.claude/feature-roadmap.json`)
77
+
78
+ ```json
79
+ {
80
+ "version": "1.0",
81
+ "features": [
82
+ {
83
+ "id": "auth-jwt",
84
+ "number": 1,
85
+ "branch": "feature/001-auth-jwt",
86
+ "name": "JWT-based authentication",
87
+ "priority": "mvp",
88
+ "status": "next",
89
+ "complexity": "medium",
90
+ "estimated_hours": "2-4",
91
+ "blockers": [],
92
+ "expected_files": ["packages/backend/src/auth/jwt.ts"],
93
+ "depends_on": []
94
+ }
95
+ ]
96
+ }
97
+ ```
98
+
99
+ ### Feature fields
100
+
101
+ | Field | Required | Тип | Заполняется кем | Назначение |
102
+ |-------|----------|-----|-----------------|-----------|
103
+ | `id` | yes | kebab-case slug | initial generation | Стабильный идентификатор |
104
+ | `number` | optional | int | `--feature-branches` flag | Sequential 1..N для branch naming |
105
+ | `branch` | optional | string | `--feature-branches` после успеха | `feature/{NNN}-{id}` actual ref |
106
+ | `name` | recommended | string | initial generation | Human-readable title |
107
+ | `priority` | yes | enum | initial generation | `mvp` \| `high` \| `medium` \| `low` |
108
+ | `status` | yes | enum | lifecycle | `planned` \| `next` \| `in_progress` \| `done` \| `blocked` |
109
+ | `complexity` | optional | enum | initial generation | `simple` \| `medium` \| `complex` |
110
+ | `estimated_hours` | optional | string | initial generation | Time hint |
111
+ | `blockers` | optional | string[] | manual | Issue IDs или free-form |
112
+ | `expected_files` | optional | string[] | initial generation | Используется `/next update` для detection |
113
+ | `depends_on` | optional | string[] | initial generation | Feature IDs которые должны завершиться первыми |
114
+
115
+ ---
116
+
117
+ ## State-file schema (`.claude/.p-replicator-state.json`)
118
+
119
+ ```json
120
+ {
121
+ "currentCommand": "/feature",
122
+ "currentPhase": {
123
+ "name": "VALIDATE",
124
+ "index": 2,
125
+ "total": 4,
126
+ "progress": 0.5
127
+ },
128
+ "lastCommand": "/replicate",
129
+ "lastFeature": "auth-jwt",
130
+ "updatedAt": "2026-05-07T..."
131
+ }
132
+ ```
133
+
134
+ **Поля:**
135
+
136
+ | Field | Тип | Назначение |
137
+ |---|---|---|
138
+ | `currentCommand` | `/<name>` | Активная команда сейчас (`null` если idle) |
139
+ | `currentPhase` | object | Live progress в текущей команде |
140
+ | `currentPhase.name` | string | Имя фазы (e.g., `VALIDATE`, `IMPLEMENT`) |
141
+ | `currentPhase.index` | int | Текущая фаза 1..total |
142
+ | `currentPhase.total` | int | Сколько всего фаз |
143
+ | `currentPhase.progress` | float 0..1 | Прогресс в текущей фазе |
144
+ | `lastCommand` | `/<name>` | Предыдущая команда (для статусной строки) |
145
+ | `lastFeature` | string | ID последней реализованной фичи |
146
+ | `updatedAt` | ISO-8601 | Time-stamp |
147
+
148
+ **Stale check:** statusline игнорирует state старше 30 минут.
149
+
150
+ **Update API:**
151
+
152
+ ```bash
153
+ node .claude/hooks/state-update.cjs \
154
+ --command /feature \
155
+ --phase VALIDATE \
156
+ --index 2 \
157
+ --total 4 \
158
+ --progress 0.5 \
159
+ --last-command /replicate \
160
+ --last-feature auth-jwt
161
+ ```
162
+
163
+ Or with full JSON:
164
+
165
+ ```bash
166
+ node .claude/hooks/state-update.cjs --json '{"currentCommand":"/run", ...}'
167
+ ```
168
+
169
+ ---
170
+
171
+ ## settings.json — структура
172
+
173
+ ```json
174
+ {
175
+ "$schema": "https://json.schemastore.org/claude-code-settings.json",
176
+ "_comment": "Описание установки",
177
+ "statusLine": {
178
+ "type": "command",
179
+ "command": "node .claude/hooks/statusline.cjs"
180
+ },
181
+ "hooks": {
182
+ "SessionStart": [ /* matchers + hooks */ ],
183
+ "Stop": [ /* matchers + hooks */ ],
184
+ "PreToolUse": [ /* user-added */ ],
185
+ "PostToolUse": [ /* user-added */ ]
186
+ }
187
+ }
188
+ ```
189
+
190
+ ### `statusLine` field
191
+
192
+ ```json
193
+ {
194
+ "statusLine": {
195
+ "type": "command", // только "command" поддерживается
196
+ "command": "node .claude/hooks/statusline.cjs"
197
+ }
198
+ }
199
+ ```
200
+
201
+ Скрипт пишет в stdout multi-line ANSI-output. Удалите поле — statusline
202
+ выключится (merge сохранит удаление при upgrade).
203
+
204
+ ### `hooks.<EventType>` array
205
+
206
+ Каждый element:
207
+
208
+ ```json
209
+ {
210
+ "matcher": "*", // или regex для tool-name
211
+ "hooks": [
212
+ {
213
+ "type": "command",
214
+ "command": "node .claude/hooks/X.cjs",
215
+ "timeout": 10 // в секундах
216
+ }
217
+ ]
218
+ }
219
+ ```
220
+
221
+ **Event types в Claude Code:**
222
+ - `SessionStart` — при начале сессии (stdout инжектится в context)
223
+ - `Stop` — при завершении turn'а (side-effects: commit, log)
224
+ - `PreToolUse`, `PostToolUse` — вокруг tool-вызовов
225
+
226
+ ---
227
+
228
+ ## COMPONENTS schema (внутри `src/utils.js`)
229
+
230
+ Контракт того что shipped и что generated:
231
+
232
+ ```javascript
233
+ const COMPONENTS = {
234
+ skills: {
235
+ src: '.claude/skills',
236
+ kind: 'pre-shipped',
237
+ label: 'Skills (10 skill packs)',
238
+ group: 'core',
239
+ items: { 'explore': '...', /* ... 10 entries */ },
240
+ },
241
+ commands: {
242
+ src: '.claude/commands',
243
+ kind: 'pre-shipped',
244
+ label: 'Commands (orchestration + workflow)',
245
+ group: 'core',
246
+ items: { 'replicate': '...', /* ... 11 entries */ },
247
+ },
248
+ agents: { kind: 'pre-shipped', items: { /* 4 entries */ } },
249
+ rules: { kind: 'pre-shipped', items: { /* 5 entries */ } },
250
+ settings: { isFile: true, kind: 'pre-shipped', items: { 'settings.json': '...' } },
251
+ hooks: { kind: 'pre-shipped', items: { /* 6 entries */ } },
252
+
253
+ // Project-generated (created by /replicate Phase 3)
254
+ projectAgents: {
255
+ kind: 'project-generated',
256
+ items: {
257
+ '.claude/agents/planner.md': '...',
258
+ '.claude/agents/code-reviewer.md': '...',
259
+ '.claude/agents/architect.md': '...',
260
+ },
261
+ },
262
+ projectRules: {
263
+ kind: 'project-generated',
264
+ items: {
265
+ '.claude/rules/security.md': '...',
266
+ '.claude/rules/coding-style.md': '...',
267
+ '.claude/rules/testing.md': '...',
268
+ },
269
+ },
270
+ projectFiles: {
271
+ kind: 'project-generated',
272
+ items: {
273
+ 'CLAUDE.md': '...',
274
+ '.claude/feature-roadmap.json': '...',
275
+ 'DEVELOPMENT_GUIDE.md': '...',
276
+ 'docker-compose.yml': '...',
277
+ },
278
+ },
279
+ };
280
+ ```
281
+
282
+ **Identity:**
283
+ - `kind: 'pre-shipped'` — installed by `init`, file paths derived from `src` + item key
284
+ - `kind: 'project-generated'` — created by `/replicate` Phase 3, item keys ARE full paths
285
+ - `isFile: true` — single-file component (settings.json), not a directory
286
+
287
+ **Helper:** `utils.getItemRelativePath(comp, itemKey)` — централизованная derivation:
288
+ - pre-shipped skills: `<src>/<itemKey>/SKILL.md`
289
+ - pre-shipped hooks: `<src>/<itemKey>.cjs`
290
+ - pre-shipped commands/rules/agents: `<src>/<itemKey>.md`
291
+ - pre-shipped settings.json: `comp.src` (full path)
292
+ - project-generated: `itemKey` (already full path)
293
+
294
+ Используется `verify`, `doctor`, `list` для единообразного path-resolution.
295
+
296
+ ---
297
+
298
+ ## Hook scripts API
299
+
300
+ ### `session-insights.cjs`
301
+
302
+ **Trigger:** `SessionStart` hook.
303
+ **Reads:** `.claude/insights/index.md` (`## YYYY-MM-DD` headings)
304
+ **Writes:** stdout (Claude Code инжектит в session context)
305
+ **Output:** до 3 свежих insights в `## Recent project insights\n\n## ... ## ... ## ...` format
306
+
307
+ ### `autocommit-roadmap.cjs` / `autocommit-insights.cjs` / `autocommit-plans.cjs`
308
+
309
+ **Trigger:** `Stop` hook.
310
+ **Reads:** target paths (roadmap json / insights/ dir / plans/ dir)
311
+ **Side-effect:** `git add` + `git diff --cached --quiet` check + `git commit --only` if changed
312
+ **stdout/stderr:** suppressed (`stdio: 'ignore'`)
313
+ **Always exits 0** (best-effort, не блокирует сессию)
314
+
315
+ ### `statusline.cjs`
316
+
317
+ **Trigger:** Claude Code `statusLine` config (every prompt render).
318
+ **Reads:** filesystem heuristics + state-file
319
+ **Writes:** stdout 6-line ANSI-output (header + 5 content)
320
+ **Defensive:** every section wrapped в `safeRun()` with fallback
321
+
322
+ ### `state-update.cjs`
323
+
324
+ **Invoked:** by pipeline commands via Bash tool
325
+ **Args:** `--command`, `--phase`, `--index`, `--total`, `--progress`, `--last-command`, `--last-feature`, `--json`
326
+ **Writes:** `.claude/.p-replicator-state.json`
327
+ **Always exits 0** (best-effort)
328
+
329
+ ---
330
+
331
+ ## Дальше
332
+
333
+ - [05_architecture.md](./05_architecture.md) — как всё это устроено внутри