create-vibe-maestro 0.4.3 → 0.4.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 (52) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/README.md +6 -6
  3. package/dist/cli/archive-run.js +75 -0
  4. package/dist/cli/maestro.js +22 -3
  5. package/dist/core/archive/audits.js +37 -0
  6. package/dist/core/archive/disk.js +38 -0
  7. package/dist/core/archive/index.js +286 -0
  8. package/dist/core/archive/limits.js +27 -0
  9. package/dist/core/archive/links.js +65 -0
  10. package/dist/core/archive/log.js +83 -0
  11. package/dist/core/archive/markdown.js +28 -0
  12. package/dist/core/archive/plan.js +183 -0
  13. package/dist/core/archive/types.js +1 -0
  14. package/dist/core/audits.js +37 -0
  15. package/dist/core/doctor/fs-utils.js +3 -2
  16. package/dist/core/doctor/index.js +4 -1
  17. package/dist/core/doctor/memory.js +52 -0
  18. package/dist/core/doctor/plans.js +1 -1
  19. package/dist/core/doctor/wiki.js +9 -33
  20. package/dist/core/plan.js +26 -4
  21. package/dist/core/transaction.js +132 -0
  22. package/dist/core/upgrade/analyze.js +14 -3
  23. package/dist/core/upgrade/baseline.js +2 -0
  24. package/dist/core/upgrade/index.js +13 -112
  25. package/dist/core/upgrade/releases.js +51 -1
  26. package/dist/core/wiki-links.js +27 -0
  27. package/docs/ROADMAP.md +1 -1
  28. package/docs/USER_GUIDE.md +56 -13
  29. package/package.json +1 -1
  30. package/registry/baseline/0.4.3/project/.claude/rules/maestro.md +40 -0
  31. package/registry/baseline/0.4.3/project/maestro/templates/handoff.md +29 -0
  32. package/registry/baseline/0.4.3/project/protocols/build.md +120 -0
  33. package/registry/baseline/0.4.3/project/protocols/completion.md +23 -0
  34. package/registry/baseline/0.4.3/project/protocols/handoff.md +17 -0
  35. package/registry/baseline/0.4.3/project/protocols/plan.md +159 -0
  36. package/registry/baseline/0.4.3/project/protocols/status.md +5 -0
  37. package/registry/baseline/0.4.3/project/protocols/wiki.md +17 -0
  38. package/registry/baseline/0.4.3/project/wiki/plans/README.md +135 -0
  39. package/registry/baseline/0.4.3/project/wiki/plans/TEMPLATE.md +83 -0
  40. package/templates/project/.claude/rules/maestro.md +1 -0
  41. package/templates/project/maestro/templates/handoff.md +1 -1
  42. package/templates/project/protocols/build.md +3 -3
  43. package/templates/project/protocols/completion.md +2 -2
  44. package/templates/project/protocols/handoff.md +6 -5
  45. package/templates/project/protocols/plan.md +3 -2
  46. package/templates/project/protocols/status.md +1 -1
  47. package/templates/project/protocols/wiki.md +1 -1
  48. package/templates/project/wiki/index.md +4 -0
  49. package/templates/project/wiki/log.md +1 -0
  50. package/templates/project/wiki/plans/0001-starter.md +2 -2
  51. package/templates/project/wiki/plans/README.md +21 -1
  52. package/templates/project/wiki/plans/TEMPLATE.md +10 -1
package/CHANGELOG.md CHANGED
@@ -4,6 +4,45 @@ 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.4 — 2026-11-04
8
+
9
+ The fifth part of 0.4: project memory stops growing. A slice result goes to its handoff and the plan keeps one line; old log entries, closed check reports and closed plan edits move to an archive inside the project, and the agent reads the archive by search; `doctor` says when memory gets long. Nothing is deleted: the moved text stays byte for byte, only link addresses change.
10
+
11
+ ### Added
12
+
13
+ - **`vibe-maestro archive`** moves old memory into an archive inside the project in one transaction with a backup and rollback. Without `--apply` it only shows what it would move, with sizes; `--json` reports what moved, what stayed and why. It works only on a project of its own version (otherwise «first `upgrade`»), and refuses on a symbolic link on its paths, on a leftover staging folder of its own or of `upgrade`, and on a destination that git ignores. It never overwrites a file whose name differs only in case or Unicode form: a report stays with the reason, anything else is refused.
14
+ - **Log:** `wiki/log.md` over 20 000 characters — the last entries worth 10 000 characters stay (at least one), older ones go to `wiki/log/YYYY-MM.md` in their order. A pointer line is added to the log header once.
15
+ - **Check reports:** closed ones (`status: resolved`, all findings resolved) go to `wiki/audits/archive/`. Open reports, reports `doctor` cannot read and reports named in a plan's `sources` stay, with the reason.
16
+ - **Plan edits:** `--section "<heading start>"` (repeatable) moves a closed edit of the active plan to `wiki/plans/archive/<plan>.md`; the heading and a line «В архиве: …» stay in the plan. Only sections below «Правки после утверждения» or «Изменения после утверждения» can move; the main part of the plan, the collection itself, «Утверждение» and a section with the current slice in a heading are refused. A wrong name is refused with a list, not a byte written.
17
+ - **Links:** relative links in moved text are rebased, and links in `wiki/**` to a moved report lead to the new place. One link search for `doctor` and `archive`.
18
+ - **Approval digest:** when a plan has one, `archive` works only if the text matches it, then writes the new digest and a line with the date and both digests to the plan's archive. An unapproved edit cannot be laundered this way: a changed plan is refused, and a report it links to stays.
19
+ - **`doctor` reports memory length** as `info`, which never fails `--strict` or `preflight`, because the limits are a hypothesis from three live projects: `memory-hot-long` (6 000 characters), `memory-plan-long` (60 000), `memory-log-long` (20 000), `memory-handoff-long` (6 000, the handoffs with the latest date in the name). Each message gives the number, the guide and what to do.
20
+
21
+ ### Changed
22
+
23
+ - **A slice result lives in the handoff; the plan keeps one line.** Closing a slice: `[ ]` → `[x]` in «Порядок работ» or in the slice's edit, and the tail ` → [итог](../handoffs/<file>.md)` at the end of that line. Only where a `[ ]` exists: slices of older plans have no mark and get none. The result, acceptance and the move to the next slice are not written to the plan. `protocols/handoff.md`, `protocols/build.md`, `wiki/plans/README.md` and `wiki/plans/TEMPLATE.md` say the same.
24
+ - **The tail does not break the approval digest.** Exactly one tail of exactly this form at the end of a checked item is left out of the digest; another link text, another folder, a second tail, a tail on `[ ]` or on a continuation line is plan text. Without tails the digest equals 0.4.3, and plans approved with the 0.4.3 or the earlier digest stay green.
25
+ - **The agent runs `archive` itself** at the handoff of a closed slice and before the final handoff, without asking: it is a move inside the project. The human gets half a line in the summary. The agent names closed plan edits itself.
26
+ - **The archive is read by search.** `.claude/rules/maestro.md`, `protocols/wiki.md`, `protocols/build.md`, `protocols/plan.md` and `protocols/status.md`: find by name or word, read the piece found. To redo a closed part: a new edit mid-plan with a link to the archived one, with the human's «да». The archive is not edited by hand and not copied back. `wiki/attic/` holds outdated and replaced documents; the archive holds closed history.
27
+ - **«Правки после утверждения»** is a section of the plan template: an edit is `### Правка N — суть (дата)`. New plans list slices as `1. [ ]`.
28
+ - `wiki/hot.md`: the guide is now up to 6 000 characters, about 60 lines.
29
+ - `wiki/log.md` and `wiki/index.md` of new projects name the archive as plain paths; existing projects keep theirs, and `upgrade` reminds about the line in `wiki/index.md`.
30
+ - The `vibe-maestro` companion package (0.1.8) depends on exactly `create-vibe-maestro@0.4.4`.
31
+ - Upgrade tests use projects generated by the real published 0.4.3 package.
32
+
33
+ ### For those who create projects with their own scripts
34
+
35
+ - **New command `vibe-maestro archive`:** without `--apply` it writes nothing; `--json` gives the report (what moved, what stayed and why; `logNote` says why a long log has nothing to move, `partial: true` means a rollback failed and the project is changed in part); a refusal is exit code 1 with not a byte written. Works only on a project of its own version.
36
+ - **Log:** entries over the limit go to `wiki/log/YYYY-MM.md`; `wiki/log.md` stays the main file, with a line about months in the header. If a script reads the log, it should read `wiki/log/` too.
37
+ - **Check reports:** closed ones (`status: resolved`) go to `wiki/audits/archive/`; open ones stay in `wiki/audits/`; `doctor` checks both folders.
38
+ - **Plan archive** is `wiki/plans/archive/<plan>.md`, not a plan; the heading and a line with a link stay in the plan; `archive` rewrites `approved_digest` only for an unchanged approved plan.
39
+ - **Links:** `archive` fixes link addresses inside `wiki/`; links to moved files from `README.md`, `docs/` and other places outside `wiki/` are not touched. Paths written as plain text stay old: the file is found by name.
40
+ - **Digest:** on a `[x]` item the tail ` → [итог](../handoffs/<file>.md)` is left out; without tails the digest is the same.
41
+ - **`doctor`:** new `info` codes `memory-hot-long`, `memory-plan-long`, `memory-log-long`, `memory-handoff-long`; they do not fail `--strict` or `preflight`.
42
+ - **Do not change:** the section names of `wiki/hot.md`; the place and names of handoffs `wiki/handoffs/YYYY-MM-DD-….md`; `create --yes`; the set of Maestro files; `.claude/settings.json` of the template.
43
+ - **Projects before 0.4.4:** `wiki/index.md` belongs to the project; add the line about the archive if you want it.
44
+ - The `vibe-maestro` companion 0.1.8 is exactly `create-vibe-maestro@0.4.4`. `upgrade` works from 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 and 0.4.3.
45
+
7
46
  ## 0.4.3 — 2026-11-01
8
47
 
9
48
  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.
package/README.md CHANGED
@@ -25,7 +25,7 @@
25
25
  </p>
26
26
 
27
27
  > [!IMPORTANT]
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.
28
+ > **0.4.4 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, 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.
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, 0.4.3). 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
 
@@ -207,7 +207,7 @@ Maestro is deliberately conservative around existing data and Git state:
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
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;
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; `archive` moves old memory inside the project the same way — nothing deleted, text byte for byte except link addresses, a plan's approval digest rewritten only when the text matched it;
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
 
@@ -289,12 +289,12 @@ npx --package create-vibe-maestro@latest vibe-maestro doctor --path . --strict
289
289
  npx --package create-vibe-maestro@latest vibe-maestro skills --path .
290
290
  npx --package create-vibe-maestro@latest vibe-maestro preflight --path . --json
291
291
  npx --package create-vibe-maestro@latest vibe-maestro sources --path . --source "../durak" --source "../dice-poker"
292
- npx --package create-vibe-maestro@latest vibe-maestro upgrade --path .
292
+ npx --package create-vibe-maestro@latest vibe-maestro archive --path .
293
293
  ```
294
294
 
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`.
295
+ `preflight` and `doctor` exit `0` when the check passes and `1` when it blocks; `sources`, `upgrade` and `archive` 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, 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.
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, 0.4.2 and 0.4.3. 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
 
@@ -0,0 +1,75 @@
1
+ import { AUDITS_ARCHIVE_DIR } from '../core/archive/audits.js';
2
+ import { formatChars } from '../core/archive/limits.js';
3
+ import { archiveProject } from '../core/archive/index.js';
4
+ import { plainTitle } from '../core/archive/plan.js';
5
+ import { quotePathArg, serviceInvocation, VERSION } from '../core/meta.js';
6
+ import { EXIT_FAILED, EXIT_OK } from './io.js';
7
+ const DIGEST_SHOWN = 12;
8
+ function describe(report, io) {
9
+ const { log, audits } = report;
10
+ if (log !== null) {
11
+ const months = log.months.map((month) => `${month.path} (${month.entries})`).join(', ');
12
+ io.out(`- Журнал wiki/log.md: ${formatChars(log.chars)} знаков при пороге ${formatChars(log.limit)} — записей в архив: ${log.movedEntries} → ${months}; в wiki/log.md остаются последние ${log.keptEntries} (до ${formatChars(log.keep)} знаков).`);
13
+ }
14
+ if (audits.moved.length > 0)
15
+ io.out(`- Закрытые отчёты проверок: ${audits.moved.length} → ${AUDITS_ARCHIVE_DIR}/.`);
16
+ for (const section of report.sections) {
17
+ if (section.status === 'already') {
18
+ io.out(`- Раздел «${section.heading}» уже в архиве.`);
19
+ continue;
20
+ }
21
+ io.out(`- Раздел плана «${section.heading}»: ${formatChars(section.chars)} знаков → ${report.planArchive}; в плане остаются заголовок и строка со ссылкой.`);
22
+ for (const nested of section.nested)
23
+ io.out(` - внутри «${nested.heading}»: ${formatChars(nested.chars)} знаков.`);
24
+ for (const warning of section.warnings)
25
+ io.out(` - Проверьте: ${warning}`);
26
+ }
27
+ if (report.logNote !== null)
28
+ io.out(`- ${report.logNote}`);
29
+ for (const digest of report.digests)
30
+ io.out(`- Отпечаток ${digest.plan}: ${digest.before.slice(0, DIGEST_SHOWN)}… → ${digest.after.slice(0, DIGEST_SHOWN)}…; оба записаны в архиве плана.`);
31
+ if (report.relinked.length > 0)
32
+ io.out(`- Адреса ссылок поправлены в файлах: ${report.relinked.length}.`);
33
+ for (const item of audits.kept)
34
+ io.out(`- Остаётся ${item.path}: ${item.reason}`);
35
+ }
36
+ /**
37
+ * Без `--apply` команда только показывает, что перенесёт: ни байта не пишет.
38
+ * Перенос — внутри проекта, ничего не удаляется.
39
+ */
40
+ export async function executeArchiveCommand(options, io) {
41
+ const report = await archiveProject(options.path, {
42
+ apply: options.apply === true,
43
+ ...(options.sections === undefined ? {} : { sections: options.sections }),
44
+ ...(options.hooks === undefined ? {} : { hooks: options.hooks }),
45
+ });
46
+ if (options.json) {
47
+ io.out(JSON.stringify(report, null, 2));
48
+ return report.ok ? EXIT_OK : EXIT_FAILED;
49
+ }
50
+ if (!report.ok) {
51
+ io.err(report.partial ? 'Vibe Coding Maestro archive: перенос прерван, и откатить удалось не всё: проект изменён частично.' : 'Vibe Coding Maestro archive: перенос не выполнен (изменений на диске нет).');
52
+ if (report.error !== undefined)
53
+ io.err(`- ${report.error}`);
54
+ for (const item of report.blockers)
55
+ io.err(`- ${item.code}${item.path ? ` (${item.path})` : ''}: ${item.message}`);
56
+ return EXIT_FAILED;
57
+ }
58
+ if (report.writes.length === 0) {
59
+ const reasons = [report.logNote === null ? 'журнал не больше порога' : null, report.audits.kept.length === 0 ? 'закрытых отчётов нет' : null].filter((reason) => reason !== null);
60
+ io.out(`Переносить в архив нечего${reasons.length > 0 ? `: ${reasons.join(', ')}` : ''}.`);
61
+ describe(report, io);
62
+ return EXIT_OK;
63
+ }
64
+ if (report.applied) {
65
+ io.out('Vibe Coding Maestro archive: перенесено в архив.');
66
+ describe(report, io);
67
+ io.out('Ничего не удалено: перенесённый текст — в файлах архива. Проект в git — закоммитьте изменения.');
68
+ return EXIT_OK;
69
+ }
70
+ io.out('Vibe Coding Maestro archive: будет перенесено в архив (пробный запуск, ни байта не записано).');
71
+ describe(report, io);
72
+ const named = (options.sections ?? []).map((section) => ` --section "${plainTitle(section)}"`).join('');
73
+ io.out(`Перенести: ${serviceInvocation(VERSION)} archive --path ${quotePathArg(options.path)}${named} --apply`);
74
+ return EXIT_OK;
75
+ }
@@ -15,6 +15,7 @@ const HELP = `${PRODUCT_NAME} — служебный CLI проекта.
15
15
  preflight механическая проверка права начинать код по активному плану
16
16
  pack архив тега сдачи для заказчика: без папок Maestro, с HANDOVER.md
17
17
  context размер текущей сессии Claude Code: пора ли в новую сессию
18
+ archive перенос старой памяти проекта в архив внутри проекта (ничего не удаляет)
18
19
 
19
20
  Общие опции команд:
20
21
  --path <путь> корень проверяемого проекта (по умолчанию текущая папка)
@@ -39,6 +40,10 @@ const HELP = `${PRODUCT_NAME} — служебный CLI проекта.
39
40
  --allow <путь> файл, который человек проверил: не секрет; флаг можно повторять
40
41
  --dry-run состав архива с подсветкой внутреннего; ничего не пишет
41
42
 
43
+ Опции archive:
44
+ --apply перенести; без флага только показывает, что перенесёт
45
+ --section <начало> закрытая правка активного плана по началу заголовка; флаг можно повторять
46
+
42
47
  Опции context:
43
48
  --window <токены> окно модели в токенах (по умолчанию — по модели из журнала сессии)
44
49
 
@@ -49,7 +54,7 @@ const HELP = `${PRODUCT_NAME} — служебный CLI проекта.
49
54
  Общие опции:
50
55
  --help, -h эта справка
51
56
  --version, -v версия`;
52
- const COMMANDS = ['doctor', 'skills', 'sources', 'upgrade', 'preflight', 'pack', 'context'];
57
+ const COMMANDS = ['doctor', 'skills', 'sources', 'upgrade', 'preflight', 'pack', 'context', 'archive'];
53
58
  const isCommand = (value) => COMMANDS.includes(value);
54
59
  export function parseMaestroArgs(argv) {
55
60
  if (argv.length === 0)
@@ -83,10 +88,20 @@ export function parseMaestroArgs(argv) {
83
88
  break;
84
89
  }
85
90
  case '--apply': {
86
- const message = only(arg, 'upgrade');
91
+ if (first !== 'upgrade' && first !== 'archive')
92
+ return { kind: 'error', message: `Флаг ${arg} доступен только для upgrade и archive.` };
93
+ options.apply = true;
94
+ break;
95
+ }
96
+ case '--section': {
97
+ const message = only(arg, 'archive');
87
98
  if (message !== null)
88
99
  return { kind: 'error', message };
89
- options.apply = true;
100
+ const section = value();
101
+ if (section === undefined || section.trim() === '')
102
+ return { kind: 'error', message: `Флаг ${arg} требует значение: начало заголовка раздела.` };
103
+ options.sections = [...(options.sections ?? []), section];
104
+ i += 1;
90
105
  break;
91
106
  }
92
107
  case '--diff': {
@@ -278,6 +293,10 @@ export async function runMaestroCli(argv, io = processIo) {
278
293
  const { executePackCommand } = await import('./pack-run.js');
279
294
  return executePackCommand({ ...parsed.options, tag: parsed.options.tag }, io);
280
295
  }
296
+ if (parsed.kind === 'archive') {
297
+ const { executeArchiveCommand } = await import('./archive-run.js');
298
+ return executeArchiveCommand(parsed.options, io);
299
+ }
281
300
  if (parsed.kind === 'context') {
282
301
  const { executeContextCommand } = await import('./context-run.js');
283
302
  return executeContextCommand(parsed.options, io);
@@ -0,0 +1,37 @@
1
+ import { parseAudit } from '../audits.js';
2
+ import { parseFlowList } from '../plan.js';
3
+ import { linkTargets } from './links.js';
4
+ import { withoutBom } from './markdown.js';
5
+ export const AUDITS_ARCHIVE_DIR = 'wiki/audits/archive';
6
+ export const AUDIT_FILE_RE = /^wiki\/audits\/([^/]+\.md)$/;
7
+ /**
8
+ * В архив уходят только закрытые отчёты. Открытые остаются: их видят `/status`,
9
+ * завершение и скрипты, и закрыть их можно позже.
10
+ */
11
+ export function selectAudits(files, plans, disk) {
12
+ const moved = new Map();
13
+ const kept = [];
14
+ const sources = new Set(plans.flatMap((plan) => parseFlowList(plan.meta?.sources ?? '[]') ?? []).map((source) => disk.locate('', source) ?? source));
15
+ const changed = plans.filter((plan) => plan.guarded && !plan.intact).map((plan) => ({ path: plan.path, links: linkTargets(plan.text, plan.path, disk.locate) }));
16
+ for (const [path, text] of [...files].sort(([left], [right]) => left.localeCompare(right))) {
17
+ const name = AUDIT_FILE_RE.exec(path)?.[1];
18
+ if (name === undefined)
19
+ continue;
20
+ const target = `${AUDITS_ARCHIVE_DIR}/${name}`;
21
+ const audit = parseAudit(withoutBom(text));
22
+ const blockingPlan = changed.find((plan) => plan.links.has(path));
23
+ if (audit.malformed)
24
+ kept.push({ path, code: 'audit-malformed', reason: 'doctor не разобрал отчёт (audit-malformed): сначала поправьте его.' });
25
+ else if (!audit.closed)
26
+ kept.push({ path, code: 'audit-open', reason: 'отчёт открыт: в архив уходят только status: resolved.' });
27
+ else if (sources.has(path))
28
+ kept.push({ path, code: 'audit-plan-source', reason: 'отчёт назван в sources плана.' });
29
+ else if (disk.exists(target))
30
+ kept.push({ path, code: 'audit-archive-exists', reason: `в архиве уже есть ${target}: перезаписывать нельзя.` });
31
+ else if (blockingPlan !== undefined)
32
+ kept.push({ path, code: 'audit-plan-changed', reason: `на него ссылается ${blockingPlan.path}, а текст этого плана изменился после утверждения: ссылку править нельзя.` });
33
+ else
34
+ moved.set(path, target);
35
+ }
36
+ return { moved, kept };
37
+ }
@@ -0,0 +1,38 @@
1
+ import { existsSync, statSync } from 'node:fs';
2
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
3
+ function identity(absolute) {
4
+ try {
5
+ const stats = statSync(absolute, { bigint: true });
6
+ return `${stats.dev}:${stats.ino}`;
7
+ }
8
+ catch {
9
+ return null;
10
+ }
11
+ }
12
+ /** Номер файла верен не на любом диске, поэтому тот же файл — это ещё и то же имя с точностью до регистра и формы букв. */
13
+ const sameName = (left, right) => basename(left).normalize('NFC').toLowerCase() === basename(right).normalize('NFC').toLowerCase();
14
+ /** `tracked` — файлы, которые адрес должен находить под их настоящим именем, как бы он ни был записан. */
15
+ export function projectDisk(root, tracked) {
16
+ const known = new Map();
17
+ for (const path of tracked) {
18
+ const id = identity(join(root, path));
19
+ if (id !== null)
20
+ known.set(id, path);
21
+ }
22
+ const located = new Map();
23
+ return {
24
+ exists: (path) => existsSync(join(root, path)),
25
+ locate: (from, decoded) => {
26
+ const absolute = resolve(root, dirname(from), decoded);
27
+ if (located.has(absolute))
28
+ return located.get(absolute);
29
+ const id = identity(absolute);
30
+ const inside = relative(root, absolute);
31
+ const outside = inside === '' || inside === '..' || inside.startsWith(`..${sep}`) || isAbsolute(inside);
32
+ const same = id === null ? undefined : known.get(id);
33
+ const path = (same !== undefined && sameName(same, absolute) ? same : undefined) ?? (outside ? undefined : inside.split(sep).join('/'));
34
+ located.set(absolute, path);
35
+ return path;
36
+ },
37
+ };
38
+ }
@@ -0,0 +1,286 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { existsSync, statSync } from 'node:fs';
3
+ import { readFile } from 'node:fs/promises';
4
+ import { join, relative, resolve, sep } from 'node:path';
5
+ import { promisify } from 'node:util';
6
+ import { absolutePathHasSymlink, markdownFiles, pathHasSymlink } from '../doctor/fs-utils.js';
7
+ import { loadManifest, MANIFEST_PATH } from '../manifest.js';
8
+ import { CREATE_COMMAND, quotePathArg, serviceInvocation, VERSION } from '../meta.js';
9
+ import { readPackageJson } from '../paths.js';
10
+ import { planBodyDigest } from '../plan.js';
11
+ import { canonicalizeSystemTempPrefix } from '../platform-paths.js';
12
+ import { applyTransaction, ARCHIVE_STAGING_DIR, STAGING_DIRS } from '../transaction.js';
13
+ import { compareVersions } from '../version.js';
14
+ import { HOT_PATH } from '../doctor/plans.js';
15
+ import { ACTIVE_PLAN_NONE, isWikiRelativePlanRef } from '../plan.js';
16
+ import { AUDIT_FILE_RE, AUDITS_ARCHIVE_DIR, selectAudits } from './audits.js';
17
+ import { projectDisk } from './disk.js';
18
+ import { countChars, formatChars, LOG_KEEP, LOG_LIMIT } from './limits.js';
19
+ import { rebaseLinks } from './links.js';
20
+ import { appendToMonth, LOG_DIR, LOG_PATH, parseLog, rotateLog } from './log.js';
21
+ import { eolOf, withoutBom } from './markdown.js';
22
+ import { appendToPlanArchive, cutSections, declaredPlan, digestLine, planArchivePath, planFiles, PLANS_ARCHIVE_DIR, resolveSections, sectionChars, writeDigest } from './plan.js';
23
+ import { blocker } from './types.js';
24
+ /**
25
+ * Перенос старой памяти проекта в архив внутри проекта: ничего не удаляется,
26
+ * текст переносится байт в байт, меняются только адреса ссылок.
27
+ *
28
+ * Без `apply` не записывается ни один байт; любое сомнение — отказ целиком.
29
+ */
30
+ const execFileAsync = promisify(execFile);
31
+ /** Строгий UTF-8 с сохранением BOM: перенос — байт в байт. */
32
+ function decodeExact(buffer) {
33
+ try {
34
+ return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(buffer);
35
+ }
36
+ catch {
37
+ return null;
38
+ }
39
+ }
40
+ /** Все документы wiki как на диске; папку-ссылку и файл-ссылку обходит, как doctor. */
41
+ async function readWiki(root, blockers) {
42
+ const files = new Map();
43
+ for (const absolute of await markdownFiles(join(root, 'wiki'))) {
44
+ const path = relative(root, absolute).split(sep).join('/');
45
+ try {
46
+ const text = decodeExact(await readFile(absolute));
47
+ if (text === null)
48
+ blockers.push(blocker('archive-invalid-utf8', 'Файл должен быть корректным UTF-8: archive переносит текст байт в байт и правит адреса ссылок.', path));
49
+ else
50
+ files.set(path, text);
51
+ }
52
+ catch (cause) {
53
+ blockers.push(blocker('archive-unreadable', `Файл не прочитать: ${cause instanceof Error ? cause.message : String(cause)}`, path));
54
+ }
55
+ }
56
+ return files;
57
+ }
58
+ /** Путь игнорируется git. Вне репозитория проверки нет; репозиторий может быть и выше проекта. */
59
+ async function ignoredByGit(root, path) {
60
+ try {
61
+ await execFileAsync('git', ['check-ignore', '-q', '--', path], { cwd: root });
62
+ return true;
63
+ }
64
+ catch {
65
+ // Код 1 — не игнорируется; 128 и прочее — не репозиторий или git недоступен: не мешаем переносу.
66
+ return false;
67
+ }
68
+ }
69
+ function report(root, patch) {
70
+ const blockers = patch.blockers ?? [];
71
+ return {
72
+ reportVersion: 1, ok: blockers.length === 0, applied: false, rolledBack: false, partial: false, root, blockers,
73
+ log: null, logNote: null, audits: { moved: [], kept: [] }, plan: null, planArchive: null, sections: [], digests: [], relinked: [], writes: [], ...patch,
74
+ };
75
+ }
76
+ const ARCHIVE_DIRS = [LOG_DIR, AUDITS_ARCHIVE_DIR, PLANS_ARCHIVE_DIR];
77
+ /** Пути, с которыми работает archive: если один из них symbolic link, запись или чтение ушли бы не туда. */
78
+ const MEMORY_PATHS = [HOT_PATH, LOG_PATH, 'wiki/audits', 'wiki/plans', ...ARCHIVE_DIRS, ARCHIVE_STAGING_DIR];
79
+ async function preconditions(root, rootInput) {
80
+ if (!existsSync(root))
81
+ return [blocker('archive-path-missing', `Папка не найдена: ${root}. Проверьте путь; путь с пробелами возьмите в кавычки.`)];
82
+ if (!statSync(root).isDirectory())
83
+ return [blocker('archive-path-not-directory', `Это файл, а не папка проекта: ${root}.`)];
84
+ if (await absolutePathHasSymlink(root))
85
+ return [blocker('archive-symlink', 'Путь к корню проекта не должен содержать symbolic link.', root)];
86
+ if (!existsSync(join(root, MANIFEST_PATH)))
87
+ return [blocker('archive-not-project', `В папке нет ${MANIFEST_PATH}: это не проект Vibe Coding Maestro или указана не та папка.`, MANIFEST_PATH)];
88
+ let manifest;
89
+ try {
90
+ manifest = await loadManifest(root);
91
+ }
92
+ catch (cause) {
93
+ return [blocker('archive-manifest-invalid', `Манифест повреждён: ${cause instanceof Error ? cause.message : String(cause)}`, MANIFEST_PATH)];
94
+ }
95
+ if (manifest.product.name !== readPackageJson().name || manifest.product.createdBy !== CREATE_COMMAND) {
96
+ return [blocker('archive-not-project', 'Манифест создан не Vibe Coding Maestro: archive переносит только память проекта Maestro.', MANIFEST_PATH)];
97
+ }
98
+ const projectVersion = manifest.product.version;
99
+ if (projectVersion !== VERSION) {
100
+ const path = quotePathArg(rootInput);
101
+ const older = (compareVersions(projectVersion, VERSION) ?? -1) < 0;
102
+ return [blocker('archive-version-mismatch', older
103
+ ? `Проект на версии ${projectVersion}, а archive — ${VERSION}: правила памяти у версий разные. Сначала обновите проект: \`${serviceInvocation(VERSION)} upgrade --path ${path}\` (без --apply только показывает изменения).`
104
+ : `Проект на версии ${projectVersion}, а archive — ${VERSION}. Запустите archive версии проекта: \`${serviceInvocation(projectVersion)} archive --path ${path}\`.`, MANIFEST_PATH)];
105
+ }
106
+ const found = [];
107
+ for (const staging of STAGING_DIRS) {
108
+ if (existsSync(join(root, staging))) {
109
+ found.push(blocker('archive-staging-present', 'Каталог транзакции уже существует: прошлый запуск upgrade или archive был прерван. В его подпапке backup/ лежат прежние версии файлов. Сверьте проект (git status, git diff), верните нужное из backup/ и только потом удалите каталог.', staging));
110
+ }
111
+ }
112
+ if (await pathHasSymlink(root, 'wiki')) {
113
+ found.push(blocker('archive-symlink', 'Путь wiki не должен содержать symbolic link.', 'wiki'));
114
+ return found;
115
+ }
116
+ for (const path of MEMORY_PATHS) {
117
+ if (await pathHasSymlink(root, path))
118
+ found.push(blocker('archive-symlink', 'Путь памяти проекта содержит symbolic link: archive с такими путями не работает.', path));
119
+ }
120
+ for (const path of ARCHIVE_DIRS) {
121
+ if (existsSync(join(root, path)) && !statSync(join(root, path)).isDirectory())
122
+ found.push(blocker('archive-not-directory', 'На этом месте должна быть папка архива, а лежит файл: переименуйте файл и запустите снова.', path));
123
+ }
124
+ return found;
125
+ }
126
+ /**
127
+ * Предложение переноса и, по `apply`, сам перенос одной транзакцией.
128
+ *
129
+ * Гарантии:
130
+ * - без `apply` не записывается ни один байт;
131
+ * - перенесённый текст — байт в байт, кроме адресов относительных ссылок;
132
+ * - ничего не удаляется из проекта: старое переезжает в архивные файлы;
133
+ * - сбой посреди записи откатывает всё уже записанное.
134
+ */
135
+ export async function archiveProject(rootInput, options = {}) {
136
+ const root = await canonicalizeSystemTempPrefix(resolve(rootInput));
137
+ try {
138
+ return await archiveMemory(root, rootInput, options);
139
+ }
140
+ catch (cause) {
141
+ // Транзакция свои сбои возвращает сама: здесь — только чтение, до первой записи.
142
+ return report(root, { blockers: [blocker('archive-unreadable', `Папку или файл проекта не прочитать, ничего не записано: ${cause instanceof Error ? cause.message : String(cause)}`)] });
143
+ }
144
+ }
145
+ async function archiveMemory(root, rootInput, options) {
146
+ const before = await preconditions(root, rootInput);
147
+ if (before.length > 0)
148
+ return report(root, { blockers: before });
149
+ const blockers = [];
150
+ const files = await readWiki(root, blockers);
151
+ if (blockers.length > 0)
152
+ return report(root, { blockers });
153
+ const wanted = options.sections ?? [];
154
+ const declared = declaredPlan(files);
155
+ if (wanted.length > 0 && declared !== ACTIVE_PLAN_NONE && isWikiRelativePlanRef(declared) && await pathHasSymlink(root, `wiki/${declared}`)) {
156
+ return report(root, { blockers: [blocker('archive-symlink', 'Активный план — symbolic link: archive с такими путями не работает.', `wiki/${declared}`)] });
157
+ }
158
+ const plans = planFiles(files);
159
+ // Отпечаток сверяется здесь один раз, до всех правок: после переноса сверять уже нечего.
160
+ const resolution = wanted.length > 0 ? resolveSections(files, plans, wanted) : { plan: null, chosen: [], blockers: [] };
161
+ blockers.push(...resolution.blockers);
162
+ const sectionPlan = resolution.plan;
163
+ const sections = sectionPlan === null ? [] : resolution.chosen.map((choice) => ({
164
+ heading: choice.heading.title,
165
+ status: choice.already ? 'already' : 'moved',
166
+ chars: sectionChars(sectionPlan.text, choice.heading),
167
+ nested: choice.nested.map((heading) => ({ heading: heading.title, chars: sectionChars(sectionPlan.text, heading) })),
168
+ warnings: choice.warnings,
169
+ }));
170
+ const disk = projectDisk(root, [...files.keys()].filter((path) => AUDIT_FILE_RE.test(path)));
171
+ const { moved, kept } = selectAudits(files, plans, disk);
172
+ const audits = { moved: [...moved].map(([from, to]) => ({ from, to })), kept };
173
+ // Адреса считаются от конечных мест всех файлов сразу: сначала все правят ссылки, потом переносы.
174
+ const next = new Map();
175
+ for (const [path, text] of files)
176
+ next.set(path, rebaseLinks(text, path, path, moved, disk.locate));
177
+ for (const [from, to] of moved) {
178
+ next.delete(from);
179
+ next.set(to, rebaseLinks(files.get(from), from, to, moved, disk.locate));
180
+ }
181
+ const touched = new Set();
182
+ /** Файлы, куда приходит перенесённый текст: они обязаны быть в git. */
183
+ const destinations = new Set(moved.values());
184
+ let log = null;
185
+ const logText = files.get(LOG_PATH);
186
+ const rotation = logText === undefined ? null : rotateLog(logText, moved, disk.locate);
187
+ if (rotation !== null) {
188
+ const eol = eolOf(logText);
189
+ next.set(LOG_PATH, rotation.log);
190
+ touched.add(LOG_PATH);
191
+ for (const month of rotation.months) {
192
+ next.set(month.path, appendToMonth(next.get(month.path) ?? null, month.path.slice(-10, -3), month.appended, eol));
193
+ touched.add(month.path);
194
+ destinations.add(month.path);
195
+ }
196
+ log = {
197
+ chars: rotation.chars,
198
+ limit: LOG_LIMIT,
199
+ keep: LOG_KEEP,
200
+ movedEntries: rotation.months.reduce((sum, month) => sum + month.entries, 0),
201
+ keptEntries: rotation.keptEntries,
202
+ months: rotation.months.map(({ path, entries }) => ({ path, entries })),
203
+ };
204
+ }
205
+ let logNote = null;
206
+ if (logText !== undefined && rotation === null && countChars(logText) > LOG_LIMIT) {
207
+ const size = `${formatChars(countChars(logText))} знаков при пороге ${formatChars(LOG_LIMIT)}`;
208
+ logNote = parseLog(logText).entries.length === 0
209
+ ? `Журнал wiki/log.md: ${size}, но нет записей с датой в начале заголовка («## ГГГГ-ММ-ДД — …»): переносить нечего.`
210
+ : `Журнал wiki/log.md: ${size}, но все записи с датой входят в последние ${formatChars(LOG_KEEP)} знаков или запись одна: переносить нечего, сократите шапку или длинную запись.`;
211
+ }
212
+ const date = (options.now ?? new Date()).toISOString().slice(0, 10);
213
+ const digests = [];
214
+ for (const plan of plans) {
215
+ const eol = eolOf(plan.text);
216
+ const archivePath = planArchivePath(plan.path);
217
+ const cut = plan === sectionPlan ? cutSections(plan.text, resolution.chosen, archivePath, eol) : null;
218
+ let text = rebaseLinks(cut?.remaining ?? plan.text, plan.path, plan.path, moved, disk.locate);
219
+ if (text === plan.text)
220
+ continue;
221
+ const blocks = (cut?.sections ?? []).map((section) => rebaseLinks(section, plan.path, archivePath, moved, disk.locate));
222
+ if (plan.digest !== null && (plan.guarded || cut !== null)) {
223
+ const after = planBodyDigest(withoutBom(text));
224
+ if (after !== plan.digest) {
225
+ text = writeDigest(text, after);
226
+ digests.push({ plan: plan.path, before: plan.digest, after });
227
+ blocks.push(digestLine(date, plan.digest, after, eol));
228
+ }
229
+ }
230
+ next.set(plan.path, text);
231
+ if (cut !== null)
232
+ touched.add(plan.path);
233
+ if (blocks.length > 0) {
234
+ next.set(archivePath, appendToPlanArchive(next.get(archivePath) ?? null, plan, blocks, eol));
235
+ touched.add(archivePath);
236
+ destinations.add(archivePath);
237
+ }
238
+ }
239
+ const contents = new Map();
240
+ for (const [path, text] of next) {
241
+ const before = files.get(path);
242
+ if (before === undefined)
243
+ contents.set(path, { action: 'create', text });
244
+ else if (before !== text)
245
+ contents.set(path, { action: 'update', text });
246
+ }
247
+ for (const from of moved.keys())
248
+ contents.set(from, { action: 'remove', text: '' });
249
+ const writes = [...contents.entries()].map(([path, value]) => ({ path, action: value.action })).sort((a, b) => a.path.localeCompare(b.path));
250
+ // Вся память вне git (папка проекта игнорируется целиком) — это выбор проекта, а не потеря при переносе.
251
+ const memoryInGit = destinations.size > 0 && !await ignoredByGit(root, HOT_PATH);
252
+ for (const write of writes) {
253
+ if (await pathHasSymlink(root, write.path))
254
+ blockers.push(blocker('archive-symlink', 'Путь переноса содержит symbolic link: запись ушла бы за пределы проекта.', write.path));
255
+ else if (write.action === 'create' && disk.exists(write.path)) {
256
+ blockers.push(blocker('archive-destination-exists', 'На этом месте уже есть файл: его имя отличается только регистром или формой букв. archive его не перезаписывает: приведите имена к одному виду и запустите снова.', write.path));
257
+ }
258
+ else if (memoryInGit && destinations.has(write.path) && await ignoredByGit(root, write.path)) {
259
+ blockers.push(blocker('archive-destination-ignored', 'Git игнорирует этот путь (.gitignore): перенесённое не попадёт в копию в облаке, а ссылки на свежем клоне станут битыми. Уберите правило из .gitignore и запустите снова.', write.path));
260
+ }
261
+ }
262
+ const relinked = writes.filter((write) => write.action === 'update' && !touched.has(write.path)).map((write) => write.path);
263
+ const details = { log, logNote, audits, plan: sectionPlan?.path ?? null, planArchive: sectionPlan === null ? null : planArchivePath(sectionPlan.path), sections, digests, relinked };
264
+ if (blockers.length > 0)
265
+ return report(root, { blockers, ...details });
266
+ if (options.apply !== true || writes.length === 0)
267
+ return report(root, { ...details, writes });
268
+ const operations = writes.map((write) => (write.action === 'remove'
269
+ ? { path: write.path, action: write.action }
270
+ : { path: write.path, action: write.action, bytes: Buffer.from(contents.get(write.path).text, 'utf8') }));
271
+ const outcome = await applyTransaction(root, ARCHIVE_STAGING_DIR, operations, options.hooks);
272
+ if (outcome.ok)
273
+ return report(root, { applied: true, ...details, writes });
274
+ if (outcome.stage === 'prepare')
275
+ return report(root, { ok: false, ...details, writes, error: `Подготовка переноса не удалась, проект не изменён: ${outcome.reason}` });
276
+ if (!outcome.rolledBack) {
277
+ return report(root, {
278
+ ok: false,
279
+ partial: true,
280
+ ...details,
281
+ writes,
282
+ error: `Перенос прерван (${outcome.reason}), и откатить удалось не всё: ${outcome.unrestored.join(', ')}. Прежние версии файлов оставлены в ${ARCHIVE_STAGING_DIR}/backup/ — верните их вручную, затем удалите ${ARCHIVE_STAGING_DIR}.`,
283
+ });
284
+ }
285
+ return report(root, { ok: false, rolledBack: true, ...details, writes, error: `Перенос прерван и откачен: ${outcome.reason}` });
286
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Ориентиры длины памяти проекта: одно место для doctor и archive.
3
+ *
4
+ * HYPOTHESIS 0.4.4: числа подобраны по трём живым проектам, а не по замеру
5
+ * токенов, поэтому doctor о них только сообщает (`info`) и ничего не блокирует.
6
+ */
7
+ /** `wiki/hot.md` — около экрана, примерно 60 строк. */
8
+ export const HOT_LIMIT = 6_000;
9
+ /** Активный план: основа плана и текущая правка. */
10
+ export const PLAN_LIMIT = 60_000;
11
+ /** `wiki/log.md`: больше — старые записи переносит archive. */
12
+ export const LOG_LIMIT = 20_000;
13
+ /** Сколько знаков последних записей остаётся в `wiki/log.md` после переноса. */
14
+ export const LOG_KEEP = 10_000;
15
+ /** Передача, с которой начнёт следующая сессия. */
16
+ export const HANDOFF_LIMIT = 6_000;
17
+ /**
18
+ * Знаки — кодовые точки Unicode после замены CRLF на LF: так счёт одинаков
19
+ * на любой ОС и не зависит от того, как записан перенос строки.
20
+ */
21
+ export function countChars(text) {
22
+ return Array.from(text.replace(/\r\n/g, '\n')).length;
23
+ }
24
+ /** Тысячи через пробел, без зависимости от локали машины. */
25
+ export function formatChars(value) {
26
+ return String(Math.round(value)).replace(/\B(?=(\d{3})+(?!\d))/g, ' ');
27
+ }