create-vibe-maestro 0.4.0 → 0.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +52 -0
- package/README.md +34 -30
- package/dist/cli/context-run.js +38 -0
- package/dist/cli/create-run.js +74 -9
- package/dist/cli/create.js +21 -2
- package/dist/cli/doctor-run.js +2 -1
- package/dist/cli/maestro.js +67 -1
- package/dist/cli/pack-run.js +44 -0
- package/dist/cli/prompt.js +12 -4
- package/dist/cli/renderer.js +5 -4
- package/dist/cli/upgrade-run.js +4 -0
- package/dist/core/context.js +169 -0
- package/dist/core/doctor/git.js +41 -1
- package/dist/core/doctor/inbox.js +5 -11
- package/dist/core/doctor/sources.js +1 -1
- package/dist/core/github.js +107 -0
- package/dist/core/init.js +37 -10
- package/dist/core/inventory.js +4 -0
- package/dist/core/pack.js +379 -0
- package/dist/core/readme.js +21 -0
- package/dist/core/settings.js +39 -0
- package/dist/core/upgrade/analyze.js +61 -8
- package/dist/core/upgrade/baseline.js +4 -0
- package/dist/core/upgrade/releases.js +73 -3
- package/dist/core/zip.js +133 -0
- package/docs/ROADMAP.md +74 -47
- package/docs/USER_GUIDE.md +113 -60
- package/package.json +1 -1
- package/registry/baseline/0.4.0/project/.claude/rules/maestro.md +35 -0
- package/registry/baseline/0.4.0/project/protocols/completion.md +22 -0
- package/registry/baseline/0.4.0/project/protocols/handoff.md +15 -0
- package/registry/baseline/0.4.1/project/.claude/commands/plan.md +2 -0
- package/registry/baseline/0.4.1/project/.claude/rules/maestro.md +35 -0
- package/registry/baseline/0.4.1/project/maestro/inbox/README.md +16 -0
- package/registry/baseline/0.4.1/project/maestro/runbooks/cowork-discovery.md +30 -0
- package/registry/baseline/0.4.1/project/protocols/discovery.md +5 -0
- package/registry/baseline/0.4.1/project/protocols/plan.md +142 -0
- package/registry/capabilities.v1.json +13 -1
- package/templates/project/.claude/commands/plan.md +1 -0
- package/templates/project/.claude/commands/start.md +2 -0
- package/templates/project/.claude/rules/maestro.md +6 -4
- package/templates/project/.claude/rules/project.md +6 -0
- package/templates/project/.claude/settings.json +2 -0
- package/templates/project/README.md +11 -0
- package/templates/project/maestro/inbox/README.md +6 -6
- package/templates/project/maestro/runbooks/cowork-discovery.md +1 -1
- package/templates/project/protocols/completion.md +1 -1
- package/templates/project/protocols/discovery.md +1 -3
- package/templates/project/protocols/handoff.md +1 -1
- package/templates/project/protocols/plan.md +14 -7
- package/templates/project/protocols/start.md +64 -0
- package/templates/project/wiki/concepts/discovery.md +30 -11
- package/templates/project/wiki/hot.md +2 -2
- package/templates/project/wiki/index.md +1 -0
- package/templates/project/wiki/passport.md +2 -0
- package/templates/project/wiki/plans/0001-starter.md +4 -3
- package/templates/project/wiki/restore.md +32 -0
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { dirname, join, resolve } from 'node:path';
|
|
3
|
+
import { defaultArchiveName, packProject } from '../core/pack.js';
|
|
4
|
+
import { resolveDesktopDirectory } from './desktop.js';
|
|
5
|
+
import { homedir } from 'node:os';
|
|
6
|
+
import { EXIT_FAILED, EXIT_OK } from './io.js';
|
|
7
|
+
/** Архив по умолчанию кладётся на Рабочий стол: его оттуда отправляют заказчику. Нет Рабочего стола — рядом с проектом. */
|
|
8
|
+
async function defaultOut(root, tag) {
|
|
9
|
+
const name = defaultArchiveName(root, tag);
|
|
10
|
+
try {
|
|
11
|
+
const desktop = await resolveDesktopDirectory({ platform: process.platform, home: homedir() });
|
|
12
|
+
if (existsSync(desktop))
|
|
13
|
+
return join(desktop, name);
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
// без домашней папки — рядом с проектом
|
|
17
|
+
}
|
|
18
|
+
return join(dirname(resolve(root)), name);
|
|
19
|
+
}
|
|
20
|
+
export async function executePackCommand(options, io) {
|
|
21
|
+
const out = options.out === undefined ? await defaultOut(options.path, options.tag) : resolve(options.out);
|
|
22
|
+
const result = await packProject({ root: options.path, tag: options.tag, out, allow: options.allow ?? [] });
|
|
23
|
+
if (options.json) {
|
|
24
|
+
io.out(JSON.stringify({ reportVersion: 1, ...result }, null, 2));
|
|
25
|
+
return result.ok ? EXIT_OK : EXIT_FAILED;
|
|
26
|
+
}
|
|
27
|
+
if (!result.ok) {
|
|
28
|
+
io.err('Vibe Coding Maestro pack: архив не создан.');
|
|
29
|
+
for (const item of result.findings)
|
|
30
|
+
io.err(`- ${item.code}${item.path ? ` (${item.path})` : ''}: ${item.message}`);
|
|
31
|
+
return EXIT_FAILED;
|
|
32
|
+
}
|
|
33
|
+
io.out(result.reused === true
|
|
34
|
+
? `Архив тега ${result.tag} уже лежит здесь и совпадает побайтово: ${result.archive}`
|
|
35
|
+
: `Архив тега ${result.tag} готов: ${result.archive}`);
|
|
36
|
+
io.out(`Файлов: ${result.files}, размер: ${result.bytes} байт, sha256: ${result.sha256}`);
|
|
37
|
+
io.out('Не вошли: wiki/, maestro/, .claude/, protocols/, .maestro/, CLAUDE.md, AGENTS.md, .mcp.json. В корне архива — HANDOVER.md: первым делом заказчик меняет все пароли и ключи.');
|
|
38
|
+
for (const note of result.notes ?? [])
|
|
39
|
+
io.out(note);
|
|
40
|
+
if ((options.allow ?? []).length > 0)
|
|
41
|
+
io.out(`Без проверки на секреты по решению человека: ${(options.allow ?? []).join(', ')}.`);
|
|
42
|
+
io.out('Перед отправкой откройте архив и проверьте HANDOVER.md. Отправка заказчику — только после «да» человека.');
|
|
43
|
+
return EXIT_OK;
|
|
44
|
+
}
|
package/dist/cli/prompt.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { createInterface } from 'node:readline';
|
|
2
|
+
import { githubReady } from '../core/github.js';
|
|
2
3
|
import { resolveProjectInput, runtimeDesktopOptions } from './desktop.js';
|
|
3
4
|
import { createRenderer, runtimeRendererOptions } from './renderer.js';
|
|
4
5
|
/** Минимальная ширина, при которой перерисовка меню по фиксированному числу строк безопасна. */
|
|
@@ -226,17 +227,24 @@ export async function askLine(input, output, renderer, question, hint, capabilit
|
|
|
226
227
|
restoreListeners(input, listenersBefore);
|
|
227
228
|
}
|
|
228
229
|
}
|
|
229
|
-
export function createReadlinePrompt(input = process.stdin, output = process.stdout) {
|
|
230
|
+
export function createReadlinePrompt(input = process.stdin, output = process.stdout, options = {}) {
|
|
230
231
|
const renderer = createRenderer((text) => output.write(text), runtimeRendererOptions(output));
|
|
231
232
|
const capabilities = promptCapabilities(output, process.env);
|
|
232
233
|
return {
|
|
233
234
|
renderer,
|
|
234
235
|
async ask() {
|
|
236
|
+
// Вход в gh проверяется, пока человек читает приветствие; нет ответа за 3 с — варианта нет.
|
|
237
|
+
const github = (options.detectGithub ?? (() => githubReady()))().catch(() => false);
|
|
235
238
|
renderer.welcome();
|
|
236
|
-
const
|
|
239
|
+
const choices = [
|
|
237
240
|
{ value: 'create', label: 'Создать новый проект' },
|
|
238
241
|
{ value: 'check', label: 'Проверить canonical project' },
|
|
239
|
-
]
|
|
242
|
+
];
|
|
243
|
+
// Новый вариант — последним: «1 — создать» и «2 — проверить» не меняются.
|
|
244
|
+
if (await github)
|
|
245
|
+
choices.push({ value: 'create-github', label: 'Создать новый проект и закрытую копию на GitHub' });
|
|
246
|
+
const chosen = await selectChoice(input, output, renderer, 'Что вы хотите сделать?', choices, capabilities);
|
|
247
|
+
const action = chosen === 'check' ? 'check' : 'create';
|
|
240
248
|
const question = action === 'create' ? 'Как назовём проект? Можно указать полный путь.' : 'Какой canonical project проверить?';
|
|
241
249
|
const hint = action === 'create' ? 'Например: Мой проект. Тогда папка появится на Рабочем столе.' : 'Перетащите папку сюда или вставьте путь.';
|
|
242
250
|
const raw = await askLine(input, output, renderer, question, hint, capabilities);
|
|
@@ -254,7 +262,7 @@ export function createReadlinePrompt(input = process.stdin, output = process.std
|
|
|
254
262
|
], capabilities);
|
|
255
263
|
renderer.preview({ action, target: project.target, name: project.name, usedDesktopDefault: project.usedDesktopDefault });
|
|
256
264
|
renderer.progress('Создаём структуру canonical project…');
|
|
257
|
-
return { action, target: project.target, name: project.name, startingPoint, usedDesktopDefault: project.usedDesktopDefault };
|
|
265
|
+
return { action, target: project.target, name: project.name, startingPoint, usedDesktopDefault: project.usedDesktopDefault, github: chosen === 'create-github' };
|
|
258
266
|
},
|
|
259
267
|
};
|
|
260
268
|
}
|
package/dist/cli/renderer.js
CHANGED
|
@@ -124,12 +124,13 @@ export function createRenderer(write, options) {
|
|
|
124
124
|
model.name ? `Название: ${model.name}` : '',
|
|
125
125
|
'Проект находится здесь:',
|
|
126
126
|
model.target,
|
|
127
|
+
model.cloud ? `Копия в облаке: ${model.cloud}` : 'Копии в облаке нет — завести её поможет /start.',
|
|
127
128
|
'',
|
|
128
129
|
'Что делать дальше:',
|
|
129
|
-
'1. Откройте папку
|
|
130
|
-
'2.
|
|
131
|
-
'3.
|
|
132
|
-
'4.
|
|
130
|
+
'1. Откройте папку проекта в Claude Code.',
|
|
131
|
+
'2. Материалы, если есть, положите в maestro/inbox/. Готовый код оставьте, где лежит: /start спросит путь.',
|
|
132
|
+
'3. Напишите /start — знакомство с задачей.',
|
|
133
|
+
'4. Потом /plan — план до кода.',
|
|
133
134
|
'',
|
|
134
135
|
'Проверка пройдена: структура проекта в порядке.',
|
|
135
136
|
].filter((line, index, all) => line !== '' || (index > 0 && all[index - 1] !== '')), 'success');
|
package/dist/cli/upgrade-run.js
CHANGED
|
@@ -47,6 +47,8 @@ export async function executeUpgradeCommand(options, io) {
|
|
|
47
47
|
if (keptAsIs.length > 0)
|
|
48
48
|
io.out(`Вы меняли эти файлы, поэтому они переданы как есть: ${keptAsIs.join(', ')}. Если в них осталась команда Maestro старой версии, обновите её — актуальная лежит в .claude/rules/maestro.md (doctor напомнит).`);
|
|
49
49
|
list('Сохранено без изменений', analysis.preserves);
|
|
50
|
+
for (const note of analysis.notes)
|
|
51
|
+
io.out(`Важно: ${note}`);
|
|
50
52
|
// До коммита doctor честно покажет git-managed-dirty: сначала diff и коммит, потом проверка.
|
|
51
53
|
io.out('Добавьте в Git все изменения, включая новые файлы (git add -A), просмотрите их (git diff --cached) и закоммитьте: до коммита doctor покажет git-managed-dirty и git-managed-untracked.');
|
|
52
54
|
// Та же версия, что применила обновление: doctor проверяет ровно её канон.
|
|
@@ -60,6 +62,8 @@ export async function executeUpgradeCommand(options, io) {
|
|
|
60
62
|
list('Уже совпадает', analysis.unchanged);
|
|
61
63
|
list('Останется без изменений', analysis.preserves);
|
|
62
64
|
list('Служебные файлы', analysis.metadata);
|
|
65
|
+
for (const note of analysis.notes)
|
|
66
|
+
io.out(`Важно: ${note}`);
|
|
63
67
|
// Применять обязана та же версия, что показала это предложение, а не новая @latest.
|
|
64
68
|
io.out(`Применить: ${serviceInvocation(VERSION)} upgrade --path ${quotePathArg(options.path)} --apply`);
|
|
65
69
|
return EXIT_OK;
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { open, readdir, readFile, stat } from 'node:fs/promises';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { join, resolve } from 'node:path';
|
|
5
|
+
/**
|
|
6
|
+
* Размер текущей сессии Claude Code по её журналу `~/.claude/projects/<папка>/<сессия>.jsonl`.
|
|
7
|
+
*
|
|
8
|
+
* Читаются только числа из `message.usage` ответов модели: текст переписки не
|
|
9
|
+
* разбирается и не печатается. Каждый шаг сессии заново отправляет модели всю
|
|
10
|
+
* историю, поэтому длинная сессия дорожает с каждым шагом.
|
|
11
|
+
*/
|
|
12
|
+
/** Окно модели по умолчанию. Сессия больше него была бы невозможна — тогда окно 1 000 000. */
|
|
13
|
+
export const DEFAULT_BUDGET = 200_000;
|
|
14
|
+
export const LARGE_WINDOW = 1_000_000;
|
|
15
|
+
/** HYPOTHESIS: пороги подобраны на глаз и уточняются повторным замером. */
|
|
16
|
+
export const FINISH_SLICE_SHARE = 0.4;
|
|
17
|
+
export const NEW_SESSION_SHARE = 0.7;
|
|
18
|
+
/** Имя папки журналов: Claude Code заменяет в пути проекта всё, кроме латиницы и цифр, на `-`. */
|
|
19
|
+
export function projectLogDirName(root) {
|
|
20
|
+
return resolve(root).replace(/[^a-zA-Z0-9]/g, '-');
|
|
21
|
+
}
|
|
22
|
+
async function newestJsonl(dir) {
|
|
23
|
+
let names;
|
|
24
|
+
try {
|
|
25
|
+
names = (await readdir(dir)).filter((name) => name.endsWith('.jsonl'));
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
let best = null;
|
|
31
|
+
for (const name of names) {
|
|
32
|
+
const path = join(dir, name);
|
|
33
|
+
const { mtimeMs } = await stat(path);
|
|
34
|
+
if (best === null || mtimeMs > best.mtime || (mtimeMs === best.mtime && path > best.path))
|
|
35
|
+
best = { path, mtime: mtimeMs };
|
|
36
|
+
}
|
|
37
|
+
return best?.path ?? null;
|
|
38
|
+
}
|
|
39
|
+
async function tail(path, bytes) {
|
|
40
|
+
const handle = await open(path, 'r');
|
|
41
|
+
try {
|
|
42
|
+
const { size } = await handle.stat();
|
|
43
|
+
const length = Math.min(size, bytes);
|
|
44
|
+
const buffer = Buffer.alloc(length);
|
|
45
|
+
await handle.read(buffer, 0, length, size - length);
|
|
46
|
+
return buffer.toString('utf8');
|
|
47
|
+
}
|
|
48
|
+
finally {
|
|
49
|
+
await handle.close();
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Журнал текущей сессии. Известен id сессии — её файл `<id>.jsonl`. Иначе самый
|
|
54
|
+
* свежий журнал в папке проекта. Длинные и не-латинские пути Claude Code может
|
|
55
|
+
* назвать иначе, поэтому запасной путь — самый свежий журнал с той же рабочей папкой.
|
|
56
|
+
*/
|
|
57
|
+
export async function findTranscript(root, claudeDir, sessionId) {
|
|
58
|
+
const projects = join(claudeDir, 'projects');
|
|
59
|
+
if (sessionId !== undefined) {
|
|
60
|
+
// Известна сессия — только её журнал: молча мерить другую сессию нельзя.
|
|
61
|
+
if (!/^[A-Za-z0-9-]+$/.test(sessionId))
|
|
62
|
+
return null;
|
|
63
|
+
const own = join(projects, projectLogDirName(root), `${sessionId}.jsonl`);
|
|
64
|
+
if (existsSync(own))
|
|
65
|
+
return own;
|
|
66
|
+
for (const dir of await readdir(projects).catch(() => [])) {
|
|
67
|
+
const candidate = join(projects, dir, `${sessionId}.jsonl`);
|
|
68
|
+
if (existsSync(candidate))
|
|
69
|
+
return candidate;
|
|
70
|
+
}
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
const direct = await newestJsonl(join(projects, projectLogDirName(root)));
|
|
74
|
+
if (direct !== null)
|
|
75
|
+
return direct;
|
|
76
|
+
let dirs;
|
|
77
|
+
try {
|
|
78
|
+
dirs = await readdir(projects);
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
const marker = `"cwd":${JSON.stringify(resolve(root))}`;
|
|
84
|
+
let best = null;
|
|
85
|
+
for (const dir of dirs) {
|
|
86
|
+
const candidate = await newestJsonl(join(projects, dir));
|
|
87
|
+
if (candidate === null)
|
|
88
|
+
continue;
|
|
89
|
+
if (!(await tail(candidate, 256 * 1024)).includes(marker))
|
|
90
|
+
continue;
|
|
91
|
+
const { mtimeMs } = await stat(candidate);
|
|
92
|
+
if (best === null || mtimeMs > best.mtime)
|
|
93
|
+
best = { path: candidate, mtime: mtimeMs };
|
|
94
|
+
}
|
|
95
|
+
return best?.path ?? null;
|
|
96
|
+
}
|
|
97
|
+
const count = (value) => (typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0);
|
|
98
|
+
export function levelFor(share) {
|
|
99
|
+
if (share >= NEW_SESSION_SHARE)
|
|
100
|
+
return 'new-session';
|
|
101
|
+
if (share >= FINISH_SLICE_SHARE)
|
|
102
|
+
return 'finish-slice';
|
|
103
|
+
return 'continue';
|
|
104
|
+
}
|
|
105
|
+
export async function measureContext(options) {
|
|
106
|
+
let budget = options.budget ?? DEFAULT_BUDGET;
|
|
107
|
+
const claudeDir = options.claudeDir ?? (process.env.CLAUDE_CONFIG_DIR || join(homedir(), '.claude'));
|
|
108
|
+
const sessionId = options.sessionId ?? (process.env.CLAUDE_CODE_SESSION_ID || undefined);
|
|
109
|
+
const transcript = await findTranscript(options.root, claudeDir, sessionId);
|
|
110
|
+
if (transcript === null) {
|
|
111
|
+
if (sessionId !== undefined) {
|
|
112
|
+
return { reportVersion: 1, ok: false, budget, message: `Журнал сессии ${sessionId} не найден в ${join(claudeDir, 'projects')}: измерять чужую сессию вместо неё команда не будет.` };
|
|
113
|
+
}
|
|
114
|
+
return { reportVersion: 1, ok: false, budget, message: `Журнал сессии Claude Code для этой папки не найден (искал в ${join(claudeDir, 'projects')}). Команда работает внутри сессии Claude Code, открытой в папке проекта.` };
|
|
115
|
+
}
|
|
116
|
+
const seen = new Set();
|
|
117
|
+
let last = null;
|
|
118
|
+
let totalInput = 0;
|
|
119
|
+
let largest = 0;
|
|
120
|
+
let recordedSession;
|
|
121
|
+
for (const line of (await readFile(transcript, 'utf8')).split('\n')) {
|
|
122
|
+
if (line.trim() === '')
|
|
123
|
+
continue;
|
|
124
|
+
let entry;
|
|
125
|
+
try {
|
|
126
|
+
entry = JSON.parse(line);
|
|
127
|
+
}
|
|
128
|
+
catch {
|
|
129
|
+
continue; // незаконченная последняя строка, пока сессия пишет журнал
|
|
130
|
+
}
|
|
131
|
+
if (entry.type !== 'assistant' || entry.isSidechain === true)
|
|
132
|
+
continue;
|
|
133
|
+
const usage = entry.message?.usage;
|
|
134
|
+
const id = entry.message?.id;
|
|
135
|
+
if (usage === undefined || typeof id !== 'string')
|
|
136
|
+
continue;
|
|
137
|
+
if (typeof entry.sessionId === 'string')
|
|
138
|
+
recordedSession = entry.sessionId;
|
|
139
|
+
const size = count(usage.input_tokens) + count(usage.cache_read_input_tokens) + count(usage.cache_creation_input_tokens) + count(usage.output_tokens);
|
|
140
|
+
// Служебные записи без расхода (`<synthetic>`) не говорят о размере контекста.
|
|
141
|
+
if (size === 0)
|
|
142
|
+
continue;
|
|
143
|
+
last = usage;
|
|
144
|
+
largest = Math.max(largest, size);
|
|
145
|
+
if (seen.has(id))
|
|
146
|
+
continue;
|
|
147
|
+
seen.add(id);
|
|
148
|
+
totalInput += count(usage.input_tokens) + count(usage.cache_read_input_tokens) + count(usage.cache_creation_input_tokens);
|
|
149
|
+
}
|
|
150
|
+
if (last === null) {
|
|
151
|
+
return { reportVersion: 1, ok: false, budget, transcript, message: 'В журнале сессии пока нет ни одного ответа модели.' };
|
|
152
|
+
}
|
|
153
|
+
const contextTokens = count(last.input_tokens) + count(last.cache_read_input_tokens) + count(last.cache_creation_input_tokens) + count(last.output_tokens);
|
|
154
|
+
if (options.budget === undefined && largest > DEFAULT_BUDGET)
|
|
155
|
+
budget = LARGE_WINDOW;
|
|
156
|
+
const share = contextTokens / budget;
|
|
157
|
+
return {
|
|
158
|
+
reportVersion: 1,
|
|
159
|
+
ok: true,
|
|
160
|
+
transcript,
|
|
161
|
+
...(recordedSession === undefined ? {} : { sessionId: recordedSession }),
|
|
162
|
+
contextTokens,
|
|
163
|
+
budget,
|
|
164
|
+
percent: Math.round(share * 100),
|
|
165
|
+
level: levelFor(share),
|
|
166
|
+
totalInputTokens: totalInput,
|
|
167
|
+
requests: seen.size,
|
|
168
|
+
};
|
|
169
|
+
}
|
package/dist/core/doctor/git.js
CHANGED
|
@@ -2,7 +2,7 @@ import { execFile } from 'node:child_process';
|
|
|
2
2
|
import { existsSync } from 'node:fs';
|
|
3
3
|
import { join } from 'node:path';
|
|
4
4
|
import { promisify } from 'node:util';
|
|
5
|
-
import { critical, error, warning } from './types.js';
|
|
5
|
+
import { critical, error, info, warning } from './types.js';
|
|
6
6
|
const execFileAsync = promisify(execFile);
|
|
7
7
|
/** Parse porcelain v1 `-z`; rename/copy records consume two NUL fields. */
|
|
8
8
|
export function parsePorcelainV1Z(output) {
|
|
@@ -43,8 +43,48 @@ export async function checkGit(root, managedDocs, findings, managedFiles = new S
|
|
|
43
43
|
if (managedDocs.has(path))
|
|
44
44
|
findings.push(error('git-managed-dirty', 'Управляемый документ имеет незакоммиченные изменения. Если это результат upgrade — просмотрите diff и закоммитьте; если правка ручная — верните файл.', path));
|
|
45
45
|
}
|
|
46
|
+
await checkCloudCopy(root, findings);
|
|
46
47
|
}
|
|
47
48
|
catch (cause) {
|
|
48
49
|
findings.push(error('git-check-failed', `Не удалось проверить Git: ${cause instanceof Error ? cause.message : String(cause)}`, '.git'));
|
|
49
50
|
}
|
|
50
51
|
}
|
|
52
|
+
/** Команда git, чей отказ — ответ «нет», а не сбой проверки. */
|
|
53
|
+
async function gitAnswer(root, args) {
|
|
54
|
+
try {
|
|
55
|
+
return (await execFileAsync('git', [...args], { cwd: root, encoding: 'utf8' })).stdout.trim();
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Есть ли копия в облаке — только по локальным данным git, без сети: `git fetch` не
|
|
63
|
+
* запускается, поэтому «отправлено» значит «по данным последней синхронизации».
|
|
64
|
+
* Уровень `info`: не красит ни обычную проверку, ни `--strict`, ни `preflight` —
|
|
65
|
+
* проект может сознательно жить только на компьютере.
|
|
66
|
+
*/
|
|
67
|
+
async function checkCloudCopy(root, findings) {
|
|
68
|
+
const remotes = await gitAnswer(root, ['remote']);
|
|
69
|
+
if (remotes === null)
|
|
70
|
+
return;
|
|
71
|
+
if (remotes === '') {
|
|
72
|
+
findings.push(info('git-no-remote', 'Копии проекта в облаке нет: у репозитория нет remote. Если этот компьютер пропадёт, проект не восстановить. Завести закрытую копию поможет `/start`.'));
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
// Ветка без коммитов или detached HEAD: отправлять пока нечего или некуда.
|
|
76
|
+
const branch = await gitAnswer(root, ['symbolic-ref', '--quiet', '--short', 'HEAD']);
|
|
77
|
+
if (branch === null || branch === '' || await gitAnswer(root, ['rev-parse', '--verify', '--quiet', 'HEAD']) === null)
|
|
78
|
+
return;
|
|
79
|
+
const upstream = await gitAnswer(root, ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}']);
|
|
80
|
+
if (upstream === null || upstream === '') {
|
|
81
|
+
const names = remotes.split(/\r?\n/).filter(Boolean);
|
|
82
|
+
const remote = names.includes('origin') ? 'origin' : names[0] ?? 'origin';
|
|
83
|
+
findings.push(info('git-no-upstream', `Ветка ${branch} ещё не связана с копией в облаке (upstream), по данным последней синхронизации. Первая отправка: git push -u ${remote} ${branch}.`));
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
const ahead = Number(await gitAnswer(root, ['rev-list', '--count', '@{u}..HEAD']));
|
|
87
|
+
if (Number.isInteger(ahead) && ahead > 0) {
|
|
88
|
+
findings.push(info('git-unpushed', `Коммитов, не отправленных в облако (${upstream}): ${ahead} — по данным последней синхронизации, без запроса в сеть. Отправка: git push.`));
|
|
89
|
+
}
|
|
90
|
+
}
|
|
@@ -1,18 +1,12 @@
|
|
|
1
|
-
import { existsSync } from 'node:fs';
|
|
2
|
-
import { readdir } from 'node:fs/promises';
|
|
3
|
-
import { join } from 'node:path';
|
|
4
1
|
import { pathHasSymlink } from './fs-utils.js';
|
|
5
|
-
import { critical
|
|
2
|
+
import { critical } from './types.js';
|
|
3
|
+
/**
|
|
4
|
+
* `maestro/inbox/` — одно место для материалов человека: файлы там не замечание,
|
|
5
|
+
* даже в `--strict`. Проверяется только, что путь не уводит за пределы проекта.
|
|
6
|
+
*/
|
|
6
7
|
export async function checkInbox(root, findings) {
|
|
7
8
|
const inboxPath = 'maestro/inbox';
|
|
8
|
-
const dir = join(root, inboxPath);
|
|
9
9
|
if (await pathHasSymlink(root, inboxPath)) {
|
|
10
10
|
findings.push(critical('inbox-symlink', 'Inbox path не должен содержать symbolic link.', inboxPath));
|
|
11
|
-
return;
|
|
12
11
|
}
|
|
13
|
-
if (!existsSync(dir))
|
|
14
|
-
return;
|
|
15
|
-
const entries = (await readdir(dir)).filter((name) => name !== 'README.md' && name !== '.gitkeep');
|
|
16
|
-
if (entries.length > 0)
|
|
17
|
-
findings.push(warning('inbox-not-empty', 'Inbox содержит необработанные материалы.', 'maestro/inbox'));
|
|
18
12
|
}
|
|
@@ -43,7 +43,7 @@ export async function checkSources(root, findings) {
|
|
|
43
43
|
if (!existsSync(metadataAbsolute)) {
|
|
44
44
|
const actualPaths = await sourceFiles(root, join(root, SOURCES_DIR), findings);
|
|
45
45
|
if (actualPaths.length > 0)
|
|
46
|
-
findings.push(critical('source-hashes-missing', '
|
|
46
|
+
findings.push(critical('source-hashes-missing', 'В maestro/sources/ лежат файлы без снимка: эта папка — только для снимков команды `vibe-maestro sources --write`. Свои материалы кладите в maestro/inbox/ — там они не замечание.', metadataPath));
|
|
47
47
|
return;
|
|
48
48
|
}
|
|
49
49
|
try {
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
import { promisify } from 'node:util';
|
|
3
|
+
const execFileAsync = promisify(execFile);
|
|
4
|
+
/** Ответ на проверку входа не должен задерживать мастер дольше этого. */
|
|
5
|
+
export const GH_DETECT_TIMEOUT_MS = 3_000;
|
|
6
|
+
/** Создание репозитория и первая отправка идут по сети. */
|
|
7
|
+
export const GH_CREATE_TIMEOUT_MS = 120_000;
|
|
8
|
+
export const defaultGhRunner = (args, options) => new Promise((resolve) => {
|
|
9
|
+
const child = execFile('gh', [...args], {
|
|
10
|
+
cwd: options.cwd,
|
|
11
|
+
timeout: options.timeoutMs,
|
|
12
|
+
encoding: 'utf8',
|
|
13
|
+
windowsHide: true,
|
|
14
|
+
// gh не задаёт вопросов и не проверяет обновления: ответить ему некому.
|
|
15
|
+
// git внутри gh тоже не спрашивает логин в терминале: лучше быстрый понятный сбой, чем зависание.
|
|
16
|
+
env: { ...process.env, GH_PROMPT_DISABLED: '1', GH_NO_UPDATE_NOTIFIER: '1', NO_COLOR: '1', GIT_TERMINAL_PROMPT: '0' },
|
|
17
|
+
}, (error, stdout, stderr) => {
|
|
18
|
+
if (error === null) {
|
|
19
|
+
resolve({ code: 0, stdout, stderr });
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
const cause = error;
|
|
23
|
+
if (cause.code === 'ENOENT')
|
|
24
|
+
resolve({ code: null, stdout, stderr, failure: 'missing' });
|
|
25
|
+
else if (cause.killed === true)
|
|
26
|
+
resolve({ code: null, stdout, stderr, failure: 'timeout' });
|
|
27
|
+
else
|
|
28
|
+
resolve({ code: typeof cause.code === 'number' ? cause.code : 1, stdout, stderr });
|
|
29
|
+
});
|
|
30
|
+
child.stdin?.end();
|
|
31
|
+
});
|
|
32
|
+
/** Есть ли `gh` и выполнен ли в нём вход на github.com. Нет ответа за отведённое время — «нет». */
|
|
33
|
+
export async function githubReady(runner = defaultGhRunner, timeoutMs = GH_DETECT_TIMEOUT_MS) {
|
|
34
|
+
try {
|
|
35
|
+
const result = await runner(['auth', 'status', '--hostname', 'github.com'], { timeoutMs });
|
|
36
|
+
return result.code === 0;
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
const TRANSLIT = {
|
|
43
|
+
а: 'a', б: 'b', в: 'v', г: 'g', д: 'd', е: 'e', ё: 'e', ж: 'zh', з: 'z', и: 'i', й: 'y', к: 'k', л: 'l', м: 'm',
|
|
44
|
+
н: 'n', о: 'o', п: 'p', р: 'r', с: 's', т: 't', у: 'u', ф: 'f', х: 'kh', ц: 'ts', ч: 'ch', ш: 'sh', щ: 'shch',
|
|
45
|
+
ъ: '', ы: 'y', ь: '', э: 'e', ю: 'yu', я: 'ya', і: 'i', ї: 'yi', є: 'ye', ґ: 'g',
|
|
46
|
+
};
|
|
47
|
+
function transliterate(text) {
|
|
48
|
+
let out = '';
|
|
49
|
+
for (const char of text.normalize('NFC')) {
|
|
50
|
+
const lower = char.toLowerCase();
|
|
51
|
+
const latin = TRANSLIT[lower];
|
|
52
|
+
if (latin === undefined) {
|
|
53
|
+
out += char;
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
out += char !== lower && latin !== '' ? latin[0].toUpperCase() + latin.slice(1) : latin;
|
|
57
|
+
}
|
|
58
|
+
return out;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Имя репозитория — латиницей из названия папки: кириллица транслитерируется,
|
|
62
|
+
* остальное, кроме букв, цифр, `.`, `_` и `-`, становится дефисом. Пустое имя —
|
|
63
|
+
* `project-ГГГГММДД`.
|
|
64
|
+
*/
|
|
65
|
+
export function githubRepoName(folderName, now = new Date()) {
|
|
66
|
+
const name = transliterate(folderName)
|
|
67
|
+
.normalize('NFD').replace(/\p{Mark}/gu, '')
|
|
68
|
+
.replace(/[^A-Za-z0-9._-]+/g, '-')
|
|
69
|
+
.replace(/-{2,}/g, '-')
|
|
70
|
+
.replace(/^[-.]+|[-.]+$/g, '')
|
|
71
|
+
.slice(0, 100)
|
|
72
|
+
.replace(/[-.]+$/g, '');
|
|
73
|
+
return name === '' ? `project-${now.toISOString().slice(0, 10).replace(/-/g, '')}` : name;
|
|
74
|
+
}
|
|
75
|
+
/** Адрес копии для показа: логин и пароль (токен), вшитые в адрес, не печатаются никогда. */
|
|
76
|
+
export function displayRemoteUrl(url) {
|
|
77
|
+
return url.replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/@]*@/i, '$1');
|
|
78
|
+
}
|
|
79
|
+
/** Команда, которой человек заведёт копию сам, из папки проекта. */
|
|
80
|
+
export function githubCreateCommand(name) {
|
|
81
|
+
return `gh repo create ${name} --private --source . --remote origin --push`;
|
|
82
|
+
}
|
|
83
|
+
function firstLine(text) {
|
|
84
|
+
return text.split(/\r?\n/).map((line) => line.trim()).find((line) => line !== '') ?? '';
|
|
85
|
+
}
|
|
86
|
+
/** `gh repo create <имя> --private --source <папка> --remote origin --push` после первого коммита. */
|
|
87
|
+
export async function createGithubCopy(projectRoot, name, runner = defaultGhRunner, timeoutMs = GH_CREATE_TIMEOUT_MS) {
|
|
88
|
+
let result;
|
|
89
|
+
try {
|
|
90
|
+
result = await runner(['repo', 'create', name, '--private', '--source', projectRoot, '--remote', 'origin', '--push'], { cwd: projectRoot, timeoutMs });
|
|
91
|
+
}
|
|
92
|
+
catch (cause) {
|
|
93
|
+
return { ok: false, reason: cause instanceof Error ? cause.message : String(cause) };
|
|
94
|
+
}
|
|
95
|
+
if (result.failure === 'missing')
|
|
96
|
+
return { ok: false, reason: 'не найдена программа GitHub CLI (gh)' };
|
|
97
|
+
if (result.failure === 'timeout')
|
|
98
|
+
return { ok: false, reason: `gh не ответил за ${Math.round(timeoutMs / 1000)} с` };
|
|
99
|
+
if (result.code !== 0)
|
|
100
|
+
return { ok: false, reason: firstLine(result.stderr) || firstLine(result.stdout) || `gh завершился с кодом ${result.code}` };
|
|
101
|
+
const url = /https:\/\/github\.com\/[^\s'"]+/.exec(`${result.stdout}\n${result.stderr}`)?.[0];
|
|
102
|
+
if (url !== undefined)
|
|
103
|
+
return { ok: true, url };
|
|
104
|
+
// gh не напечатал адрес — берём тот, что он записал в remote.
|
|
105
|
+
const remote = await execFileAsync('git', ['remote', 'get-url', 'origin'], { cwd: projectRoot, encoding: 'utf8' }).catch(() => null);
|
|
106
|
+
return { ok: true, url: displayRemoteUrl(remote?.stdout.trim() || name) };
|
|
107
|
+
}
|
package/dist/core/init.js
CHANGED
|
@@ -13,14 +13,26 @@ import { renderTemplate } from './template.js';
|
|
|
13
13
|
import { recoverTemplateVars, templateUses } from './template-recover.js';
|
|
14
14
|
import { canonicalOwnershipInventory, CONTENT_OWNED_FILES, lazyDirsForDepth, TEMPLATE_FILES } from './inventory.js';
|
|
15
15
|
import { canonicalizeSystemTempPrefix, onDiskBasename } from './platform-paths.js';
|
|
16
|
+
import { hasAnyReadme, README_PATH } from './readme.js';
|
|
17
|
+
import { SETTINGS_PATH, withPushWithoutAsking } from './settings.js';
|
|
16
18
|
import { compareVersions } from './version.js';
|
|
17
19
|
const execFileAsync = promisify(execFile);
|
|
18
20
|
const GITIGNORE_PATH = '.gitignore';
|
|
19
21
|
/** Служебный мусор ОС и сам Git не делают папку «занятой чужими файлами». */
|
|
20
22
|
const IGNORED_WHEN_EMPTY_CHECK = ['.git', '.DS_Store'];
|
|
21
23
|
/** Шаблон .gitattributes: фиксирует LF для текстовых файлов проекта. */
|
|
22
|
-
const GITATTRIBUTES_PATH = '.gitattributes';
|
|
23
24
|
export const GITATTRIBUTES_CONTENT = '* text=auto eol=lf\n*.md text eol=lf\n*.json text eol=lf\n*.yml text eol=lf\n*.yaml text eol=lf\n';
|
|
25
|
+
/**
|
|
26
|
+
* Материалы человека git хранит байт в байт: `-text` во вложенном `.gitattributes`
|
|
27
|
+
* перекрывает корневые правила, и свежий клон отдаёт исходные переносы строк.
|
|
28
|
+
* Отдельный файл, а не строка в корневом: корневой проект мог дописать, и тогда upgrade встал бы.
|
|
29
|
+
*/
|
|
30
|
+
export const INBOX_GITATTRIBUTES_CONTENT = '* -text\n';
|
|
31
|
+
/** Managed-файлы, содержимое которых задаёт код, а не шаблон: без подстановок, побайтово. */
|
|
32
|
+
export const CODE_MANAGED_SOURCES = {
|
|
33
|
+
'.gitattributes': GITATTRIBUTES_CONTENT,
|
|
34
|
+
'maestro/inbox/.gitattributes': INBOX_GITATTRIBUTES_CONTENT,
|
|
35
|
+
};
|
|
24
36
|
function failure(target, projectName, error) {
|
|
25
37
|
return {
|
|
26
38
|
ok: false,
|
|
@@ -114,7 +126,7 @@ async function findAncestorSymlink(target) {
|
|
|
114
126
|
async function recoverProjectVars(target, startingPoint, checksums) {
|
|
115
127
|
const found = {};
|
|
116
128
|
for (const relativePath of TEMPLATE_FILES) {
|
|
117
|
-
if (relativePath
|
|
129
|
+
if (relativePath in CODE_MANAGED_SOURCES || checksums[relativePath] === undefined)
|
|
118
130
|
continue;
|
|
119
131
|
// Шаблоны пакета на Windows могут прийти с CRLF, а файлы проекта всегда пишутся с LF.
|
|
120
132
|
const source = normalizeEol(await readTemplate(relativePath));
|
|
@@ -170,7 +182,7 @@ async function initGitRepository(target, ownedPaths, warnings, writtenPaths) {
|
|
|
170
182
|
const shown = writtenPaths.slice(0, 5).map((path) => quotePathArg(path)).join(' ');
|
|
171
183
|
warnings.push(`Репозиторий Git уже существовал: index не изменён и commit не создан. Добавьте записанные файлы сами: git add ${shown}${writtenPaths.length > 5 ? ' …' : ''}`);
|
|
172
184
|
}
|
|
173
|
-
return;
|
|
185
|
+
return false;
|
|
174
186
|
}
|
|
175
187
|
// Только наши пути в новом репозитории. Пакетами, чтобы не упереться в лимит длины командной строки.
|
|
176
188
|
const toAdd = [...ownedPaths].sort();
|
|
@@ -180,10 +192,12 @@ async function initGitRepository(target, ownedPaths, warnings, writtenPaths) {
|
|
|
180
192
|
await execFileAsync('git', ['commit', '-m', 'Инициализация проекта Vibe Coding Maestro'], {
|
|
181
193
|
cwd: target,
|
|
182
194
|
});
|
|
195
|
+
return true;
|
|
183
196
|
}
|
|
184
197
|
catch (error) {
|
|
185
198
|
const message = error instanceof Error ? error.message : String(error);
|
|
186
199
|
warnings.push(`Git-шаги пропущены: ${message}`);
|
|
200
|
+
return false;
|
|
187
201
|
}
|
|
188
202
|
}
|
|
189
203
|
/**
|
|
@@ -297,6 +311,9 @@ async function initProjectAt(target, options, progress) {
|
|
|
297
311
|
if (isExistingProject && options.requested?.startingPoint !== undefined && options.requested.startingPoint !== startingPoint) {
|
|
298
312
|
warnings.push(`У проекта исходная точка ${startingPoint}; --start ${options.requested.startingPoint} не применён: create не меняет параметры готового проекта.`);
|
|
299
313
|
}
|
|
314
|
+
if (isExistingProject && options.pushWithoutAsking === true) {
|
|
315
|
+
warnings.push('--push-without-asking не применён: create не меняет готовый проект, а `.claude/settings.json` принадлежит проекту. Настройку предложит `/start` — только с вашего «да».');
|
|
316
|
+
}
|
|
300
317
|
const previousChecksums = (await loadChecksums(target))?.files ?? {};
|
|
301
318
|
const nextChecksums = {};
|
|
302
319
|
const managed = [];
|
|
@@ -369,15 +386,16 @@ async function initProjectAt(target, options, progress) {
|
|
|
369
386
|
ownedPaths.push(relativePath);
|
|
370
387
|
}
|
|
371
388
|
for (const relativePath of TEMPLATE_FILES) {
|
|
372
|
-
const
|
|
373
|
-
await materialize(relativePath,
|
|
389
|
+
const constant = CODE_MANAGED_SOURCES[relativePath];
|
|
390
|
+
await materialize(relativePath, constant ?? renderTemplate(await readTemplate(relativePath), vars));
|
|
374
391
|
}
|
|
375
392
|
for (const relativePath of CONTENT_OWNED_FILES) {
|
|
376
393
|
managed.push({ path: relativePath, kind: 'generated' });
|
|
377
394
|
const absolutePath = join(target, relativePath);
|
|
378
395
|
if (!existsSync(absolutePath)) {
|
|
379
|
-
const
|
|
380
|
-
|
|
396
|
+
const rendered = renderTemplate(await readTemplate(relativePath), vars);
|
|
397
|
+
const pushRecipe = relativePath === SETTINGS_PATH && options.pushWithoutAsking === true && !isExistingProject;
|
|
398
|
+
await writeTextFile(absolutePath, pushRecipe ? withPushWithoutAsking(rendered) : rendered);
|
|
381
399
|
createdFiles.push(relativePath);
|
|
382
400
|
ownedPaths.push(relativePath);
|
|
383
401
|
}
|
|
@@ -385,6 +403,13 @@ async function initProjectAt(target, options, progress) {
|
|
|
385
403
|
preservedFiles.push(relativePath);
|
|
386
404
|
}
|
|
387
405
|
}
|
|
406
|
+
// README — только в новый проект и только если в корне нет никакого README: удалённый
|
|
407
|
+
// человеком README повторный create не возвращает, а doctor его не требует.
|
|
408
|
+
if (!isExistingProject && !(await hasAnyReadme(target))) {
|
|
409
|
+
await writeTextFile(join(target, README_PATH), renderTemplate(await readTemplate(README_PATH), vars));
|
|
410
|
+
createdFiles.push(README_PATH);
|
|
411
|
+
ownedPaths.push(README_PATH);
|
|
412
|
+
}
|
|
388
413
|
for (const dir of lazyDirs) {
|
|
389
414
|
await mkdir(join(target, dir), { recursive: true });
|
|
390
415
|
await materialize(`${dir}/.gitkeep`, '');
|
|
@@ -425,9 +450,9 @@ async function initProjectAt(target, options, progress) {
|
|
|
425
450
|
});
|
|
426
451
|
await writeManifest(target, manifest);
|
|
427
452
|
await writeChecksums(target, nextChecksums);
|
|
428
|
-
|
|
429
|
-
await initGitRepository(target, ownedPaths, warnings, [...createdFiles, ...mergedFiles])
|
|
430
|
-
|
|
453
|
+
const gitCreated = options.git === true
|
|
454
|
+
? await initGitRepository(target, ownedPaths, warnings, [...createdFiles, ...mergedFiles])
|
|
455
|
+
: false;
|
|
431
456
|
// Метка снимается последней: убитый на любом шаге, включая Git, create остаётся виден.
|
|
432
457
|
if (!isExistingProject)
|
|
433
458
|
await rm(join(target, CREATING_MARKER_PATH), { force: true });
|
|
@@ -439,5 +464,7 @@ async function initProjectAt(target, options, progress) {
|
|
|
439
464
|
preservedFiles,
|
|
440
465
|
mergedFiles,
|
|
441
466
|
warnings,
|
|
467
|
+
existingProject: isExistingProject,
|
|
468
|
+
gitCreated,
|
|
442
469
|
};
|
|
443
470
|
}
|