@trazum/cli 2.7.12 → 3.0.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/README.md +4 -2
- package/assets/trazum-statusline.sh +131 -0
- package/dist/git.d.ts +38 -0
- package/dist/git.d.ts.map +1 -1
- package/dist/git.js +54 -0
- package/dist/git.js.map +1 -1
- package/dist/i18n/en.d.ts.map +1 -1
- package/dist/i18n/en.js +170 -3
- package/dist/i18n/en.js.map +1 -1
- package/dist/i18n/es.d.ts.map +1 -1
- package/dist/i18n/es.js +174 -3
- package/dist/i18n/es.js.map +1 -1
- package/dist/i18n/types.d.ts +84 -0
- package/dist/i18n/types.d.ts.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +670 -262
- package/dist/index.js.map +1 -1
- package/dist/proactive.d.ts +344 -0
- package/dist/proactive.d.ts.map +1 -0
- package/dist/proactive.js +1079 -0
- package/dist/proactive.js.map +1 -0
- package/dist/style.d.ts +305 -26
- package/dist/style.d.ts.map +1 -1
- package/dist/style.js +449 -47
- package/dist/style.js.map +1 -1
- package/dist/watch-notify.d.ts +82 -0
- package/dist/watch-notify.d.ts.map +1 -0
- package/dist/watch-notify.js +118 -0
- package/dist/watch-notify.js.map +1 -0
- package/dist/watch-run.d.ts +7 -0
- package/dist/watch-run.d.ts.map +1 -1
- package/dist/watch-run.js.map +1 -1
- package/dist/weekly.d.ts +32 -0
- package/dist/weekly.d.ts.map +1 -0
- package/dist/weekly.js +119 -0
- package/dist/weekly.js.map +1 -0
- package/package.json +3 -2
- package/src/git.ts +77 -0
- package/src/i18n/en.ts +198 -3
- package/src/i18n/es.ts +202 -3
- package/src/i18n/types.ts +130 -0
- package/src/index.ts +715 -302
- package/src/proactive.ts +1319 -0
- package/src/style.ts +502 -54
- package/src/watch-notify.ts +152 -0
- package/src/watch-run.ts +7 -0
- package/src/weekly.ts +133 -0
|
@@ -0,0 +1,1079 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `trazum proactive`: the three places Trazum can speak first, turned on and
|
|
3
|
+
* off from one command.
|
|
4
|
+
*
|
|
5
|
+
* It edits files in a person's home directory, so this module is written for
|
|
6
|
+
* restraint before features. The rules, each held by `proactive.test.js`:
|
|
7
|
+
*
|
|
8
|
+
* - **One door for every write.** `applyChange` takes the target, the text the
|
|
9
|
+
* caller read and the text it wants, and is the only function here that
|
|
10
|
+
* writes. It refuses a target that is not on the allowlist it prints, one
|
|
11
|
+
* that is a symlink, one whose parent leaves its root, and one that changed
|
|
12
|
+
* since it was read. It writes a temporary file beside the target and renames
|
|
13
|
+
* it over, keeps the mode, and makes one backup beside the file on the first
|
|
14
|
+
* change only.
|
|
15
|
+
* - **Nothing is written because nobody said no.** Planning never writes; the
|
|
16
|
+
* caller decides, per item, and a decision of "no" is the default.
|
|
17
|
+
* - **JSON is edited as data.** A file `JSON.parse` rejects, or one this
|
|
18
|
+
* module could not write back exactly as it was apart from the lines it
|
|
19
|
+
* adds, is left alone and named.
|
|
20
|
+
* - **Its own lines are recognisable without a marker.** JSON has no comments,
|
|
21
|
+
* so a hook and a status line are Trazum's by the exact command written, and
|
|
22
|
+
* a server entry by being exactly the entry written and recorded in the
|
|
23
|
+
* manifest. The crontab line carries a trailing comment.
|
|
24
|
+
* - **The home directory is a parameter.** Nothing below reads the real
|
|
25
|
+
* environment; `Ctx` carries every fact about the machine, so a test passes a
|
|
26
|
+
* made-up one.
|
|
27
|
+
*
|
|
28
|
+
* Nothing here sends anything anywhere. What it turns on reads files already
|
|
29
|
+
* on the machine.
|
|
30
|
+
*/
|
|
31
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
32
|
+
import { constants } from 'node:fs';
|
|
33
|
+
import { access, chmod, lstat, mkdir, open, realpath, rename, rmdir, rm, stat, writeFile } from 'node:fs/promises';
|
|
34
|
+
import { basename, dirname, join, resolve, sep } from 'node:path';
|
|
35
|
+
import { bucketedProfile, bucketsFromRecords } from '@trazum/core';
|
|
36
|
+
import { loadConfig } from '@trazum/core/node';
|
|
37
|
+
import { readStore } from './store-fs.js';
|
|
38
|
+
export const ITEMS = ['statusline', 'watch', 'mcp'];
|
|
39
|
+
/** The real crontab, through the one module that may start a process. */
|
|
40
|
+
export function systemCrontab(run) {
|
|
41
|
+
return {
|
|
42
|
+
read() {
|
|
43
|
+
const result = run(['-l']);
|
|
44
|
+
if (result.errorCode === 'ENOENT')
|
|
45
|
+
return { kind: 'missing' };
|
|
46
|
+
if (result.errorCode !== null)
|
|
47
|
+
return { kind: 'error', message: result.errorCode };
|
|
48
|
+
if (result.status === 0)
|
|
49
|
+
return { kind: 'ok', text: result.stdout };
|
|
50
|
+
if (result.status === 1 && /no crontab for/i.test(result.stderr))
|
|
51
|
+
return { kind: 'none' };
|
|
52
|
+
return { kind: 'error', message: (result.stderr.trim() || `exit status ${result.status}`).slice(0, 200) };
|
|
53
|
+
},
|
|
54
|
+
write(text) {
|
|
55
|
+
const result = run(['-'], text);
|
|
56
|
+
if (result.errorCode !== null || result.status !== 0) {
|
|
57
|
+
throw new Error((result.stderr.trim() || result.errorCode || `exit status ${result.status}`).slice(0, 200));
|
|
58
|
+
}
|
|
59
|
+
},
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
// --------------------------------------------------------------------------
|
|
63
|
+
// Where it may write
|
|
64
|
+
// --------------------------------------------------------------------------
|
|
65
|
+
/** The pseudo-target for the user's crontab: not a path, and on the allowlist. */
|
|
66
|
+
export const CRONTAB = 'crontab';
|
|
67
|
+
export const BACKUP_SUFFIX = '.trazum-backup';
|
|
68
|
+
export const MANAGED_MARK = '# trazum watch (managed)';
|
|
69
|
+
export const MCP_ENTRY = { command: 'npx', args: ['-y', '@trazum/mcp'] };
|
|
70
|
+
export function pathsFor(ctx) {
|
|
71
|
+
const home = resolve(ctx.home);
|
|
72
|
+
const cwd = resolve(ctx.cwd);
|
|
73
|
+
const stateDir = join(home, '.trazum');
|
|
74
|
+
const scriptDir = join(stateDir, 'statusline');
|
|
75
|
+
return {
|
|
76
|
+
settings: join(home, '.claude', 'settings.json'),
|
|
77
|
+
scriptDir,
|
|
78
|
+
script: join(scriptDir, 'trazum-statusline.sh'),
|
|
79
|
+
stateDir,
|
|
80
|
+
manifest: join(stateDir, 'proactive.json'),
|
|
81
|
+
cronBackup: join(stateDir, `crontab${BACKUP_SUFFIX}`),
|
|
82
|
+
mcp: [
|
|
83
|
+
{ client: 'claude-code', path: join(cwd, '.mcp.json'), dir: cwd, folder: null },
|
|
84
|
+
{ client: 'cursor', path: join(cwd, '.cursor', 'mcp.json'), dir: cwd, folder: join(cwd, '.cursor') },
|
|
85
|
+
],
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
/** Every target a write may name. The list is printed when one is refused. */
|
|
89
|
+
export function allowlist(ctx) {
|
|
90
|
+
const p = pathsFor(ctx);
|
|
91
|
+
const home = resolve(ctx.home);
|
|
92
|
+
const owned = [
|
|
93
|
+
{ target: p.settings, root: home, backup: true },
|
|
94
|
+
...p.mcp.map((m) => ({ target: m.path, root: m.dir, backup: true })),
|
|
95
|
+
];
|
|
96
|
+
return [
|
|
97
|
+
...owned,
|
|
98
|
+
{ target: CRONTAB, root: home, backup: true },
|
|
99
|
+
{ target: p.script, root: home, backup: false },
|
|
100
|
+
{ target: p.manifest, root: home, backup: false },
|
|
101
|
+
{ target: p.cronBackup, root: home, backup: false },
|
|
102
|
+
// The copy made beside a file the first time it changes.
|
|
103
|
+
...owned.map((entry) => ({ target: `${entry.target}${BACKUP_SUFFIX}`, root: entry.root, backup: false })),
|
|
104
|
+
];
|
|
105
|
+
}
|
|
106
|
+
export class RefusedWrite extends Error {
|
|
107
|
+
reason;
|
|
108
|
+
target;
|
|
109
|
+
allowed;
|
|
110
|
+
constructor(reason, target, allowed) {
|
|
111
|
+
super(`refused to write ${target}: ${reason}`);
|
|
112
|
+
this.reason = reason;
|
|
113
|
+
this.target = target;
|
|
114
|
+
this.allowed = allowed;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
/** A path in the shape a person reads: `~` for the home directory. */
|
|
118
|
+
export function shown(ctx, path) {
|
|
119
|
+
const home = resolve(ctx.home);
|
|
120
|
+
if (path === home)
|
|
121
|
+
return '~';
|
|
122
|
+
return path.startsWith(`${home}${sep}`) ? `~${path.slice(home.length)}` : path;
|
|
123
|
+
}
|
|
124
|
+
async function present(path) {
|
|
125
|
+
return lstat(path).then(() => true, () => false);
|
|
126
|
+
}
|
|
127
|
+
async function realOrSelf(path) {
|
|
128
|
+
// The nearest ancestor that exists, resolved, with the rest put back: a
|
|
129
|
+
// target that is not there yet still lives somewhere that can be checked.
|
|
130
|
+
let tail = '';
|
|
131
|
+
let at = path;
|
|
132
|
+
for (;;) {
|
|
133
|
+
try {
|
|
134
|
+
return join(await realpath(at), tail);
|
|
135
|
+
}
|
|
136
|
+
catch {
|
|
137
|
+
const parent = dirname(at);
|
|
138
|
+
if (parent === at)
|
|
139
|
+
return path;
|
|
140
|
+
tail = join(basename(at), tail);
|
|
141
|
+
at = parent;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* What is at a path, and its text when it is a file, through one open.
|
|
147
|
+
*
|
|
148
|
+
* Asking what a path is and then reading it are two looks at the path, and it
|
|
149
|
+
* can be swapped for something else between them: a file checked not to be a
|
|
150
|
+
* symbolic link and then read through one. So the file is opened once, told
|
|
151
|
+
* not to follow a link, and both the kind and the text are taken from that
|
|
152
|
+
* one handle. What was checked is what was read.
|
|
153
|
+
*/
|
|
154
|
+
export async function readExisting(path) {
|
|
155
|
+
// Where the platform cannot refuse a link at open (Windows), the path is
|
|
156
|
+
// looked at after the handle is held: late, and still not before the read.
|
|
157
|
+
const noFollow = constants.O_NOFOLLOW;
|
|
158
|
+
let handle;
|
|
159
|
+
try {
|
|
160
|
+
handle = await open(path, constants.O_RDONLY | (noFollow ?? 0));
|
|
161
|
+
}
|
|
162
|
+
catch (error) {
|
|
163
|
+
const code = error.code;
|
|
164
|
+
if (code === 'ENOENT' || code === 'ENOTDIR')
|
|
165
|
+
return { kind: 'absent' };
|
|
166
|
+
if (code === 'ELOOP' || code === 'EMLINK')
|
|
167
|
+
return { kind: 'symlink' };
|
|
168
|
+
throw error;
|
|
169
|
+
}
|
|
170
|
+
try {
|
|
171
|
+
const info = await handle.stat();
|
|
172
|
+
if (!info.isFile())
|
|
173
|
+
return { kind: 'other' };
|
|
174
|
+
const text = await handle.readFile('utf8');
|
|
175
|
+
if (noFollow === undefined && (await lstat(path)).isSymbolicLink())
|
|
176
|
+
return { kind: 'symlink' };
|
|
177
|
+
return { kind: 'file', text, mode: info.mode & 0o777 };
|
|
178
|
+
}
|
|
179
|
+
finally {
|
|
180
|
+
await handle.close();
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* The only function in this module that writes.
|
|
185
|
+
*
|
|
186
|
+
* It takes the target, the text the caller read (`before`) and the text it
|
|
187
|
+
* wants (`after`). It does not decide anything; it refuses.
|
|
188
|
+
*/
|
|
189
|
+
export async function applyChange(ctx, change) {
|
|
190
|
+
const list = allowlist(ctx);
|
|
191
|
+
const names = [...new Set(list.map((entry) => entry.target))];
|
|
192
|
+
const entry = list.find((candidate) => candidate.target === change.target);
|
|
193
|
+
if (entry === undefined)
|
|
194
|
+
throw new RefusedWrite('not-allowed', change.target, names);
|
|
195
|
+
// The text on disk is what the caller read, or nothing is written. A file
|
|
196
|
+
// that changed between the read and the write is somebody else's edit.
|
|
197
|
+
if (change.target === CRONTAB) {
|
|
198
|
+
const now = await ctx.crontab.read();
|
|
199
|
+
// A crontab that cannot be read is not an empty one. Read as "none" a
|
|
200
|
+
// moment ago and unreadable now, it would have matched "nothing there", and
|
|
201
|
+
// the write would have replaced whatever the person has with one line.
|
|
202
|
+
if (now.kind === 'missing' || now.kind === 'error')
|
|
203
|
+
throw new RefusedWrite('unreadable', change.target, names);
|
|
204
|
+
const current = now.kind === 'ok' ? now.text : null;
|
|
205
|
+
if ((current ?? '') !== (change.before ?? ''))
|
|
206
|
+
throw new RefusedWrite('changed', change.target, names);
|
|
207
|
+
// A crontab made of nothing but this command's own lines has nothing of the person's to keep.
|
|
208
|
+
const theirs = cronRows(current).rows.some((row) => parseManagedLine(row) === null);
|
|
209
|
+
if (change.backup && current !== null && theirs) {
|
|
210
|
+
await writeBackup(ctx, pathsFor(ctx).cronBackup, current, 0o600);
|
|
211
|
+
}
|
|
212
|
+
await ctx.crontab.write(change.after ?? '');
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
const root = await realOrSelf(entry.root);
|
|
216
|
+
const parent = await realOrSelf(dirname(change.target));
|
|
217
|
+
if (parent !== root && !parent.startsWith(`${root}${sep}`))
|
|
218
|
+
throw new RefusedWrite('outside', change.target, names);
|
|
219
|
+
const there = await readExisting(change.target);
|
|
220
|
+
if (there.kind === 'symlink')
|
|
221
|
+
throw new RefusedWrite('symlink', change.target, names);
|
|
222
|
+
if (there.kind === 'other')
|
|
223
|
+
throw new Error(`${change.target} is not a regular file`);
|
|
224
|
+
const current = there.kind === 'file' ? there.text : null;
|
|
225
|
+
if (current !== change.before)
|
|
226
|
+
throw new RefusedWrite('changed', change.target, names);
|
|
227
|
+
if (change.after === null) {
|
|
228
|
+
if (there.kind === 'file')
|
|
229
|
+
await rm(change.target);
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
const mode = there.kind === 'file' ? there.mode : change.mode;
|
|
233
|
+
if (change.backup && entry.backup && current !== null) {
|
|
234
|
+
await writeBackup(ctx, `${change.target}${BACKUP_SUFFIX}`, current, mode);
|
|
235
|
+
}
|
|
236
|
+
await mkdir(dirname(change.target), { recursive: true });
|
|
237
|
+
const temp = join(dirname(change.target), `.${basename(change.target)}.trazum-${process.pid}-${randomBytes(4).toString('hex')}.tmp`);
|
|
238
|
+
try {
|
|
239
|
+
await writeFile(temp, change.after, { flag: 'wx', mode });
|
|
240
|
+
await chmod(temp, mode);
|
|
241
|
+
await rename(temp, change.target);
|
|
242
|
+
}
|
|
243
|
+
catch (error) {
|
|
244
|
+
await rm(temp, { force: true });
|
|
245
|
+
throw error;
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
/** One copy of what the person had, made the first time and never replaced. */
|
|
249
|
+
async function writeBackup(ctx, path, text, mode) {
|
|
250
|
+
if (!allowlist(ctx).some((entry) => entry.target === path)) {
|
|
251
|
+
throw new RefusedWrite('not-allowed', path, allowlist(ctx).map((entry) => entry.target));
|
|
252
|
+
}
|
|
253
|
+
if (await present(path))
|
|
254
|
+
return;
|
|
255
|
+
await mkdir(dirname(path), { recursive: true });
|
|
256
|
+
await writeFile(path, text, { flag: 'wx', mode });
|
|
257
|
+
}
|
|
258
|
+
/** A directory this command made, removed once it is empty. Never anything else. */
|
|
259
|
+
async function removeEmptyDir(ctx, dir) {
|
|
260
|
+
const p = pathsFor(ctx);
|
|
261
|
+
if (dir !== p.scriptDir && dir !== p.stateDir)
|
|
262
|
+
return;
|
|
263
|
+
await rmdir(dir).catch(() => undefined);
|
|
264
|
+
}
|
|
265
|
+
export function detectFormat(raw) {
|
|
266
|
+
const indent = /^([ \t]+)\S/m.exec(raw)?.[1] ?? ' ';
|
|
267
|
+
return { indent, eol: raw.includes('\r\n') ? '\r\n' : '\n', final: raw.endsWith('\n') };
|
|
268
|
+
}
|
|
269
|
+
export function serialise(value, format) {
|
|
270
|
+
const text = JSON.stringify(value, null, format.indent);
|
|
271
|
+
return (format.eol === '\r\n' ? text.replace(/\n/g, '\r\n') : text) + (format.final ? format.eol : '');
|
|
272
|
+
}
|
|
273
|
+
const isObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
274
|
+
/**
|
|
275
|
+
* A JSON object file, read for editing, or the reason it is to be left alone.
|
|
276
|
+
*
|
|
277
|
+
* The last check is the strict one: the parsed value, written back untouched,
|
|
278
|
+
* has to say what the file says. Spacing and line breaks may be normalised (the
|
|
279
|
+
* snippet in plugin/README.md has inline arrays, and refusing every file that
|
|
280
|
+
* pasted it would refuse the people this is for), and that is reported. A value
|
|
281
|
+
* that would not survive the round trip is left alone.
|
|
282
|
+
*/
|
|
283
|
+
export async function readJsonObject(ctx, file, root) {
|
|
284
|
+
const name = shown(ctx, file);
|
|
285
|
+
let there;
|
|
286
|
+
try {
|
|
287
|
+
there = await readExisting(file);
|
|
288
|
+
}
|
|
289
|
+
catch (error) {
|
|
290
|
+
return { kind: 'refused', finding: { code: 'file.unreadable', params: { file: name, why: error.message } } };
|
|
291
|
+
}
|
|
292
|
+
if (there.kind === 'absent')
|
|
293
|
+
return { kind: 'absent' };
|
|
294
|
+
if (there.kind === 'symlink')
|
|
295
|
+
return { kind: 'refused', finding: { code: 'file.symlink', params: { file: name } } };
|
|
296
|
+
if (there.kind === 'other')
|
|
297
|
+
return { kind: 'refused', finding: { code: 'file.unreadable', params: { file: name, why: 'not a regular file' } } };
|
|
298
|
+
const realRoot = await realOrSelf(root);
|
|
299
|
+
const parent = await realOrSelf(dirname(file));
|
|
300
|
+
if (parent !== realRoot && !parent.startsWith(`${realRoot}${sep}`)) {
|
|
301
|
+
return { kind: 'refused', finding: { code: 'file.outside', params: { file: name } } };
|
|
302
|
+
}
|
|
303
|
+
const raw = there.text;
|
|
304
|
+
let value;
|
|
305
|
+
try {
|
|
306
|
+
value = JSON.parse(raw);
|
|
307
|
+
}
|
|
308
|
+
catch (error) {
|
|
309
|
+
return { kind: 'refused', finding: { code: 'file.unparseable', params: { file: name, why: error.message } } };
|
|
310
|
+
}
|
|
311
|
+
if (!isObject(value))
|
|
312
|
+
return { kind: 'refused', finding: { code: 'file.shape', params: { file: name, key: '(top level)' } } };
|
|
313
|
+
const format = detectFormat(raw);
|
|
314
|
+
const rewritten = serialise(value, format);
|
|
315
|
+
// Spacing and line breaks may be normalised and are said so; a value, a key or an
|
|
316
|
+
// escape that would not survive the round trip (a duplicate key, 1.0 written as 1)
|
|
317
|
+
// is not something this command may rewrite.
|
|
318
|
+
if (rewritten !== raw && withoutSpacing(rewritten) !== withoutSpacing(raw)) {
|
|
319
|
+
return { kind: 'refused', finding: { code: 'file.notExact', params: { file: name } } };
|
|
320
|
+
}
|
|
321
|
+
return { kind: 'ok', raw, value, format, reformatted: rewritten !== raw };
|
|
322
|
+
}
|
|
323
|
+
/** The text with every space, tab and line break outside a string removed. */
|
|
324
|
+
function withoutSpacing(text) {
|
|
325
|
+
let out = '';
|
|
326
|
+
let inString = false;
|
|
327
|
+
for (let i = 0; i < text.length; i++) {
|
|
328
|
+
const ch = text[i];
|
|
329
|
+
if (inString) {
|
|
330
|
+
out += ch;
|
|
331
|
+
if (ch === '\\')
|
|
332
|
+
out += text[++i] ?? '';
|
|
333
|
+
else if (ch === '"')
|
|
334
|
+
inString = false;
|
|
335
|
+
}
|
|
336
|
+
else if (ch === '"') {
|
|
337
|
+
inString = true;
|
|
338
|
+
out += ch;
|
|
339
|
+
}
|
|
340
|
+
else if (ch !== ' ' && ch !== '\t' && ch !== '\n' && ch !== '\r') {
|
|
341
|
+
out += ch;
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
return out;
|
|
345
|
+
}
|
|
346
|
+
/** Lines that appear and lines that go, in order: a longest-common-subsequence diff. */
|
|
347
|
+
export function diffLines(before, after) {
|
|
348
|
+
const a = before === null ? [] : before.replace(/\r\n/g, '\n').replace(/\n$/, '').split('\n');
|
|
349
|
+
const b = after === null ? [] : after.replace(/\r\n/g, '\n').replace(/\n$/, '').split('\n');
|
|
350
|
+
if (before === null)
|
|
351
|
+
return { added: b, removed: [] };
|
|
352
|
+
if (after === null)
|
|
353
|
+
return { added: [], removed: a };
|
|
354
|
+
if (a.length * b.length > 4_000_000) {
|
|
355
|
+
const keep = new Map();
|
|
356
|
+
for (const line of a)
|
|
357
|
+
keep.set(line, (keep.get(line) ?? 0) + 1);
|
|
358
|
+
const added = [];
|
|
359
|
+
for (const line of b) {
|
|
360
|
+
const left = keep.get(line) ?? 0;
|
|
361
|
+
if (left > 0)
|
|
362
|
+
keep.set(line, left - 1);
|
|
363
|
+
else
|
|
364
|
+
added.push(line);
|
|
365
|
+
}
|
|
366
|
+
const had = new Map();
|
|
367
|
+
for (const line of b)
|
|
368
|
+
had.set(line, (had.get(line) ?? 0) + 1);
|
|
369
|
+
const removed = [];
|
|
370
|
+
for (const line of a) {
|
|
371
|
+
const left = had.get(line) ?? 0;
|
|
372
|
+
if (left > 0)
|
|
373
|
+
had.set(line, left - 1);
|
|
374
|
+
else
|
|
375
|
+
removed.push(line);
|
|
376
|
+
}
|
|
377
|
+
return { added, removed };
|
|
378
|
+
}
|
|
379
|
+
const table = Array.from({ length: a.length + 1 }, () => new Array(b.length + 1).fill(0));
|
|
380
|
+
for (let i = a.length - 1; i >= 0; i--) {
|
|
381
|
+
for (let j = b.length - 1; j >= 0; j--) {
|
|
382
|
+
table[i][j] = a[i] === b[j] ? table[i + 1][j + 1] + 1 : Math.max(table[i + 1][j], table[i][j + 1]);
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
const added = [];
|
|
386
|
+
const removed = [];
|
|
387
|
+
let i = 0;
|
|
388
|
+
let j = 0;
|
|
389
|
+
while (i < a.length && j < b.length) {
|
|
390
|
+
if (a[i] === b[j]) {
|
|
391
|
+
i++;
|
|
392
|
+
j++;
|
|
393
|
+
}
|
|
394
|
+
else if (table[i + 1][j] >= table[i][j + 1]) {
|
|
395
|
+
removed.push(a[i++]);
|
|
396
|
+
}
|
|
397
|
+
else {
|
|
398
|
+
added.push(b[j++]);
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
while (i < a.length)
|
|
402
|
+
removed.push(a[i++]);
|
|
403
|
+
while (j < b.length)
|
|
404
|
+
added.push(b[j++]);
|
|
405
|
+
return { added, removed };
|
|
406
|
+
}
|
|
407
|
+
function deepEqual(a, b) {
|
|
408
|
+
return JSON.stringify(a) === JSON.stringify(b);
|
|
409
|
+
}
|
|
410
|
+
const emptyManifest = () => ({ v: 1 });
|
|
411
|
+
function manifestFrom(value) {
|
|
412
|
+
const out = emptyManifest();
|
|
413
|
+
const s = value.statusline;
|
|
414
|
+
if (isObject(s)) {
|
|
415
|
+
out.statusline = {
|
|
416
|
+
createdFile: s.createdFile === true,
|
|
417
|
+
created: Array.isArray(s.created) ? s.created.filter((x) => typeof x === 'string') : [],
|
|
418
|
+
...(typeof s.script === 'string' ? { script: s.script } : {}),
|
|
419
|
+
};
|
|
420
|
+
}
|
|
421
|
+
if (isObject(value.mcp)) {
|
|
422
|
+
out.mcp = {};
|
|
423
|
+
for (const [path, record] of Object.entries(value.mcp)) {
|
|
424
|
+
if (isObject(record))
|
|
425
|
+
out.mcp[path] = { createdFile: record.createdFile === true, createdKey: record.createdKey === true };
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
return out;
|
|
429
|
+
}
|
|
430
|
+
const digest = (text) => createHash('sha256').update(text).digest('hex');
|
|
431
|
+
const manifestEmpty = (m) => m.statusline === undefined && (m.mcp === undefined || Object.keys(m.mcp).length === 0);
|
|
432
|
+
// --------------------------------------------------------------------------
|
|
433
|
+
// The CLI this will keep running
|
|
434
|
+
// --------------------------------------------------------------------------
|
|
435
|
+
const q = (text) => `'${text}'`;
|
|
436
|
+
/** A path that can sit inside single quotes, in a shell string and in a crontab. */
|
|
437
|
+
export function quotable(path) {
|
|
438
|
+
// `'` ends the quote; `%` is a newline to cron; a newline ends the line.
|
|
439
|
+
return !/['%\r\n\0]/.test(path);
|
|
440
|
+
}
|
|
441
|
+
/** Where a one-off runner unpacks a package: not there tomorrow. */
|
|
442
|
+
const TRANSIENT_HOMES = [/[\\/]_npx[\\/]/, /[\\/]dlx[\\/]/, /[\\/]bunx-/, /[\\/]\.npm[\\/]_npx[\\/]/];
|
|
443
|
+
/**
|
|
444
|
+
* The CLI a scheduled job and a hook can call tomorrow.
|
|
445
|
+
*
|
|
446
|
+
* `npx @trazum/cli` unpacks into a cache nobody promised to keep, and the
|
|
447
|
+
* status line script is not published inside the package. So a path written
|
|
448
|
+
* into somebody's settings must be one that stays: a CLI installed where the
|
|
449
|
+
* person keeps it, or one they named with `TRAZUM_BIN`. A run from the npx
|
|
450
|
+
* cache is refused, with the reason.
|
|
451
|
+
*/
|
|
452
|
+
export async function stableRuntime(ctx) {
|
|
453
|
+
const chosen = ctx.trazumBin !== undefined && ctx.trazumBin !== '';
|
|
454
|
+
const entry = chosen ? resolve(ctx.cwd, ctx.trazumBin) : ctx.entry;
|
|
455
|
+
if (!quotable(entry) || !quotable(ctx.execPath))
|
|
456
|
+
return { ok: false, code: 'unsafe', path: quotable(entry) ? ctx.execPath : entry };
|
|
457
|
+
if (!chosen && TRANSIENT_HOMES.some((pattern) => pattern.test(entry)))
|
|
458
|
+
return { ok: false, code: 'unstable', path: entry };
|
|
459
|
+
if (!(await stat(entry).then((info) => info.isFile(), () => false)))
|
|
460
|
+
return { ok: false, code: 'unstable', path: entry };
|
|
461
|
+
return { ok: true, entry, node: ctx.execPath };
|
|
462
|
+
}
|
|
463
|
+
// --------------------------------------------------------------------------
|
|
464
|
+
// Item 1: the status line and its Stop hook
|
|
465
|
+
// --------------------------------------------------------------------------
|
|
466
|
+
const statusCommand = (script, entry) => `TRAZUM_BIN=${q(entry)} ${q(script)}`;
|
|
467
|
+
/** Whether a command is the one this writes, and which CLI it names. */
|
|
468
|
+
export function parseManaged(command, script) {
|
|
469
|
+
let rest = command;
|
|
470
|
+
let bin = null;
|
|
471
|
+
const head = "TRAZUM_BIN='";
|
|
472
|
+
if (rest.startsWith(head)) {
|
|
473
|
+
const end = rest.indexOf("' ", head.length);
|
|
474
|
+
if (end < 0)
|
|
475
|
+
return null;
|
|
476
|
+
bin = rest.slice(head.length, end);
|
|
477
|
+
rest = rest.slice(end + 2);
|
|
478
|
+
}
|
|
479
|
+
if (rest === q(script))
|
|
480
|
+
return { refresh: false, bin };
|
|
481
|
+
if (rest === `${q(script)} --refresh`)
|
|
482
|
+
return { refresh: true, bin };
|
|
483
|
+
return null;
|
|
484
|
+
}
|
|
485
|
+
export function viewSettings(value, script) {
|
|
486
|
+
const view = { statusLine: 'none', foreign: '', hook: 'none', bin: null, shape: null };
|
|
487
|
+
if ('statusLine' in value) {
|
|
488
|
+
const line = value.statusLine;
|
|
489
|
+
const command = isObject(line) && typeof line.command === 'string' ? line.command : null;
|
|
490
|
+
const ours = command === null ? null : parseManaged(command, script);
|
|
491
|
+
if (ours !== null && !ours.refresh) {
|
|
492
|
+
view.statusLine = 'ours';
|
|
493
|
+
view.bin = ours.bin;
|
|
494
|
+
}
|
|
495
|
+
else {
|
|
496
|
+
view.statusLine = 'foreign';
|
|
497
|
+
view.foreign = command ?? JSON.stringify(line).slice(0, 80);
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
if ('hooks' in value) {
|
|
501
|
+
if (!isObject(value.hooks)) {
|
|
502
|
+
view.shape = 'hooks';
|
|
503
|
+
return view;
|
|
504
|
+
}
|
|
505
|
+
if ('Stop' in value.hooks) {
|
|
506
|
+
const stop = value.hooks.Stop;
|
|
507
|
+
if (!Array.isArray(stop)) {
|
|
508
|
+
view.shape = 'hooks.Stop';
|
|
509
|
+
return view;
|
|
510
|
+
}
|
|
511
|
+
for (const entry of stop) {
|
|
512
|
+
if (!isObject(entry) || !Array.isArray(entry.hooks))
|
|
513
|
+
continue;
|
|
514
|
+
for (const hook of entry.hooks) {
|
|
515
|
+
const command = isObject(hook) && typeof hook.command === 'string' ? hook.command : null;
|
|
516
|
+
const ours = command === null ? null : parseManaged(command, script);
|
|
517
|
+
if (ours?.refresh) {
|
|
518
|
+
view.hook = 'ours';
|
|
519
|
+
view.bin ??= ours.bin;
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
return view;
|
|
526
|
+
}
|
|
527
|
+
/** Adds what is missing; never replaces what is there. Returns the keys it created. */
|
|
528
|
+
export function withStatusLine(value, script, entry) {
|
|
529
|
+
const created = [];
|
|
530
|
+
const status = statusCommand(script, entry);
|
|
531
|
+
const refresh = `${status} --refresh`;
|
|
532
|
+
if (isObject(value.statusLine) && typeof value.statusLine.command === 'string' && parseManaged(value.statusLine.command, script) !== null) {
|
|
533
|
+
value.statusLine.command = status;
|
|
534
|
+
}
|
|
535
|
+
else if (!('statusLine' in value)) {
|
|
536
|
+
value.statusLine = { type: 'command', command: status };
|
|
537
|
+
}
|
|
538
|
+
if (!('hooks' in value)) {
|
|
539
|
+
value.hooks = {};
|
|
540
|
+
created.push('hooks');
|
|
541
|
+
}
|
|
542
|
+
const hooks = value.hooks;
|
|
543
|
+
if (!('Stop' in hooks)) {
|
|
544
|
+
hooks.Stop = [];
|
|
545
|
+
created.push('Stop');
|
|
546
|
+
}
|
|
547
|
+
const stop = hooks.Stop;
|
|
548
|
+
let found = false;
|
|
549
|
+
for (const entryObject of stop) {
|
|
550
|
+
if (!isObject(entryObject) || !Array.isArray(entryObject.hooks))
|
|
551
|
+
continue;
|
|
552
|
+
for (const hook of entryObject.hooks) {
|
|
553
|
+
if (isObject(hook) && typeof hook.command === 'string' && parseManaged(hook.command, script)?.refresh) {
|
|
554
|
+
hook.command = refresh;
|
|
555
|
+
found = true;
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
if (!found)
|
|
560
|
+
stop.push({ matcher: '*', hooks: [{ type: 'command', command: refresh }] });
|
|
561
|
+
return created;
|
|
562
|
+
}
|
|
563
|
+
/** Removes exactly what `withStatusLine` writes, and the containers it made when they are empty. */
|
|
564
|
+
export function withoutStatusLine(value, script, created) {
|
|
565
|
+
if (isObject(value.statusLine) && typeof value.statusLine.command === 'string') {
|
|
566
|
+
const ours = parseManaged(value.statusLine.command, script);
|
|
567
|
+
if (ours !== null && !ours.refresh)
|
|
568
|
+
delete value.statusLine;
|
|
569
|
+
}
|
|
570
|
+
if (!isObject(value.hooks) || !Array.isArray(value.hooks.Stop))
|
|
571
|
+
return;
|
|
572
|
+
const hooks = value.hooks;
|
|
573
|
+
const kept = [];
|
|
574
|
+
for (const entryObject of hooks.Stop) {
|
|
575
|
+
if (!isObject(entryObject) || !Array.isArray(entryObject.hooks)) {
|
|
576
|
+
kept.push(entryObject);
|
|
577
|
+
continue;
|
|
578
|
+
}
|
|
579
|
+
const remaining = entryObject.hooks.filter((hook) => !(isObject(hook) && typeof hook.command === 'string' && parseManaged(hook.command, script)?.refresh));
|
|
580
|
+
if (remaining.length === entryObject.hooks.length) {
|
|
581
|
+
kept.push(entryObject);
|
|
582
|
+
}
|
|
583
|
+
else if (remaining.length > 0) {
|
|
584
|
+
entryObject.hooks = remaining;
|
|
585
|
+
kept.push(entryObject);
|
|
586
|
+
}
|
|
587
|
+
else if (Object.keys(entryObject).some((key) => key !== 'matcher' && key !== 'hooks')) {
|
|
588
|
+
entryObject.hooks = [];
|
|
589
|
+
kept.push(entryObject);
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
hooks.Stop = kept;
|
|
593
|
+
if (kept.length === 0 && created.includes('Stop'))
|
|
594
|
+
delete hooks.Stop;
|
|
595
|
+
if (Object.keys(hooks).length === 0 && created.includes('hooks'))
|
|
596
|
+
delete value.hooks;
|
|
597
|
+
}
|
|
598
|
+
// --------------------------------------------------------------------------
|
|
599
|
+
// Item 2: a scheduled `watch`
|
|
600
|
+
// --------------------------------------------------------------------------
|
|
601
|
+
const CRON_SCHEDULE = '17 * * * *';
|
|
602
|
+
function quoted(text, from) {
|
|
603
|
+
if (text[from] !== "'")
|
|
604
|
+
return null;
|
|
605
|
+
const end = text.indexOf("'", from + 1);
|
|
606
|
+
return end < 0 ? null : { value: text.slice(from + 1, end), end: end + 1 };
|
|
607
|
+
}
|
|
608
|
+
/** The line this writes for a project. */
|
|
609
|
+
export function cronLine(project, node, entry) {
|
|
610
|
+
return `${CRON_SCHEDULE} cd ${q(project)} && ${q(node)} ${q(entry)} watch --once ${MANAGED_MARK}`;
|
|
611
|
+
}
|
|
612
|
+
/** A line is Trazum's when it ends in the marker and has the shape `cronLine` writes. */
|
|
613
|
+
export function parseManagedLine(line) {
|
|
614
|
+
if (!line.endsWith(` ${MANAGED_MARK}`))
|
|
615
|
+
return null;
|
|
616
|
+
const fields = line.split(' ');
|
|
617
|
+
if (fields.length < 6)
|
|
618
|
+
return null;
|
|
619
|
+
const rest = fields.slice(5).join(' ');
|
|
620
|
+
if (!rest.startsWith('cd '))
|
|
621
|
+
return null;
|
|
622
|
+
const project = quoted(rest, 3);
|
|
623
|
+
if (project === null || rest.slice(project.end, project.end + 4) !== ' && ')
|
|
624
|
+
return null;
|
|
625
|
+
const node = quoted(rest, project.end + 4);
|
|
626
|
+
if (node === null || rest[node.end] !== ' ')
|
|
627
|
+
return null;
|
|
628
|
+
const entry = quoted(rest, node.end + 1);
|
|
629
|
+
if (entry === null || rest.slice(entry.end) !== ` watch --once ${MANAGED_MARK}`)
|
|
630
|
+
return null;
|
|
631
|
+
return { line, project: project.value, node: node.value, entry: entry.value };
|
|
632
|
+
}
|
|
633
|
+
const cronRows = (text) => {
|
|
634
|
+
if (text === null || text === '')
|
|
635
|
+
return { rows: [], final: true };
|
|
636
|
+
const rows = text.split('\n');
|
|
637
|
+
const final = rows[rows.length - 1] === '';
|
|
638
|
+
if (final)
|
|
639
|
+
rows.pop();
|
|
640
|
+
return { rows, final };
|
|
641
|
+
};
|
|
642
|
+
export function managedLines(text) {
|
|
643
|
+
const out = [];
|
|
644
|
+
cronRows(text).rows.forEach((line, index) => {
|
|
645
|
+
const parsed = parseManagedLine(line);
|
|
646
|
+
if (parsed !== null)
|
|
647
|
+
out.push({ index, ...parsed });
|
|
648
|
+
});
|
|
649
|
+
return out;
|
|
650
|
+
}
|
|
651
|
+
/** The crontab with this project's managed line in it, once. Every other line is untouched. */
|
|
652
|
+
export function withManagedLine(text, line, project) {
|
|
653
|
+
const { rows } = cronRows(text);
|
|
654
|
+
const at = managedLines(text).filter((found) => found.project === project);
|
|
655
|
+
if (at.length > 0) {
|
|
656
|
+
const first = at[0];
|
|
657
|
+
rows[first.index] = line;
|
|
658
|
+
const drop = new Set(at.slice(1).map((found) => found.index));
|
|
659
|
+
return `${rows.filter((_, index) => !drop.has(index)).join('\n')}\n`;
|
|
660
|
+
}
|
|
661
|
+
return `${[...rows, line].join('\n')}\n`;
|
|
662
|
+
}
|
|
663
|
+
/** The crontab without this project's managed lines. A line that only mentions trazum stays. */
|
|
664
|
+
export function withoutManagedLines(text, project) {
|
|
665
|
+
const { rows, final } = cronRows(text);
|
|
666
|
+
const drop = new Set(managedLines(text).filter((found) => found.project === project).map((found) => found.index));
|
|
667
|
+
const kept = rows.filter((_, index) => !drop.has(index));
|
|
668
|
+
return kept.length === 0 ? '' : `${kept.join('\n')}${final ? '\n' : ''}`;
|
|
669
|
+
}
|
|
670
|
+
/** What `watch` needs before it is worth scheduling: something in the store and a limit somebody chose. */
|
|
671
|
+
export async function watchReadiness(ctx) {
|
|
672
|
+
const root = resolve(ctx.cwd);
|
|
673
|
+
const { resolved } = await readStore(root);
|
|
674
|
+
let measuredUsd = null;
|
|
675
|
+
if (resolved.records.length > 0) {
|
|
676
|
+
const report = bucketedProfile({ provider: 'store', granularity: 'bucketed', buckets: bucketsFromRecords(resolved.records), window: null, gaps: [], unavailable: [] }, { catalogue: ctx.catalogue });
|
|
677
|
+
measuredUsd = report.total.totalUsd;
|
|
678
|
+
}
|
|
679
|
+
try {
|
|
680
|
+
const { config } = await loadConfig({ from: root });
|
|
681
|
+
const budget = [config.spend?.maxUsd, config.spend?.maxDayUsd, config.spend?.maxCacheLossUsd].some((v) => v !== undefined);
|
|
682
|
+
return { records: resolved.records.length, measuredUsd, budget, configError: null };
|
|
683
|
+
}
|
|
684
|
+
catch (error) {
|
|
685
|
+
return { records: resolved.records.length, measuredUsd, budget: false, configError: error.message.slice(0, 160) };
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
const verdictOf = (item, verdict, code, params, files, notes = []) => ({ item, verdict, code, params, files, notes });
|
|
689
|
+
const inspected = (s, install = null, uninstall = null) => ({
|
|
690
|
+
status: s,
|
|
691
|
+
install,
|
|
692
|
+
uninstall,
|
|
693
|
+
});
|
|
694
|
+
const NEW_FORMAT = { indent: ' ', eol: '\n', final: true };
|
|
695
|
+
function jsonChange(item, target, read, next, backup, mode = 0o644) {
|
|
696
|
+
const before = read.kind === 'ok' ? read.raw : null;
|
|
697
|
+
const format = read.kind === 'ok' ? read.format : NEW_FORMAT;
|
|
698
|
+
const after = next === null ? null : serialise(next, format);
|
|
699
|
+
const diff = diffLines(before, after);
|
|
700
|
+
// A file this command made, and never anybody's before it, has nothing to keep.
|
|
701
|
+
return { item, target, before, after, mode, added: diff.added, removed: diff.removed, backup: backup && before !== null };
|
|
702
|
+
}
|
|
703
|
+
const isFile = (path) => stat(path).then((info) => info.isFile(), () => false);
|
|
704
|
+
/**
|
|
705
|
+
* Whether the hook can start this file by its path.
|
|
706
|
+
*
|
|
707
|
+
* The status line script runs `"$TRAZUM_BIN" from-claude-code ...`: the path
|
|
708
|
+
* itself, not node with the path. A CLI that is a file and not executable makes
|
|
709
|
+
* the hook fail, and the hook is silent by design, so the line would show
|
|
710
|
+
* Claude Code's figure for ever and nothing would say why. The schedule is not
|
|
711
|
+
* asked this: its crontab line names node and then the file.
|
|
712
|
+
*/
|
|
713
|
+
const canExecute = (path) => access(path, constants.X_OK).then(() => true, () => false);
|
|
714
|
+
async function inspectStatusLine(ctx, manifest) {
|
|
715
|
+
const p = pathsFor(ctx);
|
|
716
|
+
const files = [p.settings, p.script];
|
|
717
|
+
const file = shown(ctx, p.settings);
|
|
718
|
+
if (ctx.platform === 'win32')
|
|
719
|
+
return inspected(verdictOf('statusline', 'not-available', 'statusline.windows', {}, files));
|
|
720
|
+
const read = await readJsonObject(ctx, p.settings, resolve(ctx.home));
|
|
721
|
+
if (read.kind === 'refused') {
|
|
722
|
+
return inspected(verdictOf('statusline', 'could-not-tell', read.finding.code, read.finding.params, files));
|
|
723
|
+
}
|
|
724
|
+
const claudeDir = join(resolve(ctx.home), '.claude');
|
|
725
|
+
if (read.kind === 'absent' && !(await lstat(claudeDir).then((i) => i.isDirectory(), () => false))) {
|
|
726
|
+
return inspected(verdictOf('statusline', 'not-available', 'statusline.noClaude', { dir: shown(ctx, claudeDir) }, files));
|
|
727
|
+
}
|
|
728
|
+
const value = read.kind === 'ok' ? read.value : {};
|
|
729
|
+
const view = viewSettings(value, p.script);
|
|
730
|
+
if (view.shape !== null) {
|
|
731
|
+
return inspected(verdictOf('statusline', 'could-not-tell', 'file.shape', { file, key: view.shape }, files));
|
|
732
|
+
}
|
|
733
|
+
// Turning it off does not depend on whether turning it on could.
|
|
734
|
+
const source = await ctx.script();
|
|
735
|
+
const copy = await readExisting(p.script).catch(() => ({ kind: 'other' }));
|
|
736
|
+
const scriptThere = copy.kind !== 'absent';
|
|
737
|
+
const scriptText = copy.kind === 'file' ? copy.text : null;
|
|
738
|
+
// The copy is this command's when it is what it would write now, or what it
|
|
739
|
+
// recorded writing. Anything else there is the person's: a script they
|
|
740
|
+
// changed, or a file of their own. It is not replaced and it is not removed.
|
|
741
|
+
const scriptOurs = scriptText !== null && (scriptText === source || digest(scriptText) === manifest.statusline?.script);
|
|
742
|
+
const ours = view.statusLine === 'ours' || view.hook === 'ours';
|
|
743
|
+
let uninstall = null;
|
|
744
|
+
if (ours || scriptOurs) {
|
|
745
|
+
const changes = [];
|
|
746
|
+
if (ours) {
|
|
747
|
+
const next = structuredClone(value);
|
|
748
|
+
withoutStatusLine(next, p.script, manifest.statusline?.created ?? []);
|
|
749
|
+
const gone = manifest.statusline?.createdFile === true && Object.keys(next).length === 0;
|
|
750
|
+
changes.push(jsonChange('statusline', p.settings, read, gone ? null : next, false));
|
|
751
|
+
}
|
|
752
|
+
if (scriptOurs) {
|
|
753
|
+
changes.push({ item: 'statusline', target: p.script, before: scriptText, after: null, mode: 0o755, added: [], removed: [shown(ctx, p.script)], backup: false });
|
|
754
|
+
}
|
|
755
|
+
uninstall = {
|
|
756
|
+
changes,
|
|
757
|
+
patch: (m) => {
|
|
758
|
+
delete m.statusline;
|
|
759
|
+
},
|
|
760
|
+
};
|
|
761
|
+
}
|
|
762
|
+
if (view.statusLine === 'foreign') {
|
|
763
|
+
return inspected(verdictOf('statusline', 'not-ready', 'statusline.foreign', { command: view.foreign, file, script: shown(ctx, p.script) }, files), null, uninstall);
|
|
764
|
+
}
|
|
765
|
+
const complete = view.statusLine === 'ours' && view.hook === 'ours';
|
|
766
|
+
const binGone = view.bin !== null && !((await isFile(view.bin)) && (await canExecute(view.bin)));
|
|
767
|
+
const broken = complete && (!scriptThere || binGone);
|
|
768
|
+
if (complete && !broken)
|
|
769
|
+
return inspected(verdictOf('statusline', 'on', 'statusline.on', { file }, files), null, uninstall);
|
|
770
|
+
if (scriptThere && !scriptOurs) {
|
|
771
|
+
return inspected(verdictOf('statusline', 'not-ready', 'statusline.scriptChanged', { script: shown(ctx, p.script) }, files), null, uninstall);
|
|
772
|
+
}
|
|
773
|
+
// The script's path goes into the same shell line as the CLI's, in the same
|
|
774
|
+
// quotes, and it is under the home directory: a home with a quote in its
|
|
775
|
+
// name would end the quote early.
|
|
776
|
+
if (!quotable(p.script)) {
|
|
777
|
+
return inspected(verdictOf('statusline', 'not-ready', 'cli.unsafe', { path: p.script }, files), null, uninstall);
|
|
778
|
+
}
|
|
779
|
+
const runtime = await stableRuntime(ctx);
|
|
780
|
+
if (!runtime.ok) {
|
|
781
|
+
return inspected(verdictOf('statusline', 'not-ready', runtime.code === 'unstable' ? 'cli.unstable' : 'cli.unsafe', { path: runtime.path }, files), null, uninstall);
|
|
782
|
+
}
|
|
783
|
+
if (!(await canExecute(runtime.entry))) {
|
|
784
|
+
return inspected(verdictOf('statusline', 'not-ready', 'cli.notExecutable', { path: runtime.entry }, files), null, uninstall);
|
|
785
|
+
}
|
|
786
|
+
const next = structuredClone(value);
|
|
787
|
+
const created = withStatusLine(next, p.script, runtime.entry);
|
|
788
|
+
const changes = [];
|
|
789
|
+
if (scriptText !== source) {
|
|
790
|
+
const lines = source.split('\n').length - (source.endsWith('\n') ? 1 : 0);
|
|
791
|
+
changes.push({ item: 'statusline', target: p.script, before: scriptText, after: source, mode: 0o755, added: [`${shown(ctx, p.script)} [${lines} lines]`], removed: [], backup: false });
|
|
792
|
+
}
|
|
793
|
+
const settings = jsonChange('statusline', p.settings, read, next, !(manifest.statusline?.createdFile === true), 0o600);
|
|
794
|
+
if (settings.after !== settings.before)
|
|
795
|
+
changes.push(settings);
|
|
796
|
+
const install = {
|
|
797
|
+
changes,
|
|
798
|
+
patch: (m) => {
|
|
799
|
+
const before = m.statusline;
|
|
800
|
+
m.statusline = {
|
|
801
|
+
createdFile: before?.createdFile === true || read.kind === 'absent',
|
|
802
|
+
created: [...new Set([...(before?.created ?? []), ...created])],
|
|
803
|
+
script: digest(source),
|
|
804
|
+
};
|
|
805
|
+
},
|
|
806
|
+
};
|
|
807
|
+
const code = complete ? 'statusline.stale' : ours ? 'statusline.partial' : 'statusline.off';
|
|
808
|
+
const missing = view.statusLine === 'ours' ? 'hook' : 'line';
|
|
809
|
+
const notes = read.kind === 'ok' && read.reformatted ? [{ code: 'file.reformat', params: { file } }] : [];
|
|
810
|
+
return inspected(verdictOf('statusline', 'off', code, { file, missing }, files, notes), install, uninstall);
|
|
811
|
+
}
|
|
812
|
+
/** What `watch` reports about itself when it has nothing to watch with. */
|
|
813
|
+
function readinessParams(ready) {
|
|
814
|
+
return { measured: ready.measuredUsd === null ? '' : `$${ready.measuredUsd.toFixed(2)}` };
|
|
815
|
+
}
|
|
816
|
+
async function inspectWatch(ctx) {
|
|
817
|
+
const project = resolve(ctx.cwd);
|
|
818
|
+
const files = [CRONTAB];
|
|
819
|
+
const where = shown(ctx, project);
|
|
820
|
+
if (ctx.platform === 'win32')
|
|
821
|
+
return inspected(verdictOf('watch', 'not-available', 'watch.windows', {}, files));
|
|
822
|
+
const crontab = await ctx.crontab.read();
|
|
823
|
+
if (crontab.kind === 'missing')
|
|
824
|
+
return inspected(verdictOf('watch', 'not-available', 'watch.noCrontab', {}, files));
|
|
825
|
+
if (crontab.kind === 'error')
|
|
826
|
+
return inspected(verdictOf('watch', 'could-not-tell', 'watch.crontabError', { why: crontab.message }, files));
|
|
827
|
+
const text = crontab.kind === 'ok' ? crontab.text : null;
|
|
828
|
+
const all = managedLines(text);
|
|
829
|
+
const mine = all.filter((found) => found.project === project);
|
|
830
|
+
const others = all.length - mine.length;
|
|
831
|
+
const notes = others > 0 ? [{ code: 'watch.otherProjects', params: { count: String(others) } }] : [];
|
|
832
|
+
let uninstall = null;
|
|
833
|
+
if (mine.length > 0 && text !== null) {
|
|
834
|
+
const after = withoutManagedLines(text, project);
|
|
835
|
+
const diff = diffLines(text, after);
|
|
836
|
+
uninstall = {
|
|
837
|
+
changes: [{ item: 'watch', target: CRONTAB, before: text, after, mode: 0o600, added: diff.added, removed: diff.removed, backup: false }],
|
|
838
|
+
patch: () => undefined,
|
|
839
|
+
};
|
|
840
|
+
}
|
|
841
|
+
const ready = await watchReadiness(ctx);
|
|
842
|
+
const first = mine[0];
|
|
843
|
+
const stale = first !== undefined && !((await isFile(first.node)) && (await isFile(first.entry)));
|
|
844
|
+
const scheduled = first !== undefined && !stale;
|
|
845
|
+
if (ready.configError !== null) {
|
|
846
|
+
return inspected(verdictOf('watch', 'could-not-tell', 'watch.configError', { why: ready.configError }, files, notes), null, uninstall);
|
|
847
|
+
}
|
|
848
|
+
const unready = ready.records === 0 || !ready.budget;
|
|
849
|
+
if (unready) {
|
|
850
|
+
const code = scheduled
|
|
851
|
+
? 'watch.scheduledNotReady'
|
|
852
|
+
: ready.records === 0 && !ready.budget
|
|
853
|
+
? 'watch.noStoreNoBudget'
|
|
854
|
+
: ready.records === 0
|
|
855
|
+
? 'watch.noStore'
|
|
856
|
+
: 'watch.noBudget';
|
|
857
|
+
return inspected(verdictOf('watch', 'not-ready', code, { project: where, ...readinessParams(ready) }, files, notes), null, uninstall);
|
|
858
|
+
}
|
|
859
|
+
if (scheduled) {
|
|
860
|
+
const schedule = first.line.split(' ').slice(0, 5).join(' ');
|
|
861
|
+
return inspected(verdictOf('watch', 'on', 'watch.on', { project: where, schedule }, files, notes), null, uninstall);
|
|
862
|
+
}
|
|
863
|
+
if (!quotable(project))
|
|
864
|
+
return inspected(verdictOf('watch', 'not-ready', 'cli.unsafe', { path: project }, files, notes), null, uninstall);
|
|
865
|
+
const runtime = await stableRuntime(ctx);
|
|
866
|
+
if (!runtime.ok) {
|
|
867
|
+
return inspected(verdictOf('watch', 'not-ready', runtime.code === 'unstable' ? 'cli.unstable' : 'cli.unsafe', { path: runtime.path }, files, notes), null, uninstall);
|
|
868
|
+
}
|
|
869
|
+
const after = withManagedLine(text, cronLine(project, runtime.node, runtime.entry), project);
|
|
870
|
+
const diff = diffLines(text, after);
|
|
871
|
+
const install = {
|
|
872
|
+
changes: [{ item: 'watch', target: CRONTAB, before: text, after, mode: 0o600, added: diff.added, removed: diff.removed, backup: true }],
|
|
873
|
+
patch: () => undefined,
|
|
874
|
+
};
|
|
875
|
+
return inspected(verdictOf('watch', 'off', stale ? 'watch.stale' : 'watch.off', { project: where }, files, notes), install, uninstall);
|
|
876
|
+
}
|
|
877
|
+
async function inspectMcp(ctx, manifest) {
|
|
878
|
+
const p = pathsFor(ctx);
|
|
879
|
+
const files = p.mcp.map((m) => m.path);
|
|
880
|
+
const found = [];
|
|
881
|
+
for (const target of p.mcp) {
|
|
882
|
+
const hasFile = await present(target.path);
|
|
883
|
+
const hasFolder = target.folder !== null && (await present(target.folder));
|
|
884
|
+
if (hasFile || hasFolder)
|
|
885
|
+
found.push(target);
|
|
886
|
+
}
|
|
887
|
+
if (found.length === 0) {
|
|
888
|
+
const hasClaude = await lstat(join(resolve(ctx.home), '.claude')).then((i) => i.isDirectory(), () => false);
|
|
889
|
+
return inspected(verdictOf('mcp', 'not-available', hasClaude ? 'mcp.noClientClaude' : 'mcp.noClient', { dir: shown(ctx, resolve(ctx.cwd)) }, files));
|
|
890
|
+
}
|
|
891
|
+
const rows = [];
|
|
892
|
+
for (const target of found) {
|
|
893
|
+
const read = await readJsonObject(ctx, target.path, target.dir);
|
|
894
|
+
if (read.kind === 'refused') {
|
|
895
|
+
rows.push({ path: target.path, read, state: 'absent', refused: read.finding });
|
|
896
|
+
continue;
|
|
897
|
+
}
|
|
898
|
+
const servers = read.kind === 'ok' ? read.value.mcpServers : undefined;
|
|
899
|
+
if (servers !== undefined && !isObject(servers)) {
|
|
900
|
+
rows.push({ path: target.path, read, state: 'absent', refused: { code: 'file.shape', params: { file: shown(ctx, target.path), key: 'mcpServers' } } });
|
|
901
|
+
continue;
|
|
902
|
+
}
|
|
903
|
+
const entry = servers?.trazum;
|
|
904
|
+
rows.push({ path: target.path, read, state: entry === undefined ? 'absent' : deepEqual(entry, MCP_ENTRY) ? 'ours' : 'other', refused: null });
|
|
905
|
+
}
|
|
906
|
+
const notes = [];
|
|
907
|
+
const uninstallChanges = [];
|
|
908
|
+
const removedFrom = [];
|
|
909
|
+
const installChanges = [];
|
|
910
|
+
const addedTo = {};
|
|
911
|
+
for (const row of rows) {
|
|
912
|
+
const name = shown(ctx, row.path);
|
|
913
|
+
if (row.refused !== null) {
|
|
914
|
+
notes.push(row.refused);
|
|
915
|
+
continue;
|
|
916
|
+
}
|
|
917
|
+
const record = manifest.mcp?.[row.path];
|
|
918
|
+
if (row.state === 'absent') {
|
|
919
|
+
const next = row.read.kind === 'ok' ? structuredClone(row.read.value) : {};
|
|
920
|
+
const createdKey = !('mcpServers' in next);
|
|
921
|
+
if (createdKey)
|
|
922
|
+
next.mcpServers = {};
|
|
923
|
+
next.mcpServers.trazum = structuredClone(MCP_ENTRY);
|
|
924
|
+
installChanges.push(jsonChange('mcp', row.path, row.read, next, true));
|
|
925
|
+
if (row.read.kind === 'ok' && row.read.reformatted)
|
|
926
|
+
notes.push({ code: 'file.reformat', params: { file: name } });
|
|
927
|
+
addedTo[row.path] = { createdFile: row.read.kind === 'absent', createdKey };
|
|
928
|
+
}
|
|
929
|
+
else if (row.state === 'other') {
|
|
930
|
+
notes.push({ code: record === undefined ? 'mcp.other' : 'mcp.changed', params: { file: name } });
|
|
931
|
+
}
|
|
932
|
+
else if (record === undefined) {
|
|
933
|
+
// Exactly the entry this writes, put there by somebody else: theirs to remove.
|
|
934
|
+
notes.push({ code: 'mcp.notAdded', params: { file: name } });
|
|
935
|
+
}
|
|
936
|
+
else if (row.read.kind === 'ok') {
|
|
937
|
+
const next = structuredClone(row.read.value);
|
|
938
|
+
const servers = next.mcpServers;
|
|
939
|
+
delete servers.trazum;
|
|
940
|
+
if (Object.keys(servers).length === 0 && record.createdKey)
|
|
941
|
+
delete next.mcpServers;
|
|
942
|
+
const gone = record.createdFile && Object.keys(next).length === 0;
|
|
943
|
+
uninstallChanges.push(jsonChange('mcp', row.path, row.read, gone ? null : next, false));
|
|
944
|
+
removedFrom.push(row.path);
|
|
945
|
+
}
|
|
946
|
+
}
|
|
947
|
+
const uninstall = uninstallChanges.length === 0
|
|
948
|
+
? null
|
|
949
|
+
: {
|
|
950
|
+
changes: uninstallChanges,
|
|
951
|
+
patch: (m) => {
|
|
952
|
+
for (const path of removedFrom)
|
|
953
|
+
if (m.mcp !== undefined)
|
|
954
|
+
delete m.mcp[path];
|
|
955
|
+
if (m.mcp !== undefined && Object.keys(m.mcp).length === 0)
|
|
956
|
+
delete m.mcp;
|
|
957
|
+
},
|
|
958
|
+
};
|
|
959
|
+
const install = installChanges.length === 0
|
|
960
|
+
? null
|
|
961
|
+
: {
|
|
962
|
+
changes: installChanges,
|
|
963
|
+
patch: (m) => {
|
|
964
|
+
m.mcp = { ...(m.mcp ?? {}), ...addedTo };
|
|
965
|
+
},
|
|
966
|
+
};
|
|
967
|
+
const open = installChanges.map((change) => shown(ctx, change.target)).join(', ');
|
|
968
|
+
if (install !== null)
|
|
969
|
+
return inspected(verdictOf('mcp', 'off', 'mcp.off', { files: open }, files, notes), install, uninstall);
|
|
970
|
+
const refused = rows.find((row) => row.refused !== null)?.refused ?? null;
|
|
971
|
+
if (refused !== null) {
|
|
972
|
+
return inspected(verdictOf('mcp', 'could-not-tell', refused.code, refused.params, files, notes.filter((n) => n !== refused)), null, uninstall);
|
|
973
|
+
}
|
|
974
|
+
return inspected(verdictOf('mcp', 'on', 'mcp.on', { files: rows.map((row) => shown(ctx, row.path)).join(', ') }, files, notes), null, uninstall);
|
|
975
|
+
}
|
|
976
|
+
export async function inspectAll(ctx) {
|
|
977
|
+
const manifestRead = await readJsonObject(ctx, pathsFor(ctx).manifest, resolve(ctx.home));
|
|
978
|
+
const manifest = manifestRead.kind === 'ok' ? manifestFrom(manifestRead.value) : emptyManifest();
|
|
979
|
+
const items = {
|
|
980
|
+
statusline: await inspectStatusLine(ctx, manifest),
|
|
981
|
+
watch: await inspectWatch(ctx),
|
|
982
|
+
mcp: await inspectMcp(ctx, manifest),
|
|
983
|
+
};
|
|
984
|
+
return { items, manifest, manifestRead, blocked: manifestRead.kind === 'refused' ? manifestRead.finding : null };
|
|
985
|
+
}
|
|
986
|
+
// --------------------------------------------------------------------------
|
|
987
|
+
// Doing it
|
|
988
|
+
// --------------------------------------------------------------------------
|
|
989
|
+
/**
|
|
990
|
+
* Puts back what an item wrote before it failed, newest first, through the
|
|
991
|
+
* same door it was written by. Returns the targets it could not put back.
|
|
992
|
+
*
|
|
993
|
+
* An item is several writes: two MCP files, or the script and the settings,
|
|
994
|
+
* and then the record of what was added. Written half, it leaves an entry no
|
|
995
|
+
* record claims, which `off` would then take for the person's and never
|
|
996
|
+
* remove.
|
|
997
|
+
*/
|
|
998
|
+
export async function undo(ctx, applied) {
|
|
999
|
+
const left = [];
|
|
1000
|
+
for (const change of [...applied].reverse()) {
|
|
1001
|
+
try {
|
|
1002
|
+
await applyChange(ctx, { ...change, before: change.after, after: change.before, added: [], removed: [], backup: false });
|
|
1003
|
+
}
|
|
1004
|
+
catch {
|
|
1005
|
+
left.push(change.target);
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
return left;
|
|
1009
|
+
}
|
|
1010
|
+
function failure(ctx, error) {
|
|
1011
|
+
if (error instanceof RefusedWrite) {
|
|
1012
|
+
return {
|
|
1013
|
+
code: `write.${error.reason}`,
|
|
1014
|
+
params: { file: shown(ctx, error.target), allowed: error.allowed.map((entry) => shown(ctx, entry)).join(', ') },
|
|
1015
|
+
};
|
|
1016
|
+
}
|
|
1017
|
+
return { code: 'write.failed', params: { why: error.message.slice(0, 200) } };
|
|
1018
|
+
}
|
|
1019
|
+
/**
|
|
1020
|
+
* Turns the chosen items on or off, one item at a time, each only on a yes.
|
|
1021
|
+
*
|
|
1022
|
+
* Returns the statuses before, what each item did, and the statuses after,
|
|
1023
|
+
* read again from the disk rather than assumed.
|
|
1024
|
+
*/
|
|
1025
|
+
export async function run(ctx, options) {
|
|
1026
|
+
const p = pathsFor(ctx);
|
|
1027
|
+
let current = await inspectAll(ctx);
|
|
1028
|
+
const before = ITEMS.map((item) => current.items[item].status);
|
|
1029
|
+
const results = [];
|
|
1030
|
+
for (const item of options.items) {
|
|
1031
|
+
const plan = options.action === 'on' ? current.items[item].install : current.items[item].uninstall;
|
|
1032
|
+
const shownChanges = (plan?.changes ?? []).map((c) => ({ target: c.target, added: c.added, removed: c.removed }));
|
|
1033
|
+
if (plan === null || plan.changes.length === 0) {
|
|
1034
|
+
results.push({ item, outcome: 'nothing', changes: [], error: null });
|
|
1035
|
+
continue;
|
|
1036
|
+
}
|
|
1037
|
+
if (current.blocked !== null) {
|
|
1038
|
+
results.push({ item, outcome: 'failed', changes: shownChanges, error: current.blocked });
|
|
1039
|
+
continue;
|
|
1040
|
+
}
|
|
1041
|
+
if (options.dryRun) {
|
|
1042
|
+
results.push({ item, outcome: 'would-write', changes: shownChanges, error: null });
|
|
1043
|
+
continue;
|
|
1044
|
+
}
|
|
1045
|
+
if (!(await options.decide(item, plan.changes))) {
|
|
1046
|
+
results.push({ item, outcome: 'declined', changes: shownChanges, error: null });
|
|
1047
|
+
continue;
|
|
1048
|
+
}
|
|
1049
|
+
const applied = [];
|
|
1050
|
+
try {
|
|
1051
|
+
for (const change of plan.changes) {
|
|
1052
|
+
await applyChange(ctx, change);
|
|
1053
|
+
applied.push(change);
|
|
1054
|
+
}
|
|
1055
|
+
// The manifest follows the files it describes, and goes when nothing is left to describe.
|
|
1056
|
+
const next = structuredClone(current.manifest);
|
|
1057
|
+
plan.patch(next);
|
|
1058
|
+
const text = manifestEmpty(next) ? null : `${JSON.stringify(next, null, 2)}\n`;
|
|
1059
|
+
const was = current.manifestRead.kind === 'ok' ? current.manifestRead.raw : null;
|
|
1060
|
+
if (text !== was) {
|
|
1061
|
+
await applyChange(ctx, { item: 'manifest', target: p.manifest, before: was, after: text, mode: 0o600, added: [], removed: [], backup: false });
|
|
1062
|
+
}
|
|
1063
|
+
if (options.action === 'off') {
|
|
1064
|
+
await removeEmptyDir(ctx, p.scriptDir);
|
|
1065
|
+
await removeEmptyDir(ctx, p.stateDir);
|
|
1066
|
+
}
|
|
1067
|
+
results.push({ item, outcome: 'written', changes: shownChanges, error: null });
|
|
1068
|
+
}
|
|
1069
|
+
catch (error) {
|
|
1070
|
+
const left = await undo(ctx, applied);
|
|
1071
|
+
const finding = left.length === 0 ? failure(ctx, error) : { code: 'write.partial', params: { files: left.map((target) => (target === CRONTAB ? CRONTAB : shown(ctx, target))).join(', ') } };
|
|
1072
|
+
results.push({ item, outcome: 'failed', changes: shownChanges, error: finding });
|
|
1073
|
+
}
|
|
1074
|
+
// The next item plans against what is on disk now.
|
|
1075
|
+
current = await inspectAll(ctx);
|
|
1076
|
+
}
|
|
1077
|
+
return { before, results, after: ITEMS.map((item) => current.items[item].status) };
|
|
1078
|
+
}
|
|
1079
|
+
//# sourceMappingURL=proactive.js.map
|