create-vibe-maestro 0.4.0 → 0.4.2

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 (57) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/README.md +34 -30
  3. package/dist/cli/context-run.js +38 -0
  4. package/dist/cli/create-run.js +74 -9
  5. package/dist/cli/create.js +21 -2
  6. package/dist/cli/doctor-run.js +2 -1
  7. package/dist/cli/maestro.js +67 -1
  8. package/dist/cli/pack-run.js +44 -0
  9. package/dist/cli/prompt.js +12 -4
  10. package/dist/cli/renderer.js +5 -4
  11. package/dist/cli/upgrade-run.js +4 -0
  12. package/dist/core/context.js +169 -0
  13. package/dist/core/doctor/git.js +41 -1
  14. package/dist/core/doctor/inbox.js +5 -11
  15. package/dist/core/doctor/sources.js +1 -1
  16. package/dist/core/github.js +107 -0
  17. package/dist/core/init.js +37 -10
  18. package/dist/core/inventory.js +4 -0
  19. package/dist/core/pack.js +379 -0
  20. package/dist/core/readme.js +21 -0
  21. package/dist/core/settings.js +39 -0
  22. package/dist/core/upgrade/analyze.js +61 -8
  23. package/dist/core/upgrade/baseline.js +4 -0
  24. package/dist/core/upgrade/releases.js +73 -3
  25. package/dist/core/zip.js +133 -0
  26. package/docs/ROADMAP.md +74 -47
  27. package/docs/USER_GUIDE.md +113 -60
  28. package/package.json +1 -1
  29. package/registry/baseline/0.4.0/project/.claude/rules/maestro.md +35 -0
  30. package/registry/baseline/0.4.0/project/protocols/completion.md +22 -0
  31. package/registry/baseline/0.4.0/project/protocols/handoff.md +15 -0
  32. package/registry/baseline/0.4.1/project/.claude/commands/plan.md +2 -0
  33. package/registry/baseline/0.4.1/project/.claude/rules/maestro.md +35 -0
  34. package/registry/baseline/0.4.1/project/maestro/inbox/README.md +16 -0
  35. package/registry/baseline/0.4.1/project/maestro/runbooks/cowork-discovery.md +30 -0
  36. package/registry/baseline/0.4.1/project/protocols/discovery.md +5 -0
  37. package/registry/baseline/0.4.1/project/protocols/plan.md +142 -0
  38. package/registry/capabilities.v1.json +13 -1
  39. package/templates/project/.claude/commands/plan.md +1 -0
  40. package/templates/project/.claude/commands/start.md +2 -0
  41. package/templates/project/.claude/rules/maestro.md +6 -4
  42. package/templates/project/.claude/rules/project.md +6 -0
  43. package/templates/project/.claude/settings.json +2 -0
  44. package/templates/project/README.md +11 -0
  45. package/templates/project/maestro/inbox/README.md +6 -6
  46. package/templates/project/maestro/runbooks/cowork-discovery.md +1 -1
  47. package/templates/project/protocols/completion.md +1 -1
  48. package/templates/project/protocols/discovery.md +1 -3
  49. package/templates/project/protocols/handoff.md +1 -1
  50. package/templates/project/protocols/plan.md +14 -7
  51. package/templates/project/protocols/start.md +64 -0
  52. package/templates/project/wiki/concepts/discovery.md +30 -11
  53. package/templates/project/wiki/hot.md +2 -2
  54. package/templates/project/wiki/index.md +1 -0
  55. package/templates/project/wiki/passport.md +2 -0
  56. package/templates/project/wiki/plans/0001-starter.md +4 -3
  57. package/templates/project/wiki/restore.md +32 -0
@@ -4,6 +4,7 @@ export const TEMPLATE_FILES = [
4
4
  'wiki/plans/README.md',
5
5
  'wiki/plans/TEMPLATE.md',
6
6
  'maestro/inbox/README.md',
7
+ 'maestro/inbox/.gitattributes',
7
8
  'maestro/runbooks/cowork-discovery.md',
8
9
  'maestro/runbooks/cowork-audit.md',
9
10
  'maestro/runbooks/cowork-plan.md',
@@ -12,6 +13,7 @@ export const TEMPLATE_FILES = [
12
13
  '.claude/commands/wiki.md',
13
14
  '.claude/commands/handoff.md',
14
15
  '.claude/commands/plan.md',
16
+ '.claude/commands/start.md',
15
17
  '.claude/agents/code-reviewer.md',
16
18
  '.claude/agents/explorer.md',
17
19
  'maestro/templates/handoff.md',
@@ -29,6 +31,7 @@ export const TEMPLATE_FILES = [
29
31
  'protocols/seams.md',
30
32
  'protocols/lessons.md',
31
33
  'protocols/completion.md',
34
+ 'protocols/start.md',
32
35
  'protocols/build/step-1-rules.md',
33
36
  'protocols/build/step-2-spec.md',
34
37
  'protocols/build/step-3-architecture.md',
@@ -47,6 +50,7 @@ export const CONTENT_OWNED_FILES = [
47
50
  'wiki/log.md',
48
51
  'wiki/roadmap.md',
49
52
  'wiki/passport.md',
53
+ 'wiki/restore.md',
50
54
  'wiki/concepts/discovery.md',
51
55
  'wiki/plans/0001-starter.md',
52
56
  ];
@@ -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
+ }
@@ -0,0 +1,21 @@
1
+ import { readdir } from 'node:fs/promises';
2
+ /**
3
+ * README проекта — не в составе, который проверяет doctor: create и upgrade кладут его,
4
+ * только если в корне нет никакого README, а удалить его можно. В составе он стал бы
5
+ * обязательным, а на Linux рядом с `readme.md` появился бы второй файл.
6
+ */
7
+ export const README_PATH = 'README.md';
8
+ /** README, README.md, readme.md, README.rst, Readme.txt и т. п. — любое имя «readme» с расширением или без. */
9
+ export function isReadmeName(name) {
10
+ return /^readme(\..*)?$/i.test(name);
11
+ }
12
+ export async function hasAnyReadme(root) {
13
+ try {
14
+ return (await readdir(root)).some(isReadmeName);
15
+ }
16
+ catch (cause) {
17
+ if (cause.code === 'ENOENT')
18
+ return false;
19
+ throw cause;
20
+ }
21
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * «Отправка в облако без вопроса» — рецепт из руководства («Как подстроить защиты под проект»)
3
+ * и из `protocols/start.md`: обычный push разрешён, принудительный остаётся с вопросом —
4
+ * «спросить» сильнее «разрешить». Ключ `ask` в файле один.
5
+ */
6
+ export const SETTINGS_PATH = '.claude/settings.json';
7
+ export const PUSH_ALLOW = ['Bash(git push *)'];
8
+ /**
9
+ * Отправка, которая может перезаписать или стереть работу в облаке: принудительная
10
+ * (`--force`, `-f`, `+ветка`) и удаление веток (`--delete`, `-d`, `--mirror`, `--prune`).
11
+ * Запись `:ветка` правилом не ловится: шаблон на `:*` Claude Code читает как старое
12
+ * «команда начинается с …», и тогда с вопросом шёл бы любой push.
13
+ */
14
+ export const FORCE_PUSH_ASK = [
15
+ 'Bash(git push --force)',
16
+ 'Bash(git push -f)',
17
+ 'Bash(git push *--force*)',
18
+ 'Bash(git push -f*)',
19
+ 'Bash(git push * -f*)',
20
+ 'Bash(git push * +*)',
21
+ 'Bash(git push *--delete*)',
22
+ 'Bash(git push -d *)',
23
+ 'Bash(git push * -d *)',
24
+ 'Bash(git push *--mirror*)',
25
+ 'Bash(git push *--prune*)',
26
+ ];
27
+ /** Шаблон settings.json → тот же файл с «отправкой без вопроса»; остальные правила не меняются. */
28
+ export function withPushWithoutAsking(settingsJson) {
29
+ const settings = JSON.parse(settingsJson);
30
+ const { deny, allow, ask, ...rest } = settings.permissions;
31
+ const askRules = (ask ?? []).flatMap((rule) => rule === 'Bash(git push *)' ? [...FORCE_PUSH_ASK] : [rule]);
32
+ const permissions = {
33
+ ...(deny === undefined ? {} : { deny }),
34
+ allow: [...new Set([...(allow ?? []), ...PUSH_ALLOW])],
35
+ ask: askRules,
36
+ ...rest,
37
+ };
38
+ return `${JSON.stringify({ ...settings, permissions }, null, 2)}\n`;
39
+ }
@@ -1,18 +1,24 @@
1
- import { lstat, readFile } from 'node:fs/promises';
1
+ import { lstat, readdir, readFile } from 'node:fs/promises';
2
2
  import { join, resolve } from 'node:path';
3
3
  import { absolutePathHasSymlink, pathHasSymlink } from '../doctor/fs-utils.js';
4
4
  import { mergeGitignore } from '../gitignore.js';
5
- import { GITATTRIBUTES_CONTENT } from '../init.js';
5
+ import { CODE_MANAGED_SOURCES } from '../init.js';
6
6
  import { canonicalManagedKind, canonicalOwnershipInventory, CONTENT_OWNED_FILES, TEMPLATE_FILES } from '../inventory.js';
7
7
  import { CHECKSUMS_PATH, contentChecksum, isCanonicalManifest, loadChecksums, loadManifest, MANIFEST_PATH, normalizeEol, serializeJson, sha256, buildManifest, } from '../manifest.js';
8
8
  import { CREATE_COMMAND, serviceInvocation, VERSION } from '../meta.js';
9
9
  import { readPackageJson, packageRoot, templatesDir } from '../paths.js';
10
+ import { hasAnyReadme, README_PATH } from '../readme.js';
10
11
  import { canonicalizeSystemTempPrefix } from '../platform-paths.js';
11
12
  import { renderTemplate } from '../template.js';
12
13
  import { compareVersions } from '../version.js';
13
14
  import { findRelease, supportedVersions } from './releases.js';
14
15
  import { recoverTemplateVars, templateUses } from '../template-recover.js';
15
16
  const GITIGNORE_PATH = '.gitignore';
17
+ /** Папка материалов человека и правило «байт в байт» для неё (0.4.2). */
18
+ const INBOX_DIR = 'maestro/inbox';
19
+ const INBOX_GITATTRIBUTES_PATH = `${INBOX_DIR}/.gitattributes`;
20
+ /** Версия, с которой README проекта кладут create и upgrade; с неё и дальше удалённый README не возвращается. */
21
+ const README_SINCE = '0.4.2';
16
22
  /** Каталог транзакции. Внутри `.maestro`, чтобы не появляться в дереве проекта. */
17
23
  export const STAGING_DIR = '.maestro/upgrade-staging';
18
24
  const blocker = (code, message, path) => ({ code, message, ...(path === undefined ? {} : { path }) });
@@ -30,6 +36,7 @@ function analysis(root, status, fromVersion, blockers, baselineId = 'unknown') {
30
36
  preserves: [],
31
37
  handedOver: [],
32
38
  metadata: [],
39
+ notes: [],
33
40
  blockers,
34
41
  };
35
42
  }
@@ -59,10 +66,11 @@ async function exists(absolute) {
59
66
  async function readTemplate(relativePath) {
60
67
  return readFile(join(templatesDir(), 'project', relativePath), 'utf8');
61
68
  }
62
- /** Исходник managed-пути текущей версии. `.gitattributes` пишет константа init, а не шаблон. */
69
+ /** Исходник managed-пути текущей версии. Оба `.gitattributes` пишет константа init, а не шаблон. */
63
70
  async function currentSource(relativePath) {
64
- if (relativePath === '.gitattributes')
65
- return GITATTRIBUTES_CONTENT;
71
+ const constant = CODE_MANAGED_SOURCES[relativePath];
72
+ if (constant !== undefined)
73
+ return constant;
66
74
  return normalizeEol(await readTemplate(relativePath));
67
75
  }
68
76
  /**
@@ -280,6 +288,8 @@ export async function analyzeUpgrade(rootInput) {
280
288
  const writes = [];
281
289
  const creates = [];
282
290
  const keptExisting = [];
291
+ /** Новый managed-путь, который уже лежит побайтово таким, как его записал бы Maestro: принимается как есть. */
292
+ const adopted = [];
283
293
  for (const path of newPaths.sort()) {
284
294
  const ownership = current[path];
285
295
  if (await pathHasSymlink(root, path)) {
@@ -292,11 +302,28 @@ export async function analyzeUpgrade(rootInput) {
292
302
  keptExisting.push(path);
293
303
  continue;
294
304
  }
305
+ if (path === INBOX_GITATTRIBUTES_PATH && await isRegularFile(join(root, path))) {
306
+ if ((await readFile(join(root, path))).equals(Buffer.from(CODE_MANAGED_SOURCES[path], 'utf8'))) {
307
+ adopted.push(path);
308
+ continue;
309
+ }
310
+ blockers.push(blocker('upgrade-inbox-gitattributes-foreign', 'В maestro/inbox/ уже лежит свой .gitattributes. Upgrade кладёт сюда файл Maestro с правилом `* -text` (git хранит материалы байт в байт) и чужой не перезаписывает: уберите или переименуйте свой файл, затем повторите. Если его правила нужны, положите их в .gitattributes подпапки внутри maestro/inbox/ — он действует на свою папку. Корневой .gitattributes не правьте: это файл Maestro.', path));
311
+ continue;
312
+ }
313
+ if (path.startsWith('.claude/commands/')) {
314
+ const name = path.slice('.claude/commands/'.length).replace(/\.md$/, '');
315
+ blockers.push(blocker('upgrade-command-collision', `У проекта уже есть своя команда /${name}, а эта версия Maestro добавляет команду с тем же именем. Upgrade её не перезаписывает: переименуйте свою (например, в .claude/commands/my-${name}.md) и повторите.`, path));
316
+ continue;
317
+ }
295
318
  blockers.push(blocker('upgrade-path-collision', 'Добавляемый путь уже занят: upgrade не перезаписывает существующее содержимое.', path));
296
319
  continue;
297
320
  }
298
321
  let content;
299
- if (TEMPLATE_FILES.includes(path) || CONTENT_OWNED_FILES.includes(path)) {
322
+ const constant = CODE_MANAGED_SOURCES[path];
323
+ if (constant !== undefined) {
324
+ content = constant;
325
+ }
326
+ else if (TEMPLATE_FILES.includes(path) || CONTENT_OWNED_FILES.includes(path)) {
300
327
  const source = await readTemplate(path);
301
328
  const templateVars = renderVars(source);
302
329
  if (templateVars === null) {
@@ -315,6 +342,16 @@ export async function analyzeUpgrade(rootInput) {
315
342
  creates.push({ path, ownership });
316
343
  writes.push({ path, content, action: 'create' });
317
344
  }
345
+ // README проекта — не в каноне: только переход на 0.4.2 кладёт его, и только если в корне нет
346
+ // никакого README. Позже удалённый человеком README upgrade не возвращает.
347
+ if ((compareVersions(fromVersion, README_SINCE) ?? 0) < 0 && !await hasAnyReadme(root)) {
348
+ const source = await readTemplate(README_PATH);
349
+ const templateVars = renderVars(source);
350
+ if (templateVars !== null) {
351
+ creates.push({ path: README_PATH, ownership: 'project-owned' });
352
+ writes.push({ path: README_PATH, content: renderTemplate(source, templateVars), action: 'create' });
353
+ }
354
+ }
318
355
  // 3. Обновления managed-файлов с доказанным preimage.
319
356
  const updates = [];
320
357
  const unchanged = [];
@@ -324,7 +361,7 @@ export async function analyzeUpgrade(rootInput) {
324
361
  blockers.push(blocker('upgrade-variable-unrecoverable', 'Шаблон требует подстановку, которую нельзя восстановить из проекта; угадывать её нельзя.', path));
325
362
  continue;
326
363
  }
327
- const content = path === '.gitattributes' ? next : renderTemplate(next, templateVars);
364
+ const content = path in CODE_MANAGED_SOURCES ? next : renderTemplate(next, templateVars);
328
365
  if (normalizeEol(content) === actual) {
329
366
  unchanged.push(path);
330
367
  continue;
@@ -380,10 +417,17 @@ export async function analyzeUpgrade(rootInput) {
380
417
  nextChecksums[write.path] = contentChecksum(write.path, write.content);
381
418
  }
382
419
  }
420
+ for (const path of adopted)
421
+ nextChecksums[path] = contentChecksum(path, await currentSource(path));
383
422
  const result = analysis(root, 'upgradable', fromVersion, [], release.id);
384
423
  result.creates = creates;
385
424
  result.updates = updates;
386
- result.unchanged = unchanged.sort();
425
+ result.unchanged = [...unchanged, ...adopted].sort();
426
+ if (creates.some((item) => item.path === INBOX_GITATTRIBUTES_PATH) && await hasMaterials(root)) {
427
+ // Опыт (git 2.54): файл, который git уже видел, после нового правила изменённым не показывается —
428
+ // git не перечитывает его, пока файл не тронут. Переписать его в git байт в байт можно только явно.
429
+ result.notes.push('Материалы, которые уже лежат в maestro/inbox/, git сам не перепишет. Чтобы он хранил их байт в байт, после обновления выполните `git add --renormalize maestro/inbox` и закоммитьте вместе с обновлением. Если файл уже был нормализован (например, взят из свежего клона на другом компьютере), исходные байты есть только в его источнике.');
430
+ }
387
431
  result.metadata = [MANIFEST_PATH, CHECKSUMS_PATH];
388
432
  result.preserves = [
389
433
  ...Object.entries(baseline).filter(([path, ownership]) => ownership === 'project-owned' && path in current).map(([path]) => path),
@@ -400,6 +444,15 @@ export async function analyzeUpgrade(rootInput) {
400
444
  ],
401
445
  };
402
446
  }
447
+ /** Есть ли в maestro/inbox/ что-то, кроме файлов самого Maestro. */
448
+ async function hasMaterials(root) {
449
+ try {
450
+ return (await readdir(join(root, INBOX_DIR))).some((name) => !['README.md', '.gitkeep', '.gitattributes'].includes(name));
451
+ }
452
+ catch {
453
+ return false;
454
+ }
455
+ }
403
456
  /** Ключи сортируются так же, как в init: повторный запуск даёт побайтово тот же файл. */
404
457
  function sortKeys(files) {
405
458
  const sorted = {};
@@ -150,4 +150,8 @@ export const BASELINE_TEMPLATES = [
150
150
  { path: 'protocols/handoff.md', source: 'registry/baseline/0.3.0-beta.4/project/protocols/handoff.md', sha256: '7aec6bf47408b42fc4bb9e977664295c9461dfd69c3ff438676c99e2d2b86b80' },
151
151
  { path: 'protocols/context-budget.md', source: 'registry/baseline/0.3.0-beta.4/project/protocols/context-budget.md', sha256: 'e121d6dc75de04ea3624608be5f778d43e99afa815540738ec3a43e47ccdcf8c' },
152
152
  { path: 'maestro/runbooks/cowork-audit.md', source: 'registry/baseline/0.3.0-beta.4/project/maestro/runbooks/cowork-audit.md', sha256: 'c3326dfd63dc94bce1bd1779e2d8116685cf7281b7d902c58f9138db6343f50b' },
153
+ // Изменены в 0.4.2; с 0.2 по 0.4.1 побайтово одинаковы — копия общая.
154
+ { path: 'maestro/inbox/README.md', source: 'registry/baseline/0.4.1/project/maestro/inbox/README.md', sha256: '5c3107b469d1c65d5a9d84132f2b0cfb85804b813ad5b9b65248dc434d6981a3' },
155
+ { path: 'maestro/runbooks/cowork-discovery.md', source: 'registry/baseline/0.4.1/project/maestro/runbooks/cowork-discovery.md', sha256: '1a32c070375783cfa54a3fad5c9644810f6eda37b7cd1a272f811278360b35c4' },
156
+ { path: 'protocols/discovery.md', source: 'registry/baseline/0.4.1/project/protocols/discovery.md', sha256: '20ef8084561a1c93a16003d3dac0426b43bb97b715f445f06ef79dd738e1430a' },
153
157
  ];