create-vibe-maestro 0.3.0-beta.3 → 0.3.0

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 (78) hide show
  1. package/CHANGELOG.md +65 -1
  2. package/README.md +72 -72
  3. package/dist/cli/create-run.js +17 -0
  4. package/dist/cli/create.js +3 -3
  5. package/dist/cli/desktop.js +10 -1
  6. package/dist/cli/doctor-run.js +4 -0
  7. package/dist/cli/maestro.js +1 -1
  8. package/dist/cli/preflight-run.js +6 -2
  9. package/dist/cli/skills-run.js +0 -1
  10. package/dist/cli/upgrade-run.js +10 -3
  11. package/dist/core/doctor/entries.js +41 -0
  12. package/dist/core/doctor/git.js +10 -5
  13. package/dist/core/doctor/index.js +78 -9
  14. package/dist/core/doctor/managed.js +6 -2
  15. package/dist/core/doctor/plans.js +23 -6
  16. package/dist/core/doctor/text.js +40 -3
  17. package/dist/core/doctor/wiki.js +18 -7
  18. package/dist/core/fs-errors.js +32 -0
  19. package/dist/core/init.js +99 -11
  20. package/dist/core/inventory.js +10 -3
  21. package/dist/core/manifest.js +2 -0
  22. package/dist/core/meta.js +5 -2
  23. package/dist/core/plan.js +42 -1
  24. package/dist/core/platform-paths.js +16 -1
  25. package/dist/core/preflight.js +59 -14
  26. package/dist/core/skills.js +2 -13
  27. package/dist/core/template-recover.js +82 -0
  28. package/dist/core/template.js +2 -1
  29. package/dist/core/upgrade/analyze.js +196 -89
  30. package/dist/core/upgrade/baseline.js +6 -0
  31. package/dist/core/upgrade/index.js +20 -5
  32. package/dist/core/upgrade/instance.js +12 -2
  33. package/dist/core/upgrade/releases.js +295 -0
  34. package/dist/core/version.js +60 -0
  35. package/docs/MIGRATION_V1.md +2 -1
  36. package/docs/ROADMAP.md +59 -0
  37. package/docs/USER_GUIDE.md +97 -123
  38. package/package.json +3 -2
  39. package/registry/baseline/0.3-beta/project/.claude/commands/build.md +3 -0
  40. package/registry/baseline/0.3-beta/project/AGENTS.md +10 -0
  41. package/registry/baseline/0.3-beta/project/CLAUDE.md +10 -0
  42. package/registry/baseline/0.3-beta/project/protocols/build.md +15 -0
  43. package/registry/baseline/0.3-beta/project/protocols/plan.md +132 -0
  44. package/registry/baseline/0.3.0-beta.4/project/.claude/agents/code-reviewer.md +6 -0
  45. package/registry/baseline/0.3.0-beta.4/project/AGENTS.md +10 -0
  46. package/registry/baseline/0.3.0-beta.4/project/CLAUDE.md +10 -0
  47. package/registry/baseline/0.3.0-beta.4/project/maestro/runbooks/cowork-audit.md +11 -0
  48. package/registry/baseline/0.3.0-beta.4/project/protocols/build.md +15 -0
  49. package/registry/baseline/0.3.0-beta.4/project/protocols/context-budget.md +9 -0
  50. package/registry/baseline/0.3.0-beta.4/project/protocols/handoff.md +5 -0
  51. package/registry/baseline/0.3.0-beta.4/project/protocols/plan.md +132 -0
  52. package/registry/baseline/0.3.0-beta.4/project/protocols/wiki.md +9 -0
  53. package/registry/baseline/0.3.0-beta.4/project/wiki/index.md +32 -0
  54. package/registry/baseline/0.3.0-beta.4/project/wiki/plans/README.md +92 -0
  55. package/registry/baseline/0.3.0-beta.4/project/wiki/plans/TEMPLATE.md +65 -0
  56. package/templates/project/.claude/agents/code-reviewer.md +8 -2
  57. package/templates/project/.claude/agents/explorer.md +14 -0
  58. package/templates/project/.claude/commands/build.md +1 -1
  59. package/templates/project/.claude/rules/maestro.md +25 -0
  60. package/templates/project/.claude/rules/project.md +5 -0
  61. package/templates/project/.claude/settings.json +24 -0
  62. package/templates/project/AGENTS.md +6 -7
  63. package/templates/project/CLAUDE.md +2 -7
  64. package/templates/project/maestro/runbooks/cowork-audit.md +1 -1
  65. package/templates/project/maestro/templates/adr.md +21 -0
  66. package/templates/project/maestro/templates/handoff.md +25 -0
  67. package/templates/project/maestro/templates/progress.md +22 -0
  68. package/templates/project/protocols/build.md +3 -1
  69. package/templates/project/protocols/context-budget.md +1 -1
  70. package/templates/project/protocols/handoff.md +8 -0
  71. package/templates/project/protocols/plan.md +16 -6
  72. package/templates/project/protocols/wiki.md +1 -1
  73. package/templates/project/wiki/hot.md +1 -1
  74. package/templates/project/wiki/index.md +10 -18
  75. package/templates/project/wiki/plans/0001-starter.md +5 -4
  76. package/templates/project/wiki/plans/README.md +45 -6
  77. package/templates/project/wiki/plans/TEMPLATE.md +11 -1
  78. package/registry/trusted-skills.v1.json +0 -4
@@ -1,34 +1,38 @@
1
1
  import { lstat, readFile } from 'node:fs/promises';
2
- import { basename, join, resolve } from 'node:path';
2
+ import { join, resolve } from 'node:path';
3
3
  import { absolutePathHasSymlink, pathHasSymlink } from '../doctor/fs-utils.js';
4
+ import { GITATTRIBUTES_CONTENT } from '../init.js';
4
5
  import { canonicalManagedKind, canonicalOwnershipInventory, CONTENT_OWNED_FILES, TEMPLATE_FILES } from '../inventory.js';
5
- import { CHECKSUMS_PATH, contentChecksum, isCanonicalManifest, loadChecksums, loadManifest, MANIFEST_PATH, serializeJson, sha256, buildManifest, } from '../manifest.js';
6
- import { CREATE_COMMAND, VERSION } from '../meta.js';
6
+ import { CHECKSUMS_PATH, contentChecksum, isCanonicalManifest, loadChecksums, loadManifest, MANIFEST_PATH, normalizeEol, serializeJson, sha256, buildManifest, } from '../manifest.js';
7
+ import { CREATE_COMMAND, serviceInvocation, VERSION } from '../meta.js';
7
8
  import { readPackageJson, packageRoot, templatesDir } from '../paths.js';
8
9
  import { canonicalizeSystemTempPrefix } from '../platform-paths.js';
9
10
  import { renderTemplate } from '../template.js';
10
- import { BASELINE_ID, BASELINE_PRODUCT_VERSIONS, BASELINE_TEMPLATES, baselineOwnershipInventory, } from './baseline.js';
11
- import { recoverTemplateVars, templateUses } from './instance.js';
11
+ import { compareVersions } from '../version.js';
12
+ import { findRelease, supportedVersions } from './releases.js';
13
+ import { recoverTemplateVars, templateUses } from '../template-recover.js';
12
14
  /** Каталог транзакции. Внутри `.maestro`, чтобы не появляться в дереве проекта. */
13
15
  export const STAGING_DIR = '.maestro/upgrade-staging';
14
16
  const blocker = (code, message, path) => ({ code, message, ...(path === undefined ? {} : { path }) });
15
- function analysis(root, status, fromVersion, blockers) {
17
+ function analysis(root, status, fromVersion, blockers, baselineId = 'unknown') {
16
18
  return {
17
19
  reportVersion: 1,
18
20
  status,
19
21
  root,
20
- baselineId: BASELINE_ID,
22
+ baselineId,
21
23
  fromVersion,
22
24
  toVersion: VERSION,
23
25
  creates: [],
24
26
  updates: [],
25
27
  unchanged: [],
26
28
  preserves: [],
29
+ handedOver: [],
27
30
  metadata: [],
28
31
  blockers,
29
32
  };
30
33
  }
31
34
  const blocked = (root, fromVersion, ...blockers) => ({ analysis: analysis(root, 'blocked', fromVersion, blockers), root, writes: [] });
35
+ const blockedAt = (root, release, fromVersion, blockers) => ({ analysis: analysis(root, 'blocked', fromVersion, blockers, release.id), root, writes: [] });
32
36
  async function isRegularFile(absolute) {
33
37
  try {
34
38
  return (await lstat(absolute)).isFile();
@@ -53,9 +57,42 @@ async function exists(absolute) {
53
57
  async function readTemplate(relativePath) {
54
58
  return readFile(join(templatesDir(), 'project', relativePath), 'utf8');
55
59
  }
56
- /** Точная форма manifest, которую записал бы init предыдущей версии. */
57
- function matchesBaselineShape(manifest) {
58
- const expected = baselineOwnershipInventory(manifest.project.depth);
60
+ /** Исходник managed-пути текущей версии. `.gitattributes` пишет константа init, а не шаблон. */
61
+ async function currentSource(relativePath) {
62
+ if (relativePath === '.gitattributes')
63
+ return GITATTRIBUTES_CONTENT;
64
+ return normalizeEol(await readTemplate(relativePath));
65
+ }
66
+ /**
67
+ * Исходник managed-пути в прошлом каноне.
68
+ *
69
+ * Изменённые с тех пор пути поставляются копией в `registry/baseline`; остальные
70
+ * берутся из текущего шаблона, но только если его сумма совпадает с замороженным
71
+ * слепком. Иначе пакет не знает, как выглядел файл, и не имеет права его трогать.
72
+ */
73
+ async function releaseSource(release, relativePath) {
74
+ const copy = release.templates.find((template) => template.path === relativePath);
75
+ if (copy !== undefined) {
76
+ let source;
77
+ try {
78
+ source = normalizeEol(await readFile(join(packageRoot(), copy.source), 'utf8'));
79
+ }
80
+ catch (cause) {
81
+ return { blocker: blocker('upgrade-baseline-unreadable', `Baseline-шаблон пакета недоступен: ${cause instanceof Error ? cause.message : String(cause)}`, copy.source) };
82
+ }
83
+ if (sha256(source) !== copy.sha256) {
84
+ return { blocker: blocker('upgrade-baseline-corrupt', 'Baseline-шаблон пакета не совпадает со своей контрольной суммой и не может быть авторитетом.', copy.source) };
85
+ }
86
+ return { source };
87
+ }
88
+ const source = await currentSource(relativePath);
89
+ if (release.managedSha256[relativePath] !== sha256(source)) {
90
+ return { blocker: blocker('upgrade-baseline-drift', `В пакете нет копии этого файла в версии ${release.versions.join(', ')}: без неё upgrade не может доказать, что файл не изменён. Это дефект пакета — сообщите о нём.`, relativePath) };
91
+ }
92
+ return { source };
93
+ }
94
+ /** Точная форма manifest, которую записал бы init прошлой версии. */
95
+ function matchesShape(manifest, expected) {
59
96
  const paths = Object.keys(expected);
60
97
  if (manifest.inventory.length !== paths.length || manifest.managed.length !== paths.length)
61
98
  return false;
@@ -67,14 +104,17 @@ function matchesBaselineShape(manifest) {
67
104
  * Read-only разбор проекта: ни один байт не записывается.
68
105
  *
69
106
  * Порядок проверок — от авторитета к содержимому. Пока не доказано, что это
70
- * действительно канонический проект предыдущей версии в его собственной папке,
71
- * содержимое файлов даже не читается.
107
+ * действительно канонический проект известной прошлой версии в его собственной
108
+ * папке, содержимое файлов даже не читается.
72
109
  */
73
110
  export async function analyzeUpgrade(rootInput) {
74
111
  const root = await canonicalizeSystemTempPrefix(resolve(rootInput));
75
112
  if (await absolutePathHasSymlink(root)) {
76
113
  return blocked(root, null, blocker('upgrade-root-symlink', 'Путь к корню проекта не должен содержать symbolic link.', root));
77
114
  }
115
+ if (!await exists(root)) {
116
+ return blocked(root, null, blocker('upgrade-path-missing', `Папка не найдена: ${root}. Проверьте путь; путь с пробелами возьмите в кавычки.`));
117
+ }
78
118
  if (!await isRegularFile(join(root, MANIFEST_PATH))) {
79
119
  return blocked(root, null, blocker('upgrade-not-canonical', 'Папка не является каноническим проектом Vibe Coding Maestro: manifest отсутствует. Upgrade не преобразует произвольные папки.', MANIFEST_PATH));
80
120
  }
@@ -94,19 +134,25 @@ export async function analyzeUpgrade(rootInput) {
94
134
  if (manifest.product.name !== readPackageJson().name || manifest.product.createdBy !== CREATE_COMMAND) {
95
135
  return blocked(root, fromVersion, blocker('upgrade-foreign-manifest', 'Manifest создан не этим продуктом.', MANIFEST_PATH));
96
136
  }
97
- if (manifest.project.name !== basename(root)) {
98
- return blocked(root, fromVersion, blocker('upgrade-manifest-not-native', 'Manifest принадлежит другой папке: имя проекта не совпадает с именем каталога.', MANIFEST_PATH));
99
- }
137
+ // Личность проекта — project.id: клон или переименованная папка обновляются так же.
100
138
  const current = canonicalOwnershipInventory(depth);
101
- const baseline = baselineOwnershipInventory(depth);
102
- if (isCanonicalManifest(manifest)) {
103
- return { analysis: analysis(root, 'current', fromVersion, []), root, writes: [] };
139
+ const order = compareVersions(fromVersion, VERSION);
140
+ if (order !== null && order > 0) {
141
+ return blocked(root, fromVersion, blocker('upgrade-project-newer', `Проект уже на более новой версии ${fromVersion}, а запущена ${VERSION}; откатывать версию upgrade не умеет. Используйте ${serviceInvocation(fromVersion)}.`, MANIFEST_PATH));
142
+ }
143
+ if (fromVersion === VERSION) {
144
+ if (isCanonicalManifest(manifest)) {
145
+ return { analysis: analysis(root, 'current', fromVersion, [], VERSION), root, writes: [] };
146
+ }
147
+ return blocked(root, fromVersion, blocker('upgrade-unsupported-baseline', `Manifest называет версию ${VERSION}, но его форма inventory не совпадает с каноном этой версии.`, MANIFEST_PATH));
104
148
  }
105
- if (!matchesBaselineShape(manifest)) {
106
- return blocked(root, fromVersion, blocker('upgrade-unsupported-baseline', `Поддерживается только известный предшественник ${BASELINE_ID}; форма inventory этого проекта ему не соответствует.`, MANIFEST_PATH));
149
+ const release = findRelease(fromVersion);
150
+ if (release === undefined) {
151
+ return blocked(root, fromVersion, blocker('upgrade-unsupported-version', `Upgrade не знает версию ${fromVersion}. Обновлять он умеет с версий: ${supportedVersions().join(', ')}.`, MANIFEST_PATH));
107
152
  }
108
- if (!BASELINE_PRODUCT_VERSIONS.includes(fromVersion)) {
109
- return blocked(root, fromVersion, blocker('upgrade-unsupported-version', `Версия продукта ${fromVersion} не входит в поддерживаемый baseline ${BASELINE_ID}.`, MANIFEST_PATH));
153
+ const baseline = release.inventory(depth);
154
+ if (!matchesShape(manifest, baseline)) {
155
+ return blockedAt(root, release, fromVersion, [blocker('upgrade-unsupported-baseline', `Форма inventory проекта не совпадает с каноном ${release.id}, который записывала версия ${fromVersion}.`, MANIFEST_PATH)]);
110
156
  }
111
157
  const blockers = [];
112
158
  // Полное дерево предшественника: manifest не имеет права выдавать неполную папку за проект.
@@ -115,80 +161,123 @@ export async function analyzeUpgrade(rootInput) {
115
161
  blockers.push(blocker('upgrade-incomplete-tree', 'Обязательный путь предыдущего канона отсутствует или не является обычным файлом.', path));
116
162
  }
117
163
  }
118
- // Новый канон обязан быть надмножеством: удаление путей этот upgrade не выполняет.
119
- for (const path of Object.keys(baseline)) {
164
+ // Новый канон обязан быть надмножеством с тем же владением: ни удалять, ни передавать пути этот upgrade не умеет.
165
+ for (const [path, ownership] of Object.entries(baseline)) {
120
166
  if (!(path in current))
121
167
  blockers.push(blocker('upgrade-removal-unsupported', 'Путь предыдущего канона отсутствует в текущем; upgrade ничего не удаляет.', path));
168
+ else if (current[path] !== ownership && !(ownership === 'managed' && current[path] === 'project-owned')) {
169
+ blockers.push(blocker('upgrade-ownership-change-unsupported', `Владение путём меняется (${ownership} → ${current[path]}); этот upgrade такого перехода не знает.`, path));
170
+ }
122
171
  }
123
172
  if (blockers.length > 0)
124
- return blocked(root, fromVersion, ...blockers);
173
+ return blockedAt(root, release, fromVersion, blockers);
125
174
  if (await exists(join(root, STAGING_DIR))) {
126
- return blocked(root, fromVersion, blocker('upgrade-staging-present', 'Каталог транзакции уже существует: возможно, прошлый запуск был прерван. Проверьте и удалите его вручную.', STAGING_DIR));
175
+ return blockedAt(root, release, fromVersion, [blocker('upgrade-staging-present', 'Каталог транзакции уже существует: прошлый запуск был прерван. В его подпапке backup/ лежат прежние версии файлов. Сверьте проект (git status, git diff), верните нужное из backup/ и только потом удалите каталог.', STAGING_DIR)]);
127
176
  }
128
- // 1. Восстановление подстановок по прошлым каноническим шаблонам.
177
+ const checksums = await loadChecksums(root);
178
+ if (checksums === null) {
179
+ return blockedAt(root, release, fromVersion, [blocker('upgrade-checksums-invalid', 'Контрольные суммы проекта отсутствуют или повреждены.', CHECKSUMS_PATH)]);
180
+ }
181
+ // 1. Managed-пути прошлого канона: прошлый исходник, новый исходник и, если upgrade
182
+ // их затрагивает, доказательство, что файл на диске — неизменённый рендер прошлого.
129
183
  const vars = {};
130
- const baselineSources = new Map();
131
- for (const template of BASELINE_TEMPLATES) {
132
- let source;
133
- try {
134
- source = (await readFile(join(packageRoot(), template.source), 'utf8')).replace(/\r\n/g, '\n');
184
+ const affected = [];
185
+ const optional = [];
186
+ /** Переход managed → project-owned: нетронутый файл получает новый стартовый текст, изменённый остаётся как есть. */
187
+ const handover = [];
188
+ const startingPoint = manifest.project.startingPoint;
189
+ const remember = (path, recovered) => {
190
+ for (const key of ['projectName', 'date']) {
191
+ const value = recovered[key];
192
+ if (value === undefined)
193
+ continue;
194
+ if (vars[key] !== undefined && vars[key] !== value) {
195
+ blockers.push(blocker('upgrade-variable-conflict', `Подстановка ${key} восстанавливается по-разному в разных managed-файлах.`, path));
196
+ return false;
197
+ }
198
+ vars[key] = value;
135
199
  }
136
- catch (cause) {
137
- blockers.push(blocker('upgrade-baseline-unreadable', `Baseline-шаблон пакета недоступен: ${cause instanceof Error ? cause.message : String(cause)}`, template.source));
200
+ return true;
201
+ };
202
+ for (const [path, ownership] of Object.entries(baseline)) {
203
+ if (ownership !== 'managed' && ownership !== 'immutable')
204
+ continue;
205
+ // Пустой маркер каталога: во всех канонах это ноль байт, обновлять нечего.
206
+ if (path.endsWith('/.gitkeep'))
207
+ continue;
208
+ const previous = await releaseSource(release, path);
209
+ if ('blocker' in previous) {
210
+ blockers.push(previous.blocker);
138
211
  continue;
139
212
  }
140
- if (sha256(source) !== template.sha256) {
141
- blockers.push(blocker('upgrade-baseline-corrupt', 'Baseline-шаблон пакета не совпадает со своей контрольной суммой и не может быть авторитетом.', template.source));
213
+ const next = await currentSource(path);
214
+ if (current[path] === 'project-owned') {
215
+ if (await pathHasSymlink(root, path)) {
216
+ blockers.push(blocker('upgrade-path-symlink', 'Передаваемый проекту путь не должен содержать symbolic link.', path));
217
+ continue;
218
+ }
219
+ const actual = normalizeEol(await readFile(join(root, path), 'utf8'));
220
+ const recovered = recoverTemplateVars(previous.source, actual, startingPoint, fromVersion);
221
+ const pristine = recovered !== null && checksums.files[path] === contentChecksum(path, actual);
222
+ if (pristine && recovered !== null)
223
+ remember(path, recovered);
224
+ handover.push({ path, next: pristine ? next : null });
142
225
  continue;
143
226
  }
144
- baselineSources.set(template.path, source);
145
- if (await pathHasSymlink(root, template.path)) {
146
- blockers.push(blocker('upgrade-path-symlink', 'Обновляемый путь не должен содержать symbolic link.', template.path));
227
+ const pinsVersion = templateUses(previous.source).version || templateUses(next).version;
228
+ if (previous.source === next && !pinsVersion) {
229
+ // Этот upgrade путь не трогает: правки пользователя в нём — не его забота.
230
+ optional.push({ path, source: previous.source });
147
231
  continue;
148
232
  }
149
- const actual = await readFile(join(root, template.path), 'utf8');
150
- const recovered = recoverTemplateVars(source, actual, manifest.project.startingPoint);
233
+ if (await pathHasSymlink(root, path)) {
234
+ blockers.push(blocker('upgrade-path-symlink', 'Обновляемый путь не должен содержать symbolic link.', path));
235
+ continue;
236
+ }
237
+ const actual = normalizeEol(await readFile(join(root, path), 'utf8'));
238
+ const recovered = recoverTemplateVars(previous.source, actual, startingPoint, fromVersion);
151
239
  if (recovered === null) {
152
- blockers.push(blocker('upgrade-managed-modified', 'Managed-файл изменён относительно прошлого канона: upgrade не перезаписывает изменённое содержимое.', template.path));
240
+ blockers.push(blocker('upgrade-managed-modified', `Файл Maestro изменён вручную относительно версии ${fromVersion}, поэтому upgrade его не перезапишет. Верните файл к исходному виду или перенесите свои правки в собственный файл проекта, затем повторите.`, path));
153
241
  continue;
154
242
  }
155
- for (const key of ['projectName', 'date']) {
156
- const value = recovered[key];
157
- if (value === undefined)
158
- continue;
159
- if (vars[key] !== undefined && vars[key] !== value) {
160
- blockers.push(blocker('upgrade-variable-conflict', `Подстановка ${key} восстанавливается по-разному в разных managed-файлах.`, template.path));
161
- continue;
162
- }
163
- vars[key] = value;
243
+ if (!remember(path, recovered))
244
+ continue;
245
+ if (checksums.files[path] !== contentChecksum(path, actual)) {
246
+ blockers.push(blocker('upgrade-checksum-mismatch', 'Записанная контрольная сумма не совпадает с файлом: metadata проекта противоречива.', path));
247
+ continue;
164
248
  }
249
+ affected.push({ path, next, actual });
165
250
  }
166
251
  if (blockers.length > 0)
167
- return blocked(root, fromVersion, ...blockers);
168
- // 2. Контрольные суммы обязаны подтверждать ту же картину: расхождение metadata — тоже конфликт.
169
- const checksums = await loadChecksums(root);
170
- if (checksums === null) {
171
- return blocked(root, fromVersion, blocker('upgrade-checksums-invalid', 'Контрольные суммы проекта отсутствуют или повреждены.', CHECKSUMS_PATH));
172
- }
173
- for (const template of BASELINE_TEMPLATES) {
174
- const recorded = checksums.files[template.path];
175
- const actual = contentChecksum(template.path, await readFile(join(root, template.path)));
176
- if (recorded !== actual) {
177
- blockers.push(blocker('upgrade-checksum-mismatch', 'Записанная контрольная сумма не совпадает с файлом: metadata проекта противоречива.', template.path));
178
- }
252
+ return blockedAt(root, release, fromVersion, blockers);
253
+ // Недостающие подстановки можно взять из файлов, которые upgrade не трогает. Это
254
+ // только подсказка: правка в таком файле не имеет права остановить обновление,
255
+ // поэтому расхождение здесь не блокирует, а уже известное значение не меняется.
256
+ for (const { path, source } of optional) {
257
+ if (vars.projectName !== undefined && vars.date !== undefined)
258
+ break;
259
+ const uses = templateUses(source);
260
+ if (!uses.projectName && !uses.date)
261
+ continue;
262
+ if (await pathHasSymlink(root, path))
263
+ continue;
264
+ const recovered = recoverTemplateVars(source, await readFile(join(root, path), 'utf8'), startingPoint, fromVersion);
265
+ if (recovered === null)
266
+ continue;
267
+ vars.projectName ??= recovered.projectName;
268
+ vars.date ??= recovered.date;
179
269
  }
180
- if (blockers.length > 0)
181
- return blocked(root, fromVersion, ...blockers);
182
- // 3. Новые пути канона. Содержимое собирается только из шаблонов текущей версии.
183
- const newPaths = Object.keys(current).filter((path) => !(path in baseline));
184
- const writes = [];
185
- const creates = [];
186
270
  const renderVars = (source) => {
187
271
  const uses = templateUses(source);
188
272
  if ((uses.projectName && vars.projectName === undefined) || (uses.date && vars.date === undefined))
189
273
  return null;
190
- return { projectName: vars.projectName ?? '', date: vars.date ?? '', startingPoint: manifest.project.startingPoint };
274
+ return { projectName: vars.projectName ?? '', date: vars.date ?? '', startingPoint, version: VERSION };
191
275
  };
276
+ // 2. Новые пути канона. Содержимое собирается только из шаблонов текущей версии.
277
+ const newPaths = Object.keys(current).filter((path) => !(path in baseline));
278
+ const writes = [];
279
+ const creates = [];
280
+ const keptExisting = [];
192
281
  for (const path of newPaths.sort()) {
193
282
  const ownership = current[path];
194
283
  if (await pathHasSymlink(root, path)) {
@@ -196,6 +285,11 @@ export async function analyzeUpgrade(rootInput) {
196
285
  continue;
197
286
  }
198
287
  if (await exists(join(root, path))) {
288
+ // Файл проекта, который проект завёл сам раньше Maestro, остаётся как есть.
289
+ if (ownership === 'project-owned' && await isRegularFile(join(root, path))) {
290
+ keptExisting.push(path);
291
+ continue;
292
+ }
199
293
  blockers.push(blocker('upgrade-path-collision', 'Добавляемый путь уже занят: upgrade не перезаписывает существующее содержимое.', path));
200
294
  continue;
201
295
  }
@@ -219,31 +313,41 @@ export async function analyzeUpgrade(rootInput) {
219
313
  creates.push({ path, ownership });
220
314
  writes.push({ path, content, action: 'create' });
221
315
  }
222
- // 4. Обновления managed-файлов с доказанным preimage.
316
+ // 3. Обновления managed-файлов с доказанным preimage.
223
317
  const updates = [];
224
318
  const unchanged = [];
225
- for (const template of BASELINE_TEMPLATES) {
226
- const source = await readTemplate(template.path);
227
- const templateVars = renderVars(source);
319
+ for (const { path, next, actual } of affected) {
320
+ const templateVars = renderVars(next);
228
321
  if (templateVars === null) {
229
- blockers.push(blocker('upgrade-variable-unrecoverable', 'Шаблон требует подстановку, которую нельзя восстановить из проекта; угадывать её нельзя.', template.path));
322
+ blockers.push(blocker('upgrade-variable-unrecoverable', 'Шаблон требует подстановку, которую нельзя восстановить из проекта; угадывать её нельзя.', path));
230
323
  continue;
231
324
  }
232
- const content = renderTemplate(source, templateVars);
233
- const actual = (await readFile(join(root, template.path), 'utf8')).replace(/\r\n/g, '\n');
234
- if (content.replace(/\r\n/g, '\n') === actual) {
235
- unchanged.push(template.path);
325
+ const content = path === '.gitattributes' ? next : renderTemplate(next, templateVars);
326
+ if (normalizeEol(content) === actual) {
327
+ unchanged.push(path);
236
328
  continue;
237
329
  }
238
- updates.push({ path: template.path, ownership: current[template.path] });
239
- writes.push({ path: template.path, content, action: 'update' });
330
+ updates.push({ path, ownership: current[path] });
331
+ writes.push({ path, content, action: 'update' });
332
+ }
333
+ for (const { path, next } of handover) {
334
+ if (next === null)
335
+ continue; // изменённый файл передаётся как есть
336
+ const templateVars = renderVars(next);
337
+ if (templateVars === null)
338
+ continue; // без подстановок новый текст не собрать — файл остаётся как есть
339
+ const content = renderTemplate(next, templateVars);
340
+ if (normalizeEol(content) === normalizeEol(await readFile(join(root, path), 'utf8')))
341
+ continue;
342
+ updates.push({ path, ownership: 'project-owned' });
343
+ writes.push({ path, content, action: 'update' });
240
344
  }
241
345
  if (blockers.length > 0)
242
- return blocked(root, fromVersion, ...blockers);
243
- // 5. Metadata. Manifest пересобирается по текущему канону; проектные поля переносятся как есть.
346
+ return blockedAt(root, release, fromVersion, blockers);
347
+ // 4. Metadata. Manifest пересобирается по текущему канону; проектные поля переносятся как есть.
244
348
  const nextManifest = buildManifest({
245
349
  projectName: manifest.project.name,
246
- startingPoint: manifest.project.startingPoint,
350
+ startingPoint,
247
351
  createdAt: manifest.project.createdAt,
248
352
  productName: readPackageJson().name,
249
353
  productVersion: VERSION,
@@ -255,20 +359,23 @@ export async function analyzeUpgrade(rootInput) {
255
359
  });
256
360
  // Суммы существующих файлов сохраняются как есть: upgrade не переоценивает чужие файлы.
257
361
  const nextChecksums = { ...checksums.files };
362
+ for (const { path } of handover)
363
+ delete nextChecksums[path];
258
364
  for (const write of writes) {
259
365
  if (current[write.path] === 'managed' || current[write.path] === 'immutable') {
260
366
  nextChecksums[write.path] = contentChecksum(write.path, write.content);
261
367
  }
262
368
  }
263
- const result = analysis(root, 'upgradable', fromVersion, []);
369
+ const result = analysis(root, 'upgradable', fromVersion, [], release.id);
264
370
  result.creates = creates;
265
371
  result.updates = updates;
266
372
  result.unchanged = unchanged.sort();
267
373
  result.metadata = [MANIFEST_PATH, CHECKSUMS_PATH];
268
- result.preserves = Object.entries(baseline)
269
- .filter(([path, ownership]) => ownership === 'project-owned' && path in current)
270
- .map(([path]) => path)
271
- .sort();
374
+ result.preserves = [
375
+ ...Object.entries(baseline).filter(([path, ownership]) => ownership === 'project-owned' && path in current).map(([path]) => path),
376
+ ...keptExisting,
377
+ ].sort();
378
+ result.handedOver = handover.map(({ path }) => path).sort();
272
379
  return {
273
380
  analysis: result,
274
381
  root,
@@ -144,4 +144,10 @@ export const BASELINE_TEMPLATES = [
144
144
  { path: 'wiki/index.md', source: 'registry/baseline/0.2/project/wiki/index.md', sha256: 'a6989e7ac718c72157adf2ff80eef7921701f83b45b7da60a9569cfbf1bc538a' },
145
145
  { path: '.claude/commands/build.md', source: 'registry/baseline/0.2/project/.claude/commands/build.md', sha256: 'aac17f7752c67645e7e5b027ffc08f9a144f075aa06acf7208853070c0b4c3c7' },
146
146
  { path: 'protocols/build.md', source: 'registry/baseline/0.2/project/protocols/build.md', sha256: '2ce00c73e5f3c03bee48e1b34ce34c8253383e2a9469feb5ae05b87b68c1a499' },
147
+ // Изменены в 0.3.0; в 0.2 и во всех 0.3 beta эти файлы побайтово одинаковы, поэтому копия общая.
148
+ { path: '.claude/agents/code-reviewer.md', source: 'registry/baseline/0.3.0-beta.4/project/.claude/agents/code-reviewer.md', sha256: 'b522bf8dfaef73df89c0045e98cee5636efea4b2787eef434b1c3700035c1568' },
149
+ { path: 'protocols/wiki.md', source: 'registry/baseline/0.3.0-beta.4/project/protocols/wiki.md', sha256: 'c8c2f901e88d6c13595bbd41239755d823d278acdb9c0202aeb1b5832ef24632' },
150
+ { path: 'protocols/handoff.md', source: 'registry/baseline/0.3.0-beta.4/project/protocols/handoff.md', sha256: '7aec6bf47408b42fc4bb9e977664295c9461dfd69c3ff438676c99e2d2b86b80' },
151
+ { path: 'protocols/context-budget.md', source: 'registry/baseline/0.3.0-beta.4/project/protocols/context-budget.md', sha256: 'e121d6dc75de04ea3624608be5f778d43e99afa815540738ec3a43e47ccdcf8c' },
152
+ { path: 'maestro/runbooks/cowork-audit.md', source: 'registry/baseline/0.3.0-beta.4/project/maestro/runbooks/cowork-audit.md', sha256: 'c3326dfd63dc94bce1bd1779e2d8116685cf7281b7d902c58f9138db6343f50b' },
147
153
  ];
@@ -83,12 +83,27 @@ export async function upgradeProject(rootInput, options = {}) {
83
83
  }
84
84
  }
85
85
  catch (cause) {
86
+ const reason = cause instanceof Error ? cause.message : String(cause);
87
+ const unrestored = [];
86
88
  for (const write of [...committed].reverse()) {
87
89
  const target = join(root, write.path);
88
- if (write.action === 'update')
89
- await rename(join(backupDir, write.path), target).catch(() => undefined);
90
- else
91
- await rm(target, { force: true });
90
+ try {
91
+ if (write.action === 'update')
92
+ await rename(join(backupDir, write.path), target);
93
+ else
94
+ await rm(target, { force: true });
95
+ }
96
+ catch {
97
+ unrestored.push(write.path);
98
+ }
99
+ }
100
+ if (unrestored.length > 0) {
101
+ // Откат не удался: backup — единственная копия прежних файлов, удалять его нельзя.
102
+ return result(plan, {
103
+ ok: false,
104
+ rolledBack: false,
105
+ error: `Применение прервано (${reason}), и откатить удалось не всё: ${unrestored.join(', ')}. Прежние версии файлов оставлены в ${STAGING_DIR}/backup/ — верните их вручную, затем удалите ${STAGING_DIR}.`,
106
+ });
92
107
  }
93
108
  // Каталоги, созданные ради новых путей, удаляются только пустыми и только свои.
94
109
  for (const dir of [...createdDirs].reverse())
@@ -97,7 +112,7 @@ export async function upgradeProject(rootInput, options = {}) {
97
112
  return result(plan, {
98
113
  ok: false,
99
114
  rolledBack: true,
100
- error: `Применение прервано и откачено: ${cause instanceof Error ? cause.message : String(cause)}`,
115
+ error: `Применение прервано и откачено: ${reason}`,
101
116
  });
102
117
  }
103
118
  await rm(staging, { recursive: true, force: true });
@@ -16,6 +16,7 @@ import { renderTemplate } from '../template.js';
16
16
  /** Сентинелы содержат NUL: этот символ не может встретиться в тексте шаблона. */
17
17
  const PROJECT_NAME_SENTINEL = '\u0000{PROJECT_NAME}\u0000';
18
18
  const DATE_SENTINEL = '\u0000{DATE}\u0000';
19
+ const VERSION_SENTINEL = '\u0000{MAESTRO_VERSION}\u0000';
19
20
  function escapeRegExp(value) {
20
21
  return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
21
22
  }
@@ -24,11 +25,14 @@ function escapeRegExp(value) {
24
25
  *
25
26
  * Возвращает null, если такого набора подстановок не существует.
26
27
  */
27
- export function recoverTemplateVars(source, actual, startingPoint) {
28
+ export function recoverTemplateVars(source, actual, startingPoint, version) {
29
+ // Версия не восстанавливается, а берётся из manifest: файл обязан быть рендером
30
+ // ровно той версии, которая записала проект.
28
31
  const shape = renderTemplate(source, {
29
32
  projectName: PROJECT_NAME_SENTINEL,
30
33
  date: DATE_SENTINEL,
31
34
  startingPoint,
35
+ version,
32
36
  });
33
37
  const parts = shape.split(new RegExp(`(${escapeRegExp(PROJECT_NAME_SENTINEL)}|${escapeRegExp(DATE_SENTINEL)})`));
34
38
  const groups = [];
@@ -58,6 +62,7 @@ export function recoverTemplateVars(source, actual, startingPoint) {
58
62
  projectName: recovered.projectName ?? '',
59
63
  date: recovered.date ?? '',
60
64
  startingPoint,
65
+ version,
61
66
  };
62
67
  return normalizeEol(renderTemplate(source, vars)) === normalizeEol(actual) ? recovered : null;
63
68
  }
@@ -67,6 +72,11 @@ export function templateUses(source) {
67
72
  projectName: PROJECT_NAME_SENTINEL,
68
73
  date: DATE_SENTINEL,
69
74
  startingPoint: 'idea',
75
+ version: VERSION_SENTINEL,
70
76
  });
71
- return { projectName: probe.includes(PROJECT_NAME_SENTINEL), date: probe.includes(DATE_SENTINEL) };
77
+ return {
78
+ projectName: probe.includes(PROJECT_NAME_SENTINEL),
79
+ date: probe.includes(DATE_SENTINEL),
80
+ version: probe.includes(VERSION_SENTINEL),
81
+ };
72
82
  }