create-vibe-maestro 0.4.2 → 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 (94) hide show
  1. package/CHANGELOG.md +92 -0
  2. package/README.md +11 -11
  3. package/dist/cli/archive-run.js +75 -0
  4. package/dist/cli/context-run.js +10 -0
  5. package/dist/cli/maestro.js +46 -4
  6. package/dist/cli/pack-run.js +42 -3
  7. package/dist/cli/upgrade-run.js +44 -5
  8. package/dist/core/archive/audits.js +37 -0
  9. package/dist/core/archive/disk.js +38 -0
  10. package/dist/core/archive/index.js +286 -0
  11. package/dist/core/archive/limits.js +27 -0
  12. package/dist/core/archive/links.js +65 -0
  13. package/dist/core/archive/log.js +83 -0
  14. package/dist/core/archive/markdown.js +28 -0
  15. package/dist/core/archive/plan.js +183 -0
  16. package/dist/core/archive/types.js +1 -0
  17. package/dist/core/audits.js +37 -0
  18. package/dist/core/context.js +47 -2
  19. package/dist/core/doctor/fs-utils.js +3 -2
  20. package/dist/core/doctor/index.js +5 -2
  21. package/dist/core/doctor/memory.js +52 -0
  22. package/dist/core/doctor/plans.js +4 -4
  23. package/dist/core/doctor/wiki.js +9 -33
  24. package/dist/core/gitignore.js +3 -1
  25. package/dist/core/inventory.js +2 -10
  26. package/dist/core/pack.js +130 -12
  27. package/dist/core/plan.js +43 -2
  28. package/dist/core/preflight.js +6 -5
  29. package/dist/core/template.js +2 -1
  30. package/dist/core/text-diff.js +108 -0
  31. package/dist/core/transaction.js +132 -0
  32. package/dist/core/upgrade/analyze.js +82 -5
  33. package/dist/core/upgrade/baseline.js +12 -0
  34. package/dist/core/upgrade/index.js +31 -87
  35. package/dist/core/upgrade/releases.js +143 -2
  36. package/dist/core/wiki-links.js +27 -0
  37. package/docs/ROADMAP.md +8 -4
  38. package/docs/USER_GUIDE.md +117 -35
  39. package/package.json +1 -1
  40. package/registry/baseline/0.4.2/project/.claude/agents/code-reviewer.md +13 -0
  41. package/registry/baseline/0.4.2/project/.claude/rules/maestro.md +37 -0
  42. package/registry/baseline/0.4.2/project/maestro/runbooks/cowork-audit.md +11 -0
  43. package/registry/baseline/0.4.2/project/maestro/templates/handoff.md +25 -0
  44. package/registry/baseline/0.4.2/project/protocols/audit.md +5 -0
  45. package/registry/baseline/0.4.2/project/protocols/build.md +18 -0
  46. package/registry/baseline/0.4.2/project/protocols/completion.md +22 -0
  47. package/registry/baseline/0.4.2/project/protocols/handoff.md +15 -0
  48. package/registry/baseline/0.4.2/project/protocols/plan.md +149 -0
  49. package/registry/baseline/0.4.2/project/protocols/start.md +64 -0
  50. package/registry/baseline/0.4.2/project/protocols/wiki.md +9 -0
  51. package/registry/baseline/0.4.2/project/wiki/plans/README.md +131 -0
  52. package/registry/baseline/0.4.2/project/wiki/plans/TEMPLATE.md +75 -0
  53. package/registry/baseline/0.4.3/project/.claude/rules/maestro.md +40 -0
  54. package/registry/baseline/0.4.3/project/maestro/templates/handoff.md +29 -0
  55. package/registry/baseline/0.4.3/project/protocols/build.md +120 -0
  56. package/registry/baseline/0.4.3/project/protocols/completion.md +23 -0
  57. package/registry/baseline/0.4.3/project/protocols/handoff.md +17 -0
  58. package/registry/baseline/0.4.3/project/protocols/plan.md +159 -0
  59. package/registry/baseline/0.4.3/project/protocols/status.md +5 -0
  60. package/registry/baseline/0.4.3/project/protocols/wiki.md +17 -0
  61. package/registry/baseline/0.4.3/project/wiki/plans/README.md +135 -0
  62. package/registry/baseline/0.4.3/project/wiki/plans/TEMPLATE.md +83 -0
  63. package/registry/capabilities.v1.json +19 -19
  64. package/templates/project/.claude/agents/code-reviewer.md +18 -7
  65. package/templates/project/.claude/rules/maestro.md +7 -3
  66. package/templates/project/.claude/settings.json +1 -0
  67. package/templates/project/maestro/runbooks/cowork-audit.md +9 -2
  68. package/templates/project/maestro/templates/audit.md +31 -0
  69. package/templates/project/maestro/templates/handoff.md +6 -2
  70. package/templates/project/protocols/audit.md +70 -1
  71. package/templates/project/protocols/build.md +111 -9
  72. package/templates/project/protocols/completion.md +8 -7
  73. package/templates/project/protocols/handoff.md +7 -4
  74. package/templates/project/protocols/plan.md +34 -23
  75. package/templates/project/protocols/start.md +1 -1
  76. package/templates/project/protocols/status.md +1 -1
  77. package/templates/project/protocols/wiki.md +10 -2
  78. package/templates/project/wiki/icebox.md +12 -0
  79. package/templates/project/wiki/index.md +5 -0
  80. package/templates/project/wiki/log.md +1 -0
  81. package/templates/project/wiki/passport.md +1 -1
  82. package/templates/project/wiki/plans/0001-starter.md +15 -4
  83. package/templates/project/wiki/plans/README.md +27 -3
  84. package/templates/project/wiki/plans/TEMPLATE.md +23 -6
  85. /package/{templates → registry/baseline/0.4.2}/project/protocols/build/audit-phase.md +0 -0
  86. /package/{templates → registry/baseline/0.4.2}/project/protocols/build/audit-plan.md +0 -0
  87. /package/{templates → registry/baseline/0.4.2}/project/protocols/build/step-1-rules.md +0 -0
  88. /package/{templates → registry/baseline/0.4.2}/project/protocols/build/step-2-spec.md +0 -0
  89. /package/{templates → registry/baseline/0.4.2}/project/protocols/build/step-3-architecture.md +0 -0
  90. /package/{templates → registry/baseline/0.4.2}/project/protocols/build/step-5-feature-loop.md +0 -0
  91. /package/{templates → registry/baseline/0.4.2}/project/protocols/context-budget.md +0 -0
  92. /package/{templates → registry/baseline/0.4.2}/project/protocols/discovery.md +0 -0
  93. /package/{templates → registry/baseline/0.4.2}/project/protocols/lessons.md +0 -0
  94. /package/{templates → registry/baseline/0.4.2}/project/protocols/seams.md +0 -0
@@ -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
+ }
@@ -0,0 +1,65 @@
1
+ import { posix } from 'node:path';
2
+ import { isExternalLink, markdownLinks } from '../wiki-links.js';
3
+ /** Часть адреса: скобки ломают разбор ссылки, а `encodeURIComponent` их не кодирует. */
4
+ const percent = (char) => (char === '(' ? '%28' : char === ')' ? '%29' : encodeURIComponent(char));
5
+ const encodePart = (part) => encodeURIComponent(part).replace(/[()]/g, percent);
6
+ /** Имя файла в адресе, который пишет archive: кириллица как есть, то, что сломало бы ссылку, — кодами. */
7
+ export const linkName = (name) => name.replace(/[\s%()<>#]/g, percent);
8
+ /** Ссылки на файлы проекта: внешняя, ведущая наружу проекта или только якорь сюда не входят. */
9
+ function localLinks(text, from, locate) {
10
+ const fromDir = posix.dirname(from);
11
+ const links = [];
12
+ for (const link of markdownLinks(text)) {
13
+ const hashAt = link.destination.indexOf('#');
14
+ const rawPath = hashAt === -1 ? link.destination : link.destination.slice(0, hashAt);
15
+ const anchor = hashAt === -1 ? '' : link.destination.slice(hashAt);
16
+ const pathText = rawPath.trim();
17
+ if (pathText === '' || isExternalLink(pathText))
18
+ continue;
19
+ let decoded;
20
+ try {
21
+ decoded = decodeURIComponent(pathText);
22
+ }
23
+ catch {
24
+ continue;
25
+ }
26
+ const plain = posix.normalize(posix.join(fromDir, decoded)).replace(/\/$/, '');
27
+ const located = locate?.(from, decoded);
28
+ if (located === undefined && (pathText.startsWith('/') || plain === '..' || plain.startsWith('../')))
29
+ continue;
30
+ links.push({ link, pathText, anchor, target: located ?? plain, directory: decoded.endsWith('/') });
31
+ }
32
+ return links;
33
+ }
34
+ /** На какие файлы проекта ссылается текст файла `from`. */
35
+ export function linkTargets(text, from, locate) {
36
+ return new Set(localLinks(text, from, locate).map((link) => link.target));
37
+ }
38
+ /**
39
+ * Переносит адреса относительных ссылок: текст `from` переезжает в `to`, а файлы
40
+ * из `moved` (старый путь → новый, пути от корня проекта) — на новые места.
41
+ *
42
+ * Меняется только адрес ссылки, и только если он теперь должен быть другим;
43
+ * весь остальной текст — байт в байт. Якорь `#…` и вид записи (`<…>`, `%`-кодировка)
44
+ * сохраняются. Внешняя ссылка и ссылка наружу проекта не трогаются: их адрес от
45
+ * переноса не зависит. `locate` находит файл так же, как doctor; без него адрес
46
+ * понимается как строка.
47
+ */
48
+ export function rebaseLinks(text, from, to, moved = new Map(), locate) {
49
+ const toDir = posix.dirname(to);
50
+ const sameDir = posix.dirname(from) === toDir;
51
+ let out = '';
52
+ let cursor = 0;
53
+ for (const { link, pathText, anchor, target, directory } of localLinks(text, from, locate)) {
54
+ const finalTarget = moved.get(target) ?? target;
55
+ if (sameDir && finalTarget === target)
56
+ continue;
57
+ let relative = posix.relative(toDir, finalTarget) || '.';
58
+ if (directory)
59
+ relative += '/';
60
+ const written = pathText.includes('%') ? relative.split('/').map((part) => (part === '..' || part === '.' ? part : encodePart(part))).join('/') : relative;
61
+ out += text.slice(cursor, link.start) + written + anchor;
62
+ cursor = link.start + link.destination.length;
63
+ }
64
+ return out + text.slice(cursor);
65
+ }
@@ -0,0 +1,83 @@
1
+ import { rebaseLinks } from './links.js';
2
+ import { countChars, LOG_KEEP, LOG_LIMIT } from './limits.js';
3
+ import { eolOf, markdownLines } from './markdown.js';
4
+ export const LOG_PATH = 'wiki/log.md';
5
+ export const LOG_DIR = 'wiki/log';
6
+ /** Строка в шапке `wiki/log.md`: добавляется при первом переносе, повтор узнаётся по тексту. */
7
+ export const LOG_POINTER = 'Старые записи — по месяцам в [log/](log/).';
8
+ const HEADING_RE = /^##[ \t]/;
9
+ /** Дата — в начале заголовка, можно в квадратных скобках: `## 2026-10-12 — …`, `## [2026-10-19] build | …`. */
10
+ const DATED_RE = /^##[ \t]+\[?(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])(?!\d)/;
11
+ /**
12
+ * Записи журнала — блоки от `## ` до следующего `## ` вне блоков кода. Блок без даты
13
+ * едет с предыдущей записью, а до первой датированной записи всё — шапка.
14
+ */
15
+ export function parseLog(text) {
16
+ const starts = [];
17
+ for (const { line, offset, code } of markdownLines(text)) {
18
+ if (code || !HEADING_RE.test(line))
19
+ continue;
20
+ const date = DATED_RE.exec(line);
21
+ if (date !== null)
22
+ starts.push({ offset, month: `${date[1]}-${date[2]}` });
23
+ }
24
+ if (starts.length === 0)
25
+ return { preamble: text, entries: [] };
26
+ return {
27
+ preamble: text.slice(0, starts[0].offset),
28
+ entries: starts.map((start, index) => ({ month: start.month, text: text.slice(start.offset, starts[index + 1]?.offset ?? text.length) })),
29
+ };
30
+ }
31
+ /** Шапка нового файла месяца. */
32
+ export function monthHeader(month, eol) {
33
+ return `# Журнал: ${month}${eol}${eol}Записи, перенесённые из [log.md](../log.md) командой \`vibe-maestro archive\`: текст прежний, поправлены только адреса ссылок. Новые записи пишутся в \`wiki/log.md\`.${eol}${eol}`;
34
+ }
35
+ /**
36
+ * Перенос по порогу: `wiki/log.md` больше `LOG_LIMIT` знаков — в нём остаются
37
+ * последние записи на `LOG_KEEP` знаков (минимум одна), старые уходят в файлы
38
+ * месяцев. Нечего переносить — `null`.
39
+ */
40
+ export function rotateLog(text, moved = new Map(), locate) {
41
+ const chars = countChars(text);
42
+ if (chars <= LOG_LIMIT)
43
+ return null;
44
+ const { preamble, entries } = parseLog(text);
45
+ let kept = 0;
46
+ let keptChars = 0;
47
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
48
+ const size = countChars(entries[index].text);
49
+ if (kept > 0 && keptChars + size > LOG_KEEP)
50
+ break;
51
+ kept += 1;
52
+ keptChars += size;
53
+ }
54
+ const leaving = entries.slice(0, entries.length - kept);
55
+ if (leaving.length === 0)
56
+ return null;
57
+ const eol = eolOf(text);
58
+ const months = new Map();
59
+ for (const entry of leaving) {
60
+ const path = `${LOG_DIR}/${entry.month}.md`;
61
+ const current = months.get(path) ?? { entries: 0, appended: '' };
62
+ current.entries += 1;
63
+ current.appended += rebaseLinks(entry.text, LOG_PATH, path, moved, locate);
64
+ months.set(path, current);
65
+ }
66
+ const start = rebaseLinks(preamble, LOG_PATH, LOG_PATH, moved, locate);
67
+ const head = start.includes(LOG_POINTER)
68
+ ? start
69
+ : `${start.replace(/(?:\r?\n)+$/, '')}${start.trim() === '' ? '' : `${eol}${eol}`}${LOG_POINTER}${eol}${eol}`;
70
+ const rest = entries.slice(entries.length - kept).map((entry) => rebaseLinks(entry.text, LOG_PATH, LOG_PATH, moved, locate)).join('');
71
+ return {
72
+ chars,
73
+ keptEntries: kept,
74
+ log: head + rest,
75
+ months: [...months.entries()].map(([path, value]) => ({ path, ...value })),
76
+ };
77
+ }
78
+ /** Текст файла месяца после дописывания: новый — с шапкой, прежний — с переводом строки перед дописанным. */
79
+ export function appendToMonth(existing, month, appended, eol) {
80
+ if (existing === null)
81
+ return monthHeader(month, eol) + appended;
82
+ return existing === '' || existing.endsWith('\n') ? existing + appended : existing + eol + appended;
83
+ }
@@ -0,0 +1,28 @@
1
+ const FENCE_RE = /^ {0,3}(`{3,}|~{3,})(.*)$/;
2
+ /** Строки с пометкой блоков кода: закрывает блок то же ограждение, не короче открывшего. */
3
+ export function markdownLines(text) {
4
+ const lines = [];
5
+ let open = null;
6
+ let offset = 0;
7
+ for (const line of text.split(/(?<=\n)/)) {
8
+ const fence = FENCE_RE.exec(line.replace(/\r?\n$/, ''));
9
+ const marker = fence?.[1] ?? '';
10
+ const rest = fence?.[2] ?? '';
11
+ if (open === null) {
12
+ const opens = fence !== null && !(marker.startsWith('`') && rest.includes('`'));
13
+ if (opens)
14
+ open = marker;
15
+ lines.push({ line, offset, code: opens });
16
+ }
17
+ else {
18
+ if (fence !== null && marker[0] === open[0] && marker.length >= open.length && rest.trim() === '')
19
+ open = null;
20
+ lines.push({ line, offset, code: true });
21
+ }
22
+ offset += line.length;
23
+ }
24
+ return lines;
25
+ }
26
+ export const eolOf = (text) => (text.includes('\r\n') ? '\r\n' : '\n');
27
+ /** Разборы (frontmatter, отпечаток) работают с текстом без BOM, как его читает doctor; записывается текст с BOM. */
28
+ export const withoutBom = (text) => text.replace(/^\uFEFF/, '');