create-vibe-maestro 0.4.4 → 0.4.6

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 (47) hide show
  1. package/CHANGELOG.md +76 -0
  2. package/README.md +141 -164
  3. package/dist/cli/archive-run.js +29 -4
  4. package/dist/cli/context-run.js +23 -2
  5. package/dist/cli/upgrade-run.js +10 -2
  6. package/dist/core/archive/index.js +10 -3
  7. package/dist/core/archive/limits.js +8 -0
  8. package/dist/core/archive/plan.js +78 -7
  9. package/dist/core/context.js +56 -9
  10. package/dist/core/doctor/git.js +1 -1
  11. package/dist/core/doctor/index.js +2 -0
  12. package/dist/core/doctor/memory-lag.js +79 -0
  13. package/dist/core/doctor/sources.js +1 -1
  14. package/dist/core/preflight.js +6 -2
  15. package/dist/core/upgrade/index.js +2 -0
  16. package/dist/core/upgrade/releases.js +96 -2
  17. package/docs/ROADMAP.md +63 -2
  18. package/docs/USER_GUIDE.md +62 -24
  19. package/package.json +1 -1
  20. package/registry/baseline/0.4.4/project/.claude/rules/maestro.md +41 -0
  21. package/registry/baseline/0.4.4/project/maestro/templates/audit.md +31 -0
  22. package/registry/baseline/0.4.4/project/maestro/templates/handoff.md +29 -0
  23. package/registry/baseline/0.4.4/project/protocols/audit.md +74 -0
  24. package/registry/baseline/0.4.4/project/protocols/build.md +120 -0
  25. package/registry/baseline/0.4.4/project/protocols/completion.md +23 -0
  26. package/registry/baseline/0.4.4/project/protocols/handoff.md +18 -0
  27. package/registry/baseline/0.4.5/project/.claude/rules/maestro.md +41 -0
  28. package/registry/baseline/0.4.5/project/maestro/runbooks/cowork-audit.md +18 -0
  29. package/registry/baseline/0.4.5/project/maestro/templates/audit.md +31 -0
  30. package/registry/baseline/0.4.5/project/maestro/templates/handoff.md +36 -0
  31. package/registry/baseline/0.4.5/project/maestro/templates/progress.md +22 -0
  32. package/registry/baseline/0.4.5/project/protocols/audit.md +77 -0
  33. package/registry/baseline/0.4.5/project/protocols/build.md +120 -0
  34. package/registry/baseline/0.4.5/project/protocols/completion.md +23 -0
  35. package/registry/baseline/0.4.5/project/protocols/handoff.md +18 -0
  36. package/registry/baseline/0.4.5/project/protocols/plan.md +160 -0
  37. package/templates/project/.claude/rules/maestro.md +2 -2
  38. package/templates/project/maestro/runbooks/cowork-audit.md +1 -1
  39. package/templates/project/maestro/templates/audit.md +5 -5
  40. package/templates/project/maestro/templates/handoff.md +13 -4
  41. package/templates/project/maestro/templates/progress.md +12 -10
  42. package/templates/project/protocols/audit.md +13 -10
  43. package/templates/project/protocols/build.md +12 -4
  44. package/templates/project/protocols/completion.md +3 -3
  45. package/templates/project/protocols/handoff.md +10 -10
  46. package/templates/project/protocols/plan.md +1 -1
  47. package/templates/project/wiki/log.md +2 -3
@@ -5,7 +5,31 @@ import { plainTitle } from '../core/archive/plan.js';
5
5
  import { quotePathArg, serviceInvocation, VERSION } from '../core/meta.js';
6
6
  import { EXIT_FAILED, EXIT_OK } from './io.js';
7
7
  const DIGEST_SHOWN = 12;
8
- function describe(report, io) {
8
+ /** Сколько правок плана показать: у живых планов их десятки. */
9
+ const EDITS_SHOWN = 10;
10
+ const EDIT_TITLE_CHARS = 80;
11
+ /** Без `--section`: какие правки плана можно перенести. Только подсказка: сама команда их не трогает. */
12
+ function describePlanEdits(report, path, io) {
13
+ const edits = report.planEdits;
14
+ if (edits === null || edits.sections.length === 0)
15
+ return;
16
+ const total = edits.sections.reduce((sum, item) => sum + item.chars, 0);
17
+ io.out(`- Правки плана ${edits.plan}, которые можно перенести в архив: ${formatChars(edits.sections.length)}, вместе ${formatChars(total)} знаков. Сама команда их не трогает — называйте по одной через --section:`);
18
+ const shown = [...edits.sections].sort((left, right) => right.chars - left.chars).slice(0, EDITS_SHOWN);
19
+ for (const item of shown) {
20
+ const title = [...item.heading].length > EDIT_TITLE_CHARS ? `${[...item.heading].slice(0, EDIT_TITLE_CHARS).join('')}…` : item.heading;
21
+ const note = item.open ? ' — есть незакрытое, переносить рано' : item.currentSlice ? ' — упоминает текущую порцию, проверьте' : '';
22
+ io.out(` - «${title}»: ${formatChars(item.chars)} знаков${note}.`);
23
+ }
24
+ if (edits.sections.length > shown.length) {
25
+ const rest = total - shown.reduce((sum, item) => sum + item.chars, 0);
26
+ io.out(` - и ещё ${formatChars(edits.sections.length - shown.length)} поменьше, вместе ${formatChars(rest)} знаков.`);
27
+ }
28
+ io.out(` Переносите только правки, все порции которых закрыты: ${serviceInvocation(VERSION)} archive --path ${quotePathArg(path)} --section "начало заголовка". Отпечаток плана перезапишется сам.`);
29
+ if (!edits.intact)
30
+ io.out(' Сейчас перенос остановит archive-plan-changed: текст плана изменился после утверждения. Сначала покажите изменения человеку и запишите новый отпечаток.');
31
+ }
32
+ function describe(report, path, io) {
9
33
  const { log, audits } = report;
10
34
  if (log !== null) {
11
35
  const months = log.months.map((month) => `${month.path} (${month.entries})`).join(', ');
@@ -32,6 +56,7 @@ function describe(report, io) {
32
56
  io.out(`- Адреса ссылок поправлены в файлах: ${report.relinked.length}.`);
33
57
  for (const item of audits.kept)
34
58
  io.out(`- Остаётся ${item.path}: ${item.reason}`);
59
+ describePlanEdits(report, path, io);
35
60
  }
36
61
  /**
37
62
  * Без `--apply` команда только показывает, что перенесёт: ни байта не пишет.
@@ -58,17 +83,17 @@ export async function executeArchiveCommand(options, io) {
58
83
  if (report.writes.length === 0) {
59
84
  const reasons = [report.logNote === null ? 'журнал не больше порога' : null, report.audits.kept.length === 0 ? 'закрытых отчётов нет' : null].filter((reason) => reason !== null);
60
85
  io.out(`Переносить в архив нечего${reasons.length > 0 ? `: ${reasons.join(', ')}` : ''}.`);
61
- describe(report, io);
86
+ describe(report, options.path, io);
62
87
  return EXIT_OK;
63
88
  }
64
89
  if (report.applied) {
65
90
  io.out('Vibe Coding Maestro archive: перенесено в архив.');
66
- describe(report, io);
91
+ describe(report, options.path, io);
67
92
  io.out('Ничего не удалено: перенесённый текст — в файлах архива. Проект в git — закоммитьте изменения.');
68
93
  return EXIT_OK;
69
94
  }
70
95
  io.out('Vibe Coding Maestro archive: будет перенесено в архив (пробный запуск, ни байта не записано).');
71
- describe(report, io);
96
+ describe(report, options.path, io);
72
97
  const named = (options.sections ?? []).map((section) => ` --section "${plainTitle(section)}"`).join('');
73
98
  io.out(`Перенести: ${serviceInvocation(VERSION)} archive --path ${quotePathArg(options.path)}${named} --apply`);
74
99
  return EXIT_OK;
@@ -1,4 +1,4 @@
1
- import { FINISH_SLICE_SHARE, measureContext, NEW_SESSION_SHARE } from '../core/context.js';
1
+ import { measureContext, thresholdsFor } from '../core/context.js';
2
2
  import { EXIT_FAILED, EXIT_OK } from './io.js';
3
3
  /** Тысячи через пробел, без зависимости от локали машины. */
4
4
  export function formatTokens(value) {
@@ -13,6 +13,23 @@ export function tokensWord(value) {
13
13
  return 'токена';
14
14
  return 'токенов';
15
15
  }
16
+ /** «1 шаг», «2 шага», «5 шагов». */
17
+ export function stepsWord(value) {
18
+ const n = Math.abs(Math.round(value));
19
+ if (n % 10 === 1 && n % 100 !== 11)
20
+ return 'шаг';
21
+ if ([2, 3, 4].includes(n % 10) && ![12, 13, 14].includes(n % 100))
22
+ return 'шага';
23
+ return 'шагов';
24
+ }
25
+ /** Сколько шагов осталось до порога новой сессии и когда проверить размер снова. */
26
+ function stepsLine(growth, steps, threshold) {
27
+ const rate = `сессия растёт примерно на ${formatTokens(growth)} ${tokensWord(growth)} за шаг`;
28
+ if (steps < 2)
29
+ return `Сейчас ${rate}: до порога ${formatTokens(threshold)} остался примерно один шаг. Проверьте размер сразу после него.`;
30
+ const half = Math.max(1, Math.floor(steps / 2));
31
+ return `Сейчас ${rate}: до порога ${formatTokens(threshold)} осталось примерно ${formatTokens(steps)} ${stepsWord(steps)}. Оценка грубая — проверьте размер снова не позже чем через ${formatTokens(half)} ${stepsWord(half)}.`;
32
+ }
16
33
  const ADVICE = {
17
34
  continue: 'Можно продолжать в этой сессии.',
18
35
  'finish-slice': 'Порцию лучше закончить в этой сессии, а следующую начать в новой — после передачи дел (/handoff).',
@@ -41,8 +58,12 @@ export async function executeContextCommand(options, io) {
41
58
  io.out(`Размер сессии: ${formatTokens(tokens)} ${tokensWord(tokens)} (${report.percent}% окна модели в ${formatTokens(report.budget)}).`);
42
59
  io.out(windowLine(report.windowSource, report.model, report.budget));
43
60
  io.out(ADVICE[report.level]);
61
+ if (report.growthPerStep !== undefined && report.stepsToNewSession !== undefined) {
62
+ io.out(stepsLine(report.growthPerStep, report.stepsToNewSession, thresholdsFor(report.budget).newSessionTokens));
63
+ }
44
64
  const total = report.totalInputTokens ?? 0;
45
65
  io.out(`За сессию модель получила на вход ${formatTokens(total)} ${tokensWord(total)} (шагов модели: ${report.requests}): каждый шаг заново пересылает всю историю.`);
46
- io.out(`Пороги ${Math.round(FINISH_SLICE_SHARE * 100)}% и ${Math.round(NEW_SESSION_SHARE * 100)}% — гипотеза; их уточнит замер.`);
66
+ const { finishSliceTokens, newSessionTokens } = thresholdsFor(report.budget);
67
+ io.out(`Пороги ${formatTokens(finishSliceTokens)} и ${formatTokens(newSessionTokens)} ${tokensWord(newSessionTokens)} — гипотеза; их уточнит замер.`);
47
68
  return EXIT_OK;
48
69
  }
@@ -19,13 +19,17 @@ const DIFF_TITLES = {
19
19
  * а запись требует отдельного человеческого намерения.
20
20
  */
21
21
  export async function executeUpgradeCommand(options, io) {
22
- const result = await upgradeProject(options.path, { apply: options.apply === true });
22
+ const result = await upgradeProject(options.path, {
23
+ apply: options.apply === true,
24
+ ...(options.hooks === undefined ? {} : { hooks: options.hooks }),
25
+ });
23
26
  if (options.json) {
24
27
  io.out(JSON.stringify({
25
28
  reportVersion: 1,
26
29
  ok: result.ok,
27
30
  applied: result.applied,
28
31
  rolledBack: result.rolledBack,
32
+ partial: result.partial,
29
33
  ...(result.error === undefined ? {} : { error: result.error }),
30
34
  analysis: result.analysis,
31
35
  }, null, 2));
@@ -33,7 +37,11 @@ export async function executeUpgradeCommand(options, io) {
33
37
  }
34
38
  const { analysis } = result;
35
39
  if (analysis.status === 'blocked' || result.ok === false) {
36
- io.err(`Vibe Coding Maestro upgrade: обновление не выполнено (изменений на диске нет).`);
40
+ // Осталась папка транзакции: прошлый запуск мог изменить проект, поэтому «изменений нет» здесь не обещается.
41
+ const staged = analysis.blockers.some((item) => item.code === 'upgrade-staging-present');
42
+ io.err(result.partial
43
+ ? 'Vibe Coding Maestro upgrade: обновление прервано, и откатить удалось не всё: проект изменён частично.'
44
+ : `Vibe Coding Maestro upgrade: ${staged ? 'обновление не запущено.' : 'обновление не выполнено (изменений на диске нет).'}`);
37
45
  if (result.error !== undefined)
38
46
  io.err(`- ${result.error}`);
39
47
  for (const item of analysis.blockers)
@@ -19,7 +19,7 @@ import { countChars, formatChars, LOG_KEEP, LOG_LIMIT } from './limits.js';
19
19
  import { rebaseLinks } from './links.js';
20
20
  import { appendToMonth, LOG_DIR, LOG_PATH, parseLog, rotateLog } from './log.js';
21
21
  import { eolOf, withoutBom } from './markdown.js';
22
- import { appendToPlanArchive, cutSections, declaredPlan, digestLine, planArchivePath, planFiles, PLANS_ARCHIVE_DIR, resolveSections, sectionChars, writeDigest } from './plan.js';
22
+ import { appendToPlanArchive, cutSections, declaredPlan, digestLine, listPlanEdits, planArchivePath, planFiles, PLANS_ARCHIVE_DIR, resolveSections, sectionChars, writeDigest } from './plan.js';
23
23
  import { blocker } from './types.js';
24
24
  /**
25
25
  * Перенос старой памяти проекта в архив внутри проекта: ничего не удаляется,
@@ -70,7 +70,7 @@ function report(root, patch) {
70
70
  const blockers = patch.blockers ?? [];
71
71
  return {
72
72
  reportVersion: 1, ok: blockers.length === 0, applied: false, rolledBack: false, partial: false, root, blockers,
73
- log: null, logNote: null, audits: { moved: [], kept: [] }, plan: null, planArchive: null, sections: [], digests: [], relinked: [], writes: [], ...patch,
73
+ log: null, logNote: null, audits: { moved: [], kept: [] }, plan: null, planArchive: null, sections: [], planEdits: null, digests: [], relinked: [], writes: [], ...patch,
74
74
  };
75
75
  }
76
76
  const ARCHIVE_DIRS = [LOG_DIR, AUDITS_ARCHIVE_DIR, PLANS_ARCHIVE_DIR];
@@ -167,6 +167,13 @@ async function archiveMemory(root, rootInput, options) {
167
167
  nested: choice.nested.map((heading) => ({ heading: heading.title, chars: sectionChars(sectionPlan.text, heading) })),
168
168
  warnings: choice.warnings,
169
169
  }));
170
+ // Подсказка, а не перенос: считается по плану как он есть сейчас, отпечаток не сверяется и ничего не блокирует.
171
+ const listing = wanted.length > 0 ? null : listPlanEdits(files, plans);
172
+ const planEdits = listing === null ? null : {
173
+ plan: listing.plan.path,
174
+ intact: listing.plan.intact,
175
+ sections: listing.edits.map((edit) => ({ heading: edit.heading.title, chars: sectionChars(listing.plan.text, edit.heading), open: edit.open, currentSlice: edit.currentSlice })),
176
+ };
170
177
  const disk = projectDisk(root, [...files.keys()].filter((path) => AUDIT_FILE_RE.test(path)));
171
178
  const { moved, kept } = selectAudits(files, plans, disk);
172
179
  const audits = { moved: [...moved].map(([from, to]) => ({ from, to })), kept };
@@ -260,7 +267,7 @@ async function archiveMemory(root, rootInput, options) {
260
267
  }
261
268
  }
262
269
  const relinked = writes.filter((write) => write.action === 'update' && !touched.has(write.path)).map((write) => write.path);
263
- const details = { log, logNote, audits, plan: sectionPlan?.path ?? null, planArchive: sectionPlan === null ? null : planArchivePath(sectionPlan.path), sections, digests, relinked };
270
+ const details = { log, logNote, audits, plan: sectionPlan?.path ?? null, planArchive: sectionPlan === null ? null : planArchivePath(sectionPlan.path), sections, planEdits, digests, relinked };
264
271
  if (blockers.length > 0)
265
272
  return report(root, { blockers, ...details });
266
273
  if (options.apply !== true || writes.length === 0)
@@ -14,6 +14,14 @@ export const LOG_LIMIT = 20_000;
14
14
  export const LOG_KEEP = 10_000;
15
15
  /** Передача, с которой начнёт следующая сессия. */
16
16
  export const HANDOFF_LIMIT = 6_000;
17
+ /**
18
+ * Коммиты кода после последней передачи. HYPOTHESIS 0.4.5: числа — из проигрыша
19
+ * истории трёх живых проектов; поэтому doctor только сообщает (`info`).
20
+ */
21
+ /** Столько коммитов кода, а `wiki/hot.md` не называет текущую порцию. */
22
+ export const HOT_BEHIND_COMMITS = 3;
23
+ /** Столько коммитов кода без новой передачи. */
24
+ export const HANDOFF_COMMITS_LIMIT = 10;
17
25
  /**
18
26
  * Знаки — кодовые точки Unicode после замены CRLF на LF: так счёт одинаков
19
27
  * на любой ОС и не зависит от того, как записан перенос строки.
@@ -60,7 +60,15 @@ const WORD_RE = /^[\p{L}\p{N}_]/u;
60
60
  const COLLECTIONS = ['Правки после утверждения', 'Изменения после утверждения'];
61
61
  const APPROVAL = 'Утверждение';
62
62
  const POINTER_RE = /^В архиве: \[[^\]]*\]\(archive\/[^)]*\)\.?$/;
63
- const UNCHECKED_RE = /^[ \t]*(?:[-*+]|\d+[.)])[ \t]+\[ \]/gm;
63
+ /** Неотмеченный пункт списка; в блоках кода не считается. */
64
+ const UNCHECKED_RE = /^[ \t]*(?:[-*+]|\d+[.)])[ \t]+\[ \]/;
65
+ /** Пометки незакрытого: целым словом, в любом регистре. Само слово не значит «открыто», поэтому только предупреждение. */
66
+ const OPEN_MARK_RE = /(?<![\p{L}\p{N}_])(?:UNKNOWN|OPEN_QUESTION|HYPOTHESIS|не\s+проверено|открыто)(?![\p{L}\p{N}_])/iu;
67
+ /** Строка находок с нулём открытых содержит «открыто», но пометкой не является. */
68
+ const CLOSED_FINDINGS_RE = /Находки:\s*critical\s+\d+,\s*high\s+\d+,\s*medium\s+\d+,\s*low\s+\d+;\s*открыто\s+0(?!\d)/;
69
+ /** Раздел бывает в десятки тысяч знаков: агент видит сами строки и не перечитывает его. */
70
+ const SHOWN_MARKS = 3;
71
+ const SHOWN_CHARS = 100;
64
72
  /** Сколько заголовков показать в отказе: у живых планов их сотни. */
65
73
  const LISTED = 30;
66
74
  /** Заголовки и аргументы сравниваются без разметки и с одинарными пробелами. */
@@ -68,7 +76,7 @@ export function plainTitle(value) {
68
76
  return value.replace(/`|\*\*|[«»]/g, '').replace(/\s+/g, ' ').trim();
69
77
  }
70
78
  const startsWithWord = (title, wanted) => title.startsWith(wanted) && !WORD_RE.test(title.slice(wanted.length));
71
- function mentionsSlice(text, slice) {
79
+ export function mentionsSlice(text, slice) {
72
80
  const escaped = slice.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
73
81
  return new RegExp(`(?<![\\p{L}\\p{N}_])${escaped}(?![\\p{L}\\p{N}_])`, 'u').test(text);
74
82
  }
@@ -100,7 +108,10 @@ function chooseSection(text, plan, argument, headings, collection) {
100
108
  return { blocker: blocker('archive-section-not-found', `В плане нет раздела, заголовок которого начинается с «${argument}». Правки плана: ${listed(movable) || 'их нет'}.`, plan.path) };
101
109
  if (found.length > 1)
102
110
  return { blocker: blocker('archive-section-ambiguous', `«${argument}» подходит к разделам: ${listed(found)}. Уточните начало заголовка; одинаковые заголовки так не перенести.`, plan.path) };
103
- const heading = found[0];
111
+ return examineSection(text, plan, found[0], headings, collection);
112
+ }
113
+ /** Можно ли перенести раздел и что в нём насторожит; одна проверка и для переноса, и для подсказки без `--section`. */
114
+ function examineSection(text, plan, heading, headings, collection) {
104
115
  const title = `«${heading.title}»`;
105
116
  if (heading === collection || COLLECTIONS.includes(heading.title))
106
117
  return { blocker: blocker('archive-section-collection', `${title} — сборник правок: внутри могут быть и открытые. Называйте закрытые правки по одной.`, plan.path) };
@@ -120,13 +131,45 @@ function chooseSection(text, plan, argument, headings, collection) {
120
131
  const section = text.slice(heading.start, heading.end);
121
132
  const rest = section.slice(heading.line.length);
122
133
  const warnings = [];
123
- if (declaredSlice !== null && mentionsSlice(rest, declaredSlice))
134
+ const currentSlice = declaredSlice !== null && mentionsSlice(rest, declaredSlice);
135
+ if (currentSlice)
124
136
  warnings.push(`раздел ${title} упоминает текущую порцию ${declaredSlice}.`);
125
- const unchecked = [...rest.matchAll(UNCHECKED_RE)].length;
137
+ const unchecked = markdownLines(rest).filter(({ line, code }) => !code && UNCHECKED_RE.test(line)).length;
126
138
  if (unchecked > 0)
127
139
  warnings.push(`в разделе ${title} неотмеченных пунктов [ ]: ${formatChars(unchecked)}.`);
128
- return { choice: { heading, nested, already: POINTER_RE.test(rest.trim()), warnings } };
140
+ const already = POINTER_RE.test(rest.trim());
141
+ const marks = already ? null : openMarksWarning(title, section);
142
+ if (marks !== null)
143
+ warnings.push(marks);
144
+ return { choice: { heading, nested, already, open: unchecked > 0 || marks !== null, currentSlice, warnings } };
145
+ }
146
+ /** Строка с пометкой, не длиннее `SHOWN_CHARS` кодовых точек; слово остаётся видно и в длинной строке. */
147
+ function shownLine(line, mark) {
148
+ const points = [...line];
149
+ if (points.length <= SHOWN_CHARS)
150
+ return line;
151
+ const before = [...line.slice(0, mark)].length;
152
+ const start = before < SHOWN_CHARS / 2 ? 0 : Math.min(before - SHOWN_CHARS / 4, points.length - SHOWN_CHARS);
153
+ const shown = points.slice(start, start + SHOWN_CHARS).join('');
154
+ return `${start > 0 ? '…' : ''}${shown}${start + SHOWN_CHARS < points.length ? '…' : ''}`;
129
155
  }
156
+ /** Предупреждение о пометках незакрытого в тексте раздела; блоки кода не считаются. */
157
+ function openMarksWarning(title, section) {
158
+ const found = [];
159
+ for (const { line, code } of markdownLines(section)) {
160
+ if (code)
161
+ continue;
162
+ const text = line.trim();
163
+ const mark = OPEN_MARK_RE.exec(text.replace(CLOSED_FINDINGS_RE, (found) => ' '.repeat(found.length)));
164
+ if (mark !== null)
165
+ found.push(`«${shownLine(text, mark.index)}»`);
166
+ }
167
+ if (found.length === 0)
168
+ return null;
169
+ const more = found.length > SHOWN_MARKS ? `; ещё ${formatChars(found.length - SHOWN_MARKS)}` : '';
170
+ return `в разделе ${title} есть пометки незакрытого: ${found.slice(0, SHOWN_MARKS).join('; ')}${more}. Закрыто — переносите; открыто — сначала запишите в wiki/hot.md или wiki/icebox.md: обратно архив не копируют.`;
171
+ }
172
+ const findCollection = (headings) => headings.find((heading) => (heading.level === 2 || heading.level === 3) && COLLECTIONS.some((name) => startsWithWord(heading.title, name)));
130
173
  /** `active_plan` из `wiki/hot.md`. */
131
174
  export function declaredPlan(files) {
132
175
  const hot = files.get(HOT_PATH);
@@ -146,7 +189,7 @@ export function resolveSections(files, plans, wanted) {
146
189
  if (!plan.intact)
147
190
  return refuse(blocker('archive-plan-changed', 'Текст плана изменился после утверждения (approved_digest не совпадает): перенос записал бы новый отпечаток поверх неутверждённой правки. Покажите изменения человеку; после его «да» запишите отпечаток из вывода preflight и повторите.', plan.path), plan);
148
191
  const headings = planHeadings(plan.text);
149
- const collection = headings.find((heading) => (heading.level === 2 || heading.level === 3) && COLLECTIONS.some((name) => startsWithWord(heading.title, name)));
192
+ const collection = findCollection(headings);
150
193
  if (collection === undefined)
151
194
  return refuse(blocker('archive-section-no-collection', `В плане нет раздела «${COLLECTIONS[0]}» или «${COLLECTIONS[1]}»: переносить можно только правки, которые стоят ниже него.`, plan.path), plan);
152
195
  const chosen = [];
@@ -166,6 +209,34 @@ export function resolveSections(files, plans, wanted) {
166
209
  }
167
210
  return { plan, chosen, blockers };
168
211
  }
212
+ /**
213
+ * Правки активного плана, которые можно перенести через `--section`: без раздела текущей порции,
214
+ * сборников, записи об утверждении и уже перенесённых. Ничего не меняет и не блокирует.
215
+ * `null` — активного плана или сборника правок нет.
216
+ */
217
+ export function listPlanEdits(files, plans) {
218
+ const declared = declaredPlan(files);
219
+ if (declared === ACTIVE_PLAN_NONE || !isWikiRelativePlanRef(declared))
220
+ return null;
221
+ const plan = plans.find((item) => item.path === `wiki/${declared}`);
222
+ if (plan === undefined || plan.meta === null)
223
+ return null;
224
+ const headings = planHeadings(plan.text);
225
+ const collection = findCollection(headings);
226
+ if (collection === undefined)
227
+ return null;
228
+ const edits = [];
229
+ for (const heading of headings) {
230
+ if ((heading.level !== 2 && heading.level !== 3) || heading.start <= collection.start)
231
+ continue;
232
+ if (edits.some((other) => heading.start < other.heading.end))
233
+ continue;
234
+ const { choice } = examineSection(plan.text, plan, heading, headings, collection);
235
+ if (choice !== undefined && !choice.already)
236
+ edits.push(choice);
237
+ }
238
+ return { plan, edits };
239
+ }
169
240
  export function cutSections(text, chosen, archivePath, eol) {
170
241
  const name = posix.basename(archivePath);
171
242
  const sections = [];
@@ -41,9 +41,23 @@ 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;
53
+ /**
54
+ * Оценка «сколько шагов до порога»: рост считается по последним шагам сессии.
55
+ * Шагов меньше `GROWTH_MIN_STEPS` или сессия не растёт — оценки нет.
56
+ */
57
+ export const GROWTH_STEPS = 30;
58
+ export const GROWTH_MIN_STEPS = 10;
59
+ /** Размер упал больше чем вдвое — сессию сжали: рост считается только после сжатия. */
60
+ const COMPACTION_DROP = 0.5;
47
61
  /** Имя папки журналов: Claude Code заменяет в пути проекта всё, кроме латиницы и цифр, на `-`. */
48
62
  export function projectLogDirName(root) {
49
63
  return resolve(root).replace(/[^a-zA-Z0-9]/g, '-');
@@ -124,10 +138,36 @@ export async function findTranscript(root, claudeDir, sessionId) {
124
138
  return best?.path ?? null;
125
139
  }
126
140
  const count = (value) => (typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0);
127
- export function levelFor(share) {
128
- if (share >= NEW_SESSION_SHARE)
141
+ /** Пороги при этом окне. Токены — целые, поэтому округление вверх не сдвигает границу. */
142
+ export function thresholdsFor(budget) {
143
+ return {
144
+ finishSliceTokens: Math.min(FINISH_SLICE_TOKENS, Math.ceil((budget * FINISH_SLICE_PERCENT) / 100)),
145
+ newSessionTokens: Math.min(NEW_SESSION_TOKENS, Math.ceil((budget * NEW_SESSION_PERCENT) / 100)),
146
+ };
147
+ }
148
+ /**
149
+ * Рост сессии за шаг по размерам последних шагов (по одному числу на ответ модели, в порядке журнала).
150
+ * `null` — шагов мало или сессия не растёт.
151
+ */
152
+ export function growthPerStep(sizes) {
153
+ let recent = sizes.slice(-(GROWTH_STEPS + 1));
154
+ for (let index = recent.length - 1; index > 0; index -= 1) {
155
+ if (recent[index] < recent[index - 1] * COMPACTION_DROP) {
156
+ recent = recent.slice(index);
157
+ break;
158
+ }
159
+ }
160
+ const steps = recent.length - 1;
161
+ if (steps < GROWTH_MIN_STEPS)
162
+ return null;
163
+ const growth = (recent[steps] - recent[0]) / steps;
164
+ return growth >= 1 ? Math.round(growth) : null;
165
+ }
166
+ export function levelFor(tokens, budget) {
167
+ const { finishSliceTokens, newSessionTokens } = thresholdsFor(budget);
168
+ if (tokens >= newSessionTokens)
129
169
  return 'new-session';
130
- if (share >= FINISH_SLICE_SHARE)
170
+ if (tokens >= finishSliceTokens)
131
171
  return 'finish-slice';
132
172
  return 'continue';
133
173
  }
@@ -143,6 +183,8 @@ export async function measureContext(options) {
143
183
  return { reportVersion: 1, ok: false, budget, message: `Журнал сессии Claude Code для этой папки не найден (искал в ${join(claudeDir, 'projects')}). Команда работает внутри сессии Claude Code, открытой в папке проекта.` };
144
184
  }
145
185
  const seen = new Set();
186
+ /** Размер каждого шага модели: один ответ бывает записан несколькими строками, берётся последняя. */
187
+ const stepSizes = new Map();
146
188
  let last = null;
147
189
  let lastModel;
148
190
  /** Самый большой контекст у каждой модели: после смены модели окно судится по ней одной. */
@@ -176,6 +218,7 @@ export async function measureContext(options) {
176
218
  lastModel = typeof entry.message?.model === 'string' ? entry.message.model : undefined;
177
219
  largest = Math.max(largest, size);
178
220
  largestByModel.set(lastModel ?? '', Math.max(largestByModel.get(lastModel ?? '') ?? 0, size));
221
+ stepSizes.set(id, size);
179
222
  if (seen.has(id))
180
223
  continue;
181
224
  seen.add(id);
@@ -196,7 +239,9 @@ export async function measureContext(options) {
196
239
  if ((byModel === null ? largest : largestByModel.get(lastModel ?? '') ?? 0) > budget)
197
240
  budget = LARGE_WINDOW;
198
241
  }
199
- const share = contextTokens / budget;
242
+ const level = levelFor(contextTokens, budget);
243
+ const thresholds = thresholdsFor(budget);
244
+ const growth = level === 'finish-slice' ? growthPerStep([...stepSizes.values()]) : null;
200
245
  return {
201
246
  reportVersion: 1,
202
247
  ok: true,
@@ -206,9 +251,11 @@ export async function measureContext(options) {
206
251
  budget,
207
252
  ...(lastModel === undefined ? {} : { model: lastModel }),
208
253
  windowSource,
209
- percent: Math.round(share * 100),
210
- level: levelFor(share),
254
+ percent: Math.round((contextTokens / budget) * 100),
255
+ level,
256
+ ...thresholds,
211
257
  totalInputTokens: totalInput,
212
258
  requests: seen.size,
259
+ ...(growth === null ? {} : { growthPerStep: growth, stepsToNewSession: Math.floor((thresholds.newSessionTokens - contextTokens) / growth) }),
213
260
  };
214
261
  }
@@ -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
  }
@@ -11,6 +11,7 @@ import { checkGit } from './git.js';
11
11
  import { checkInbox } from './inbox.js';
12
12
  import { checkInventory, checkManagedFiles } from './managed.js';
13
13
  import { checkMemory } from './memory.js';
14
+ import { checkMemoryLag } from './memory-lag.js';
14
15
  import { checkPlans } from './plans.js';
15
16
  import { checkProtocols } from './protocols.js';
16
17
  import { checkSources } from './sources.js';
@@ -119,6 +120,7 @@ export async function doctorProject(rootInput, options = {}) {
119
120
  checkPlans(root, wiki, findings);
120
121
  checkMemory(rootInput, wiki, findings);
121
122
  await checkGit(root, managedDocs, findings, managedFiles);
123
+ await checkMemoryLag(root, wiki, findings);
122
124
  await checkInbox(root, findings);
123
125
  await checkSources(root, findings);
124
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
+ }
@@ -62,7 +62,7 @@ export async function checkSources(root, findings) {
62
62
  const actualSet = new Set(actualPaths);
63
63
  for (const path of actualPaths) {
64
64
  if (!(path in hashes))
65
- findings.push(critical('source-hash-missing', 'Для source отсутствует versioned hash.', path));
65
+ findings.push(critical('source-hash-missing', 'Файл в maestro/sources/ не записан в снимке: эта папка — только для снимков команды `vibe-maestro sources --write`. Свой материал переложите в maestro/inbox/ — там он не замечание.', path));
66
66
  else if (sha256(await readFile(join(root, path))) !== hashes[path])
67
67
  findings.push(critical('source-hash-mismatch', 'Source не совпадает с versioned hash.', path));
68
68
  }
@@ -137,8 +137,9 @@ function decideForPlan(plan, planPath, digest, digestMatches) {
137
137
  route = 'human';
138
138
  at('preflight-blocking-questions', `Открытых блокирующих вопросов: ${plan.blockingQuestions}. Их закрывает человек, а не агент.`);
139
139
  }
140
- if (plan.specDelta !== 'none') {
141
- at('preflight-spec-delta', `Объявлен spec delta (${plan.specDelta}): граница изменилась и требует повторного утверждения.`);
140
+ // `resolved` — правка уже утверждена: текст после неё держит отпечаток, блокировать нечего.
141
+ if (plan.specDelta === 'open') {
142
+ at('preflight-spec-delta', 'Объявлен spec delta (open): граница изменилась и требует повторного утверждения.');
142
143
  }
143
144
  if (plan.kind === 'program') {
144
145
  if (plan.activePhase === null) {
@@ -153,6 +154,9 @@ function decideForPlan(plan, planPath, digest, digestMatches) {
153
154
  const allowed = [
154
155
  finding('info', 'preflight-slice-selected', `Разрешена ровно одна порция: ${plan.currentSlice}. Остановка на её стоп-гейте обязательна.`, planPath),
155
156
  ];
157
+ if (plan.specDelta === 'resolved') {
158
+ allowed.push(finding('info', 'preflight-spec-delta-resolved', 'В плане записано spec_delta: resolved — правка границы уже утверждена, работе это не мешает. Верните в поле none: так видно, что открытых правок нет.', planPath));
159
+ }
156
160
  if (plan.approvedDigest === null) {
157
161
  allowed.push(finding('info', 'preflight-digest-missing', 'Отпечаток утверждения не записан: правку текста плана после утверждения гейт не заметит. Запишите в approved_digest строку «Отпечаток плана».', planPath));
158
162
  }
@@ -13,6 +13,7 @@ const result = (plan, patch = {}) => ({
13
13
  updatedFiles: [],
14
14
  removedFiles: [],
15
15
  rolledBack: false,
16
+ partial: false,
16
17
  plan,
17
18
  ...patch,
18
19
  });
@@ -60,6 +61,7 @@ export async function upgradeProject(rootInput, options = {}) {
60
61
  return result(plan, {
61
62
  ok: false,
62
63
  rolledBack: false,
64
+ partial: true,
63
65
  error: `Применение прервано (${outcome.reason}), и откатить удалось не всё: ${outcome.unrestored.join(', ')}. Прежние версии файлов оставлены в ${STAGING_DIR}/backup/ — верните их вручную, затем удалите ${STAGING_DIR}.`,
64
66
  });
65
67
  }