gennady 0.8.3 → 0.8.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/README.md +212 -3
  2. package/ai/directives/sdd/audit.directive.xml +22 -11
  3. package/ai/directives/sdd/critic-protocol.xml +3 -0
  4. package/ai/directives/sdd/critic.directive.xml +25 -3
  5. package/ai/skills/README.md +150 -0
  6. package/ai/skills/sdd-check/SKILL.md +19 -9
  7. package/ai/skills/sdd-execute/scripts/README.md +3 -0
  8. package/ai/skills/sdd-execute/scripts/_sdd-lib.sh +60 -0
  9. package/ai/skills/sdd-execute/scripts/check.sh +238 -0
  10. package/ai/skills/sdd-execute/scripts/sdd +12 -0
  11. package/ai/skills/sdd-hooks-install/SKILL.md +88 -0
  12. package/ai/skills/workspace-permission-setup/SKILL.md +193 -0
  13. package/cli/cmd/README.md +185 -0
  14. package/dist/ai/directives/sdd/audit.directive.xml +22 -11
  15. package/dist/ai/directives/sdd/critic-protocol.xml +3 -0
  16. package/dist/ai/directives/sdd/critic.directive.xml +25 -3
  17. package/dist/ai/skills/README.md +150 -0
  18. package/dist/ai/skills/sdd-check/SKILL.md +19 -9
  19. package/dist/ai/skills/sdd-execute/scripts/README.md +3 -0
  20. package/dist/ai/skills/sdd-execute/scripts/_sdd-lib.sh +60 -0
  21. package/dist/ai/skills/sdd-execute/scripts/check.sh +238 -0
  22. package/dist/ai/skills/sdd-execute/scripts/sdd +12 -0
  23. package/dist/ai/skills/sdd-hooks-install/SKILL.md +88 -0
  24. package/dist/ai/skills/workspace-permission-setup/SKILL.md +193 -0
  25. package/dist/chunks/index-BHEP1kYv.js +164 -0
  26. package/dist/chunks/index-DqSFtXFv.js +813 -0
  27. package/dist/chunks/index-Ukr3nSKB.js +377 -0
  28. package/dist/cli/cmd/lint/checks/anchor-thin.check.d.ts +11 -0
  29. package/dist/cli/cmd/lint/lint.cmd.d.ts +1 -1
  30. package/dist/cli/cmd/lint/lint.types.d.ts +2 -0
  31. package/dist/gennady.js +4 -4
  32. package/package.json +1 -1
  33. package/dist/chunks/index-4fUNp3za.js +0 -156
  34. package/dist/chunks/index-C9UEDrqg.js +0 -754
  35. package/dist/chunks/index-jOIhIHdS.js +0 -369
@@ -0,0 +1,185 @@
1
+ # cli/cmd — Команды CLI
2
+
3
+ 16 команд для AI-агентов: работа с git, генерация commit-сообщений, ревью, merge-конфликты, линтинг, навигация по коду, синхронизация, мониторинг.
4
+
5
+ ---
6
+
7
+ ## Типовые сценарии
8
+
9
+ ### 1. Сделать коммит
10
+
11
+ ```bash
12
+ # Сгенерировать commit message из staged-изменений
13
+ npx gennady commit
14
+
15
+ # One-line + сразу применить
16
+ npx gennady commit --mode=oneline --apply
17
+
18
+ # С указанием задачи
19
+ npx gennady commit --task=MAILCORE-123
20
+ ```
21
+
22
+ ### 2. Проверить качество кода
23
+
24
+ ```bash
25
+ # Линтинг директории
26
+ npx gennady lint ./src
27
+
28
+ # Только staged .ts файлы
29
+ npx gennady lint --staged
30
+
31
+ # Автофикс DbC-контрактов
32
+ npx gennady lint ./src --autofix
33
+ ```
34
+
35
+ ### 3. Навигация по проекту
36
+
37
+ ```bash
38
+ # Карта проекта (все файлы с аннотациями)
39
+ npx gennady orient
40
+
41
+ # Найти файлы по задаче
42
+ npx gennady orient --task=TSK-03
43
+
44
+ # Кто потребляет модуль
45
+ npx gennady orient --consumer=DbcTsLinter
46
+
47
+ # Граф зависимостей
48
+ npx gennady orient --graph
49
+
50
+ # Детальный просмотр файла
51
+ npx gennady orient --file=path/to/file.ts
52
+
53
+ # Встроить orient-инструкции в AGENTS.md
54
+ npx gennady agents-rules
55
+ ```
56
+
57
+ ### 4. Ревью MR/PR
58
+
59
+ ```bash
60
+ # Верификация MR по текущей ветке
61
+ npx gennady review-verify
62
+
63
+ # По URL
64
+ npx gennady review-verify --url="https://gitlab.com/group/repo/-/merge_requests/42"
65
+
66
+ # По ref
67
+ npx gennady review-verify group/repo!42
68
+
69
+ # Только XML issues
70
+ npx gennady review-issues --ref=group/repo!42
71
+
72
+ # Ответить на discussion-треды
73
+ echo '[{"discussionId":"abc","body":"Fixed"}]' | \
74
+ npx gennady vcs-reply --project=group/repo --iid=42
75
+ ```
76
+
77
+ ### 5. AI-ревью staged-изменений
78
+
79
+ ```bash
80
+ npx gennady review
81
+ npx gennady review --branch=develop
82
+ ```
83
+
84
+ ### 6. Разрешить merge-конфликты
85
+
86
+ ```bash
87
+ # После git merge с конфликтами
88
+ npx gennady resolve-conflicts
89
+ npx gennady resolve-conflicts --branch=main --incoming=feature/x
90
+ ```
91
+
92
+ ### 7. Собрать файлы для AI-контекста
93
+
94
+ ```bash
95
+ # XML (по умолчанию)
96
+ npx gennady cat "./src/**/*.ts"
97
+
98
+ # Markdown, без цвета
99
+ npx gennady cat "./src/**/*.ts" --output=md --plain | pbcopy
100
+
101
+ # Из удалённого MR
102
+ npx gennady cat --url="https://gitlab.com/.../-/merge_requests/123"
103
+ ```
104
+
105
+ ### 8. Синхронизировать директивы и навыки
106
+
107
+ ```bash
108
+ # Директивы
109
+ npx gennady sync
110
+ npx gennady sync --dry-run
111
+
112
+ # Навыки
113
+ npx gennady sync-skills
114
+ npx gennady sync-skills --dry-run
115
+ ```
116
+
117
+ ### 9. Мульти-модельный анализ
118
+
119
+ ```bash
120
+ # Мнение двух моделей с синтезом
121
+ npx gennady alt-opinion \
122
+ --model="llmproxy/kimi-k2.6" \
123
+ --model="llmproxy/glm-5.1" \
124
+ --synthModel="llmproxy/deepseek-v4-pro" \
125
+ --file="./spec.md"
126
+ ```
127
+
128
+ ### 10. Мониторинг AI-агентов
129
+
130
+ ```bash
131
+ # Live-дашборд
132
+ npx gennady agent-mon
133
+
134
+ # Одноразовый снапшот
135
+ npx gennady agent-mon --once
136
+ ```
137
+
138
+ ---
139
+
140
+ ## Все команды
141
+
142
+ | Команда | Назначение |
143
+ | ------------------- | ------------------------------------------------------- |
144
+ | `commit` | Генерация commit message из staged-изменений через AI |
145
+ | `cat` | Вывод файлов в XML/Markdown для AI-контекста |
146
+ | `review` | AI-ревью staged изменений |
147
+ | `review-verify` | Сборка промпта для верификации MR/PR discussions |
148
+ | `review-issues` | XML-артефакт issues из MR/PR |
149
+ | `vcs-reply` | Постинг ответов в GitLab MR discussions |
150
+ | `resolve-conflicts` | Промпт для AI-разрешения merge-конфликтов |
151
+ | `remote-console` | Зеркалирование браузерной консоли в stdout |
152
+ | `lint` | Валидация .ts файлов: headers, anchors, DbC, invariants |
153
+ | `alt-opinion` | Мульти-модельные мнения с синтезом |
154
+ | `sync` | Синхронизация `ai/directives/` из npm-пакета |
155
+ | `sync-skills` | Синхронизация SDD-навыков в `.claude/skills/` |
156
+ | `agent-mon` | Интерактивный дашборд мониторинга AI-агентов |
157
+ | `orient` | Навигация по file-header и DBC-контрактам |
158
+ | `agents-rules` | Инструкция по orient для AI-агентов |
159
+
160
+ ---
161
+
162
+ ## Структура команды
163
+
164
+ ```
165
+ cli/cmd/<name>/
166
+ ├── <name>.cmd.ts # Исполняемая логика команды
167
+ ├── index.ts # Точка входа для динамического импорта
168
+ ├── help.ts # help-вывод (опционально)
169
+ └── README.md # Документация (есть только у orient — канонический источник для agents-rules)
170
+ ```
171
+
172
+ При добавлении команды обновить: `cli/cmd/README.md` (этот файл), `cli/AGENTS.md`, `cli/gennady.ts`.
173
+
174
+ ---
175
+
176
+ ## Связанные спеки
177
+
178
+ - `specs/cli/cli.spec.md` — общая спека CLI
179
+ - `specs/cli/lint/lint.spec.md` — линтинг
180
+ - `specs/cli/alt-opinion/alt-opinion.spec.md` — alt-opinion
181
+ - `specs/cli/cat/cat.spec.md` — cat
182
+ - `specs/cli/sync/sync.spec.md` — sync
183
+ - `specs/cli/sync-skills/sync-skills.spec.md` — sync-skills
184
+ - `specs/cli/agents-rules/agents-rules.spec.md` — agents-rules
185
+ - `specs/cli/e2e/e2e.spec.md` — e2e-тестирование
@@ -45,6 +45,16 @@
45
45
  Files in diff but absent from ticket declaration + Execution Log → candidates for `CLOSED_WORLD_DRIFT` (public entities) or `EXECUTION_LOG_INCOMPLETE` (utility-only changes).
46
46
  </Axiom>
47
47
 
48
+ <Axiom id="AX_MECHANICAL_VIA_SDD_CHECK">
49
+ Deterministic mechanical checks — file-header presence, Task-ID collision, tracker-sync — are NOT hand-coded here. They live in one tool, `sdd check`, which sdd-check (whole tree) and this directive (scoped) both consume. Single source of mechanical truth → no drift between the two SDD reviewers.
50
+
51
+ - `sdd check --files <git-diff in-scope files>` → [HEADERS] (`@file`/`@consumers`/`@tasks` presence).
52
+ - `sdd check --task <Task-ID>` → [TASKID] (collision for that id) + [TRACKER_SYNC] (Meta.Status vs tracker row).
53
+ - `sdd check <root>` (no flag) → tree-wide [TASKID] orphan refs (epic mode).
54
+
55
+ Audit still owns everything the tool cannot decide mechanically: semantic `@consumers` resolvability, current-Task-ID identity, append-only `@tasks` regression vs git, section-anchor coverage, and all code-reading checks (closed-world, completeness, rules-compliance, runtime-backing, backflow).
56
+ </Axiom>
57
+
48
58
  <Axiom id="AX_DRIFT_TAXONOMY">
49
59
  Findings are classified by type. Every finding has exactly one:
50
60
 
@@ -318,13 +328,15 @@
318
328
  <Goal>Verify Task-ID integrity and ticket section-anchor coverage per `AX_TASK_ID_INTEGRITY`. Reuses STEP_2 git-diff scope.</Goal>
319
329
  <Action>
320
330
  1. TRACE_HEADER (STACK `ROOT__TASK_ID_INTEGRITY_CHECK`).
321
- 2. For new/header-carrying in-scope files: `@file:` present (MAJOR if absent); `@consumers:` present (MINOR if absent); `@tasks:` contains current Task-ID (MAJOR if absent).
322
- 3. Collect all `@tasks: TSK-NN[, …]` references from in-scope files.
323
- 4. Each ID — verify `tasks/**/*.task-NN.md` exists. Orphan → `TASK_ID_DRIFT` (`MAJOR`, HIGH).
324
- 5. Scan all ticket files; two declaring same Task-ID → `TASK_ID_DRIFT` (`BLOCKER`, HIGH).
325
- 6. Compare current `@tasks:` values against pre-task git ref. Prior IDs removed → `TASK_ID_DRIFT` (`MAJOR`).
326
- 7. **Ticket section-anchor coverage** (per `AX_TASK_ID_INTEGRITY` last bullet). For each anchor name templated in `TASK_TICKET_STRUCTURE` → `~/.claude/skills/sdd-execute/scripts/sdd extract <ticket> <NAME>`. Exit `2` → `EXECUTION_LOG_INCOMPLETE` `missing-section-anchor`; exit `3` → `EXECUTION_LOG_INCOMPLETE` `anchor-unbalanced`. Zero anchors found → escalate to BLOCKER.
327
- 8. Phase Progress. STOP.
331
+ 2. **Mechanical primitives — delegate, do NOT hand-grep** (shared source of truth with sdd-check, per `AX_MECHANICAL_VIA_SDD_CHECK`):
332
+ - `~/.claude/skills/sdd-execute/scripts/sdd check --files <git-diff in-scope files>` → [HEADERS]: `verdict=PARTIAL`/`NONE` on a code file → `@file:` absent = `TASK_ID_DRIFT`/`MAJOR`, `@tasks:` absent = `MAJOR`; `has_consumers=0` = `MINOR`.
333
+ - `~/.claude/skills/sdd-execute/scripts/sdd check --task <Task-ID>` → [TASKID] `collision` → `TASK_ID_DRIFT` (`BLOCKER`); orphan refs surface in tree-mode (run plain `sdd check` for epic-level).
334
+ 3. **Residual semantic checks the tool cannot do** (keep here):
335
+ - `@consumers:` value must resolve to an entity name in spec/codebase (not a path/dir) → `MINOR` if it does not.
336
+ - `@tasks:` contains current Task-ID (the tool reports presence; YOU confirm it is THIS Task-ID, not just any).
337
+ - Compare current `@tasks:` values against pre-task git ref. Prior IDs removed → `TASK_ID_DRIFT` (`MAJOR`).
338
+ 4. **Ticket section-anchor coverage** (per `AX_TASK_ID_INTEGRITY` last bullet). For each anchor name templated in `TASK_TICKET_STRUCTURE` → `~/.claude/skills/sdd-execute/scripts/sdd extract <ticket> <NAME>`. Exit `2` → `EXECUTION_LOG_INCOMPLETE` `missing-section-anchor`; exit `3` → `EXECUTION_LOG_INCOMPLETE` `anchor-unbalanced`. Zero anchors found → escalate to BLOCKER.
339
+ 5. Phase Progress. STOP.
328
340
  </Action>
329
341
  </Step>
330
342
 
@@ -375,10 +387,9 @@
375
387
  4. **Placeholder leftover scan** (fabricated done): for every `[x]` line in current round, scan for residual `<...>` literal. Any match → `EXECUTION_LOG_INCOMPLETE` (`BLOCKER`) tagged «fabricated done».
376
388
  5. Round immutability: prior round sections compared against pre-round git ref. Any edit/reorder/delete → `EXECUTION_LOG_INCOMPLETE` (`BLOCKER`).
377
389
  6. Reopens metadata: Meta `Reopens: <count>` = (Round headers count − 1). Mismatch → `EXECUTION_LOG_INCOMPLETE` (`MAJOR`).
378
- 7. Tracker sync:
379
- - ticket Status (Meta) matches `tasks/<scope>/README.md` Tracker row for this Task-ID.
380
- - `tasks/README.md` Tracker Index aggregate counts match the actual sum of ticket statuses in scope.
381
- - Mismatches → `EXECUTION_LOG_INCOMPLETE` (`MAJOR`) tagged «tracker desync».
390
+ 7. Tracker sync — delegate to `sdd check --task <Task-ID>` (per `AX_MECHANICAL_VIA_SDD_CHECK`), do NOT hand-grep:
391
+ - read [TRACKER_SYNC]: `match=NO` (ticket Meta.Status ≠ tracker row) or `NO_ROW` → `EXECUTION_LOG_INCOMPLETE` (`MAJOR`) tagged «tracker desync». `UNPARSEABLE` → INFO.
392
+ - aggregate Tracker Index counts (`tasks/README.md`) vs sum of statuses in scope remains a manual cross-check in epic mode.
382
393
  8. Phase Progress. STOP.
383
394
  </Action>
384
395
  </Step>
@@ -21,6 +21,7 @@
21
21
  7. Non-goals — explicit exclusions.
22
22
  8. Consistency — no internal contradictions.
23
23
  9. Testability — claims verifiable, not vague ("should be fast").
24
+ 10. Parsimony — every entity/type/contract traces to a requirement or use-case. Flag: unjustified (no driving requirement), redundant (two entities overlap WITHIN this spec), speculative (surface beyond stated boundary). Prefer reuse/extend over a new entity. Scope is intra-spec only — you cannot see the project, so never claim "X already exists elsewhere" (that is the orchestrator's check).
24
25
  </Axiom>
25
26
 
26
27
  <Axiom id="AX_TASK_DIMENSIONS">
@@ -30,6 +31,7 @@
30
31
  3. Phases — ordered correctly, deps explicit, no gaps (impl without test), Target Files non-overlapping.
31
32
  4. Clarity — fresh agent can build from this alone. Inputs/outputs specified.
32
33
  5. Completeness — all sections filled, no <TBD> or <YYYY-MM-DD>.
34
+ 6. Parsimony — task introduces NO entity/type/method absent from the parent spec inventory. New surface declared in a task without spec backing = finding. Spec entities are reused, not re-declared. Cross-project reuse is the orchestrator's check, not yours.
33
35
  </Axiom>
34
36
 
35
37
  <Axiom id="AX_SEVERITY">
@@ -54,6 +56,7 @@
54
56
  <Pattern id="AP_FORMAT_BIAS">Assuming quality from formatting. Structure ≠ correctness.</Pattern>
55
57
  <Pattern id="AP_CREEP">Reading beyond artifact + parent spec.</Pattern>
56
58
  <Pattern id="AP_INTERNAL_PARANOIA">Flagging type violations at internal boundaries. Type system prevents these.</Pattern>
59
+ <Pattern id="AP_REUSE_BLIND">Claiming an entity duplicates something "in the project". You see only artifact + parent spec — judge redundancy ONLY within that scope. Project-wide dedup is the orchestrator's job.</Pattern>
57
60
  </Anti_Patterns>
58
61
 
59
62
  <Execution_Plan>
@@ -1,7 +1,7 @@
1
1
  <SddCritic keywords="critic, spec-review, task-review, bdd-audit, blind-spot, autonomous-polish, multi-round, pre-execute, orchestration" type="directive" ver="2.0">
2
2
  <Directive_Context>
3
3
  <Mission>
4
- Autonomous critique loop for SDD artifacts — spec, task, or batch (spec + all tasks). You are the ORCHESTRATOR in the root session. Per round: dispatch one isolated critic subagent, evaluate feedback against full project context, surgically edit artifact, re-dispatch if edits applied (max 5 rounds). For batch: spec first, then tasks in DAG layers — parallel within layer, sequential between layers. On CLEAN: delete `## Critic Rounds` (temporary scaffolding). Artifact is clean, improvements integrated.
4
+ Autonomous critique loop for SDD artifacts — spec, task, or batch (spec + all tasks). You are the ORCHESTRATOR in the root session. Per round: dispatch one isolated critic subagent, evaluate feedback against full project context, reconcile every introduced entity against existing project surface (reuse > extend > justify > escalate), surgically edit artifact, re-dispatch if edits applied (max 5 rounds). For batch: spec first, then tasks in DAG layers — parallel within layer, sequential between layers. On CLEAN: delete `## Critic Rounds` (temporary scaffolding). Artifact is clean, improvements integrated.
5
5
  </Mission>
6
6
  </Directive_Context>
7
7
 
@@ -15,6 +15,7 @@
15
15
  <Axiom id="AX_DEFAULT_ACCEPT">Uncertain → ACCEPT. Cost of rejecting real finding > cost of accepting marginal one.</Axiom>
16
16
  <Axiom id="AX_CONFUSION_BUG">Critic confusion ("don't understand X") → artifact underspecified → ALWAYS accept, clarify.</Axiom>
17
17
  <Axiom id="AX_SURGICAL">Close the gap only. No restructure, rewrite, restyle. Structural overhaul → suggest re-scaffold, stop.</Axiom>
18
+ <Axiom id="AX_REUSE_FIRST">Orchestrator holds full project context — the ONLY actor able to detect duplication against existing code/specs (the isolated critic cannot). For every entity/type/method/contract the artifact introduces, reconcile before accepting it: REUSE existing (adapt artifact to it) > EXTEND existing > JUSTIFY new (record one-line rationale in artifact: why existing surface is insufficient) > ESCALATE to operator. Unjustified new surface is a finding to resolve, not to wave through. Bias toward consolidation — do not let the system grow a duplicate entity each round.</Axiom>
18
19
  <Axiom id="AX_SCRATCH_LOG">`## Critic Rounds` = temporary working memory for orchestrator between rounds. Deleted on final CLEAN.</Axiom>
19
20
  <Axiom id="AX_TASK_PARALLEL">Tasks critiqued in DAG layers. Same layer (no inter-dependencies) → parallel dispatch. Different layers → sequential.</Axiom>
20
21
  <Axiom id="AX_LANG">Directive: English. Artifact prose (Critic Rounds, summary): Russian.</Axiom>
@@ -36,6 +37,7 @@
36
37
  <Pattern id="AP_OVEREDIT">Rewriting sections. Close the gap, don't redecorate.</Pattern>
37
38
  <Pattern id="AP_DISMISS_CONFUSION">Ignoring "I don't understand X". Always fix.</Pattern>
38
39
  <Pattern id="AP_VAGUE_REJECT">Rejecting without citing specific context.</Pattern>
40
+ <Pattern id="AP_ENTITY_SPRAWL">Accepting a new entity/type/method without first searching the project for one to reuse or extend. New surface every round = sprawl.</Pattern>
39
41
  </Anti_Patterns>
40
42
 
41
43
  <Execution_Plan>
@@ -71,14 +73,27 @@
71
73
  ACCEPT: genuine gap, misunderstanding reveals ambiguity, would break downstream agent, or uncertain (AX_DEFAULT_ACCEPT).
72
74
  REJECT: misreading no competent agent would make AND specific context cited that resolves it.
73
75
  Confusion points → ALWAYS accept (AX_CONFUSION_BUG).
74
- Zero accepted → go to STEP_5 (stop). Any accepted → go to STEP_3.
76
+ Go to STEP_2B (reconcile entities) — always, even with zero accepted findings.
77
+ </Action>
78
+ </Step>
79
+
80
+ <Step id="2B_RECONCILE">
81
+ <Goal>Reuse-first reconciliation — orchestrator-only, uses full project context (AX_REUSE_FIRST).</Goal>
82
+ <Action>
83
+ Round 1: reconcile EVERY entity/type/method/contract the artifact introduces. Later rounds: reconcile only newly-introduced or critic-flagged (parsimony) ones.
84
+ For each, search the project (code + sibling specs) for surface that already covers it, then classify:
85
+ - REUSE — existing covers it → edit artifact to point at it, drop the new declaration (surgical).
86
+ - EXTEND — existing should grow → note the extension target in the artifact, drop the duplicate (surgical).
87
+ - JUSTIFY — genuinely new → record one-line rationale in the artifact (why existing surface is insufficient) (surgical).
88
+ - ESCALATE — call unclear, OR consolidation requires merging/removing entities (structural) → surface to operator; H_STRUCTURAL if it needs re-scaffold. Do NOT perform structural consolidation yourself.
89
+ Surgical reuse/justify edits + accepted findings → go to STEP_3. Zero edits after reconciliation → go to STEP_5 (stop).
75
90
  </Action>
76
91
  </Step>
77
92
 
78
93
  <Step id="3_EDIT">
79
94
  <Goal>Surgical edit.</Goal>
80
95
  <Action>
81
- Per accepted finding: add missing BDD scenario, clarify boundary, correct entity ref, fill placeholder. Target only the gap. Structural rewrite → H_STRUCTURAL.
96
+ Per accepted finding: add missing BDD scenario, clarify boundary, correct entity ref, fill placeholder. Per reconcile decision: point at existing surface (REUSE/EXTEND) or record new-entity rationale (JUSTIFY). Target only the gap. Structural rewrite or entity merge/removal → H_STRUCTURAL / ESCALATE.
82
97
  </Action>
83
98
  </Step>
84
99
 
@@ -91,6 +106,7 @@
91
106
  - Verdict: <CLEAN|NEEDS_WORK|CRITICAL>
92
107
  - Accepted: N — <list>
93
108
  - Rejected: N — "<finding>" → <reason>
109
+ - Reconcile: <entity → REUSE <target> | EXTEND <target> | JUSTIFY <rationale> | ESCALATE>
94
110
  - Changes: <list>
95
111
  ```
96
112
  Append-only.
@@ -136,6 +152,10 @@
136
152
  - <change>
137
153
  - ...
138
154
 
155
+ ♻️ Reuse decisions:
156
+ - <entity> → REUSE <target> | EXTEND <target> | JUSTIFY <rationale> | ESCALATE <question>
157
+ - ...
158
+
139
159
  ⚠️ Unresolved (if not CLEAN):
140
160
  - <finding> → <recommendation>
141
161
 
@@ -154,5 +174,7 @@
154
174
  - Keep `## Critic Rounds` after CLEAN.
155
175
  - ACCEPT without edit.
156
176
  - REJECT without specific context.
177
+ - Accept a new entity without reuse-first reconciliation (AX_REUSE_FIRST).
178
+ - Structurally merge/remove entities yourself — ESCALATE instead.
157
179
  </HardForbidden>
158
180
  </SddCritic>
@@ -0,0 +1,150 @@
1
+ # ai/skills — AI-навыки для агентов
2
+
3
+ 15 навыков (13 SDD + alt-opinion + workspace-permission-setup) для Specification-Driven Development, мульти-модельного анализа и настройки автономной среды.
4
+
5
+ > `sdd-hooks-install` (хуки live-прогресса для `sdd-execute`) и `workspace-permission-setup` мигрированы в хранилище из `~/.claude/skills` — теперь под git и деплоятся через `sync-skills`.
6
+
7
+ ---
8
+
9
+ ## Типовые сценарии (Use Cases)
10
+
11
+ ### 1. Спроектировать новый модуль с нуля
12
+
13
+ ```bash
14
+ npx gennady sync-skills
15
+ ```
16
+
17
+ Затем в агенте: «@sdd-setup создай проект» → «@sdd-discover спроектируй scope vcs-client» → «@sdd-module-decomposition разбей на модули» → «@sdd-scaffold сгенерируй таски» → «@sdd-critic проверь таски» → «@sdd-execute TSK-01»
18
+
19
+ | Шаг | Навык | Что делает |
20
+ | --- | ----- | ---------- |
21
+ | 1 | `sdd-setup` | Инициализирует `specs/README.md` (Vision, Scope Graph, таблица скоупов) |
22
+ | 2 | `sdd-discover` | Создаёт `specs/<scope>/<scope>.spec.md` — видение, требования, архитектура |
23
+ | 3 | `sdd-module-decomposition` | Декомпозирует product/library scope на модульные спеки с инвентарём сущностей |
24
+ | 4 | `sdd-scaffold` | Генерирует DAG тасков из спек: Cascade Table, BDD, Phases Overview |
25
+ | 5 | `sdd-critic` | Многораундовая критика тасков: диспатчит критика, правит артефакт (до 5 раундов) |
26
+ | 6 | `sdd-execute` | Исполняет один таск от начала до конца: dispatch фаз → audit |
27
+
28
+ ### 2. Выполнить задачу
29
+
30
+ ```
31
+ @sdd-execute TSK-03
32
+ ```
33
+
34
+ Или: «выполни следующую», «execute pickable», «выбери что делать дальше».
35
+
36
+ Навык читает таск, диспатчит фазы одну за другой, закрывает round, диспатчит fresh-eyes audit.
37
+
38
+ ### 3. Выполнить пачку задач
39
+
40
+ ```
41
+ @sdd-execute-batch выполни всю очередь
42
+ ```
43
+
44
+ Параллелит таски с непересекающимися файлами. Опциональный epic-level audit.
45
+
46
+ ### 4. Проверить качество спеки / таска
47
+
48
+ ```
49
+ @sdd-critic проверь спеку cli/cli.spec.md
50
+ @sdd-critic проверь таск TSK-03
51
+ ```
52
+
53
+ Многораундовая критика (до 5 раундов): диспатчит изолированного критика, оценивает фидбек, правит артефакт.
54
+
55
+ ### 5. Продолжить / доработать существующую спеку
56
+
57
+ ```
58
+ @sdd-continue добавь sync-skills в cli
59
+ @sdd-continue измени архитектуру на event-driven
60
+ ```
61
+
62
+ Автоопределение режима: refine (добавить) или pivot (заменить).
63
+
64
+ ### 6. Проверить целостность SDD-воркфлоу
65
+
66
+ ```
67
+ @sdd-check
68
+ ```
69
+
70
+ Read-only: проверяет связность спек, синхронизацию трекеров, полноту execution-логов, консистентность DAG.
71
+
72
+ ### 7. Аудит завершённой задачи
73
+
74
+ ```
75
+ @sdd-audit TSK-05
76
+ ```
77
+
78
+ Fresh-eyes: читает таск + спеку + git diff, механический линтинг, верификация правил. Фидинги роутятся в артефакты (правки спек, переоткрытие тасков).
79
+
80
+ ### 8. Починить после ревью / sdd-check
81
+
82
+ ```
83
+ @sdd-fix найди и исправь проблемы из sdd-check
84
+ ```
85
+
86
+ Классифицирует фидинги, согласовывает с оператором, исполняет фиксы, переоткрывает таски, верифицирует.
87
+
88
+ ### 9. Спроектировать инфраструктурный скоуп
89
+
90
+ ```
91
+ @sdd-infra спроектируй infra-golang
92
+ ```
93
+
94
+ Для bootstrap'а tooling'а: package manager, type-checker, linter, formatter, test runner, git hooks, CI.
95
+
96
+ ### 10. Получить мульти-модельное мнение
97
+
98
+ ```
99
+ @alt-opinion оцени спеку cli/cli.spec.md
100
+ ```
101
+
102
+ Запускает 2+ модели параллельно, синтезирует через третью. Без аргументов — автоаудит текущего контекста сессии.
103
+
104
+ ---
105
+
106
+ ## Execution-паттерны
107
+
108
+ | Паттерн | Как работает | Навыки |
109
+ | ------- | ----------- | ------ |
110
+ | **Directive activation** | Извлечь intent → загрузить директиву → активироваться как она → выполнить план | sdd-setup, sdd-discover, sdd-module-decomposition, sdd-scaffold, sdd-audit, sdd-continue, sdd-critic, sdd-fix, sdd-infra |
111
+ | **Orchestrator** | Прочитать таск → dispatch фаз (typed Handoff) → dispatch audit. Сам код не пишет | sdd-execute, sdd-execute-batch |
112
+ | **CLI delegation** | Подготовить артефакт → вызвать `npx gennady alt-opinion` → показать результат | alt-opinion |
113
+ | **Read-only verifier** | Саморефлексия + механические проверки через `sdd scan`. Код не пишет | sdd-check |
114
+
115
+ ---
116
+
117
+ ## Структура навыка
118
+
119
+ ```
120
+ ai/skills/<name>/
121
+ ├── SKILL.md # YAML frontmatter (name, description, compatibility) + markdown body
122
+ ├── scripts/ # опционально: bash/js утилиты
123
+ └── *.prompt.md # опционально: кастомные промпты
124
+ ```
125
+
126
+ ---
127
+
128
+ ## Синхронизация в проекты
129
+
130
+ ```bash
131
+ # Синхронизировать все навыки
132
+ npx gennady sync-skills
133
+
134
+ # Предпросмотр
135
+ npx gennady sync-skills --dry-run
136
+
137
+ # Конкретный навык
138
+ npx gennady sync-skills sdd-execute
139
+ ```
140
+
141
+ Навыки деплоятся из `ai/skills/` → `.claude/skills/` проекта. Пути нормализуются: dev-пути (`~/Developer/gennady/...`) заменяются на продуктовые.
142
+
143
+ ---
144
+
145
+ ## Связанные спеки
146
+
147
+ - `specs/ai-skills/ai-skills.spec.md` — общая спека библиотеки
148
+ - `specs/ai-skills/skill-contract/skill-contract.spec.md` — контракт навыка
149
+ - `specs/ai-skills/sdd-skills/sdd-skills.spec.md` — SDD-навыки
150
+ - `specs/ai-skills/alt-opinion/alt-opinion.spec.md` — alt-opinion
@@ -42,9 +42,12 @@ Output: a compact self-assessment table before proceeding to mechanical checks.
42
42
  <ExecutionStrategy>
43
43
  **BATCH ALL READS.** Use the SDD scan tool for one-shot snapshot, then targeted reads.
44
44
 
45
- 1. **One bash call** to get comprehensive snapshot:
46
- `~/Developer/gennady/ai/skills/sdd-execute/scripts/sdd scan <project-root>`
47
- This emits [HEADER] [TASKS] [TRACKERS] [SPECS] [WARNINGS] [SUMMARY] in a single call — replaces multiple find/grep commands.
45
+ 1. **Two bash calls** to get comprehensive snapshot + mechanical findings:
46
+ - `~/Developer/gennady/ai/skills/sdd-execute/scripts/sdd scan <project-root>`
47
+ → [HEADER] [TASKS] [TRACKERS] [SPECS] [WARNINGS] [SUMMARY] in one call.
48
+ - `~/Developer/gennady/ai/skills/sdd-execute/scripts/sdd check <project-root>`
49
+ → [TASKID] (collisions, orphan @tasks refs) + [TRACKER_SYNC] (ticket Meta.Status vs tracker row).
50
+ This is the SAME tool sdd-audit uses — do NOT re-implement these greps by hand (Checks 3 & 5b below read its output).
48
51
 
49
52
  2. **Concurrent reads** of all key files: Portal, scope specs (from SPECS list), trackers with issues (from WARNINGS). Do NOT read module specs initially — only if Check 2 needs them.
50
53
 
@@ -52,7 +55,7 @@ Output: a compact self-assessment table before proceeding to mechanical checks.
52
55
 
53
56
  4. **Do NOT scan code files.** Check 6 samples at most 3 files.
54
57
 
55
- Total: ≤5 tool calls for all 8 checks. Target: <15 seconds.
58
+ Total: ≤6 tool calls for all checks (scan + check + check --files + targeted reads). Target: <15 seconds.
56
59
  </ExecutionStrategy>
57
60
 
58
61
  <Checks>
@@ -66,9 +69,9 @@ Read `specs/README.md`. Verify: scopes table entries match `specs/<scope>/<scope
66
69
 
67
70
  For each scope spec 9/7: module paths resolve to files. Module spec 1 links to parent. Cross-scope references resolve.
68
71
 
69
- ### Check 3 — Tracker Sync (1 grep)
72
+ ### Check 3 — Tracker Sync (from `sdd check` [TRACKER_SYNC])
70
73
 
71
- `grep -rn "\[x\] DONE\|\[ \] TODO\|\[~\] IN_PROGRESS\|\[!\] BLOCKED" tasks/README.md tasks/*/README.md`. Compare counts.
74
+ Read the [TRACKER_SYNC] section of `sdd check`. Each row `match=NO` (ticket Meta.Status ≠ tracker row) or `NO_ROW` (ticket has no tracker row) is a FAIL with the Task-ID. `UNPARSEABLE` (old-template ticket without Meta.Status) → INFO, not a fail. Do NOT re-grep counts by hand.
72
75
 
73
76
  ### Check 4 — DAG Consistency (parse from tracker)
74
77
 
@@ -78,9 +81,15 @@ Parse `Dependencies:` from each task ticket planning surface. Topological sort.
78
81
 
79
82
  From scan [TASKS] output: check `placeholders` column for any task with >0. Flag tasks where placeholders > 0 even if status DONE. Also inspect `warnings` column for `no-execlog-section` or `anchors-mismatch`.
80
83
 
81
- ### Check 6 — File Headers (sample 3 files)
84
+ ### Check 5b — Task-ID Integrity (from `sdd check` [TASKID])
82
85
 
83
- Pick 3 recently modified .ts files from `git diff --name-only HEAD~3`. Check for `@file:`, `@consumers:`, `@tasks:`.
86
+ Read the [TASKID] section of `sdd check`. `collision` (one Task-ID on ≥2 ticket files) → FAIL (BLOCKER). `orphan` (a code `@tasks: TSK-NN` with no ticket file) → FAIL. Empty section → PASS. Same tool sdd-audit STEP_2_5 uses.
87
+
88
+ ### Check 6 — File Headers (from `sdd check --files`)
89
+
90
+ Pass recently modified source files to the shared checker instead of sampling by hand:
91
+ `sdd check --files $(git diff --name-only HEAD~3 | grep -E '\.(ts|js|sh|go)$')`.
92
+ Read [HEADERS]: `verdict=PARTIAL` (has some markers, missing `@file` or `@tasks`) or `NONE` on a code file → FAIL. `@consumers` absence alone → MINOR.
84
93
 
85
94
  ### Check 7 — Test Coverage (1 find)
86
95
 
@@ -107,7 +116,8 @@ First: Self-Reflection. Then: Mechanical Checks. Use compact single-line-per-che
107
116
  ▸ MECHANICAL
108
117
  ✅ Portal 4 scopes, graph ↔ table
109
118
  ✅ Spec linking all modules → parent, cross-scope refs resolve
110
- ✅ Tracker sync dbc 13/13 cli 7/7 vcs 1/1
119
+ ✅ Tracker sync dbc 13/13 cli 7/7 vcs 1/1 (sdd check [TRACKER_SYNC])
120
+ ✅ Task-ID no collisions, no orphan @tasks (sdd check [TASKID])
111
121
  ✅ DAG no cycles, all deps satisfied
112
122
  ✅ Execution Log no <YYYY-MM-DD> placeholders in tasks
113
123
  ✅ File headers 21 files scanned, all have @file: + @consumers:
@@ -13,6 +13,7 @@ All scripts honor the contract: **never produce silent empty output**. On miss,
13
13
  ~/Developer/gennady/ai/skills/sdd-execute/scripts/sdd verify <file>... # comprehensive gate (typecheck + lint + grep)
14
14
  ~/Developer/gennady/ai/skills/sdd-execute/scripts/sdd check-blockers <ticket-file> # scan Execution Log per AX_BLOCKER_RESOLUTION_TRAIL
15
15
  ~/Developer/gennady/ai/skills/sdd-execute/scripts/sdd scan [project-root] # one-shot rich snapshot for triage skills
16
+ ~/Developer/gennady/ai/skills/sdd-execute/scripts/sdd check [root|--task TSK-NN|--files f...] # deterministic mechanical checks (shared by sdd-check + sdd-audit)
16
17
  ```
17
18
 
18
19
  Single permission rule covers all subcommands:
@@ -37,6 +38,8 @@ Or broader:
37
38
  | `verify.sh` | Three-gate verification: typecheck + gennady DBC lint + forbidden-construct grep |
38
39
  | `check-blockers.sh` | Detect unresolved BLOCKER entries in ticket Execution Log per `AX_BLOCKER_RESOLUTION_TRAIL` |
39
40
  | `scan.sh` | Emit comprehensive project snapshot ([HEADER]/[TASKS]/[TRACKERS]/[SPECS]/[WARNINGS]/[SUMMARY]). Designed so triage skills make ONE call instead of many ad-hoc find/grep. Surfaces suspicious states automatically (DONE+placeholders, DONE+active-blocker, anchor mismatch, unparseable Status, broken spec links). |
41
+ | `check.sh` | Deterministic mechanical checks — [TASKID] (collisions, orphan `@tasks`), [TRACKER_SYNC] (ticket Meta.Status vs tracker row), [HEADERS] (`--files` mode). Single source of mechanical truth shared by `sdd-check` (whole tree) and `sdd-audit` (scoped via `--task`/`--files`). Exit 0 clean / 3 findings / 2 structural / 4 bad-invocation. |
42
+ | `_sdd-lib.sh` | Shared artifact parsers (status, Task-ID, tracker-row, header flags) sourced by `check.sh`. Not executed directly. `scan.sh` migration to this lib pending. |
40
43
 
41
44
  ## Anchor convention (used by `extract`)
42
45
 
@@ -0,0 +1,60 @@
1
+ # @file: Shared SDD artifact parsers — sourced by scan.sh / check.sh, never executed directly.
2
+ # @consumers: check.sh (canonical), scan.sh (migration pending).
3
+ # @contract: pure functions of file contents; no stdout side effects beyond the echoed result.
4
+ #
5
+ # Why this lib exists:
6
+ # - check.sh and scan.sh both parse ticket Meta.Status, Task-ID, tracker rows, file headers.
7
+ # - One implementation here = no drift between the two SDD tree tools (the whole point of
8
+ # `sdd check`: a single source of mechanical truth that both sdd-check and sdd-audit consume).
9
+ #
10
+ # macOS bash 3.2 compatible: grep -E / sed -E / awk only. No grep -P, no GNU sed -i.
11
+
12
+ # Extract Meta.Status flag from a ticket. Echoes: DONE | TODO | IN_PROGRESS | BLOCKED | UNKNOWN
13
+ sdd_lib_status() {
14
+ local f="$1" line flag
15
+ line=$(head -60 "$f" 2>/dev/null | grep -m1 -E '^\s*-?\s*\*?\*?Status:\*?\*?\s*\[.\]' || true)
16
+ [[ -z "$line" ]] && { echo "UNKNOWN"; return; }
17
+ flag=$(echo "$line" | sed -nE 's/.*\[(.)\].*/\1/p')
18
+ case "$flag" in
19
+ x|X) echo "DONE" ;;
20
+ ' ') echo "TODO" ;;
21
+ '~') echo "IN_PROGRESS" ;;
22
+ '!') echo "BLOCKED" ;;
23
+ *) echo "UNKNOWN" ;;
24
+ esac
25
+ }
26
+
27
+ # Extract Task-ID (TSK-NN) from a ticket Meta. Echoes the ID or empty string.
28
+ sdd_lib_task_id() {
29
+ local f="$1"
30
+ head -30 "$f" 2>/dev/null \
31
+ | grep -m1 -oE 'Task-ID:\*?\*?\s*TSK-[0-9]+' \
32
+ | grep -oE 'TSK-[0-9]+' || true
33
+ }
34
+
35
+ # Map a tracker-row status cell (`[x]` DONE etc.) to canonical token for ONE Task-ID.
36
+ # Args: <tracker-file> <TSK-NN>. Echoes DONE|TODO|IN_PROGRESS|BLOCKED|UNKNOWN (UNKNOWN if no row).
37
+ sdd_lib_tracker_status() {
38
+ local tr="$1" id="$2" row flag
39
+ # Row form: | [TSK-NN](...) | ... | `[x]` DONE | ... | (also bare TSK-NN)
40
+ row=$(grep -m1 -E "\|[[:space:]]*\[?${id}[]\(]" "$tr" 2>/dev/null || true)
41
+ [[ -z "$row" ]] && { echo "UNKNOWN"; return; }
42
+ flag=$(echo "$row" | sed -nE 's/.*`?\[(.)\]`?[[:space:]]+(DONE|TODO|IN_PROGRESS|BLOCKED).*/\1/p')
43
+ case "$flag" in
44
+ x|X) echo "DONE" ;;
45
+ ' ') echo "TODO" ;;
46
+ '~') echo "IN_PROGRESS" ;;
47
+ '!') echo "BLOCKED" ;;
48
+ *) echo "UNKNOWN" ;;
49
+ esac
50
+ }
51
+
52
+ # Header-trio presence for a source file. Echoes three space-separated flags: <file> <consumers> <tasks>
53
+ # Each flag is 1 (marker present) or 0 (absent). `@tasks: N/A` counts as present.
54
+ sdd_lib_header_flags() {
55
+ local f="$1" hf=0 hc=0 ht=0
56
+ head -20 "$f" 2>/dev/null | grep -qE '@file:' && hf=1
57
+ head -20 "$f" 2>/dev/null | grep -qE '@consumers:' && hc=1
58
+ head -20 "$f" 2>/dev/null | grep -qE '@tasks:' && ht=1
59
+ echo "$hf $hc $ht"
60
+ }