octopi-agent 0.55.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.
- package/LICENSE +201 -0
- package/NOTICE +7 -0
- package/README.md +244 -0
- package/README_CN.md +241 -0
- package/dist/cli/args.d.ts +20 -0
- package/dist/cli/args.js +90 -0
- package/dist/cli/commands.d.ts +10 -0
- package/dist/cli/commands.js +253 -0
- package/dist/cli/daemon.d.ts +40 -0
- package/dist/cli/daemon.js +549 -0
- package/dist/cli/doctor/data.d.ts +64 -0
- package/dist/cli/doctor/data.js +209 -0
- package/dist/cli/doctor/index.d.ts +131 -0
- package/dist/cli/doctor/index.js +711 -0
- package/dist/cli/doctor/redact.d.ts +21 -0
- package/dist/cli/doctor/redact.js +48 -0
- package/dist/cli/doctor/restore.d.ts +36 -0
- package/dist/cli/doctor/restore.js +93 -0
- package/dist/cli/helpers.d.ts +38 -0
- package/dist/cli/helpers.js +158 -0
- package/dist/cli/index.d.ts +5 -0
- package/dist/cli/index.js +62 -0
- package/dist/cli/process-utils.d.ts +55 -0
- package/dist/cli/process-utils.js +306 -0
- package/dist/cli/serve-webui.d.ts +1 -0
- package/dist/cli/serve-webui.js +82 -0
- package/dist/cli/webui.d.ts +13 -0
- package/dist/cli/webui.js +249 -0
- package/dist/config-migrations.d.ts +198 -0
- package/dist/config-migrations.js +692 -0
- package/dist/config-schema/index.d.ts +1400 -0
- package/dist/config-schema/index.js +100 -0
- package/dist/config-schema/webui.d.ts +15 -0
- package/dist/config-schema/webui.js +15 -0
- package/dist/config-schema.d.ts +9 -0
- package/dist/config-schema.js +9 -0
- package/dist/config.d.ts +18 -0
- package/dist/config.js +136 -0
- package/dist/index.d.ts +24 -0
- package/dist/index.js +35 -0
- package/dist/init.d.ts +86 -0
- package/dist/init.js +386 -0
- package/dist/integration/index.d.ts +8 -0
- package/dist/integration/index.js +8 -0
- package/dist/integration/tui/app.d.ts +50 -0
- package/dist/integration/tui/app.js +584 -0
- package/dist/integration/tui/components.d.ts +82 -0
- package/dist/integration/tui/components.js +291 -0
- package/dist/integration/tui/index.d.ts +8 -0
- package/dist/integration/tui/index.js +8 -0
- package/dist/integration/tui/theme.d.ts +77 -0
- package/dist/integration/tui/theme.js +90 -0
- package/dist/testing/chaos-provider.d.ts +109 -0
- package/dist/testing/chaos-provider.js +211 -0
- package/dist/testing/index.d.ts +15 -0
- package/dist/testing/index.js +10 -0
- package/dist/testing/recording-provider.d.ts +75 -0
- package/dist/testing/recording-provider.js +172 -0
- package/dist/testing/replay-provider.d.ts +52 -0
- package/dist/testing/replay-provider.js +138 -0
- package/dist/testing/scenario-composer.d.ts +86 -0
- package/dist/testing/scenario-composer.js +200 -0
- package/dist/testing/scenario-runner.d.ts +134 -0
- package/dist/testing/scenario-runner.js +240 -0
- package/octopi.example.json +220 -0
- package/octopi.schema.json +2206 -0
- package/package.json +97 -0
|
@@ -0,0 +1,711 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* doctor 检测与修复(本地确定性,零 LLM)
|
|
3
|
+
*
|
|
4
|
+
* @module
|
|
5
|
+
*/
|
|
6
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync, readdirSync, statSync, } from 'node:fs';
|
|
7
|
+
import { createInterface } from 'node:readline/promises';
|
|
8
|
+
import { dirname, join, resolve } from 'node:path';
|
|
9
|
+
import { getOctopiHome } from '@octopi-agent/engine/paths.js';
|
|
10
|
+
import { validateConfig } from '../../config-schema.js';
|
|
11
|
+
import { applyConfigMigrations, detectConfigMigrations, expandEnvPlaceholders, parseConfigJson, } from '../../config-migrations.js';
|
|
12
|
+
import { applyDataLayerFixes, checkDeprecatedSessionStore, detectDataLayer, resolveAgentDataTargets, } from './data.js';
|
|
13
|
+
import { latestConfigBackup, listConfigBackups, restoreConfigFromBackup, } from './restore.js';
|
|
14
|
+
import { redactConfig, looksLikeSecret, redactSecretString } from './redact.js';
|
|
15
|
+
// ── 路径解析 ──
|
|
16
|
+
/**
|
|
17
|
+
* 解析 doctor 检查的配置路径(显式 -c 最优先)
|
|
18
|
+
*
|
|
19
|
+
* @param args - CLI 参数
|
|
20
|
+
* @returns home 与 config 路径信息
|
|
21
|
+
*/
|
|
22
|
+
export function resolveDoctorPaths(args) {
|
|
23
|
+
const home = getOctopiHome();
|
|
24
|
+
const homeConfig = join(home, 'octopi.json');
|
|
25
|
+
const cwdConfig = resolve(process.cwd(), 'octopi.json');
|
|
26
|
+
if (args.config) {
|
|
27
|
+
const configPath = resolve(args.config);
|
|
28
|
+
return { home, configPath, cwdConfig, homeConfig };
|
|
29
|
+
}
|
|
30
|
+
if (existsSync(homeConfig)) {
|
|
31
|
+
return { home, configPath: homeConfig, cwdConfig, homeConfig };
|
|
32
|
+
}
|
|
33
|
+
if (existsSync(cwdConfig)) {
|
|
34
|
+
return { home, configPath: cwdConfig, cwdConfig, homeConfig };
|
|
35
|
+
}
|
|
36
|
+
return { home, configPath: null, cwdConfig, homeConfig };
|
|
37
|
+
}
|
|
38
|
+
function migrationToFinding(m) {
|
|
39
|
+
return {
|
|
40
|
+
id: m.id,
|
|
41
|
+
domain: 'config',
|
|
42
|
+
severity: m.severity,
|
|
43
|
+
message: m.message,
|
|
44
|
+
hint: m.hint,
|
|
45
|
+
fixable: m.autoFixable,
|
|
46
|
+
group: m.autoFixable ? 'config' : undefined,
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* 将 fixable findings 按分组聚合
|
|
51
|
+
*
|
|
52
|
+
* @param findings - 诊断结果
|
|
53
|
+
* @returns 可修复分组
|
|
54
|
+
*/
|
|
55
|
+
export function groupFixableFindings(findings) {
|
|
56
|
+
const map = new Map();
|
|
57
|
+
for (const f of findings) {
|
|
58
|
+
if (!f.fixable || !f.group)
|
|
59
|
+
continue;
|
|
60
|
+
let entry = map.get(f.group);
|
|
61
|
+
if (!entry) {
|
|
62
|
+
entry = { group: f.group, items: [] };
|
|
63
|
+
map.set(f.group, entry);
|
|
64
|
+
}
|
|
65
|
+
entry.items.push({ id: f.id, message: f.message });
|
|
66
|
+
}
|
|
67
|
+
return [...map.values()];
|
|
68
|
+
}
|
|
69
|
+
// ── 布局检测 ──
|
|
70
|
+
const LEGACY_PERSONA_MOVES = [
|
|
71
|
+
{ from: 'SOUL.md', to: 'persona/10-soul.md' },
|
|
72
|
+
{ from: 'IDENTITY.md', to: 'persona/20-identity.md' },
|
|
73
|
+
{ from: 'USER.md', to: 'persona/30-user.md' },
|
|
74
|
+
{ from: 'TOOLS.md', to: 'persona/40-tools.md' },
|
|
75
|
+
];
|
|
76
|
+
const LEGACY_AGENT_DIRS = ['memory', 'wisdom', 'extract'];
|
|
77
|
+
function checkLayout(home, configPath, raw, allowDeleteLegacyDirs, explicitConfig) {
|
|
78
|
+
const findings = [];
|
|
79
|
+
if (!existsSync(join(home, 'octopi.json')) && !configPath) {
|
|
80
|
+
findings.push({
|
|
81
|
+
id: 'FS001',
|
|
82
|
+
domain: 'layout',
|
|
83
|
+
severity: 'error',
|
|
84
|
+
message: `Octopi home not initialized: ${home}`,
|
|
85
|
+
hint: 'run octopi init (layout fix does not create octopi.json)',
|
|
86
|
+
fixable: false,
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
if (configPath && !explicitConfig) {
|
|
90
|
+
const cwdConfig = resolve(process.cwd(), 'octopi.json');
|
|
91
|
+
const homeConfig = join(home, 'octopi.json');
|
|
92
|
+
if (resolve(configPath) === resolve(homeConfig) &&
|
|
93
|
+
existsSync(cwdConfig) &&
|
|
94
|
+
resolve(cwdConfig) !== resolve(homeConfig)) {
|
|
95
|
+
findings.push({
|
|
96
|
+
id: 'CFG009',
|
|
97
|
+
domain: 'config',
|
|
98
|
+
severity: 'error',
|
|
99
|
+
message: `cwd octopi.json may shadow OCTOPI_HOME config: ${cwdConfig}`,
|
|
100
|
+
hint: 'prefer -c or OCTOPI_HOME; avoid stray workspace configs',
|
|
101
|
+
fixable: false,
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
const agents = raw && Array.isArray(raw.agents) ? raw.agents : [];
|
|
106
|
+
for (const agent of agents) {
|
|
107
|
+
if (typeof agent !== 'object' || agent === null)
|
|
108
|
+
continue;
|
|
109
|
+
const a = agent;
|
|
110
|
+
const id = typeof a.id === 'string' ? a.id : 'unknown';
|
|
111
|
+
const agentHome = typeof a.home === 'string' && a.home
|
|
112
|
+
? a.home
|
|
113
|
+
: typeof a.persona === 'string'
|
|
114
|
+
? a.persona
|
|
115
|
+
: join(home, 'agents', id);
|
|
116
|
+
for (const sub of ['skills']) {
|
|
117
|
+
const dir = join(agentHome, sub);
|
|
118
|
+
if (!existsSync(dir)) {
|
|
119
|
+
findings.push({
|
|
120
|
+
id: 'FS002',
|
|
121
|
+
domain: 'layout',
|
|
122
|
+
severity: 'warn',
|
|
123
|
+
message: `agent "${id}" missing ${sub}/ under ${agentHome}`,
|
|
124
|
+
fixable: true,
|
|
125
|
+
group: 'layout',
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
for (const { from, to } of LEGACY_PERSONA_MOVES) {
|
|
130
|
+
const fromPath = join(agentHome, from);
|
|
131
|
+
const toPath = join(agentHome, to);
|
|
132
|
+
if (existsSync(fromPath) && !existsSync(toPath)) {
|
|
133
|
+
findings.push({
|
|
134
|
+
id: 'FS003',
|
|
135
|
+
domain: 'layout',
|
|
136
|
+
severity: 'warn',
|
|
137
|
+
message: `agent "${id}": legacy persona file ${from}`,
|
|
138
|
+
hint: `move to ${to}`,
|
|
139
|
+
fixable: true,
|
|
140
|
+
group: 'layout',
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
for (const legacy of LEGACY_AGENT_DIRS) {
|
|
145
|
+
const dir = join(agentHome, legacy);
|
|
146
|
+
if (existsSync(dir)) {
|
|
147
|
+
findings.push({
|
|
148
|
+
id: 'FS004',
|
|
149
|
+
domain: 'layout',
|
|
150
|
+
severity: 'info',
|
|
151
|
+
message: `agent "${id}": obsolete directory ${legacy}/ (memory lives in agent.db)`,
|
|
152
|
+
hint: allowDeleteLegacyDirs
|
|
153
|
+
? 'will rename to *.deprecated with --fix layout'
|
|
154
|
+
: 'safe to archive manually; not auto-deleted without --allow-delete-legacy-dirs',
|
|
155
|
+
fixable: allowDeleteLegacyDirs,
|
|
156
|
+
group: allowDeleteLegacyDirs ? 'layout' : undefined,
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
if (raw && typeof raw.plugins === 'object' && raw.plugins !== null) {
|
|
162
|
+
const plugins = raw.plugins;
|
|
163
|
+
const loadPaths = Array.isArray(plugins.loadPaths) ? plugins.loadPaths : [];
|
|
164
|
+
for (const p of loadPaths) {
|
|
165
|
+
if (typeof p !== 'string')
|
|
166
|
+
continue;
|
|
167
|
+
if (!existsSync(p)) {
|
|
168
|
+
findings.push({
|
|
169
|
+
id: 'FS005',
|
|
170
|
+
domain: 'layout',
|
|
171
|
+
severity: 'warn',
|
|
172
|
+
message: `plugins.loadPaths entry missing: ${p}`,
|
|
173
|
+
hint: 'create the directory or correct plugins.loadPaths in config (layout fix does not invent plugin roots)',
|
|
174
|
+
fixable: false,
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
return findings;
|
|
180
|
+
}
|
|
181
|
+
// ── Zod / 语义 ──
|
|
182
|
+
function checkZod(raw) {
|
|
183
|
+
const result = validateConfig(raw);
|
|
184
|
+
if (result.success) {
|
|
185
|
+
return [
|
|
186
|
+
{
|
|
187
|
+
id: 'ZOD000',
|
|
188
|
+
domain: 'config',
|
|
189
|
+
severity: 'ok',
|
|
190
|
+
message: 'HarnessConfigSchema validation passed',
|
|
191
|
+
fixable: false,
|
|
192
|
+
},
|
|
193
|
+
];
|
|
194
|
+
}
|
|
195
|
+
return (result.errors ?? []).map((e) => ({
|
|
196
|
+
id: 'ZOD001',
|
|
197
|
+
domain: 'config',
|
|
198
|
+
severity: 'error',
|
|
199
|
+
message: `${e.path || '(root)'}: ${e.message}`,
|
|
200
|
+
fixable: false,
|
|
201
|
+
}));
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* 复检 apiKey 语义(展开后);只报告 ok/missing
|
|
205
|
+
*
|
|
206
|
+
* @param rawExpanded - env 展开后的配置
|
|
207
|
+
* @returns findings
|
|
208
|
+
*/
|
|
209
|
+
export function checkApiKeySemantics(rawExpanded) {
|
|
210
|
+
const findings = [];
|
|
211
|
+
if (typeof rawExpanded !== 'object' || rawExpanded === null)
|
|
212
|
+
return findings;
|
|
213
|
+
const models = rawExpanded.models;
|
|
214
|
+
const providers = typeof models === 'object' && models !== null
|
|
215
|
+
? models.providers
|
|
216
|
+
: undefined;
|
|
217
|
+
if (!providers || typeof providers !== 'object')
|
|
218
|
+
return findings;
|
|
219
|
+
for (const [name, cfg] of Object.entries(providers)) {
|
|
220
|
+
if (typeof cfg !== 'object' || cfg === null)
|
|
221
|
+
continue;
|
|
222
|
+
const apiKey = cfg.apiKey;
|
|
223
|
+
const api = cfg.api;
|
|
224
|
+
if (typeof apiKey === 'string' && apiKey.length > 0) {
|
|
225
|
+
findings.push({
|
|
226
|
+
id: 'CFG008',
|
|
227
|
+
domain: 'config',
|
|
228
|
+
severity: 'ok',
|
|
229
|
+
message: `models.providers.${name}.apiKey: present (redacted)`,
|
|
230
|
+
fixable: false,
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
else if (api === undefined || String(api).includes('openai') || String(api).includes('anthropic')) {
|
|
234
|
+
findings.push({
|
|
235
|
+
id: 'CFG008',
|
|
236
|
+
domain: 'config',
|
|
237
|
+
severity: 'warn',
|
|
238
|
+
message: `models.providers.${name}.apiKey: missing after env expansion`,
|
|
239
|
+
hint: 'set env var or keep "${VAR}" placeholder in config',
|
|
240
|
+
fixable: false,
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
return findings;
|
|
245
|
+
}
|
|
246
|
+
function domainAllowed(id, domain, only) {
|
|
247
|
+
if (!only || only.length === 0)
|
|
248
|
+
return true;
|
|
249
|
+
return only.includes(domain) || only.includes(id);
|
|
250
|
+
}
|
|
251
|
+
function diagnoseConfigLayoutData(home, configPath, allowDeleteLegacyDirs, explicitConfig) {
|
|
252
|
+
const findings = [];
|
|
253
|
+
let rawUnexpanded = null;
|
|
254
|
+
let parseRecovered = false;
|
|
255
|
+
if (!configPath) {
|
|
256
|
+
findings.push({
|
|
257
|
+
id: 'CFG000',
|
|
258
|
+
domain: 'config',
|
|
259
|
+
severity: 'error',
|
|
260
|
+
message: 'octopi.json not found',
|
|
261
|
+
hint: 'run octopi init or pass -c <path>',
|
|
262
|
+
fixable: false,
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
else {
|
|
266
|
+
const text = readFileSync(configPath, 'utf-8');
|
|
267
|
+
const attempt = parseConfigJson(text);
|
|
268
|
+
if (!attempt.ok) {
|
|
269
|
+
findings.push({
|
|
270
|
+
id: 'R001',
|
|
271
|
+
domain: 'config',
|
|
272
|
+
severity: 'error',
|
|
273
|
+
message: `config JSON parse failed: ${attempt.error ?? 'unknown'}`,
|
|
274
|
+
hint: 'fix syntax manually or restore a backup; doctor will not guess content',
|
|
275
|
+
fixable: false,
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
else if (attempt.recovered) {
|
|
279
|
+
parseRecovered = true;
|
|
280
|
+
findings.push({
|
|
281
|
+
id: 'R001',
|
|
282
|
+
domain: 'config',
|
|
283
|
+
severity: 'warn',
|
|
284
|
+
message: 'config JSON recovered (comments/trailing commas)',
|
|
285
|
+
hint: 'will write normalized JSON when applying --fix config',
|
|
286
|
+
fixable: true,
|
|
287
|
+
group: 'config',
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
if (attempt.ok && typeof attempt.raw === 'object' && attempt.raw !== null) {
|
|
291
|
+
rawUnexpanded = attempt.raw;
|
|
292
|
+
for (const m of detectConfigMigrations(rawUnexpanded)) {
|
|
293
|
+
// CFG010 在下方用带路径对照的增强版覆盖,避免重复
|
|
294
|
+
if (m.id === 'CFG010')
|
|
295
|
+
continue;
|
|
296
|
+
findings.push(migrationToFinding(m));
|
|
297
|
+
}
|
|
298
|
+
findings.push(...checkZod(rawUnexpanded));
|
|
299
|
+
try {
|
|
300
|
+
// 展开后的文本仅用于复检 apiKey 是否可解析;env 值可能破坏 JSON 结构
|
|
301
|
+
findings.push(...checkApiKeySemantics(JSON.parse(expandEnvPlaceholders(text))));
|
|
302
|
+
}
|
|
303
|
+
catch {
|
|
304
|
+
// 展开 parse 失败(例如 env 含未转义引号):退回未展开形状做存在性检查,绝不写回展开文本
|
|
305
|
+
findings.push(...checkApiKeySemantics(rawUnexpanded));
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
findings.push(...checkLayout(home, configPath, rawUnexpanded, allowDeleteLegacyDirs, explicitConfig));
|
|
310
|
+
const targets = resolveAgentDataTargets(home, rawUnexpanded);
|
|
311
|
+
findings.push(...detectDataLayer(targets));
|
|
312
|
+
if (configPath) {
|
|
313
|
+
findings.push(...checkDeprecatedSessionStore(rawUnexpanded, targets, dirname(resolve(configPath))));
|
|
314
|
+
}
|
|
315
|
+
return { findings, raw: rawUnexpanded, parseRecovered, targets };
|
|
316
|
+
}
|
|
317
|
+
/**
|
|
318
|
+
* 默认交互式选择器(TTY)
|
|
319
|
+
*
|
|
320
|
+
* @param candidates - 可修复分组
|
|
321
|
+
* @returns 用户选择的分组;取消为空数组
|
|
322
|
+
*/
|
|
323
|
+
export async function defaultSelectFixGroups(candidates) {
|
|
324
|
+
if (candidates.length === 0)
|
|
325
|
+
return [];
|
|
326
|
+
console.log('\nFixable groups:');
|
|
327
|
+
candidates.forEach((c, i) => {
|
|
328
|
+
console.log(` [${i + 1}] ${c.group} — ${c.items.map((it) => it.id).join(', ')}`);
|
|
329
|
+
for (const it of c.items)
|
|
330
|
+
console.log(` - ${it.message}`);
|
|
331
|
+
});
|
|
332
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
333
|
+
try {
|
|
334
|
+
const answer = (await rl.question('Apply which groups? [a=all / 1,2 / q=cancel]: ')).trim().toLowerCase();
|
|
335
|
+
if (!answer || answer === 'q' || answer === 'n')
|
|
336
|
+
return [];
|
|
337
|
+
if (answer === 'a' || answer === 'all' || answer === 'y' || answer === 'yes') {
|
|
338
|
+
return candidates.map((c) => c.group);
|
|
339
|
+
}
|
|
340
|
+
const picked = new Set();
|
|
341
|
+
for (const part of answer.split(/[\s,]+/)) {
|
|
342
|
+
const idx = Number(part) - 1;
|
|
343
|
+
if (Number.isInteger(idx) && candidates[idx])
|
|
344
|
+
picked.add(candidates[idx].group);
|
|
345
|
+
}
|
|
346
|
+
return [...picked];
|
|
347
|
+
}
|
|
348
|
+
finally {
|
|
349
|
+
rl.close();
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
/**
|
|
353
|
+
* 执行 doctor 检测(及可选修复)
|
|
354
|
+
*
|
|
355
|
+
* @param args - CLI 参数
|
|
356
|
+
* @param options - doctor 选项
|
|
357
|
+
* @returns 报告
|
|
358
|
+
*/
|
|
359
|
+
export async function runDoctor(args, options = {}) {
|
|
360
|
+
const paths = resolveDoctorPaths(args);
|
|
361
|
+
const explicitConfig = Boolean(args.config);
|
|
362
|
+
const fixFindings = [];
|
|
363
|
+
let diagnosis = diagnoseConfigLayoutData(paths.home, paths.configPath, Boolean(options.allowDeleteLegacyDirs), explicitConfig);
|
|
364
|
+
const backups = paths.configPath && existsSync(paths.configPath) ? listConfigBackups(paths.configPath) : [];
|
|
365
|
+
if (options.fix && !options.dryRun) {
|
|
366
|
+
const candidates = groupFixableFindings(diagnosis.findings);
|
|
367
|
+
const shadowing = diagnosis.findings.some((f) => f.id === 'CFG009');
|
|
368
|
+
let selected = options.selectedGroups ?? null;
|
|
369
|
+
let refuseReason = null;
|
|
370
|
+
if (selected === null) {
|
|
371
|
+
if (options.selectFixGroups) {
|
|
372
|
+
selected = await options.selectFixGroups(candidates);
|
|
373
|
+
if (selected.length === 0) {
|
|
374
|
+
fixFindings.push({
|
|
375
|
+
id: 'FIX000',
|
|
376
|
+
domain: 'config',
|
|
377
|
+
severity: 'info',
|
|
378
|
+
message: 'interactive fix cancelled; no changes written',
|
|
379
|
+
fixable: false,
|
|
380
|
+
});
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
else if (shadowing && !args.config) {
|
|
384
|
+
refuseReason =
|
|
385
|
+
'CFG009: cwd octopi.json may shadow OCTOPI_HOME config; pass -c <path> to choose which file to fix';
|
|
386
|
+
selected = [];
|
|
387
|
+
}
|
|
388
|
+
else if (options.yes) {
|
|
389
|
+
selected = candidates.map((c) => c.group);
|
|
390
|
+
}
|
|
391
|
+
else if (options.interactive === true || (options.interactive !== false && Boolean(process.stdin.isTTY) && candidates.length > 0)) {
|
|
392
|
+
selected = await defaultSelectFixGroups(candidates);
|
|
393
|
+
if (selected.length === 0) {
|
|
394
|
+
fixFindings.push({
|
|
395
|
+
id: 'FIX000',
|
|
396
|
+
domain: 'config',
|
|
397
|
+
severity: 'info',
|
|
398
|
+
message: 'interactive fix cancelled; no changes written',
|
|
399
|
+
fixable: false,
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
else {
|
|
404
|
+
// 非 TTY 且未显式 --yes:拒绝静默写盘(与 help 中 --yes 契约一致)
|
|
405
|
+
refuseReason =
|
|
406
|
+
'refusing non-interactive --fix without --yes (pass --fix --yes, or run in a TTY for group selection)';
|
|
407
|
+
selected = [];
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
else if (shadowing && !args.config) {
|
|
411
|
+
refuseReason =
|
|
412
|
+
'CFG009: cwd octopi.json may shadow OCTOPI_HOME config; pass -c <path> to choose which file to fix';
|
|
413
|
+
selected = [];
|
|
414
|
+
}
|
|
415
|
+
if (refuseReason) {
|
|
416
|
+
fixFindings.push({
|
|
417
|
+
id: 'FIX000',
|
|
418
|
+
domain: 'config',
|
|
419
|
+
severity: 'warn',
|
|
420
|
+
message: refuseReason,
|
|
421
|
+
hint: 'no changes written',
|
|
422
|
+
fixable: false,
|
|
423
|
+
});
|
|
424
|
+
}
|
|
425
|
+
const applySet = new Set(selected ?? []);
|
|
426
|
+
const applyConfig = applySet.has('config');
|
|
427
|
+
const applyLayout = applySet.has('layout');
|
|
428
|
+
const applyData = applySet.has('data');
|
|
429
|
+
if (applyConfig && paths.configPath && diagnosis.raw) {
|
|
430
|
+
const applied = applyConfigMigrations(diagnosis.raw);
|
|
431
|
+
if (applied.changed || diagnosis.parseRecovered) {
|
|
432
|
+
const backupPath = `${paths.configPath}.bak.${new Date().toISOString().replace(/[:.]/g, '-')}`;
|
|
433
|
+
writeFileSync(backupPath, readFileSync(paths.configPath, 'utf-8'), 'utf-8');
|
|
434
|
+
writeFileSync(paths.configPath, JSON.stringify(diagnosis.raw, null, 2) + '\n', 'utf-8');
|
|
435
|
+
fixFindings.push({
|
|
436
|
+
id: 'FIX000',
|
|
437
|
+
domain: 'config',
|
|
438
|
+
severity: 'ok',
|
|
439
|
+
message: `config migrations written; backup at ${backupPath}`,
|
|
440
|
+
hint: applied.notes.join('; ') || undefined,
|
|
441
|
+
fixable: false,
|
|
442
|
+
});
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
if (applyLayout) {
|
|
446
|
+
const layoutFixed = applyLayoutFixes(paths.home, diagnosis.raw, options);
|
|
447
|
+
if (layoutFixed.length > 0) {
|
|
448
|
+
fixFindings.push({
|
|
449
|
+
id: 'FIX001',
|
|
450
|
+
domain: 'layout',
|
|
451
|
+
severity: 'ok',
|
|
452
|
+
message: `layout fixes: ${layoutFixed.join('; ')}`,
|
|
453
|
+
fixable: false,
|
|
454
|
+
});
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
if (applyData) {
|
|
458
|
+
const dataResult = await applyDataLayerFixes(diagnosis.targets, { dryRun: false });
|
|
459
|
+
fixFindings.push(...dataResult.findings);
|
|
460
|
+
}
|
|
461
|
+
diagnosis = diagnoseConfigLayoutData(paths.home, paths.configPath, Boolean(options.allowDeleteLegacyDirs), explicitConfig);
|
|
462
|
+
}
|
|
463
|
+
else if (options.fix && options.dryRun) {
|
|
464
|
+
const candidates = groupFixableFindings(diagnosis.findings);
|
|
465
|
+
const probe = diagnosis.raw ? structuredClone(diagnosis.raw) : null;
|
|
466
|
+
const applied = probe ? applyConfigMigrations(probe) : { notes: [] };
|
|
467
|
+
const dataDry = await applyDataLayerFixes(diagnosis.targets, { dryRun: true });
|
|
468
|
+
fixFindings.push({
|
|
469
|
+
id: 'FIX000',
|
|
470
|
+
domain: 'config',
|
|
471
|
+
severity: 'info',
|
|
472
|
+
message: `dry-run would apply groups [${candidates.map((c) => c.group).join(', ') || 'none'}]; file not modified`,
|
|
473
|
+
hint: applied.notes.join('; ') || undefined,
|
|
474
|
+
fixable: true,
|
|
475
|
+
});
|
|
476
|
+
fixFindings.push(...dataDry.findings);
|
|
477
|
+
}
|
|
478
|
+
const filtered = diagnosis.findings
|
|
479
|
+
.filter((f) => domainAllowed(f.id, f.domain, options.only))
|
|
480
|
+
.concat(fixFindings);
|
|
481
|
+
filtered.push({
|
|
482
|
+
id: 'RUN001',
|
|
483
|
+
domain: 'runtime',
|
|
484
|
+
severity: 'info',
|
|
485
|
+
message: 'doctor runs locally with deterministic rules only (no LLM; secrets redacted in reports)',
|
|
486
|
+
fixable: false,
|
|
487
|
+
});
|
|
488
|
+
const summary = { error: 0, warn: 0, info: 0, ok: 0 };
|
|
489
|
+
for (const f of filtered) {
|
|
490
|
+
summary[f.severity] += 1;
|
|
491
|
+
}
|
|
492
|
+
const finalBackups = paths.configPath && existsSync(paths.configPath) ? listConfigBackups(paths.configPath) : backups;
|
|
493
|
+
return {
|
|
494
|
+
home: paths.home,
|
|
495
|
+
configPath: paths.configPath,
|
|
496
|
+
findings: filtered,
|
|
497
|
+
summary,
|
|
498
|
+
fixableCount: filtered.filter((f) => f.fixable).length,
|
|
499
|
+
backups: finalBackups,
|
|
500
|
+
};
|
|
501
|
+
}
|
|
502
|
+
/**
|
|
503
|
+
* 应用布局侧修复
|
|
504
|
+
*
|
|
505
|
+
* @param home - OCTOPI_HOME
|
|
506
|
+
* @param raw - 配置对象
|
|
507
|
+
* @param options - doctor 选项
|
|
508
|
+
* @returns 已执行动作说明
|
|
509
|
+
*/
|
|
510
|
+
export function applyLayoutFixes(home, raw, options) {
|
|
511
|
+
const notes = [];
|
|
512
|
+
if (options.dryRun)
|
|
513
|
+
return ['[dry-run] layout fixes skipped'];
|
|
514
|
+
mkdirSync(join(home, 'plugins'), { recursive: true });
|
|
515
|
+
mkdirSync(join(home, 'audit'), { recursive: true });
|
|
516
|
+
mkdirSync(join(home, 'sessions'), { recursive: true });
|
|
517
|
+
const agents = raw && Array.isArray(raw.agents) ? raw.agents : [{ id: 'default' }];
|
|
518
|
+
for (const agent of agents) {
|
|
519
|
+
const a = (typeof agent === 'object' && agent !== null ? agent : {});
|
|
520
|
+
const id = typeof a.id === 'string' && a.id ? a.id : 'default';
|
|
521
|
+
const agentHome = typeof a.home === 'string' && a.home
|
|
522
|
+
? resolve(a.home)
|
|
523
|
+
: typeof a.persona === 'string'
|
|
524
|
+
? resolve(a.persona)
|
|
525
|
+
: join(home, 'agents', id);
|
|
526
|
+
mkdirSync(agentHome, { recursive: true });
|
|
527
|
+
mkdirSync(join(agentHome, 'skills'), { recursive: true });
|
|
528
|
+
const workspace = typeof a.workspace === 'string' && a.workspace ? resolve(a.workspace) : join(home, 'workspace', id);
|
|
529
|
+
mkdirSync(workspace, { recursive: true });
|
|
530
|
+
for (const { from, to } of LEGACY_PERSONA_MOVES) {
|
|
531
|
+
const fromPath = join(agentHome, from);
|
|
532
|
+
const toPath = join(agentHome, to);
|
|
533
|
+
if (existsSync(fromPath) && !existsSync(toPath)) {
|
|
534
|
+
mkdirSync(dirname(toPath), { recursive: true });
|
|
535
|
+
renameSync(fromPath, toPath);
|
|
536
|
+
notes.push(`persona ${from} → ${to} (${id})`);
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
if (options.allowDeleteLegacyDirs) {
|
|
540
|
+
for (const legacy of LEGACY_AGENT_DIRS) {
|
|
541
|
+
const dir = join(agentHome, legacy);
|
|
542
|
+
if (existsSync(dir)) {
|
|
543
|
+
const target = `${dir}.deprecated`;
|
|
544
|
+
if (!existsSync(target)) {
|
|
545
|
+
renameSync(dir, target);
|
|
546
|
+
notes.push(`renamed ${legacy}/ → ${legacy}.deprecated/ (${id})`);
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
if (notes.length === 0)
|
|
553
|
+
notes.push('layout already consistent');
|
|
554
|
+
return notes;
|
|
555
|
+
}
|
|
556
|
+
/**
|
|
557
|
+
* 将报告格式化为人类可读文本(已脱敏)
|
|
558
|
+
*
|
|
559
|
+
* @param report - doctor 报告
|
|
560
|
+
* @returns 展示文本
|
|
561
|
+
*/
|
|
562
|
+
/**
|
|
563
|
+
* 清洗 finding 文案中的疑似密钥
|
|
564
|
+
*
|
|
565
|
+
* @param text - 原始 message/hint
|
|
566
|
+
* @returns 脱敏后文本
|
|
567
|
+
*/
|
|
568
|
+
function scrubFindingText(text) {
|
|
569
|
+
if (!looksLikeSecret(text))
|
|
570
|
+
return text;
|
|
571
|
+
return text.replace(/sk-[A-Za-z0-9_-]+/g, (m) => redactSecretString(m));
|
|
572
|
+
}
|
|
573
|
+
export function formatDoctorReport(report) {
|
|
574
|
+
const lines = [];
|
|
575
|
+
lines.push('🏥 Octopi Doctor');
|
|
576
|
+
lines.push(` Home: ${report.home}`);
|
|
577
|
+
lines.push(` Config: ${report.configPath ?? '(not found)'}`);
|
|
578
|
+
if (report.backups && report.backups.length > 0) {
|
|
579
|
+
lines.push(` Backups:${report.backups.length} (latest: ${report.backups[0]})`);
|
|
580
|
+
}
|
|
581
|
+
lines.push('');
|
|
582
|
+
const mark = {
|
|
583
|
+
error: '✗',
|
|
584
|
+
warn: '⚠',
|
|
585
|
+
info: 'ℹ',
|
|
586
|
+
ok: '✓',
|
|
587
|
+
};
|
|
588
|
+
for (const f of report.findings) {
|
|
589
|
+
const message = scrubFindingText(f.message);
|
|
590
|
+
const hint = f.hint ? `\n ${scrubFindingText(f.hint)}` : '';
|
|
591
|
+
const fix = f.fixable ? ` [fixable${f.group ? `:${f.group}` : ''}]` : '';
|
|
592
|
+
lines.push(`${mark[f.severity]} ${f.id} [${f.severity}] ${message}${fix}${hint}`);
|
|
593
|
+
}
|
|
594
|
+
lines.push('');
|
|
595
|
+
lines.push(`Summary: ${report.summary.error} error, ${report.summary.warn} warn, ${report.summary.info} info, ${report.summary.ok} ok`);
|
|
596
|
+
if (report.fixableCount > 0) {
|
|
597
|
+
lines.push(`Next: octopi doctor --fix --yes`);
|
|
598
|
+
}
|
|
599
|
+
return lines.join('\n');
|
|
600
|
+
}
|
|
601
|
+
/**
|
|
602
|
+
* 报告转 JSON(脱敏)
|
|
603
|
+
*
|
|
604
|
+
* @param report - doctor 报告
|
|
605
|
+
* @returns JSON 字符串
|
|
606
|
+
*/
|
|
607
|
+
export function doctorReportToJson(report) {
|
|
608
|
+
const findings = report.findings.map((f) => ({
|
|
609
|
+
...f,
|
|
610
|
+
message: scrubFindingText(f.message),
|
|
611
|
+
hint: f.hint ? scrubFindingText(f.hint) : undefined,
|
|
612
|
+
}));
|
|
613
|
+
return JSON.stringify({
|
|
614
|
+
home: report.home,
|
|
615
|
+
configPath: report.configPath,
|
|
616
|
+
summary: report.summary,
|
|
617
|
+
fixableCount: report.fixableCount,
|
|
618
|
+
backups: report.backups ?? [],
|
|
619
|
+
findings,
|
|
620
|
+
redactedNote: 'secret values never emitted; doctor does not call LLMs',
|
|
621
|
+
redacted: redactConfig({ note: 'secret values never emitted; doctor does not call LLMs' }),
|
|
622
|
+
}, null, 2);
|
|
623
|
+
}
|
|
624
|
+
/**
|
|
625
|
+
* 处理 --restore
|
|
626
|
+
*
|
|
627
|
+
* @param args - CLI 参数(restore 可为 true 或备份路径)
|
|
628
|
+
* @returns 是否已处理 restore 模式
|
|
629
|
+
*/
|
|
630
|
+
export async function doctorRestoreCommand(args) {
|
|
631
|
+
const paths = resolveDoctorPaths(args);
|
|
632
|
+
if (!paths.configPath) {
|
|
633
|
+
console.error('octopi doctor --restore: config not found; pass -c <path>');
|
|
634
|
+
process.exitCode = 3;
|
|
635
|
+
return;
|
|
636
|
+
}
|
|
637
|
+
const restoreArg = args.restore;
|
|
638
|
+
let backupPath = null;
|
|
639
|
+
if (typeof restoreArg === 'string' && restoreArg) {
|
|
640
|
+
backupPath = resolve(restoreArg);
|
|
641
|
+
}
|
|
642
|
+
else {
|
|
643
|
+
backupPath = latestConfigBackup(paths.configPath);
|
|
644
|
+
}
|
|
645
|
+
if (!backupPath) {
|
|
646
|
+
const listed = listConfigBackups(paths.configPath);
|
|
647
|
+
console.error(`octopi doctor --restore: no backup found for ${paths.configPath}`);
|
|
648
|
+
if (listed.length > 0) {
|
|
649
|
+
console.error('Available backups:');
|
|
650
|
+
for (const p of listed)
|
|
651
|
+
console.error(` ${p}`);
|
|
652
|
+
}
|
|
653
|
+
process.exitCode = 3;
|
|
654
|
+
return;
|
|
655
|
+
}
|
|
656
|
+
const result = restoreConfigFromBackup(paths.configPath, backupPath);
|
|
657
|
+
console.log(result.ok ? `✅ ${result.message}` : `❌ ${result.message}`);
|
|
658
|
+
if (args.json) {
|
|
659
|
+
console.log(JSON.stringify({ redactedNote: 'restore copies local files only; no LLM', ...result }, null, 2));
|
|
660
|
+
}
|
|
661
|
+
process.exitCode = result.ok ? 0 : 3;
|
|
662
|
+
}
|
|
663
|
+
/**
|
|
664
|
+
* CLI 入口:octopi doctor
|
|
665
|
+
*
|
|
666
|
+
* @param args - CLI 参数
|
|
667
|
+
* @param options - 选项
|
|
668
|
+
*/
|
|
669
|
+
export async function doctorCommand(args, options = {}) {
|
|
670
|
+
if (args.restore) {
|
|
671
|
+
await doctorRestoreCommand(args);
|
|
672
|
+
return;
|
|
673
|
+
}
|
|
674
|
+
const report = await runDoctor(args, {
|
|
675
|
+
...options,
|
|
676
|
+
selectedGroups: options.selectedGroups,
|
|
677
|
+
});
|
|
678
|
+
if (options.json) {
|
|
679
|
+
console.log(doctorReportToJson(report));
|
|
680
|
+
}
|
|
681
|
+
else {
|
|
682
|
+
console.log(formatDoctorReport(report));
|
|
683
|
+
}
|
|
684
|
+
if (report.summary.error > 0) {
|
|
685
|
+
process.exitCode = 2;
|
|
686
|
+
}
|
|
687
|
+
else if (report.summary.warn > 0) {
|
|
688
|
+
process.exitCode = 1;
|
|
689
|
+
}
|
|
690
|
+
else {
|
|
691
|
+
process.exitCode = 0;
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
/** 供测试:列出 agent 目录 */
|
|
695
|
+
export function listAgentDirs(home) {
|
|
696
|
+
const agentsDir = join(home, 'agents');
|
|
697
|
+
if (!existsSync(agentsDir))
|
|
698
|
+
return [];
|
|
699
|
+
return readdirSync(agentsDir)
|
|
700
|
+
.filter((name) => {
|
|
701
|
+
try {
|
|
702
|
+
return statSync(join(agentsDir, name)).isDirectory();
|
|
703
|
+
}
|
|
704
|
+
catch {
|
|
705
|
+
return false;
|
|
706
|
+
}
|
|
707
|
+
})
|
|
708
|
+
.sort();
|
|
709
|
+
}
|
|
710
|
+
export { listConfigBackups, latestConfigBackup, restoreConfigFromBackup };
|
|
711
|
+
export { detectDataLayer, applyDataLayerFixes, resolveAgentDataTargets, checkDeprecatedSessionStore, };
|