create-vibe-maestro 0.4.1 → 0.4.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +90 -0
- package/README.md +37 -34
- package/dist/cli/context-run.js +10 -0
- package/dist/cli/create-run.js +74 -9
- package/dist/cli/create.js +21 -2
- package/dist/cli/doctor-run.js +2 -1
- package/dist/cli/maestro.js +25 -2
- package/dist/cli/pack-run.js +42 -3
- package/dist/cli/prompt.js +12 -4
- package/dist/cli/renderer.js +5 -4
- package/dist/cli/upgrade-run.js +48 -5
- package/dist/core/context.js +47 -2
- package/dist/core/doctor/git.js +41 -1
- package/dist/core/doctor/inbox.js +5 -11
- package/dist/core/doctor/index.js +1 -1
- package/dist/core/doctor/plans.js +3 -3
- package/dist/core/doctor/sources.js +1 -1
- package/dist/core/github.js +107 -0
- package/dist/core/gitignore.js +3 -1
- package/dist/core/init.js +37 -10
- package/dist/core/inventory.js +6 -10
- package/dist/core/pack.js +130 -12
- package/dist/core/plan.js +21 -2
- package/dist/core/preflight.js +6 -5
- package/dist/core/readme.js +21 -0
- package/dist/core/settings.js +39 -0
- package/dist/core/template.js +2 -1
- package/dist/core/text-diff.js +108 -0
- package/dist/core/upgrade/analyze.js +131 -12
- package/dist/core/upgrade/baseline.js +14 -0
- package/dist/core/upgrade/index.js +53 -10
- package/dist/core/upgrade/releases.js +152 -11
- package/docs/ROADMAP.md +75 -44
- package/docs/USER_GUIDE.md +142 -79
- package/package.json +1 -1
- package/registry/baseline/0.4.1/project/.claude/commands/plan.md +2 -0
- package/registry/baseline/0.4.1/project/.claude/rules/maestro.md +35 -0
- package/registry/baseline/0.4.1/project/maestro/inbox/README.md +16 -0
- package/registry/baseline/0.4.1/project/maestro/runbooks/cowork-discovery.md +30 -0
- package/registry/baseline/0.4.1/project/protocols/plan.md +142 -0
- 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/discovery.md +3 -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/capabilities.v1.json +32 -20
- package/templates/project/.claude/agents/code-reviewer.md +18 -7
- package/templates/project/.claude/commands/plan.md +1 -0
- package/templates/project/.claude/commands/start.md +2 -0
- package/templates/project/.claude/rules/maestro.md +10 -5
- package/templates/project/.claude/rules/project.md +6 -0
- package/templates/project/.claude/settings.json +3 -0
- package/templates/project/README.md +11 -0
- package/templates/project/maestro/inbox/README.md +6 -6
- package/templates/project/maestro/runbooks/cowork-audit.md +9 -2
- package/templates/project/maestro/runbooks/cowork-discovery.md +1 -1
- package/templates/project/maestro/templates/audit.md +31 -0
- package/templates/project/maestro/templates/handoff.md +5 -1
- 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 +3 -1
- package/templates/project/protocols/plan.md +45 -28
- package/templates/project/protocols/start.md +64 -0
- package/templates/project/protocols/wiki.md +10 -2
- package/templates/project/wiki/concepts/discovery.md +30 -11
- package/templates/project/wiki/hot.md +2 -2
- package/templates/project/wiki/icebox.md +12 -0
- package/templates/project/wiki/index.md +2 -0
- package/templates/project/wiki/passport.md +3 -1
- package/templates/project/wiki/plans/0001-starter.md +16 -4
- package/templates/project/wiki/plans/README.md +7 -3
- package/templates/project/wiki/plans/TEMPLATE.md +13 -5
- package/templates/project/wiki/restore.md +32 -0
- /package/{templates → registry/baseline/0.4.1}/project/protocols/discovery.md +0 -0
- /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/lessons.md +0 -0
- /package/{templates → registry/baseline/0.4.2}/project/protocols/seams.md +0 -0
package/dist/core/init.js
CHANGED
|
@@ -13,14 +13,26 @@ import { renderTemplate } from './template.js';
|
|
|
13
13
|
import { recoverTemplateVars, templateUses } from './template-recover.js';
|
|
14
14
|
import { canonicalOwnershipInventory, CONTENT_OWNED_FILES, lazyDirsForDepth, TEMPLATE_FILES } from './inventory.js';
|
|
15
15
|
import { canonicalizeSystemTempPrefix, onDiskBasename } from './platform-paths.js';
|
|
16
|
+
import { hasAnyReadme, README_PATH } from './readme.js';
|
|
17
|
+
import { SETTINGS_PATH, withPushWithoutAsking } from './settings.js';
|
|
16
18
|
import { compareVersions } from './version.js';
|
|
17
19
|
const execFileAsync = promisify(execFile);
|
|
18
20
|
const GITIGNORE_PATH = '.gitignore';
|
|
19
21
|
/** Служебный мусор ОС и сам Git не делают папку «занятой чужими файлами». */
|
|
20
22
|
const IGNORED_WHEN_EMPTY_CHECK = ['.git', '.DS_Store'];
|
|
21
23
|
/** Шаблон .gitattributes: фиксирует LF для текстовых файлов проекта. */
|
|
22
|
-
const GITATTRIBUTES_PATH = '.gitattributes';
|
|
23
24
|
export const GITATTRIBUTES_CONTENT = '* text=auto eol=lf\n*.md text eol=lf\n*.json text eol=lf\n*.yml text eol=lf\n*.yaml text eol=lf\n';
|
|
25
|
+
/**
|
|
26
|
+
* Материалы человека git хранит байт в байт: `-text` во вложенном `.gitattributes`
|
|
27
|
+
* перекрывает корневые правила, и свежий клон отдаёт исходные переносы строк.
|
|
28
|
+
* Отдельный файл, а не строка в корневом: корневой проект мог дописать, и тогда upgrade встал бы.
|
|
29
|
+
*/
|
|
30
|
+
export const INBOX_GITATTRIBUTES_CONTENT = '* -text\n';
|
|
31
|
+
/** Managed-файлы, содержимое которых задаёт код, а не шаблон: без подстановок, побайтово. */
|
|
32
|
+
export const CODE_MANAGED_SOURCES = {
|
|
33
|
+
'.gitattributes': GITATTRIBUTES_CONTENT,
|
|
34
|
+
'maestro/inbox/.gitattributes': INBOX_GITATTRIBUTES_CONTENT,
|
|
35
|
+
};
|
|
24
36
|
function failure(target, projectName, error) {
|
|
25
37
|
return {
|
|
26
38
|
ok: false,
|
|
@@ -114,7 +126,7 @@ async function findAncestorSymlink(target) {
|
|
|
114
126
|
async function recoverProjectVars(target, startingPoint, checksums) {
|
|
115
127
|
const found = {};
|
|
116
128
|
for (const relativePath of TEMPLATE_FILES) {
|
|
117
|
-
if (relativePath
|
|
129
|
+
if (relativePath in CODE_MANAGED_SOURCES || checksums[relativePath] === undefined)
|
|
118
130
|
continue;
|
|
119
131
|
// Шаблоны пакета на Windows могут прийти с CRLF, а файлы проекта всегда пишутся с LF.
|
|
120
132
|
const source = normalizeEol(await readTemplate(relativePath));
|
|
@@ -170,7 +182,7 @@ async function initGitRepository(target, ownedPaths, warnings, writtenPaths) {
|
|
|
170
182
|
const shown = writtenPaths.slice(0, 5).map((path) => quotePathArg(path)).join(' ');
|
|
171
183
|
warnings.push(`Репозиторий Git уже существовал: index не изменён и commit не создан. Добавьте записанные файлы сами: git add ${shown}${writtenPaths.length > 5 ? ' …' : ''}`);
|
|
172
184
|
}
|
|
173
|
-
return;
|
|
185
|
+
return false;
|
|
174
186
|
}
|
|
175
187
|
// Только наши пути в новом репозитории. Пакетами, чтобы не упереться в лимит длины командной строки.
|
|
176
188
|
const toAdd = [...ownedPaths].sort();
|
|
@@ -180,10 +192,12 @@ async function initGitRepository(target, ownedPaths, warnings, writtenPaths) {
|
|
|
180
192
|
await execFileAsync('git', ['commit', '-m', 'Инициализация проекта Vibe Coding Maestro'], {
|
|
181
193
|
cwd: target,
|
|
182
194
|
});
|
|
195
|
+
return true;
|
|
183
196
|
}
|
|
184
197
|
catch (error) {
|
|
185
198
|
const message = error instanceof Error ? error.message : String(error);
|
|
186
199
|
warnings.push(`Git-шаги пропущены: ${message}`);
|
|
200
|
+
return false;
|
|
187
201
|
}
|
|
188
202
|
}
|
|
189
203
|
/**
|
|
@@ -297,6 +311,9 @@ async function initProjectAt(target, options, progress) {
|
|
|
297
311
|
if (isExistingProject && options.requested?.startingPoint !== undefined && options.requested.startingPoint !== startingPoint) {
|
|
298
312
|
warnings.push(`У проекта исходная точка ${startingPoint}; --start ${options.requested.startingPoint} не применён: create не меняет параметры готового проекта.`);
|
|
299
313
|
}
|
|
314
|
+
if (isExistingProject && options.pushWithoutAsking === true) {
|
|
315
|
+
warnings.push('--push-without-asking не применён: create не меняет готовый проект, а `.claude/settings.json` принадлежит проекту. Настройку предложит `/start` — только с вашего «да».');
|
|
316
|
+
}
|
|
300
317
|
const previousChecksums = (await loadChecksums(target))?.files ?? {};
|
|
301
318
|
const nextChecksums = {};
|
|
302
319
|
const managed = [];
|
|
@@ -369,15 +386,16 @@ async function initProjectAt(target, options, progress) {
|
|
|
369
386
|
ownedPaths.push(relativePath);
|
|
370
387
|
}
|
|
371
388
|
for (const relativePath of TEMPLATE_FILES) {
|
|
372
|
-
const
|
|
373
|
-
await materialize(relativePath,
|
|
389
|
+
const constant = CODE_MANAGED_SOURCES[relativePath];
|
|
390
|
+
await materialize(relativePath, constant ?? renderTemplate(await readTemplate(relativePath), vars));
|
|
374
391
|
}
|
|
375
392
|
for (const relativePath of CONTENT_OWNED_FILES) {
|
|
376
393
|
managed.push({ path: relativePath, kind: 'generated' });
|
|
377
394
|
const absolutePath = join(target, relativePath);
|
|
378
395
|
if (!existsSync(absolutePath)) {
|
|
379
|
-
const
|
|
380
|
-
|
|
396
|
+
const rendered = renderTemplate(await readTemplate(relativePath), vars);
|
|
397
|
+
const pushRecipe = relativePath === SETTINGS_PATH && options.pushWithoutAsking === true && !isExistingProject;
|
|
398
|
+
await writeTextFile(absolutePath, pushRecipe ? withPushWithoutAsking(rendered) : rendered);
|
|
381
399
|
createdFiles.push(relativePath);
|
|
382
400
|
ownedPaths.push(relativePath);
|
|
383
401
|
}
|
|
@@ -385,6 +403,13 @@ async function initProjectAt(target, options, progress) {
|
|
|
385
403
|
preservedFiles.push(relativePath);
|
|
386
404
|
}
|
|
387
405
|
}
|
|
406
|
+
// README — только в новый проект и только если в корне нет никакого README: удалённый
|
|
407
|
+
// человеком README повторный create не возвращает, а doctor его не требует.
|
|
408
|
+
if (!isExistingProject && !(await hasAnyReadme(target))) {
|
|
409
|
+
await writeTextFile(join(target, README_PATH), renderTemplate(await readTemplate(README_PATH), vars));
|
|
410
|
+
createdFiles.push(README_PATH);
|
|
411
|
+
ownedPaths.push(README_PATH);
|
|
412
|
+
}
|
|
388
413
|
for (const dir of lazyDirs) {
|
|
389
414
|
await mkdir(join(target, dir), { recursive: true });
|
|
390
415
|
await materialize(`${dir}/.gitkeep`, '');
|
|
@@ -425,9 +450,9 @@ async function initProjectAt(target, options, progress) {
|
|
|
425
450
|
});
|
|
426
451
|
await writeManifest(target, manifest);
|
|
427
452
|
await writeChecksums(target, nextChecksums);
|
|
428
|
-
|
|
429
|
-
await initGitRepository(target, ownedPaths, warnings, [...createdFiles, ...mergedFiles])
|
|
430
|
-
|
|
453
|
+
const gitCreated = options.git === true
|
|
454
|
+
? await initGitRepository(target, ownedPaths, warnings, [...createdFiles, ...mergedFiles])
|
|
455
|
+
: false;
|
|
431
456
|
// Метка снимается последней: убитый на любом шаге, включая Git, create остаётся виден.
|
|
432
457
|
if (!isExistingProject)
|
|
433
458
|
await rm(join(target, CREATING_MARKER_PATH), { force: true });
|
|
@@ -439,5 +464,7 @@ async function initProjectAt(target, options, progress) {
|
|
|
439
464
|
preservedFiles,
|
|
440
465
|
mergedFiles,
|
|
441
466
|
warnings,
|
|
467
|
+
existingProject: isExistingProject,
|
|
468
|
+
gitCreated,
|
|
442
469
|
};
|
|
443
470
|
}
|
package/dist/core/inventory.js
CHANGED
|
@@ -4,6 +4,7 @@ export const TEMPLATE_FILES = [
|
|
|
4
4
|
'wiki/plans/README.md',
|
|
5
5
|
'wiki/plans/TEMPLATE.md',
|
|
6
6
|
'maestro/inbox/README.md',
|
|
7
|
+
'maestro/inbox/.gitattributes',
|
|
7
8
|
'maestro/runbooks/cowork-discovery.md',
|
|
8
9
|
'maestro/runbooks/cowork-audit.md',
|
|
9
10
|
'maestro/runbooks/cowork-plan.md',
|
|
@@ -12,9 +13,11 @@ export const TEMPLATE_FILES = [
|
|
|
12
13
|
'.claude/commands/wiki.md',
|
|
13
14
|
'.claude/commands/handoff.md',
|
|
14
15
|
'.claude/commands/plan.md',
|
|
16
|
+
'.claude/commands/start.md',
|
|
15
17
|
'.claude/agents/code-reviewer.md',
|
|
16
18
|
'.claude/agents/explorer.md',
|
|
17
19
|
'maestro/templates/handoff.md',
|
|
20
|
+
'maestro/templates/audit.md',
|
|
18
21
|
'maestro/templates/adr.md',
|
|
19
22
|
'maestro/templates/progress.md',
|
|
20
23
|
'.gitattributes',
|
|
@@ -22,19 +25,10 @@ export const TEMPLATE_FILES = [
|
|
|
22
25
|
'protocols/status.md',
|
|
23
26
|
'protocols/wiki.md',
|
|
24
27
|
'protocols/handoff.md',
|
|
25
|
-
'protocols/discovery.md',
|
|
26
28
|
'protocols/plan.md',
|
|
27
29
|
'protocols/audit.md',
|
|
28
|
-
'protocols/context-budget.md',
|
|
29
|
-
'protocols/seams.md',
|
|
30
|
-
'protocols/lessons.md',
|
|
31
30
|
'protocols/completion.md',
|
|
32
|
-
'protocols/
|
|
33
|
-
'protocols/build/step-2-spec.md',
|
|
34
|
-
'protocols/build/step-3-architecture.md',
|
|
35
|
-
'protocols/build/step-5-feature-loop.md',
|
|
36
|
-
'protocols/build/audit-plan.md',
|
|
37
|
-
'protocols/build/audit-phase.md',
|
|
31
|
+
'protocols/start.md',
|
|
38
32
|
];
|
|
39
33
|
/** Стартовые содержательные документы: Maestro создаёт, затем ими владеет проект. */
|
|
40
34
|
export const CONTENT_OWNED_FILES = [
|
|
@@ -47,6 +41,8 @@ export const CONTENT_OWNED_FILES = [
|
|
|
47
41
|
'wiki/log.md',
|
|
48
42
|
'wiki/roadmap.md',
|
|
49
43
|
'wiki/passport.md',
|
|
44
|
+
'wiki/restore.md',
|
|
45
|
+
'wiki/icebox.md',
|
|
50
46
|
'wiki/concepts/discovery.md',
|
|
51
47
|
'wiki/plans/0001-starter.md',
|
|
52
48
|
];
|
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,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
|
-
/**
|
|
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. */
|
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 = [];
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { readdir } from 'node:fs/promises';
|
|
2
|
+
/**
|
|
3
|
+
* README проекта — не в составе, который проверяет doctor: create и upgrade кладут его,
|
|
4
|
+
* только если в корне нет никакого README, а удалить его можно. В составе он стал бы
|
|
5
|
+
* обязательным, а на Linux рядом с `readme.md` появился бы второй файл.
|
|
6
|
+
*/
|
|
7
|
+
export const README_PATH = 'README.md';
|
|
8
|
+
/** README, README.md, readme.md, README.rst, Readme.txt и т. п. — любое имя «readme» с расширением или без. */
|
|
9
|
+
export function isReadmeName(name) {
|
|
10
|
+
return /^readme(\..*)?$/i.test(name);
|
|
11
|
+
}
|
|
12
|
+
export async function hasAnyReadme(root) {
|
|
13
|
+
try {
|
|
14
|
+
return (await readdir(root)).some(isReadmeName);
|
|
15
|
+
}
|
|
16
|
+
catch (cause) {
|
|
17
|
+
if (cause.code === 'ENOENT')
|
|
18
|
+
return false;
|
|
19
|
+
throw cause;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* «Отправка в облако без вопроса» — рецепт из руководства («Как подстроить защиты под проект»)
|
|
3
|
+
* и из `protocols/start.md`: обычный push разрешён, принудительный остаётся с вопросом —
|
|
4
|
+
* «спросить» сильнее «разрешить». Ключ `ask` в файле один.
|
|
5
|
+
*/
|
|
6
|
+
export const SETTINGS_PATH = '.claude/settings.json';
|
|
7
|
+
export const PUSH_ALLOW = ['Bash(git push *)'];
|
|
8
|
+
/**
|
|
9
|
+
* Отправка, которая может перезаписать или стереть работу в облаке: принудительная
|
|
10
|
+
* (`--force`, `-f`, `+ветка`) и удаление веток (`--delete`, `-d`, `--mirror`, `--prune`).
|
|
11
|
+
* Запись `:ветка` правилом не ловится: шаблон на `:*` Claude Code читает как старое
|
|
12
|
+
* «команда начинается с …», и тогда с вопросом шёл бы любой push.
|
|
13
|
+
*/
|
|
14
|
+
export const FORCE_PUSH_ASK = [
|
|
15
|
+
'Bash(git push --force)',
|
|
16
|
+
'Bash(git push -f)',
|
|
17
|
+
'Bash(git push *--force*)',
|
|
18
|
+
'Bash(git push -f*)',
|
|
19
|
+
'Bash(git push * -f*)',
|
|
20
|
+
'Bash(git push * +*)',
|
|
21
|
+
'Bash(git push *--delete*)',
|
|
22
|
+
'Bash(git push -d *)',
|
|
23
|
+
'Bash(git push * -d *)',
|
|
24
|
+
'Bash(git push *--mirror*)',
|
|
25
|
+
'Bash(git push *--prune*)',
|
|
26
|
+
];
|
|
27
|
+
/** Шаблон settings.json → тот же файл с «отправкой без вопроса»; остальные правила не меняются. */
|
|
28
|
+
export function withPushWithoutAsking(settingsJson) {
|
|
29
|
+
const settings = JSON.parse(settingsJson);
|
|
30
|
+
const { deny, allow, ask, ...rest } = settings.permissions;
|
|
31
|
+
const askRules = (ask ?? []).flatMap((rule) => rule === 'Bash(git push *)' ? [...FORCE_PUSH_ASK] : [rule]);
|
|
32
|
+
const permissions = {
|
|
33
|
+
...(deny === undefined ? {} : { deny }),
|
|
34
|
+
allow: [...new Set([...(allow ?? []), ...PUSH_ALLOW])],
|
|
35
|
+
ask: askRules,
|
|
36
|
+
...rest,
|
|
37
|
+
};
|
|
38
|
+
return `${JSON.stringify({ ...settings, permissions }, null, 2)}\n`;
|
|
39
|
+
}
|
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
|
+
}
|