create-vibe-maestro 0.3.1 → 0.4.1

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 (36) hide show
  1. package/CHANGELOG.md +36 -2
  2. package/README.md +8 -6
  3. package/dist/cli/context-run.js +38 -0
  4. package/dist/cli/maestro.js +67 -1
  5. package/dist/cli/pack-run.js +44 -0
  6. package/dist/cli/upgrade-run.js +1 -1
  7. package/dist/core/context.js +169 -0
  8. package/dist/core/gitignore.js +11 -0
  9. package/dist/core/inventory.js +2 -0
  10. package/dist/core/pack.js +379 -0
  11. package/dist/core/upgrade/analyze.js +15 -1
  12. package/dist/core/upgrade/index.js +11 -5
  13. package/dist/core/upgrade/releases.js +66 -9
  14. package/dist/core/zip.js +133 -0
  15. package/docs/ROADMAP.md +74 -12
  16. package/docs/USER_GUIDE.md +89 -9
  17. package/package.json +1 -1
  18. package/registry/baseline/0.3.1/project/.claude/agents/code-reviewer.md +12 -0
  19. package/registry/baseline/0.3.1/project/.claude/agents/explorer.md +14 -0
  20. package/registry/baseline/0.3.1/project/.claude/rules/maestro.md +25 -0
  21. package/registry/baseline/0.3.1/project/protocols/build.md +17 -0
  22. package/registry/baseline/0.3.1/project/protocols/handoff.md +13 -0
  23. package/registry/baseline/0.4.0/project/.claude/rules/maestro.md +35 -0
  24. package/registry/baseline/0.4.0/project/protocols/completion.md +22 -0
  25. package/registry/baseline/0.4.0/project/protocols/handoff.md +15 -0
  26. package/registry/capabilities.v1.json +12 -0
  27. package/templates/project/.claude/agents/code-reviewer.md +1 -0
  28. package/templates/project/.claude/agents/explorer.md +1 -1
  29. package/templates/project/.claude/rules/maestro.md +11 -1
  30. package/templates/project/.claude/settings.json +0 -2
  31. package/templates/project/protocols/build.md +2 -1
  32. package/templates/project/protocols/completion.md +22 -0
  33. package/templates/project/protocols/handoff.md +2 -0
  34. package/templates/project/wiki/index.md +1 -0
  35. package/templates/project/wiki/passport.md +44 -0
  36. package/dist/core/upgrade/instance.js +0 -82
@@ -0,0 +1,379 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { existsSync } from 'node:fs';
4
+ import { mkdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
5
+ import { dirname, join, posix, resolve } from 'node:path';
6
+ import { promisify } from 'node:util';
7
+ import { MANIFEST_PATH } from './manifest.js';
8
+ import { buildZip, ZipTooLargeError } from './zip.js';
9
+ const execFileAsync = promisify(execFile);
10
+ /**
11
+ * Упаковка проекта для заказчика: архив тега сдачи без внутренней кухни Maestro
12
+ * плюс `HANDOVER.md`. Один и тот же тег всегда даёт побайтово один и тот же архив:
13
+ * всё берётся из тега (а не из рабочей папки), порядок и время записей фиксированы.
14
+ */
15
+ export const PASSPORT_PATH = 'wiki/passport.md';
16
+ export const HANDOVER_PATH = 'HANDOVER.md';
17
+ /** Внутренние места Maestro и агентов в корне: заказчику они не нужны и в архив не попадают. */
18
+ export const INTERNAL_PATHS = ['wiki/', 'maestro/', '.claude/', 'protocols/', '.maestro/', 'CLAUDE.md', 'AGENTS.md', '.mcp.json'];
19
+ /** Разделы паспорта, без которых сдавать нельзя. */
20
+ export const PASSPORT_SECTIONS = [
21
+ 'Репозиторий',
22
+ 'Где работает',
23
+ 'Домен и DNS',
24
+ 'Данные, базы, резервные копии',
25
+ 'Внешние сервисы и чей аккаунт',
26
+ 'Переменные окружения',
27
+ 'Расписания и фоновые задачи',
28
+ 'Как запустить, обновить, откатить',
29
+ ];
30
+ const finding = (code, message, path) => ({ code, message, ...(path === undefined ? {} : { path }) });
31
+ /** Настройки машины, которые иначе меняли бы байты архива или вывод git. */
32
+ const GIT_PINNED = ['-c', 'core.autocrlf=false', '-c', 'core.eol=lf', '-c', 'log.showSignature=false', '-c', 'core.quotepath=off'];
33
+ async function git(root, args) {
34
+ return (await execFileAsync('git', [...GIT_PINNED, ...args], { cwd: root, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 })).stdout;
35
+ }
36
+ async function gitBuffer(root, args) {
37
+ return (await execFileAsync('git', [...GIT_PINNED, ...args], { cwd: root, encoding: 'buffer', maxBuffer: 4 * 1024 * 1024 * 1024 })).stdout;
38
+ }
39
+ /** Строка-заготовка шаблона: «- Пока нет» или «- Адрес: пока нет». Обычный текст со словами «пока нет» — запись. */
40
+ const PLACEHOLDER_LINE = /^\s*[-*]\s*(?:[^:\n]*:\s*)?пока нет\.?\s*$/i;
41
+ /** Разделы паспорта, которые не заполнены: нет раздела, нет записи или осталась заготовка «пока нет». */
42
+ export function passportGaps(text) {
43
+ const sections = new Map();
44
+ const parts = text.replace(/\r\n/g, '\n').replace(/<!--[\s\S]*?-->/g, '').split(/^## +/m).slice(1);
45
+ for (const part of parts) {
46
+ const newline = part.indexOf('\n');
47
+ const title = (newline < 0 ? part : part.slice(0, newline)).trim();
48
+ sections.set(title, newline < 0 ? '' : part.slice(newline + 1));
49
+ }
50
+ return PASSPORT_SECTIONS.filter((title) => {
51
+ const body = sections.get(title);
52
+ if (body === undefined)
53
+ return true;
54
+ const lines = body.split('\n').filter((line) => line.trim() !== '');
55
+ return lines.length === 0 || lines.some((line) => PLACEHOLDER_LINE.test(line));
56
+ });
57
+ }
58
+ function parsePax(data) {
59
+ const records = {};
60
+ let offset = 0;
61
+ while (offset < data.length) {
62
+ const space = data.indexOf(0x20, offset);
63
+ if (space < 0)
64
+ break;
65
+ const length = Number.parseInt(data.subarray(offset, space).toString('ascii'), 10);
66
+ if (!Number.isFinite(length) || length <= 0)
67
+ break;
68
+ const record = data.subarray(space + 1, offset + length - 1).toString('utf8');
69
+ const equals = record.indexOf('=');
70
+ if (equals > 0)
71
+ records[record.slice(0, equals)] = record.slice(equals + 1);
72
+ offset += length;
73
+ }
74
+ return records;
75
+ }
76
+ /** Разбор tar из `git archive`: ustar с префиксом и pax-заголовками для длинных путей. */
77
+ export function parseTar(buffer) {
78
+ const entries = [];
79
+ let offset = 0;
80
+ let pax = {};
81
+ while (offset + 512 <= buffer.length) {
82
+ const header = buffer.subarray(offset, offset + 512);
83
+ if (header.every((byte) => byte === 0))
84
+ break;
85
+ const field = (start, end) => {
86
+ const raw = header.subarray(start, end);
87
+ const zero = raw.indexOf(0);
88
+ return raw.subarray(0, zero < 0 ? raw.length : zero).toString('utf8');
89
+ };
90
+ const size = Number.parseInt(field(124, 136).trim() || '0', 8);
91
+ if (!Number.isFinite(size) || size < 0)
92
+ throw new Error('Не удалось прочитать размер записи в выводе git archive.');
93
+ const type = String.fromCharCode(header[156] ?? 0);
94
+ const start = offset + 512;
95
+ const data = buffer.subarray(start, start + size);
96
+ offset = start + Math.ceil(size / 512) * 512;
97
+ if (type === 'x') {
98
+ pax = parsePax(data);
99
+ continue;
100
+ }
101
+ if (type === 'g')
102
+ continue;
103
+ const prefix = field(345, 500);
104
+ const name = field(0, 100);
105
+ const path = pax.path ?? (prefix === '' ? name : `${prefix}/${name}`);
106
+ const link = pax.linkpath ?? field(157, 257);
107
+ pax = {};
108
+ // Права зависят от tar.umask машины; в архиве остаётся только «исполняемый или нет».
109
+ const mode = (Number.parseInt(field(100, 108).trim() || '0', 8) & 0o111) !== 0 ? 0o755 : 0o644;
110
+ if (type === '5')
111
+ continue;
112
+ if (type === '2')
113
+ entries.push({ path, mode: 0o120000 | 0o777, data: Buffer.from(link, 'utf8'), symlink: true });
114
+ else if (type === '0' || type === '\0' || type === '7')
115
+ entries.push({ path, mode: 0o100000 | mode, data: Buffer.from(data), symlink: false });
116
+ else
117
+ throw new Error(`Неподдерживаемая запись tar (${type}): ${path}`);
118
+ }
119
+ return entries;
120
+ }
121
+ const isInternal = (path) => INTERNAL_PATHS.some((internal) => (internal.endsWith('/') ? path.startsWith(internal) : path === internal));
122
+ /** Файлы и папки агентов, оставшиеся после исключения корневых: признак того, что в продукт попало чужое. */
123
+ const AGENT_PATH = /(^|\/)(\.claude|\.maestro|\.cursor)\/|(^|\/)(CLAUDE\.md|AGENTS\.md|GEMINI\.md|\.mcp\.json|\.cursorrules|\.windsurfrules)$/;
124
+ const SECRET_NAMES = [
125
+ { label: 'файл .env', test: (base) => (base === '.env' || base.startsWith('.env.') || base === '.envrc') && !/^\.env\.(example|sample|template)$/.test(base) },
126
+ { label: 'закрытый ключ SSH', test: (base) => /^id_(rsa|dsa|ecdsa|ed25519)$/.test(base) },
127
+ { label: 'хранилище ключей', test: (base) => /\.(p12|pfx|jks|keystore|key)$/i.test(base) },
128
+ { label: 'файл паролей', test: (base) => base === '.netrc' || base === '.pgpass' },
129
+ { label: 'файл секретов', test: (base) => /^(secrets?\.(ya?ml|json|toml)|credentials.*\.json|service[-_]?account.*\.json)$/i.test(base) },
130
+ { label: 'файл базы данных', test: (base) => /\.(sqlite3?|db)$/i.test(base) },
131
+ ];
132
+ /** Заготовки вместо настоящего значения: такие строки секретом не считаются. */
133
+ const PLACEHOLDER_VALUE = /^(?:[$<{%]|your|example|changeme|change-me|placeholder|dummy|test|xxx|\*\*\*)|example|xxxxx/i;
134
+ const LOCAL_HOSTS = new Set(['localhost', '127.0.0.1', '0.0.0.0', '::1']);
135
+ /** JWT с ролью service_role (Supabase и похожие) — секрет; публичный anon-ключ — нет. */
136
+ function hasServiceRoleJwt(line) {
137
+ for (const match of line.matchAll(/eyJ[A-Za-z0-9_-]{8,}\.(eyJ[A-Za-z0-9_-]{8,})\.[A-Za-z0-9_-]{8,}/g)) {
138
+ try {
139
+ if (Buffer.from(match[1], 'base64url').toString('utf8').includes('"service_role"'))
140
+ return true;
141
+ }
142
+ catch {
143
+ // не JWT
144
+ }
145
+ }
146
+ return false;
147
+ }
148
+ function hasDatabasePassword(line) {
149
+ for (const match of line.matchAll(/\b(?:postgres(?:ql)?|mysql|mariadb|mongodb(?:\+srv)?|rediss?|amqps?):\/\/[^\s:@\/"'`]*:([^\s@\/"'`]+)@([^\s:\/"'`?]+)/gi)) {
150
+ const password = match[1];
151
+ const host = match[2].toLowerCase();
152
+ if (LOCAL_HOSTS.has(host) || PLACEHOLDER_VALUE.test(password) || ['password', 'pass', 'postgres', 'root', 'secret'].includes(password.toLowerCase()))
153
+ continue;
154
+ return true;
155
+ }
156
+ return false;
157
+ }
158
+ const SECRET_CONTENT = [
159
+ // Ключ, а не код, который проверяет заголовок: за заголовком идёт перевод строки (в том числе `\n` в JSON) или сам ключ.
160
+ { label: 'закрытый ключ', test: (line) => /-----BEGIN [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----(?:\\(?:r\\)?n|\s*$|[A-Za-z0-9+/])/.test(line) },
161
+ { label: 'ключ AWS', test: (line) => [...line.matchAll(/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g)].some((match) => !match[0].endsWith('EXAMPLE')) },
162
+ { label: 'секретный ключ AWS', test: (line) => [...line.matchAll(/aws_secret_access_key["']?\s*[:=]\s*["']?([A-Za-z0-9/+]{40})(?![A-Za-z0-9/+])/gi)].some((match) => !match[1].includes('EXAMPLE')) },
163
+ { label: 'токен GitHub', test: (line) => /\b(?:gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{22,})/.test(line) },
164
+ { label: 'ключ Anthropic', test: (line) => /\bsk-ant-[A-Za-z0-9_-]{20,}/.test(line) },
165
+ { label: 'ключ OpenAI', test: (line) => /\bsk-(?:proj-)?[A-Za-z0-9_-]{32,}/.test(line) },
166
+ { label: 'токен Telegram-бота', test: (line) => /\b\d{8,10}:AA[0-9A-Za-z_-]{33}\b/.test(line) },
167
+ { label: 'токен Slack', test: (line) => /\bxox[abposr]-[A-Za-z0-9-]{10,}/.test(line) },
168
+ { label: 'ключ Stripe', test: (line) => /\b(?:sk|rk)_live_[0-9A-Za-z]{20,}/.test(line) },
169
+ { label: 'токен Supabase', test: (line) => /\bsbp_[a-f0-9]{40}\b/.test(line) || hasServiceRoleJwt(line) },
170
+ { label: 'токен npm', test: (line) => /\bnpm_[A-Za-z0-9]{36}\b/.test(line) },
171
+ { label: 'токен в .npmrc', test: (line) => /_authToken\s*=\s*(?!\$\{)\S+/.test(line) },
172
+ { label: 'пароль в адресе базы данных', test: hasDatabasePassword },
173
+ {
174
+ label: 'пароль или ключ в коде',
175
+ test: (line) => [...line.matchAll(/\b(?:password|passwd|secret|api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|private[_-]?key)\b["']?\s*[:=]\s*["']([^"'\s]{8,})["']/gi)]
176
+ // Браузерные ключи Google (Firebase, Карты) публичны по замыслу; JWT разбирает правило Supabase.
177
+ .some((match) => !PLACEHOLDER_VALUE.test(match[1]) && !/^(?:AIza|eyJ)/.test(match[1])),
178
+ },
179
+ ];
180
+ const MAX_SCAN_BYTES = 50 * 1024 * 1024;
181
+ /** Текст файла для проверки: UTF-8 или UTF-16 по метке; двоичный — null. */
182
+ function scanText(data) {
183
+ if (data[0] === 0xff && data[1] === 0xfe)
184
+ return data.subarray(2).toString('utf16le');
185
+ if (data[0] === 0xfe && data[1] === 0xff)
186
+ return Buffer.from(data.subarray(2)).swap16().toString('utf16le');
187
+ if (data.subarray(0, 8000).includes(0))
188
+ return null;
189
+ return data.toString('utf8');
190
+ }
191
+ /** Секреты по имени файла. */
192
+ export function secretName(path) {
193
+ const base = path.slice(path.lastIndexOf('/') + 1);
194
+ return SECRET_NAMES.find((rule) => rule.test(base))?.label ?? null;
195
+ }
196
+ /** Секреты по имени файла и по содержимому. Значение секрета в находку не попадает. */
197
+ export function findSecrets(path, data) {
198
+ const named = secretName(path);
199
+ if (named !== null)
200
+ return [finding('pack-secret', `Похоже на секрет (${named}): такой файл заказчику не отдают.`, path)];
201
+ if (data.length > MAX_SCAN_BYTES)
202
+ return [];
203
+ const text = scanText(data);
204
+ if (text === null)
205
+ return [];
206
+ const found = [];
207
+ text.split('\n').forEach((line, index) => {
208
+ const rule = SECRET_CONTENT.find((item) => item.test(line));
209
+ if (rule !== undefined)
210
+ found.push(finding('pack-secret', `Строка ${index + 1} похожа на секрет (${rule.label}).`, path));
211
+ });
212
+ return found;
213
+ }
214
+ /** Ссылка, ведущая за пределы проекта или по абсолютному пути: в архиве она указала бы на чужое. */
215
+ function symlinkEscapes(path, target) {
216
+ if (target.startsWith('/') || /^[A-Za-z]:[\\/]/.test(target))
217
+ return true;
218
+ return posix.normalize(posix.join(posix.dirname(path), target)).startsWith('../');
219
+ }
220
+ /** Текст `HANDOVER.md`: обязательный шаг «смените все пароли и ключи» и паспорт из тега. */
221
+ export function handoverText(input) {
222
+ const passport = input.passport.replace(/\r\n/g, '\n');
223
+ const firstSection = passport.search(/^## /m);
224
+ const body = (firstSection < 0 ? passport : passport.slice(firstSection)).replace(/^## /gm, '### ').trimEnd();
225
+ return [
226
+ `# Передача проекта ${input.projectName}`,
227
+ '',
228
+ `Версия: тег \`${input.tag}\`, коммит \`${input.commit}\`.`,
229
+ '',
230
+ '## Первым делом: смените все пароли и ключи',
231
+ '',
232
+ 'Пока проект делали, пароли и ключи знали исполнители. Сразу после передачи смените их все: ключи API, пароли от хостинга, баз данных, домена, почты и внешних сервисов. Новые значения задайте там, где они задаются (раздел «Переменные окружения» ниже), и проверьте, что проект работает.',
233
+ '',
234
+ '## Паспорт проекта',
235
+ '',
236
+ body,
237
+ '',
238
+ ].join('\n');
239
+ }
240
+ /** Имя файла архива по умолчанию: папка проекта и тег. */
241
+ export function defaultArchiveName(root, tag) {
242
+ const safe = (value) => value.normalize('NFC').replace(/[^\p{L}\p{N}._-]+/gu, '-').replace(/^-+|-+$/g, '');
243
+ return `${safe(resolve(root).split(/[\\/]/).pop() ?? 'project') || 'project'}-${safe(tag) || 'tag'}.zip`;
244
+ }
245
+ export async function packProject(options) {
246
+ const root = resolve(options.root);
247
+ const { tag } = options;
248
+ const fail = (...findings) => ({ ok: false, findings, tag });
249
+ if (!existsSync(root))
250
+ return fail(finding('pack-path-missing', `Папка не найдена: ${root}. Проверьте путь; путь с пробелами возьмите в кавычки.`));
251
+ if (!existsSync(join(root, MANIFEST_PATH)))
252
+ return fail(finding('pack-not-project', 'Это не проект Vibe Coding Maestro: нет `.maestro/manifest.json`.', MANIFEST_PATH));
253
+ let prefix;
254
+ try {
255
+ prefix = (await git(root, ['rev-parse', '--show-prefix'])).trim();
256
+ }
257
+ catch {
258
+ return fail(finding('pack-no-git', 'У проекта нет Git-истории: упаковывается только тег сдачи.'));
259
+ }
260
+ if (prefix !== '')
261
+ return fail(finding('pack-not-git-root', 'Проект должен быть корнем своего Git-репозитория.'));
262
+ let commit;
263
+ try {
264
+ commit = (await git(root, ['rev-parse', '--verify', '--quiet', `refs/tags/${tag}^{commit}`])).trim();
265
+ }
266
+ catch {
267
+ const tags = (await git(root, ['tag', '--list']).catch(() => '')).split('\n').filter((line) => line !== '');
268
+ const known = tags.length === 0 ? 'В проекте пока нет ни одного тега.' : `Есть теги: ${tags.slice(-10).join(', ')}.`;
269
+ return fail(finding('pack-tag-missing', `Тег «${tag}» не найден. ${known} Тег сдачи ставится по протоколу завершения, после «да» человека.`));
270
+ }
271
+ let passport;
272
+ try {
273
+ passport = await git(root, ['show', `${commit}:${PASSPORT_PATH}`]);
274
+ }
275
+ catch {
276
+ return fail(finding('pack-passport-missing', `В теге «${tag}» нет паспорта \`${PASSPORT_PATH}\`. Заполните паспорт, закоммитьте и поставьте новый тег.`, PASSPORT_PATH));
277
+ }
278
+ const gaps = passportGaps(passport);
279
+ if (gaps.length > 0) {
280
+ return fail(finding('pack-passport-incomplete', `Паспорт в теге «${tag}» не заполнен: ${gaps.map((title) => `«${title}»`).join(', ')}. В каждом разделе нужна запись или «не применимо». Заполните, закоммитьте и поставьте новый тег.`, PASSPORT_PATH));
281
+ }
282
+ let projectName = tag;
283
+ try {
284
+ const manifest = JSON.parse(await git(root, ['show', `${commit}:${MANIFEST_PATH}`]));
285
+ if (typeof manifest.project?.name === 'string' && manifest.project.name !== '')
286
+ projectName = manifest.project.name;
287
+ }
288
+ catch {
289
+ // Имя — только заголовок HANDOVER.md; без manifest в теге остаётся имя тега.
290
+ }
291
+ const time = Number.parseInt((await git(root, ['show', '-s', '--format=%ct', commit])).trim(), 10);
292
+ if (!Number.isFinite(time))
293
+ return fail(finding('pack-commit-time', `Не удалось прочитать время коммита тега «${tag}».`));
294
+ const entries = parseTar(await gitBuffer(root, ['archive', '--format=tar', commit]));
295
+ const notes = [];
296
+ const submodules = (await git(root, ['ls-tree', '-r', '-z', commit])).split('\0')
297
+ .filter((line) => line.split(' ')[1] === 'commit')
298
+ .map((line) => line.slice(line.indexOf('\t') + 1));
299
+ if (submodules.length > 0)
300
+ notes.push(`Подмодули Git в архив не входят: ${submodules.join(', ')}.`);
301
+ const allowed = new Set(options.allow ?? []);
302
+ const findings = [];
303
+ const kept = entries.filter((entry) => !isInternal(entry.path));
304
+ for (const entry of kept) {
305
+ if (AGENT_PATH.test(entry.path)) {
306
+ findings.push(finding('pack-internal-path', 'Файл или папка агента внутри продукта: заказчику их не отдают.', entry.path));
307
+ continue;
308
+ }
309
+ if (entry.path === HANDOVER_PATH) {
310
+ findings.push(finding('pack-handover-collision', `В корне проекта уже есть ${HANDOVER_PATH}; упаковка пишет этот файл сама. Переименуйте свой и поставьте новый тег.`, entry.path));
311
+ continue;
312
+ }
313
+ if (entry.symlink) {
314
+ if (symlinkEscapes(entry.path, entry.data.toString('utf8')))
315
+ findings.push(finding('pack-symlink-outside', 'Ссылка ведёт за пределы проекта: в архиве она укажет на чужие файлы.', entry.path));
316
+ else if (!allowed.has(entry.path) && secretName(entry.path) !== null)
317
+ findings.push(finding('pack-secret', `Похоже на секрет (${secretName(entry.path)}): такой файл заказчику не отдают.`, entry.path));
318
+ continue;
319
+ }
320
+ if (allowed.has(entry.path))
321
+ continue;
322
+ if (entry.data.length > MAX_SCAN_BYTES)
323
+ notes.push(`Не проверен на секреты (больше 50 МБ): ${entry.path}.`);
324
+ findings.push(...findSecrets(entry.path, entry.data));
325
+ }
326
+ const handover = Buffer.from(handoverText({ projectName, tag, commit, passport }), 'utf8');
327
+ findings.push(...findSecrets(HANDOVER_PATH, handover).map((item) => ({ ...item, message: `${item.message} Секрет в паспорте: в паспорт пишут только имена.` })));
328
+ const packed = new Set(kept.map((entry) => entry.path));
329
+ for (const path of allowed)
330
+ if (!packed.has(path))
331
+ notes.push(`--allow ${path}: такого файла в теге нет, флаг ничего не меняет.`);
332
+ if (findings.length > 0) {
333
+ const allowHint = findings.some((item) => item.code === 'pack-secret' && item.path !== HANDOVER_PATH)
334
+ ? ' Если человек посмотрел файл и это не секрет (например, тестовый пример), повторите с `--allow <путь>` — только после его «да».'
335
+ : '';
336
+ findings.push(finding('pack-refused', `Архив не создан. Уберите это из тега (или пометьте \`export-ignore\` в своём \`.gitattributes\`), закоммитьте, поставьте новый тег и повторите.${allowHint}`));
337
+ return { ok: false, findings, tag, commit };
338
+ }
339
+ const zipEntries = [
340
+ ...kept.map((entry) => ({ path: entry.path, data: entry.data, mode: entry.mode })),
341
+ { path: HANDOVER_PATH, data: handover, mode: 0o100644 },
342
+ ].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
343
+ let zip;
344
+ try {
345
+ zip = buildZip(zipEntries, time);
346
+ }
347
+ catch (cause) {
348
+ if (cause instanceof ZipTooLargeError)
349
+ return { ok: false, findings: [finding('pack-too-large', cause.message)], tag, commit };
350
+ throw cause;
351
+ }
352
+ const sha256 = createHash('sha256').update(zip).digest('hex');
353
+ let out = resolve(options.out);
354
+ const failWrite = (cause) => ({ ok: false, findings: [finding('pack-write-failed', `Не удалось записать архив: ${cause instanceof Error ? cause.message : String(cause)}`, out)], tag, commit });
355
+ try {
356
+ if (existsSync(out) && (await stat(out)).isDirectory())
357
+ out = join(out, defaultArchiveName(root, tag));
358
+ const summary = { tag, commit, archive: out, sha256, files: zipEntries.length, bytes: zip.length, ...(notes.length > 0 ? { notes } : {}) };
359
+ if (existsSync(out)) {
360
+ if ((await stat(out)).isFile() && (await readFile(out)).equals(zip))
361
+ return { ok: true, findings: [], reused: true, ...summary };
362
+ return { ok: false, findings: [finding('pack-out-exists', `По этому пути уже есть другой файл: ${out}. Удалите его или укажите другой --out.`, out)], tag, commit };
363
+ }
364
+ await mkdir(dirname(out), { recursive: true });
365
+ const temporary = `${out}.${process.pid}.tmp`;
366
+ try {
367
+ await writeFile(temporary, zip);
368
+ await rename(temporary, out);
369
+ }
370
+ catch (cause) {
371
+ await rm(temporary, { force: true });
372
+ return failWrite(cause);
373
+ }
374
+ return { ok: true, findings: [], reused: false, ...summary };
375
+ }
376
+ catch (cause) {
377
+ return failWrite(cause);
378
+ }
379
+ }
@@ -1,6 +1,7 @@
1
1
  import { lstat, readFile } from 'node:fs/promises';
2
2
  import { join, resolve } from 'node:path';
3
3
  import { absolutePathHasSymlink, pathHasSymlink } from '../doctor/fs-utils.js';
4
+ import { mergeGitignore } from '../gitignore.js';
4
5
  import { GITATTRIBUTES_CONTENT } from '../init.js';
5
6
  import { canonicalManagedKind, canonicalOwnershipInventory, CONTENT_OWNED_FILES, TEMPLATE_FILES } from '../inventory.js';
6
7
  import { CHECKSUMS_PATH, contentChecksum, isCanonicalManifest, loadChecksums, loadManifest, MANIFEST_PATH, normalizeEol, serializeJson, sha256, buildManifest, } from '../manifest.js';
@@ -11,6 +12,7 @@ import { renderTemplate } from '../template.js';
11
12
  import { compareVersions } from '../version.js';
12
13
  import { findRelease, supportedVersions } from './releases.js';
13
14
  import { recoverTemplateVars, templateUses } from '../template-recover.js';
15
+ const GITIGNORE_PATH = '.gitignore';
14
16
  /** Каталог транзакции. Внутри `.maestro`, чтобы не появляться в дереве проекта. */
15
17
  export const STAGING_DIR = '.maestro/upgrade-staging';
16
18
  const blocker = (code, message, path) => ({ code, message, ...(path === undefined ? {} : { path }) });
@@ -342,6 +344,18 @@ export async function analyzeUpgrade(rootInput) {
342
344
  updates.push({ path, ownership: 'project-owned' });
343
345
  writes.push({ path, content, action: 'update' });
344
346
  }
347
+ // .gitignore принадлежит проекту: upgrade только дописывает недостающие строки Maestro,
348
+ // строки проекта не меняет. Что это обычный файл, доказано проверкой полного дерева выше.
349
+ // Строки Maestro — ASCII, поэтому сравнение и дописывание идут по байтам (latin1): свои
350
+ // строки проекта в любой кодировке остаются байт в байт.
351
+ const raw = await readFile(join(root, GITIGNORE_PATH));
352
+ // Метка UTF-8 (BOM) в начале не должна прятать первую строку от сравнения.
353
+ const bom = raw.subarray(0, 3).equals(Buffer.from([0xef, 0xbb, 0xbf])) ? 3 : 0;
354
+ const gitignore = mergeGitignore(raw.subarray(bom).toString('latin1'));
355
+ if (gitignore.addedEntries.length > 0) {
356
+ updates.push({ path: GITIGNORE_PATH, ownership: 'project-owned', appends: gitignore.addedEntries });
357
+ writes.push({ path: GITIGNORE_PATH, content: raw.subarray(0, bom).toString('latin1') + gitignore.content, action: 'update', encoding: 'latin1' });
358
+ }
345
359
  if (blockers.length > 0)
346
360
  return blockedAt(root, release, fromVersion, blockers);
347
361
  // 4. Metadata. Manifest пересобирается по текущему канону; проектные поля переносятся как есть.
@@ -374,7 +388,7 @@ export async function analyzeUpgrade(rootInput) {
374
388
  result.preserves = [
375
389
  ...Object.entries(baseline).filter(([path, ownership]) => ownership === 'project-owned' && path in current).map(([path]) => path),
376
390
  ...keptExisting,
377
- ].sort();
391
+ ].filter((path) => !updates.some((item) => item.path === path)).sort();
378
392
  result.handedOver = handover.map(({ path }) => path).sort();
379
393
  return {
380
394
  analysis: result,
@@ -1,5 +1,5 @@
1
1
  import { existsSync } from 'node:fs';
2
- import { mkdir, readFile, rename, rm, rmdir, writeFile } from 'node:fs/promises';
2
+ import { copyFile, mkdir, rename, rm, rmdir, writeFile } from 'node:fs/promises';
3
3
  import { dirname, join } from 'node:path';
4
4
  import { analyzeUpgrade, STAGING_DIR } from './analyze.js';
5
5
  export { analyzeUpgrade, STAGING_DIR } from './analyze.js';
@@ -25,9 +25,13 @@ function missingDirs(root, relativePath) {
25
25
  }
26
26
  return created;
27
27
  }
28
- async function writeStaged(absolute, content) {
28
+ /** Содержимое Maestro пишется с LF; дописанный файл проекта (`latin1`) — байт в байт. */
29
+ async function writeStaged(absolute, content, encoding) {
29
30
  await mkdir(dirname(absolute), { recursive: true });
30
- await writeFile(absolute, content.replace(/\r\n/g, '\n'), 'utf8');
31
+ if (encoding === 'latin1')
32
+ await writeFile(absolute, Buffer.from(content, 'latin1'));
33
+ else
34
+ await writeFile(absolute, content.replace(/\r\n/g, '\n'), 'utf8');
31
35
  }
32
36
  /**
33
37
  * Безопасная эволюция канонического проекта предыдущей версии.
@@ -58,9 +62,11 @@ export async function upgradeProject(rootInput, options = {}) {
58
62
  try {
59
63
  await mkdir(staging, { recursive: false });
60
64
  for (const write of writes) {
61
- await writeStaged(join(newDir, write.path), write.content);
65
+ await writeStaged(join(newDir, write.path), write.content, write.encoding);
62
66
  if (write.action === 'update') {
63
- await writeStaged(join(backupDir, write.path), await readFile(join(root, write.path), 'utf8'));
67
+ // Backup — точная копия байтов: откат возвращает файл таким, каким он был.
68
+ await mkdir(dirname(join(backupDir, write.path)), { recursive: true });
69
+ await copyFile(join(root, write.path), join(backupDir, write.path));
64
70
  }
65
71
  }
66
72
  }
@@ -202,10 +202,11 @@ const V030_CONTENT_OWNED_FILES = [
202
202
  'wiki/concepts/discovery.md',
203
203
  'wiki/plans/0001-starter.md',
204
204
  ];
205
- function v030OwnershipInventory(depth) {
206
- return {
207
- ...Object.fromEntries(V030_TEMPLATE_FILES.map((path) => [path, 'managed'])),
208
- ...Object.fromEntries(V030_CONTENT_OWNED_FILES.map((path) => [path, 'project-owned'])),
205
+ /** Форма inventory канонов 0.3.0 и новее: managed-шаблоны, файлы проекта, каталоги по глубине. */
206
+ function ownershipInventory(templateFiles, contentOwnedFiles) {
207
+ return (depth) => ({
208
+ ...Object.fromEntries(templateFiles.map((path) => [path, 'managed'])),
209
+ ...Object.fromEntries(contentOwnedFiles.map((path) => [path, 'project-owned'])),
209
210
  ...Object.fromEntries(v03LazyDirs(depth).map((path) => [
210
211
  `${path}/.gitkeep`,
211
212
  path === 'maestro/sources' ? 'immutable' : 'managed',
@@ -213,8 +214,9 @@ function v030OwnershipInventory(depth) {
213
214
  '.gitignore': 'project-owned',
214
215
  '.maestro/manifest.json': 'generated',
215
216
  '.maestro/checksums.json': 'generated',
216
- };
217
+ });
217
218
  }
219
+ const v030OwnershipInventory = ownershipInventory(V030_TEMPLATE_FILES, V030_CONTENT_OWNED_FILES);
218
220
  /** Слепок `templates/project` 0.3.0. */
219
221
  const V030_MANAGED_SHA256 = {
220
222
  '.claude/rules/maestro.md': 'f30e231f962a1dd27f423f6173829ecf45c9df30ce50bcbd88dfd4db65e78da0',
@@ -252,6 +254,39 @@ const V030_MANAGED_SHA256 = {
252
254
  'protocols/build/audit-plan.md': '1a6cd6e69044a1985822ed28809123d2980a223fb78e39aa63d4f5618bb66a64',
253
255
  'protocols/build/audit-phase.md': 'ac0c1919380516e3c0da09697b2a021a96866016816fb76d7aef2866c8c08f81',
254
256
  };
257
+ /** 0.3.1: тот же состав файлов; в правилах Maestro управляемые команды названы поимённо. */
258
+ const V031_MANAGED_SHA256 = {
259
+ ...V030_MANAGED_SHA256,
260
+ '.claude/rules/maestro.md': '340131be8c15a06fb7905452f000fa7dac775093c85370163c0af68c14198cae',
261
+ };
262
+ /** Копии шаблонов 0.3.1, изменённых в 0.4.0. В 0.3.0 протоколы были побайтово такими же. */
263
+ const v031Copy = (path) => ({
264
+ path,
265
+ source: `registry/baseline/0.3.1/project/${path}`,
266
+ sha256: V031_MANAGED_SHA256[path],
267
+ });
268
+ /** Файлы, которые 0.4.0 изменил: в 0.3.0 и 0.3.1 они одинаковы. */
269
+ const CHANGED_IN_040_SAME_SINCE_030 = ['.claude/agents/code-reviewer.md', '.claude/agents/explorer.md', 'protocols/build.md', 'protocols/handoff.md'];
270
+ /** Канон 0.4.0: протокол «Завершение» (Maestro) и паспорт проекта (проект). */
271
+ const V040_TEMPLATE_FILES = [...V030_TEMPLATE_FILES, 'protocols/completion.md'];
272
+ const V040_CONTENT_OWNED_FILES = [...V030_CONTENT_OWNED_FILES, 'wiki/passport.md'];
273
+ /** Слепок `templates/project` 0.4.0. */
274
+ const V040_MANAGED_SHA256 = {
275
+ ...V030_MANAGED_SHA256,
276
+ '.claude/rules/maestro.md': '6c230aa2dbd3105f8afd242d7dfa6749499cca8e1b6d974ff496ba6e7928a930',
277
+ '.claude/agents/code-reviewer.md': 'ce515ba41d042f6cd26475f693e1cb1a24a007d0d515d3876c467759e7a81f86',
278
+ '.claude/agents/explorer.md': '27b8239748816977c5ee628782b43330a1b803df19899dd081a1962d71a42d13',
279
+ 'protocols/build.md': 'e7c1df3dc5b44ed6b03c4d83e28afcdc7e048b48fb20168f622238d6b7d502a9',
280
+ 'protocols/handoff.md': '4f01fb23b248d4acd1d5b917fc08971d763eeccf893286d58decc4b3345d1ce2',
281
+ 'protocols/completion.md': '7dba5ef6d31427c7cad88f6dd81218d48e978a1b88610f2a70c5eec736cdf302',
282
+ };
283
+ const v040OwnershipInventory = ownershipInventory(V040_TEMPLATE_FILES, V040_CONTENT_OWNED_FILES);
284
+ /** Копии шаблонов 0.4.0, изменённых в 0.4.1. */
285
+ const v040Copy = (path) => ({
286
+ path,
287
+ source: `registry/baseline/0.4.0/project/${path}`,
288
+ sha256: V040_MANAGED_SHA256[path],
289
+ });
255
290
  export const RELEASES = [
256
291
  {
257
292
  id: BASELINE_ID,
@@ -283,18 +318,40 @@ export const RELEASES = [
283
318
  versions: ['0.3.0'],
284
319
  inventory: v030OwnershipInventory,
285
320
  managedSha256: V030_MANAGED_SHA256,
286
- templates: [{
321
+ templates: [
322
+ {
287
323
  path: '.claude/rules/maestro.md',
288
324
  source: 'registry/baseline/0.3.0/project/.claude/rules/maestro.md',
289
325
  sha256: V030_MANAGED_SHA256['.claude/rules/maestro.md'],
290
- }],
326
+ },
327
+ ...CHANGED_IN_040_SAME_SINCE_030.map(v031Copy),
328
+ ],
291
329
  },
292
330
  {
293
- // 0.3.1: тот же состав файлов; в правилах Maestro управляемые команды названы поимённо.
294
331
  id: '0.3.1',
295
332
  versions: ['0.3.1'],
296
333
  inventory: v030OwnershipInventory,
297
- managedSha256: { ...V030_MANAGED_SHA256, '.claude/rules/maestro.md': '340131be8c15a06fb7905452f000fa7dac775093c85370163c0af68c14198cae' },
334
+ managedSha256: V031_MANAGED_SHA256,
335
+ templates: ['.claude/rules/maestro.md', ...CHANGED_IN_040_SAME_SINCE_030].map(v031Copy),
336
+ },
337
+ {
338
+ id: '0.4.0',
339
+ versions: ['0.4.0'],
340
+ inventory: v040OwnershipInventory,
341
+ managedSha256: V040_MANAGED_SHA256,
342
+ templates: ['.claude/rules/maestro.md', 'protocols/completion.md', 'protocols/handoff.md'].map(v040Copy),
343
+ },
344
+ {
345
+ // 0.4.1: тот же состав файлов; правила и протоколы зовут `context` и `pack`.
346
+ id: '0.4.1',
347
+ versions: ['0.4.1'],
348
+ inventory: v040OwnershipInventory,
349
+ managedSha256: {
350
+ ...V040_MANAGED_SHA256,
351
+ '.claude/rules/maestro.md': '490eed80098f853068d208ced54391d71c1de740e1fbd8199f54d98f9831216e',
352
+ 'protocols/handoff.md': '10b1a9d21ce40eef441eaf545024cb246b6dda9ae84bfdd4226891aedb253044',
353
+ 'protocols/completion.md': 'fe500e828bf1fc5e73745815cd019af455180f94aba06f13c2b02dfcad61cbfd',
354
+ },
298
355
  templates: [],
299
356
  },
300
357
  ];