@trazum/cli 2.5.2 → 2.6.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/dist/filter.d.ts.map +1 -1
- package/dist/filter.js +43 -7
- package/dist/filter.js.map +1 -1
- package/dist/i18n/en.d.ts.map +1 -1
- package/dist/i18n/en.js +16 -0
- package/dist/i18n/en.js.map +1 -1
- package/dist/i18n/es.d.ts.map +1 -1
- package/dist/i18n/es.js +16 -0
- package/dist/i18n/es.js.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -1
- package/dist/index.js.map +1 -1
- package/dist/serve-import-schema.d.ts +34 -0
- package/dist/serve-import-schema.d.ts.map +1 -0
- package/dist/serve-import-schema.js +31 -0
- package/dist/serve-import-schema.js.map +1 -0
- package/dist/serve-import.d.ts +43 -0
- package/dist/serve-import.d.ts.map +1 -0
- package/dist/serve-import.js +49 -0
- package/dist/serve-import.js.map +1 -0
- package/dist/serve-schema.d.ts +70 -0
- package/dist/serve-schema.d.ts.map +1 -1
- package/dist/serve-schema.js +8 -0
- package/dist/serve-schema.js.map +1 -1
- package/dist/serve.d.ts.map +1 -1
- package/dist/serve.js +9 -2
- package/dist/serve.js.map +1 -1
- package/dist/task-files.d.ts +9 -0
- package/dist/task-files.d.ts.map +1 -0
- package/dist/task-files.js +136 -0
- package/dist/task-files.js.map +1 -0
- package/dist/task.d.ts +2 -0
- package/dist/task.d.ts.map +1 -0
- package/dist/task.js +137 -0
- package/dist/task.js.map +1 -0
- package/package.json +2 -2
- package/src/filter.ts +46 -10
- package/src/i18n/en.ts +16 -0
- package/src/i18n/es.ts +16 -0
- package/src/index.ts +8 -1
- package/src/serve-import-schema.ts +31 -0
- package/src/serve-import.ts +57 -0
- package/src/serve-schema.ts +8 -0
- package/src/serve.ts +9 -2
- package/src/task-files.ts +114 -0
- package/src/task.ts +119 -0
package/dist/task.js
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { analyzeTask, compareTasks, parseTaskReport, taskPolicy, MAX_INPUT_CHARS } from '@trazum/core';
|
|
2
|
+
import { changeTaskInstructions, readTaskText, writeTaskText } from './task-files.js';
|
|
3
|
+
const HELP = `Usage:
|
|
4
|
+
trazum task analyze --id <id> --type <type> --criterion <text>
|
|
5
|
+
--claude-code <file> [--codex <file>] [--claude-code <file> ...]
|
|
6
|
+
[--outcome accepted|rejected|unknown --assessor <label>]
|
|
7
|
+
[--policy baseline|repeat-review-v1] [-o <new-report.json>]
|
|
8
|
+
trazum task policy <report.json> [-o <new-policy.md>]
|
|
9
|
+
trazum task apply <report.json> --instructions <existing-file>
|
|
10
|
+
trazum task revert --instructions <existing-file>
|
|
11
|
+
trazum task compare <before.json> <after.json> [-o <new-comparison.json>]
|
|
12
|
+
|
|
13
|
+
Analyze explicit, complete task sources from Claude Code and Codex locally.
|
|
14
|
+
Repeat the source flags to include sessions from both harnesses. No home scan,
|
|
15
|
+
network access, provider call, hook installation or command execution occurs.
|
|
16
|
+
Up to 16 sources and ${MAX_INPUT_CHARS} characters combined. Do not split one
|
|
17
|
+
session across sources or import the same session more than once.
|
|
18
|
+
Reports and comparisons are JSON by default (--json is also accepted).
|
|
19
|
+
Outcome and assessor are caller declarations, never inferred from usage.
|
|
20
|
+
Policy application adds a small, optional managed block to the file you choose.
|
|
21
|
+
Review the diff and run a comparable task yourself before comparing reports.
|
|
22
|
+
Revert removes only the exact unchanged block. Close other editors while applying
|
|
23
|
+
or reverting. Existing output reports are never overwritten; new files use 0600.
|
|
24
|
+
Repeated tool results may be intentional. A paired comparison is an observation,
|
|
25
|
+
not proof of causal savings, task quality or remaining subscription allowance.
|
|
26
|
+
`;
|
|
27
|
+
const ALLOWED = {
|
|
28
|
+
analyze: ['id', 'type', 'criterion', 'outcome', 'assessor', 'policy', 'claude-code', 'codex', 'out', 'json'],
|
|
29
|
+
policy: ['out'],
|
|
30
|
+
apply: ['instructions'],
|
|
31
|
+
revert: ['instructions'],
|
|
32
|
+
compare: ['out', 'json'],
|
|
33
|
+
};
|
|
34
|
+
function parse(action, args) {
|
|
35
|
+
const allowed = ALLOWED[action];
|
|
36
|
+
if (!allowed)
|
|
37
|
+
throw new Error('Unknown task action. Run trazum task --help.');
|
|
38
|
+
const flags = new Map();
|
|
39
|
+
const sources = [];
|
|
40
|
+
const paths = [];
|
|
41
|
+
for (let index = 0; index < args.length; index++) {
|
|
42
|
+
const arg = args[index];
|
|
43
|
+
if (!arg.startsWith('-')) {
|
|
44
|
+
paths.push(arg);
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
const name = arg === '-o' ? 'out' : arg.startsWith('--') ? arg.slice(2) : '';
|
|
48
|
+
if (!allowed.includes(name))
|
|
49
|
+
throw new Error('Unsupported task option. Run trazum task --help.');
|
|
50
|
+
if (flags.has(name))
|
|
51
|
+
throw new Error('Task options cannot be repeated except source flags.');
|
|
52
|
+
if (name === 'json') {
|
|
53
|
+
flags.set(name, 'true');
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
const value = args[++index];
|
|
57
|
+
if (value === undefined || value.trim() === '' || value.startsWith('-'))
|
|
58
|
+
throw new Error('A task option is missing its value.');
|
|
59
|
+
if (name === 'claude-code' || name === 'codex') {
|
|
60
|
+
sources.push({ format: name, path: value });
|
|
61
|
+
if (sources.length > 16)
|
|
62
|
+
throw new Error('At most 16 task sources are accepted.');
|
|
63
|
+
}
|
|
64
|
+
else
|
|
65
|
+
flags.set(name, value);
|
|
66
|
+
}
|
|
67
|
+
return { flags, sources, paths };
|
|
68
|
+
}
|
|
69
|
+
function required(flags, name) {
|
|
70
|
+
const value = flags.get(name);
|
|
71
|
+
if (value === undefined)
|
|
72
|
+
throw new Error(`Missing --${name}. Run trazum task --help.`);
|
|
73
|
+
return value;
|
|
74
|
+
}
|
|
75
|
+
async function emit(value, output) {
|
|
76
|
+
let text = `${typeof value === 'string' ? value : JSON.stringify(value, null, 2)}\n`;
|
|
77
|
+
if (text.length > MAX_INPUT_CHARS && typeof value !== 'string')
|
|
78
|
+
text = `${JSON.stringify(value)}\n`;
|
|
79
|
+
if (text.length > MAX_INPUT_CHARS)
|
|
80
|
+
throw new Error('Task output exceeds the report limit; use a smaller complete task source.');
|
|
81
|
+
if (output !== undefined)
|
|
82
|
+
await writeTaskText(output, text);
|
|
83
|
+
else
|
|
84
|
+
process.stdout.write(text);
|
|
85
|
+
}
|
|
86
|
+
export async function runTask(args) {
|
|
87
|
+
if (args.length === 0 || (args.length === 1 && ['--help', '-h'].includes(args[0])) ||
|
|
88
|
+
(args.length === 2 && Object.hasOwn(ALLOWED, args[0]) && ['--help', '-h'].includes(args[1]))) {
|
|
89
|
+
process.stdout.write(HELP);
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
const action = args[0];
|
|
93
|
+
const { flags, sources, paths } = parse(action, args.slice(1));
|
|
94
|
+
const expectedPaths = action === 'compare' ? 2 : action === 'policy' || action === 'apply' ? 1 : 0;
|
|
95
|
+
if (paths.length !== expectedPaths)
|
|
96
|
+
throw new Error('Wrong number of task input files. Run trazum task --help.');
|
|
97
|
+
if (action === 'analyze') {
|
|
98
|
+
const taskId = required(flags, 'id');
|
|
99
|
+
const taskType = required(flags, 'type');
|
|
100
|
+
const criterion = required(flags, 'criterion');
|
|
101
|
+
if (sources.length === 0)
|
|
102
|
+
throw new Error('Provide at least one --claude-code or --codex file.');
|
|
103
|
+
const contents = [];
|
|
104
|
+
let total = 0;
|
|
105
|
+
for (const source of sources) {
|
|
106
|
+
const text = await readTaskText(source.path, MAX_INPUT_CHARS - total);
|
|
107
|
+
total += text.length;
|
|
108
|
+
contents.push({ format: source.format, text });
|
|
109
|
+
}
|
|
110
|
+
const report = analyzeTask({ taskId, taskType, criterion, sources: contents,
|
|
111
|
+
...(flags.has('outcome') ? { outcome: flags.get('outcome') } : {}),
|
|
112
|
+
...(flags.has('assessor') ? { assessor: flags.get('assessor') } : {}),
|
|
113
|
+
...(flags.has('policy') ? { policyId: flags.get('policy') } : {}),
|
|
114
|
+
});
|
|
115
|
+
await emit(report, flags.get('out'));
|
|
116
|
+
}
|
|
117
|
+
else if (action === 'compare') {
|
|
118
|
+
const before = parseTaskReport(await readTaskText(paths[0]));
|
|
119
|
+
const after = parseTaskReport(await readTaskText(paths[1]));
|
|
120
|
+
await emit(compareTasks(before, after), flags.get('out'));
|
|
121
|
+
}
|
|
122
|
+
else if (action === 'policy' || action === 'apply') {
|
|
123
|
+
const report = parseTaskReport(await readTaskText(paths[0]));
|
|
124
|
+
const policy = taskPolicy(report);
|
|
125
|
+
if (action === 'policy')
|
|
126
|
+
await emit(policy.instructions, flags.get('out'));
|
|
127
|
+
else {
|
|
128
|
+
const changed = await changeTaskInstructions(required(flags, 'instructions'), 'apply');
|
|
129
|
+
await emit({ version: 1, kind: 'trazum-task-policy', policyId: policy.id, applied: true, changed });
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
else if (action === 'revert') {
|
|
133
|
+
const changed = await changeTaskInstructions(required(flags, 'instructions'), 'revert');
|
|
134
|
+
await emit({ version: 1, kind: 'trazum-task-policy', policyId: 'repeat-review-v1', applied: false, changed });
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
//# sourceMappingURL=task.js.map
|
package/dist/task.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"task.js","sourceRoot":"","sources":["../src/task.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,eAAe,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AACvG,OAAO,EAAE,sBAAsB,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAEtF,MAAM,IAAI,GAAG;;;;;;;;;;;;;uBAaU,eAAe;;;;;;;;;;CAUrC,CAAC;AAGF,MAAM,OAAO,GAAsC;IACjD,OAAO,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,SAAS,EAAE,UAAU,E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AoB,EAAE,QAAQ,EAAE,MAAM,CAAC,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,CAAC;QACtG,CAAC;IACH,CAAC;SAAM,IAAI,MAAM,KAAK,QAAQ,EAAE,CAAC;QAC/B,MAAM,OAAO,GAAG,MAAM,sBAAsB,CAAC,QAAQ,CAAC,KAAK,EAAE,cAAc,CAAC,EAAE,QAAQ,CAAC,CAAC;QACxF,MAAM,IAAI,CAAC,EAAE,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,oBAAoB,EAAE,QAAQ,EAAE,kBAAkB,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC;IAChH,CAAC;AACH,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@trazum/cli",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.6.0",
|
|
4
4
|
"description": "What your AI agents cost, per project, offline: prices Claude Code sessions and Anthropic, OpenAI, OpenRouter, OTel and LiteLLM usage, writes the bill as PDF, HTML or CSV, and enforces budgets in CI.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "David Mu\u00f1oz Rey",
|
|
@@ -50,7 +50,7 @@
|
|
|
50
50
|
"prepublishOnly": "npm run build && npm test"
|
|
51
51
|
},
|
|
52
52
|
"dependencies": {
|
|
53
|
-
"@trazum/core": "2.
|
|
53
|
+
"@trazum/core": "2.6.0"
|
|
54
54
|
},
|
|
55
55
|
"devDependencies": {
|
|
56
56
|
"@types/node": "^26.6.3",
|
package/src/filter.ts
CHANGED
|
@@ -4,11 +4,11 @@ import { mkdir, lstat, open } from 'node:fs/promises';
|
|
|
4
4
|
import { createHash } from 'node:crypto';
|
|
5
5
|
import { resolve, join } from 'node:path';
|
|
6
6
|
import { once } from 'node:events';
|
|
7
|
-
import { compactToolOutput, EFFICIENT_OUTPUT_INSTRUCTIONS } from '@trazum/core';
|
|
7
|
+
import { compactToolOutput, EFFICIENT_OUTPUT_INSTRUCTIONS, type ToolOutputView } from '@trazum/core';
|
|
8
8
|
|
|
9
9
|
const MAX_BYTES = 1024 * 1024;
|
|
10
10
|
const HELP = `Usage:
|
|
11
|
-
trazum filter compact --recovery-dir <private-directory>
|
|
11
|
+
trazum filter compact --recovery-dir <private-directory> [--stats]
|
|
12
12
|
trazum filter restore <sha256> --recovery-dir <private-directory>
|
|
13
13
|
trazum filter instructions print optional output guidance
|
|
14
14
|
|
|
@@ -18,8 +18,25 @@ Use Bash pipefail to preserve the producing command's failure status.
|
|
|
18
18
|
Original logs may contain sensitive data: --recovery-dir explicitly opts into local
|
|
19
19
|
retention. Delete that directory when the originals are no longer needed.
|
|
20
20
|
Token counts are estimates, not billing or subscription-quota measurements.
|
|
21
|
+
--stats writes one JSON record to stderr, without log content or recovery paths.
|
|
21
22
|
`;
|
|
22
23
|
|
|
24
|
+
/** Report only the view actually emitted, including recovery-instruction overhead. */
|
|
25
|
+
function reportStats(inputBytes: number, outputBytes: number, view: ToolOutputView | null,
|
|
26
|
+
reason: string, applied = false): void {
|
|
27
|
+
const before = view?.estimatedTokensBefore ?? null;
|
|
28
|
+
const after = applied ? view?.estimatedTokensAfter ?? null : before;
|
|
29
|
+
const saved = before === null || after === null ? null : before - after;
|
|
30
|
+
process.stderr.write(`${JSON.stringify({
|
|
31
|
+
schemaVersion: 1, kind: 'trazum-tool-filter', estimateOnly: true, applied, reason,
|
|
32
|
+
inputBytes, outputBytes, estimatedTokensBefore: before, estimatedTokensAfter: after,
|
|
33
|
+
estimatedTokensSaved: saved,
|
|
34
|
+
estimatedReductionPercent: saved === null || before === null ? null
|
|
35
|
+
: before === 0 ? 0 : Math.round(saved / before * 10000) / 100,
|
|
36
|
+
repeatedLines: applied ? view?.repeatedLines ?? 0 : 0,
|
|
37
|
+
})}\n`);
|
|
38
|
+
}
|
|
39
|
+
|
|
23
40
|
const digest = (bytes: Buffer) => createHash('sha256').update(bytes).digest('hex');
|
|
24
41
|
const quote = (text: string) => `'${text.replaceAll("'", "'\\''")}'`;
|
|
25
42
|
async function emit(bytes: Buffer | string): Promise<void> {
|
|
@@ -34,7 +51,8 @@ async function privateDirectory(path: string, create: boolean): Promise<void> {
|
|
|
34
51
|
}
|
|
35
52
|
}
|
|
36
53
|
async function readOriginal(store: string, key: string): Promise<Buffer> {
|
|
37
|
-
|
|
54
|
+
// Opening a FIFO must not block before the regular-file check can reject it.
|
|
55
|
+
const file = await open(join(store, `${key}.log`), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
38
56
|
try {
|
|
39
57
|
const stat = await file.stat();
|
|
40
58
|
if (!stat.isFile() || stat.size > MAX_BYTES) throw new Error('Invalid recovery file.');
|
|
@@ -56,14 +74,14 @@ async function saveOriginal(store: string, key: string, bytes: Buffer): Promise<
|
|
|
56
74
|
try { await file.writeFile(bytes); await file.sync(); }
|
|
57
75
|
finally { await file.close(); }
|
|
58
76
|
}
|
|
59
|
-
async function compact(store: string): Promise<void> {
|
|
77
|
+
async function compact(store: string, stats: boolean): Promise<void> {
|
|
60
78
|
const chunks: Buffer[] = [];
|
|
61
79
|
let size = 0;
|
|
62
80
|
let passthrough = false;
|
|
63
81
|
for await (const value of process.stdin) {
|
|
64
82
|
const chunk = Buffer.isBuffer(value) ? value : Buffer.from(value);
|
|
65
|
-
if (passthrough) { await emit(chunk); continue; }
|
|
66
83
|
size += chunk.length;
|
|
84
|
+
if (passthrough) { await emit(chunk); continue; }
|
|
67
85
|
if (size > MAX_BYTES) {
|
|
68
86
|
passthrough = true;
|
|
69
87
|
for (const buffered of chunks) await emit(buffered);
|
|
@@ -71,24 +89,42 @@ async function compact(store: string): Promise<void> {
|
|
|
71
89
|
await emit(chunk);
|
|
72
90
|
} else { chunks.push(chunk); }
|
|
73
91
|
}
|
|
74
|
-
if (passthrough)
|
|
92
|
+
if (passthrough) {
|
|
93
|
+
if (stats) reportStats(size, size, null, 'stream-limit');
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
75
96
|
const bytes = Buffer.concat(chunks);
|
|
76
97
|
const input = bytes.toString('utf8');
|
|
77
98
|
// Invalid UTF-8 must pass byte-for-byte rather than acquire replacement chars.
|
|
78
|
-
if (!Buffer.from(input).equals(bytes)) {
|
|
99
|
+
if (!Buffer.from(input).equals(bytes)) {
|
|
100
|
+
await emit(bytes);
|
|
101
|
+
if (stats) reportStats(size, size, null, 'invalid-utf8');
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
79
104
|
const key = digest(bytes);
|
|
80
105
|
const view = compactToolOutput(input, `trazum filter restore ${key} --recovery-dir ${quote(store)}`);
|
|
81
|
-
if (!view.applied) {
|
|
106
|
+
if (!view.applied) {
|
|
107
|
+
await emit(bytes);
|
|
108
|
+
if (stats) reportStats(size, size, view, view.reason);
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
82
111
|
try { await saveOriginal(store, key, bytes); }
|
|
83
112
|
catch {
|
|
84
113
|
// A filter must not swallow a tool's output because local persistence failed.
|
|
85
|
-
process.stderr.write('Trazum: original could not be retained; passing log through unchanged.\n');
|
|
114
|
+
if (!stats) process.stderr.write('Trazum: original could not be retained; passing log through unchanged.\n');
|
|
86
115
|
await emit(bytes);
|
|
116
|
+
if (stats) reportStats(size, size, view, 'storage-failed');
|
|
87
117
|
return;
|
|
88
118
|
}
|
|
89
119
|
await emit(view.text);
|
|
120
|
+
if (stats) reportStats(size, Buffer.byteLength(view.text), view, view.reason, true);
|
|
90
121
|
}
|
|
91
122
|
export async function runFilter(args: string[]): Promise<void> {
|
|
123
|
+
let stats = false;
|
|
124
|
+
if (args[0] === 'compact' && args.length === 4) {
|
|
125
|
+
const index = args[1] === '--stats' ? 1 : args[3] === '--stats' ? 3 : -1;
|
|
126
|
+
if (index !== -1) { stats = true; args = args.filter((_, i) => i !== index); }
|
|
127
|
+
}
|
|
92
128
|
if (args.length === 0 || (args.length === 1 && ['--help', '-h'].includes(args[0]!))) {
|
|
93
129
|
await emit(HELP); return;
|
|
94
130
|
}
|
|
@@ -109,6 +145,6 @@ export async function runFilter(args: string[]): Promise<void> {
|
|
|
109
145
|
await emit(await readOriginal(store, key));
|
|
110
146
|
} else {
|
|
111
147
|
if (process.stdin.isTTY) throw new Error('Pipe a tool log into stdin; interactive tools are not supported.');
|
|
112
|
-
await compact(store);
|
|
148
|
+
await compact(store, stats);
|
|
113
149
|
}
|
|
114
150
|
}
|
package/src/i18n/en.ts
CHANGED
|
@@ -89,6 +89,7 @@ ${bold('USAGE')}
|
|
|
89
89
|
trazum ladder <log>
|
|
90
90
|
trazum feedback
|
|
91
91
|
trazum filter compact|restore|instructions [--recovery-dir <directory>]
|
|
92
|
+
trazum task analyze|policy|apply|revert|compare [--help]
|
|
92
93
|
trazum --version
|
|
93
94
|
|
|
94
95
|
${bold('OPTIONS FOR init')}
|
|
@@ -428,8 +429,23 @@ ${bold('OPTIONS FOR rules')}
|
|
|
428
429
|
"Inert" is always said about the corpus. A rule that finds nothing in these
|
|
429
430
|
files has not been shown to find nothing anywhere.
|
|
430
431
|
|
|
432
|
+
${bold('OPTIONS FOR task')}
|
|
433
|
+
--id <id> --type <type> Identify a task and its comparable task type.
|
|
434
|
+
--criterion <text> Declare the acceptance criterion before a change.
|
|
435
|
+
--claude-code <file> Add an explicit Claude Code task transcript; repeatable.
|
|
436
|
+
--codex <file> Add an explicit Codex task transcript; repeatable.
|
|
437
|
+
--outcome <value> accepted, rejected or unknown (default unknown).
|
|
438
|
+
--assessor <label> Required for a declared accepted or rejected outcome.
|
|
439
|
+
--policy <id> baseline (default) or repeat-review-v1.
|
|
440
|
+
--instructions <file> Existing local instruction file for apply or revert.
|
|
441
|
+
-o, --out <new-file> Create a private report or policy; never overwrite.
|
|
442
|
+
--json Reports and comparisons are already JSON by default.
|
|
443
|
+
Run task --help for analyze, policy, apply, revert and compare syntax.
|
|
444
|
+
Sources total at most 400,000 characters. Task success is never inferred.
|
|
445
|
+
|
|
431
446
|
${bold('OPTIONS FOR filter')}
|
|
432
447
|
--recovery-dir <directory> Private recovery directory; required for compact/restore.
|
|
448
|
+
--stats Compact only: emit net estimated savings as JSON on stderr.
|
|
433
449
|
Run trazum filter --help for the opt-in stdin log-filter workflow.
|
|
434
450
|
|
|
435
451
|
${bold('OPTIONS FOR feedback')}
|
package/src/i18n/es.ts
CHANGED
|
@@ -76,6 +76,7 @@ ${bold('USO')}
|
|
|
76
76
|
trazum ladder <log>
|
|
77
77
|
trazum feedback
|
|
78
78
|
trazum filter compact|restore|instructions [--recovery-dir <directory>]
|
|
79
|
+
trazum task analyze|policy|apply|revert|compare [--help]
|
|
79
80
|
trazum --version
|
|
80
81
|
|
|
81
82
|
${bold('OPCIONES DE init')}
|
|
@@ -432,8 +433,23 @@ ${bold('OPCIONES DE rules')}
|
|
|
432
433
|
"Inerte" se dice siempre sobre el corpus. Una regla que no encuentra nada en
|
|
433
434
|
estos ficheros no ha demostrado no encontrar nada en ninguna parte.
|
|
434
435
|
|
|
436
|
+
${bold('OPCIONES DE task')}
|
|
437
|
+
--id <id> --type <tipo> Identifica una tarea y su tipo comparable.
|
|
438
|
+
--criterion <texto> Declara el criterio de aceptación antes del cambio.
|
|
439
|
+
--claude-code <archivo> Añade una sesión explícita de Claude Code; repetible.
|
|
440
|
+
--codex <archivo> Añade una sesión explícita de Codex; repetible.
|
|
441
|
+
--outcome <valor> accepted, rejected o unknown (por defecto unknown).
|
|
442
|
+
--assessor <etiqueta> Obligatorio para un resultado accepted o rejected.
|
|
443
|
+
--policy <id> baseline (por defecto) o repeat-review-v1.
|
|
444
|
+
--instructions <archivo> Archivo local existente para apply o revert.
|
|
445
|
+
-o, --out <archivo-nuevo> Crea un informe o política privados; no sobrescribe.
|
|
446
|
+
--json Los informes y comparaciones ya usan JSON por defecto.
|
|
447
|
+
Consulta task --help para analyze, policy, apply, revert y compare.
|
|
448
|
+
Máximo 400.000 caracteres entre fuentes. Nunca se infiere el éxito de la tarea.
|
|
449
|
+
|
|
435
450
|
${bold('OPCIONES DE filter')}
|
|
436
451
|
--recovery-dir <directorio> Directorio privado; obligatorio para compact/restore.
|
|
452
|
+
--stats Solo compact: emite ahorro neto estimado en JSON por stderr.
|
|
437
453
|
trazum filter --help explica el filtro opcional (ayuda en inglés).
|
|
438
454
|
|
|
439
455
|
${bold('OPCIONES DE feedback')}
|
package/src/index.ts
CHANGED
|
@@ -324,6 +324,7 @@ interface Args {
|
|
|
324
324
|
}
|
|
325
325
|
|
|
326
326
|
const VALUE_FLAGS = new Set([
|
|
327
|
+
'id', 'type', 'criterion', 'outcome', 'assessor', 'policy', 'claude-code', 'codex', 'instructions',
|
|
327
328
|
'recovery-dir',
|
|
328
329
|
'answers',
|
|
329
330
|
'label-by-cwd',
|
|
@@ -737,7 +738,8 @@ function disabledRules(args: Args, config: TrazumConfig): RuleId[] | undefined {
|
|
|
737
738
|
*/
|
|
738
739
|
const GLOBAL_FLAGS = ['help', 'h', 'version', 'v', 'locale', 'json', 'config', 'pricing', 'pricing-live', 'max-input'];
|
|
739
740
|
const COMMAND_FLAGS: Record<string, string[]> = {
|
|
740
|
-
|
|
741
|
+
task: ['id', 'type', 'criterion', 'outcome', 'assessor', 'policy', 'claude-code', 'codex', 'instructions', 'out', 'o', 'json'],
|
|
742
|
+
filter: ['recovery-dir', 'stats'],
|
|
741
743
|
optimize: [
|
|
742
744
|
'level', 'model', 'calls', 'output-tokens', 'cache-hit-rate', 'batch',
|
|
743
745
|
'disable', 'llm', 'exact-tokens', 'diff', 'reorder', 'out', 'o',
|
|
@@ -13507,6 +13509,11 @@ function printRank(
|
|
|
13507
13509
|
|
|
13508
13510
|
async function main(): Promise<void> {
|
|
13509
13511
|
const argv = process.argv.slice(2);
|
|
13512
|
+
if (argv[0] === 'task') {
|
|
13513
|
+
const { runTask } = await import('./task.js');
|
|
13514
|
+
await runTask(argv.slice(1));
|
|
13515
|
+
return;
|
|
13516
|
+
}
|
|
13510
13517
|
// The stdin display filter has its own small grammar and no project config.
|
|
13511
13518
|
if (argv[0] === 'filter') {
|
|
13512
13519
|
const { runFilter } = await import('./filter.js');
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
const object = (properties: Record<string, unknown>) => ({
|
|
2
|
+
type: 'object', properties, required: Object.keys(properties), additionalProperties: false,
|
|
3
|
+
});
|
|
4
|
+
const count = { type: 'integer', minimum: 0 };
|
|
5
|
+
const counters = (names: string[]) => Object.fromEntries(names.map((name) => [name, count]));
|
|
6
|
+
const common = {
|
|
7
|
+
schemaVersion: { const: 1 }, log: { type: 'string' }, records: count,
|
|
8
|
+
evidence: object({ billingMode: { const: 'unknown' }, valuation: { const: 'api-equivalent' }, completeness: { const: 'not-established' } }),
|
|
9
|
+
limitations: { type: 'array', items: { type: 'string' } },
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
export const IMPORT_SCHEMAS = {
|
|
13
|
+
UsageImportRequest: {
|
|
14
|
+
type: 'object', required: ['format', 'text'], additionalProperties: false,
|
|
15
|
+
properties: {
|
|
16
|
+
format: { type: 'string', enum: ['claude-code', 'codex'] },
|
|
17
|
+
text: { type: 'string', minLength: 1, description: 'Non-blank transcript JSONL contents, never a path. No automatic format detection or shared deduplication state.' },
|
|
18
|
+
label: { type: 'string', minLength: 1, maxLength: 200, description: 'Optional explicit, non-blank workload label; limited to 200 UTF-16 code units. Never inferred from source metadata.' },
|
|
19
|
+
},
|
|
20
|
+
},
|
|
21
|
+
UsageImportAnswer: {
|
|
22
|
+
description: 'Complete JSON response is limited to 1,000,000 UTF-8 bytes. Empty output does not establish zero usage. Preserve diagnostics alongside downstream reports.',
|
|
23
|
+
oneOf: [
|
|
24
|
+
object({ ...common, format: { const: 'codex' }, diagnostics: object(counters(['duplicates', 'unparseable', 'missingModel', 'unsupported', 'otherLines'])) }),
|
|
25
|
+
object({ ...common, format: { const: 'claude-code' }, diagnostics: object({
|
|
26
|
+
...counters(['collapsed', 'noRequestId', 'otherLines', 'unparseable', 'assistantWithoutUsage', 'streamed', 'disagreements', 'synthetic']),
|
|
27
|
+
resume: object({ line: count, records: count }),
|
|
28
|
+
}) }),
|
|
29
|
+
],
|
|
30
|
+
},
|
|
31
|
+
};
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { claudeCodeRecords, codexRecords } from '@trazum/core';
|
|
2
|
+
|
|
3
|
+
/** Bound the complete serialized answer, including JSON escaping and repeated labels. */
|
|
4
|
+
export const MAX_IMPORT_RESPONSE_BYTES = 1_000_000;
|
|
5
|
+
|
|
6
|
+
interface ImportPayload {
|
|
7
|
+
format: 'claude-code' | 'codex';
|
|
8
|
+
text: string;
|
|
9
|
+
label?: string;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function validateImportPayload(value: unknown): asserts value is ImportPayload {
|
|
13
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
|
14
|
+
throw new Error('The body must be a JSON object.');
|
|
15
|
+
}
|
|
16
|
+
const payload = value as Record<string, unknown>;
|
|
17
|
+
if (Object.keys(payload).some((key) => !['format', 'text', 'label'].includes(key))) {
|
|
18
|
+
throw new Error('Unknown properties are not accepted for usage imports.');
|
|
19
|
+
}
|
|
20
|
+
if (payload.format !== 'claude-code' && payload.format !== 'codex') {
|
|
21
|
+
throw new Error('format must be claude-code or codex.');
|
|
22
|
+
}
|
|
23
|
+
if (typeof payload.text !== 'string' || payload.text.trim() === '') {
|
|
24
|
+
throw new Error('text must be non-empty transcript contents, not a file path.');
|
|
25
|
+
}
|
|
26
|
+
if (payload.label !== undefined && (typeof payload.label !== 'string' ||
|
|
27
|
+
payload.label.trim() === '' || payload.label.length > 200)) {
|
|
28
|
+
throw new Error('label must be non-empty text of at most 200 characters.');
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Explicit text only: no filesystem, measurement lookup or provider access. */
|
|
33
|
+
export function importUsage(payload: ImportPayload) {
|
|
34
|
+
const options = payload.label === undefined ? {} : { label: payload.label };
|
|
35
|
+
const conversion = payload.format === 'codex'
|
|
36
|
+
? codexRecords(payload.text, options) : claudeCodeRecords(payload.text, options);
|
|
37
|
+
const { records, ...diagnostics } = conversion;
|
|
38
|
+
const result = {
|
|
39
|
+
schemaVersion: 1 as const,
|
|
40
|
+
format: payload.format,
|
|
41
|
+
log: records.map((record) => JSON.stringify(record)).join('\n'),
|
|
42
|
+
records: records.length,
|
|
43
|
+
diagnostics,
|
|
44
|
+
evidence: { billingMode: 'unknown', valuation: 'api-equivalent', completeness: 'not-established' },
|
|
45
|
+
limitations: [
|
|
46
|
+
'Conversion diagnostics describe the supplied text only; missing source events and missing files cannot be detected.',
|
|
47
|
+
'Usage priced downstream is API-equivalent, not a subscription invoice or proof of realized savings.',
|
|
48
|
+
'No deduplication state is shared between calls. Do not concatenate overlapping imports.',
|
|
49
|
+
'Session identifiers are retained. Prompt, tool, cwd and path content is not copied; labels are caller supplied.',
|
|
50
|
+
'Empty output means no convertible records, not zero usage or zero cost. Preserve these diagnostics alongside downstream reports.',
|
|
51
|
+
],
|
|
52
|
+
};
|
|
53
|
+
if (Buffer.byteLength(JSON.stringify(result), 'utf8') > MAX_IMPORT_RESPONSE_BYTES) {
|
|
54
|
+
throw new Error(`Normalized import response exceeds ${MAX_IMPORT_RESPONSE_BYTES} UTF-8 bytes; use a smaller complete source or a shorter label.`);
|
|
55
|
+
}
|
|
56
|
+
return result;
|
|
57
|
+
}
|
package/src/serve-schema.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { SAVINGS_SCHEMAS } from './serve-savings-schema.js';
|
|
2
|
+
import { IMPORT_SCHEMAS } from './serve-import-schema.js';
|
|
2
3
|
/** Public contract for local, read-only cost and savings analysis. No provider calls occur here. */
|
|
3
4
|
const ref = (name: string) => ({ $ref: `#/components/schemas/${name}` });
|
|
4
5
|
const nullable = (schema: object) => ({ anyOf: [schema, { type: 'null' }] });
|
|
@@ -47,6 +48,7 @@ export function validateCostPayload(value: unknown): asserts value is Record<str
|
|
|
47
48
|
|
|
48
49
|
const schemas = {
|
|
49
50
|
...SAVINGS_SCHEMAS,
|
|
51
|
+
...IMPORT_SCHEMAS,
|
|
50
52
|
CostRequest: COST_REQUEST_SCHEMA,
|
|
51
53
|
HarnessCapabilities: object({
|
|
52
54
|
schemaVersion: { const: 1 },
|
|
@@ -120,6 +122,12 @@ export const SERVE_OPENAPI = {
|
|
|
120
122
|
info: { title: 'Trazum local cost and savings API', version: '1.0.0', description: 'Loopback-only read-only estimates, policy judgements and savings analysis. No authentication or CORS. Does not reserve budget, send model calls, or enforce an upstream decision. Measured positions are snapshots supplied by the CLI; inspect their windows.' },
|
|
121
123
|
servers: [{ url: 'http://127.0.0.1:7317', description: 'Default TCP listener. Substitute the chosen --port, or use the Unix socket transport.' }],
|
|
122
124
|
paths: {
|
|
125
|
+
'/usage/import': { post: {
|
|
126
|
+
operationId: 'importUsage', summary: 'Normalize explicit Claude Code or Codex transcript text',
|
|
127
|
+
description: 'Read-only conversion with explicit source format. No files, provider calls or measured-budget lookup. Prompts, tool content and cwd are excluded; session identifiers remain. Whole request and complete response each have a 1,000,000-byte UTF-8 limit, including JSON escaping. Unknown properties and blank inputs are refused. Conversion success does not certify source completeness or subscription billing.',
|
|
128
|
+
requestBody: { required: true, content: { 'application/json': { schema: ref('UsageImportRequest') } } },
|
|
129
|
+
responses: { '200': response('UsageImportAnswer', 'Normalized JSONL and conversion diagnostics, including zero-record imports.'), '400': response('Error', 'Malformed request, unsupported format, or input/output exceeding its byte limit.') },
|
|
130
|
+
} },
|
|
123
131
|
'/capabilities': { get: { operationId: 'getCapabilities', summary: 'Discover native import formats and Trazum access channels', responses: { '200': response('HarnessCapabilities', 'Static metadata; no environment, filesystem, session or network discovery.') } } },
|
|
124
132
|
'/health': { get: { operationId: 'getHealth', summary: 'Check the local process', responses: { '200': response('Health', 'Process is available.') } } },
|
|
125
133
|
'/openapi.json': { get: { operationId: 'getOpenApi', summary: 'Read this OpenAPI document', responses: { '200': { description: 'OpenAPI 3.1 document.', content: { 'application/json': { schema: { type: 'object', required: ['openapi', 'info', 'paths', 'components'] } } } } } } },
|
package/src/serve.ts
CHANGED
|
@@ -24,6 +24,7 @@
|
|
|
24
24
|
*/
|
|
25
25
|
|
|
26
26
|
import { createServer } from 'node:http';
|
|
27
|
+
import { importUsage, validateImportPayload } from './serve-import.js';
|
|
27
28
|
import { planSavings, verifySavings, validateSavingsPayload } from './serve-savings.js';
|
|
28
29
|
import { SERVE_OPENAPI, validateCostPayload } from './serve-schema.js';
|
|
29
30
|
import type { IncomingMessage, Server, ServerResponse } from 'node:http';
|
|
@@ -111,10 +112,11 @@ export function buildServer(context: ServeContext): Server {
|
|
|
111
112
|
}
|
|
112
113
|
|
|
113
114
|
const savings = url.pathname === '/savings/plan' || url.pathname === '/savings/verify';
|
|
114
|
-
|
|
115
|
+
const importing = url.pathname === '/usage/import';
|
|
116
|
+
if (request.method !== 'POST' || (url.pathname !== '/cost' && !savings && !importing)) {
|
|
115
117
|
send(response, 404, {
|
|
116
118
|
error: 'not-found',
|
|
117
|
-
detail: 'POST /cost, POST /savings/plan, POST /savings/verify, GET /health, GET /capabilities, or GET /openapi.json.',
|
|
119
|
+
detail: 'POST /cost, POST /usage/import, POST /savings/plan, POST /savings/verify, GET /health, GET /capabilities, or GET /openapi.json.',
|
|
118
120
|
});
|
|
119
121
|
return;
|
|
120
122
|
}
|
|
@@ -123,6 +125,11 @@ export function buildServer(context: ServeContext): Server {
|
|
|
123
125
|
try {
|
|
124
126
|
const raw = await readBody(request);
|
|
125
127
|
const parsed: unknown = raw.trim() === '' ? {} : JSON.parse(raw);
|
|
128
|
+
if (importing) {
|
|
129
|
+
validateImportPayload(parsed);
|
|
130
|
+
send(response, 200, importUsage(parsed));
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
126
133
|
if (savings) {
|
|
127
134
|
if (url.pathname === '/savings/verify') {
|
|
128
135
|
validateSavingsPayload(parsed, true);
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { constants } from 'node:fs';
|
|
2
|
+
import { link, lstat, open, rename, unlink } from 'node:fs/promises';
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { dirname, join } from 'node:path';
|
|
5
|
+
import { MAX_INPUT_CHARS, TASK_POLICY_INSTRUCTIONS } from '@trazum/core';
|
|
6
|
+
|
|
7
|
+
const START = '<!-- trazum:repeat-review-v1:start -->';
|
|
8
|
+
const END = '<!-- trazum:repeat-review-v1:end -->';
|
|
9
|
+
const BLOCK = `\n\n${START}\n${TASK_POLICY_INSTRUCTIONS}\n${END}\n`;
|
|
10
|
+
|
|
11
|
+
export class TaskFileError extends Error {}
|
|
12
|
+
|
|
13
|
+
/** Read bounded, stable regular files; a FIFO must not block before fstat. */
|
|
14
|
+
export async function readTaskText(path: string, maxChars = MAX_INPUT_CHARS): Promise<string> {
|
|
15
|
+
let file;
|
|
16
|
+
try {
|
|
17
|
+
file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
18
|
+
const before = await file.stat();
|
|
19
|
+
const maxBytes = maxChars * 4;
|
|
20
|
+
if (!before.isFile() || before.size > maxBytes) throw new TaskFileError('Input must be a bounded regular file, not a symlink or stream.');
|
|
21
|
+
const entry = await lstat(path);
|
|
22
|
+
if (!entry.isFile() || entry.isSymbolicLink()) throw new TaskFileError('Input must be a regular file, not a symlink or stream.');
|
|
23
|
+
if (before.dev !== entry.dev || before.ino !== entry.ino || before.mtimeMs !== entry.mtimeMs || before.size !== entry.size) {
|
|
24
|
+
throw new TaskFileError('Input changed while opening; retry after other edits finish.');
|
|
25
|
+
}
|
|
26
|
+
const buffer = Buffer.alloc(Math.min(before.size + 1, maxBytes + 1));
|
|
27
|
+
let length = 0;
|
|
28
|
+
while (length < buffer.length) {
|
|
29
|
+
const { bytesRead } = await file.read(buffer, length, buffer.length - length, null);
|
|
30
|
+
if (bytesRead === 0) break;
|
|
31
|
+
length += bytesRead;
|
|
32
|
+
}
|
|
33
|
+
const after = await file.stat();
|
|
34
|
+
const currentEntry = await lstat(path);
|
|
35
|
+
if (length !== before.size || before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs) {
|
|
36
|
+
throw new TaskFileError('Input changed while reading; finish the task and retry with a stable transcript.');
|
|
37
|
+
}
|
|
38
|
+
if (currentEntry.isSymbolicLink() || currentEntry.dev !== before.dev || currentEntry.ino !== before.ino) {
|
|
39
|
+
throw new TaskFileError('Input was replaced while reading; retry after other edits finish.');
|
|
40
|
+
}
|
|
41
|
+
const bytes = buffer.subarray(0, length);
|
|
42
|
+
const text = bytes.toString('utf8');
|
|
43
|
+
if (!Buffer.from(text, 'utf8').equals(bytes) || text.includes('\0')) throw new TaskFileError('Input must be UTF-8 text without NUL bytes.');
|
|
44
|
+
if (text.length > maxChars) throw new TaskFileError(`Input exceeds ${maxChars} characters; use a smaller complete task source.`);
|
|
45
|
+
return text;
|
|
46
|
+
} catch (error) {
|
|
47
|
+
if (error instanceof TaskFileError) throw error;
|
|
48
|
+
throw new TaskFileError('Cannot read input; provide an existing, readable regular file without a symlink.');
|
|
49
|
+
} finally { await file?.close(); }
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Reports are explicit opt-in files. Existing data is never overwritten. */
|
|
53
|
+
export async function writeTaskText(path: string, text: string): Promise<void> {
|
|
54
|
+
let temporary: string | undefined;
|
|
55
|
+
try {
|
|
56
|
+
const candidate = join(dirname(path), `.trazum-task-report-${randomUUID()}.tmp`);
|
|
57
|
+
const file = await open(candidate, 'wx', 0o600);
|
|
58
|
+
temporary = candidate;
|
|
59
|
+
try {
|
|
60
|
+
await file.writeFile(text, 'utf8');
|
|
61
|
+
await file.sync();
|
|
62
|
+
} finally { await file.close(); }
|
|
63
|
+
// Publish a complete file atomically, without replacing an existing destination.
|
|
64
|
+
await link(temporary, path);
|
|
65
|
+
} catch {
|
|
66
|
+
throw new TaskFileError('Cannot create output; choose a new file in an existing writable directory.');
|
|
67
|
+
} finally {
|
|
68
|
+
if (temporary !== undefined) await unlink(temporary).catch(() => {});
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Change only the exact, versioned block. No transcript content becomes instructions. */
|
|
73
|
+
export async function changeTaskInstructions(path: string, operation: 'apply' | 'revert'): Promise<boolean> {
|
|
74
|
+
let temporary: string | undefined;
|
|
75
|
+
try {
|
|
76
|
+
const before = await lstat(path);
|
|
77
|
+
if (!before.isFile() || before.isSymbolicLink() || before.nlink !== 1 ||
|
|
78
|
+
(process.platform !== 'win32' && before.uid !== process.getuid?.())) {
|
|
79
|
+
throw new TaskFileError('Instructions must be a regular file owned by you, without symlinks or hard links.');
|
|
80
|
+
}
|
|
81
|
+
const text = await readTaskText(path);
|
|
82
|
+
const starts = text.split(START).length - 1;
|
|
83
|
+
const ends = text.split(END).length - 1;
|
|
84
|
+
const hasBlock = text.includes(BLOCK);
|
|
85
|
+
if (starts !== ends || starts > 1 || (starts === 1 && !hasBlock)) {
|
|
86
|
+
throw new TaskFileError('The managed policy block was edited or is malformed; review it manually before retrying.');
|
|
87
|
+
}
|
|
88
|
+
if ((operation === 'apply' && hasBlock) || (operation === 'revert' && !hasBlock)) return false;
|
|
89
|
+
const updated = operation === 'apply' ? text + BLOCK : text.replace(BLOCK, '');
|
|
90
|
+
if (updated.length > MAX_INPUT_CHARS) throw new TaskFileError('Instructions would exceed the input limit.');
|
|
91
|
+
const candidate = join(dirname(path), `.trazum-task-${randomUUID()}.tmp`);
|
|
92
|
+
const file = await open(candidate, 'wx', 0o600);
|
|
93
|
+
temporary = candidate;
|
|
94
|
+
try {
|
|
95
|
+
await file.writeFile(updated, 'utf8');
|
|
96
|
+
await file.chmod(before.mode & 0o777);
|
|
97
|
+
await file.sync();
|
|
98
|
+
} finally { await file.close(); }
|
|
99
|
+
const current = await lstat(path);
|
|
100
|
+
if (current.dev !== before.dev || current.ino !== before.ino || current.nlink !== 1 ||
|
|
101
|
+
current.size !== before.size || current.mtimeMs !== before.mtimeMs || current.ctimeMs !== before.ctimeMs ||
|
|
102
|
+
await readTaskText(path) !== text) {
|
|
103
|
+
throw new TaskFileError('Instructions changed while preparing the policy; retry after other edits finish.');
|
|
104
|
+
}
|
|
105
|
+
await rename(temporary, path);
|
|
106
|
+
temporary = undefined;
|
|
107
|
+
return true;
|
|
108
|
+
} catch (error) {
|
|
109
|
+
if (error instanceof TaskFileError) throw error;
|
|
110
|
+
throw new TaskFileError('Cannot update instructions; choose an existing writable file in a writable directory.');
|
|
111
|
+
} finally {
|
|
112
|
+
if (temporary !== undefined) await unlink(temporary).catch(() => {});
|
|
113
|
+
}
|
|
114
|
+
}
|