create-vibe-maestro 0.4.2 → 0.4.4
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.
- package/CHANGELOG.md +92 -0
- package/README.md +11 -11
- package/dist/cli/archive-run.js +75 -0
- package/dist/cli/context-run.js +10 -0
- package/dist/cli/maestro.js +46 -4
- package/dist/cli/pack-run.js +42 -3
- package/dist/cli/upgrade-run.js +44 -5
- package/dist/core/archive/audits.js +37 -0
- package/dist/core/archive/disk.js +38 -0
- package/dist/core/archive/index.js +286 -0
- package/dist/core/archive/limits.js +27 -0
- package/dist/core/archive/links.js +65 -0
- package/dist/core/archive/log.js +83 -0
- package/dist/core/archive/markdown.js +28 -0
- package/dist/core/archive/plan.js +183 -0
- package/dist/core/archive/types.js +1 -0
- package/dist/core/audits.js +37 -0
- package/dist/core/context.js +47 -2
- package/dist/core/doctor/fs-utils.js +3 -2
- package/dist/core/doctor/index.js +5 -2
- package/dist/core/doctor/memory.js +52 -0
- package/dist/core/doctor/plans.js +4 -4
- package/dist/core/doctor/wiki.js +9 -33
- package/dist/core/gitignore.js +3 -1
- package/dist/core/inventory.js +2 -10
- package/dist/core/pack.js +130 -12
- package/dist/core/plan.js +43 -2
- package/dist/core/preflight.js +6 -5
- package/dist/core/template.js +2 -1
- package/dist/core/text-diff.js +108 -0
- package/dist/core/transaction.js +132 -0
- package/dist/core/upgrade/analyze.js +82 -5
- package/dist/core/upgrade/baseline.js +12 -0
- package/dist/core/upgrade/index.js +31 -87
- package/dist/core/upgrade/releases.js +143 -2
- package/dist/core/wiki-links.js +27 -0
- package/docs/ROADMAP.md +8 -4
- package/docs/USER_GUIDE.md +117 -35
- package/package.json +1 -1
- package/registry/baseline/0.4.2/project/.claude/agents/code-reviewer.md +13 -0
- package/registry/baseline/0.4.2/project/.claude/rules/maestro.md +37 -0
- package/registry/baseline/0.4.2/project/maestro/runbooks/cowork-audit.md +11 -0
- package/registry/baseline/0.4.2/project/maestro/templates/handoff.md +25 -0
- package/registry/baseline/0.4.2/project/protocols/audit.md +5 -0
- package/registry/baseline/0.4.2/project/protocols/build.md +18 -0
- package/registry/baseline/0.4.2/project/protocols/completion.md +22 -0
- package/registry/baseline/0.4.2/project/protocols/handoff.md +15 -0
- package/registry/baseline/0.4.2/project/protocols/plan.md +149 -0
- package/registry/baseline/0.4.2/project/protocols/start.md +64 -0
- package/registry/baseline/0.4.2/project/protocols/wiki.md +9 -0
- package/registry/baseline/0.4.2/project/wiki/plans/README.md +131 -0
- package/registry/baseline/0.4.2/project/wiki/plans/TEMPLATE.md +75 -0
- package/registry/baseline/0.4.3/project/.claude/rules/maestro.md +40 -0
- package/registry/baseline/0.4.3/project/maestro/templates/handoff.md +29 -0
- package/registry/baseline/0.4.3/project/protocols/build.md +120 -0
- package/registry/baseline/0.4.3/project/protocols/completion.md +23 -0
- package/registry/baseline/0.4.3/project/protocols/handoff.md +17 -0
- package/registry/baseline/0.4.3/project/protocols/plan.md +159 -0
- package/registry/baseline/0.4.3/project/protocols/status.md +5 -0
- package/registry/baseline/0.4.3/project/protocols/wiki.md +17 -0
- package/registry/baseline/0.4.3/project/wiki/plans/README.md +135 -0
- package/registry/baseline/0.4.3/project/wiki/plans/TEMPLATE.md +83 -0
- package/registry/capabilities.v1.json +19 -19
- package/templates/project/.claude/agents/code-reviewer.md +18 -7
- package/templates/project/.claude/rules/maestro.md +7 -3
- package/templates/project/.claude/settings.json +1 -0
- package/templates/project/maestro/runbooks/cowork-audit.md +9 -2
- package/templates/project/maestro/templates/audit.md +31 -0
- package/templates/project/maestro/templates/handoff.md +6 -2
- package/templates/project/protocols/audit.md +70 -1
- package/templates/project/protocols/build.md +111 -9
- package/templates/project/protocols/completion.md +8 -7
- package/templates/project/protocols/handoff.md +7 -4
- package/templates/project/protocols/plan.md +34 -23
- package/templates/project/protocols/start.md +1 -1
- package/templates/project/protocols/status.md +1 -1
- package/templates/project/protocols/wiki.md +10 -2
- package/templates/project/wiki/icebox.md +12 -0
- package/templates/project/wiki/index.md +5 -0
- package/templates/project/wiki/log.md +1 -0
- package/templates/project/wiki/passport.md +1 -1
- package/templates/project/wiki/plans/0001-starter.md +15 -4
- package/templates/project/wiki/plans/README.md +27 -3
- package/templates/project/wiki/plans/TEMPLATE.md +23 -6
- /package/{templates → registry/baseline/0.4.2}/project/protocols/build/audit-phase.md +0 -0
- /package/{templates → registry/baseline/0.4.2}/project/protocols/build/audit-plan.md +0 -0
- /package/{templates → registry/baseline/0.4.2}/project/protocols/build/step-1-rules.md +0 -0
- /package/{templates → registry/baseline/0.4.2}/project/protocols/build/step-2-spec.md +0 -0
- /package/{templates → registry/baseline/0.4.2}/project/protocols/build/step-3-architecture.md +0 -0
- /package/{templates → registry/baseline/0.4.2}/project/protocols/build/step-5-feature-loop.md +0 -0
- /package/{templates → registry/baseline/0.4.2}/project/protocols/context-budget.md +0 -0
- /package/{templates → registry/baseline/0.4.2}/project/protocols/discovery.md +0 -0
- /package/{templates → registry/baseline/0.4.2}/project/protocols/lessons.md +0 -0
- /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
|
-
|
|
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
|
-
/**
|
|
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
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
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,53 @@ 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
|
-
/**
|
|
40
|
+
/** Отметка пункта списка `[x]` или `[X]`: в отпечатке она считается `[ ]`, а текст пункта — нет. */
|
|
41
|
+
const CHECKED_ITEM_RE = /^([ \t]*(?:[-*+]|\d+[.)])[ \t]+)\[[xX]\]/gm;
|
|
42
|
+
/**
|
|
43
|
+
* Строка итога закрытой порции: один хвост ` → [итог](../handoffs/<имя>.md)` в конце строки
|
|
44
|
+
* с `[x]`. Другой текст ссылки, другая папка, второй хвост, хвост у `[ ]` или на строке
|
|
45
|
+
* продолжения пункта — это уже текст плана.
|
|
46
|
+
*/
|
|
47
|
+
const RESULT_LINE_RE = /^([ \t]*(?:[-*+]|\d+[.)])[ \t]+)(\[[xX]\])(.*?) → \[итог\]\(\.\.\/handoffs\/[^\s()/]+\.md\)$/gm;
|
|
48
|
+
const clearMarks = (body) => body.replace(CHECKED_ITEM_RE, '$1[ ]');
|
|
49
|
+
/** Пробелы перед хвостом — конец строки пункта, а его пробелы в отпечаток не входят. */
|
|
50
|
+
const withoutResult = (body, mark) => body.replace(RESULT_LINE_RE, (_line, lead, checked, item) => `${lead}${mark(checked)}${item.replace(/[ \t]+$/, '')}`);
|
|
51
|
+
const dropResults = (body) => withoutResult(body, (checked) => checked);
|
|
52
|
+
const reopenResults = (body) => withoutResult(body, () => '[ ]');
|
|
53
|
+
/**
|
|
54
|
+
* sha256 утверждённого: классификация из frontmatter плюс текст плана (LF, без хвостовых
|
|
55
|
+
* пробелов). Отметки выполненных пунктов и строки итога не входят: закрыть порцию — не
|
|
56
|
+
* изменить план. Без строк итога отпечаток тот же, что в 0.4.3.
|
|
57
|
+
*/
|
|
41
58
|
export function planBodyDigest(text) {
|
|
59
|
+
return digest(text, (body) => clearMarks(dropResults(body)));
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Отпечаток 0.3.0–0.4.2, где отметки пунктов ещё входили в текст. Принимается, чтобы
|
|
63
|
+
* план, утверждённый раньше с отмеченными пунктами, без правок оставался зелёным.
|
|
64
|
+
*/
|
|
65
|
+
export function legacyPlanBodyDigest(text) {
|
|
66
|
+
return digest(text, (body) => body);
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Записанный отпечаток совпадает с планом — нынешним способом или одним из прежних.
|
|
70
|
+
* Строка итога не мешает ни одному: в отпечатке 0.3.0–0.4.2 отметки входят в текст, поэтому
|
|
71
|
+
* порция с итогом читается и как закрытая до утверждения, и как закрытая после него.
|
|
72
|
+
*/
|
|
73
|
+
export function planDigestMatches(approvedDigest, text) {
|
|
74
|
+
return [
|
|
75
|
+
planBodyDigest(text),
|
|
76
|
+
digest(text, clearMarks),
|
|
77
|
+
legacyPlanBodyDigest(text),
|
|
78
|
+
digest(text, dropResults),
|
|
79
|
+
digest(text, reopenResults),
|
|
80
|
+
].includes(approvedDigest);
|
|
81
|
+
}
|
|
82
|
+
function digest(text, normalizeBody) {
|
|
42
83
|
const match = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(text);
|
|
43
84
|
const meta = match ? frontmatterValues(match[1] ?? '') : {};
|
|
44
85
|
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();
|
|
86
|
+
const body = normalizeBody(text.slice(match ? match[0].length : 0).replace(/\r\n/g, '\n').replace(/[ \t]+$/gm, '').trim());
|
|
46
87
|
return createHash('sha256').update(`${classification}\n---\n${body}`).digest('hex');
|
|
47
88
|
}
|
|
48
89
|
/** Значения key: value для отпечатка; полный разбор с проверками живёт в doctor/text.ts. */
|
package/dist/core/preflight.js
CHANGED
|
@@ -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
|
-
|
|
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 &&
|
|
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 = [];
|
package/dist/core/template.js
CHANGED
|
@@ -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 =
|
|
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
|
+
}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { copyFile, mkdir, rename, rm, rmdir, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { dirname, join } from 'node:path';
|
|
4
|
+
/**
|
|
5
|
+
* Запись нескольких файлов проекта одной транзакцией: всё готовится в staging,
|
|
6
|
+
* прежние байты — в backup, сбой публикации откатывает уже сделанное.
|
|
7
|
+
*
|
|
8
|
+
* Общая для `upgrade` и `archive`: содержимое приходит байтами, поэтому
|
|
9
|
+
* переносы строк решает вызывающий (upgrade пишет Maestro с LF, archive
|
|
10
|
+
* переносит текст проекта как есть).
|
|
11
|
+
*/
|
|
12
|
+
/** Папка транзакции `upgrade`; `archive` не работает, пока она есть, и наоборот. */
|
|
13
|
+
export const UPGRADE_STAGING_DIR = '.maestro/upgrade-staging';
|
|
14
|
+
/** Папка транзакции `archive`. */
|
|
15
|
+
export const ARCHIVE_STAGING_DIR = '.maestro/archive-staging';
|
|
16
|
+
export const STAGING_DIRS = [UPGRADE_STAGING_DIR, ARCHIVE_STAGING_DIR];
|
|
17
|
+
/** Папки удалённых файлов, от глубоких к верхним: убираются, только если опустели. */
|
|
18
|
+
function parentDirs(paths) {
|
|
19
|
+
const dirs = new Set();
|
|
20
|
+
for (const path of paths) {
|
|
21
|
+
const parts = path.split('/').slice(0, -1);
|
|
22
|
+
for (let i = parts.length; i > 0; i -= 1)
|
|
23
|
+
dirs.add(parts.slice(0, i).join('/'));
|
|
24
|
+
}
|
|
25
|
+
return [...dirs].sort((a, b) => b.split('/').length - a.split('/').length || a.localeCompare(b));
|
|
26
|
+
}
|
|
27
|
+
/** Каталоги, которых ещё нет: только их можно удалить при откате. */
|
|
28
|
+
function missingDirs(root, relativePath) {
|
|
29
|
+
const parts = relativePath.split('/').slice(0, -1);
|
|
30
|
+
const created = [];
|
|
31
|
+
let current = '';
|
|
32
|
+
for (const part of parts) {
|
|
33
|
+
current = current === '' ? part : `${current}/${part}`;
|
|
34
|
+
if (!existsSync(join(root, current)))
|
|
35
|
+
created.push(current);
|
|
36
|
+
}
|
|
37
|
+
return created;
|
|
38
|
+
}
|
|
39
|
+
const message = (cause) => (cause instanceof Error ? cause.message : String(cause));
|
|
40
|
+
/**
|
|
41
|
+
* Гарантии:
|
|
42
|
+
* - всё содержимое готовится в staging до того, как затронут первый файл проекта;
|
|
43
|
+
* - staging создаётся без `recursive`: занятая папка (вторая транзакция) — отказ до записи;
|
|
44
|
+
* - сбой публикации откатывает уже опубликованные и удалённые пути из backup;
|
|
45
|
+
* - каталоги, созданные ради новых путей, при откате удаляются, только если пусты;
|
|
46
|
+
* - папка, которую опустошило удаление, уходит вместе с файлами.
|
|
47
|
+
*/
|
|
48
|
+
export async function applyTransaction(root, stagingDir, operations, hooks = {}) {
|
|
49
|
+
const staging = join(root, stagingDir);
|
|
50
|
+
const newDir = join(staging, 'new');
|
|
51
|
+
const backupDir = join(staging, 'backup');
|
|
52
|
+
const createdDirs = [];
|
|
53
|
+
for (const operation of operations) {
|
|
54
|
+
if (operation.action !== 'create')
|
|
55
|
+
continue;
|
|
56
|
+
for (const dir of missingDirs(root, operation.path))
|
|
57
|
+
if (!createdDirs.includes(dir))
|
|
58
|
+
createdDirs.push(dir);
|
|
59
|
+
}
|
|
60
|
+
try {
|
|
61
|
+
await mkdir(staging, { recursive: false });
|
|
62
|
+
}
|
|
63
|
+
catch (cause) {
|
|
64
|
+
// Чужую staging-папку не трогаем: её занятость и есть причина отказа.
|
|
65
|
+
return { ok: false, stage: 'prepare', reason: message(cause) };
|
|
66
|
+
}
|
|
67
|
+
try {
|
|
68
|
+
for (const operation of operations) {
|
|
69
|
+
if (operation.action !== 'remove') {
|
|
70
|
+
const target = join(newDir, operation.path);
|
|
71
|
+
await mkdir(dirname(target), { recursive: true });
|
|
72
|
+
await writeFile(target, operation.bytes ?? Buffer.alloc(0));
|
|
73
|
+
}
|
|
74
|
+
if (operation.action !== 'create') {
|
|
75
|
+
// Backup — точная копия байтов: откат возвращает обновлённый или удалённый файл таким, каким он был.
|
|
76
|
+
await mkdir(dirname(join(backupDir, operation.path)), { recursive: true });
|
|
77
|
+
await copyFile(join(root, operation.path), join(backupDir, operation.path));
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
catch (cause) {
|
|
82
|
+
await rm(staging, { recursive: true, force: true });
|
|
83
|
+
return { ok: false, stage: 'prepare', reason: message(cause) };
|
|
84
|
+
}
|
|
85
|
+
const committed = [];
|
|
86
|
+
try {
|
|
87
|
+
for (const operation of operations) {
|
|
88
|
+
if (hooks.beforeCommit !== undefined)
|
|
89
|
+
await hooks.beforeCommit(operation.path);
|
|
90
|
+
const target = join(root, operation.path);
|
|
91
|
+
if (operation.action === 'remove') {
|
|
92
|
+
await rm(target);
|
|
93
|
+
}
|
|
94
|
+
else {
|
|
95
|
+
await mkdir(dirname(target), { recursive: true });
|
|
96
|
+
await rename(join(newDir, operation.path), target);
|
|
97
|
+
}
|
|
98
|
+
committed.push(operation);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
catch (cause) {
|
|
102
|
+
const reason = message(cause);
|
|
103
|
+
const unrestored = [];
|
|
104
|
+
for (const operation of [...committed].reverse()) {
|
|
105
|
+
const target = join(root, operation.path);
|
|
106
|
+
try {
|
|
107
|
+
if (operation.action === 'create') {
|
|
108
|
+
await rm(target, { force: true });
|
|
109
|
+
}
|
|
110
|
+
else {
|
|
111
|
+
await mkdir(dirname(target), { recursive: true });
|
|
112
|
+
await rename(join(backupDir, operation.path), target);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
catch {
|
|
116
|
+
unrestored.push(operation.path);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
// Откат не удался: backup — единственная копия прежних файлов, удалять его нельзя.
|
|
120
|
+
if (unrestored.length > 0)
|
|
121
|
+
return { ok: false, stage: 'commit', rolledBack: false, reason, unrestored };
|
|
122
|
+
for (const dir of [...createdDirs].reverse())
|
|
123
|
+
await rmdir(join(root, dir)).catch(() => undefined);
|
|
124
|
+
await rm(staging, { recursive: true, force: true });
|
|
125
|
+
return { ok: false, stage: 'commit', rolledBack: true, reason };
|
|
126
|
+
}
|
|
127
|
+
const removed = operations.filter((operation) => operation.action === 'remove').map((operation) => operation.path);
|
|
128
|
+
for (const dir of parentDirs(removed))
|
|
129
|
+
await rmdir(join(root, dir)).catch(() => undefined);
|
|
130
|
+
await rm(staging, { recursive: true, force: true });
|
|
131
|
+
return { ok: true };
|
|
132
|
+
}
|