create-vibe-maestro 0.3.0-beta.4 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/CHANGELOG.md +45 -1
  2. package/README.md +28 -19
  3. package/dist/cli/create-run.js +4 -0
  4. package/dist/cli/create.js +3 -0
  5. package/dist/cli/maestro.js +1 -1
  6. package/dist/cli/preflight-run.js +2 -0
  7. package/dist/cli/skills-run.js +0 -1
  8. package/dist/cli/upgrade-run.js +6 -1
  9. package/dist/core/doctor/entries.js +41 -0
  10. package/dist/core/doctor/git.js +9 -4
  11. package/dist/core/doctor/index.js +19 -11
  12. package/dist/core/doctor/managed.js +6 -2
  13. package/dist/core/doctor/plans.js +23 -6
  14. package/dist/core/doctor/text.js +40 -3
  15. package/dist/core/doctor/wiki.js +18 -7
  16. package/dist/core/init.js +71 -11
  17. package/dist/core/inventory.js +10 -3
  18. package/dist/core/manifest.js +2 -0
  19. package/dist/core/plan.js +42 -1
  20. package/dist/core/preflight.js +48 -14
  21. package/dist/core/skills.js +2 -13
  22. package/dist/core/template-recover.js +82 -0
  23. package/dist/core/upgrade/analyze.js +47 -11
  24. package/dist/core/upgrade/baseline.js +6 -0
  25. package/dist/core/upgrade/releases.js +140 -1
  26. package/docs/MIGRATION_V1.md +1 -1
  27. package/docs/ROADMAP.md +2 -2
  28. package/docs/USER_GUIDE.md +57 -37
  29. package/package.json +1 -1
  30. package/registry/baseline/0.3.0/project/.claude/rules/maestro.md +25 -0
  31. package/registry/baseline/0.3.0-beta.4/project/.claude/agents/code-reviewer.md +6 -0
  32. package/registry/baseline/0.3.0-beta.4/project/AGENTS.md +10 -0
  33. package/registry/baseline/0.3.0-beta.4/project/CLAUDE.md +10 -0
  34. package/registry/baseline/0.3.0-beta.4/project/maestro/runbooks/cowork-audit.md +11 -0
  35. package/registry/baseline/0.3.0-beta.4/project/protocols/build.md +15 -0
  36. package/registry/baseline/0.3.0-beta.4/project/protocols/context-budget.md +9 -0
  37. package/registry/baseline/0.3.0-beta.4/project/protocols/handoff.md +5 -0
  38. package/registry/baseline/0.3.0-beta.4/project/protocols/plan.md +132 -0
  39. package/registry/baseline/0.3.0-beta.4/project/protocols/wiki.md +9 -0
  40. package/registry/baseline/0.3.0-beta.4/project/wiki/index.md +32 -0
  41. package/registry/baseline/0.3.0-beta.4/project/wiki/plans/README.md +92 -0
  42. package/registry/baseline/0.3.0-beta.4/project/wiki/plans/TEMPLATE.md +65 -0
  43. package/templates/project/.claude/agents/code-reviewer.md +8 -2
  44. package/templates/project/.claude/agents/explorer.md +14 -0
  45. package/templates/project/.claude/rules/maestro.md +25 -0
  46. package/templates/project/.claude/rules/project.md +5 -0
  47. package/templates/project/.claude/settings.json +34 -0
  48. package/templates/project/AGENTS.md +6 -7
  49. package/templates/project/CLAUDE.md +2 -7
  50. package/templates/project/maestro/runbooks/cowork-audit.md +1 -1
  51. package/templates/project/maestro/templates/adr.md +21 -0
  52. package/templates/project/maestro/templates/handoff.md +25 -0
  53. package/templates/project/maestro/templates/progress.md +22 -0
  54. package/templates/project/protocols/build.md +2 -0
  55. package/templates/project/protocols/context-budget.md +1 -1
  56. package/templates/project/protocols/handoff.md +8 -0
  57. package/templates/project/protocols/plan.md +14 -4
  58. package/templates/project/protocols/wiki.md +1 -1
  59. package/templates/project/wiki/hot.md +1 -1
  60. package/templates/project/wiki/index.md +10 -18
  61. package/templates/project/wiki/plans/0001-starter.md +5 -4
  62. package/templates/project/wiki/plans/README.md +45 -6
  63. package/templates/project/wiki/plans/TEMPLATE.md +11 -1
  64. package/registry/trusted-skills.v1.json +0 -4
@@ -2,12 +2,17 @@ import { existsSync } from 'node:fs';
2
2
  import { readFile } from 'node:fs/promises';
3
3
  import { dirname, relative, resolve, sep } from 'node:path';
4
4
  import { markdownFiles, pathHasSymlink } from './fs-utils.js';
5
- import { decodeUtf8, frontmatter } from './text.js';
5
+ import { decodeUtf8, frontmatter, hasFrontmatterBlock } from './text.js';
6
6
  import { critical, error } from './types.js';
7
7
  /** Возвращает прочитанные wiki-документы, чтобы соседние проверки не читали дерево повторно. */
8
+ /** Frontmatter обязателен там, где его читают проверки; в остальной wiki он по желанию. */
9
+ function requiresFrontmatter(path) {
10
+ return path === 'wiki/hot.md' || /^wiki\/(plans|audits|progress)\//.test(path);
11
+ }
8
12
  export async function checkWiki(root, findings) {
9
13
  const wikiPath = 'wiki';
10
14
  const wiki = resolve(root, wikiPath);
15
+ const projectRoot = resolve(root);
11
16
  if (await pathHasSymlink(root, wikiPath)) {
12
17
  findings.push(critical('wiki-symlink', 'Wiki path не должен содержать symbolic link.', wikiPath));
13
18
  return new Map();
@@ -22,8 +27,11 @@ export async function checkWiki(root, findings) {
22
27
  continue;
23
28
  }
24
29
  decoded.set(path, text);
25
- if (frontmatter(text) === null)
26
- findings.push(error('wiki-frontmatter-invalid', 'Wiki Markdown должен начинаться простым YAML frontmatter key: value.', path));
30
+ if (frontmatter(text) === null && (requiresFrontmatter(path) || hasFrontmatterBlock(text))) {
31
+ findings.push(error('wiki-frontmatter-invalid', requiresFrontmatter(path)
32
+ ? 'Этот файл wiki должен начинаться frontmatter: строки key: value между ---.'
33
+ : 'Frontmatter не разобран: допустимы строки key: value, комментарии # и списки «- item» под ключом.', path));
34
+ }
27
35
  for (const match of text.matchAll(/\[[^\]]*\]\((?:<([^>]+)>|([^\s)]+))(?:\s+['"][^'"]*['"])?\)/g)) {
28
36
  const destination = (match[1] ?? match[2] ?? '').split('#')[0]?.trim();
29
37
  if (!destination || /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(destination))
@@ -37,8 +45,9 @@ export async function checkWiki(root, findings) {
37
45
  continue;
38
46
  }
39
47
  const target = resolve(dirname(absolute), raw);
40
- if (target !== wiki && !target.startsWith(`${wiki}${sep}`))
41
- findings.push(error('wiki-link-outside', `Локальная wiki-ссылка выходит за пределы wiki: ${destination}`, path));
48
+ // Ссылка на код или протоколы проекта законна; наружу проекта — нет.
49
+ if (target !== projectRoot && !target.startsWith(`${projectRoot}${sep}`))
50
+ findings.push(error('wiki-link-outside', `Локальная wiki-ссылка выходит за пределы проекта: ${destination}`, path));
42
51
  else if (!existsSync(target))
43
52
  findings.push(error('wiki-link-broken', `Битая локальная wiki-ссылка: ${destination}`, path));
44
53
  }
@@ -87,8 +96,10 @@ export async function checkWiki(root, findings) {
87
96
  if (hot !== undefined) {
88
97
  const declared = frontmatter(hot)?.active_progress;
89
98
  const expected = active.length === 0 ? 'none' : active.length === 1 ? active[0] : null;
90
- if (expected === null || declared !== expected)
91
- findings.push(error('hot-active-progress-mismatch', 'Contract: hot.md active_progress должен быть none либо путём единственного progress с status: active.', 'wiki/hot.md'));
99
+ if (expected === null || declared !== expected) {
100
+ const hint = expected === null ? ` Сейчас status: active у нескольких записей: ${active.join(', ')}.` : ` Ожидается active_progress: ${expected} (путь от wiki/, без «wiki/»).`;
101
+ findings.push(error('hot-active-progress-mismatch', `Contract: hot.md active_progress должен быть none либо путём единственного progress с status: active.${hint}`, 'wiki/hot.md'));
102
+ }
92
103
  }
93
104
  return decoded;
94
105
  }
package/dist/core/init.js CHANGED
@@ -1,15 +1,16 @@
1
1
  import { execFile } from 'node:child_process';
2
2
  import { existsSync } from 'node:fs';
3
- import { lstat, mkdir, readdir, readFile, stat, writeFile } from 'node:fs/promises';
3
+ import { lstat, mkdir, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
4
4
  import { basename, dirname, join, parse, resolve } from 'node:path';
5
5
  import { promisify } from 'node:util';
6
6
  import { describeFsError } from './fs-errors.js';
7
7
  import { mergeGitignore, REQUIRED_GITIGNORE_ENTRIES } from './gitignore.js';
8
8
  import { CREATE_COMMAND, quotePathArg, serviceInvocation, VERSION } from './meta.js';
9
- import { CHECKSUMS_PATH, contentChecksum, loadChecksums, MAESTRO_DIR, MANIFEST_PATH, buildManifest, isCanonicalManifest, loadManifest, writeChecksums, writeManifest, } from './manifest.js';
9
+ import { CHECKSUMS_PATH, CREATING_MARKER_PATH, normalizeEol, contentChecksum, loadChecksums, MAESTRO_DIR, MANIFEST_PATH, buildManifest, isCanonicalManifest, loadManifest, writeChecksums, writeManifest, } from './manifest.js';
10
10
  import { DEPTHS } from './manifest.js';
11
11
  import { normalizeTarget, readPackageJson, templatesDir } from './paths.js';
12
12
  import { renderTemplate } from './template.js';
13
+ import { recoverTemplateVars, templateUses } from './template-recover.js';
13
14
  import { canonicalOwnershipInventory, CONTENT_OWNED_FILES, lazyDirsForDepth, TEMPLATE_FILES } from './inventory.js';
14
15
  import { canonicalizeSystemTempPrefix, onDiskBasename } from './platform-paths.js';
15
16
  import { compareVersions } from './version.js';
@@ -104,6 +105,39 @@ async function findAncestorSymlink(target) {
104
105
  }
105
106
  return null;
106
107
  }
108
+ /**
109
+ * Подстановки существующего проекта (отображаемое имя, дата создания) по его же
110
+ * неизменённым managed-файлам. Версия та же, что у пакета (create не работает с
111
+ * проектами других версий), поэтому источник — текущие шаблоны. Файл, изменённый
112
+ * пользователем, не используется: восстановление по нему было бы угадыванием.
113
+ */
114
+ async function recoverProjectVars(target, startingPoint, checksums) {
115
+ const found = {};
116
+ for (const relativePath of TEMPLATE_FILES) {
117
+ if (relativePath === GITATTRIBUTES_PATH || checksums[relativePath] === undefined)
118
+ continue;
119
+ // Шаблоны пакета на Windows могут прийти с CRLF, а файлы проекта всегда пишутся с LF.
120
+ const source = normalizeEol(await readTemplate(relativePath));
121
+ const uses = templateUses(source);
122
+ if ((!uses.projectName || found.projectName !== undefined) && (!uses.date || found.date !== undefined))
123
+ continue;
124
+ let actual;
125
+ try {
126
+ actual = await readFile(join(target, relativePath), 'utf8');
127
+ }
128
+ catch {
129
+ continue;
130
+ }
131
+ if (contentChecksum(relativePath, actual) !== checksums[relativePath])
132
+ continue;
133
+ const vars = recoverTemplateVars(source, actual, startingPoint, VERSION);
134
+ if (vars === null)
135
+ continue;
136
+ found.projectName ??= vars.projectName;
137
+ found.date ??= vars.date;
138
+ }
139
+ return found;
140
+ }
107
141
  /**
108
142
  * Готовит Git, не присваивая чужую работу.
109
143
  *
@@ -114,7 +148,7 @@ async function findAncestorSymlink(target) {
114
148
  * никогда git add -A;
115
149
  * - локальная идентичность настраивается только когда репозиторий создаём мы сами.
116
150
  */
117
- async function initGitRepository(target, ownedPaths, warnings) {
151
+ async function initGitRepository(target, ownedPaths, warnings, writtenPaths) {
118
152
  try {
119
153
  const repositoryExisted = existsSync(join(target, '.git'));
120
154
  if (!repositoryExisted) {
@@ -131,7 +165,11 @@ async function initGitRepository(target, ownedPaths, warnings) {
131
165
  }
132
166
  }
133
167
  if (repositoryExisted) {
134
- warnings.push('Репозиторий Git уже существовал: index не изменён и commit не создан — добавьте файлы Maestro вручную.');
168
+ // Добавлять нечего — и подсказывать нечего.
169
+ if (writtenPaths.length > 0) {
170
+ const shown = writtenPaths.slice(0, 5).map((path) => quotePathArg(path)).join(' ');
171
+ warnings.push(`Репозиторий Git уже существовал: index не изменён и commit не создан. Добавьте записанные файлы сами: git add ${shown}${writtenPaths.length > 5 ? ' …' : ''}`);
172
+ }
135
173
  return;
136
174
  }
137
175
  // Только наши пути в новом репозитории. Пакетами, чтобы не упереться в лимит длины командной строки.
@@ -204,6 +242,9 @@ async function initProjectAt(target, options, progress) {
204
242
  }
205
243
  }
206
244
  }
245
+ if (existsSync(join(target, CREATING_MARKER_PATH))) {
246
+ return failure(target, options.name ?? basename(target), `Прошлый запуск create в этой папке был прерван: осталась метка ${CREATING_MARKER_PATH}, файлы Maestro могут быть неполными. Если папка была новой — удалите её целиком и запустите create заново; если в ней есть ваши файлы — сначала проверьте git status.`);
247
+ }
207
248
  let previousManifest = null;
208
249
  if (existsSync(join(target, MANIFEST_PATH))) {
209
250
  try {
@@ -218,11 +259,11 @@ async function initProjectAt(target, options, progress) {
218
259
  // Create не меняет версию проекта ни вверх, ни вниз: для этого есть upgrade с проверкой каждого файла.
219
260
  const newer = (compareVersions(projectVersion, VERSION) ?? -1) > 0;
220
261
  return failure(target, options.name ?? basename(target), newer
221
- ? `Это проект Vibe Coding Maestro более новой версии ${projectVersion}, а create — версии ${VERSION}. Create не меняет версию проекта; проверка: ${serviceInvocation(projectVersion)} doctor --path ${quotePathArg(target)}.`
222
- : `Это проект Vibe Coding Maestro версии ${projectVersion}, а create — версии ${VERSION}. Create не обновляет проекты; используйте ${serviceInvocation(VERSION)} upgrade --path ${quotePathArg(target)} (без --apply только показывает изменения).`);
262
+ ? `Это проект Vibe Coding Maestro более новой версии ${projectVersion}, а create — версии ${VERSION}. Create не меняет версию проекта; проверка: \`${serviceInvocation(projectVersion)} doctor --path ${quotePathArg(target)}\`.`
263
+ : `Это проект Vibe Coding Maestro версии ${projectVersion}, а create — версии ${VERSION}. Create не обновляет проекты; используйте \`${serviceInvocation(VERSION)} upgrade --path ${quotePathArg(target)}\` (без --apply только показывает изменения).`);
223
264
  }
265
+ // Личность проекта — project.id: клон или переименованная папка остаются тем же проектом.
224
266
  if (!isCanonicalManifest(previousManifest)
225
- || previousManifest.project.name !== onDiskBasename(target)
226
267
  || !(await hasCompleteCanonicalTree(target, previousManifest))) {
227
268
  return failure(target, options.name ?? basename(target), `Папка не является каноническим проектом Vibe Coding Maestro: ${target}. Core не преобразует foreign или неполные проекты; используйте новую пустую папку.`);
228
269
  }
@@ -236,8 +277,9 @@ async function initProjectAt(target, options, progress) {
236
277
  * - в манифесте проект опознаётся по имени папки (идентичность на диске);
237
278
  * - отображаемое название в документах берётся из --name, иначе из имени папки.
238
279
  */
239
- const folderName = onDiskBasename(target);
240
- const displayName = options.name ?? folderName;
280
+ // Unicode приводится к NFC: одно и то же имя, набранное на macOS и на Linux, совпадает.
281
+ const folderName = onDiskBasename(target).normalize('NFC');
282
+ const displayName = (options.name ?? folderName).normalize('NFC');
241
283
  // Параметры существующего проекта не переписываются: манифест должен остаться стабильным.
242
284
  const projectName = previousManifest?.project.name ?? folderName;
243
285
  const startingPoint = previousManifest?.project.startingPoint ?? options.startingPoint;
@@ -249,6 +291,12 @@ async function initProjectAt(target, options, progress) {
249
291
  const preservedFiles = [];
250
292
  const mergedFiles = [];
251
293
  const warnings = [];
294
+ if (isExistingProject && options.requested?.depth !== undefined && options.requested.depth !== depth) {
295
+ warnings.push(`У проекта глубина ${depth}; --depth ${options.requested.depth} не применён: create не меняет параметры готового проекта.`);
296
+ }
297
+ if (isExistingProject && options.requested?.startingPoint !== undefined && options.requested.startingPoint !== startingPoint) {
298
+ warnings.push(`У проекта исходная точка ${startingPoint}; --start ${options.requested.startingPoint} не применён: create не меняет параметры готового проекта.`);
299
+ }
252
300
  const previousChecksums = (await loadChecksums(target))?.files ?? {};
253
301
  const nextChecksums = {};
254
302
  const managed = [];
@@ -263,7 +311,16 @@ async function initProjectAt(target, options, progress) {
263
311
  progress.existingProject = isExistingProject;
264
312
  progress.started = true;
265
313
  await mkdir(join(target, MAESTRO_DIR), { recursive: true });
266
- const vars = { projectName: displayName, date: isoDate(now), startingPoint };
314
+ // Метка ставится до первой записи и снимается после последней: прерванный create виден.
315
+ if (!isExistingProject)
316
+ await writeFile(join(target, CREATING_MARKER_PATH), `${now.toISOString()}\n`, 'utf8');
317
+ // Повторный запуск не переписывает подстановки: имя и дату берём из неизменённых файлов проекта.
318
+ const recovered = isExistingProject ? await recoverProjectVars(target, startingPoint, previousChecksums) : {};
319
+ const vars = {
320
+ projectName: options.name === undefined ? recovered.projectName ?? displayName : displayName,
321
+ date: recovered.date ?? isoDate(now),
322
+ startingPoint,
323
+ };
267
324
  /**
268
325
  * Записывает managed-файл, если его нет; сохраняет содержимое, если пользователь его изменил.
269
326
  *
@@ -369,8 +426,11 @@ async function initProjectAt(target, options, progress) {
369
426
  await writeManifest(target, manifest);
370
427
  await writeChecksums(target, nextChecksums);
371
428
  if (options.git === true) {
372
- await initGitRepository(target, ownedPaths, warnings);
429
+ await initGitRepository(target, ownedPaths, warnings, [...createdFiles, ...mergedFiles]);
373
430
  }
431
+ // Метка снимается последней: убитый на любом шаге, включая Git, create остаётся виден.
432
+ if (!isExistingProject)
433
+ await rm(join(target, CREATING_MARKER_PATH), { force: true });
374
434
  return {
375
435
  ok: true,
376
436
  target,
@@ -1,8 +1,6 @@
1
1
  /** Доверенный inventory обязательных системных путей, поставляемый с этой версией пакета. */
2
2
  export const TEMPLATE_FILES = [
3
- 'CLAUDE.md',
4
- 'AGENTS.md',
5
- 'wiki/index.md',
3
+ '.claude/rules/maestro.md',
6
4
  'wiki/plans/README.md',
7
5
  'wiki/plans/TEMPLATE.md',
8
6
  'maestro/inbox/README.md',
@@ -15,6 +13,10 @@ export const TEMPLATE_FILES = [
15
13
  '.claude/commands/handoff.md',
16
14
  '.claude/commands/plan.md',
17
15
  '.claude/agents/code-reviewer.md',
16
+ '.claude/agents/explorer.md',
17
+ 'maestro/templates/handoff.md',
18
+ 'maestro/templates/adr.md',
19
+ 'maestro/templates/progress.md',
18
20
  '.gitattributes',
19
21
  'protocols/build.md',
20
22
  'protocols/status.md',
@@ -35,6 +37,11 @@ export const TEMPLATE_FILES = [
35
37
  ];
36
38
  /** Стартовые содержательные документы: Maestro создаёт, затем ими владеет проект. */
37
39
  export const CONTENT_OWNED_FILES = [
40
+ 'CLAUDE.md',
41
+ 'AGENTS.md',
42
+ '.claude/rules/project.md',
43
+ '.claude/settings.json',
44
+ 'wiki/index.md',
38
45
  'wiki/hot.md',
39
46
  'wiki/log.md',
40
47
  'wiki/roadmap.md',
@@ -8,6 +8,8 @@ import { readPackageJson } from './paths.js';
8
8
  export const MAESTRO_DIR = '.maestro';
9
9
  export const MANIFEST_PATH = `${MAESTRO_DIR}/manifest.json`;
10
10
  export const CHECKSUMS_PATH = `${MAESTRO_DIR}/checksums.json`;
11
+ /** Метка незавершённого create: появляется до первой записи и исчезает после последней. */
12
+ export const CREATING_MARKER_PATH = `${MAESTRO_DIR}/creating`;
11
13
  export const DEPTHS = ['light', 'standard', 'advanced'];
12
14
  export function sha256(data) {
13
15
  return createHash('sha256').update(data).digest('hex');
package/dist/core/plan.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { createHash } from 'node:crypto';
1
2
  /**
2
3
  * Канонический контракт plan-документа 0.3 (Planning Gate, Phase 0).
3
4
  *
@@ -25,6 +26,43 @@ export const PLAN_REQUIRED_KEYS = [
25
26
  ];
26
27
  /** Общие для wiki поля документа: допустимы, но контрактом плана не управляются. */
27
28
  export const PLAN_OPTIONAL_KEYS = ['type', 'title'];
29
+ /**
30
+ * Отпечаток утверждения: sha256 текста плана без frontmatter. Необязателен
31
+ * (планы до 0.3.0 его не имеют); если записан, расхождение закрывает гейт.
32
+ */
33
+ export const PLAN_APPROVAL_DIGEST_KEY = 'approved_digest';
34
+ /**
35
+ * Поля frontmatter, которые описывают, ЧТО утверждено: их смена — новая граница плана.
36
+ * Состояние работы (status, current_slice, active_phase, даты, поля гейта) сюда не входит:
37
+ * его меняет сама работа, и гейт не должен закрываться от каждого шага.
38
+ */
39
+ export const PLAN_DIGEST_KEYS = ['id', 'kind', 'scale', 'mode', 'governance', 'risk', 'profiles', 'sources', 'supersedes'];
40
+ /** sha256 утверждённого: классификация из frontmatter плюс текст плана (LF, без хвостовых пробелов). */
41
+ export function planBodyDigest(text) {
42
+ const match = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(text);
43
+ const meta = match ? frontmatterValues(match[1] ?? '') : {};
44
+ 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();
46
+ return createHash('sha256').update(`${classification}\n---\n${body}`).digest('hex');
47
+ }
48
+ /** Значения key: value для отпечатка; полный разбор с проверками живёт в doctor/text.ts. */
49
+ function frontmatterValues(block) {
50
+ const values = {};
51
+ let listKey = null;
52
+ for (const line of block.split(/\r?\n/)) {
53
+ const listItem = /^\s+-\s+(.*?)\s*$/.exec(line);
54
+ if (listItem && listKey !== null) {
55
+ values[listKey] = `${values[listKey] ?? ''}${values[listKey] ? ', ' : ''}${listItem[1] ?? ''}`;
56
+ continue;
57
+ }
58
+ const item = /^([a-z][a-z0-9_]*):\s*(.*?)\s*$/.exec(line);
59
+ if (!item || !item[1])
60
+ continue;
61
+ listKey = item[2] ? null : item[1];
62
+ values[item[1]] = (item[2] ?? '').replace(/\s+#.*$/, '').replace(/^(["'])(.*)\1$/, '$2').replace(/^\[(.*)\]$/, '$1').replace(/\s*,\s*/g, ', ');
63
+ }
64
+ return values;
65
+ }
28
66
  /**
29
67
  * Машиночитаемые поля build gate.
30
68
  *
@@ -179,7 +217,7 @@ function dateField(meta, field, issues) {
179
217
  */
180
218
  export function validatePlanFrontmatter(meta) {
181
219
  const issues = [];
182
- const allowed = new Set([...PLAN_REQUIRED_KEYS, ...PLAN_OPTIONAL_KEYS, ...PLAN_GATE_KEYS]);
220
+ const allowed = new Set([...PLAN_REQUIRED_KEYS, ...PLAN_OPTIONAL_KEYS, ...PLAN_GATE_KEYS, PLAN_APPROVAL_DIGEST_KEY]);
183
221
  for (const key of PLAN_REQUIRED_KEYS) {
184
222
  if (!(key in meta))
185
223
  issues.push(issue('plan-schema-invalid', key, `Обязательное поле плана отсутствует: ${key}.`));
@@ -211,6 +249,7 @@ export function validatePlanFrontmatter(meta) {
211
249
  const specDelta = enumField(meta, 'spec_delta', PLAN_SPEC_DELTAS, issues);
212
250
  const currentSlice = nullableField(meta, 'current_slice', (value) => ACTIVE_PHASE_TOKEN.test(value), 'допустимо null или идентификатор порции', issues);
213
251
  const currentPhaseApproved = enumField(meta, 'current_phase_approved', PLAN_PHASE_APPROVALS, issues);
252
+ const approvedDigest = nullableField(meta, PLAN_APPROVAL_DIGEST_KEY, (value) => /^[0-9a-f]{64}$/.test(value), 'допустимо null или sha256 из строки «Отпечаток плана» вывода preflight', issues);
214
253
  if (status !== null && approvedBy !== null && approvedAt !== null) {
215
254
  const hasApproval = approvedBy.value !== null && approvedAt.value !== null;
216
255
  if (APPROVAL_REQUIRED_STATUSES.includes(status) && !hasApproval) {
@@ -253,6 +292,8 @@ export function validatePlanFrontmatter(meta) {
253
292
  specDelta,
254
293
  currentSlice: currentSlice === null ? null : currentSlice.value,
255
294
  currentPhaseApproved: currentPhaseApproved === null ? null : currentPhaseApproved === 'yes',
295
+ approvedDigest: approvedDigest === null ? null : approvedDigest.value,
296
+ currentSliceDeclared: currentSlice !== null,
256
297
  },
257
298
  issues,
258
299
  };
@@ -15,11 +15,11 @@
15
15
  * ничего не запускает и ничего не пишет.
16
16
  */
17
17
  import { existsSync, statSync } from 'node:fs';
18
- import { readFile } from 'node:fs/promises';
18
+ 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, isWikiRelativePlanRef, validatePlanFrontmatter, PLAN_SCALES, } from './plan.js';
22
+ import { ACTIVE_PLAN_NONE, APPROVAL_REQUIRED_STATUSES, isWikiRelativePlanRef, planBodyDigest, validatePlanFrontmatter, PLAN_SCALES, } from './plan.js';
23
23
  export const HOT_PATH = 'wiki/hot.md';
24
24
  /**
25
25
  * Явные критерии исключения для QUICK.
@@ -42,6 +42,7 @@ const decision = (patch) => ({
42
42
  plan: null,
43
43
  slice: null,
44
44
  exception: null,
45
+ planDigest: null,
45
46
  findings: [],
46
47
  ...patch,
47
48
  });
@@ -59,9 +60,11 @@ export function decideBuildPreflight(state, request) {
59
60
  return decision({ findings: [finding('block', 'preflight-quick-criteria-unknown', `Неизвестные критерии QUICK: ${unknown.join(', ')}. Допустимы: ${QUICK_CRITERIA.join(', ')}.`)] });
60
61
  }
61
62
  if (request.scale !== 'quick') {
62
- return decision({
63
- findings: [finding('block', 'preflight-plan-absent', `Активного плана нет, а масштаб работы ${request.scale} требует утверждённого плана. Маршрут: protocols/plan.md.`, HOT_PATH)],
64
- });
63
+ const approved = state.approvedPlans ?? [];
64
+ const message = approved.length > 0
65
+ ? `Утверждённый план есть, но не объявлен: запишите active_plan: ${approved[0].slice('wiki/'.length)} в wiki/hot.md (protocols/plan.md, Stage G) и повторите проверку.`
66
+ : `Активного плана нет, а масштаб работы ${request.scale} требует утверждённого плана. Маршрут: protocols/plan.md.`;
67
+ return decision({ findings: [finding('block', 'preflight-plan-absent', message, HOT_PATH)] });
65
68
  }
66
69
  const missing = QUICK_CRITERIA.filter((item) => !(request.quickCriteria ?? []).includes(item));
67
70
  if (missing.length > 0) {
@@ -93,27 +96,31 @@ export function decideBuildPreflight(state, request) {
93
96
  findings: validation.issues.map((issue) => finding('block', 'preflight-plan-invalid', `${issue.field}: ${issue.message}`, state.planPath ?? undefined)),
94
97
  });
95
98
  }
96
- return decideForPlan(validation.plan, state.planPath);
99
+ return decideForPlan(validation.plan, state.planPath, planBodyDigest(state.planText));
97
100
  }
98
- function decideForPlan(plan, planPath) {
101
+ function decideForPlan(plan, planPath, digest) {
99
102
  const findings = [];
100
103
  const at = (code, message) => { findings.push(finding('block', code, message, planPath)); };
101
104
  let route = 'plan';
102
105
  if (plan.status !== 'approved' && plan.status !== 'active') {
103
106
  at('preflight-plan-not-approved', `Статус плана ${plan.status}: код по неутверждённому плану не пишется.`);
104
- return decision({ plan: planPath, route, findings });
107
+ return decision({ plan: planPath, route, planDigest: digest, findings });
105
108
  }
106
109
  if (plan.approvedBy === null || plan.approvedAt === null) {
107
110
  route = 'human';
108
111
  at('preflight-approval-missing', 'У утверждённого плана нет следа человеческого решения.');
109
- return decision({ plan: planPath, route, findings });
112
+ return decision({ plan: planPath, route, planDigest: digest, findings });
113
+ }
114
+ if (plan.approvedDigest !== null && plan.approvedDigest !== digest) {
115
+ at('preflight-plan-changed', 'Текст плана изменился после утверждения: покажите изменения человеку; после повторного «план утверждаю» запишите в approved_digest новый отпечаток.');
116
+ return decision({ plan: planPath, route: 'human', planDigest: digest, findings });
110
117
  }
111
118
  const missing = [];
112
119
  if (plan.blockingQuestions === null)
113
120
  missing.push('blocking_questions');
114
121
  if (plan.specDelta === null)
115
122
  missing.push('spec_delta');
116
- if (plan.currentSlice === null)
123
+ if (!plan.currentSliceDeclared)
117
124
  missing.push('current_slice');
118
125
  if (plan.kind === 'program' && plan.currentPhaseApproved === null)
119
126
  missing.push('current_phase_approved');
@@ -121,6 +128,10 @@ function decideForPlan(plan, planPath) {
121
128
  at('preflight-gate-fields-missing', `План не объявляет обязательные для build поля: ${missing.join(', ')}. Необъявленное считается неизвестным.`);
122
129
  return decision({ plan: planPath, route, findings });
123
130
  }
131
+ if (plan.currentSlice === null) {
132
+ at('preflight-slice-closed', 'Порция не выбрана (current_slice: null): прошлая закрыта. Следующую порцию выбирают вместе с человеком и записывают в current_slice.');
133
+ return decision({ plan: planPath, route: 'human', planDigest: digest, findings });
134
+ }
124
135
  if ((plan.blockingQuestions ?? 0) > 0) {
125
136
  route = 'human';
126
137
  at('preflight-blocking-questions', `Открытых блокирующих вопросов: ${plan.blockingQuestions}. Их закрывает человек, а не агент.`);
@@ -138,14 +149,19 @@ function decideForPlan(plan, planPath) {
138
149
  }
139
150
  }
140
151
  const blocked = findings.some((item) => item.level === 'block');
152
+ const allowed = [
153
+ finding('info', 'preflight-slice-selected', `Разрешена ровно одна порция: ${plan.currentSlice}. Остановка на её стоп-гейте обязательна.`, planPath),
154
+ ];
155
+ if (plan.approvedDigest === null) {
156
+ allowed.push(finding('info', 'preflight-digest-missing', 'Отпечаток утверждения не записан: правку текста плана после утверждения гейт не заметит. Запишите в approved_digest строку «Отпечаток плана».', planPath));
157
+ }
141
158
  return decision({
142
159
  ok: !blocked,
143
160
  route: blocked ? route : 'build',
144
161
  plan: planPath,
145
162
  slice: blocked ? null : plan.currentSlice,
146
- findings: blocked ? findings : [
147
- finding('info', 'preflight-slice-selected', `Разрешена ровно одна порция: ${plan.currentSlice}. Остановка на её стоп-гейте обязательна.`, planPath),
148
- ],
163
+ planDigest: digest,
164
+ findings: blocked ? findings : allowed,
149
165
  });
150
166
  }
151
167
  /** Читает состояние проекта. Ничего не пишет и ничего не исполняет. */
@@ -157,12 +173,30 @@ export async function inspectBuildPreflight(rootInput) {
157
173
  const meta = frontmatter(hotText);
158
174
  const declared = meta?.active_plan ?? ACTIVE_PLAN_NONE;
159
175
  if (declared === ACTIVE_PLAN_NONE)
160
- return { declared: null, planPath: null, planText: null, hotFound: true };
176
+ return { declared: null, planPath: null, planText: null, hotFound: true, approvedPlans: await approvedPlans(root) };
161
177
  if (!isWikiRelativePlanRef(declared))
162
178
  return { declared, planPath: null, planText: null, hotFound: true };
163
179
  const planPath = `wiki/${declared}`;
164
180
  return { declared, planPath, planText: await readText(join(root, planPath)), hotFound: true };
165
181
  }
182
+ /** Утверждённые планы в wiki/plans/ — только для подсказки «план есть, но не объявлен». */
183
+ async function approvedPlans(root) {
184
+ let names;
185
+ try {
186
+ names = (await readdir(join(root, 'wiki/plans'))).filter((name) => name.endsWith('.md') && name !== 'README.md' && name !== 'TEMPLATE.md').sort();
187
+ }
188
+ catch {
189
+ return [];
190
+ }
191
+ const found = [];
192
+ for (const name of names) {
193
+ const text = await readText(join(root, 'wiki/plans', name));
194
+ const status = text === null ? undefined : frontmatter(text)?.status;
195
+ if (status !== undefined && APPROVAL_REQUIRED_STATUSES.includes(status))
196
+ found.push(`wiki/plans/${name}`);
197
+ }
198
+ return found;
199
+ }
166
200
  async function readText(absolute) {
167
201
  try {
168
202
  return decodeUtf8(await readFile(absolute));
@@ -1,7 +1,5 @@
1
- import { lstat, opendir, open, readFile } from 'node:fs/promises';
1
+ import { lstat, opendir, open } from 'node:fs/promises';
2
2
  import { join, relative, resolve, sep } from 'node:path';
3
- import { tryLoadManifest } from './manifest.js';
4
- import { packageRoot } from './paths.js';
5
3
  export const SKILL_MAX_DEPTH = 4;
6
4
  export const SKILL_MAX_FILES = 200;
7
5
  export const SKILL_MAX_BYTES = 256 * 1024;
@@ -156,14 +154,6 @@ async function readBounded(path) {
156
154
  await handle.close();
157
155
  }
158
156
  }
159
- async function recommendations(root) {
160
- const registry = JSON.parse(await readFile(join(packageRoot(), 'registry/trusted-skills.v1.json'), 'utf8'));
161
- const startingPoint = (await tryLoadManifest(root))?.project.startingPoint;
162
- const items = startingPoint === undefined ? [] : registry.skills
163
- .filter((item) => item.startingPoints.includes(startingPoint)).slice(0, 5)
164
- .map(({ startingPoints: _, ...item }) => item);
165
- return { version: registry.version, items };
166
- }
167
157
  export async function scanSkills(projectPath) {
168
158
  const root = resolve(projectPath);
169
159
  const results = [];
@@ -187,6 +177,5 @@ export async function scanSkills(projectPath) {
187
177
  results.push({ code: 'frontmatter-malformed', level: 'warning', path: relativePath, message: parsed.warning });
188
178
  skills.push({ path: relativePath, frontmatter: parsed.value, status: parsed.warning ? 'warning' : 'ok' });
189
179
  }
190
- const trusted = await recommendations(root);
191
- return { registryVersion: trusted.version, installed: false, notice: 'ничего не установлено', skills, results, recommendations: trusted.items };
180
+ return { installed: false, notice: 'ничего не установлено', skills, results };
192
181
  }
@@ -0,0 +1,82 @@
1
+ import { normalizeEol } from './manifest.js';
2
+ import { renderTemplate } from './template.js';
3
+ /**
4
+ * Доказательство того, что файл на диске — это буквально прошлый канонический
5
+ * шаблон, а не похожий на него текст.
6
+ *
7
+ * Прямое сравнение контрольных сумм здесь невозможно: шаблон рендерится с
8
+ * подстановками (имя проекта, дата), поэтому у одного и того же canonical файла
9
+ * нет одной канонической суммы. Вместо ослабления проверки восстанавливаем
10
+ * подстановки и требуем побайтового совпадения повторного рендера. Совпадение
11
+ * доказывает preimage; несовпадение означает «файл изменён» и блокирует запись.
12
+ *
13
+ * Восстановление не может дать ложного «да»: любое найденное решение проверяется
14
+ * повторным рендером. Неоднозначный случай даёт null, то есть отказ.
15
+ */
16
+ /** Сентинелы содержат NUL: этот символ не может встретиться в тексте шаблона. */
17
+ const PROJECT_NAME_SENTINEL = '\u0000{PROJECT_NAME}\u0000';
18
+ const DATE_SENTINEL = '\u0000{DATE}\u0000';
19
+ const VERSION_SENTINEL = '\u0000{MAESTRO_VERSION}\u0000';
20
+ function escapeRegExp(value) {
21
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
22
+ }
23
+ /**
24
+ * Восстанавливает подстановки, при которых `source` рендерится ровно в `actual`.
25
+ *
26
+ * Возвращает null, если такого набора подстановок не существует.
27
+ */
28
+ export function recoverTemplateVars(source, actual, startingPoint, version) {
29
+ // Версия не восстанавливается, а берётся из manifest: файл обязан быть рендером
30
+ // ровно той версии, которая записала проект.
31
+ const shape = renderTemplate(source, {
32
+ projectName: PROJECT_NAME_SENTINEL,
33
+ date: DATE_SENTINEL,
34
+ startingPoint,
35
+ version,
36
+ });
37
+ const parts = shape.split(new RegExp(`(${escapeRegExp(PROJECT_NAME_SENTINEL)}|${escapeRegExp(DATE_SENTINEL)})`));
38
+ const groups = [];
39
+ let pattern = '';
40
+ for (const part of parts) {
41
+ if (part === PROJECT_NAME_SENTINEL || part === DATE_SENTINEL) {
42
+ const name = part === PROJECT_NAME_SENTINEL ? 'projectName' : 'date';
43
+ const first = groups.indexOf(name);
44
+ // Повторное вхождение той же переменной обязано совпасть буквально.
45
+ pattern += first === -1 ? '([^\\r\\n]*?)' : `\\${first + 1}`;
46
+ if (first === -1)
47
+ groups.push(name);
48
+ continue;
49
+ }
50
+ pattern += escapeRegExp(part);
51
+ }
52
+ const match = new RegExp(`^${pattern}$`).exec(normalizeEol(actual));
53
+ if (match === null)
54
+ return null;
55
+ const recovered = {};
56
+ groups.forEach((name, index) => {
57
+ recovered[name] = match[index + 1] ?? '';
58
+ });
59
+ // Единственный авторитет — повторный рендер. Всё, что не совпало побайтово,
60
+ // считается изменённым файлом.
61
+ const vars = {
62
+ projectName: recovered.projectName ?? '',
63
+ date: recovered.date ?? '',
64
+ startingPoint,
65
+ version,
66
+ };
67
+ return normalizeEol(renderTemplate(source, vars)) === normalizeEol(actual) ? recovered : null;
68
+ }
69
+ /** Плейсхолдеры, которые шаблон реально использует: нерасшифрованную переменную нельзя угадывать. */
70
+ export function templateUses(source) {
71
+ const probe = renderTemplate(source, {
72
+ projectName: PROJECT_NAME_SENTINEL,
73
+ date: DATE_SENTINEL,
74
+ startingPoint: 'idea',
75
+ version: VERSION_SENTINEL,
76
+ });
77
+ return {
78
+ projectName: probe.includes(PROJECT_NAME_SENTINEL),
79
+ date: probe.includes(DATE_SENTINEL),
80
+ version: probe.includes(VERSION_SENTINEL),
81
+ };
82
+ }