create-vibe-maestro 0.4.3 → 0.4.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/CHANGELOG.md +73 -0
  2. package/README.md +7 -7
  3. package/dist/cli/archive-run.js +75 -0
  4. package/dist/cli/context-run.js +3 -2
  5. package/dist/cli/maestro.js +22 -3
  6. package/dist/cli/upgrade-run.js +10 -2
  7. package/dist/core/archive/audits.js +37 -0
  8. package/dist/core/archive/disk.js +38 -0
  9. package/dist/core/archive/index.js +286 -0
  10. package/dist/core/archive/limits.js +35 -0
  11. package/dist/core/archive/links.js +65 -0
  12. package/dist/core/archive/log.js +83 -0
  13. package/dist/core/archive/markdown.js +28 -0
  14. package/dist/core/archive/plan.js +220 -0
  15. package/dist/core/archive/types.js +1 -0
  16. package/dist/core/audits.js +37 -0
  17. package/dist/core/context.js +23 -9
  18. package/dist/core/doctor/fs-utils.js +3 -2
  19. package/dist/core/doctor/git.js +1 -1
  20. package/dist/core/doctor/index.js +6 -1
  21. package/dist/core/doctor/memory-lag.js +79 -0
  22. package/dist/core/doctor/memory.js +52 -0
  23. package/dist/core/doctor/plans.js +1 -1
  24. package/dist/core/doctor/wiki.js +9 -33
  25. package/dist/core/plan.js +26 -4
  26. package/dist/core/transaction.js +132 -0
  27. package/dist/core/upgrade/analyze.js +14 -3
  28. package/dist/core/upgrade/baseline.js +2 -0
  29. package/dist/core/upgrade/index.js +15 -112
  30. package/dist/core/upgrade/releases.js +95 -1
  31. package/dist/core/wiki-links.js +27 -0
  32. package/docs/ROADMAP.md +21 -3
  33. package/docs/USER_GUIDE.md +66 -16
  34. package/package.json +1 -1
  35. package/registry/baseline/0.4.3/project/.claude/rules/maestro.md +40 -0
  36. package/registry/baseline/0.4.3/project/maestro/templates/handoff.md +29 -0
  37. package/registry/baseline/0.4.3/project/protocols/build.md +120 -0
  38. package/registry/baseline/0.4.3/project/protocols/completion.md +23 -0
  39. package/registry/baseline/0.4.3/project/protocols/handoff.md +17 -0
  40. package/registry/baseline/0.4.3/project/protocols/plan.md +159 -0
  41. package/registry/baseline/0.4.3/project/protocols/status.md +5 -0
  42. package/registry/baseline/0.4.3/project/protocols/wiki.md +17 -0
  43. package/registry/baseline/0.4.3/project/wiki/plans/README.md +135 -0
  44. package/registry/baseline/0.4.3/project/wiki/plans/TEMPLATE.md +83 -0
  45. package/registry/baseline/0.4.4/project/.claude/rules/maestro.md +41 -0
  46. package/registry/baseline/0.4.4/project/maestro/templates/audit.md +31 -0
  47. package/registry/baseline/0.4.4/project/maestro/templates/handoff.md +29 -0
  48. package/registry/baseline/0.4.4/project/protocols/audit.md +74 -0
  49. package/registry/baseline/0.4.4/project/protocols/build.md +120 -0
  50. package/registry/baseline/0.4.4/project/protocols/completion.md +23 -0
  51. package/registry/baseline/0.4.4/project/protocols/handoff.md +18 -0
  52. package/templates/project/.claude/rules/maestro.md +3 -2
  53. package/templates/project/maestro/templates/audit.md +3 -3
  54. package/templates/project/maestro/templates/handoff.md +10 -3
  55. package/templates/project/protocols/audit.md +11 -8
  56. package/templates/project/protocols/build.md +4 -4
  57. package/templates/project/protocols/completion.md +4 -4
  58. package/templates/project/protocols/handoff.md +8 -7
  59. package/templates/project/protocols/plan.md +3 -2
  60. package/templates/project/protocols/status.md +1 -1
  61. package/templates/project/protocols/wiki.md +1 -1
  62. package/templates/project/wiki/index.md +4 -0
  63. package/templates/project/wiki/log.md +1 -0
  64. package/templates/project/wiki/plans/0001-starter.md +2 -2
  65. package/templates/project/wiki/plans/README.md +21 -1
  66. package/templates/project/wiki/plans/TEMPLATE.md +10 -1
@@ -0,0 +1,220 @@
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 OPEN_MARK_RE = /(?<![\p{L}\p{N}_])(?:UNKNOWN|OPEN_QUESTION|HYPOTHESIS|не\s+проверено|открыто)(?![\p{L}\p{N}_])/iu;
66
+ /** Строка находок с нулём открытых содержит «открыто», но пометкой не является. */
67
+ const CLOSED_FINDINGS_RE = /Находки:\s*critical\s+\d+,\s*high\s+\d+,\s*medium\s+\d+,\s*low\s+\d+;\s*открыто\s+0(?!\d)/;
68
+ /** Раздел бывает в десятки тысяч знаков: агент видит сами строки и не перечитывает его. */
69
+ const SHOWN_MARKS = 3;
70
+ const SHOWN_CHARS = 100;
71
+ /** Сколько заголовков показать в отказе: у живых планов их сотни. */
72
+ const LISTED = 30;
73
+ /** Заголовки и аргументы сравниваются без разметки и с одинарными пробелами. */
74
+ export function plainTitle(value) {
75
+ return value.replace(/`|\*\*|[«»]/g, '').replace(/\s+/g, ' ').trim();
76
+ }
77
+ const startsWithWord = (title, wanted) => title.startsWith(wanted) && !WORD_RE.test(title.slice(wanted.length));
78
+ export function mentionsSlice(text, slice) {
79
+ const escaped = slice.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
80
+ return new RegExp(`(?<![\\p{L}\\p{N}_])${escaped}(?![\\p{L}\\p{N}_])`, 'u').test(text);
81
+ }
82
+ export function planHeadings(text) {
83
+ const body = /^\uFEFF?---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/.exec(text)?.[0].length ?? 0;
84
+ const headings = [];
85
+ for (const { line, offset, code } of markdownLines(text)) {
86
+ if (code || offset < body)
87
+ continue;
88
+ const match = HEADING_RE.exec(line);
89
+ if (match !== null)
90
+ headings.push({ level: match[1]?.length ?? 0, line, title: plainTitle(match[2] ?? ''), start: offset, end: text.length });
91
+ }
92
+ headings.forEach((heading, index) => {
93
+ heading.end = headings.slice(index + 1).find((next) => next.level <= heading.level)?.start ?? text.length;
94
+ });
95
+ return headings;
96
+ }
97
+ function listed(headings) {
98
+ const shown = headings.slice(0, LISTED).map((heading) => `«${heading.title.slice(0, 80)}»`).join('; ');
99
+ return headings.length > LISTED ? `${shown}; и ещё ${headings.length - LISTED}` : shown;
100
+ }
101
+ function chooseSection(text, plan, argument, headings, collection) {
102
+ const wanted = plainTitle(argument);
103
+ const candidates = headings.filter((heading) => heading.level === 2 || heading.level === 3);
104
+ const found = wanted === '' ? [] : candidates.filter((heading) => startsWithWord(heading.title, wanted));
105
+ const movable = candidates.filter((heading) => heading.start > collection.start);
106
+ if (found.length === 0)
107
+ return { blocker: blocker('archive-section-not-found', `В плане нет раздела, заголовок которого начинается с «${argument}». Правки плана: ${listed(movable) || 'их нет'}.`, plan.path) };
108
+ if (found.length > 1)
109
+ return { blocker: blocker('archive-section-ambiguous', `«${argument}» подходит к разделам: ${listed(found)}. Уточните начало заголовка; одинаковые заголовки так не перенести.`, plan.path) };
110
+ const heading = found[0];
111
+ const title = `«${heading.title}»`;
112
+ if (heading === collection || COLLECTIONS.includes(heading.title))
113
+ return { blocker: blocker('archive-section-collection', `${title} — сборник правок: внутри могут быть и открытые. Называйте закрытые правки по одной.`, plan.path) };
114
+ if (heading.start < collection.start)
115
+ return { blocker: blocker('archive-section-main-part', `${title} — основная часть плана, она в архив не переносится. Переносить можно только разделы ниже «${collection.title}».`, plan.path) };
116
+ const nested = headings.filter((other) => other.start > heading.start && other.start < heading.end);
117
+ const slice = plan.meta?.current_slice;
118
+ const declaredSlice = slice === undefined || slice === PLAN_NULL ? null : slice;
119
+ for (const part of [heading, ...nested]) {
120
+ if (COLLECTIONS.includes(part.title))
121
+ return { blocker: blocker('archive-section-collection', `Внутри ${title} стоит сборник правок «${part.title}»: внутри него могут быть и открытые.`, plan.path) };
122
+ if (part === heading ? startsWithWord(part.title, APPROVAL) : part.title === APPROVAL)
123
+ return { blocker: blocker('archive-section-approval', `«${part.title}» — запись об утверждении плана, она остаётся в плане.`, plan.path) };
124
+ if (declaredSlice !== null && mentionsSlice(part.title, declaredSlice))
125
+ return { blocker: blocker('archive-section-current-slice', `В заголовке «${part.title}» стоит текущая порция ${declaredSlice}: открытое в архив не переносится.`, plan.path) };
126
+ }
127
+ const section = text.slice(heading.start, heading.end);
128
+ const rest = section.slice(heading.line.length);
129
+ const warnings = [];
130
+ if (declaredSlice !== null && mentionsSlice(rest, declaredSlice))
131
+ warnings.push(`раздел ${title} упоминает текущую порцию ${declaredSlice}.`);
132
+ const unchecked = [...rest.matchAll(UNCHECKED_RE)].length;
133
+ if (unchecked > 0)
134
+ warnings.push(`в разделе ${title} неотмеченных пунктов [ ]: ${formatChars(unchecked)}.`);
135
+ const already = POINTER_RE.test(rest.trim());
136
+ const marks = already ? null : openMarksWarning(title, section);
137
+ if (marks !== null)
138
+ warnings.push(marks);
139
+ return { choice: { heading, nested, already, warnings } };
140
+ }
141
+ /** Строка с пометкой, не длиннее `SHOWN_CHARS` кодовых точек; слово остаётся видно и в длинной строке. */
142
+ function shownLine(line, mark) {
143
+ const points = [...line];
144
+ if (points.length <= SHOWN_CHARS)
145
+ return line;
146
+ const before = [...line.slice(0, mark)].length;
147
+ const start = before < SHOWN_CHARS / 2 ? 0 : Math.min(before - SHOWN_CHARS / 4, points.length - SHOWN_CHARS);
148
+ const shown = points.slice(start, start + SHOWN_CHARS).join('');
149
+ return `${start > 0 ? '…' : ''}${shown}${start + SHOWN_CHARS < points.length ? '…' : ''}`;
150
+ }
151
+ /** Предупреждение о пометках незакрытого в тексте раздела; блоки кода не считаются. */
152
+ function openMarksWarning(title, section) {
153
+ const found = [];
154
+ for (const { line, code } of markdownLines(section)) {
155
+ if (code)
156
+ continue;
157
+ const text = line.trim();
158
+ const mark = OPEN_MARK_RE.exec(text.replace(CLOSED_FINDINGS_RE, (found) => ' '.repeat(found.length)));
159
+ if (mark !== null)
160
+ found.push(`«${shownLine(text, mark.index)}»`);
161
+ }
162
+ if (found.length === 0)
163
+ return null;
164
+ const more = found.length > SHOWN_MARKS ? `; ещё ${formatChars(found.length - SHOWN_MARKS)}` : '';
165
+ return `в разделе ${title} есть пометки незакрытого: ${found.slice(0, SHOWN_MARKS).join('; ')}${more}. Закрыто — переносите; открыто — сначала запишите в wiki/hot.md или wiki/icebox.md: обратно архив не копируют.`;
166
+ }
167
+ /** `active_plan` из `wiki/hot.md`. */
168
+ export function declaredPlan(files) {
169
+ const hot = files.get(HOT_PATH);
170
+ return (hot === undefined ? null : frontmatter(withoutBom(hot)))?.active_plan ?? ACTIVE_PLAN_NONE;
171
+ }
172
+ /** Находит названные разделы активного плана; ничего не меняет. */
173
+ export function resolveSections(files, plans, wanted) {
174
+ const refuse = (item, plan = null) => ({ plan, chosen: [], blockers: [item] });
175
+ const declared = declaredPlan(files);
176
+ if (declared === ACTIVE_PLAN_NONE)
177
+ return refuse(blocker('archive-section-no-plan', 'Активного плана нет (active_plan: none): --section работает только в активном плане.', HOT_PATH));
178
+ const plan = isWikiRelativePlanRef(declared) ? plans.find((item) => item.path === `wiki/${declared}`) : undefined;
179
+ if (plan === undefined)
180
+ return refuse(blocker('archive-section-plan-missing', `Объявленный активный план не найден: ${declared}.`, HOT_PATH));
181
+ if (plan.meta === null)
182
+ return refuse(blocker('archive-section-plan-invalid', 'Frontmatter плана не разобран: сначала поправьте его (doctor).', plan.path), plan);
183
+ if (!plan.intact)
184
+ return refuse(blocker('archive-plan-changed', 'Текст плана изменился после утверждения (approved_digest не совпадает): перенос записал бы новый отпечаток поверх неутверждённой правки. Покажите изменения человеку; после его «да» запишите отпечаток из вывода preflight и повторите.', plan.path), plan);
185
+ const headings = planHeadings(plan.text);
186
+ const collection = headings.find((heading) => (heading.level === 2 || heading.level === 3) && COLLECTIONS.some((name) => startsWithWord(heading.title, name)));
187
+ if (collection === undefined)
188
+ return refuse(blocker('archive-section-no-collection', `В плане нет раздела «${COLLECTIONS[0]}» или «${COLLECTIONS[1]}»: переносить можно только правки, которые стоят ниже него.`, plan.path), plan);
189
+ const chosen = [];
190
+ const blockers = [];
191
+ for (const argument of wanted) {
192
+ const result = chooseSection(plan.text, plan, argument, headings, collection);
193
+ if (result.blocker !== undefined)
194
+ blockers.push(result.blocker);
195
+ else if (result.choice !== undefined) {
196
+ const { heading } = result.choice;
197
+ const overlapping = chosen.find((other) => heading.start < other.heading.end && other.heading.start < heading.end);
198
+ if (overlapping !== undefined)
199
+ blockers.push(blocker('archive-section-overlap', `Разделы «${overlapping.heading.title}» и «${heading.title}» пересекаются: назовите один из них.`, plan.path));
200
+ else
201
+ chosen.push(result.choice);
202
+ }
203
+ }
204
+ return { plan, chosen, blockers };
205
+ }
206
+ export function cutSections(text, chosen, archivePath, eol) {
207
+ const name = posix.basename(archivePath);
208
+ const sections = [];
209
+ let remaining = '';
210
+ let cursor = 0;
211
+ for (const { heading } of [...chosen].filter((item) => !item.already).sort((left, right) => left.heading.start - right.heading.start)) {
212
+ sections.push(text.slice(heading.start, heading.end));
213
+ const line = /\n$/.test(heading.line) ? heading.line : `${heading.line}${eol}`;
214
+ remaining += `${text.slice(cursor, heading.start)}${line}${eol}В архиве: [${name.replace(/[[\]]/g, '')}](archive/${linkName(name)}).${eol}${eol}`;
215
+ cursor = heading.end;
216
+ }
217
+ return { remaining: remaining + text.slice(cursor), sections };
218
+ }
219
+ /** Размер раздела для отчёта. */
220
+ 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
+ }
@@ -41,9 +41,15 @@ export function windowForModel(model) {
41
41
  return DEFAULT_BUDGET;
42
42
  return LARGE_WINDOW;
43
43
  }
44
- /** HYPOTHESIS: пороги подобраны на глаз и уточняются повторным замером. */
45
- export const FINISH_SLICE_SHARE = 0.4;
46
- export const NEW_SESSION_SHARE = 0.7;
44
+ /**
45
+ * Пороги в токенах: цену шага задаёт размер сессии, а не доля окна.
46
+ * HYPOTHESIS: числа — из проигрыша настоящих сессий, уточняются повторным замером.
47
+ */
48
+ export const FINISH_SLICE_TOKENS = 400_000;
49
+ export const NEW_SESSION_TOKENS = 600_000;
50
+ /** У модели с меньшим окном действует меньшее из двух: порог выше окна не сработал бы. */
51
+ const FINISH_SLICE_PERCENT = 40;
52
+ const NEW_SESSION_PERCENT = 70;
47
53
  /** Имя папки журналов: Claude Code заменяет в пути проекта всё, кроме латиницы и цифр, на `-`. */
48
54
  export function projectLogDirName(root) {
49
55
  return resolve(root).replace(/[^a-zA-Z0-9]/g, '-');
@@ -124,10 +130,18 @@ export async function findTranscript(root, claudeDir, sessionId) {
124
130
  return best?.path ?? null;
125
131
  }
126
132
  const count = (value) => (typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0);
127
- export function levelFor(share) {
128
- if (share >= NEW_SESSION_SHARE)
133
+ /** Пороги при этом окне. Токены — целые, поэтому округление вверх не сдвигает границу. */
134
+ export function thresholdsFor(budget) {
135
+ return {
136
+ finishSliceTokens: Math.min(FINISH_SLICE_TOKENS, Math.ceil((budget * FINISH_SLICE_PERCENT) / 100)),
137
+ newSessionTokens: Math.min(NEW_SESSION_TOKENS, Math.ceil((budget * NEW_SESSION_PERCENT) / 100)),
138
+ };
139
+ }
140
+ export function levelFor(tokens, budget) {
141
+ const { finishSliceTokens, newSessionTokens } = thresholdsFor(budget);
142
+ if (tokens >= newSessionTokens)
129
143
  return 'new-session';
130
- if (share >= FINISH_SLICE_SHARE)
144
+ if (tokens >= finishSliceTokens)
131
145
  return 'finish-slice';
132
146
  return 'continue';
133
147
  }
@@ -196,7 +210,6 @@ export async function measureContext(options) {
196
210
  if ((byModel === null ? largest : largestByModel.get(lastModel ?? '') ?? 0) > budget)
197
211
  budget = LARGE_WINDOW;
198
212
  }
199
- const share = contextTokens / budget;
200
213
  return {
201
214
  reportVersion: 1,
202
215
  ok: true,
@@ -206,8 +219,9 @@ export async function measureContext(options) {
206
219
  budget,
207
220
  ...(lastModel === undefined ? {} : { model: lastModel }),
208
221
  windowSource,
209
- percent: Math.round(share * 100),
210
- level: levelFor(share),
222
+ percent: Math.round((contextTokens / budget) * 100),
223
+ level: levelFor(contextTokens, budget),
224
+ ...thresholdsFor(budget),
211
225
  totalInputTokens: totalInput,
212
226
  requests: seen.size,
213
227
  };
@@ -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
- if (cause.code === 'ENOENT')
33
+ const { code } = cause;
34
+ if (code === 'ENOENT' || code === 'ENOTDIR')
34
35
  return false;
35
36
  throw cause;
36
37
  }
@@ -50,7 +50,7 @@ export async function checkGit(root, managedDocs, findings, managedFiles = new S
50
50
  }
51
51
  }
52
52
  /** Команда git, чей отказ — ответ «нет», а не сбой проверки. */
53
- async function gitAnswer(root, args) {
53
+ export async function gitAnswer(root, args) {
54
54
  try {
55
55
  return (await execFileAsync('git', [...args], { cwd: root, encoding: 'utf8' })).stdout.trim();
56
56
  }
@@ -10,6 +10,8 @@ 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';
14
+ import { checkMemoryLag } from './memory-lag.js';
13
15
  import { checkPlans } from './plans.js';
14
16
  import { checkProtocols } from './protocols.js';
15
17
  import { checkSources } from './sources.js';
@@ -114,8 +116,11 @@ export async function doctorProject(rootInput, options = {}) {
114
116
  checkInventory(manifest, findings);
115
117
  const { managedDocs, managedFiles } = await checkManagedFiles(root, manifest, checksums, findings);
116
118
  await checkProtocols(root, findings);
117
- checkPlans(root, await checkWiki(root, findings), findings);
119
+ const wiki = await checkWiki(root, findings);
120
+ checkPlans(root, wiki, findings);
121
+ checkMemory(rootInput, wiki, findings);
118
122
  await checkGit(root, managedDocs, findings, managedFiles);
123
+ await checkMemoryLag(root, wiki, findings);
119
124
  await checkInbox(root, findings);
120
125
  await checkSources(root, findings);
121
126
  await checkProjectEntries(root, manifest.product.version, findings);
@@ -0,0 +1,79 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { existsSync } from 'node:fs';
3
+ import { stat } from 'node:fs/promises';
4
+ import { join } from 'node:path';
5
+ import { promisify } from 'node:util';
6
+ import { HANDOFF_COMMITS_LIMIT, HOT_BEHIND_COMMITS } from '../archive/limits.js';
7
+ import { withoutBom } from '../archive/markdown.js';
8
+ import { declaredPlan, mentionsSlice } from '../archive/plan.js';
9
+ import { MANIFEST_PATH } from '../manifest.js';
10
+ import { ACTIVE_PLAN_NONE, isWikiRelativePlanRef, PLAN_NULL } from '../plan.js';
11
+ import { gitAnswer, parsePorcelainV1Z } from './git.js';
12
+ import { HOT_PATH } from './plans.js';
13
+ import { frontmatter } from './text.js';
14
+ import { info } from './types.js';
15
+ const execFileAsync = promisify(execFile);
16
+ /** `glob`: передача — плоская папка, вложенные файлы передачами не считаются. */
17
+ const HANDOFFS = ':(glob)wiki/handoffs/*.md';
18
+ const CHECK_LOG = 'Если работа идёт не в этой сессии — сверь `git log` и запиши передачу.';
19
+ /** Коммит, добавивший файл: передача считается добавленной один раз, поправленная ссылка в ней счёт не сбрасывает. */
20
+ const lastAdded = (root, path) => gitAnswer(root, ['log', '-1', '-M', '--diff-filter=A', '--format=%H', '--', path]);
21
+ /** Текст без шапки: `active_plan` в ней может совпасть с именем порции. */
22
+ const withoutFrontmatter = (text) => withoutBom(text).replace(/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/, '');
23
+ /** Передача ещё не закоммичена и свежее последнего коммита: на шаге передачи doctor идёт до коммита. */
24
+ async function handoffInProgress(root) {
25
+ const committed = Number(await gitAnswer(root, ['log', '-1', '--format=%ct']));
26
+ try {
27
+ const { stdout } = await execFileAsync('git', ['status', '--porcelain=v1', '-z', '--untracked-files=all', '--', HANDOFFS], { cwd: root, encoding: 'utf8' });
28
+ for (const entry of parsePorcelainV1Z(stdout)) {
29
+ if (entry.status !== '??' && !entry.status.includes('A'))
30
+ continue;
31
+ if ((await stat(join(root, entry.path))).mtimeMs >= committed * 1000)
32
+ return true;
33
+ }
34
+ return false;
35
+ }
36
+ catch {
37
+ return true;
38
+ }
39
+ }
40
+ /** Текущая порция активного плана; null — порции нет. */
41
+ function currentSlice(wiki) {
42
+ const declared = declaredPlan(wiki);
43
+ if (declared === ACTIVE_PLAN_NONE || !isWikiRelativePlanRef(declared))
44
+ return null;
45
+ const plan = wiki.get(`wiki/${declared}`);
46
+ const slice = plan === undefined ? undefined : frontmatter(withoutBom(plan))?.current_slice;
47
+ return slice === undefined || slice === PLAN_NULL || slice === '' ? null : slice;
48
+ }
49
+ /**
50
+ * Отстала ли память от кода: только с доказательством из git. Опора — последняя
51
+ * добавленная передача, а пока передач нет — коммит с manifest, чтобы история до
52
+ * Maestro не считалась. Нет `.git`, нет опоры, мелкий клон, отказ git — молчит.
53
+ * Только `info`: посреди обычной порции это тоже срабатывает, а пороги — гипотеза.
54
+ */
55
+ export async function checkMemoryLag(root, wiki, findings) {
56
+ if (!existsSync(join(root, '.git')))
57
+ return;
58
+ // В мелком клоне самый ранний коммит «добавляет» всё сразу: опора была бы ложной.
59
+ if (await gitAnswer(root, ['rev-parse', '--is-shallow-repository']) !== 'false')
60
+ return;
61
+ const handoff = await lastAdded(root, HANDOFFS);
62
+ const anchor = handoff === '' ? await lastAdded(root, MANIFEST_PATH) : handoff;
63
+ if (anchor === null || anchor === '')
64
+ return;
65
+ const answer = await gitAnswer(root, ['rev-list', '--count', `${anchor}..HEAD`, '--', '.', ':(exclude)wiki']);
66
+ const commits = answer === null ? Number.NaN : Number(answer);
67
+ if (!Number.isInteger(commits) || commits < HOT_BEHIND_COMMITS)
68
+ return;
69
+ if (await handoffInProgress(root))
70
+ return;
71
+ const counted = handoff === '' ? `передач ещё не было, а коммитов кода с подключения Maestro: ${commits}` : `после последней передачи коммитов кода: ${commits}`;
72
+ const slice = currentSlice(wiki);
73
+ if (slice !== null && !mentionsSlice(withoutFrontmatter(wiki.get(HOT_PATH) ?? ''), slice)) {
74
+ findings.push(info('memory-hot-behind', `wiki/hot.md не называет текущую порцию ${slice}, ${counted}. ${CHECK_LOG}`, HOT_PATH));
75
+ }
76
+ if (commits >= HANDOFF_COMMITS_LIMIT) {
77
+ findings.push(info('memory-handoff-behind', `Отстала передача: ${counted} при ориентире ${HANDOFF_COMMITS_LIMIT}. ${CHECK_LOG}`));
78
+ }
79
+ }
@@ -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;
@@ -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 match of text.matchAll(/\[[^\]]*\]\((?:<([^>]+)>|([^\s)]+))(?:\s+['"][^'"]*['"])?\)/g)) {
36
- const destination = (match[1] ?? match[2] ?? '').split('#')[0]?.trim();
37
- if (!destination || /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(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 meta = frontmatter(text);
64
- let malformed = !meta?.audit_id || !meta.status || !auditStatuses.has(meta.status);
65
- const starts = [...text.matchAll(/^## Finding ([A-Za-z0-9][A-Za-z0-9._-]*)\s*$/gm)];
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.replace(CHECKED_ITEM_RE, '$1[ ]'));
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 approvedDigest === planBodyDigest(text) || approvedDigest === legacyPlanBodyDigest(text);
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);