create-vibe-maestro 0.4.1 → 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 (46) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +33 -30
  3. package/dist/cli/create-run.js +74 -9
  4. package/dist/cli/create.js +21 -2
  5. package/dist/cli/doctor-run.js +2 -1
  6. package/dist/cli/prompt.js +12 -4
  7. package/dist/cli/renderer.js +5 -4
  8. package/dist/cli/upgrade-run.js +4 -0
  9. package/dist/core/doctor/git.js +41 -1
  10. package/dist/core/doctor/inbox.js +5 -11
  11. package/dist/core/doctor/sources.js +1 -1
  12. package/dist/core/github.js +107 -0
  13. package/dist/core/init.js +37 -10
  14. package/dist/core/inventory.js +4 -0
  15. package/dist/core/readme.js +21 -0
  16. package/dist/core/settings.js +39 -0
  17. package/dist/core/upgrade/analyze.js +61 -8
  18. package/dist/core/upgrade/baseline.js +4 -0
  19. package/dist/core/upgrade/releases.js +60 -10
  20. package/docs/ROADMAP.md +71 -44
  21. package/docs/USER_GUIDE.md +82 -58
  22. package/package.json +1 -1
  23. package/registry/baseline/0.4.1/project/.claude/commands/plan.md +2 -0
  24. package/registry/baseline/0.4.1/project/.claude/rules/maestro.md +35 -0
  25. package/registry/baseline/0.4.1/project/maestro/inbox/README.md +16 -0
  26. package/registry/baseline/0.4.1/project/maestro/runbooks/cowork-discovery.md +30 -0
  27. package/registry/baseline/0.4.1/project/protocols/discovery.md +5 -0
  28. package/registry/baseline/0.4.1/project/protocols/plan.md +142 -0
  29. package/registry/capabilities.v1.json +13 -1
  30. package/templates/project/.claude/commands/plan.md +1 -0
  31. package/templates/project/.claude/commands/start.md +2 -0
  32. package/templates/project/.claude/rules/maestro.md +5 -3
  33. package/templates/project/.claude/rules/project.md +6 -0
  34. package/templates/project/.claude/settings.json +2 -0
  35. package/templates/project/README.md +11 -0
  36. package/templates/project/maestro/inbox/README.md +6 -6
  37. package/templates/project/maestro/runbooks/cowork-discovery.md +1 -1
  38. package/templates/project/protocols/discovery.md +1 -3
  39. package/templates/project/protocols/plan.md +14 -7
  40. package/templates/project/protocols/start.md +64 -0
  41. package/templates/project/wiki/concepts/discovery.md +30 -11
  42. package/templates/project/wiki/hot.md +2 -2
  43. package/templates/project/wiki/index.md +1 -0
  44. package/templates/project/wiki/passport.md +2 -0
  45. package/templates/project/wiki/plans/0001-starter.md +4 -3
  46. package/templates/project/wiki/restore.md +32 -0
@@ -0,0 +1,107 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { promisify } from 'node:util';
3
+ const execFileAsync = promisify(execFile);
4
+ /** Ответ на проверку входа не должен задерживать мастер дольше этого. */
5
+ export const GH_DETECT_TIMEOUT_MS = 3_000;
6
+ /** Создание репозитория и первая отправка идут по сети. */
7
+ export const GH_CREATE_TIMEOUT_MS = 120_000;
8
+ export const defaultGhRunner = (args, options) => new Promise((resolve) => {
9
+ const child = execFile('gh', [...args], {
10
+ cwd: options.cwd,
11
+ timeout: options.timeoutMs,
12
+ encoding: 'utf8',
13
+ windowsHide: true,
14
+ // gh не задаёт вопросов и не проверяет обновления: ответить ему некому.
15
+ // git внутри gh тоже не спрашивает логин в терминале: лучше быстрый понятный сбой, чем зависание.
16
+ env: { ...process.env, GH_PROMPT_DISABLED: '1', GH_NO_UPDATE_NOTIFIER: '1', NO_COLOR: '1', GIT_TERMINAL_PROMPT: '0' },
17
+ }, (error, stdout, stderr) => {
18
+ if (error === null) {
19
+ resolve({ code: 0, stdout, stderr });
20
+ return;
21
+ }
22
+ const cause = error;
23
+ if (cause.code === 'ENOENT')
24
+ resolve({ code: null, stdout, stderr, failure: 'missing' });
25
+ else if (cause.killed === true)
26
+ resolve({ code: null, stdout, stderr, failure: 'timeout' });
27
+ else
28
+ resolve({ code: typeof cause.code === 'number' ? cause.code : 1, stdout, stderr });
29
+ });
30
+ child.stdin?.end();
31
+ });
32
+ /** Есть ли `gh` и выполнен ли в нём вход на github.com. Нет ответа за отведённое время — «нет». */
33
+ export async function githubReady(runner = defaultGhRunner, timeoutMs = GH_DETECT_TIMEOUT_MS) {
34
+ try {
35
+ const result = await runner(['auth', 'status', '--hostname', 'github.com'], { timeoutMs });
36
+ return result.code === 0;
37
+ }
38
+ catch {
39
+ return false;
40
+ }
41
+ }
42
+ const TRANSLIT = {
43
+ а: 'a', б: 'b', в: 'v', г: 'g', д: 'd', е: 'e', ё: 'e', ж: 'zh', з: 'z', и: 'i', й: 'y', к: 'k', л: 'l', м: 'm',
44
+ н: 'n', о: 'o', п: 'p', р: 'r', с: 's', т: 't', у: 'u', ф: 'f', х: 'kh', ц: 'ts', ч: 'ch', ш: 'sh', щ: 'shch',
45
+ ъ: '', ы: 'y', ь: '', э: 'e', ю: 'yu', я: 'ya', і: 'i', ї: 'yi', є: 'ye', ґ: 'g',
46
+ };
47
+ function transliterate(text) {
48
+ let out = '';
49
+ for (const char of text.normalize('NFC')) {
50
+ const lower = char.toLowerCase();
51
+ const latin = TRANSLIT[lower];
52
+ if (latin === undefined) {
53
+ out += char;
54
+ continue;
55
+ }
56
+ out += char !== lower && latin !== '' ? latin[0].toUpperCase() + latin.slice(1) : latin;
57
+ }
58
+ return out;
59
+ }
60
+ /**
61
+ * Имя репозитория — латиницей из названия папки: кириллица транслитерируется,
62
+ * остальное, кроме букв, цифр, `.`, `_` и `-`, становится дефисом. Пустое имя —
63
+ * `project-ГГГГММДД`.
64
+ */
65
+ export function githubRepoName(folderName, now = new Date()) {
66
+ const name = transliterate(folderName)
67
+ .normalize('NFD').replace(/\p{Mark}/gu, '')
68
+ .replace(/[^A-Za-z0-9._-]+/g, '-')
69
+ .replace(/-{2,}/g, '-')
70
+ .replace(/^[-.]+|[-.]+$/g, '')
71
+ .slice(0, 100)
72
+ .replace(/[-.]+$/g, '');
73
+ return name === '' ? `project-${now.toISOString().slice(0, 10).replace(/-/g, '')}` : name;
74
+ }
75
+ /** Адрес копии для показа: логин и пароль (токен), вшитые в адрес, не печатаются никогда. */
76
+ export function displayRemoteUrl(url) {
77
+ return url.replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/@]*@/i, '$1');
78
+ }
79
+ /** Команда, которой человек заведёт копию сам, из папки проекта. */
80
+ export function githubCreateCommand(name) {
81
+ return `gh repo create ${name} --private --source . --remote origin --push`;
82
+ }
83
+ function firstLine(text) {
84
+ return text.split(/\r?\n/).map((line) => line.trim()).find((line) => line !== '') ?? '';
85
+ }
86
+ /** `gh repo create <имя> --private --source <папка> --remote origin --push` после первого коммита. */
87
+ export async function createGithubCopy(projectRoot, name, runner = defaultGhRunner, timeoutMs = GH_CREATE_TIMEOUT_MS) {
88
+ let result;
89
+ try {
90
+ result = await runner(['repo', 'create', name, '--private', '--source', projectRoot, '--remote', 'origin', '--push'], { cwd: projectRoot, timeoutMs });
91
+ }
92
+ catch (cause) {
93
+ return { ok: false, reason: cause instanceof Error ? cause.message : String(cause) };
94
+ }
95
+ if (result.failure === 'missing')
96
+ return { ok: false, reason: 'не найдена программа GitHub CLI (gh)' };
97
+ if (result.failure === 'timeout')
98
+ return { ok: false, reason: `gh не ответил за ${Math.round(timeoutMs / 1000)} с` };
99
+ if (result.code !== 0)
100
+ return { ok: false, reason: firstLine(result.stderr) || firstLine(result.stdout) || `gh завершился с кодом ${result.code}` };
101
+ const url = /https:\/\/github\.com\/[^\s'"]+/.exec(`${result.stdout}\n${result.stderr}`)?.[0];
102
+ if (url !== undefined)
103
+ return { ok: true, url };
104
+ // gh не напечатал адрес — берём тот, что он записал в remote.
105
+ const remote = await execFileAsync('git', ['remote', 'get-url', 'origin'], { cwd: projectRoot, encoding: 'utf8' }).catch(() => null);
106
+ return { ok: true, url: displayRemoteUrl(remote?.stdout.trim() || name) };
107
+ }
package/dist/core/init.js CHANGED
@@ -13,14 +13,26 @@ import { renderTemplate } from './template.js';
13
13
  import { recoverTemplateVars, templateUses } from './template-recover.js';
14
14
  import { canonicalOwnershipInventory, CONTENT_OWNED_FILES, lazyDirsForDepth, TEMPLATE_FILES } from './inventory.js';
15
15
  import { canonicalizeSystemTempPrefix, onDiskBasename } from './platform-paths.js';
16
+ import { hasAnyReadme, README_PATH } from './readme.js';
17
+ import { SETTINGS_PATH, withPushWithoutAsking } from './settings.js';
16
18
  import { compareVersions } from './version.js';
17
19
  const execFileAsync = promisify(execFile);
18
20
  const GITIGNORE_PATH = '.gitignore';
19
21
  /** Служебный мусор ОС и сам Git не делают папку «занятой чужими файлами». */
20
22
  const IGNORED_WHEN_EMPTY_CHECK = ['.git', '.DS_Store'];
21
23
  /** Шаблон .gitattributes: фиксирует LF для текстовых файлов проекта. */
22
- const GITATTRIBUTES_PATH = '.gitattributes';
23
24
  export const GITATTRIBUTES_CONTENT = '* text=auto eol=lf\n*.md text eol=lf\n*.json text eol=lf\n*.yml text eol=lf\n*.yaml text eol=lf\n';
25
+ /**
26
+ * Материалы человека git хранит байт в байт: `-text` во вложенном `.gitattributes`
27
+ * перекрывает корневые правила, и свежий клон отдаёт исходные переносы строк.
28
+ * Отдельный файл, а не строка в корневом: корневой проект мог дописать, и тогда upgrade встал бы.
29
+ */
30
+ export const INBOX_GITATTRIBUTES_CONTENT = '* -text\n';
31
+ /** Managed-файлы, содержимое которых задаёт код, а не шаблон: без подстановок, побайтово. */
32
+ export const CODE_MANAGED_SOURCES = {
33
+ '.gitattributes': GITATTRIBUTES_CONTENT,
34
+ 'maestro/inbox/.gitattributes': INBOX_GITATTRIBUTES_CONTENT,
35
+ };
24
36
  function failure(target, projectName, error) {
25
37
  return {
26
38
  ok: false,
@@ -114,7 +126,7 @@ async function findAncestorSymlink(target) {
114
126
  async function recoverProjectVars(target, startingPoint, checksums) {
115
127
  const found = {};
116
128
  for (const relativePath of TEMPLATE_FILES) {
117
- if (relativePath === GITATTRIBUTES_PATH || checksums[relativePath] === undefined)
129
+ if (relativePath in CODE_MANAGED_SOURCES || checksums[relativePath] === undefined)
118
130
  continue;
119
131
  // Шаблоны пакета на Windows могут прийти с CRLF, а файлы проекта всегда пишутся с LF.
120
132
  const source = normalizeEol(await readTemplate(relativePath));
@@ -170,7 +182,7 @@ async function initGitRepository(target, ownedPaths, warnings, writtenPaths) {
170
182
  const shown = writtenPaths.slice(0, 5).map((path) => quotePathArg(path)).join(' ');
171
183
  warnings.push(`Репозиторий Git уже существовал: index не изменён и commit не создан. Добавьте записанные файлы сами: git add ${shown}${writtenPaths.length > 5 ? ' …' : ''}`);
172
184
  }
173
- return;
185
+ return false;
174
186
  }
175
187
  // Только наши пути в новом репозитории. Пакетами, чтобы не упереться в лимит длины командной строки.
176
188
  const toAdd = [...ownedPaths].sort();
@@ -180,10 +192,12 @@ async function initGitRepository(target, ownedPaths, warnings, writtenPaths) {
180
192
  await execFileAsync('git', ['commit', '-m', 'Инициализация проекта Vibe Coding Maestro'], {
181
193
  cwd: target,
182
194
  });
195
+ return true;
183
196
  }
184
197
  catch (error) {
185
198
  const message = error instanceof Error ? error.message : String(error);
186
199
  warnings.push(`Git-шаги пропущены: ${message}`);
200
+ return false;
187
201
  }
188
202
  }
189
203
  /**
@@ -297,6 +311,9 @@ async function initProjectAt(target, options, progress) {
297
311
  if (isExistingProject && options.requested?.startingPoint !== undefined && options.requested.startingPoint !== startingPoint) {
298
312
  warnings.push(`У проекта исходная точка ${startingPoint}; --start ${options.requested.startingPoint} не применён: create не меняет параметры готового проекта.`);
299
313
  }
314
+ if (isExistingProject && options.pushWithoutAsking === true) {
315
+ warnings.push('--push-without-asking не применён: create не меняет готовый проект, а `.claude/settings.json` принадлежит проекту. Настройку предложит `/start` — только с вашего «да».');
316
+ }
300
317
  const previousChecksums = (await loadChecksums(target))?.files ?? {};
301
318
  const nextChecksums = {};
302
319
  const managed = [];
@@ -369,15 +386,16 @@ async function initProjectAt(target, options, progress) {
369
386
  ownedPaths.push(relativePath);
370
387
  }
371
388
  for (const relativePath of TEMPLATE_FILES) {
372
- const source = relativePath === GITATTRIBUTES_PATH ? GITATTRIBUTES_CONTENT : await readTemplate(relativePath);
373
- await materialize(relativePath, relativePath === GITATTRIBUTES_PATH ? source : renderTemplate(source, vars));
389
+ const constant = CODE_MANAGED_SOURCES[relativePath];
390
+ await materialize(relativePath, constant ?? renderTemplate(await readTemplate(relativePath), vars));
374
391
  }
375
392
  for (const relativePath of CONTENT_OWNED_FILES) {
376
393
  managed.push({ path: relativePath, kind: 'generated' });
377
394
  const absolutePath = join(target, relativePath);
378
395
  if (!existsSync(absolutePath)) {
379
- const source = await readTemplate(relativePath);
380
- await writeTextFile(absolutePath, renderTemplate(source, vars));
396
+ const rendered = renderTemplate(await readTemplate(relativePath), vars);
397
+ const pushRecipe = relativePath === SETTINGS_PATH && options.pushWithoutAsking === true && !isExistingProject;
398
+ await writeTextFile(absolutePath, pushRecipe ? withPushWithoutAsking(rendered) : rendered);
381
399
  createdFiles.push(relativePath);
382
400
  ownedPaths.push(relativePath);
383
401
  }
@@ -385,6 +403,13 @@ async function initProjectAt(target, options, progress) {
385
403
  preservedFiles.push(relativePath);
386
404
  }
387
405
  }
406
+ // README — только в новый проект и только если в корне нет никакого README: удалённый
407
+ // человеком README повторный create не возвращает, а doctor его не требует.
408
+ if (!isExistingProject && !(await hasAnyReadme(target))) {
409
+ await writeTextFile(join(target, README_PATH), renderTemplate(await readTemplate(README_PATH), vars));
410
+ createdFiles.push(README_PATH);
411
+ ownedPaths.push(README_PATH);
412
+ }
388
413
  for (const dir of lazyDirs) {
389
414
  await mkdir(join(target, dir), { recursive: true });
390
415
  await materialize(`${dir}/.gitkeep`, '');
@@ -425,9 +450,9 @@ async function initProjectAt(target, options, progress) {
425
450
  });
426
451
  await writeManifest(target, manifest);
427
452
  await writeChecksums(target, nextChecksums);
428
- if (options.git === true) {
429
- await initGitRepository(target, ownedPaths, warnings, [...createdFiles, ...mergedFiles]);
430
- }
453
+ const gitCreated = options.git === true
454
+ ? await initGitRepository(target, ownedPaths, warnings, [...createdFiles, ...mergedFiles])
455
+ : false;
431
456
  // Метка снимается последней: убитый на любом шаге, включая Git, create остаётся виден.
432
457
  if (!isExistingProject)
433
458
  await rm(join(target, CREATING_MARKER_PATH), { force: true });
@@ -439,5 +464,7 @@ async function initProjectAt(target, options, progress) {
439
464
  preservedFiles,
440
465
  mergedFiles,
441
466
  warnings,
467
+ existingProject: isExistingProject,
468
+ gitCreated,
442
469
  };
443
470
  }
@@ -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,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
  ];
@@ -287,6 +287,44 @@ const v040Copy = (path) => ({
287
287
  source: `registry/baseline/0.4.0/project/${path}`,
288
288
  sha256: V040_MANAGED_SHA256[path],
289
289
  });
290
+ /** Слепок `templates/project` 0.4.1: тот же состав файлов; правила и протоколы зовут `context` и `pack`. */
291
+ const V041_MANAGED_SHA256 = {
292
+ ...V040_MANAGED_SHA256,
293
+ '.claude/rules/maestro.md': '490eed80098f853068d208ced54391d71c1de740e1fbd8199f54d98f9831216e',
294
+ 'protocols/handoff.md': '10b1a9d21ce40eef441eaf545024cb246b6dda9ae84bfdd4226891aedb253044',
295
+ 'protocols/completion.md': 'fe500e828bf1fc5e73745815cd019af455180f94aba06f13c2b02dfcad61cbfd',
296
+ };
297
+ /** Копии шаблонов 0.4.1, изменённых в 0.4.2; одна копия служит всем версиям с тем же содержимым. */
298
+ const v041Copy = (path) => ({
299
+ path,
300
+ source: `registry/baseline/0.4.1/project/${path}`,
301
+ sha256: V041_MANAGED_SHA256[path],
302
+ });
303
+ /** Файлы, которые 0.4.2 изменил: со времён 0.3 beta (а discovery, inbox и runbook — с 0.2) они не менялись. */
304
+ export const CHANGED_IN_042_SAME_SINCE_BETA1 = [
305
+ '.claude/commands/plan.md',
306
+ 'maestro/inbox/README.md',
307
+ 'maestro/runbooks/cowork-discovery.md',
308
+ 'protocols/discovery.md',
309
+ ];
310
+ /** Файлы, которые 0.4.2 изменил: в 0.3.0 — 0.4.1 они одинаковы. */
311
+ const CHANGED_IN_042_SAME_SINCE_030 = ['protocols/plan.md'];
312
+ /** Канон 0.4.2: старт проекта — протокол и команда, материалы байт в байт (Maestro); страница восстановления (проект). */
313
+ const V042_TEMPLATE_FILES = [...V040_TEMPLATE_FILES, '.claude/commands/start.md', 'protocols/start.md', 'maestro/inbox/.gitattributes'];
314
+ const V042_CONTENT_OWNED_FILES = [...V040_CONTENT_OWNED_FILES, 'wiki/restore.md'];
315
+ /** Слепок `templates/project` 0.4.2. */
316
+ const V042_MANAGED_SHA256 = {
317
+ ...V041_MANAGED_SHA256,
318
+ '.claude/commands/plan.md': '4ddbab1b68f68e967904b959db61355153c7d7877981ee47a9917f02c9e6e84c',
319
+ '.claude/commands/start.md': '44e1321e7ed557d96540835b882d549c523aa834da5c396318605f5aec9794b2',
320
+ '.claude/rules/maestro.md': '29e768f5c0d3f7b54bc4340ae19c0de720b75794619f8bd68a5766d70324ed62',
321
+ 'maestro/inbox/.gitattributes': '705fd4d6451a31d36b3df7de96f83f30ac976c9b4a6d1e51671d8e2f33e2d0da',
322
+ 'maestro/inbox/README.md': '2fbd307347c2504ba7ce369e87ffa224aa630e1d7bf364ab666839a5bb7a4abd',
323
+ 'maestro/runbooks/cowork-discovery.md': 'a0b092f87e7a1749f6dda76a9e2cb2de4228cd9d5bcf27f3f89b79e34e3b6bc0',
324
+ 'protocols/discovery.md': '2c120e5bb2f118f9749fbe72eecb6ecd93635eddb84e3ce22b9f0de7bbc43374',
325
+ 'protocols/plan.md': '43cd0f436b5baa3e9f2642719c27b2fd42972e5677897f0bb360a4ad0c984ffc',
326
+ 'protocols/start.md': '567024859e702424348fb5e4e72c1d09895e34f2d7e25ee2ccf7139369cdb022',
327
+ };
290
328
  export const RELEASES = [
291
329
  {
292
330
  id: BASELINE_ID,
@@ -304,6 +342,7 @@ export const RELEASES = [
304
342
  templates: [
305
343
  ...['CLAUDE.md', 'AGENTS.md', '.claude/commands/build.md', 'protocols/build.md', 'protocols/plan.md'].map(v03BetaCopy),
306
344
  ...CHANGED_IN_030_SAME_SINCE_BETA1.map(v03Beta4Copy),
345
+ ...CHANGED_IN_042_SAME_SINCE_BETA1.map(v041Copy),
307
346
  ],
308
347
  },
309
348
  {
@@ -311,7 +350,10 @@ export const RELEASES = [
311
350
  versions: ['0.3.0-beta.4'],
312
351
  inventory: v03OwnershipInventory,
313
352
  managedSha256: V03_BETA4_MANAGED_SHA256,
314
- templates: ['CLAUDE.md', 'AGENTS.md', 'protocols/build.md', 'protocols/plan.md', ...CHANGED_IN_030_SAME_SINCE_BETA1].map(v03Beta4Copy),
353
+ templates: [
354
+ ...['CLAUDE.md', 'AGENTS.md', 'protocols/build.md', 'protocols/plan.md', ...CHANGED_IN_030_SAME_SINCE_BETA1].map(v03Beta4Copy),
355
+ ...CHANGED_IN_042_SAME_SINCE_BETA1.map(v041Copy),
356
+ ],
315
357
  },
316
358
  {
317
359
  id: '0.3.0',
@@ -325,6 +367,7 @@ export const RELEASES = [
325
367
  sha256: V030_MANAGED_SHA256['.claude/rules/maestro.md'],
326
368
  },
327
369
  ...CHANGED_IN_040_SAME_SINCE_030.map(v031Copy),
370
+ ...[...CHANGED_IN_042_SAME_SINCE_BETA1, ...CHANGED_IN_042_SAME_SINCE_030].map(v041Copy),
328
371
  ],
329
372
  },
330
373
  {
@@ -332,26 +375,33 @@ export const RELEASES = [
332
375
  versions: ['0.3.1'],
333
376
  inventory: v030OwnershipInventory,
334
377
  managedSha256: V031_MANAGED_SHA256,
335
- templates: ['.claude/rules/maestro.md', ...CHANGED_IN_040_SAME_SINCE_030].map(v031Copy),
378
+ templates: [
379
+ ...['.claude/rules/maestro.md', ...CHANGED_IN_040_SAME_SINCE_030].map(v031Copy),
380
+ ...[...CHANGED_IN_042_SAME_SINCE_BETA1, ...CHANGED_IN_042_SAME_SINCE_030].map(v041Copy),
381
+ ],
336
382
  },
337
383
  {
338
384
  id: '0.4.0',
339
385
  versions: ['0.4.0'],
340
386
  inventory: v040OwnershipInventory,
341
387
  managedSha256: V040_MANAGED_SHA256,
342
- templates: ['.claude/rules/maestro.md', 'protocols/completion.md', 'protocols/handoff.md'].map(v040Copy),
388
+ templates: [
389
+ ...['.claude/rules/maestro.md', 'protocols/completion.md', 'protocols/handoff.md'].map(v040Copy),
390
+ ...[...CHANGED_IN_042_SAME_SINCE_BETA1, ...CHANGED_IN_042_SAME_SINCE_030].map(v041Copy),
391
+ ],
343
392
  },
344
393
  {
345
- // 0.4.1: тот же состав файлов; правила и протоколы зовут `context` и `pack`.
346
394
  id: '0.4.1',
347
395
  versions: ['0.4.1'],
348
396
  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
- },
397
+ managedSha256: V041_MANAGED_SHA256,
398
+ templates: ['.claude/rules/maestro.md', ...CHANGED_IN_042_SAME_SINCE_BETA1, ...CHANGED_IN_042_SAME_SINCE_030].map(v041Copy),
399
+ },
400
+ {
401
+ id: '0.4.2',
402
+ versions: ['0.4.2'],
403
+ inventory: ownershipInventory(V042_TEMPLATE_FILES, V042_CONTENT_OWNED_FILES),
404
+ managedSha256: V042_MANAGED_SHA256,
355
405
  templates: [],
356
406
  },
357
407
  ];