create-vibe-maestro 0.4.2 → 0.4.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.
Files changed (66) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/README.md +9 -9
  3. package/dist/cli/context-run.js +10 -0
  4. package/dist/cli/maestro.js +25 -2
  5. package/dist/cli/pack-run.js +42 -3
  6. package/dist/cli/upgrade-run.js +44 -5
  7. package/dist/core/context.js +47 -2
  8. package/dist/core/doctor/index.js +1 -1
  9. package/dist/core/doctor/plans.js +3 -3
  10. package/dist/core/gitignore.js +3 -1
  11. package/dist/core/inventory.js +2 -10
  12. package/dist/core/pack.js +130 -12
  13. package/dist/core/plan.js +21 -2
  14. package/dist/core/preflight.js +6 -5
  15. package/dist/core/template.js +2 -1
  16. package/dist/core/text-diff.js +108 -0
  17. package/dist/core/upgrade/analyze.js +70 -4
  18. package/dist/core/upgrade/baseline.js +10 -0
  19. package/dist/core/upgrade/index.js +53 -10
  20. package/dist/core/upgrade/releases.js +93 -2
  21. package/docs/ROADMAP.md +7 -3
  22. package/docs/USER_GUIDE.md +69 -30
  23. package/package.json +1 -1
  24. package/registry/baseline/0.4.2/project/.claude/agents/code-reviewer.md +13 -0
  25. package/registry/baseline/0.4.2/project/.claude/rules/maestro.md +37 -0
  26. package/registry/baseline/0.4.2/project/maestro/runbooks/cowork-audit.md +11 -0
  27. package/registry/baseline/0.4.2/project/maestro/templates/handoff.md +25 -0
  28. package/registry/baseline/0.4.2/project/protocols/audit.md +5 -0
  29. package/registry/baseline/0.4.2/project/protocols/build.md +18 -0
  30. package/registry/baseline/0.4.2/project/protocols/completion.md +22 -0
  31. package/registry/baseline/0.4.2/project/protocols/handoff.md +15 -0
  32. package/registry/baseline/0.4.2/project/protocols/plan.md +149 -0
  33. package/registry/baseline/0.4.2/project/protocols/start.md +64 -0
  34. package/registry/baseline/0.4.2/project/protocols/wiki.md +9 -0
  35. package/registry/baseline/0.4.2/project/wiki/plans/README.md +131 -0
  36. package/registry/baseline/0.4.2/project/wiki/plans/TEMPLATE.md +75 -0
  37. package/registry/capabilities.v1.json +19 -19
  38. package/templates/project/.claude/agents/code-reviewer.md +18 -7
  39. package/templates/project/.claude/rules/maestro.md +6 -3
  40. package/templates/project/.claude/settings.json +1 -0
  41. package/templates/project/maestro/runbooks/cowork-audit.md +9 -2
  42. package/templates/project/maestro/templates/audit.md +31 -0
  43. package/templates/project/maestro/templates/handoff.md +5 -1
  44. package/templates/project/protocols/audit.md +70 -1
  45. package/templates/project/protocols/build.md +111 -9
  46. package/templates/project/protocols/completion.md +8 -7
  47. package/templates/project/protocols/handoff.md +3 -1
  48. package/templates/project/protocols/plan.md +32 -22
  49. package/templates/project/protocols/start.md +1 -1
  50. package/templates/project/protocols/wiki.md +10 -2
  51. package/templates/project/wiki/icebox.md +12 -0
  52. package/templates/project/wiki/index.md +1 -0
  53. package/templates/project/wiki/passport.md +1 -1
  54. package/templates/project/wiki/plans/0001-starter.md +13 -2
  55. package/templates/project/wiki/plans/README.md +7 -3
  56. package/templates/project/wiki/plans/TEMPLATE.md +13 -5
  57. /package/{templates → registry/baseline/0.4.2}/project/protocols/build/audit-phase.md +0 -0
  58. /package/{templates → registry/baseline/0.4.2}/project/protocols/build/audit-plan.md +0 -0
  59. /package/{templates → registry/baseline/0.4.2}/project/protocols/build/step-1-rules.md +0 -0
  60. /package/{templates → registry/baseline/0.4.2}/project/protocols/build/step-2-spec.md +0 -0
  61. /package/{templates → registry/baseline/0.4.2}/project/protocols/build/step-3-architecture.md +0 -0
  62. /package/{templates → registry/baseline/0.4.2}/project/protocols/build/step-5-feature-loop.md +0 -0
  63. /package/{templates → registry/baseline/0.4.2}/project/protocols/context-budget.md +0 -0
  64. /package/{templates → registry/baseline/0.4.2}/project/protocols/discovery.md +0 -0
  65. /package/{templates → registry/baseline/0.4.2}/project/protocols/lessons.md +0 -0
  66. /package/{templates → registry/baseline/0.4.2}/project/protocols/seams.md +0 -0
package/CHANGELOG.md CHANGED
@@ -4,6 +4,59 @@ All notable changes to Vibe Coding Maestro are documented here.
4
4
 
5
5
  The project follows Semantic Versioning while prerelease interfaces may still change between beta versions.
6
6
 
7
+ ## 0.4.3 — 2026-11-01
8
+
9
+ The fourth part of 0.4: checks, protocols and command fixes. Checks run once and only the fixes are re-checked; small tasks follow the same path as any plan; eight protocols instead of eighteen; `upgrade` shows its changes and can remove retired Maestro files; `pack` shows what goes to the customer before packing. The set of project files changes; `vibe-maestro upgrade` migrates projects from 0.4.2, 0.4.1, 0.4.0, 0.3.1, 0.3.0, 0.3.0-beta.1 – beta.4 and 0.2.0-beta.1.
10
+
11
+ ### Added
12
+
13
+ - **`upgrade --diff`** prints the changes themselves as unified-diff hunks: what is added, what changes line by line, what is removed. The plain proposal now shows the number of changed lines next to every file and points to `--diff`. `--diff` writes nothing and does not combine with `--apply` or `--json`. Line diff of its own, no dependencies.
14
+ - **`upgrade` removes retired Maestro files** — only those in its explicit list and only untouched ones (the previous source and the checksum match). A modified file stops the upgrade with a clear hint (bring it back or move your edits to your own file); a file already gone is skipped. Removal is part of the same transaction: bytes go to `backup/` first, a rollback brings them back; a folder emptied by removal goes away. Any other path missing from the new canon still stops the upgrade.
15
+ - **`maestro/templates/audit.md`** (managed): a check report in the format `doctor` accepts — header, `## Finding` with one-line fields, the fix check inside `resolution`, a new finding of the fix check as a new `## Finding`, «не исправляем» left `open`. IDs must be Latin letters, digits, `.`, `-`, `_` — `doctor` does not see a finding with another ID; the sample and the Cowork runbook say so.
16
+ - **`wiki/icebox.md`** (belongs to the project): ideas set aside — why and when to come back; unfixed check findings may point here.
17
+ - **`pack --dry-run`** shows what goes into the archive and highlights what to look at, without writing a byte. Highlights: service files (`.gitignore`, `.gitattributes`, `.DS_Store`, `.vscode/`, `.idea/`, `.github/`, `*.log`), home, project and temporary paths, Maestro names, internal folders (`wiki/`, `maestro/`, `protocols/`, `.claude/`), plan numbers. A highlight is a warning: packing is not refused and the exit code is unchanged. Plain `pack` prints the highlights too; JSON gets `highlights` when there are any and `noAccess` when the passport has no accesses; `--dry-run` reports `dryRun`, `entries` and, before the tag exists, `untagged`. The root `.gitattributes` and `.gitignore` that Maestro writes are marked «оставьте» instead of «убрать».
18
+ - «Проверки на GitHub» in `protocols/build.md` and a short rule in `.claude/rules/maestro.md`: check locally with the same commands first, push in a batch after a closed slice, do not push while the previous run is going, run a GitHub check by hand only for what cannot be checked locally (at most once per slice, never instead of the local run), and after a push keep working instead of waiting; the result is looked at once — at the start of the next slice or before merging. An economical workflow sample: `concurrency` with `cancel-in-progress`, a quick job on branches, the full set on pull requests, `paths-ignore` for `wiki/`, `maestro/` and documents, a schedule only by the human's decision about cost.
19
+
20
+ ### Changed
21
+
22
+ - **Eight protocols instead of eighteen.** The text of ten small protocols moved verbatim, anchors included: working rules, specification, architecture, the task capsule and the TDD loop into `protocols/build.md`; plan audit, seams and council reconciliation into `protocols/audit.md`; lessons into `protocols/wiki.md`. `protocols/discovery.md` (only a pointer to the start since 0.4.2) is gone. Contract IDs `VCM-…` are unchanged; the capability ledger names the new owners.
23
+ - **Checks without an extra round** (owner's decision of 2026-11-01). `protocols/audit.md` is the single owner of check rules: what each check is for, when it runs (plan audit before approval and `preflight`, code review after a slice with green tests), strictness — the stricter of the plan's classification and the project depth, one scale for plans and code, one full round and then one check of the fixes only, what to hand the read-only reviewer, how to write the report. A plan draft is always checked against the real situation (`plan.md` Stage D: every FACT by a file, code or command output, a guess by experience or HYPOTHESIS), for every scale. Critical/high are fixed and only the fix is checked; medium/low are fixed or written down with a reason, and the work stops. The human's «проверь ещё раз» always means a check.
24
+ - **One scale** — `critical | high | medium | low` with meanings for plans and code, word for word the same in `protocols/audit.md`, `.claude/agents/code-reviewer.md` and the Cowork runbook. `doctor`'s own message levels (`critical`, `error`, `warning`, `info`) are a different thing and do not change.
25
+ - `code-reviewer` knows three kinds of work — slice review, plan audit, fix check — returns findings in the sample's format and writes no file: the author writes the report without changing the reviewer's words, IDs or evidence.
26
+ - `governance` of a plan is never below the project depth; below it, the depth applies. The starter `governance: light` plan in a `standard` project is no longer a contradiction.
27
+ - **A small task** (`QUICK`) has its mini-plan in `wiki/plans/` (`kind: mini`, `scale: quick`: goal, files, check, risk, stop gate, what was checked) and is approved and closed like any plan; one confirmed red test per set. A small edit while another plan is active becomes a new slice of that plan after the human's «да» and a new digest. «The plan must define…» applies to FEATURE and up.
28
+ - **Labels:** one table in `protocols/plan.md` with Russian names and when to use each; the plan template uses the same six; three are enough in conversation.
29
+ - **New session:** one sentence in four places — `.claude/rules/maestro.md`, `protocols/build.md`, `protocols/handoff.md`, `protocols/plan.md` — advised by `context`, also after plan approval (no longer «always a new session»).
30
+ - **Ask the human only about what they understand and own** — what we do, money, sending to people and publishing, deleting what cannot be restored, their accounts and settings. Tests, plan and code checks, fix checks and GitHub checks run inside the work. At the end of a slice, a plain-words summary in two or three lines; the handoff template has a «Итог для человека» section. No new confirmations.
31
+ - **Ticks do not break the approval digest:** `[x]`/`[X]` in list items count as `[ ]`; editing an item's text still closes the gate. Plans approved before keep working: the previous digest of unchanged text is accepted. The plan template lists «done» criteria as `- [ ]`.
32
+ - **`pack --out dist/`** (or `dist\`) is a folder: it is created and the archive goes inside under the default name (it used to become a file named `dist`).
33
+ - **`HANDOVER.md`** says «доступов не было, менять нечего» instead of «смените все пароли и ключи» only when every access section of the passport — «Где работает», «Домен и DNS», «Данные, базы, резервные копии», «Внешние сервисы и чей аккаунт», «Переменные окружения» — is «не применимо». Any doubt keeps the old step.
34
+ - **`context` takes the window from the model** named in the transcript: 200 000 for a closed list of past models (Claude 3.x, Opus 4/4.1/4.5, Sonnet 4/4.5, Haiku 4.5; a session already larger means 1 000 000, as before), 1 000 000 for newer Claude models. An unknown name is said plainly with a hint to use `--window`, which still wins. A «Модель … — окно …» line; JSON gains `model` and `windowSource`.
35
+ - `protocols/completion.md`: `pack --dry-run` first; the agent checks and cleans the list and gives the human a summary; packing and sending stay behind «да». What stays open, including findings «не исправляем», is named in the final handoff.
36
+ - The template engine leaves GitHub `${{ … }}` expressions alone; any other unknown `{{…}}` still fails.
37
+ - The `vibe-maestro` companion package (0.1.7) depends on exactly `create-vibe-maestro@0.4.3`.
38
+ - Upgrade tests use projects generated by the real published 0.4.2 package.
39
+ - From the independent review: a small edit mid-plan needs a corner check of the new slice and the usual slice review, not a new audit of the whole plan, unless it changes approach, boundaries, classification, data, security or deployment (one «new risk» list everywhere); deleting or rewriting a file in a normal commit is an edit, not a destructive action — a confirmation is for what cannot be restored; the GitHub workflow sample runs the quick job on every push, `main` included; `upgrade` reminds to add `wiki/icebox.md` to the project's own `wiki/index.md` and gives a complete hint for a modified retired file; `context` reads Bedrock `global.` model names and judges a session larger than 200 000 by the current model only; `pack` does not take a URL path for an internal folder or a year for a plan number and catches «по плану 0002»; the starter mini-plan has the QUICK shape.
40
+ - From the live run of a small task: a medium/low fixed after the last fix check closes without a new round; a review with no findings is written in the slice handoff, not in `wiki/audits/` (doctor needs at least one finding); `preflight` and `doctor` name both kinds of «да» for a changed plan — a repeated «план утверждаю» or the «да» to a small edit mid-plan; `pack --dry-run` works before the delivery tag (it shows the last commit), so the list is cleaned before the tag is set once; the tag name goes into the passport before tagging; the passport template and `pack` say that «не применимо» with an explanation counts as an access record.
41
+
42
+ ### For those who create projects with their own scripts
43
+
44
+ - **Fewer protocols.** Removed: `protocols/discovery.md`, `seams.md`, `lessons.md`, `context-budget.md` and the `protocols/build/` folder. Their text is in `protocols/build.md`, `protocols/audit.md`, `protocols/wiki.md`; the `VCM-…` anchors are unchanged. If you link to the old paths, replace them.
45
+ - **`upgrade` removes** untouched Maestro files that left the canon; a modified one stops it (`upgrade-removed-modified`). `--json` gains the field `removes`; the rest is unchanged. `upgrade --diff` shows the changes themselves. A project's own `maestro/templates/audit.md` stops the upgrade (`upgrade-template-collision`): rename it.
46
+ - **New files:** `maestro/templates/audit.md` (Maestro), `wiki/icebox.md` (project). Projects before 0.4.3: `.claude/settings.json` belongs to the project — add `Edit(/maestro/templates/audit.md)` to `deny` if you want the same protection.
47
+ - **Labels do not change:** FACT, HYPOTHESIS, UNKNOWN, HUMAN_DECISION, AGENT_PROPOSAL, OPEN_QUESTION.
48
+ - **The report scale is the same** — `critical|high|medium|low`; there is now a sample. `doctor`'s rules for `wiki/audits/` do not change; finding IDs must be Latin letters, digits, `.`, `-`, `_`. Medium/low left unfixed stay `status: open` with `resolution: не исправляем — причина; где записано` — `doctor` stays green; critical/high are closed only after a verified fix. `doctor`'s own message levels do not change.
49
+ - **Checks:** the plan is always checked against the real situation; after code review only the fixes are checked. A hub rule like «a clean plan — one round; only medium/low — write down and go on» agrees with this and may stay.
50
+ - **QUICK mini-plan** lives in `wiki/plans/` (`kind: mini`, `scale: quick`) and is approved like any plan. `preflight --scale quick --quick …` works as before, but the protocols no longer offer it.
51
+ - **Strictness — the stricter of two:** the plan's classification and the project depth. Small tasks run lighter in a `--depth light` project; whoever creates the project chooses.
52
+ - **Plan digest:** `[x]` ticks in lists are not counted; old digests of unchanged plans are accepted.
53
+ - **`pack`:** `--out` ending with `/` or `\` is a folder; `--dry-run` shows the list without writing (before the tag it shows the last commit); highlights are warnings, the exit code is unchanged, JSON gains `highlights`, `noAccess`, and in dry-run `dryRun`, `entries`, `untagged`; without accesses in the passport `HANDOVER.md` says «доступов не было» instead of «смените все пароли и ключи» — if your script looks for that line, take it into account.
54
+ - **`context`:** the window comes from the model in the transcript; the line «За сессию модель получила на вход …» and the `totalInputTokens` field are unchanged; JSON gains `model` and `windowSource`.
55
+ - **GitHub checks:** the agent's rule — check locally before pushing, push in a batch, run a GitHub check by hand only for what cannot be checked locally, do not wait after a push. The template's `.claude/settings.json` gains no `ask` rule for it.
56
+ - **Asking the human:** only about what they understand and own; technical checks run without questions, the slice summary is in plain words. No new confirmations.
57
+ - **Unchanged:** section names of `wiki/hot.md`, the `start:` flag in `wiki/concepts/discovery.md`, the materials place `maestro/inbox/` and the `-text` rule, `create --yes` without a repository.
58
+ - The `vibe-maestro` companion 0.1.7 depends on exactly `create-vibe-maestro@0.4.3`.
59
+
7
60
  ## 0.4.2 — 2026-11-01
8
61
 
9
62
  The third part of 0.4: starting a project. One first step everywhere — create → `/start` → `/plan`; materials in one place, kept byte for byte; a private copy in the cloud from day one. The set of project files changes; `vibe-maestro upgrade` migrates projects from 0.4.1, 0.4.0, 0.3.1, 0.3.0, 0.3.0-beta.1 – beta.4 and 0.2.0-beta.1.
package/README.md CHANGED
@@ -25,7 +25,7 @@
25
25
  </p>
26
26
 
27
27
  > [!IMPORTANT]
28
- > **0.4.2 is published on npm.** Create a project with `npx create-vibe-maestro@latest`. Every generated project records the exact Maestro version in `.claude/rules/maestro.md`, so its checks do not change under it when a new version is published; `vibe-maestro upgrade` moves it forward when you decide. Interfaces may still change before 1.0. The CLI and generated project templates are Russian-first; English localization is planned before a global release.
28
+ > **0.4.3 is published on npm.** Create a project with `npx create-vibe-maestro@latest`. Every generated project records the exact Maestro version in `.claude/rules/maestro.md`, so its checks do not change under it when a new version is published; `vibe-maestro upgrade` moves it forward when you decide. Interfaces may still change before 1.0. The CLI and generated project templates are Russian-first; English localization is planned before a global release.
29
29
 
30
30
  When an AI-assisted project lasts longer than one chat, the same problems keep returning:
31
31
 
@@ -78,7 +78,7 @@ Vibe Coding Maestro doctor: всё сходится.
78
78
  The second line is `info` (from local Git data only; it never fails `doctor`, `--strict` or `preflight`) and disappears once the project has a copy in the cloud. `@latest` above is the newest published Maestro. If it is newer than your project, `doctor` says so and prints the exact commands to check the project with its own version or to upgrade it.
79
79
 
80
80
  > [!WARNING]
81
- > **Core 0.3 creates new canonical projects only.** It can also re-check a complete project already created by the same canonical engine, and `vibe-maestro upgrade` can evolve a provably canonical project created by an earlier published version (0.2.0-beta.1, 0.3.0-beta.1 – 0.3.0-beta.4, 0.3.0, 0.3.1, 0.4.0, 0.4.1). It refuses to modify a non-empty, non-canonical directory, and no flag overrides that refusal. Safe conversion of arbitrary existing projects belongs to a separate future Converter.
81
+ > **Core 0.3 creates new canonical projects only.** It can also re-check a complete project already created by the same canonical engine, and `vibe-maestro upgrade` can evolve a provably canonical project created by an earlier published version (0.2.0-beta.1, 0.3.0-beta.1 – 0.3.0-beta.4, 0.3.0, 0.3.1, 0.4.0, 0.4.1, 0.4.2). It refuses to modify a non-empty, non-canonical directory, and no flag overrides that refusal. Safe conversion of arbitrary existing projects belongs to a separate future Converter.
82
82
 
83
83
  ## Что дальше после создания проекта: Planning Gate
84
84
 
@@ -114,7 +114,7 @@ npx --package create-vibe-maestro@latest vibe-maestro doctor --path .
114
114
 
115
115
  | Масштаб | Что создаётся |
116
116
  |---|---|
117
- | `QUICK` | mini-plan в `wiki/progress/`, без тяжёлого пакета планирования |
117
+ | `QUICK` | mini-plan в `wiki/plans/` — тот же путь, что у любого плана, без тяжёлого пакета планирования |
118
118
  | `FEATURE` | один план `wiki/plans/<номер>-<слаг>.md` |
119
119
  | `PROJECT` | полный пакет планирования в одном основном плане |
120
120
  | `PROGRAM` / `INTEGRATION` | `wiki/programs/<слаг>/`: программа, фазы и source inventory |
@@ -148,7 +148,7 @@ My Project/
148
148
  ├── .claude/settings.json # yours: default deny/ask rules (Maestro files, push, publish)
149
149
  ├── .claude/commands/ # /start, /status, /plan, /build, /wiki, /handoff adapters
150
150
  ├── .claude/agents/ # read-only code-reviewer and explorer
151
- ├── protocols/ # canonical rules for planning, building, handoff and project completion
151
+ ├── protocols/ # eight canonical protocols: start, plan, build, audit, wiki, status, handoff, completion
152
152
  ├── wiki/ # shared memory: start answers, plans, decisions, progress, audits, passport, restore page
153
153
  ├── maestro/ # inbox for your materials (kept byte for byte), runbooks, and templates
154
154
  └── .maestro/ # manifest, ownership inventory and integrity metadata
@@ -178,7 +178,7 @@ From there, `protocols/build.md` routes the agent through the relevant rules, pl
178
178
 
179
179
  ## A normal working cycle
180
180
 
181
- The guided path above is the whole cycle: material in `maestro/inbox/` → `/start` (getting to know the task) → plan → human approval → one bounded build with tests and live evidence → `doctor` → handoff, then a new session for the next slice (`vibe-maestro context` tells the agent how large the session has grown). When the last slice is done, `protocols/completion.md` walks through delivery or closing: criteria checked, tests green, a delivery tag, a complete project passport (`wiki/passport.md`: where everything lives, names of environment variables but never their values), customer documents, a final handoff; `vibe-maestro pack` builds the customer archive from the delivery tag. Independent audit findings are recorded with stable IDs; open `high` or `critical` findings block a green doctor result.
181
+ The guided path above is the whole cycle: material in `maestro/inbox/` → `/start` (getting to know the task) → plan → human approval → one bounded build with tests and live evidence → `doctor` → handoff, then a new session for the next slice (`vibe-maestro context` tells the agent how large the session has grown). When the last slice is done, `protocols/completion.md` walks through delivery or closing: criteria checked, tests green, a delivery tag, a complete project passport (`wiki/passport.md`: where everything lives, names of environment variables but never their values), customer documents, a final handoff; `vibe-maestro pack` builds the customer archive from the delivery tag. Checks run once: the plan is always checked against the real situation, a plan audit before approval, one code review per slice, then only the fixes are re-checked; the agent runs tests and checks itself and asks the human only about what they understand and own. Independent audit findings are recorded with stable IDs on one `critical | high | medium | low` scale (sample: `maestro/templates/audit.md`); open `high` or `critical` findings block a green doctor result.
182
182
 
183
183
  Claude Code projects receive six thin commands:
184
184
 
@@ -206,8 +206,8 @@ Maestro is deliberately conservative around existing data and Git state:
206
206
  - `.claude/settings.json` ships default rules for Claude Code: its file tools are denied Maestro files, and `git push`, `npm publish`, `rm -rf` and `git reset --hard` ask first; this is not a sandbox, and the file belongs to the project, so a team can change the rules — see [how to tune protections for a project](docs/USER_GUIDE.md#как-подстроить-защиты-под-проект) (Russian);
207
207
  - API keys live only in `.env`, which `.gitignore` excludes and `doctor` reports if Git tracks it; the agent writes a key you paste into `.env` itself, or opens `.env` in an editor for you to paste it (a key typed into the chat stays in the session history);
208
208
  - `sources` reads existing code read-only and writes nothing without an explicit `--write`;
209
- - `pack` builds the customer archive only from a delivery tag, leaves Maestro and agent folders out, adds `HANDOVER.md` with «change all passwords and keys», refuses on common kinds of secrets (a sieve, not a guarantee) or an incomplete passport, and gives the same bytes for the same tag;
210
- - `upgrade` is a dry run without `--apply`, refuses a modified managed file, and rolls back a failed apply;
209
+ - `pack` builds the customer archive only from a delivery tag, leaves Maestro and agent folders out, adds `HANDOVER.md` with «change all passwords and keys» (or «there were no accesses» when every access section of the passport is «не применимо»), refuses on common kinds of secrets (a sieve, not a guarantee) or an incomplete passport, and gives the same bytes for the same tag; `pack --dry-run` shows the archive list first and highlights service files, personal paths, Maestro names, internal folders and plan numbers;
210
+ - `upgrade` is a dry run without `--apply` (`--diff` prints the changes themselves), refuses a modified managed file, removes only untouched Maestro files that left the canon, and rolls back a failed apply;
211
211
  - generated projects pin the exact Maestro version instead of `@latest`, so a new release cannot change a project's checks until someone runs `upgrade`;
212
212
  - there is intentionally no `doctor --fix` that could overwrite useful work.
213
213
 
@@ -271,7 +271,7 @@ Run the preview from the project folder; it writes nothing:
271
271
  npx --package create-vibe-maestro@latest vibe-maestro upgrade --path .
272
272
  ```
273
273
 
274
- It lists every file it would add or update and prints the exact command, with the exact version, that applies the change (`--apply`). A file you edited by hand is never overwritten: the upgrade stops and names it. Moving to 0.4.2 adds the `/start` command and protocol, `maestro/inbox/.gitattributes` and `wiki/restore.md`, and a `README.md` only if the project has no README of any name; if materials already sit in `maestro/inbox/`, run `git add --renormalize maestro/inbox` before committing so Git keeps them byte for byte. After applying, add all changes to Git including the new files (`git add -A`), review and commit them — until then `doctor` reports the uncommitted and untracked Maestro files — then run `doctor --strict` with the same version.
274
+ It lists every file it would add, update or remove, with changed line counts, and prints the exact command, with the exact version, that applies the change (`--apply`); `--diff` prints the changes line by line. A file you edited by hand is never overwritten or removed: the upgrade stops and names it. Moving to 0.4.3 removes ten small protocols whose text moved into `protocols/build.md`, `protocols/audit.md` and `protocols/wiki.md`, and adds `maestro/templates/audit.md` and `wiki/icebox.md`. Moving to 0.4.2 adds the `/start` command and protocol, `maestro/inbox/.gitattributes` and `wiki/restore.md`, and a `README.md` only if the project has no README of any name; if materials already sit in `maestro/inbox/`, run `git add --renormalize maestro/inbox` before committing so Git keeps them byte for byte. After applying, add all changes to Git including the new files (`git add -A`), review and commit them — until then `doctor` reports the uncommitted and untracked Maestro files — then run `doctor --strict` with the same version.
275
275
 
276
276
  ## Automation and CI
277
277
 
@@ -294,7 +294,7 @@ npx --package create-vibe-maestro@latest vibe-maestro upgrade --path .
294
294
 
295
295
  `preflight` and `doctor` exit `0` when the check passes and `1` when it blocks; `sources` and `upgrade` write nothing at all unless you add `--write` or `--apply`.
296
296
 
297
- The repository release gate covers tests, type checking, build, audit, source acceptance, packed-tarball installation, all three depths, paths with spaces, deterministic doctor JSON, protocol drift, canonical identity forgery, incomplete canonical trees, forbidden audit waivers, symlink boundaries, and upgrades from projects created by the published 0.3 betas, 0.3.x, 0.4.0 and 0.4.1. Pull requests and `main` run on Ubuntu, macOS, and Windows with Node.js 20 and 22; a branch push runs one quick Ubuntu job.
297
+ The repository release gate covers tests, type checking, build, audit, source acceptance, packed-tarball installation, all three depths, paths with spaces, deterministic doctor JSON, protocol drift, canonical identity forgery, incomplete canonical trees, forbidden audit waivers, symlink boundaries, and upgrades from projects created by the published 0.3 betas, 0.3.x, 0.4.0, 0.4.1 and 0.4.2. Pull requests and `main` run on Ubuntu, macOS, and Windows with Node.js 20 and 22; a branch push runs one quick Ubuntu job.
298
298
 
299
299
  ## Current scope
300
300
 
@@ -18,6 +18,15 @@ const ADVICE = {
18
18
  'finish-slice': 'Порцию лучше закончить в этой сессии, а следующую начать в новой — после передачи дел (/handoff).',
19
19
  'new-session': 'Пора в новую сессию: сделайте передачу дел (/handoff) сейчас и продолжайте в новой.',
20
20
  };
21
+ /** Откуда взято окно — одной строкой. */
22
+ function windowLine(source, model, budget) {
23
+ if (source === 'option')
24
+ return `Окно задано вручную (--window): ${formatTokens(budget)} ${tokensWord(budget)}.`;
25
+ if (source === 'model' && model !== undefined)
26
+ return `Модель ${model} — окно ${formatTokens(budget)} ${tokensWord(budget)}.`;
27
+ const name = model === undefined ? 'в журнале не названа' : `«${model}» мне незнакома`;
28
+ return `Модель ${name}: окно взято ${formatTokens(budget)} ${tokensWord(budget)} по размеру сессии. Знаете окно этой модели — задайте его: --window <токены>.`;
29
+ }
21
30
  export async function executeContextCommand(options, io) {
22
31
  const report = await measureContext({ root: options.path, ...(options.window === undefined ? {} : { budget: options.window }) });
23
32
  if (options.json) {
@@ -30,6 +39,7 @@ export async function executeContextCommand(options, io) {
30
39
  }
31
40
  const tokens = report.contextTokens ?? 0;
32
41
  io.out(`Размер сессии: ${formatTokens(tokens)} ${tokensWord(tokens)} (${report.percent}% окна модели в ${formatTokens(report.budget)}).`);
42
+ io.out(windowLine(report.windowSource, report.model, report.budget));
33
43
  io.out(ADVICE[report.level]);
34
44
  const total = report.totalInputTokens ?? 0;
35
45
  io.out(`За сессию модель получила на вход ${formatTokens(total)} ${tokensWord(total)} (шагов модели: ${report.requests}): каждый шаг заново пересылает всю историю.`);
@@ -31,14 +31,16 @@ const HELP = `${PRODUCT_NAME} — служебный CLI проекта.
31
31
 
32
32
  Опции upgrade:
33
33
  --apply выполнить обновление; без флага это только dry-run
34
+ --diff показать сами правки построчно (только просмотр, ни байта не пишет)
34
35
 
35
36
  Опции pack:
36
37
  --tag <тег> тег сдачи (обязательно)
37
- --out <файл> куда записать архив (по умолчанию — Рабочий стол)
38
+ --out <файл> куда записать архив (по умолчанию — Рабочий стол); путь с / или \ на конце — папка
38
39
  --allow <путь> файл, который человек проверил: не секрет; флаг можно повторять
40
+ --dry-run состав архива с подсветкой внутреннего; ничего не пишет
39
41
 
40
42
  Опции context:
41
- --window <токены> окно модели в токенах (по умолчанию 200000, у длинной сессии 1000000)
43
+ --window <токены> окно модели в токенах (по умолчанию — по модели из журнала сессии)
42
44
 
43
45
  Опции preflight:
44
46
  --scale <масштаб> ${PLAN_SCALES.join(' | ')} (по умолчанию feature)
@@ -87,6 +89,13 @@ export function parseMaestroArgs(argv) {
87
89
  options.apply = true;
88
90
  break;
89
91
  }
92
+ case '--diff': {
93
+ const message = only(arg, 'upgrade');
94
+ if (message !== null)
95
+ return { kind: 'error', message };
96
+ options.diff = true;
97
+ break;
98
+ }
90
99
  case '--scale': {
91
100
  const message = only(arg, 'preflight');
92
101
  if (message !== null)
@@ -170,6 +179,13 @@ export function parseMaestroArgs(argv) {
170
179
  i += 1;
171
180
  break;
172
181
  }
182
+ case '--dry-run': {
183
+ const message = only(arg, 'pack');
184
+ if (message !== null)
185
+ return { kind: 'error', message };
186
+ options.dryRun = true;
187
+ break;
188
+ }
173
189
  case '--allow': {
174
190
  const message = only(arg, 'pack');
175
191
  if (message !== null)
@@ -207,6 +223,13 @@ export function parseMaestroArgs(argv) {
207
223
  return { kind: 'error', message: `Лишний аргумент: ${arg}` };
208
224
  }
209
225
  }
226
+ if (first === 'upgrade' && options.diff === true) {
227
+ if (options.apply === true)
228
+ return { kind: 'error', message: 'Флаг --diff только показывает правки и не сочетается с --apply: сначала посмотрите, затем примените отдельной командой.' };
229
+ // Отчёт --json по договору не содержит текста файлов.
230
+ if (options.json)
231
+ return { kind: 'error', message: 'Флаг --diff показывает правки текстом и не сочетается с --json: отчёт --json содержимого файлов не содержит.' };
232
+ }
210
233
  if (first === 'pack' && options.tag === undefined) {
211
234
  return { kind: 'error', message: 'Команда pack требует --tag <тег сдачи>.' };
212
235
  }
@@ -1,9 +1,18 @@
1
1
  import { existsSync } from 'node:fs';
2
2
  import { dirname, join, resolve } from 'node:path';
3
+ import { quotePathArg, serviceInvocation, VERSION } from '../core/meta.js';
3
4
  import { defaultArchiveName, packProject } from '../core/pack.js';
4
5
  import { resolveDesktopDirectory } from './desktop.js';
5
6
  import { homedir } from 'node:os';
6
7
  import { EXIT_FAILED, EXIT_OK } from './io.js';
8
+ /** `--out dist/` или `--out dist\` — папка: архив ложится в неё под именем по умолчанию, папка создаётся. */
9
+ function outPath(out, root, tag) {
10
+ if (!/[\\/]$/.test(out))
11
+ return resolve(out);
12
+ return join(resolve(out.replace(/[\\/]+$/, '') || out), defaultArchiveName(root, tag));
13
+ }
14
+ /** Строка подсветки: путь, что найдено и где. */
15
+ const highlightLine = (item) => `${item.path} — ${item.reason}${item.line === undefined ? '' : ` (строка ${item.line})`}`;
7
16
  /** Архив по умолчанию кладётся на Рабочий стол: его оттуда отправляют заказчику. Нет Рабочего стола — рядом с проектом. */
8
17
  async function defaultOut(root, tag) {
9
18
  const name = defaultArchiveName(root, tag);
@@ -18,8 +27,8 @@ async function defaultOut(root, tag) {
18
27
  return join(dirname(resolve(root)), name);
19
28
  }
20
29
  export async function executePackCommand(options, io) {
21
- const out = options.out === undefined ? await defaultOut(options.path, options.tag) : resolve(options.out);
22
- const result = await packProject({ root: options.path, tag: options.tag, out, allow: options.allow ?? [] });
30
+ const out = options.out === undefined ? await defaultOut(options.path, options.tag) : outPath(options.out, options.path, options.tag);
31
+ const result = await packProject({ root: options.path, tag: options.tag, out, allow: options.allow ?? [], dryRun: options.dryRun === true });
23
32
  if (options.json) {
24
33
  io.out(JSON.stringify({ reportVersion: 1, ...result }, null, 2));
25
34
  return result.ok ? EXIT_OK : EXIT_FAILED;
@@ -30,11 +39,41 @@ export async function executePackCommand(options, io) {
30
39
  io.err(`- ${item.code}${item.path ? ` (${item.path})` : ''}: ${item.message}`);
31
40
  return EXIT_FAILED;
32
41
  }
42
+ const highlights = result.highlights ?? [];
43
+ if (result.dryRun === true) {
44
+ const marks = new Map();
45
+ for (const item of highlights)
46
+ marks.set(item.path, [...(marks.get(item.path) ?? []), `${item.reason}${item.line === undefined ? '' : ` (строка ${item.line})`}`]);
47
+ io.out(result.untagged === true
48
+ ? `Метки ${result.tag} ещё нет: показан состав последнего коммита (${(result.commit ?? '').slice(0, 7)}), ничего не записано; файлов — ${result.files}. Метку ставят на этот коммит — архив будет таким же; незакоммиченное в архив не попадёт.`
49
+ : `Состав архива тега ${result.tag} (ничего не записано): файлов — ${result.files}.`);
50
+ for (const path of result.entries ?? [])
51
+ io.out(` ${path}${marks.has(path) ? ` ← ${(marks.get(path) ?? []).join('; ')}` : ''}`);
52
+ for (const note of result.notes ?? [])
53
+ io.out(note);
54
+ const toCheck = highlights.filter((item) => !item.reason.includes('оставьте')).length;
55
+ io.out(toCheck === 0
56
+ ? `Убирать нечего${highlights.length > 0 ? ': подсвечены только файлы с пометкой «оставьте»' : ''}.`
57
+ : `Подсвечено к проверке — ${toCheck}: внутреннее уберите до упаковки (правка, коммит${result.untagged === true ? '' : ', новый тег'}); помеченное «оставьте» не трогайте. Подсветка — предупреждение, упаковку она не запрещает.`);
58
+ io.out(result.noAccess === true
59
+ ? 'HANDOVER.md: доступов не было — в паспорте все разделы о доступах «не применимо», менять заказчику нечего.'
60
+ : 'HANDOVER.md: первым делом заказчик меняет все пароли и ключи — в разделах паспорта о доступах есть записи. «Доступов не было» пишется, только если в каждом из них ровно «не применимо», без пояснений.');
61
+ const packCommand = `${serviceInvocation(VERSION)} pack --path ${quotePathArg(options.path)} --tag ${options.tag}${options.out === undefined ? '' : ` --out ${quotePathArg(options.out)}`}`;
62
+ io.out(result.untagged === true
63
+ ? `Дальше: имя метки ${options.tag} — в паспорт, коммит; метка (git tag -a ${options.tag}) — после «да» человека; затем упаковать: ${packCommand} — тоже после «да».`
64
+ : `Упаковать: ${packCommand} — только после «да» человека.`);
65
+ return EXIT_OK;
66
+ }
33
67
  io.out(result.reused === true
34
68
  ? `Архив тега ${result.tag} уже лежит здесь и совпадает побайтово: ${result.archive}`
35
69
  : `Архив тега ${result.tag} готов: ${result.archive}`);
36
70
  io.out(`Файлов: ${result.files}, размер: ${result.bytes} байт, sha256: ${result.sha256}`);
37
- io.out('Не вошли: wiki/, maestro/, .claude/, protocols/, .maestro/, CLAUDE.md, AGENTS.md, .mcp.json. В корне архива — HANDOVER.md: первым делом заказчик меняет все пароли и ключи.');
71
+ io.out(`Не вошли: wiki/, maestro/, .claude/, protocols/, .maestro/, CLAUDE.md, AGENTS.md, .mcp.json. В корне архива — HANDOVER.md: ${result.noAccess === true ? 'доступов не было, менять заказчику нечего' : 'первым делом заказчик меняет все пароли и ключи'}.`);
72
+ if (highlights.length > 0) {
73
+ io.out(`Подсвечено — проверьте перед отправкой (предупреждение, не отказ):`);
74
+ for (const item of highlights)
75
+ io.out(` ${highlightLine(item)}`);
76
+ }
38
77
  for (const note of result.notes ?? [])
39
78
  io.out(note);
40
79
  if ((options.allow ?? []).length > 0)
@@ -1,6 +1,19 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { join } from 'node:path';
1
3
  import { quotePathArg, serviceInvocation, VERSION } from '../core/meta.js';
2
- import { upgradeProject } from '../core/upgrade/index.js';
4
+ import { formatHunk } from '../core/text-diff.js';
5
+ import { upgradeDiffs, upgradeProject } from '../core/upgrade/index.js';
3
6
  import { EXIT_FAILED, EXIT_OK } from './io.js';
7
+ /** Сколько строк добавится и уберётся: «строк: +12 -5». */
8
+ function lineCounts({ added, removed }) {
9
+ const parts = [...(added > 0 ? [`+${added}`] : []), ...(removed > 0 ? [`-${removed}`] : [])];
10
+ return parts.length === 0 ? '' : ` (строк: ${parts.join(' ')})`;
11
+ }
12
+ const DIFF_TITLES = {
13
+ create: 'Будет добавлено',
14
+ update: 'Будет обновлено',
15
+ remove: 'Будет удалено',
16
+ };
4
17
  /**
5
18
  * Без `--apply` команда только показывает предложение: это dry-run по умолчанию,
6
19
  * а запись требует отдельного человеческого намерения.
@@ -42,6 +55,8 @@ export async function executeUpgradeCommand(options, io) {
42
55
  io.out(`Обновление применено: ${analysis.fromVersion ?? analysis.baselineId} → ${analysis.toVersion}.`);
43
56
  list('Добавлено', result.createdFiles);
44
57
  list('Обновлено', result.updatedFiles);
58
+ // Без Git удалённый текст остаётся только в пакете Maestro прошлой версии.
59
+ list(`Удалено (файлы Maestro, которых больше нет в составе; прежний текст — ${existsSync(join(analysis.root, '.git')) ? 'в истории Git' : 'в пакете Maestro прошлой версии'})`, result.removedFiles);
45
60
  list('Передано проекту (дальше файл ваш, Maestro его не проверяет и не перезаписывает)', analysis.handedOver);
46
61
  const keptAsIs = analysis.handedOver.filter((path) => !result.updatedFiles.includes(path));
47
62
  if (keptAsIs.length > 0)
@@ -50,21 +65,45 @@ export async function executeUpgradeCommand(options, io) {
50
65
  for (const note of analysis.notes)
51
66
  io.out(`Важно: ${note}`);
52
67
  // До коммита doctor честно покажет git-managed-dirty: сначала diff и коммит, потом проверка.
53
- io.out('Добавьте в Git все изменения, включая новые файлы (git add -A), просмотрите их (git diff --cached) и закоммитьте: до коммита doctor покажет git-managed-dirty и git-managed-untracked.');
68
+ io.out('Добавьте в Git все изменения, включая новые и удалённые файлы (git add -A), просмотрите их (git diff --cached) и закоммитьте: до коммита doctor покажет git-managed-dirty и git-managed-untracked.');
54
69
  // Та же версия, что применила обновление: doctor проверяет ровно её канон.
55
70
  io.out(`Затем проверьте: ${serviceInvocation(VERSION)} doctor --path ${quotePathArg(options.path)} --strict`);
56
71
  return EXIT_OK;
57
72
  }
73
+ const diffs = await upgradeDiffs(result.plan);
74
+ const counted = new Map(diffs.map((item) => [item.path, lineCounts(item.diff)]));
75
+ const apply = `Применить: ${serviceInvocation(VERSION)} upgrade --path ${quotePathArg(options.path)} --apply`;
76
+ if (options.diff === true) {
77
+ io.out(`Предложение обновления ${analysis.fromVersion ?? analysis.baselineId} → ${analysis.toVersion} (ни один байт не записан). Правки построчно: «+» — строка добавится, «-» — уберётся.`);
78
+ for (const item of diffs) {
79
+ io.out('');
80
+ io.out(`=== ${DIFF_TITLES[item.action]}: ${item.path}${counted.get(item.path) ?? ''}`);
81
+ for (const hunk of item.diff.hunks)
82
+ for (const line of formatHunk(hunk))
83
+ io.out(line);
84
+ }
85
+ io.out('');
86
+ list('Перейдёт к проекту (дальше файл ваш, Maestro его не проверяет и не перезаписывает)', analysis.handedOver);
87
+ list('Служебные файлы (пересчитываются)', analysis.metadata);
88
+ for (const note of analysis.notes)
89
+ io.out(`Важно: ${note}`);
90
+ io.out(apply);
91
+ return EXIT_OK;
92
+ }
58
93
  io.out(`Предложение обновления ${analysis.fromVersion ?? analysis.baselineId} → ${analysis.toVersion} (ни один байт не записан).`);
59
- list('Будет добавлено', analysis.creates.map((item) => item.path));
60
- list('Будет обновлено', analysis.updates.map((item) => item.appends === undefined ? item.path : `${item.path} — допишет строки: ${item.appends.join(', ')}`));
94
+ list('Будет добавлено', analysis.creates.map((item) => `${item.path}${counted.get(item.path) ?? ''}`));
95
+ list('Будет обновлено', analysis.updates.map((item) => item.appends === undefined
96
+ ? `${item.path}${counted.get(item.path) ?? ''}`
97
+ : `${item.path} — допишет строки: ${item.appends.join(', ')}`));
98
+ list('Будет удалено (файлы Maestro без ваших правок, которых больше нет в составе)', analysis.removes.map((path) => `${path}${counted.get(path) ?? ''}`));
61
99
  list('Перейдёт к проекту (дальше файл ваш, Maestro его не проверяет и не перезаписывает)', analysis.handedOver);
62
100
  list('Уже совпадает', analysis.unchanged);
63
101
  list('Останется без изменений', analysis.preserves);
64
102
  list('Служебные файлы', analysis.metadata);
65
103
  for (const note of analysis.notes)
66
104
  io.out(`Важно: ${note}`);
105
+ io.out(`Сами правки построчно: ${serviceInvocation(VERSION)} upgrade --path ${quotePathArg(options.path)} --diff (полный показ — сотни строк). Их читает агент и пересказывает человеку простыми словами, что изменится для него.`);
67
106
  // Применять обязана та же версия, что показала это предложение, а не новая @latest.
68
- io.out(`Применить: ${serviceInvocation(VERSION)} upgrade --path ${quotePathArg(options.path)} --apply`);
107
+ io.out(apply);
69
108
  return EXIT_OK;
70
109
  }
@@ -12,6 +12,35 @@ import { join, resolve } from 'node:path';
12
12
  /** Окно модели по умолчанию. Сессия больше него была бы невозможна — тогда окно 1 000 000. */
13
13
  export const DEFAULT_BUDGET = 200_000;
14
14
  export const LARGE_WINDOW = 1_000_000;
15
+ /**
16
+ * Окно модели по её названию в журнале (`message.model`); null — название незнакомо.
17
+ *
18
+ * Окно 200 000 — закрытый список прошлого: Claude 3.x, Opus 4 / 4.1 / 4.5, Sonnet 4 / 4.5,
19
+ * Haiku 4.5 (справочник моделей Anthropic на 06.10.2026). Модели Claude новее — Opus и Sonnet
20
+ * с 4.6, всё семейство 5 и новее, Fable и Mythos — 1 000 000 (HYPOTHESIS для будущих версий).
21
+ * Префикс площадки (`anthropic.`, `us.anthropic.`), дата выпуска и `@дата` Vertex отбрасываются.
22
+ */
23
+ export function windowForModel(model) {
24
+ // `[1m]` — так Claude Code называет модель с явно включённым окном 1 000 000.
25
+ if (/\[1m\]$/i.test(model.trim()))
26
+ return LARGE_WINDOW;
27
+ const name = model.trim().toLowerCase()
28
+ .replace(/^(?:[a-z]+\.)?anthropic\./, '')
29
+ .replace(/@\d{8}$/, '')
30
+ .replace(/-\d{8}(?:-v\d+:\d+)?$/, '');
31
+ if (/^claude-3(?:-\d)?-(?:opus|sonnet|haiku)$/.test(name))
32
+ return DEFAULT_BUDGET;
33
+ const match = /^claude-(opus|sonnet|haiku|fable|mythos)-(\d+)(?:-(\d))?$/.exec(name);
34
+ if (match === null)
35
+ return null;
36
+ const major = Number(match[2]);
37
+ const minor = Number(match[3] ?? '0');
38
+ if (major < 4)
39
+ return DEFAULT_BUDGET;
40
+ if (major === 4 && minor <= 5)
41
+ return DEFAULT_BUDGET;
42
+ return LARGE_WINDOW;
43
+ }
15
44
  /** HYPOTHESIS: пороги подобраны на глаз и уточняются повторным замером. */
16
45
  export const FINISH_SLICE_SHARE = 0.4;
17
46
  export const NEW_SESSION_SHARE = 0.7;
@@ -115,6 +144,9 @@ export async function measureContext(options) {
115
144
  }
116
145
  const seen = new Set();
117
146
  let last = null;
147
+ let lastModel;
148
+ /** Самый большой контекст у каждой модели: после смены модели окно судится по ней одной. */
149
+ const largestByModel = new Map();
118
150
  let totalInput = 0;
119
151
  let largest = 0;
120
152
  let recordedSession;
@@ -141,7 +173,9 @@ export async function measureContext(options) {
141
173
  if (size === 0)
142
174
  continue;
143
175
  last = usage;
176
+ lastModel = typeof entry.message?.model === 'string' ? entry.message.model : undefined;
144
177
  largest = Math.max(largest, size);
178
+ largestByModel.set(lastModel ?? '', Math.max(largestByModel.get(lastModel ?? '') ?? 0, size));
145
179
  if (seen.has(id))
146
180
  continue;
147
181
  seen.add(id);
@@ -151,8 +185,17 @@ export async function measureContext(options) {
151
185
  return { reportVersion: 1, ok: false, budget, transcript, message: 'В журнале сессии пока нет ни одного ответа модели.' };
152
186
  }
153
187
  const contextTokens = count(last.input_tokens) + count(last.cache_read_input_tokens) + count(last.cache_creation_input_tokens) + count(last.output_tokens);
154
- if (options.budget === undefined && largest > DEFAULT_BUDGET)
155
- budget = LARGE_WINDOW;
188
+ // `--window` главнее; иначе окно по модели; незнакомая модель — как раньше, по размеру сессии.
189
+ const byModel = lastModel === undefined ? null : windowForModel(lastModel);
190
+ let windowSource = 'option';
191
+ if (options.budget === undefined) {
192
+ windowSource = byModel === null ? 'unknown-model' : 'model';
193
+ budget = byModel ?? DEFAULT_BUDGET;
194
+ // Сессия больше 200 000 у модели «на 200 000» значит, что у неё включено окно 1 000 000.
195
+ // Смотрится только эта модель: прежняя модель с большим окном не раздувает окно новой.
196
+ if ((byModel === null ? largest : largestByModel.get(lastModel ?? '') ?? 0) > budget)
197
+ budget = LARGE_WINDOW;
198
+ }
156
199
  const share = contextTokens / budget;
157
200
  return {
158
201
  reportVersion: 1,
@@ -161,6 +204,8 @@ export async function measureContext(options) {
161
204
  ...(recordedSession === undefined ? {} : { sessionId: recordedSession }),
162
205
  contextTokens,
163
206
  budget,
207
+ ...(lastModel === undefined ? {} : { model: lastModel }),
208
+ windowSource,
164
209
  percent: Math.round(share * 100),
165
210
  level: levelFor(share),
166
211
  totalInputTokens: totalInput,
@@ -42,7 +42,7 @@ function versionFinding(rootInput, manifest, canonical) {
42
42
  : info('project-version-newer', `Проект обновлён более новой версией ${projectVersion}, а проверяет ${VERSION}. Точная проверка: ${checkSame}.`, MANIFEST_PATH);
43
43
  }
44
44
  return order < 0
45
- ? error('project-outdated', `Проект создан Vibe Coding Maestro ${projectVersion}, а запущена ${VERSION}: у этих версий разный состав файлов. Проверить проект его версией: ${checkSame}. Обновить проект до ${VERSION}: ${upgrade} (без --apply только показывает изменения).`, MANIFEST_PATH)
45
+ ? error('project-outdated', `Проект создан Vibe Coding Maestro ${projectVersion}, а запущена ${VERSION}: у этих версий разный состав файлов. Проверить проект его версией: ${checkSame}. Обновить проект до ${VERSION}: ${upgrade} (без --apply только показывает изменения, с --diff — сами правки построчно).`, MANIFEST_PATH)
46
46
  : error('project-newer', `Проект создан более новой версией ${projectVersion}, а запущена ${VERSION}. Проверьте проект его версией: ${checkSame}.`, MANIFEST_PATH);
47
47
  }
48
48
  export async function doctorProject(rootInput, options = {}) {
@@ -1,6 +1,6 @@
1
1
  import { existsSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
- import { ACTIVE_PLAN_NONE, APPROVAL_REQUIRED_STATUSES, isExternalSourceRef, isWikiRelativePlanRef, planBodyDigest, validatePlanFrontmatter } from '../plan.js';
3
+ import { ACTIVE_PLAN_NONE, APPROVAL_REQUIRED_STATUSES, isExternalSourceRef, isWikiRelativePlanRef, planDigestMatches, validatePlanFrontmatter } from '../plan.js';
4
4
  import { frontmatter } from './text.js';
5
5
  import { error } from './types.js';
6
6
  export const PLANS_DIR = 'wiki/plans';
@@ -40,8 +40,8 @@ export function checkPlans(root, decoded, findings) {
40
40
  if (plan === null)
41
41
  continue;
42
42
  plans.set(path, plan);
43
- if (APPROVAL_REQUIRED_STATUSES.includes(plan.status) && plan.approvedDigest !== null && plan.approvedDigest !== planBodyDigest(text)) {
44
- findings.push(error('plan-changed-after-approval', 'Текст утверждённого плана изменился после утверждения (approved_digest не совпадает). Покажите изменения человеку; после повторного «план утверждаю» запишите новый отпечаток из вывода preflight.', path));
43
+ if (APPROVAL_REQUIRED_STATUSES.includes(plan.status) && plan.approvedDigest !== null && !planDigestMatches(plan.approvedDigest, text)) {
44
+ findings.push(error('plan-changed-after-approval', 'Текст утверждённого плана изменился после утверждения (approved_digest не совпадает). Покажите изменения человеку; после его «да» — повторного «план утверждаю» или «да» на правку посреди плана (protocols/plan.md) — запишите новый отпечаток из вывода preflight.', path));
45
45
  }
46
46
  }
47
47
  const byId = new Map();
@@ -16,7 +16,9 @@ export const REQUIRED_GITIGNORE_ENTRIES = [
16
16
  '.claude/worktrees/',
17
17
  '.claude/settings.local.json',
18
18
  ];
19
- const BLOCK_HEADER = `# --- ${PRODUCT_NAME} ---`;
19
+ /** Заголовок блока Maestro в `.gitignore` проекта. */
20
+ export const GITIGNORE_BLOCK_HEADER = `# --- ${PRODUCT_NAME} ---`;
21
+ const BLOCK_HEADER = GITIGNORE_BLOCK_HEADER;
20
22
  /**
21
23
  * Приводит строку .gitignore к сравнимому виду.
22
24
  * node_modules и node_modules/ считаются одной записью, отступы не значимы.
@@ -17,6 +17,7 @@ export const TEMPLATE_FILES = [
17
17
  '.claude/agents/code-reviewer.md',
18
18
  '.claude/agents/explorer.md',
19
19
  'maestro/templates/handoff.md',
20
+ 'maestro/templates/audit.md',
20
21
  'maestro/templates/adr.md',
21
22
  'maestro/templates/progress.md',
22
23
  '.gitattributes',
@@ -24,20 +25,10 @@ export const TEMPLATE_FILES = [
24
25
  'protocols/status.md',
25
26
  'protocols/wiki.md',
26
27
  'protocols/handoff.md',
27
- 'protocols/discovery.md',
28
28
  'protocols/plan.md',
29
29
  'protocols/audit.md',
30
- 'protocols/context-budget.md',
31
- 'protocols/seams.md',
32
- 'protocols/lessons.md',
33
30
  'protocols/completion.md',
34
31
  'protocols/start.md',
35
- 'protocols/build/step-1-rules.md',
36
- 'protocols/build/step-2-spec.md',
37
- 'protocols/build/step-3-architecture.md',
38
- 'protocols/build/step-5-feature-loop.md',
39
- 'protocols/build/audit-plan.md',
40
- 'protocols/build/audit-phase.md',
41
32
  ];
42
33
  /** Стартовые содержательные документы: Maestro создаёт, затем ими владеет проект. */
43
34
  export const CONTENT_OWNED_FILES = [
@@ -51,6 +42,7 @@ export const CONTENT_OWNED_FILES = [
51
42
  'wiki/roadmap.md',
52
43
  'wiki/passport.md',
53
44
  'wiki/restore.md',
45
+ 'wiki/icebox.md',
54
46
  'wiki/concepts/discovery.md',
55
47
  'wiki/plans/0001-starter.md',
56
48
  ];