create-vibe-maestro 0.4.3 → 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 +39 -0
- package/README.md +6 -6
- package/dist/cli/archive-run.js +75 -0
- package/dist/cli/maestro.js +22 -3
- 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/doctor/fs-utils.js +3 -2
- package/dist/core/doctor/index.js +4 -1
- package/dist/core/doctor/memory.js +52 -0
- package/dist/core/doctor/plans.js +1 -1
- package/dist/core/doctor/wiki.js +9 -33
- package/dist/core/plan.js +26 -4
- package/dist/core/transaction.js +132 -0
- package/dist/core/upgrade/analyze.js +14 -3
- package/dist/core/upgrade/baseline.js +2 -0
- package/dist/core/upgrade/index.js +13 -112
- package/dist/core/upgrade/releases.js +51 -1
- package/dist/core/wiki-links.js +27 -0
- package/docs/ROADMAP.md +1 -1
- package/docs/USER_GUIDE.md +56 -13
- package/package.json +1 -1
- 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/templates/project/.claude/rules/maestro.md +1 -0
- package/templates/project/maestro/templates/handoff.md +1 -1
- package/templates/project/protocols/build.md +3 -3
- package/templates/project/protocols/completion.md +2 -2
- package/templates/project/protocols/handoff.md +6 -5
- package/templates/project/protocols/plan.md +3 -2
- package/templates/project/protocols/status.md +1 -1
- package/templates/project/protocols/wiki.md +1 -1
- package/templates/project/wiki/index.md +4 -0
- package/templates/project/wiki/log.md +1 -0
- package/templates/project/wiki/plans/0001-starter.md +2 -2
- package/templates/project/wiki/plans/README.md +21 -1
- package/templates/project/wiki/plans/TEMPLATE.md +10 -1
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { posix } from 'node:path';
|
|
2
|
+
import { isExternalLink, markdownLinks } from '../wiki-links.js';
|
|
3
|
+
/** Часть адреса: скобки ломают разбор ссылки, а `encodeURIComponent` их не кодирует. */
|
|
4
|
+
const percent = (char) => (char === '(' ? '%28' : char === ')' ? '%29' : encodeURIComponent(char));
|
|
5
|
+
const encodePart = (part) => encodeURIComponent(part).replace(/[()]/g, percent);
|
|
6
|
+
/** Имя файла в адресе, который пишет archive: кириллица как есть, то, что сломало бы ссылку, — кодами. */
|
|
7
|
+
export const linkName = (name) => name.replace(/[\s%()<>#]/g, percent);
|
|
8
|
+
/** Ссылки на файлы проекта: внешняя, ведущая наружу проекта или только якорь сюда не входят. */
|
|
9
|
+
function localLinks(text, from, locate) {
|
|
10
|
+
const fromDir = posix.dirname(from);
|
|
11
|
+
const links = [];
|
|
12
|
+
for (const link of markdownLinks(text)) {
|
|
13
|
+
const hashAt = link.destination.indexOf('#');
|
|
14
|
+
const rawPath = hashAt === -1 ? link.destination : link.destination.slice(0, hashAt);
|
|
15
|
+
const anchor = hashAt === -1 ? '' : link.destination.slice(hashAt);
|
|
16
|
+
const pathText = rawPath.trim();
|
|
17
|
+
if (pathText === '' || isExternalLink(pathText))
|
|
18
|
+
continue;
|
|
19
|
+
let decoded;
|
|
20
|
+
try {
|
|
21
|
+
decoded = decodeURIComponent(pathText);
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
continue;
|
|
25
|
+
}
|
|
26
|
+
const plain = posix.normalize(posix.join(fromDir, decoded)).replace(/\/$/, '');
|
|
27
|
+
const located = locate?.(from, decoded);
|
|
28
|
+
if (located === undefined && (pathText.startsWith('/') || plain === '..' || plain.startsWith('../')))
|
|
29
|
+
continue;
|
|
30
|
+
links.push({ link, pathText, anchor, target: located ?? plain, directory: decoded.endsWith('/') });
|
|
31
|
+
}
|
|
32
|
+
return links;
|
|
33
|
+
}
|
|
34
|
+
/** На какие файлы проекта ссылается текст файла `from`. */
|
|
35
|
+
export function linkTargets(text, from, locate) {
|
|
36
|
+
return new Set(localLinks(text, from, locate).map((link) => link.target));
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Переносит адреса относительных ссылок: текст `from` переезжает в `to`, а файлы
|
|
40
|
+
* из `moved` (старый путь → новый, пути от корня проекта) — на новые места.
|
|
41
|
+
*
|
|
42
|
+
* Меняется только адрес ссылки, и только если он теперь должен быть другим;
|
|
43
|
+
* весь остальной текст — байт в байт. Якорь `#…` и вид записи (`<…>`, `%`-кодировка)
|
|
44
|
+
* сохраняются. Внешняя ссылка и ссылка наружу проекта не трогаются: их адрес от
|
|
45
|
+
* переноса не зависит. `locate` находит файл так же, как doctor; без него адрес
|
|
46
|
+
* понимается как строка.
|
|
47
|
+
*/
|
|
48
|
+
export function rebaseLinks(text, from, to, moved = new Map(), locate) {
|
|
49
|
+
const toDir = posix.dirname(to);
|
|
50
|
+
const sameDir = posix.dirname(from) === toDir;
|
|
51
|
+
let out = '';
|
|
52
|
+
let cursor = 0;
|
|
53
|
+
for (const { link, pathText, anchor, target, directory } of localLinks(text, from, locate)) {
|
|
54
|
+
const finalTarget = moved.get(target) ?? target;
|
|
55
|
+
if (sameDir && finalTarget === target)
|
|
56
|
+
continue;
|
|
57
|
+
let relative = posix.relative(toDir, finalTarget) || '.';
|
|
58
|
+
if (directory)
|
|
59
|
+
relative += '/';
|
|
60
|
+
const written = pathText.includes('%') ? relative.split('/').map((part) => (part === '..' || part === '.' ? part : encodePart(part))).join('/') : relative;
|
|
61
|
+
out += text.slice(cursor, link.start) + written + anchor;
|
|
62
|
+
cursor = link.start + link.destination.length;
|
|
63
|
+
}
|
|
64
|
+
return out + text.slice(cursor);
|
|
65
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { rebaseLinks } from './links.js';
|
|
2
|
+
import { countChars, LOG_KEEP, LOG_LIMIT } from './limits.js';
|
|
3
|
+
import { eolOf, markdownLines } from './markdown.js';
|
|
4
|
+
export const LOG_PATH = 'wiki/log.md';
|
|
5
|
+
export const LOG_DIR = 'wiki/log';
|
|
6
|
+
/** Строка в шапке `wiki/log.md`: добавляется при первом переносе, повтор узнаётся по тексту. */
|
|
7
|
+
export const LOG_POINTER = 'Старые записи — по месяцам в [log/](log/).';
|
|
8
|
+
const HEADING_RE = /^##[ \t]/;
|
|
9
|
+
/** Дата — в начале заголовка, можно в квадратных скобках: `## 2026-10-12 — …`, `## [2026-10-19] build | …`. */
|
|
10
|
+
const DATED_RE = /^##[ \t]+\[?(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])(?!\d)/;
|
|
11
|
+
/**
|
|
12
|
+
* Записи журнала — блоки от `## ` до следующего `## ` вне блоков кода. Блок без даты
|
|
13
|
+
* едет с предыдущей записью, а до первой датированной записи всё — шапка.
|
|
14
|
+
*/
|
|
15
|
+
export function parseLog(text) {
|
|
16
|
+
const starts = [];
|
|
17
|
+
for (const { line, offset, code } of markdownLines(text)) {
|
|
18
|
+
if (code || !HEADING_RE.test(line))
|
|
19
|
+
continue;
|
|
20
|
+
const date = DATED_RE.exec(line);
|
|
21
|
+
if (date !== null)
|
|
22
|
+
starts.push({ offset, month: `${date[1]}-${date[2]}` });
|
|
23
|
+
}
|
|
24
|
+
if (starts.length === 0)
|
|
25
|
+
return { preamble: text, entries: [] };
|
|
26
|
+
return {
|
|
27
|
+
preamble: text.slice(0, starts[0].offset),
|
|
28
|
+
entries: starts.map((start, index) => ({ month: start.month, text: text.slice(start.offset, starts[index + 1]?.offset ?? text.length) })),
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
/** Шапка нового файла месяца. */
|
|
32
|
+
export function monthHeader(month, eol) {
|
|
33
|
+
return `# Журнал: ${month}${eol}${eol}Записи, перенесённые из [log.md](../log.md) командой \`vibe-maestro archive\`: текст прежний, поправлены только адреса ссылок. Новые записи пишутся в \`wiki/log.md\`.${eol}${eol}`;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Перенос по порогу: `wiki/log.md` больше `LOG_LIMIT` знаков — в нём остаются
|
|
37
|
+
* последние записи на `LOG_KEEP` знаков (минимум одна), старые уходят в файлы
|
|
38
|
+
* месяцев. Нечего переносить — `null`.
|
|
39
|
+
*/
|
|
40
|
+
export function rotateLog(text, moved = new Map(), locate) {
|
|
41
|
+
const chars = countChars(text);
|
|
42
|
+
if (chars <= LOG_LIMIT)
|
|
43
|
+
return null;
|
|
44
|
+
const { preamble, entries } = parseLog(text);
|
|
45
|
+
let kept = 0;
|
|
46
|
+
let keptChars = 0;
|
|
47
|
+
for (let index = entries.length - 1; index >= 0; index -= 1) {
|
|
48
|
+
const size = countChars(entries[index].text);
|
|
49
|
+
if (kept > 0 && keptChars + size > LOG_KEEP)
|
|
50
|
+
break;
|
|
51
|
+
kept += 1;
|
|
52
|
+
keptChars += size;
|
|
53
|
+
}
|
|
54
|
+
const leaving = entries.slice(0, entries.length - kept);
|
|
55
|
+
if (leaving.length === 0)
|
|
56
|
+
return null;
|
|
57
|
+
const eol = eolOf(text);
|
|
58
|
+
const months = new Map();
|
|
59
|
+
for (const entry of leaving) {
|
|
60
|
+
const path = `${LOG_DIR}/${entry.month}.md`;
|
|
61
|
+
const current = months.get(path) ?? { entries: 0, appended: '' };
|
|
62
|
+
current.entries += 1;
|
|
63
|
+
current.appended += rebaseLinks(entry.text, LOG_PATH, path, moved, locate);
|
|
64
|
+
months.set(path, current);
|
|
65
|
+
}
|
|
66
|
+
const start = rebaseLinks(preamble, LOG_PATH, LOG_PATH, moved, locate);
|
|
67
|
+
const head = start.includes(LOG_POINTER)
|
|
68
|
+
? start
|
|
69
|
+
: `${start.replace(/(?:\r?\n)+$/, '')}${start.trim() === '' ? '' : `${eol}${eol}`}${LOG_POINTER}${eol}${eol}`;
|
|
70
|
+
const rest = entries.slice(entries.length - kept).map((entry) => rebaseLinks(entry.text, LOG_PATH, LOG_PATH, moved, locate)).join('');
|
|
71
|
+
return {
|
|
72
|
+
chars,
|
|
73
|
+
keptEntries: kept,
|
|
74
|
+
log: head + rest,
|
|
75
|
+
months: [...months.entries()].map(([path, value]) => ({ path, ...value })),
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
/** Текст файла месяца после дописывания: новый — с шапкой, прежний — с переводом строки перед дописанным. */
|
|
79
|
+
export function appendToMonth(existing, month, appended, eol) {
|
|
80
|
+
if (existing === null)
|
|
81
|
+
return monthHeader(month, eol) + appended;
|
|
82
|
+
return existing === '' || existing.endsWith('\n') ? existing + appended : existing + eol + appended;
|
|
83
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
const FENCE_RE = /^ {0,3}(`{3,}|~{3,})(.*)$/;
|
|
2
|
+
/** Строки с пометкой блоков кода: закрывает блок то же ограждение, не короче открывшего. */
|
|
3
|
+
export function markdownLines(text) {
|
|
4
|
+
const lines = [];
|
|
5
|
+
let open = null;
|
|
6
|
+
let offset = 0;
|
|
7
|
+
for (const line of text.split(/(?<=\n)/)) {
|
|
8
|
+
const fence = FENCE_RE.exec(line.replace(/\r?\n$/, ''));
|
|
9
|
+
const marker = fence?.[1] ?? '';
|
|
10
|
+
const rest = fence?.[2] ?? '';
|
|
11
|
+
if (open === null) {
|
|
12
|
+
const opens = fence !== null && !(marker.startsWith('`') && rest.includes('`'));
|
|
13
|
+
if (opens)
|
|
14
|
+
open = marker;
|
|
15
|
+
lines.push({ line, offset, code: opens });
|
|
16
|
+
}
|
|
17
|
+
else {
|
|
18
|
+
if (fence !== null && marker[0] === open[0] && marker.length >= open.length && rest.trim() === '')
|
|
19
|
+
open = null;
|
|
20
|
+
lines.push({ line, offset, code: true });
|
|
21
|
+
}
|
|
22
|
+
offset += line.length;
|
|
23
|
+
}
|
|
24
|
+
return lines;
|
|
25
|
+
}
|
|
26
|
+
export const eolOf = (text) => (text.includes('\r\n') ? '\r\n' : '\n');
|
|
27
|
+
/** Разборы (frontmatter, отпечаток) работают с текстом без BOM, как его читает doctor; записывается текст с BOM. */
|
|
28
|
+
export const withoutBom = (text) => text.replace(/^\uFEFF/, '');
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import { posix } from 'node:path';
|
|
2
|
+
import { frontmatter } from '../doctor/text.js';
|
|
3
|
+
import { HOT_PATH, planFileName } from '../doctor/plans.js';
|
|
4
|
+
import { ACTIVE_PLAN_NONE, isWikiRelativePlanRef, PLAN_APPROVAL_DIGEST_KEY, PLAN_NULL, planDigestMatches } from '../plan.js';
|
|
5
|
+
import { countChars, formatChars } from './limits.js';
|
|
6
|
+
import { linkName } from './links.js';
|
|
7
|
+
import { markdownLines, withoutBom } from './markdown.js';
|
|
8
|
+
import { blocker } from './types.js';
|
|
9
|
+
export const PLANS_ARCHIVE_DIR = 'wiki/plans/archive';
|
|
10
|
+
/** Законченные планы: к ним не возвращаются, их отпечаток никто не сверит. `blocked` — пауза, он сюда не входит. */
|
|
11
|
+
const FINISHED_STATUSES = ['completed', 'rejected', 'superseded'];
|
|
12
|
+
export function planFiles(files) {
|
|
13
|
+
const plans = [];
|
|
14
|
+
for (const [path, text] of files) {
|
|
15
|
+
if (planFileName(path) === null)
|
|
16
|
+
continue;
|
|
17
|
+
const plain = withoutBom(text);
|
|
18
|
+
const meta = frontmatter(plain);
|
|
19
|
+
const recorded = meta?.[PLAN_APPROVAL_DIGEST_KEY];
|
|
20
|
+
const digest = recorded === undefined || recorded === PLAN_NULL ? null : recorded;
|
|
21
|
+
plans.push({
|
|
22
|
+
path,
|
|
23
|
+
text,
|
|
24
|
+
meta,
|
|
25
|
+
digest,
|
|
26
|
+
guarded: digest !== null && !FINISHED_STATUSES.includes(meta?.status ?? ''),
|
|
27
|
+
intact: digest === null || planDigestMatches(digest, plain),
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
return plans;
|
|
31
|
+
}
|
|
32
|
+
export const planArchivePath = (planPath) => `${PLANS_ARCHIVE_DIR}/${posix.basename(planPath)}`;
|
|
33
|
+
/** Шапка нового архива плана. */
|
|
34
|
+
function planArchiveHeader(plan, eol) {
|
|
35
|
+
const name = posix.basename(plan.path);
|
|
36
|
+
return [
|
|
37
|
+
'---', 'type: plan-archive', `plan: ${plan.meta?.id ?? name.slice(0, -3)}`, `source: ${plan.path}`, '---', '',
|
|
38
|
+
`# Архив плана: ${name.slice(0, -3)}`, '',
|
|
39
|
+
`Закрытые правки, перенесённые из [плана](../${linkName(name)}) командой \`vibe-maestro archive\`: текст прежний, поправлены только адреса ссылок. Это история: читайте поиском, руками не правьте и обратно в план не копируйте.`, '', '',
|
|
40
|
+
].join(eol);
|
|
41
|
+
}
|
|
42
|
+
/** Дописывает блоки в архив плана: новый файл — с шапкой, между блоками — пустая строка. */
|
|
43
|
+
export function appendToPlanArchive(existing, plan, blocks, eol) {
|
|
44
|
+
let text = existing ?? planArchiveHeader(plan, eol);
|
|
45
|
+
for (const block of blocks) {
|
|
46
|
+
if (!/(?:\r?\n){2}$/.test(text))
|
|
47
|
+
text += /\r?\n$/.test(text) ? eol : `${eol}${eol}`;
|
|
48
|
+
text += block;
|
|
49
|
+
}
|
|
50
|
+
return text;
|
|
51
|
+
}
|
|
52
|
+
/** Строка в архиве плана: чем заменён отпечаток и когда. */
|
|
53
|
+
export const digestLine = (date, before, after, eol) => `Отпечаток плана заменён командой \`vibe-maestro archive\` ${date}: \`${before}\` → \`${after}\`. Текст совпадал с прежним отпечатком, изменились только перенесённые разделы и адреса ссылок.${eol}`;
|
|
54
|
+
/** Записывает новый отпечаток в строку frontmatter, остальные байты те же. */
|
|
55
|
+
export function writeDigest(text, digest) {
|
|
56
|
+
return text.replace(new RegExp(`^${PLAN_APPROVAL_DIGEST_KEY}:.*$`, 'm'), `${PLAN_APPROVAL_DIGEST_KEY}: ${digest}`);
|
|
57
|
+
}
|
|
58
|
+
const HEADING_RE = /^ {0,3}(#{1,6})[ \t]+(.*?)[ \t]*\r?\n?$/;
|
|
59
|
+
const WORD_RE = /^[\p{L}\p{N}_]/u;
|
|
60
|
+
const COLLECTIONS = ['Правки после утверждения', 'Изменения после утверждения'];
|
|
61
|
+
const APPROVAL = 'Утверждение';
|
|
62
|
+
const POINTER_RE = /^В архиве: \[[^\]]*\]\(archive\/[^)]*\)\.?$/;
|
|
63
|
+
const UNCHECKED_RE = /^[ \t]*(?:[-*+]|\d+[.)])[ \t]+\[ \]/gm;
|
|
64
|
+
/** Сколько заголовков показать в отказе: у живых планов их сотни. */
|
|
65
|
+
const LISTED = 30;
|
|
66
|
+
/** Заголовки и аргументы сравниваются без разметки и с одинарными пробелами. */
|
|
67
|
+
export function plainTitle(value) {
|
|
68
|
+
return value.replace(/`|\*\*|[«»]/g, '').replace(/\s+/g, ' ').trim();
|
|
69
|
+
}
|
|
70
|
+
const startsWithWord = (title, wanted) => title.startsWith(wanted) && !WORD_RE.test(title.slice(wanted.length));
|
|
71
|
+
function mentionsSlice(text, slice) {
|
|
72
|
+
const escaped = slice.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
73
|
+
return new RegExp(`(?<![\\p{L}\\p{N}_])${escaped}(?![\\p{L}\\p{N}_])`, 'u').test(text);
|
|
74
|
+
}
|
|
75
|
+
export function planHeadings(text) {
|
|
76
|
+
const body = /^\uFEFF?---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/.exec(text)?.[0].length ?? 0;
|
|
77
|
+
const headings = [];
|
|
78
|
+
for (const { line, offset, code } of markdownLines(text)) {
|
|
79
|
+
if (code || offset < body)
|
|
80
|
+
continue;
|
|
81
|
+
const match = HEADING_RE.exec(line);
|
|
82
|
+
if (match !== null)
|
|
83
|
+
headings.push({ level: match[1]?.length ?? 0, line, title: plainTitle(match[2] ?? ''), start: offset, end: text.length });
|
|
84
|
+
}
|
|
85
|
+
headings.forEach((heading, index) => {
|
|
86
|
+
heading.end = headings.slice(index + 1).find((next) => next.level <= heading.level)?.start ?? text.length;
|
|
87
|
+
});
|
|
88
|
+
return headings;
|
|
89
|
+
}
|
|
90
|
+
function listed(headings) {
|
|
91
|
+
const shown = headings.slice(0, LISTED).map((heading) => `«${heading.title.slice(0, 80)}»`).join('; ');
|
|
92
|
+
return headings.length > LISTED ? `${shown}; и ещё ${headings.length - LISTED}` : shown;
|
|
93
|
+
}
|
|
94
|
+
function chooseSection(text, plan, argument, headings, collection) {
|
|
95
|
+
const wanted = plainTitle(argument);
|
|
96
|
+
const candidates = headings.filter((heading) => heading.level === 2 || heading.level === 3);
|
|
97
|
+
const found = wanted === '' ? [] : candidates.filter((heading) => startsWithWord(heading.title, wanted));
|
|
98
|
+
const movable = candidates.filter((heading) => heading.start > collection.start);
|
|
99
|
+
if (found.length === 0)
|
|
100
|
+
return { blocker: blocker('archive-section-not-found', `В плане нет раздела, заголовок которого начинается с «${argument}». Правки плана: ${listed(movable) || 'их нет'}.`, plan.path) };
|
|
101
|
+
if (found.length > 1)
|
|
102
|
+
return { blocker: blocker('archive-section-ambiguous', `«${argument}» подходит к разделам: ${listed(found)}. Уточните начало заголовка; одинаковые заголовки так не перенести.`, plan.path) };
|
|
103
|
+
const heading = found[0];
|
|
104
|
+
const title = `«${heading.title}»`;
|
|
105
|
+
if (heading === collection || COLLECTIONS.includes(heading.title))
|
|
106
|
+
return { blocker: blocker('archive-section-collection', `${title} — сборник правок: внутри могут быть и открытые. Называйте закрытые правки по одной.`, plan.path) };
|
|
107
|
+
if (heading.start < collection.start)
|
|
108
|
+
return { blocker: blocker('archive-section-main-part', `${title} — основная часть плана, она в архив не переносится. Переносить можно только разделы ниже «${collection.title}».`, plan.path) };
|
|
109
|
+
const nested = headings.filter((other) => other.start > heading.start && other.start < heading.end);
|
|
110
|
+
const slice = plan.meta?.current_slice;
|
|
111
|
+
const declaredSlice = slice === undefined || slice === PLAN_NULL ? null : slice;
|
|
112
|
+
for (const part of [heading, ...nested]) {
|
|
113
|
+
if (COLLECTIONS.includes(part.title))
|
|
114
|
+
return { blocker: blocker('archive-section-collection', `Внутри ${title} стоит сборник правок «${part.title}»: внутри него могут быть и открытые.`, plan.path) };
|
|
115
|
+
if (part === heading ? startsWithWord(part.title, APPROVAL) : part.title === APPROVAL)
|
|
116
|
+
return { blocker: blocker('archive-section-approval', `«${part.title}» — запись об утверждении плана, она остаётся в плане.`, plan.path) };
|
|
117
|
+
if (declaredSlice !== null && mentionsSlice(part.title, declaredSlice))
|
|
118
|
+
return { blocker: blocker('archive-section-current-slice', `В заголовке «${part.title}» стоит текущая порция ${declaredSlice}: открытое в архив не переносится.`, plan.path) };
|
|
119
|
+
}
|
|
120
|
+
const section = text.slice(heading.start, heading.end);
|
|
121
|
+
const rest = section.slice(heading.line.length);
|
|
122
|
+
const warnings = [];
|
|
123
|
+
if (declaredSlice !== null && mentionsSlice(rest, declaredSlice))
|
|
124
|
+
warnings.push(`раздел ${title} упоминает текущую порцию ${declaredSlice}.`);
|
|
125
|
+
const unchecked = [...rest.matchAll(UNCHECKED_RE)].length;
|
|
126
|
+
if (unchecked > 0)
|
|
127
|
+
warnings.push(`в разделе ${title} неотмеченных пунктов [ ]: ${formatChars(unchecked)}.`);
|
|
128
|
+
return { choice: { heading, nested, already: POINTER_RE.test(rest.trim()), warnings } };
|
|
129
|
+
}
|
|
130
|
+
/** `active_plan` из `wiki/hot.md`. */
|
|
131
|
+
export function declaredPlan(files) {
|
|
132
|
+
const hot = files.get(HOT_PATH);
|
|
133
|
+
return (hot === undefined ? null : frontmatter(withoutBom(hot)))?.active_plan ?? ACTIVE_PLAN_NONE;
|
|
134
|
+
}
|
|
135
|
+
/** Находит названные разделы активного плана; ничего не меняет. */
|
|
136
|
+
export function resolveSections(files, plans, wanted) {
|
|
137
|
+
const refuse = (item, plan = null) => ({ plan, chosen: [], blockers: [item] });
|
|
138
|
+
const declared = declaredPlan(files);
|
|
139
|
+
if (declared === ACTIVE_PLAN_NONE)
|
|
140
|
+
return refuse(blocker('archive-section-no-plan', 'Активного плана нет (active_plan: none): --section работает только в активном плане.', HOT_PATH));
|
|
141
|
+
const plan = isWikiRelativePlanRef(declared) ? plans.find((item) => item.path === `wiki/${declared}`) : undefined;
|
|
142
|
+
if (plan === undefined)
|
|
143
|
+
return refuse(blocker('archive-section-plan-missing', `Объявленный активный план не найден: ${declared}.`, HOT_PATH));
|
|
144
|
+
if (plan.meta === null)
|
|
145
|
+
return refuse(blocker('archive-section-plan-invalid', 'Frontmatter плана не разобран: сначала поправьте его (doctor).', plan.path), plan);
|
|
146
|
+
if (!plan.intact)
|
|
147
|
+
return refuse(blocker('archive-plan-changed', 'Текст плана изменился после утверждения (approved_digest не совпадает): перенос записал бы новый отпечаток поверх неутверждённой правки. Покажите изменения человеку; после его «да» запишите отпечаток из вывода preflight и повторите.', plan.path), plan);
|
|
148
|
+
const headings = planHeadings(plan.text);
|
|
149
|
+
const collection = headings.find((heading) => (heading.level === 2 || heading.level === 3) && COLLECTIONS.some((name) => startsWithWord(heading.title, name)));
|
|
150
|
+
if (collection === undefined)
|
|
151
|
+
return refuse(blocker('archive-section-no-collection', `В плане нет раздела «${COLLECTIONS[0]}» или «${COLLECTIONS[1]}»: переносить можно только правки, которые стоят ниже него.`, plan.path), plan);
|
|
152
|
+
const chosen = [];
|
|
153
|
+
const blockers = [];
|
|
154
|
+
for (const argument of wanted) {
|
|
155
|
+
const result = chooseSection(plan.text, plan, argument, headings, collection);
|
|
156
|
+
if (result.blocker !== undefined)
|
|
157
|
+
blockers.push(result.blocker);
|
|
158
|
+
else if (result.choice !== undefined) {
|
|
159
|
+
const { heading } = result.choice;
|
|
160
|
+
const overlapping = chosen.find((other) => heading.start < other.heading.end && other.heading.start < heading.end);
|
|
161
|
+
if (overlapping !== undefined)
|
|
162
|
+
blockers.push(blocker('archive-section-overlap', `Разделы «${overlapping.heading.title}» и «${heading.title}» пересекаются: назовите один из них.`, plan.path));
|
|
163
|
+
else
|
|
164
|
+
chosen.push(result.choice);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
return { plan, chosen, blockers };
|
|
168
|
+
}
|
|
169
|
+
export function cutSections(text, chosen, archivePath, eol) {
|
|
170
|
+
const name = posix.basename(archivePath);
|
|
171
|
+
const sections = [];
|
|
172
|
+
let remaining = '';
|
|
173
|
+
let cursor = 0;
|
|
174
|
+
for (const { heading } of [...chosen].filter((item) => !item.already).sort((left, right) => left.heading.start - right.heading.start)) {
|
|
175
|
+
sections.push(text.slice(heading.start, heading.end));
|
|
176
|
+
const line = /\n$/.test(heading.line) ? heading.line : `${heading.line}${eol}`;
|
|
177
|
+
remaining += `${text.slice(cursor, heading.start)}${line}${eol}В архиве: [${name.replace(/[[\]]/g, '')}](archive/${linkName(name)}).${eol}${eol}`;
|
|
178
|
+
cursor = heading.end;
|
|
179
|
+
}
|
|
180
|
+
return { remaining: remaining + text.slice(cursor), sections };
|
|
181
|
+
}
|
|
182
|
+
/** Размер раздела для отчёта. */
|
|
183
|
+
export const sectionChars = (text, heading) => countChars(text.slice(heading.start, heading.end));
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const blocker = (code, message, path) => ({ code, message, ...(path === undefined ? {} : { path }) });
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { frontmatter } from './doctor/text.js';
|
|
2
|
+
/**
|
|
3
|
+
* Разбор отчёта проверки: один для doctor и archive. Если бы archive считал
|
|
4
|
+
* закрытым то, что doctor не разобрал, в архив уехал бы неразборчивый отчёт.
|
|
5
|
+
*/
|
|
6
|
+
const AUDIT_STATUSES = new Set(['open', 'resolved']);
|
|
7
|
+
export function parseAudit(text) {
|
|
8
|
+
const meta = frontmatter(text);
|
|
9
|
+
let malformed = !meta?.audit_id || !meta.status || !AUDIT_STATUSES.has(meta.status);
|
|
10
|
+
const starts = [...text.matchAll(/^## Finding ([A-Za-z0-9][A-Za-z0-9._-]*)\s*$/gm)];
|
|
11
|
+
if (starts.length === 0)
|
|
12
|
+
malformed = true;
|
|
13
|
+
const blocking = [];
|
|
14
|
+
const ids = new Set();
|
|
15
|
+
for (let index = 0; index < starts.length; index += 1) {
|
|
16
|
+
const current = starts[index];
|
|
17
|
+
const id = current?.[1] ?? '';
|
|
18
|
+
const body = text.slice((current?.index ?? 0) + (current?.[0].length ?? 0), starts[index + 1]?.index ?? text.length);
|
|
19
|
+
const fields = (name) => [...body.matchAll(new RegExp(`^- ${name}:[ \\t]*(.*?)[ \\t]*$`, 'gm'))].map((match) => match[1]?.trim() ?? '');
|
|
20
|
+
const severityValues = fields('severity');
|
|
21
|
+
const targetValues = fields('target');
|
|
22
|
+
const evidenceValues = fields('evidence');
|
|
23
|
+
const statusValues = fields('status');
|
|
24
|
+
const resolutionValues = fields('resolution');
|
|
25
|
+
const severity = severityValues[0];
|
|
26
|
+
const status = statusValues[0];
|
|
27
|
+
if (ids.has(id) || severityValues.length !== 1 || targetValues.length !== 1 || evidenceValues.length !== 1 || statusValues.length !== 1 || resolutionValues.length !== 1 || !['critical', 'high', 'medium', 'low'].includes(severity ?? '') || !targetValues[0] || !evidenceValues[0] || !AUDIT_STATUSES.has(status ?? '') || !resolutionValues[0])
|
|
28
|
+
malformed = true;
|
|
29
|
+
else if (meta?.status !== 'open' && status === 'open')
|
|
30
|
+
malformed = true;
|
|
31
|
+
else if ((severity === 'critical' || severity === 'high') && status === 'open')
|
|
32
|
+
blocking.push({ id, severity });
|
|
33
|
+
ids.add(id);
|
|
34
|
+
}
|
|
35
|
+
// Разобранный отчёт `resolved` не содержит открытых находок: иначе он был бы malformed.
|
|
36
|
+
return { malformed, closed: !malformed && meta?.status === 'resolved', blocking };
|
|
37
|
+
}
|
|
@@ -20,7 +20,7 @@ export async function absolutePathHasSymlink(absolutePath) {
|
|
|
20
20
|
}
|
|
21
21
|
return false;
|
|
22
22
|
}
|
|
23
|
-
/** Проверяет относительный путь внутри проекта покомпонентно; отсутствующий путь не symlink. */
|
|
23
|
+
/** Проверяет относительный путь внутри проекта покомпонентно; отсутствующий путь и путь сквозь файл не symlink. */
|
|
24
24
|
export async function pathHasSymlink(root, relativePath) {
|
|
25
25
|
let current = root;
|
|
26
26
|
for (const part of relativePath.split('/')) {
|
|
@@ -30,7 +30,8 @@ export async function pathHasSymlink(root, relativePath) {
|
|
|
30
30
|
return true;
|
|
31
31
|
}
|
|
32
32
|
catch (cause) {
|
|
33
|
-
|
|
33
|
+
const { code } = cause;
|
|
34
|
+
if (code === 'ENOENT' || code === 'ENOTDIR')
|
|
34
35
|
return false;
|
|
35
36
|
throw cause;
|
|
36
37
|
}
|
|
@@ -10,6 +10,7 @@ import { checkProjectEntries } from './entries.js';
|
|
|
10
10
|
import { checkGit } from './git.js';
|
|
11
11
|
import { checkInbox } from './inbox.js';
|
|
12
12
|
import { checkInventory, checkManagedFiles } from './managed.js';
|
|
13
|
+
import { checkMemory } from './memory.js';
|
|
13
14
|
import { checkPlans } from './plans.js';
|
|
14
15
|
import { checkProtocols } from './protocols.js';
|
|
15
16
|
import { checkSources } from './sources.js';
|
|
@@ -114,7 +115,9 @@ export async function doctorProject(rootInput, options = {}) {
|
|
|
114
115
|
checkInventory(manifest, findings);
|
|
115
116
|
const { managedDocs, managedFiles } = await checkManagedFiles(root, manifest, checksums, findings);
|
|
116
117
|
await checkProtocols(root, findings);
|
|
117
|
-
|
|
118
|
+
const wiki = await checkWiki(root, findings);
|
|
119
|
+
checkPlans(root, wiki, findings);
|
|
120
|
+
checkMemory(rootInput, wiki, findings);
|
|
118
121
|
await checkGit(root, managedDocs, findings, managedFiles);
|
|
119
122
|
await checkInbox(root, findings);
|
|
120
123
|
await checkSources(root, findings);
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { countChars, formatChars, HANDOFF_LIMIT, HOT_LIMIT, LOG_LIMIT, PLAN_LIMIT } from '../archive/limits.js';
|
|
2
|
+
import { quotePathArg, serviceInvocation, VERSION } from '../meta.js';
|
|
3
|
+
import { ACTIVE_PLAN_NONE, isCalendarDate, isWikiRelativePlanRef } from '../plan.js';
|
|
4
|
+
import { HOT_PATH } from './plans.js';
|
|
5
|
+
import { frontmatter } from './text.js';
|
|
6
|
+
import { info } from './types.js';
|
|
7
|
+
const LOG_FILE = 'wiki/log.md';
|
|
8
|
+
/** Передача — плоская папка, имя `ГГГГ-ММ-ДД-….md`; прочие имена не проверяются. */
|
|
9
|
+
const HANDOFF_RE = /^wiki\/handoffs\/(\d{4}-\d{2}-\d{2})-[^/]+\.md$/;
|
|
10
|
+
/** Передачи с самой поздней датой в имени: с них начнёт следующая сессия. */
|
|
11
|
+
function latestHandoffs(decoded) {
|
|
12
|
+
const dated = [...decoded.keys()].flatMap((path) => {
|
|
13
|
+
const date = HANDOFF_RE.exec(path)?.[1];
|
|
14
|
+
return date !== undefined && isCalendarDate(date) ? [{ path, date }] : [];
|
|
15
|
+
});
|
|
16
|
+
const latest = dated.reduce((max, item) => (item.date > max ? item.date : max), '');
|
|
17
|
+
return dated.filter((item) => item.date === latest).map((item) => item.path).sort();
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Длина того, что читает начало сессии. Только `info`: пороги — гипотеза
|
|
21
|
+
* (`archive/limits.ts`), и блокировать работу по гипотезе нельзя.
|
|
22
|
+
*/
|
|
23
|
+
export function checkMemory(rootInput, decoded, findings) {
|
|
24
|
+
const archive = `${serviceInvocation(VERSION)} archive --path ${quotePathArg(rootInput)}`;
|
|
25
|
+
const over = (path, limit) => {
|
|
26
|
+
const text = decoded.get(path);
|
|
27
|
+
if (text === undefined)
|
|
28
|
+
return null;
|
|
29
|
+
const chars = countChars(text);
|
|
30
|
+
return chars > limit ? chars : null;
|
|
31
|
+
};
|
|
32
|
+
const size = (chars, limit) => `${formatChars(chars)} знаков при ориентире ${formatChars(limit)}`;
|
|
33
|
+
const hot = over(HOT_PATH, HOT_LIMIT);
|
|
34
|
+
if (hot !== null)
|
|
35
|
+
findings.push(info('memory-hot-long', `Горячий контекст длинный: ${size(hot, HOT_LIMIT)} (около 60 строк). При передаче перепишите его коротко, справочное вынесите в отдельные файлы.`, HOT_PATH));
|
|
36
|
+
const hotText = decoded.get(HOT_PATH);
|
|
37
|
+
const declared = (hotText === undefined ? null : frontmatter(hotText))?.active_plan ?? ACTIVE_PLAN_NONE;
|
|
38
|
+
if (declared !== ACTIVE_PLAN_NONE && isWikiRelativePlanRef(declared)) {
|
|
39
|
+
const path = `wiki/${declared}`;
|
|
40
|
+
const plan = over(path, PLAN_LIMIT);
|
|
41
|
+
if (plan !== null)
|
|
42
|
+
findings.push(info('memory-plan-long', `Активный план длинный: ${size(plan, PLAN_LIMIT)}. Закрытые правки уберите в архив: \`${archive} --section "<начало заголовка>"\` (без --apply только показывает перенос).`, path));
|
|
43
|
+
}
|
|
44
|
+
const log = over(LOG_FILE, LOG_LIMIT);
|
|
45
|
+
if (log !== null)
|
|
46
|
+
findings.push(info('memory-log-long', `Журнал длинный: ${size(log, LOG_LIMIT)}. Старые записи уберите в архив: \`${archive}\` (без --apply только показывает перенос).`, LOG_FILE));
|
|
47
|
+
for (const path of latestHandoffs(decoded)) {
|
|
48
|
+
const handoff = over(path, HANDOFF_LIMIT);
|
|
49
|
+
if (handoff !== null)
|
|
50
|
+
findings.push(info('memory-handoff-long', `Последняя передача длинная: ${size(handoff, HANDOFF_LIMIT)}. Следующую пишите короче, подробности — ссылками; старые передачи — история, их не сокращают.`, path));
|
|
51
|
+
}
|
|
52
|
+
}
|
|
@@ -14,7 +14,7 @@ const NON_PLAN_FILES = new Set(['README.md', 'TEMPLATE.md']);
|
|
|
14
14
|
* ту же границу держит `isWikiRelativePlanRef`, поэтому preflight не может счесть
|
|
15
15
|
* доказанным план, невидимый здесь.
|
|
16
16
|
*/
|
|
17
|
-
function planFileName(path) {
|
|
17
|
+
export function planFileName(path) {
|
|
18
18
|
const match = /^wiki\/plans\/([^/]+\.md)$/.exec(path);
|
|
19
19
|
const name = match?.[1];
|
|
20
20
|
return name === undefined || NON_PLAN_FILES.has(name) ? null : name;
|
package/dist/core/doctor/wiki.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { existsSync } from 'node:fs';
|
|
2
2
|
import { readFile } from 'node:fs/promises';
|
|
3
3
|
import { dirname, relative, resolve, sep } from 'node:path';
|
|
4
|
+
import { parseAudit } from '../audits.js';
|
|
5
|
+
import { isExternalLink, linkPath, markdownLinks } from '../wiki-links.js';
|
|
4
6
|
import { markdownFiles, pathHasSymlink } from './fs-utils.js';
|
|
5
7
|
import { decodeUtf8, frontmatter, hasFrontmatterBlock } from './text.js';
|
|
6
8
|
import { critical, error } from './types.js';
|
|
@@ -32,9 +34,9 @@ export async function checkWiki(root, findings) {
|
|
|
32
34
|
? 'Этот файл wiki должен начинаться frontmatter: строки key: value между ---.'
|
|
33
35
|
: 'Frontmatter не разобран: допустимы строки key: value, комментарии # и списки «- item» под ключом.', path));
|
|
34
36
|
}
|
|
35
|
-
for (const
|
|
36
|
-
const destination = (
|
|
37
|
-
if (!destination ||
|
|
37
|
+
for (const link of markdownLinks(text)) {
|
|
38
|
+
const destination = linkPath(link.destination);
|
|
39
|
+
if (!destination || isExternalLink(destination))
|
|
38
40
|
continue;
|
|
39
41
|
let raw;
|
|
40
42
|
try {
|
|
@@ -56,38 +58,12 @@ export async function checkWiki(root, findings) {
|
|
|
56
58
|
findings.push(error('text-unreadable', `Не удалось прочитать Markdown: ${cause instanceof Error ? cause.message : String(cause)}`, path));
|
|
57
59
|
}
|
|
58
60
|
}
|
|
59
|
-
const auditStatuses = new Set(['open', 'resolved']);
|
|
60
61
|
for (const [path, text] of decoded) {
|
|
61
|
-
if (!/^wiki\/audits\/[^/]+\.md$/.test(path))
|
|
62
|
+
if (!/^wiki\/audits\/(?:archive\/)?[^/]+\.md$/.test(path))
|
|
62
63
|
continue;
|
|
63
|
-
const
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
if (starts.length === 0)
|
|
67
|
-
malformed = true;
|
|
68
|
-
const ids = new Set();
|
|
69
|
-
for (let index = 0; index < starts.length; index += 1) {
|
|
70
|
-
const current = starts[index];
|
|
71
|
-
const id = current?.[1] ?? '';
|
|
72
|
-
const body = text.slice((current?.index ?? 0) + (current?.[0].length ?? 0), starts[index + 1]?.index ?? text.length);
|
|
73
|
-
const fields = (name) => [...body.matchAll(new RegExp(`^- ${name}:[ \\t]*(.*?)[ \\t]*$`, 'gm'))].map((match) => match[1]?.trim() ?? '');
|
|
74
|
-
const severityValues = fields('severity');
|
|
75
|
-
const targetValues = fields('target');
|
|
76
|
-
const evidenceValues = fields('evidence');
|
|
77
|
-
const statusValues = fields('status');
|
|
78
|
-
const resolutionValues = fields('resolution');
|
|
79
|
-
const severity = severityValues[0];
|
|
80
|
-
const status = statusValues[0];
|
|
81
|
-
if (ids.has(id) || severityValues.length !== 1 || targetValues.length !== 1 || evidenceValues.length !== 1 || statusValues.length !== 1 || resolutionValues.length !== 1 || !['critical', 'high', 'medium', 'low'].includes(severity ?? '') || !targetValues[0] || !evidenceValues[0] || !auditStatuses.has(status ?? '') || !resolutionValues[0])
|
|
82
|
-
malformed = true;
|
|
83
|
-
else if (meta?.status !== 'open' && status === 'open')
|
|
84
|
-
malformed = true;
|
|
85
|
-
else if ((severity === 'critical' || severity === 'high') && status === 'open')
|
|
86
|
-
findings.push(error('audit-blocking-finding', `Открытая ${severity} находка ${id} блокирует doctor.`, path));
|
|
87
|
-
ids.add(id);
|
|
88
|
-
}
|
|
89
|
-
if (/^## Finding /m.test(text) && starts.length === 0)
|
|
90
|
-
malformed = true;
|
|
64
|
+
const { malformed, blocking } = parseAudit(text);
|
|
65
|
+
for (const { id, severity } of blocking)
|
|
66
|
+
findings.push(error('audit-blocking-finding', `Открытая ${severity} находка ${id} блокирует doctor.`, path));
|
|
91
67
|
if (malformed)
|
|
92
68
|
findings.push(error('audit-malformed', 'Audit требует audit_id, допустимый status и валидные findings.', path));
|
|
93
69
|
}
|
package/dist/core/plan.js
CHANGED
|
@@ -39,12 +39,24 @@ export const PLAN_APPROVAL_DIGEST_KEY = 'approved_digest';
|
|
|
39
39
|
export const PLAN_DIGEST_KEYS = ['id', 'kind', 'scale', 'mode', 'governance', 'risk', 'profiles', 'sources', 'supersedes'];
|
|
40
40
|
/** Отметка пункта списка `[x]` или `[X]`: в отпечатке она считается `[ ]`, а текст пункта — нет. */
|
|
41
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, () => '[ ]');
|
|
42
53
|
/**
|
|
43
54
|
* sha256 утверждённого: классификация из frontmatter плюс текст плана (LF, без хвостовых
|
|
44
|
-
* пробелов). Отметки выполненных пунктов не входят:
|
|
55
|
+
* пробелов). Отметки выполненных пунктов и строки итога не входят: закрыть порцию — не
|
|
56
|
+
* изменить план. Без строк итога отпечаток тот же, что в 0.4.3.
|
|
45
57
|
*/
|
|
46
58
|
export function planBodyDigest(text) {
|
|
47
|
-
return digest(text, (body) => body
|
|
59
|
+
return digest(text, (body) => clearMarks(dropResults(body)));
|
|
48
60
|
}
|
|
49
61
|
/**
|
|
50
62
|
* Отпечаток 0.3.0–0.4.2, где отметки пунктов ещё входили в текст. Принимается, чтобы
|
|
@@ -53,9 +65,19 @@ export function planBodyDigest(text) {
|
|
|
53
65
|
export function legacyPlanBodyDigest(text) {
|
|
54
66
|
return digest(text, (body) => body);
|
|
55
67
|
}
|
|
56
|
-
/**
|
|
68
|
+
/**
|
|
69
|
+
* Записанный отпечаток совпадает с планом — нынешним способом или одним из прежних.
|
|
70
|
+
* Строка итога не мешает ни одному: в отпечатке 0.3.0–0.4.2 отметки входят в текст, поэтому
|
|
71
|
+
* порция с итогом читается и как закрытая до утверждения, и как закрытая после него.
|
|
72
|
+
*/
|
|
57
73
|
export function planDigestMatches(approvedDigest, text) {
|
|
58
|
-
return
|
|
74
|
+
return [
|
|
75
|
+
planBodyDigest(text),
|
|
76
|
+
digest(text, clearMarks),
|
|
77
|
+
legacyPlanBodyDigest(text),
|
|
78
|
+
digest(text, dropResults),
|
|
79
|
+
digest(text, reopenResults),
|
|
80
|
+
].includes(approvedDigest);
|
|
59
81
|
}
|
|
60
82
|
function digest(text, normalizeBody) {
|
|
61
83
|
const match = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(text);
|