create-vibe-maestro 0.4.2 → 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 (66) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/README.md +9 -9
  3. package/dist/cli/context-run.js +10 -0
  4. package/dist/cli/maestro.js +25 -2
  5. package/dist/cli/pack-run.js +42 -3
  6. package/dist/cli/upgrade-run.js +44 -5
  7. package/dist/core/context.js +47 -2
  8. package/dist/core/doctor/index.js +1 -1
  9. package/dist/core/doctor/plans.js +3 -3
  10. package/dist/core/gitignore.js +3 -1
  11. package/dist/core/inventory.js +2 -10
  12. package/dist/core/pack.js +130 -12
  13. package/dist/core/plan.js +21 -2
  14. package/dist/core/preflight.js +6 -5
  15. package/dist/core/template.js +2 -1
  16. package/dist/core/text-diff.js +108 -0
  17. package/dist/core/upgrade/analyze.js +70 -4
  18. package/dist/core/upgrade/baseline.js +10 -0
  19. package/dist/core/upgrade/index.js +53 -10
  20. package/dist/core/upgrade/releases.js +93 -2
  21. package/docs/ROADMAP.md +7 -3
  22. package/docs/USER_GUIDE.md +69 -30
  23. package/package.json +1 -1
  24. package/registry/baseline/0.4.2/project/.claude/agents/code-reviewer.md +13 -0
  25. package/registry/baseline/0.4.2/project/.claude/rules/maestro.md +37 -0
  26. package/registry/baseline/0.4.2/project/maestro/runbooks/cowork-audit.md +11 -0
  27. package/registry/baseline/0.4.2/project/maestro/templates/handoff.md +25 -0
  28. package/registry/baseline/0.4.2/project/protocols/audit.md +5 -0
  29. package/registry/baseline/0.4.2/project/protocols/build.md +18 -0
  30. package/registry/baseline/0.4.2/project/protocols/completion.md +22 -0
  31. package/registry/baseline/0.4.2/project/protocols/handoff.md +15 -0
  32. package/registry/baseline/0.4.2/project/protocols/plan.md +149 -0
  33. package/registry/baseline/0.4.2/project/protocols/start.md +64 -0
  34. package/registry/baseline/0.4.2/project/protocols/wiki.md +9 -0
  35. package/registry/baseline/0.4.2/project/wiki/plans/README.md +131 -0
  36. package/registry/baseline/0.4.2/project/wiki/plans/TEMPLATE.md +75 -0
  37. package/registry/capabilities.v1.json +19 -19
  38. package/templates/project/.claude/agents/code-reviewer.md +18 -7
  39. package/templates/project/.claude/rules/maestro.md +6 -3
  40. package/templates/project/.claude/settings.json +1 -0
  41. package/templates/project/maestro/runbooks/cowork-audit.md +9 -2
  42. package/templates/project/maestro/templates/audit.md +31 -0
  43. package/templates/project/maestro/templates/handoff.md +5 -1
  44. package/templates/project/protocols/audit.md +70 -1
  45. package/templates/project/protocols/build.md +111 -9
  46. package/templates/project/protocols/completion.md +8 -7
  47. package/templates/project/protocols/handoff.md +3 -1
  48. package/templates/project/protocols/plan.md +32 -22
  49. package/templates/project/protocols/start.md +1 -1
  50. package/templates/project/protocols/wiki.md +10 -2
  51. package/templates/project/wiki/icebox.md +12 -0
  52. package/templates/project/wiki/index.md +1 -0
  53. package/templates/project/wiki/passport.md +1 -1
  54. package/templates/project/wiki/plans/0001-starter.md +13 -2
  55. package/templates/project/wiki/plans/README.md +7 -3
  56. package/templates/project/wiki/plans/TEMPLATE.md +13 -5
  57. /package/{templates → registry/baseline/0.4.2}/project/protocols/build/audit-phase.md +0 -0
  58. /package/{templates → registry/baseline/0.4.2}/project/protocols/build/audit-plan.md +0 -0
  59. /package/{templates → registry/baseline/0.4.2}/project/protocols/build/step-1-rules.md +0 -0
  60. /package/{templates → registry/baseline/0.4.2}/project/protocols/build/step-2-spec.md +0 -0
  61. /package/{templates → registry/baseline/0.4.2}/project/protocols/build/step-3-architecture.md +0 -0
  62. /package/{templates → registry/baseline/0.4.2}/project/protocols/build/step-5-feature-loop.md +0 -0
  63. /package/{templates → registry/baseline/0.4.2}/project/protocols/context-budget.md +0 -0
  64. /package/{templates → registry/baseline/0.4.2}/project/protocols/discovery.md +0 -0
  65. /package/{templates → registry/baseline/0.4.2}/project/protocols/lessons.md +0 -0
  66. /package/{templates → registry/baseline/0.4.2}/project/protocols/seams.md +0 -0
package/dist/core/pack.js CHANGED
@@ -2,8 +2,11 @@ import { execFile } from 'node:child_process';
2
2
  import { createHash } from 'node:crypto';
3
3
  import { existsSync } from 'node:fs';
4
4
  import { mkdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
5
+ import { homedir } from 'node:os';
5
6
  import { dirname, join, posix, resolve } from 'node:path';
6
7
  import { promisify } from 'node:util';
8
+ import { GITIGNORE_BLOCK_HEADER, REQUIRED_GITIGNORE_ENTRIES } from './gitignore.js';
9
+ import { GITATTRIBUTES_CONTENT } from './init.js';
7
10
  import { MANIFEST_PATH } from './manifest.js';
8
11
  import { buildZip, ZipTooLargeError } from './zip.js';
9
12
  const execFileAsync = promisify(execFile);
@@ -16,6 +19,14 @@ export const PASSPORT_PATH = 'wiki/passport.md';
16
19
  export const HANDOVER_PATH = 'HANDOVER.md';
17
20
  /** Внутренние места Maestro и агентов в корне: заказчику они не нужны и в архив не попадают. */
18
21
  export const INTERNAL_PATHS = ['wiki/', 'maestro/', '.claude/', 'protocols/', '.maestro/', 'CLAUDE.md', 'AGENTS.md', '.mcp.json'];
22
+ /** Разделы паспорта о доступах: если все они «не применимо», менять заказчику нечего. */
23
+ export const ACCESS_SECTIONS = [
24
+ 'Где работает',
25
+ 'Домен и DNS',
26
+ 'Данные, базы, резервные копии',
27
+ 'Внешние сервисы и чей аккаунт',
28
+ 'Переменные окружения',
29
+ ];
19
30
  /** Разделы паспорта, без которых сдавать нельзя. */
20
31
  export const PASSPORT_SECTIONS = [
21
32
  'Репозиторий',
@@ -38,8 +49,11 @@ async function gitBuffer(root, args) {
38
49
  }
39
50
  /** Строка-заготовка шаблона: «- Пока нет» или «- Адрес: пока нет». Обычный текст со словами «пока нет» — запись. */
40
51
  const PLACEHOLDER_LINE = /^\s*[-*]\s*(?:[^:\n]*:\s*)?пока нет\.?\s*$/i;
41
- /** Разделы паспорта, которые не заполнены: нет раздела, нет записи или осталась заготовка «пока нет». */
42
- export function passportGaps(text) {
52
+ /** Запись «не применимо»: «- Не применимо» или «- Адрес: не применимо». */
53
+ const NOT_APPLICABLE_LINE = /^\s*(?:[-*]\s*)?(?:[^:\n]*:\s*)?не применимо\.?\s*$/i;
54
+ /** Пояснение шаблона в разделе «Переменные окружения»: это не запись. */
55
+ const ENV_SECTION_HINT = 'Только имена и где задаются (`.env`, панель хостинга), значения — никогда.';
56
+ function passportSections(text) {
43
57
  const sections = new Map();
44
58
  const parts = text.replace(/\r\n/g, '\n').replace(/<!--[\s\S]*?-->/g, '').split(/^## +/m).slice(1);
45
59
  for (const part of parts) {
@@ -47,6 +61,22 @@ export function passportGaps(text) {
47
61
  const title = (newline < 0 ? part : part.slice(0, newline)).trim();
48
62
  sections.set(title, newline < 0 ? '' : part.slice(newline + 1));
49
63
  }
64
+ return sections;
65
+ }
66
+ /**
67
+ * Доступов не было: каждый раздел о доступах есть и в нём только «не применимо».
68
+ * Любая другая запись — сомнение, и `HANDOVER.md` просит сменить пароли и ключи.
69
+ */
70
+ export function passportHasNoAccess(text) {
71
+ const sections = passportSections(text);
72
+ return ACCESS_SECTIONS.every((title) => {
73
+ const lines = (sections.get(title) ?? '').split('\n').map((line) => line.trim()).filter((line) => line !== '' && line !== ENV_SECTION_HINT);
74
+ return lines.length > 0 && lines.every((line) => NOT_APPLICABLE_LINE.test(line));
75
+ });
76
+ }
77
+ /** Разделы паспорта, которые не заполнены: нет раздела, нет записи или осталась заготовка «пока нет». */
78
+ export function passportGaps(text) {
79
+ const sections = passportSections(text);
50
80
  return PASSPORT_SECTIONS.filter((title) => {
51
81
  const body = sections.get(title);
52
82
  if (body === undefined)
@@ -211,25 +241,95 @@ export function findSecrets(path, data) {
211
241
  });
212
242
  return found;
213
243
  }
244
+ /**
245
+ * Корневые файлы, которые пишет Maestro: подсвечиваются с пометкой «оставьте».
246
+ * Строки самого Maestro не разбираются; свои строки проекта в `.gitignore` — как обычно.
247
+ */
248
+ const MAESTRO_ROOT_FILES = new Map([
249
+ ['.gitattributes', { reason: 'служебный файл Maestro — оставьте: его проверяет doctor, заказчику он не мешает', ownLines: new Set(GITATTRIBUTES_CONTENT.split('\n')) }],
250
+ ['.gitignore', { reason: 'служебный файл — оставьте: он не пускает в git секреты и лишнее', ownLines: new Set([GITIGNORE_BLOCK_HEADER, ...REQUIRED_GITIGNORE_ENTRIES]) }],
251
+ ]);
252
+ /** Служебные файлы разработки: заказчику обычно не нужны. */
253
+ const SERVICE_FILE = /(^|\/)(?:\.gitignore|\.gitattributes|\.DS_Store)$|(^|\/)(?:\.vscode|\.idea|\.github)\/|\.log$/;
254
+ /** Подсветка содержимого по строкам: первое совпадение каждого вида на файл. */
255
+ function contentHighlights(text, home, root) {
256
+ // Путь Windows в строке кода или JSON записан с удвоенной обратной косой: `C:\\Users\\…`.
257
+ const variants = (path) => (path === '' ? [] : [...new Set([path, path.split('/').join('\\'), path.split('/').join('\\\\')])]);
258
+ const roots = variants(root.replace(/\\/g, '/').replace(/\/+$/, ''));
259
+ const homes = variants(home.replace(/\\/g, '/').replace(/\/+$/, ''));
260
+ const rules = [
261
+ { reason: 'путь папки проекта', test: (line) => roots.some((path) => line.includes(path)) },
262
+ {
263
+ reason: 'путь домашней папки',
264
+ test: (line) => homes.some((path) => line.includes(path)) || /(?:^|[^\w.-])(?:\/Users\/[^/\s]+\/|\/home\/[^/\s]+\/|[A-Za-z]:\\{1,2}Users\\{1,2}[^\\\s]+\\)/.test(line),
265
+ },
266
+ { reason: 'временная папка', test: (line) => /(?:^|[^\w.-])(?:\/tmp\/|\/private\/var\/)/.test(line) },
267
+ { reason: 'имя Maestro', test: (line) => /Vibe Coding Maestro|vibe-maestro/i.test(line) },
268
+ // Адрес в интернете (`https://…/wiki/…`) — не внутренняя папка проекта: адреса вырезаются до проверки.
269
+ { reason: 'внутренняя папка', test: (line) => /(?<![\w.-])(?:wiki|maestro|protocols)\/|(?<![\w-])\.claude\//.test(line.replace(/\b[a-z][\w+.-]*:\/\/\S+/gi, '')) },
270
+ // «план 0002», «по плану 0002»; год («план 2026 года») — не номер плана.
271
+ { reason: 'номер плана', test: (line) => /\bPLAN-\d{4}\b|(?<!\p{L})план(?:а|е|у|ы|ом)?\s+(?!(?:19|20)\d\d(?!\d))\d{4}(?!\d)/iu.test(line) },
272
+ ];
273
+ const found = new Map();
274
+ text.split('\n').forEach((line, index) => {
275
+ for (const rule of rules) {
276
+ if (!found.has(rule.reason) && rule.test(line))
277
+ found.set(rule.reason, index + 1);
278
+ }
279
+ });
280
+ // Путь проекта лежит внутри домашней или временной папки: одну и ту же строку называем точнее.
281
+ for (const wider of ['путь домашней папки', 'временная папка']) {
282
+ if (found.has(wider) && found.get(wider) === found.get('путь папки проекта'))
283
+ found.delete(wider);
284
+ }
285
+ return rules.flatMap((rule) => (found.has(rule.reason) ? [{ reason: rule.reason, line: found.get(rule.reason) }] : []));
286
+ }
287
+ /**
288
+ * Что подсветить в файле архива: служебный файл, личные и временные пути, имена Maestro,
289
+ * внутренние папки, номера планов. Это повод посмотреть, а не отказ: упаковка не запрещается.
290
+ */
291
+ export function packHighlights(path, data, context) {
292
+ // Корневые файлы, которые кладёт Maestro: о них стоит знать, но убирать их не нужно — они безвредны.
293
+ const maestro = MAESTRO_ROOT_FILES.get(path);
294
+ const highlights = [];
295
+ if (maestro !== undefined)
296
+ highlights.push({ path, reason: maestro.reason });
297
+ else if (SERVICE_FILE.test(path))
298
+ highlights.push({ path, reason: 'служебный файл' });
299
+ if (data.length > MAX_SCAN_BYTES)
300
+ return highlights;
301
+ const text = scanText(data);
302
+ if (text === null)
303
+ return highlights;
304
+ // Строки самого Maestro заменяются пустыми: номера остальных строк не сдвигаются.
305
+ const own = maestro === undefined ? text : text.split('\n').map((line) => (maestro.ownLines.has(line.trim()) ? '' : line)).join('\n');
306
+ for (const item of contentHighlights(own, context.home, context.root))
307
+ highlights.push({ path, ...item });
308
+ return highlights;
309
+ }
214
310
  /** Ссылка, ведущая за пределы проекта или по абсолютному пути: в архиве она указала бы на чужое. */
215
311
  function symlinkEscapes(path, target) {
216
312
  if (target.startsWith('/') || /^[A-Za-z]:[\\/]/.test(target))
217
313
  return true;
218
314
  return posix.normalize(posix.join(posix.dirname(path), target)).startsWith('../');
219
315
  }
220
- /** Текст `HANDOVER.md`: обязательный шаг «смените все пароли и ключи» и паспорт из тега. */
316
+ /**
317
+ * Текст `HANDOVER.md`: паспорт из тега и шаг «смените все пароли и ключи». Шаг заменяется
318
+ * на «доступов не было», только если в паспорте все разделы о доступах — «не применимо».
319
+ */
221
320
  export function handoverText(input) {
222
321
  const passport = input.passport.replace(/\r\n/g, '\n');
223
322
  const firstSection = passport.search(/^## /m);
224
323
  const body = (firstSection < 0 ? passport : passport.slice(firstSection)).replace(/^## /gm, '### ').trimEnd();
324
+ const access = passportHasNoAccess(passport)
325
+ ? ['## Доступы', '', 'Доступов не было, менять нечего: в паспорте все разделы о хостинге, домене, данных, внешних сервисах и переменных окружения — «не применимо».']
326
+ : ['## Первым делом: смените все пароли и ключи', '', 'Пока проект делали, пароли и ключи знали исполнители. Сразу после передачи смените их все: ключи API, пароли от хостинга, баз данных, домена, почты и внешних сервисов. Новые значения задайте там, где они задаются (раздел «Переменные окружения» ниже), и проверьте, что проект работает.'];
225
327
  return [
226
328
  `# Передача проекта ${input.projectName}`,
227
329
  '',
228
330
  `Версия: тег \`${input.tag}\`, коммит \`${input.commit}\`.`,
229
331
  '',
230
- '## Первым делом: смените все пароли и ключи',
231
- '',
232
- 'Пока проект делали, пароли и ключи знали исполнители. Сразу после передачи смените их все: ключи API, пароли от хостинга, баз данных, домена, почты и внешних сервисов. Новые значения задайте там, где они задаются (раздел «Переменные окружения» ниже), и проверьте, что проект работает.',
332
+ ...access,
233
333
  '',
234
334
  '## Паспорт проекта',
235
335
  '',
@@ -259,11 +359,14 @@ export async function packProject(options) {
259
359
  }
260
360
  if (prefix !== '')
261
361
  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 {
362
+ /** Коммит метки; без метки показ состава берёт последний коммит (HEAD), а упаковка отказывает. */
363
+ const revision = async (ref) => (await git(root, ['rev-parse', '--verify', '--quiet', `${ref}^{commit}`]).catch(() => '')).trim() || null;
364
+ const tagged = await revision(`refs/tags/${tag}`);
365
+ // Состав смотрят до метки: агент убирает внутреннее, и метку ставят один раз, на чистый коммит.
366
+ const head = tagged === null && options.dryRun === true ? await revision('HEAD') : null;
367
+ const commit = tagged ?? head;
368
+ const untagged = tagged === null;
369
+ if (commit === null) {
267
370
  const tags = (await git(root, ['tag', '--list']).catch(() => '')).split('\n').filter((line) => line !== '');
268
371
  const known = tags.length === 0 ? 'В проекте пока нет ни одного тега.' : `Есть теги: ${tags.slice(-10).join(', ')}.`;
269
372
  return fail(finding('pack-tag-missing', `Тег «${tag}» не найден. ${known} Тег сдачи ставится по протоколу завершения, после «да» человека.`));
@@ -340,6 +443,21 @@ export async function packProject(options) {
340
443
  ...kept.map((entry) => ({ path: entry.path, data: entry.data, mode: entry.mode })),
341
444
  { path: HANDOVER_PATH, data: handover, mode: 0o100644 },
342
445
  ].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
446
+ const context = { home: options.home ?? homedir(), root };
447
+ const highlights = [
448
+ ...kept.flatMap((entry) => (entry.symlink ? (SERVICE_FILE.test(entry.path) ? [{ path: entry.path, reason: 'служебный файл' }] : []) : packHighlights(entry.path, entry.data, context))),
449
+ ...packHighlights(HANDOVER_PATH, handover, context),
450
+ ].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
451
+ const extra = {
452
+ ...(highlights.length > 0 ? { highlights } : {}),
453
+ ...(passportHasNoAccess(passport) ? { noAccess: true } : {}),
454
+ };
455
+ if (options.dryRun === true) {
456
+ return {
457
+ ok: true, findings: [], tag, commit, dryRun: true, ...(untagged ? { untagged: true } : {}), files: zipEntries.length,
458
+ entries: zipEntries.map((entry) => entry.path), ...(notes.length > 0 ? { notes } : {}), ...extra,
459
+ };
460
+ }
343
461
  let zip;
344
462
  try {
345
463
  zip = buildZip(zipEntries, time);
@@ -355,7 +473,7 @@ export async function packProject(options) {
355
473
  try {
356
474
  if (existsSync(out) && (await stat(out)).isDirectory())
357
475
  out = join(out, defaultArchiveName(root, tag));
358
- const summary = { tag, commit, archive: out, sha256, files: zipEntries.length, bytes: zip.length, ...(notes.length > 0 ? { notes } : {}) };
476
+ const summary = { tag, commit, archive: out, sha256, files: zipEntries.length, bytes: zip.length, ...(notes.length > 0 ? { notes } : {}), ...extra };
359
477
  if (existsSync(out)) {
360
478
  if ((await stat(out)).isFile() && (await readFile(out)).equals(zip))
361
479
  return { ok: true, findings: [], reused: true, ...summary };
package/dist/core/plan.js CHANGED
@@ -37,12 +37,31 @@ export const PLAN_APPROVAL_DIGEST_KEY = 'approved_digest';
37
37
  * его меняет сама работа, и гейт не должен закрываться от каждого шага.
38
38
  */
39
39
  export const PLAN_DIGEST_KEYS = ['id', 'kind', 'scale', 'mode', 'governance', 'risk', 'profiles', 'sources', 'supersedes'];
40
- /** sha256 утверждённого: классификация из frontmatter плюс текст плана (LF, без хвостовых пробелов). */
40
+ /** Отметка пункта списка `[x]` или `[X]`: в отпечатке она считается `[ ]`, а текст пункта — нет. */
41
+ const CHECKED_ITEM_RE = /^([ \t]*(?:[-*+]|\d+[.)])[ \t]+)\[[xX]\]/gm;
42
+ /**
43
+ * sha256 утверждённого: классификация из frontmatter плюс текст плана (LF, без хвостовых
44
+ * пробелов). Отметки выполненных пунктов не входят: отметить пункт — не изменить план.
45
+ */
41
46
  export function planBodyDigest(text) {
47
+ return digest(text, (body) => body.replace(CHECKED_ITEM_RE, '$1[ ]'));
48
+ }
49
+ /**
50
+ * Отпечаток 0.3.0–0.4.2, где отметки пунктов ещё входили в текст. Принимается, чтобы
51
+ * план, утверждённый раньше с отмеченными пунктами, без правок оставался зелёным.
52
+ */
53
+ export function legacyPlanBodyDigest(text) {
54
+ return digest(text, (body) => body);
55
+ }
56
+ /** Записанный отпечаток совпадает с планом — новым способом или прежним. */
57
+ export function planDigestMatches(approvedDigest, text) {
58
+ return approvedDigest === planBodyDigest(text) || approvedDigest === legacyPlanBodyDigest(text);
59
+ }
60
+ function digest(text, normalizeBody) {
42
61
  const match = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(text);
43
62
  const meta = match ? frontmatterValues(match[1] ?? '') : {};
44
63
  const classification = PLAN_DIGEST_KEYS.map((key) => `${key}: ${meta[key] ?? ''}`).join('\n');
45
- const body = text.slice(match ? match[0].length : 0).replace(/\r\n/g, '\n').replace(/[ \t]+$/gm, '').trim();
64
+ const body = normalizeBody(text.slice(match ? match[0].length : 0).replace(/\r\n/g, '\n').replace(/[ \t]+$/gm, '').trim());
46
65
  return createHash('sha256').update(`${classification}\n---\n${body}`).digest('hex');
47
66
  }
48
67
  /** Значения key: value для отпечатка; полный разбор с проверками живёт в doctor/text.ts. */
@@ -19,7 +19,7 @@ import { readdir, readFile } from 'node:fs/promises';
19
19
  import { join, resolve } from 'node:path';
20
20
  import { MANIFEST_PATH } from './manifest.js';
21
21
  import { decodeUtf8, frontmatter } from './doctor/text.js';
22
- import { ACTIVE_PLAN_NONE, APPROVAL_REQUIRED_STATUSES, isWikiRelativePlanRef, planBodyDigest, validatePlanFrontmatter, PLAN_SCALES, } from './plan.js';
22
+ import { ACTIVE_PLAN_NONE, APPROVAL_REQUIRED_STATUSES, isWikiRelativePlanRef, planBodyDigest, planDigestMatches, validatePlanFrontmatter, PLAN_SCALES, } from './plan.js';
23
23
  export const HOT_PATH = 'wiki/hot.md';
24
24
  /**
25
25
  * Явные критерии исключения для QUICK.
@@ -96,9 +96,10 @@ export function decideBuildPreflight(state, request) {
96
96
  findings: validation.issues.map((issue) => finding('block', 'preflight-plan-invalid', `${issue.field}: ${issue.message}`, state.planPath ?? undefined)),
97
97
  });
98
98
  }
99
- return decideForPlan(validation.plan, state.planPath, planBodyDigest(state.planText));
99
+ return decideForPlan(validation.plan, state.planPath, planBodyDigest(state.planText), planDigestMatches(validation.plan.approvedDigest ?? '', state.planText));
100
100
  }
101
- function decideForPlan(plan, planPath, digest) {
101
+ /** `digest` — отпечаток для записи; `digestMatches` — совпал ли записанный (новым способом или прежним). */
102
+ function decideForPlan(plan, planPath, digest, digestMatches) {
102
103
  const findings = [];
103
104
  const at = (code, message) => { findings.push(finding('block', code, message, planPath)); };
104
105
  let route = 'plan';
@@ -111,8 +112,8 @@ function decideForPlan(plan, planPath, digest) {
111
112
  at('preflight-approval-missing', 'У утверждённого плана нет следа человеческого решения.');
112
113
  return decision({ plan: planPath, route, planDigest: digest, findings });
113
114
  }
114
- if (plan.approvedDigest !== null && plan.approvedDigest !== digest) {
115
- at('preflight-plan-changed', 'Текст плана изменился после утверждения: покажите изменения человеку; после повторного «план утверждаю» запишите в approved_digest новый отпечаток.');
115
+ if (plan.approvedDigest !== null && !digestMatches) {
116
+ at('preflight-plan-changed', 'Текст плана изменился после утверждения: покажите изменения человеку; после его «да» — повторного «план утверждаю» или «да» на правку посреди плана (protocols/plan.md) — запишите в approved_digest новый отпечаток.');
116
117
  return decision({ plan: planPath, route: 'human', planDigest: digest, findings });
117
118
  }
118
119
  const missing = [];
@@ -8,8 +8,9 @@ const FRONTMATTER_RE = /^(---\r?\n)([\s\S]*?)(\r?\n---[ \t]*(?:\r?\n|$))/;
8
8
  /**
9
9
  * Умышленно широкий: любой {{...}} обязан быть известным.
10
10
  * Опечатка в шаблоне (в т.ч. кириллицей) должна падать, а не молча уезжать в файл проекта.
11
+ * Исключение одно: `${{ … }}` — выражение GitHub Actions в образце настройки проверок, не подстановка Maestro.
11
12
  */
12
- const PLACEHOLDER_RE = /\{\{([^{}\r\n]+)\}\}/g;
13
+ const PLACEHOLDER_RE = /(?<!\$)\{\{([^{}\r\n]+)\}\}/g;
13
14
  export function splitFrontmatter(content) {
14
15
  const match = FRONTMATTER_RE.exec(content);
15
16
  if (!match) {
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Построчное сравнение двух текстов без зависимостей: что убрать, что добавить.
3
+ *
4
+ * Общие начало и конец отрезаются сразу, середина сравнивается по наибольшей
5
+ * общей подпоследовательности строк. Файлы Maestro — сотни строк, поэтому
6
+ * квадратная таблица на одну середину дешёвая; слишком большая середина
7
+ * показывается целиком как «убрать всё старое, добавить всё новое».
8
+ */
9
+ /** Больше клеток таблица не строится: такой файл не правка, а замена. */
10
+ const MAX_TABLE_CELLS = 4_000_000;
11
+ /** Строки текста; перевод строки в конце не даёт лишней пустой строки. CRLF считается LF. */
12
+ export function splitLines(text) {
13
+ if (text === '')
14
+ return [];
15
+ const lines = text.replace(/\r\n/g, '\n').split('\n');
16
+ if (lines.at(-1) === '')
17
+ lines.pop();
18
+ return lines;
19
+ }
20
+ /** Полная последовательность строк: общие, убранные и добавленные, по порядку. */
21
+ export function diffLines(before, after) {
22
+ let prefix = 0;
23
+ while (prefix < before.length && prefix < after.length && before[prefix] === after[prefix])
24
+ prefix += 1;
25
+ let suffix = 0;
26
+ while (suffix < before.length - prefix
27
+ && suffix < after.length - prefix
28
+ && before[before.length - 1 - suffix] === after[after.length - 1 - suffix])
29
+ suffix += 1;
30
+ const a = before.slice(prefix, before.length - suffix);
31
+ const b = after.slice(prefix, after.length - suffix);
32
+ const lines = before.slice(0, prefix).map((text) => ({ kind: 'same', text }));
33
+ if ((a.length + 1) * (b.length + 1) > MAX_TABLE_CELLS) {
34
+ lines.push(...a.map((text) => ({ kind: 'remove', text })), ...b.map((text) => ({ kind: 'add', text })));
35
+ }
36
+ else {
37
+ // table[i * width + j] — длина общей подпоследовательности хвостов a[i..] и b[j..].
38
+ const width = b.length + 1;
39
+ const table = new Uint32Array((a.length + 1) * width);
40
+ for (let i = a.length - 1; i >= 0; i -= 1) {
41
+ for (let j = b.length - 1; j >= 0; j -= 1) {
42
+ table[i * width + j] = a[i] === b[j]
43
+ ? table[(i + 1) * width + j + 1] + 1
44
+ : Math.max(table[(i + 1) * width + j], table[i * width + j + 1]);
45
+ }
46
+ }
47
+ let i = 0;
48
+ let j = 0;
49
+ while (i < a.length || j < b.length) {
50
+ if (i < a.length && j < b.length && a[i] === b[j]) {
51
+ lines.push({ kind: 'same', text: a[i] });
52
+ i += 1;
53
+ j += 1;
54
+ }
55
+ else if (j === b.length || (i < a.length && table[(i + 1) * width + j] >= table[i * width + j + 1])) {
56
+ // При равенстве сначала убранное: так читается привычнее («было — стало»).
57
+ lines.push({ kind: 'remove', text: a[i] });
58
+ i += 1;
59
+ }
60
+ else {
61
+ lines.push({ kind: 'add', text: b[j] });
62
+ j += 1;
63
+ }
64
+ }
65
+ }
66
+ lines.push(...before.slice(before.length - suffix).map((text) => ({ kind: 'same', text })));
67
+ return lines;
68
+ }
69
+ /** Куски правок с `context` общими строками вокруг; далёкие правки — отдельными кусками. */
70
+ export function diffText(before, after, context = 3) {
71
+ const lines = diffLines(splitLines(before), splitLines(after));
72
+ const added = lines.filter((line) => line.kind === 'add').length;
73
+ const removed = lines.filter((line) => line.kind === 'remove').length;
74
+ const changed = lines.flatMap((line, index) => (line.kind === 'same' ? [] : [index]));
75
+ const hunks = [];
76
+ let start = 0;
77
+ while (start < changed.length) {
78
+ let end = start;
79
+ // Правки, между которыми не больше 2 × context общих строк, идут одним куском.
80
+ while (end + 1 < changed.length && changed[end + 1] - changed[end] <= 2 * context + 1)
81
+ end += 1;
82
+ const from = Math.max(0, changed[start] - context);
83
+ const to = Math.min(lines.length, changed[end] + context + 1);
84
+ let oldStart = 1;
85
+ let newStart = 1;
86
+ for (const line of lines.slice(0, from)) {
87
+ if (line.kind !== 'add')
88
+ oldStart += 1;
89
+ if (line.kind !== 'remove')
90
+ newStart += 1;
91
+ }
92
+ const slice = lines.slice(from, to);
93
+ const oldLines = slice.filter((line) => line.kind !== 'add').length;
94
+ const newLines = slice.filter((line) => line.kind !== 'remove').length;
95
+ // Как в unified diff: у пустой стороны номер — строка перед куском.
96
+ hunks.push({ oldStart: oldLines === 0 ? oldStart - 1 : oldStart, oldLines, newStart: newLines === 0 ? newStart - 1 : newStart, newLines, lines: slice });
97
+ start = end + 1;
98
+ }
99
+ return { added, removed, hunks };
100
+ }
101
+ /** Кусок в привычном виде unified diff: заголовок `@@ … @@` и строки с « », «-», «+». */
102
+ export function formatHunk(hunk) {
103
+ const mark = { same: ' ', add: '+', remove: '-' };
104
+ return [
105
+ `@@ -${hunk.oldStart},${hunk.oldLines} +${hunk.newStart},${hunk.newLines} @@`,
106
+ ...hunk.lines.map((line) => `${mark[line.kind]}${line.text}`),
107
+ ];
108
+ }
@@ -11,12 +11,15 @@ import { hasAnyReadme, README_PATH } from '../readme.js';
11
11
  import { canonicalizeSystemTempPrefix } from '../platform-paths.js';
12
12
  import { renderTemplate } from '../template.js';
13
13
  import { compareVersions } from '../version.js';
14
- import { findRelease, supportedVersions } from './releases.js';
14
+ import { findRelease, REMOVED_PATHS, supportedVersions } from './releases.js';
15
15
  import { recoverTemplateVars, templateUses } from '../template-recover.js';
16
16
  const GITIGNORE_PATH = '.gitignore';
17
17
  /** Папка материалов человека и правило «байт в байт» для неё (0.4.2). */
18
18
  const INBOX_DIR = 'maestro/inbox';
19
19
  const INBOX_GITATTRIBUTES_PATH = `${INBOX_DIR}/.gitattributes`;
20
+ /** Страница отложенных идей (0.4.3) и каталог памяти, в котором о ней стоит строка. */
21
+ const ICEBOX_PATH = 'wiki/icebox.md';
22
+ const WIKI_INDEX_PATH = 'wiki/index.md';
20
23
  /** Версия, с которой README проекта кладут create и upgrade; с неё и дальше удалённый README не возвращается. */
21
24
  const README_SINCE = '0.4.2';
22
25
  /** Каталог транзакции. Внутри `.maestro`, чтобы не появляться в дереве проекта. */
@@ -32,6 +35,7 @@ function analysis(root, status, fromVersion, blockers, baselineId = 'unknown') {
32
35
  toVersion: VERSION,
33
36
  creates: [],
34
37
  updates: [],
38
+ removes: [],
35
39
  unchanged: [],
36
40
  preserves: [],
37
41
  handedOver: [],
@@ -95,6 +99,9 @@ async function releaseSource(release, relativePath) {
95
99
  }
96
100
  return { source };
97
101
  }
102
+ if (!TEMPLATE_FILES.includes(relativePath) && CODE_MANAGED_SOURCES[relativePath] === undefined) {
103
+ return { blocker: blocker('upgrade-baseline-drift', `В пакете нет копии этого файла в версии ${release.versions.join(', ')}: без неё upgrade не может доказать, что файл не изменён. Это дефект пакета — сообщите о нём.`, relativePath) };
104
+ }
98
105
  const source = await currentSource(relativePath);
99
106
  if (release.managedSha256[relativePath] !== sha256(source)) {
100
107
  return { blocker: blocker('upgrade-baseline-drift', `В пакете нет копии этого файла в версии ${release.versions.join(', ')}: без неё upgrade не может доказать, что файл не изменён. Это дефект пакета — сообщите о нём.`, relativePath) };
@@ -166,15 +173,25 @@ export async function analyzeUpgrade(rootInput) {
166
173
  }
167
174
  const blockers = [];
168
175
  // Полное дерево предшественника: manifest не имеет права выдавать неполную папку за проект.
176
+ // Ушедший из состава файл исключение: если его уже нет, удалять нечего.
169
177
  for (const path of Object.keys(baseline)) {
178
+ if (!(path in current))
179
+ continue;
170
180
  if (!await isRegularFile(join(root, path))) {
171
181
  blockers.push(blocker('upgrade-incomplete-tree', 'Обязательный путь предыдущего канона отсутствует или не является обычным файлом.', path));
172
182
  }
173
183
  }
174
- // Новый канон обязан быть надмножеством с тем же владением: ни удалять, ни передавать пути этот upgrade не умеет.
184
+ // Новый канон — надмножество с тем же владением; исключение — файлы Maestro из явного списка
185
+ // удаляемых. Незнакомое удаление и незнакомая смена владения останавливают upgrade.
186
+ /** Файлы Maestro, ушедшие из состава: удаляются, только если не тронуты. */
187
+ const retired = [];
175
188
  for (const [path, ownership] of Object.entries(baseline)) {
176
- if (!(path in current))
177
- blockers.push(blocker('upgrade-removal-unsupported', 'Путь предыдущего канона отсутствует в текущем; upgrade ничего не удаляет.', path));
189
+ if (!(path in current)) {
190
+ if (ownership === 'managed' && REMOVED_PATHS[path] !== undefined)
191
+ retired.push(path);
192
+ else
193
+ blockers.push(blocker('upgrade-removal-unsupported', 'Путь предыдущего канона отсутствует в текущем, а в списке удаляемых файлов Maestro его нет; незнакомое удаление upgrade не выполняет.', path));
194
+ }
178
195
  else if (current[path] !== ownership && !(ownership === 'managed' && current[path] === 'project-owned')) {
179
196
  blockers.push(blocker('upgrade-ownership-change-unsupported', `Владение путём меняется (${ownership} → ${current[path]}); этот upgrade такого перехода не знает.`, path));
180
197
  }
@@ -215,6 +232,8 @@ export async function analyzeUpgrade(rootInput) {
215
232
  // Пустой маркер каталога: во всех канонах это ноль байт, обновлять нечего.
216
233
  if (path.endsWith('/.gitkeep'))
217
234
  continue;
235
+ if (!(path in current))
236
+ continue; // ушедший файл разбирается ниже
218
237
  const previous = await releaseSource(release, path);
219
238
  if ('blocker' in previous) {
220
239
  blockers.push(previous.blocker);
@@ -258,6 +277,39 @@ export async function analyzeUpgrade(rootInput) {
258
277
  }
259
278
  affected.push({ path, next, actual });
260
279
  }
280
+ // 1а. Ушедшие файлы Maestro: удаляется только неизменённый рендер прошлой версии;
281
+ // изменённый — остановка, отсутствующий — пропуск.
282
+ const removes = [];
283
+ for (const path of retired.sort()) {
284
+ if (await pathHasSymlink(root, path)) {
285
+ blockers.push(blocker('upgrade-path-symlink', 'Удаляемый путь не должен содержать symbolic link.', path));
286
+ continue;
287
+ }
288
+ if (!await exists(join(root, path)))
289
+ continue;
290
+ if (!await isRegularFile(join(root, path))) {
291
+ blockers.push(blocker('upgrade-removal-not-file', 'На месте удаляемого файла Maestro лежит не обычный файл: upgrade его не трогает.', path));
292
+ continue;
293
+ }
294
+ const previous = await releaseSource(release, path);
295
+ if ('blocker' in previous) {
296
+ blockers.push(previous.blocker);
297
+ continue;
298
+ }
299
+ const actual = normalizeEol(await readFile(join(root, path), 'utf8'));
300
+ const recovered = recoverTemplateVars(previous.source, actual, startingPoint, fromVersion);
301
+ if (recovered === null) {
302
+ blockers.push(blocker('upgrade-removed-modified', `В версии ${REMOVED_PATHS[path]} этот файл Maestro убран из состава, и upgrade удалил бы его, но файл изменён вручную относительно версии ${fromVersion}. Перенесите свои правки в собственный файл проекта и удалите этот (или верните его исходный вид — ${await exists(join(root, '.git')) ? `прежний текст покажет \`git log -p -- ${path}\`` : `исходник лежит в пакете create-vibe-maestro@${fromVersion}`}), затем повторите.`, path));
303
+ continue;
304
+ }
305
+ if (!remember(path, recovered))
306
+ continue;
307
+ if (checksums.files[path] !== contentChecksum(path, actual)) {
308
+ blockers.push(blocker('upgrade-checksum-mismatch', 'Записанная контрольная сумма не совпадает с файлом: metadata проекта противоречива.', path));
309
+ continue;
310
+ }
311
+ removes.push(path);
312
+ }
261
313
  if (blockers.length > 0)
262
314
  return blockedAt(root, release, fromVersion, blockers);
263
315
  // Недостающие подстановки можно взять из файлов, которые upgrade не трогает. Это
@@ -315,6 +367,11 @@ export async function analyzeUpgrade(rootInput) {
315
367
  blockers.push(blocker('upgrade-command-collision', `У проекта уже есть своя команда /${name}, а эта версия Maestro добавляет команду с тем же именем. Upgrade её не перезаписывает: переименуйте свою (например, в .claude/commands/my-${name}.md) и повторите.`, path));
316
368
  continue;
317
369
  }
370
+ if (path.startsWith('maestro/templates/')) {
371
+ const name = path.slice('maestro/templates/'.length);
372
+ blockers.push(blocker('upgrade-template-collision', `У проекта уже есть свой образец maestro/templates/${name}, а эта версия Maestro добавляет образец с тем же именем. Upgrade его не перезаписывает: переименуйте свой (например, в maestro/templates/my-${name}) и повторите.`, path));
373
+ continue;
374
+ }
318
375
  blockers.push(blocker('upgrade-path-collision', 'Добавляемый путь уже занят: upgrade не перезаписывает существующее содержимое.', path));
319
376
  continue;
320
377
  }
@@ -395,6 +452,8 @@ export async function analyzeUpgrade(rootInput) {
395
452
  }
396
453
  if (blockers.length > 0)
397
454
  return blockedAt(root, release, fromVersion, blockers);
455
+ for (const path of removes)
456
+ writes.push({ path, content: '', action: 'remove' });
398
457
  // 4. Metadata. Manifest пересобирается по текущему канону; проектные поля переносятся как есть.
399
458
  const nextManifest = buildManifest({
400
459
  projectName: manifest.project.name,
@@ -412,6 +471,8 @@ export async function analyzeUpgrade(rootInput) {
412
471
  const nextChecksums = { ...checksums.files };
413
472
  for (const { path } of handover)
414
473
  delete nextChecksums[path];
474
+ for (const path of retired)
475
+ delete nextChecksums[path];
415
476
  for (const write of writes) {
416
477
  if (current[write.path] === 'managed' || current[write.path] === 'immutable') {
417
478
  nextChecksums[write.path] = contentChecksum(write.path, write.content);
@@ -422,12 +483,17 @@ export async function analyzeUpgrade(rootInput) {
422
483
  const result = analysis(root, 'upgradable', fromVersion, [], release.id);
423
484
  result.creates = creates;
424
485
  result.updates = updates;
486
+ result.removes = removes;
425
487
  result.unchanged = [...unchanged, ...adopted].sort();
426
488
  if (creates.some((item) => item.path === INBOX_GITATTRIBUTES_PATH) && await hasMaterials(root)) {
427
489
  // Опыт (git 2.54): файл, который git уже видел, после нового правила изменённым не показывается —
428
490
  // git не перечитывает его, пока файл не тронут. Переписать его в git байт в байт можно только явно.
429
491
  result.notes.push('Материалы, которые уже лежат в maestro/inbox/, git сам не перепишет. Чтобы он хранил их байт в байт, после обновления выполните `git add --renormalize maestro/inbox` и закоммитьте вместе с обновлением. Если файл уже был нормализован (например, взят из свежего клона на другом компьютере), исходные байты есть только в его источнике.');
430
492
  }
493
+ // Каталог памяти принадлежит проекту: upgrade его не правит, но о новой странице напоминает.
494
+ if (creates.some((item) => item.path === ICEBOX_PATH) && !(await readFile(join(root, WIKI_INDEX_PATH), 'utf8').catch(() => '')).includes('icebox.md')) {
495
+ result.notes.push('Появилась страница отложенных идей wiki/icebox.md. Каталог wiki/index.md принадлежит проекту, и upgrade его не правит: допишите в него строку со ссылкой на icebox.md.');
496
+ }
431
497
  result.metadata = [MANIFEST_PATH, CHECKSUMS_PATH];
432
498
  result.preserves = [
433
499
  ...Object.entries(baseline).filter(([path, ownership]) => ownership === 'project-owned' && path in current).map(([path]) => path),
@@ -154,4 +154,14 @@ export const BASELINE_TEMPLATES = [
154
154
  { path: 'maestro/inbox/README.md', source: 'registry/baseline/0.4.1/project/maestro/inbox/README.md', sha256: '5c3107b469d1c65d5a9d84132f2b0cfb85804b813ad5b9b65248dc434d6981a3' },
155
155
  { path: 'maestro/runbooks/cowork-discovery.md', source: 'registry/baseline/0.4.1/project/maestro/runbooks/cowork-discovery.md', sha256: '1a32c070375783cfa54a3fad5c9644810f6eda37b7cd1a272f811278360b35c4' },
156
156
  { path: 'protocols/discovery.md', source: 'registry/baseline/0.4.1/project/protocols/discovery.md', sha256: '20ef8084561a1c93a16003d3dac0426b43bb97b715f445f06ef79dd738e1430a' },
157
+ // Изменены или убраны в 0.4.3; с 0.2 по 0.4.2 побайтово одинаковы — копия общая.
158
+ { path: 'protocols/audit.md', source: 'registry/baseline/0.4.2/project/protocols/audit.md', sha256: 'c49f38b83db21af01f0f01552c7e8dc9743cd01c3ad12f3f31940f9cf83f76c6' },
159
+ { path: 'protocols/seams.md', source: 'registry/baseline/0.4.2/project/protocols/seams.md', sha256: 'c7669b55b5d298cbfea97cd3c2284c9cb33aceacc9504e6e3ae3851e669ff5bd' },
160
+ { path: 'protocols/lessons.md', source: 'registry/baseline/0.4.2/project/protocols/lessons.md', sha256: '04c94dbed682da746d46271fc2563d1e9ee79f3cd10a60d2d06762e3c1421d0e' },
161
+ { path: 'protocols/build/step-1-rules.md', source: 'registry/baseline/0.4.2/project/protocols/build/step-1-rules.md', sha256: '4a989545399e0492a9cffe1a88cbbe5ebd972f055f4a2871c33cbad224e46fac' },
162
+ { path: 'protocols/build/step-2-spec.md', source: 'registry/baseline/0.4.2/project/protocols/build/step-2-spec.md', sha256: '110f58dae0758974f6d15f186249fa1c4c3dd3967210287d28ce86654152e0e8' },
163
+ { path: 'protocols/build/step-3-architecture.md', source: 'registry/baseline/0.4.2/project/protocols/build/step-3-architecture.md', sha256: 'ea2b0916a8289c0248318a348f992be91a57c8fdc69227029e4f822530dbada1' },
164
+ { path: 'protocols/build/step-5-feature-loop.md', source: 'registry/baseline/0.4.2/project/protocols/build/step-5-feature-loop.md', sha256: '27856936f0217e02fbd0de8ba9172197fcccb3032037e8555695e156362bc9b0' },
165
+ { path: 'protocols/build/audit-plan.md', source: 'registry/baseline/0.4.2/project/protocols/build/audit-plan.md', sha256: '1a6cd6e69044a1985822ed28809123d2980a223fb78e39aa63d4f5618bb66a64' },
166
+ { path: 'protocols/build/audit-phase.md', source: 'registry/baseline/0.4.2/project/protocols/build/audit-phase.md', sha256: 'ac0c1919380516e3c0da09697b2a021a96866016816fb76d7aef2866c8c08f81' },
157
167
  ];