create-vibe-maestro 0.4.1 → 0.4.3

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 (93) hide show
  1. package/CHANGELOG.md +90 -0
  2. package/README.md +37 -34
  3. package/dist/cli/context-run.js +10 -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 +25 -2
  8. package/dist/cli/pack-run.js +42 -3
  9. package/dist/cli/prompt.js +12 -4
  10. package/dist/cli/renderer.js +5 -4
  11. package/dist/cli/upgrade-run.js +48 -5
  12. package/dist/core/context.js +47 -2
  13. package/dist/core/doctor/git.js +41 -1
  14. package/dist/core/doctor/inbox.js +5 -11
  15. package/dist/core/doctor/index.js +1 -1
  16. package/dist/core/doctor/plans.js +3 -3
  17. package/dist/core/doctor/sources.js +1 -1
  18. package/dist/core/github.js +107 -0
  19. package/dist/core/gitignore.js +3 -1
  20. package/dist/core/init.js +37 -10
  21. package/dist/core/inventory.js +6 -10
  22. package/dist/core/pack.js +130 -12
  23. package/dist/core/plan.js +21 -2
  24. package/dist/core/preflight.js +6 -5
  25. package/dist/core/readme.js +21 -0
  26. package/dist/core/settings.js +39 -0
  27. package/dist/core/template.js +2 -1
  28. package/dist/core/text-diff.js +108 -0
  29. package/dist/core/upgrade/analyze.js +131 -12
  30. package/dist/core/upgrade/baseline.js +14 -0
  31. package/dist/core/upgrade/index.js +53 -10
  32. package/dist/core/upgrade/releases.js +152 -11
  33. package/docs/ROADMAP.md +75 -44
  34. package/docs/USER_GUIDE.md +142 -79
  35. package/package.json +1 -1
  36. package/registry/baseline/0.4.1/project/.claude/commands/plan.md +2 -0
  37. package/registry/baseline/0.4.1/project/.claude/rules/maestro.md +35 -0
  38. package/registry/baseline/0.4.1/project/maestro/inbox/README.md +16 -0
  39. package/registry/baseline/0.4.1/project/maestro/runbooks/cowork-discovery.md +30 -0
  40. package/registry/baseline/0.4.1/project/protocols/plan.md +142 -0
  41. package/registry/baseline/0.4.2/project/.claude/agents/code-reviewer.md +13 -0
  42. package/registry/baseline/0.4.2/project/.claude/rules/maestro.md +37 -0
  43. package/registry/baseline/0.4.2/project/maestro/runbooks/cowork-audit.md +11 -0
  44. package/registry/baseline/0.4.2/project/maestro/templates/handoff.md +25 -0
  45. package/registry/baseline/0.4.2/project/protocols/audit.md +5 -0
  46. package/registry/baseline/0.4.2/project/protocols/build.md +18 -0
  47. package/registry/baseline/0.4.2/project/protocols/completion.md +22 -0
  48. package/registry/baseline/0.4.2/project/protocols/discovery.md +3 -0
  49. package/registry/baseline/0.4.2/project/protocols/handoff.md +15 -0
  50. package/registry/baseline/0.4.2/project/protocols/plan.md +149 -0
  51. package/registry/baseline/0.4.2/project/protocols/start.md +64 -0
  52. package/registry/baseline/0.4.2/project/protocols/wiki.md +9 -0
  53. package/registry/baseline/0.4.2/project/wiki/plans/README.md +131 -0
  54. package/registry/baseline/0.4.2/project/wiki/plans/TEMPLATE.md +75 -0
  55. package/registry/capabilities.v1.json +32 -20
  56. package/templates/project/.claude/agents/code-reviewer.md +18 -7
  57. package/templates/project/.claude/commands/plan.md +1 -0
  58. package/templates/project/.claude/commands/start.md +2 -0
  59. package/templates/project/.claude/rules/maestro.md +10 -5
  60. package/templates/project/.claude/rules/project.md +6 -0
  61. package/templates/project/.claude/settings.json +3 -0
  62. package/templates/project/README.md +11 -0
  63. package/templates/project/maestro/inbox/README.md +6 -6
  64. package/templates/project/maestro/runbooks/cowork-audit.md +9 -2
  65. package/templates/project/maestro/runbooks/cowork-discovery.md +1 -1
  66. package/templates/project/maestro/templates/audit.md +31 -0
  67. package/templates/project/maestro/templates/handoff.md +5 -1
  68. package/templates/project/protocols/audit.md +70 -1
  69. package/templates/project/protocols/build.md +111 -9
  70. package/templates/project/protocols/completion.md +8 -7
  71. package/templates/project/protocols/handoff.md +3 -1
  72. package/templates/project/protocols/plan.md +45 -28
  73. package/templates/project/protocols/start.md +64 -0
  74. package/templates/project/protocols/wiki.md +10 -2
  75. package/templates/project/wiki/concepts/discovery.md +30 -11
  76. package/templates/project/wiki/hot.md +2 -2
  77. package/templates/project/wiki/icebox.md +12 -0
  78. package/templates/project/wiki/index.md +2 -0
  79. package/templates/project/wiki/passport.md +3 -1
  80. package/templates/project/wiki/plans/0001-starter.md +16 -4
  81. package/templates/project/wiki/plans/README.md +7 -3
  82. package/templates/project/wiki/plans/TEMPLATE.md +13 -5
  83. package/templates/project/wiki/restore.md +32 -0
  84. /package/{templates → registry/baseline/0.4.1}/project/protocols/discovery.md +0 -0
  85. /package/{templates → registry/baseline/0.4.2}/project/protocols/build/audit-phase.md +0 -0
  86. /package/{templates → registry/baseline/0.4.2}/project/protocols/build/audit-plan.md +0 -0
  87. /package/{templates → registry/baseline/0.4.2}/project/protocols/build/step-1-rules.md +0 -0
  88. /package/{templates → registry/baseline/0.4.2}/project/protocols/build/step-2-spec.md +0 -0
  89. /package/{templates → registry/baseline/0.4.2}/project/protocols/build/step-3-architecture.md +0 -0
  90. /package/{templates → registry/baseline/0.4.2}/project/protocols/build/step-5-feature-loop.md +0 -0
  91. /package/{templates → registry/baseline/0.4.2}/project/protocols/context-budget.md +0 -0
  92. /package/{templates → registry/baseline/0.4.2}/project/protocols/lessons.md +0 -0
  93. /package/{templates → registry/baseline/0.4.2}/project/protocols/seams.md +0 -0
@@ -1,9 +1,18 @@
1
1
  import { existsSync } from 'node:fs';
2
2
  import { dirname, join, resolve } from 'node:path';
3
+ import { quotePathArg, serviceInvocation, VERSION } from '../core/meta.js';
3
4
  import { defaultArchiveName, packProject } from '../core/pack.js';
4
5
  import { resolveDesktopDirectory } from './desktop.js';
5
6
  import { homedir } from 'node:os';
6
7
  import { EXIT_FAILED, EXIT_OK } from './io.js';
8
+ /** `--out dist/` или `--out dist\` — папка: архив ложится в неё под именем по умолчанию, папка создаётся. */
9
+ function outPath(out, root, tag) {
10
+ if (!/[\\/]$/.test(out))
11
+ return resolve(out);
12
+ return join(resolve(out.replace(/[\\/]+$/, '') || out), defaultArchiveName(root, tag));
13
+ }
14
+ /** Строка подсветки: путь, что найдено и где. */
15
+ const highlightLine = (item) => `${item.path} — ${item.reason}${item.line === undefined ? '' : ` (строка ${item.line})`}`;
7
16
  /** Архив по умолчанию кладётся на Рабочий стол: его оттуда отправляют заказчику. Нет Рабочего стола — рядом с проектом. */
8
17
  async function defaultOut(root, tag) {
9
18
  const name = defaultArchiveName(root, tag);
@@ -18,8 +27,8 @@ async function defaultOut(root, tag) {
18
27
  return join(dirname(resolve(root)), name);
19
28
  }
20
29
  export async function executePackCommand(options, io) {
21
- const out = options.out === undefined ? await defaultOut(options.path, options.tag) : resolve(options.out);
22
- const result = await packProject({ root: options.path, tag: options.tag, out, allow: options.allow ?? [] });
30
+ const out = options.out === undefined ? await defaultOut(options.path, options.tag) : outPath(options.out, options.path, options.tag);
31
+ const result = await packProject({ root: options.path, tag: options.tag, out, allow: options.allow ?? [], dryRun: options.dryRun === true });
23
32
  if (options.json) {
24
33
  io.out(JSON.stringify({ reportVersion: 1, ...result }, null, 2));
25
34
  return result.ok ? EXIT_OK : EXIT_FAILED;
@@ -30,11 +39,41 @@ export async function executePackCommand(options, io) {
30
39
  io.err(`- ${item.code}${item.path ? ` (${item.path})` : ''}: ${item.message}`);
31
40
  return EXIT_FAILED;
32
41
  }
42
+ const highlights = result.highlights ?? [];
43
+ if (result.dryRun === true) {
44
+ const marks = new Map();
45
+ for (const item of highlights)
46
+ marks.set(item.path, [...(marks.get(item.path) ?? []), `${item.reason}${item.line === undefined ? '' : ` (строка ${item.line})`}`]);
47
+ io.out(result.untagged === true
48
+ ? `Метки ${result.tag} ещё нет: показан состав последнего коммита (${(result.commit ?? '').slice(0, 7)}), ничего не записано; файлов — ${result.files}. Метку ставят на этот коммит — архив будет таким же; незакоммиченное в архив не попадёт.`
49
+ : `Состав архива тега ${result.tag} (ничего не записано): файлов — ${result.files}.`);
50
+ for (const path of result.entries ?? [])
51
+ io.out(` ${path}${marks.has(path) ? ` ← ${(marks.get(path) ?? []).join('; ')}` : ''}`);
52
+ for (const note of result.notes ?? [])
53
+ io.out(note);
54
+ const toCheck = highlights.filter((item) => !item.reason.includes('оставьте')).length;
55
+ io.out(toCheck === 0
56
+ ? `Убирать нечего${highlights.length > 0 ? ': подсвечены только файлы с пометкой «оставьте»' : ''}.`
57
+ : `Подсвечено к проверке — ${toCheck}: внутреннее уберите до упаковки (правка, коммит${result.untagged === true ? '' : ', новый тег'}); помеченное «оставьте» не трогайте. Подсветка — предупреждение, упаковку она не запрещает.`);
58
+ io.out(result.noAccess === true
59
+ ? 'HANDOVER.md: доступов не было — в паспорте все разделы о доступах «не применимо», менять заказчику нечего.'
60
+ : 'HANDOVER.md: первым делом заказчик меняет все пароли и ключи — в разделах паспорта о доступах есть записи. «Доступов не было» пишется, только если в каждом из них ровно «не применимо», без пояснений.');
61
+ const packCommand = `${serviceInvocation(VERSION)} pack --path ${quotePathArg(options.path)} --tag ${options.tag}${options.out === undefined ? '' : ` --out ${quotePathArg(options.out)}`}`;
62
+ io.out(result.untagged === true
63
+ ? `Дальше: имя метки ${options.tag} — в паспорт, коммит; метка (git tag -a ${options.tag}) — после «да» человека; затем упаковать: ${packCommand} — тоже после «да».`
64
+ : `Упаковать: ${packCommand} — только после «да» человека.`);
65
+ return EXIT_OK;
66
+ }
33
67
  io.out(result.reused === true
34
68
  ? `Архив тега ${result.tag} уже лежит здесь и совпадает побайтово: ${result.archive}`
35
69
  : `Архив тега ${result.tag} готов: ${result.archive}`);
36
70
  io.out(`Файлов: ${result.files}, размер: ${result.bytes} байт, sha256: ${result.sha256}`);
37
- io.out('Не вошли: wiki/, maestro/, .claude/, protocols/, .maestro/, CLAUDE.md, AGENTS.md, .mcp.json. В корне архива — HANDOVER.md: первым делом заказчик меняет все пароли и ключи.');
71
+ io.out(`Не вошли: wiki/, maestro/, .claude/, protocols/, .maestro/, CLAUDE.md, AGENTS.md, .mcp.json. В корне архива — HANDOVER.md: ${result.noAccess === true ? 'доступов не было, менять заказчику нечего' : 'первым делом заказчик меняет все пароли и ключи'}.`);
72
+ if (highlights.length > 0) {
73
+ io.out(`Подсвечено — проверьте перед отправкой (предупреждение, не отказ):`);
74
+ for (const item of highlights)
75
+ io.out(` ${highlightLine(item)}`);
76
+ }
38
77
  for (const note of result.notes ?? [])
39
78
  io.out(note);
40
79
  if ((options.allow ?? []).length > 0)
@@ -1,4 +1,5 @@
1
1
  import { createInterface } from 'node:readline';
2
+ import { githubReady } from '../core/github.js';
2
3
  import { resolveProjectInput, runtimeDesktopOptions } from './desktop.js';
3
4
  import { createRenderer, runtimeRendererOptions } from './renderer.js';
4
5
  /** Минимальная ширина, при которой перерисовка меню по фиксированному числу строк безопасна. */
@@ -226,17 +227,24 @@ export async function askLine(input, output, renderer, question, hint, capabilit
226
227
  restoreListeners(input, listenersBefore);
227
228
  }
228
229
  }
229
- export function createReadlinePrompt(input = process.stdin, output = process.stdout) {
230
+ export function createReadlinePrompt(input = process.stdin, output = process.stdout, options = {}) {
230
231
  const renderer = createRenderer((text) => output.write(text), runtimeRendererOptions(output));
231
232
  const capabilities = promptCapabilities(output, process.env);
232
233
  return {
233
234
  renderer,
234
235
  async ask() {
236
+ // Вход в gh проверяется, пока человек читает приветствие; нет ответа за 3 с — варианта нет.
237
+ const github = (options.detectGithub ?? (() => githubReady()))().catch(() => false);
235
238
  renderer.welcome();
236
- const action = await selectChoice(input, output, renderer, 'Что вы хотите сделать?', [
239
+ const choices = [
237
240
  { value: 'create', label: 'Создать новый проект' },
238
241
  { value: 'check', label: 'Проверить canonical project' },
239
- ], capabilities);
242
+ ];
243
+ // Новый вариант — последним: «1 — создать» и «2 — проверить» не меняются.
244
+ if (await github)
245
+ choices.push({ value: 'create-github', label: 'Создать новый проект и закрытую копию на GitHub' });
246
+ const chosen = await selectChoice(input, output, renderer, 'Что вы хотите сделать?', choices, capabilities);
247
+ const action = chosen === 'check' ? 'check' : 'create';
240
248
  const question = action === 'create' ? 'Как назовём проект? Можно указать полный путь.' : 'Какой canonical project проверить?';
241
249
  const hint = action === 'create' ? 'Например: Мой проект. Тогда папка появится на Рабочем столе.' : 'Перетащите папку сюда или вставьте путь.';
242
250
  const raw = await askLine(input, output, renderer, question, hint, capabilities);
@@ -254,7 +262,7 @@ export function createReadlinePrompt(input = process.stdin, output = process.std
254
262
  ], capabilities);
255
263
  renderer.preview({ action, target: project.target, name: project.name, usedDesktopDefault: project.usedDesktopDefault });
256
264
  renderer.progress('Создаём структуру canonical project…');
257
- return { action, target: project.target, name: project.name, startingPoint, usedDesktopDefault: project.usedDesktopDefault };
265
+ return { action, target: project.target, name: project.name, startingPoint, usedDesktopDefault: project.usedDesktopDefault, github: chosen === 'create-github' };
258
266
  },
259
267
  };
260
268
  }
@@ -124,12 +124,13 @@ export function createRenderer(write, options) {
124
124
  model.name ? `Название: ${model.name}` : '',
125
125
  'Проект находится здесь:',
126
126
  model.target,
127
+ model.cloud ? `Копия в облаке: ${model.cloud}` : 'Копии в облаке нет — завести её поможет /start.',
127
128
  '',
128
129
  'Что делать дальше:',
129
- '1. Откройте папку проекта.',
130
- '2. Добавьте заметки и файлы в maestro/inbox/.',
131
- '3. Начните с wiki/hot.md.',
132
- '4. Для discovery откройте maestro/runbooks/cowork-discovery.md.',
130
+ '1. Откройте папку проекта в Claude Code.',
131
+ '2. Материалы, если есть, положите в maestro/inbox/. Готовый код оставьте, где лежит: /start спросит путь.',
132
+ '3. Напишите /start — знакомство с задачей.',
133
+ '4. Потом /plan — план до кода.',
133
134
  '',
134
135
  'Проверка пройдена: структура проекта в порядке.',
135
136
  ].filter((line, index, all) => line !== '' || (index > 0 && all[index - 1] !== '')), 'success');
@@ -1,6 +1,19 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { join } from 'node:path';
1
3
  import { quotePathArg, serviceInvocation, VERSION } from '../core/meta.js';
2
- import { upgradeProject } from '../core/upgrade/index.js';
4
+ import { formatHunk } from '../core/text-diff.js';
5
+ import { upgradeDiffs, upgradeProject } from '../core/upgrade/index.js';
3
6
  import { EXIT_FAILED, EXIT_OK } from './io.js';
7
+ /** Сколько строк добавится и уберётся: «строк: +12 -5». */
8
+ function lineCounts({ added, removed }) {
9
+ const parts = [...(added > 0 ? [`+${added}`] : []), ...(removed > 0 ? [`-${removed}`] : [])];
10
+ return parts.length === 0 ? '' : ` (строк: ${parts.join(' ')})`;
11
+ }
12
+ const DIFF_TITLES = {
13
+ create: 'Будет добавлено',
14
+ update: 'Будет обновлено',
15
+ remove: 'Будет удалено',
16
+ };
4
17
  /**
5
18
  * Без `--apply` команда только показывает предложение: это dry-run по умолчанию,
6
19
  * а запись требует отдельного человеческого намерения.
@@ -42,25 +55,55 @@ export async function executeUpgradeCommand(options, io) {
42
55
  io.out(`Обновление применено: ${analysis.fromVersion ?? analysis.baselineId} → ${analysis.toVersion}.`);
43
56
  list('Добавлено', result.createdFiles);
44
57
  list('Обновлено', result.updatedFiles);
58
+ // Без Git удалённый текст остаётся только в пакете Maestro прошлой версии.
59
+ list(`Удалено (файлы Maestro, которых больше нет в составе; прежний текст — ${existsSync(join(analysis.root, '.git')) ? 'в истории Git' : 'в пакете Maestro прошлой версии'})`, result.removedFiles);
45
60
  list('Передано проекту (дальше файл ваш, Maestro его не проверяет и не перезаписывает)', analysis.handedOver);
46
61
  const keptAsIs = analysis.handedOver.filter((path) => !result.updatedFiles.includes(path));
47
62
  if (keptAsIs.length > 0)
48
63
  io.out(`Вы меняли эти файлы, поэтому они переданы как есть: ${keptAsIs.join(', ')}. Если в них осталась команда Maestro старой версии, обновите её — актуальная лежит в .claude/rules/maestro.md (doctor напомнит).`);
49
64
  list('Сохранено без изменений', analysis.preserves);
65
+ for (const note of analysis.notes)
66
+ io.out(`Важно: ${note}`);
50
67
  // До коммита doctor честно покажет git-managed-dirty: сначала diff и коммит, потом проверка.
51
- io.out('Добавьте в Git все изменения, включая новые файлы (git add -A), просмотрите их (git diff --cached) и закоммитьте: до коммита doctor покажет git-managed-dirty и git-managed-untracked.');
68
+ io.out('Добавьте в Git все изменения, включая новые и удалённые файлы (git add -A), просмотрите их (git diff --cached) и закоммитьте: до коммита doctor покажет git-managed-dirty и git-managed-untracked.');
52
69
  // Та же версия, что применила обновление: doctor проверяет ровно её канон.
53
70
  io.out(`Затем проверьте: ${serviceInvocation(VERSION)} doctor --path ${quotePathArg(options.path)} --strict`);
54
71
  return EXIT_OK;
55
72
  }
73
+ const diffs = await upgradeDiffs(result.plan);
74
+ const counted = new Map(diffs.map((item) => [item.path, lineCounts(item.diff)]));
75
+ const apply = `Применить: ${serviceInvocation(VERSION)} upgrade --path ${quotePathArg(options.path)} --apply`;
76
+ if (options.diff === true) {
77
+ io.out(`Предложение обновления ${analysis.fromVersion ?? analysis.baselineId} → ${analysis.toVersion} (ни один байт не записан). Правки построчно: «+» — строка добавится, «-» — уберётся.`);
78
+ for (const item of diffs) {
79
+ io.out('');
80
+ io.out(`=== ${DIFF_TITLES[item.action]}: ${item.path}${counted.get(item.path) ?? ''}`);
81
+ for (const hunk of item.diff.hunks)
82
+ for (const line of formatHunk(hunk))
83
+ io.out(line);
84
+ }
85
+ io.out('');
86
+ list('Перейдёт к проекту (дальше файл ваш, Maestro его не проверяет и не перезаписывает)', analysis.handedOver);
87
+ list('Служебные файлы (пересчитываются)', analysis.metadata);
88
+ for (const note of analysis.notes)
89
+ io.out(`Важно: ${note}`);
90
+ io.out(apply);
91
+ return EXIT_OK;
92
+ }
56
93
  io.out(`Предложение обновления ${analysis.fromVersion ?? analysis.baselineId} → ${analysis.toVersion} (ни один байт не записан).`);
57
- list('Будет добавлено', analysis.creates.map((item) => item.path));
58
- list('Будет обновлено', analysis.updates.map((item) => item.appends === undefined ? item.path : `${item.path} — допишет строки: ${item.appends.join(', ')}`));
94
+ list('Будет добавлено', analysis.creates.map((item) => `${item.path}${counted.get(item.path) ?? ''}`));
95
+ list('Будет обновлено', analysis.updates.map((item) => item.appends === undefined
96
+ ? `${item.path}${counted.get(item.path) ?? ''}`
97
+ : `${item.path} — допишет строки: ${item.appends.join(', ')}`));
98
+ list('Будет удалено (файлы Maestro без ваших правок, которых больше нет в составе)', analysis.removes.map((path) => `${path}${counted.get(path) ?? ''}`));
59
99
  list('Перейдёт к проекту (дальше файл ваш, Maestro его не проверяет и не перезаписывает)', analysis.handedOver);
60
100
  list('Уже совпадает', analysis.unchanged);
61
101
  list('Останется без изменений', analysis.preserves);
62
102
  list('Служебные файлы', analysis.metadata);
103
+ for (const note of analysis.notes)
104
+ io.out(`Важно: ${note}`);
105
+ io.out(`Сами правки построчно: ${serviceInvocation(VERSION)} upgrade --path ${quotePathArg(options.path)} --diff (полный показ — сотни строк). Их читает агент и пересказывает человеку простыми словами, что изменится для него.`);
63
106
  // Применять обязана та же версия, что показала это предложение, а не новая @latest.
64
- io.out(`Применить: ${serviceInvocation(VERSION)} upgrade --path ${quotePathArg(options.path)} --apply`);
107
+ io.out(apply);
65
108
  return EXIT_OK;
66
109
  }
@@ -12,6 +12,35 @@ import { join, resolve } from 'node:path';
12
12
  /** Окно модели по умолчанию. Сессия больше него была бы невозможна — тогда окно 1 000 000. */
13
13
  export const DEFAULT_BUDGET = 200_000;
14
14
  export const LARGE_WINDOW = 1_000_000;
15
+ /**
16
+ * Окно модели по её названию в журнале (`message.model`); null — название незнакомо.
17
+ *
18
+ * Окно 200 000 — закрытый список прошлого: Claude 3.x, Opus 4 / 4.1 / 4.5, Sonnet 4 / 4.5,
19
+ * Haiku 4.5 (справочник моделей Anthropic на 06.10.2026). Модели Claude новее — Opus и Sonnet
20
+ * с 4.6, всё семейство 5 и новее, Fable и Mythos — 1 000 000 (HYPOTHESIS для будущих версий).
21
+ * Префикс площадки (`anthropic.`, `us.anthropic.`), дата выпуска и `@дата` Vertex отбрасываются.
22
+ */
23
+ export function windowForModel(model) {
24
+ // `[1m]` — так Claude Code называет модель с явно включённым окном 1 000 000.
25
+ if (/\[1m\]$/i.test(model.trim()))
26
+ return LARGE_WINDOW;
27
+ const name = model.trim().toLowerCase()
28
+ .replace(/^(?:[a-z]+\.)?anthropic\./, '')
29
+ .replace(/@\d{8}$/, '')
30
+ .replace(/-\d{8}(?:-v\d+:\d+)?$/, '');
31
+ if (/^claude-3(?:-\d)?-(?:opus|sonnet|haiku)$/.test(name))
32
+ return DEFAULT_BUDGET;
33
+ const match = /^claude-(opus|sonnet|haiku|fable|mythos)-(\d+)(?:-(\d))?$/.exec(name);
34
+ if (match === null)
35
+ return null;
36
+ const major = Number(match[2]);
37
+ const minor = Number(match[3] ?? '0');
38
+ if (major < 4)
39
+ return DEFAULT_BUDGET;
40
+ if (major === 4 && minor <= 5)
41
+ return DEFAULT_BUDGET;
42
+ return LARGE_WINDOW;
43
+ }
15
44
  /** HYPOTHESIS: пороги подобраны на глаз и уточняются повторным замером. */
16
45
  export const FINISH_SLICE_SHARE = 0.4;
17
46
  export const NEW_SESSION_SHARE = 0.7;
@@ -115,6 +144,9 @@ export async function measureContext(options) {
115
144
  }
116
145
  const seen = new Set();
117
146
  let last = null;
147
+ let lastModel;
148
+ /** Самый большой контекст у каждой модели: после смены модели окно судится по ней одной. */
149
+ const largestByModel = new Map();
118
150
  let totalInput = 0;
119
151
  let largest = 0;
120
152
  let recordedSession;
@@ -141,7 +173,9 @@ export async function measureContext(options) {
141
173
  if (size === 0)
142
174
  continue;
143
175
  last = usage;
176
+ lastModel = typeof entry.message?.model === 'string' ? entry.message.model : undefined;
144
177
  largest = Math.max(largest, size);
178
+ largestByModel.set(lastModel ?? '', Math.max(largestByModel.get(lastModel ?? '') ?? 0, size));
145
179
  if (seen.has(id))
146
180
  continue;
147
181
  seen.add(id);
@@ -151,8 +185,17 @@ export async function measureContext(options) {
151
185
  return { reportVersion: 1, ok: false, budget, transcript, message: 'В журнале сессии пока нет ни одного ответа модели.' };
152
186
  }
153
187
  const contextTokens = count(last.input_tokens) + count(last.cache_read_input_tokens) + count(last.cache_creation_input_tokens) + count(last.output_tokens);
154
- if (options.budget === undefined && largest > DEFAULT_BUDGET)
155
- budget = LARGE_WINDOW;
188
+ // `--window` главнее; иначе окно по модели; незнакомая модель — как раньше, по размеру сессии.
189
+ const byModel = lastModel === undefined ? null : windowForModel(lastModel);
190
+ let windowSource = 'option';
191
+ if (options.budget === undefined) {
192
+ windowSource = byModel === null ? 'unknown-model' : 'model';
193
+ budget = byModel ?? DEFAULT_BUDGET;
194
+ // Сессия больше 200 000 у модели «на 200 000» значит, что у неё включено окно 1 000 000.
195
+ // Смотрится только эта модель: прежняя модель с большим окном не раздувает окно новой.
196
+ if ((byModel === null ? largest : largestByModel.get(lastModel ?? '') ?? 0) > budget)
197
+ budget = LARGE_WINDOW;
198
+ }
156
199
  const share = contextTokens / budget;
157
200
  return {
158
201
  reportVersion: 1,
@@ -161,6 +204,8 @@ export async function measureContext(options) {
161
204
  ...(recordedSession === undefined ? {} : { sessionId: recordedSession }),
162
205
  contextTokens,
163
206
  budget,
207
+ ...(lastModel === undefined ? {} : { model: lastModel }),
208
+ windowSource,
164
209
  percent: Math.round(share * 100),
165
210
  level: levelFor(share),
166
211
  totalInputTokens: totalInput,
@@ -2,7 +2,7 @@ import { execFile } from 'node:child_process';
2
2
  import { existsSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
4
  import { promisify } from 'node:util';
5
- import { critical, error, warning } from './types.js';
5
+ import { critical, error, info, warning } from './types.js';
6
6
  const execFileAsync = promisify(execFile);
7
7
  /** Parse porcelain v1 `-z`; rename/copy records consume two NUL fields. */
8
8
  export function parsePorcelainV1Z(output) {
@@ -43,8 +43,48 @@ export async function checkGit(root, managedDocs, findings, managedFiles = new S
43
43
  if (managedDocs.has(path))
44
44
  findings.push(error('git-managed-dirty', 'Управляемый документ имеет незакоммиченные изменения. Если это результат upgrade — просмотрите diff и закоммитьте; если правка ручная — верните файл.', path));
45
45
  }
46
+ await checkCloudCopy(root, findings);
46
47
  }
47
48
  catch (cause) {
48
49
  findings.push(error('git-check-failed', `Не удалось проверить Git: ${cause instanceof Error ? cause.message : String(cause)}`, '.git'));
49
50
  }
50
51
  }
52
+ /** Команда git, чей отказ — ответ «нет», а не сбой проверки. */
53
+ async function gitAnswer(root, args) {
54
+ try {
55
+ return (await execFileAsync('git', [...args], { cwd: root, encoding: 'utf8' })).stdout.trim();
56
+ }
57
+ catch {
58
+ return null;
59
+ }
60
+ }
61
+ /**
62
+ * Есть ли копия в облаке — только по локальным данным git, без сети: `git fetch` не
63
+ * запускается, поэтому «отправлено» значит «по данным последней синхронизации».
64
+ * Уровень `info`: не красит ни обычную проверку, ни `--strict`, ни `preflight` —
65
+ * проект может сознательно жить только на компьютере.
66
+ */
67
+ async function checkCloudCopy(root, findings) {
68
+ const remotes = await gitAnswer(root, ['remote']);
69
+ if (remotes === null)
70
+ return;
71
+ if (remotes === '') {
72
+ findings.push(info('git-no-remote', 'Копии проекта в облаке нет: у репозитория нет remote. Если этот компьютер пропадёт, проект не восстановить. Завести закрытую копию поможет `/start`.'));
73
+ return;
74
+ }
75
+ // Ветка без коммитов или detached HEAD: отправлять пока нечего или некуда.
76
+ const branch = await gitAnswer(root, ['symbolic-ref', '--quiet', '--short', 'HEAD']);
77
+ if (branch === null || branch === '' || await gitAnswer(root, ['rev-parse', '--verify', '--quiet', 'HEAD']) === null)
78
+ return;
79
+ const upstream = await gitAnswer(root, ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}']);
80
+ if (upstream === null || upstream === '') {
81
+ const names = remotes.split(/\r?\n/).filter(Boolean);
82
+ const remote = names.includes('origin') ? 'origin' : names[0] ?? 'origin';
83
+ findings.push(info('git-no-upstream', `Ветка ${branch} ещё не связана с копией в облаке (upstream), по данным последней синхронизации. Первая отправка: git push -u ${remote} ${branch}.`));
84
+ return;
85
+ }
86
+ const ahead = Number(await gitAnswer(root, ['rev-list', '--count', '@{u}..HEAD']));
87
+ if (Number.isInteger(ahead) && ahead > 0) {
88
+ findings.push(info('git-unpushed', `Коммитов, не отправленных в облако (${upstream}): ${ahead} — по данным последней синхронизации, без запроса в сеть. Отправка: git push.`));
89
+ }
90
+ }
@@ -1,18 +1,12 @@
1
- import { existsSync } from 'node:fs';
2
- import { readdir } from 'node:fs/promises';
3
- import { join } from 'node:path';
4
1
  import { pathHasSymlink } from './fs-utils.js';
5
- import { critical, warning } from './types.js';
2
+ import { critical } from './types.js';
3
+ /**
4
+ * `maestro/inbox/` — одно место для материалов человека: файлы там не замечание,
5
+ * даже в `--strict`. Проверяется только, что путь не уводит за пределы проекта.
6
+ */
6
7
  export async function checkInbox(root, findings) {
7
8
  const inboxPath = 'maestro/inbox';
8
- const dir = join(root, inboxPath);
9
9
  if (await pathHasSymlink(root, inboxPath)) {
10
10
  findings.push(critical('inbox-symlink', 'Inbox path не должен содержать symbolic link.', inboxPath));
11
- return;
12
11
  }
13
- if (!existsSync(dir))
14
- return;
15
- const entries = (await readdir(dir)).filter((name) => name !== 'README.md' && name !== '.gitkeep');
16
- if (entries.length > 0)
17
- findings.push(warning('inbox-not-empty', 'Inbox содержит необработанные материалы.', 'maestro/inbox'));
18
12
  }
@@ -42,7 +42,7 @@ function versionFinding(rootInput, manifest, canonical) {
42
42
  : info('project-version-newer', `Проект обновлён более новой версией ${projectVersion}, а проверяет ${VERSION}. Точная проверка: ${checkSame}.`, MANIFEST_PATH);
43
43
  }
44
44
  return order < 0
45
- ? error('project-outdated', `Проект создан Vibe Coding Maestro ${projectVersion}, а запущена ${VERSION}: у этих версий разный состав файлов. Проверить проект его версией: ${checkSame}. Обновить проект до ${VERSION}: ${upgrade} (без --apply только показывает изменения).`, MANIFEST_PATH)
45
+ ? error('project-outdated', `Проект создан Vibe Coding Maestro ${projectVersion}, а запущена ${VERSION}: у этих версий разный состав файлов. Проверить проект его версией: ${checkSame}. Обновить проект до ${VERSION}: ${upgrade} (без --apply только показывает изменения, с --diff — сами правки построчно).`, MANIFEST_PATH)
46
46
  : error('project-newer', `Проект создан более новой версией ${projectVersion}, а запущена ${VERSION}. Проверьте проект его версией: ${checkSame}.`, MANIFEST_PATH);
47
47
  }
48
48
  export async function doctorProject(rootInput, options = {}) {
@@ -1,6 +1,6 @@
1
1
  import { existsSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
- import { ACTIVE_PLAN_NONE, APPROVAL_REQUIRED_STATUSES, isExternalSourceRef, isWikiRelativePlanRef, planBodyDigest, validatePlanFrontmatter } from '../plan.js';
3
+ import { ACTIVE_PLAN_NONE, APPROVAL_REQUIRED_STATUSES, isExternalSourceRef, isWikiRelativePlanRef, planDigestMatches, validatePlanFrontmatter } from '../plan.js';
4
4
  import { frontmatter } from './text.js';
5
5
  import { error } from './types.js';
6
6
  export const PLANS_DIR = 'wiki/plans';
@@ -40,8 +40,8 @@ export function checkPlans(root, decoded, findings) {
40
40
  if (plan === null)
41
41
  continue;
42
42
  plans.set(path, plan);
43
- if (APPROVAL_REQUIRED_STATUSES.includes(plan.status) && plan.approvedDigest !== null && plan.approvedDigest !== planBodyDigest(text)) {
44
- findings.push(error('plan-changed-after-approval', 'Текст утверждённого плана изменился после утверждения (approved_digest не совпадает). Покажите изменения человеку; после повторного «план утверждаю» запишите новый отпечаток из вывода preflight.', path));
43
+ if (APPROVAL_REQUIRED_STATUSES.includes(plan.status) && plan.approvedDigest !== null && !planDigestMatches(plan.approvedDigest, text)) {
44
+ findings.push(error('plan-changed-after-approval', 'Текст утверждённого плана изменился после утверждения (approved_digest не совпадает). Покажите изменения человеку; после его «да» — повторного «план утверждаю» или «да» на правку посреди плана (protocols/plan.md) — запишите новый отпечаток из вывода preflight.', path));
45
45
  }
46
46
  }
47
47
  const byId = new Map();
@@ -43,7 +43,7 @@ export async function checkSources(root, findings) {
43
43
  if (!existsSync(metadataAbsolute)) {
44
44
  const actualPaths = await sourceFiles(root, join(root, SOURCES_DIR), findings);
45
45
  if (actualPaths.length > 0)
46
- findings.push(critical('source-hashes-missing', 'Для существующих sources отсутствует metadata с versioned hashes.', metadataPath));
46
+ findings.push(critical('source-hashes-missing', 'В maestro/sources/ лежат файлы без снимка: эта папка — только для снимков команды `vibe-maestro sources --write`. Свои материалы кладите в maestro/inbox/ — там они не замечание.', metadataPath));
47
47
  return;
48
48
  }
49
49
  try {
@@ -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
+ }
@@ -16,7 +16,9 @@ export const REQUIRED_GITIGNORE_ENTRIES = [
16
16
  '.claude/worktrees/',
17
17
  '.claude/settings.local.json',
18
18
  ];
19
- const BLOCK_HEADER = `# --- ${PRODUCT_NAME} ---`;
19
+ /** Заголовок блока Maestro в `.gitignore` проекта. */
20
+ export const GITIGNORE_BLOCK_HEADER = `# --- ${PRODUCT_NAME} ---`;
21
+ const BLOCK_HEADER = GITIGNORE_BLOCK_HEADER;
20
22
  /**
21
23
  * Приводит строку .gitignore к сравнимому виду.
22
24
  * node_modules и node_modules/ считаются одной записью, отступы не значимы.