@trazum/cli 2.5.2 → 2.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +4 -2
  2. package/dist/filter.d.ts.map +1 -1
  3. package/dist/filter.js +43 -7
  4. package/dist/filter.js.map +1 -1
  5. package/dist/i18n/en.d.ts.map +1 -1
  6. package/dist/i18n/en.js +66 -7
  7. package/dist/i18n/en.js.map +1 -1
  8. package/dist/i18n/es.d.ts.map +1 -1
  9. package/dist/i18n/es.js +67 -7
  10. package/dist/i18n/es.js.map +1 -1
  11. package/dist/i18n/types.d.ts +22 -1
  12. package/dist/i18n/types.d.ts.map +1 -1
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +271 -20
  15. package/dist/index.js.map +1 -1
  16. package/dist/serve-import-schema.d.ts +34 -0
  17. package/dist/serve-import-schema.d.ts.map +1 -0
  18. package/dist/serve-import-schema.js +32 -0
  19. package/dist/serve-import-schema.js.map +1 -0
  20. package/dist/serve-import.d.ts +49 -0
  21. package/dist/serve-import.d.ts.map +1 -0
  22. package/dist/serve-import.js +52 -0
  23. package/dist/serve-import.js.map +1 -0
  24. package/dist/serve-schema.d.ts +70 -0
  25. package/dist/serve-schema.d.ts.map +1 -1
  26. package/dist/serve-schema.js +9 -0
  27. package/dist/serve-schema.js.map +1 -1
  28. package/dist/serve.d.ts.map +1 -1
  29. package/dist/serve.js +9 -2
  30. package/dist/serve.js.map +1 -1
  31. package/dist/task-files.d.ts +9 -0
  32. package/dist/task-files.d.ts.map +1 -0
  33. package/dist/task-files.js +136 -0
  34. package/dist/task-files.js.map +1 -0
  35. package/dist/task.d.ts +2 -0
  36. package/dist/task.d.ts.map +1 -0
  37. package/dist/task.js +137 -0
  38. package/dist/task.js.map +1 -0
  39. package/package.json +7 -4
  40. package/src/filter.ts +46 -10
  41. package/src/i18n/en.ts +72 -7
  42. package/src/i18n/es.ts +75 -7
  43. package/src/i18n/types.ts +23 -1
  44. package/src/index.ts +259 -16
  45. package/src/serve-import-schema.ts +32 -0
  46. package/src/serve-import.ts +60 -0
  47. package/src/serve-schema.ts +9 -0
  48. package/src/serve.ts +9 -2
  49. package/src/task-files.ts +114 -0
  50. package/src/task.ts +119 -0
@@ -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
+ }
package/src/task.ts ADDED
@@ -0,0 +1,119 @@
1
+ import { analyzeTask, compareTasks, parseTaskReport, taskPolicy, MAX_INPUT_CHARS } from '@trazum/core';
2
+ import { changeTaskInstructions, readTaskText, writeTaskText } from './task-files.js';
3
+
4
+ const HELP = `Usage:
5
+ trazum task analyze --id <id> --type <type> --criterion <text>
6
+ --claude-code <file> [--codex <file>] [--claude-code <file> ...]
7
+ [--outcome accepted|rejected|unknown --assessor <label>]
8
+ [--policy baseline|repeat-review-v1] [-o <new-report.json>]
9
+ trazum task policy <report.json> [-o <new-policy.md>]
10
+ trazum task apply <report.json> --instructions <existing-file>
11
+ trazum task revert --instructions <existing-file>
12
+ trazum task compare <before.json> <after.json> [-o <new-comparison.json>]
13
+
14
+ Analyze explicit, complete task sources from Claude Code and Codex locally.
15
+ Repeat the source flags to include sessions from both harnesses. No home scan,
16
+ network access, provider call, hook installation or command execution occurs.
17
+ Up to 16 sources and ${MAX_INPUT_CHARS} characters combined. Do not split one
18
+ session across sources or import the same session more than once.
19
+ Reports and comparisons are JSON by default (--json is also accepted).
20
+ Outcome and assessor are caller declarations, never inferred from usage.
21
+ Policy application adds a small, optional managed block to the file you choose.
22
+ Review the diff and run a comparable task yourself before comparing reports.
23
+ Revert removes only the exact unchanged block. Close other editors while applying
24
+ or reverting. Existing output reports are never overwritten; new files use 0600.
25
+ Repeated tool results may be intentional. A paired comparison is an observation,
26
+ not proof of causal savings, task quality or remaining subscription allowance.
27
+ `;
28
+
29
+ type Parsed = { flags: Map<string, string>; paths: string[]; sources: { format: 'claude-code' | 'codex'; path: string }[] };
30
+ const ALLOWED: Record<string, readonly string[]> = {
31
+ analyze: ['id', 'type', 'criterion', 'outcome', 'assessor', 'policy', 'claude-code', 'codex', 'out', 'json'],
32
+ policy: ['out'],
33
+ apply: ['instructions'],
34
+ revert: ['instructions'],
35
+ compare: ['out', 'json'],
36
+ };
37
+
38
+ function parse(action: string, args: string[]): Parsed {
39
+ const allowed = ALLOWED[action];
40
+ if (!allowed) throw new Error('Unknown task action. Run trazum task --help.');
41
+ const flags = new Map<string, string>();
42
+ const sources: Parsed['sources'] = [];
43
+ const paths: string[] = [];
44
+ for (let index = 0; index < args.length; index++) {
45
+ const arg = args[index]!;
46
+ if (!arg.startsWith('-')) { paths.push(arg); continue; }
47
+ const name = arg === '-o' ? 'out' : arg.startsWith('--') ? arg.slice(2) : '';
48
+ if (!allowed.includes(name)) throw new Error('Unsupported task option. Run trazum task --help.');
49
+ if (flags.has(name)) throw new Error('Task options cannot be repeated except source flags.');
50
+ if (name === 'json') { flags.set(name, 'true'); continue; }
51
+ const value = args[++index];
52
+ if (value === undefined || value.trim() === '' || value.startsWith('-')) throw new Error('A task option is missing its value.');
53
+ if (name === 'claude-code' || name === 'codex') {
54
+ sources.push({ format: name, path: value });
55
+ if (sources.length > 16) throw new Error('At most 16 task sources are accepted.');
56
+ } else flags.set(name, value);
57
+ }
58
+ return { flags, sources, paths };
59
+ }
60
+
61
+ function required(flags: Map<string, string>, name: string): string {
62
+ const value = flags.get(name);
63
+ if (value === undefined) throw new Error(`Missing --${name}. Run trazum task --help.`);
64
+ return value;
65
+ }
66
+
67
+ async function emit(value: string | object, output?: string): Promise<void> {
68
+ let text = `${typeof value === 'string' ? value : JSON.stringify(value, null, 2)}\n`;
69
+ if (text.length > MAX_INPUT_CHARS && typeof value !== 'string') text = `${JSON.stringify(value)}\n`;
70
+ if (text.length > MAX_INPUT_CHARS) throw new Error('Task output exceeds the report limit; use a smaller complete task source.');
71
+ if (output !== undefined) await writeTaskText(output, text);
72
+ else process.stdout.write(text);
73
+ }
74
+
75
+ export async function runTask(args: string[]): Promise<void> {
76
+ if (args.length === 0 || (args.length === 1 && ['--help', '-h'].includes(args[0]!)) ||
77
+ (args.length === 2 && Object.hasOwn(ALLOWED, args[0]!) && ['--help', '-h'].includes(args[1]!))) {
78
+ process.stdout.write(HELP);
79
+ return;
80
+ }
81
+ const action = args[0]!;
82
+ const { flags, sources, paths } = parse(action, args.slice(1));
83
+ const expectedPaths = action === 'compare' ? 2 : action === 'policy' || action === 'apply' ? 1 : 0;
84
+ if (paths.length !== expectedPaths) throw new Error('Wrong number of task input files. Run trazum task --help.');
85
+ if (action === 'analyze') {
86
+ const taskId = required(flags, 'id');
87
+ const taskType = required(flags, 'type');
88
+ const criterion = required(flags, 'criterion');
89
+ if (sources.length === 0) throw new Error('Provide at least one --claude-code or --codex file.');
90
+ const contents: { format: 'claude-code' | 'codex'; text: string }[] = [];
91
+ let total = 0;
92
+ for (const source of sources) {
93
+ const text = await readTaskText(source.path, MAX_INPUT_CHARS - total);
94
+ total += text.length;
95
+ contents.push({ format: source.format, text });
96
+ }
97
+ const report = analyzeTask({ taskId, taskType, criterion, sources: contents,
98
+ ...(flags.has('outcome') ? { outcome: flags.get('outcome') } : {}),
99
+ ...(flags.has('assessor') ? { assessor: flags.get('assessor') } : {}),
100
+ ...(flags.has('policy') ? { policyId: flags.get('policy') } : {}),
101
+ });
102
+ await emit(report, flags.get('out'));
103
+ } else if (action === 'compare') {
104
+ const before = parseTaskReport(await readTaskText(paths[0]!));
105
+ const after = parseTaskReport(await readTaskText(paths[1]!));
106
+ await emit(compareTasks(before, after), flags.get('out'));
107
+ } else if (action === 'policy' || action === 'apply') {
108
+ const report = parseTaskReport(await readTaskText(paths[0]!));
109
+ const policy = taskPolicy(report);
110
+ if (action === 'policy') await emit(policy.instructions, flags.get('out'));
111
+ else {
112
+ const changed = await changeTaskInstructions(required(flags, 'instructions'), 'apply');
113
+ await emit({ version: 1, kind: 'trazum-task-policy', policyId: policy.id, applied: true, changed });
114
+ }
115
+ } else if (action === 'revert') {
116
+ const changed = await changeTaskInstructions(required(flags, 'instructions'), 'revert');
117
+ await emit({ version: 1, kind: 'trazum-task-policy', policyId: 'repeat-review-v1', applied: false, changed });
118
+ }
119
+ }