onionskin-cli 0.0.0-stage → 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +136 -0
- package/INSTALL.md +17 -0
- package/LICENSE +21 -0
- package/NOTICE +46 -0
- package/README.md +88 -2
- package/docs/contracts/batch.schema.json +839 -0
- package/docs/contracts/history.schema.json +126 -0
- package/docs/contracts/ops.schema.json +541 -0
- package/package.json +54 -4
- package/scripts/checker/check.py +411 -0
- package/scripts/checker/requirements.txt +5 -0
- package/scripts/install-check.mjs +9 -0
- package/scripts/requirements.txt +5 -0
- package/scripts/rewriter/apple/main.swift +135 -0
- package/scripts/rewriter/apple/onionskin-fm +0 -0
- package/scripts/rewriter/apple/onionskin-fm.json +6 -0
- package/skills/onionskin/SKILL.md +117 -0
- package/skills/onionskin/reference/batch.md +94 -0
- package/skills/onionskin/reference/formats.md +15 -0
- package/skills/onionskin/reference/ops.md +253 -0
- package/skills/onionskin/reference/troubleshooting.md +73 -0
- package/skills/onionskin/reference/voice-guide.md +86 -0
- package/skills/onionskin/voice.example.md +51 -0
- package/src/agent-detect.js +149 -0
- package/src/agent-events.js +159 -0
- package/src/agent-prompt.js +27 -0
- package/src/agent-runner.js +593 -0
- package/src/analyze.js +17 -0
- package/src/anchors.js +190 -0
- package/src/apply.js +387 -0
- package/src/auth.js +130 -0
- package/src/batch.js +322 -0
- package/src/check-worker.js +8 -0
- package/src/checker.js +293 -0
- package/src/cli.js +516 -0
- package/src/constants.js +20 -0
- package/src/diff.js +267 -0
- package/src/doctor.js +247 -0
- package/src/docx.js +438 -0
- package/src/fmt.js +30 -0
- package/src/fsutil.js +348 -0
- package/src/history-worker.js +16 -0
- package/src/history.js +576 -0
- package/src/lease.js +79 -0
- package/src/local.js +242 -0
- package/src/merge-pptx.js +198 -0
- package/src/merge-xlsx.js +453 -0
- package/src/merge.js +410 -0
- package/src/offload.js +34 -0
- package/src/ops/common.js +48 -0
- package/src/ops/docx-table.js +323 -0
- package/src/ops/docx.js +503 -0
- package/src/ops/engine.js +41 -0
- package/src/ops/pptx.js +336 -0
- package/src/ops/run.js +115 -0
- package/src/ops/runs.js +127 -0
- package/src/ops/schema.js +109 -0
- package/src/ops/xlsx.js +277 -0
- package/src/package.js +189 -0
- package/src/paths.js +64 -0
- package/src/person.js +66 -0
- package/src/pptx.js +194 -0
- package/src/question.js +47 -0
- package/src/quick-plan.js +107 -0
- package/src/quick.js +164 -0
- package/src/redline-check.js +251 -0
- package/src/redline-worker.js +29 -0
- package/src/redline.js +438 -0
- package/src/reply.js +410 -0
- package/src/review.js +274 -0
- package/src/rewrite-check.js +1014 -0
- package/src/rewriter-cleanup.js +105 -0
- package/src/rewriter-setup.js +104 -0
- package/src/rewriter.js +396 -0
- package/src/sanitize.js +42 -0
- package/src/sentence-span.js +25 -0
- package/src/server-entry.js +13 -0
- package/src/server.js +576 -0
- package/src/session.js +1910 -0
- package/src/settings.js +161 -0
- package/src/setup.js +160 -0
- package/src/stamp-words.js +10 -0
- package/src/stamps.js +59 -0
- package/src/style.js +110 -0
- package/src/suggest-reply.js +84 -0
- package/src/suggest.js +261 -0
- package/src/text.js +31 -0
- package/src/tracked-words.js +43 -0
- package/src/voice-guide.js +182 -0
- package/src/voice-learn.js +314 -0
- package/src/voice-sample-worker.js +95 -0
- package/src/voice-samples.js +329 -0
- package/src/voice-store.js +305 -0
- package/src/voice-worker.js +28 -0
- package/src/voice.js +297 -0
- package/src/xlsx.js +454 -0
- package/src/xml-tree.js +118 -0
- package/src/xml.js +127 -0
- package/src/zip-write.js +74 -0
- package/src/zip.js +88 -0
- package/vendor/engine/DocViewer-BZLXUcxJ.js +15137 -0
- package/vendor/engine/THIRD_PARTY_LICENSES.txt +79 -0
- package/vendor/engine/collab-BVynXMqc.js +2591 -0
- package/vendor/engine/collab.js +2 -0
- package/vendor/engine/core.js +4 -0
- package/vendor/engine/default-worker-DogNT09A.js +35625 -0
- package/vendor/engine/embed.js +107 -0
- package/vendor/engine/index.js +5 -0
- package/vendor/engine/office-engine.embed.js +184 -0
- package/vendor/engine/office-engine.worker.js +36030 -0
- package/vendor/engine/xlsx-ops-SYAv6V0f.js +939 -0
- package/vendor/engine-node/LICENSE +21 -0
- package/vendor/engine-node/engine-node.mjs +46618 -0
- package/vendor/engine.lock.json +26 -0
- package/web/dist/assets/index-CFISATkn.js +197 -0
- package/web/dist/assets/index-spXE4oTz.css +1 -0
- package/web/dist/index.html +14 -0
package/src/anchors.js
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import { normText } from "./text.js";
|
|
2
|
+
import { readDocxParagraphs, resolveDurable, durableFromEngine } from "./docx.js";
|
|
3
|
+
import { parseDeck, pptxDurable, resolvePptx } from "./pptx.js";
|
|
4
|
+
import { a1, a1Range, ch, parseWorkbook, resolveXlsx, sheetRows, xlsxDurable } from "./xlsx.js";
|
|
5
|
+
|
|
6
|
+
// One seam per format for the three things the server does with the bytes it holds: read the units, build a durable anchor from an
|
|
7
|
+
// engine location (at Send) and re-resolve one against newer bytes (after `done`). DOCX lives in docx.js, XLSX in xlsx.js, PPTX in pptx.js.
|
|
8
|
+
|
|
9
|
+
export function readUnits(format, bytes) {
|
|
10
|
+
if (format === "docx") return { format, paragraphs: readDocxParagraphs(bytes) };
|
|
11
|
+
if (format === "xlsx") return { format, wb: parseWorkbook(bytes) };
|
|
12
|
+
if (format === "pptx") return { format, deck: parseDeck(bytes) };
|
|
13
|
+
throw new Error(`unknown format ${format}`);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** The browser's captured anchor ({location, quote, prefix, suffix, paraText, hitKind}) -> durable anchor from the written bytes, or null. */
|
|
17
|
+
export function buildDurable(units, anchor) {
|
|
18
|
+
if (!anchor?.location) return null;
|
|
19
|
+
const { format } = units;
|
|
20
|
+
if (format === "docx") return durableFromEngine(units.paragraphs, anchor.location, { quote: anchor.paraText ? "" : anchor.quote, prefix: anchor.prefix, suffix: anchor.suffix, paraText: anchor.paraText });
|
|
21
|
+
if (format === "xlsx") return xlsxDurable(units.wb, anchor.location);
|
|
22
|
+
return pptxDurable(units.deck, anchor.location, { quote: anchor.quote, prefix: anchor.prefix, suffix: anchor.suffix, text: anchor.quote, shapeWide: !!anchor.hitKind });
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Re-resolve a stored durable anchor against new units. DOCX results keep their own shape (see docx.js). */
|
|
26
|
+
export function resolveDurableAny(units, durable) {
|
|
27
|
+
if (!durable) return { method: "none" };
|
|
28
|
+
if (units.format === "docx") return resolveDurable(units.paragraphs, durable);
|
|
29
|
+
if (units.format === "xlsx") return resolveXlsx(units.wb, durable);
|
|
30
|
+
return resolvePptx(units.deck, durable);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* What the browser stores of a view (`getViewState()` at Send), made durable. XLSX: the sheet and the top-left and selected cells as
|
|
35
|
+
* cell anchors, so a reload can land on the same logical cell after rows or columns moved. PPTX: the slide id and zoom.
|
|
36
|
+
*/
|
|
37
|
+
export function viewDurable(units, vs) {
|
|
38
|
+
if (!vs) return null;
|
|
39
|
+
if (units.format === "xlsx" && vs.format === "xlsx") {
|
|
40
|
+
const loc = (range) => ({ sheetIndex: vs.sheetIndex, sheetName: vs.sheetName, range });
|
|
41
|
+
return { format: "xlsx", top: xlsxDurable(units.wb, loc(vs.topLeft)), sel: xlsxDurable(units.wb, loc(vs.selection)), raw: { sheetIndex: vs.sheetIndex, sheetName: vs.sheetName, topLeft: vs.topLeft, selection: vs.selection } };
|
|
42
|
+
}
|
|
43
|
+
if (units.format === "pptx" && vs.format === "pptx") {
|
|
44
|
+
const d = pptxDurable(units.deck, { slideIndex: vs.slideIndex });
|
|
45
|
+
return { format: "pptx", durable: d, zoom: vs.zoom ?? "fit", slideIndex: vs.slideIndex };
|
|
46
|
+
}
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** The view to restore, in terms of the current file: {format:'xlsx', sheetIndex, sheetName, topLeft, selection} / {format:'pptx', slideIndex, zoom}. */
|
|
51
|
+
export function resolveView(units, view) {
|
|
52
|
+
if (!view) return null;
|
|
53
|
+
if (units.format === "xlsx" && view.top) {
|
|
54
|
+
const top = resolveXlsx(units.wb, view.top);
|
|
55
|
+
const sheetOf = (r) => ({ sheetIndex: r.sheetIndex, sheetName: r.sheetName });
|
|
56
|
+
// same top-left cell by identity when it can be found; else the same address on the same sheet
|
|
57
|
+
const raw = view.raw;
|
|
58
|
+
const sheet = top.method !== "none" ? sheetOf(top) : (() => {
|
|
59
|
+
const s = units.wb.sheets.find((x) => x.sheetId === view.top.sheetId && x.name === view.top.sheetName) || units.wb.sheets.find((x) => x.name === raw.sheetName) || units.wb.sheets.find((x) => x.sheetId === view.top.sheetId);
|
|
60
|
+
return s ? { sheetIndex: s.index, sheetName: s.name } : null;
|
|
61
|
+
})();
|
|
62
|
+
if (!sheet) return null;
|
|
63
|
+
const topLeft = top.method !== "none" ? a1(top.r0, top.c0) : raw.topLeft;
|
|
64
|
+
// the selection keeps its own anchor when it resolves; otherwise it shifts by the same offset as the top-left cell
|
|
65
|
+
let selection = raw.selection;
|
|
66
|
+
const sel = view.sel ? resolveXlsx(units.wb, view.sel) : { method: "none" };
|
|
67
|
+
if (sel.method !== "none" && sel.sheetName === sheet.sheetName) selection = sel.range;
|
|
68
|
+
return { format: "xlsx", ...sheet, topLeft, selection, topMethod: top.method };
|
|
69
|
+
}
|
|
70
|
+
if (units.format === "pptx" && view.durable) {
|
|
71
|
+
const r = resolvePptx(units.deck, { ...view.durable, shapeId: null });
|
|
72
|
+
return r.method === "none" ? { format: "pptx", slideIndex: Math.min(view.slideIndex ?? 0, Math.max(0, units.deck.slides.length - 1)), zoom: view.zoom, exact: false } : { format: "pptx", slideIndex: r.slideIndex, slideId: r.slideId, zoom: view.zoom, exact: true };
|
|
73
|
+
}
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// ---- changed regions: what the agent changed, found by comparing the file before and after ----------------------
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Longest-common-subsequence diff of two string sequences. Returns, for every index of `b`, 'same', 'changed' (paired with an unmatched
|
|
81
|
+
* element of `a` in the same gap: it was edited) or 'added'. Common prefix and suffix are trimmed first; a middle larger than 4M cells
|
|
82
|
+
* falls back to a multiset comparison (ceiling: no pairing, so it can only say 'added').
|
|
83
|
+
*/
|
|
84
|
+
export function diffSeq(a, b) {
|
|
85
|
+
const out = new Array(b.length).fill("added");
|
|
86
|
+
const pairedA = new Array(b.length).fill(-1);
|
|
87
|
+
let p = 0;
|
|
88
|
+
while (p < a.length && p < b.length && a[p] === b[p]) (out[p] = "same", p++);
|
|
89
|
+
let s = 0;
|
|
90
|
+
while (s < a.length - p && s < b.length - p && a[a.length - 1 - s] === b[b.length - 1 - s]) (out[b.length - 1 - s] = "same", s++);
|
|
91
|
+
const A = a.slice(p, a.length - s);
|
|
92
|
+
const B = b.slice(p, b.length - s);
|
|
93
|
+
if (!B.length) return { kind: out, pairedA };
|
|
94
|
+
if (A.length * B.length > 4_000_000) {
|
|
95
|
+
const have = new Map();
|
|
96
|
+
for (const x of A) have.set(x, (have.get(x) || 0) + 1);
|
|
97
|
+
B.forEach((x, i) => {
|
|
98
|
+
if (have.get(x) > 0) (have.set(x, have.get(x) - 1), (out[p + i] = "same"));
|
|
99
|
+
});
|
|
100
|
+
return { kind: out, pairedA };
|
|
101
|
+
}
|
|
102
|
+
const n = A.length;
|
|
103
|
+
const m = B.length;
|
|
104
|
+
const w = m + 1;
|
|
105
|
+
const T = new Uint16Array((n + 1) * w);
|
|
106
|
+
for (let i = n - 1; i >= 0; i--) for (let j = m - 1; j >= 0; j--) T[i * w + j] = A[i] === B[j] ? Math.min(65535, T[(i + 1) * w + j + 1] + 1) : Math.max(T[(i + 1) * w + j], T[i * w + j + 1]);
|
|
107
|
+
let i = 0;
|
|
108
|
+
let j = 0;
|
|
109
|
+
let gapA = 0; // start of the unmatched run of A
|
|
110
|
+
let gapB = 0;
|
|
111
|
+
const flush = (ea, eb) => {
|
|
112
|
+
// pair the unmatched runs in order: a replaced element is 'changed', the surplus of B is 'added'
|
|
113
|
+
for (let k = 0; gapB + k < eb && gapA + k < ea; k++) {
|
|
114
|
+
out[p + gapB + k] = "changed";
|
|
115
|
+
pairedA[p + gapB + k] = p + gapA + k;
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
while (i < n && j < m) {
|
|
119
|
+
if (A[i] === B[j]) {
|
|
120
|
+
flush(i, j);
|
|
121
|
+
out[p + j] = "same";
|
|
122
|
+
i++;
|
|
123
|
+
j++;
|
|
124
|
+
gapA = i;
|
|
125
|
+
gapB = j;
|
|
126
|
+
} else if (T[(i + 1) * w + j] >= T[i * w + j + 1]) i++;
|
|
127
|
+
else j++;
|
|
128
|
+
}
|
|
129
|
+
flush(n, m);
|
|
130
|
+
return { kind: out, pairedA };
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const MAX_CHANGES = 300;
|
|
134
|
+
|
|
135
|
+
/** Regions of the post file the agent changed: [{kind:'changed'|'added', ...position}] in post coordinates, capped; `truncated` says it was. */
|
|
136
|
+
export function changedRegions(format, preBytes, postBytes) {
|
|
137
|
+
const items = [];
|
|
138
|
+
const push = (it) => items.length < MAX_CHANGES && items.push(it);
|
|
139
|
+
if (format === "docx") {
|
|
140
|
+
const pre = readDocxParagraphs(preBytes);
|
|
141
|
+
const post = readDocxParagraphs(postBytes);
|
|
142
|
+
const { kind } = diffSeq(pre.map((p) => p.hash), post.map((p) => p.hash));
|
|
143
|
+
post.forEach((p, i) => kind[i] !== "same" && push({ kind: kind[i], text: normText(p.text).slice(0, 160), ordinal: p.ordinal }));
|
|
144
|
+
} else if (format === "xlsx") {
|
|
145
|
+
const A = parseWorkbook(preBytes);
|
|
146
|
+
const B = parseWorkbook(postBytes);
|
|
147
|
+
for (const sb of B.sheets) {
|
|
148
|
+
const sa = A.sheets.find((x) => x.name === sb.name) || A.sheets.find((x) => x.sheetId === sb.sheetId && !B.sheets.some((y) => y !== sb && y.name === x.name));
|
|
149
|
+
const rowsB = sheetRows(B, sb);
|
|
150
|
+
if (!sa) {
|
|
151
|
+
for (const row of rowsB) push({ kind: "added", sheetId: sb.sheetId, sheetName: sb.name, range: a1Range({ r0: row.r, c0: row.cells[0].c, r1: row.r, c1: row.cells[row.cells.length - 1].c }) });
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
const rowsA = sheetRows(A, sa);
|
|
155
|
+
const sig = (row) => row.cells.map((c) => `${c.c}:${ch(c)}`).join("|");
|
|
156
|
+
const { kind, pairedA } = diffSeq(rowsA.map(sig), rowsB.map(sig));
|
|
157
|
+
rowsB.forEach((row, i) => {
|
|
158
|
+
if (kind[i] === "same") return;
|
|
159
|
+
const where = { sheetId: sb.sheetId, sheetName: sb.name };
|
|
160
|
+
if (kind[i] === "changed") {
|
|
161
|
+
const old = new Map(rowsA[pairedA[i]].cells.map((c) => [c.c, c.text]));
|
|
162
|
+
const seen = new Set();
|
|
163
|
+
for (const c of row.cells) {
|
|
164
|
+
seen.add(c.c);
|
|
165
|
+
if (old.get(c.c) !== c.text) push({ kind: "changed", ...where, range: a1(row.r, c.c) });
|
|
166
|
+
}
|
|
167
|
+
for (const c of old.keys()) if (!seen.has(c)) push({ kind: "changed", ...where, range: a1(row.r, c) });
|
|
168
|
+
} else push({ kind: "added", ...where, range: a1Range({ r0: row.r, c0: row.cells[0].c, r1: row.r, c1: row.cells[row.cells.length - 1].c }) });
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
} else if (format === "pptx") {
|
|
172
|
+
const A = parseDeck(preBytes);
|
|
173
|
+
const B = parseDeck(postBytes);
|
|
174
|
+
A.ensure();
|
|
175
|
+
B.ensure();
|
|
176
|
+
for (const sb of B.slides) {
|
|
177
|
+
const sa = A.slides.find((x) => x.id === sb.id);
|
|
178
|
+
if (!sa) {
|
|
179
|
+
push({ kind: "added", slideId: sb.id });
|
|
180
|
+
continue;
|
|
181
|
+
}
|
|
182
|
+
for (const sh of sb.shapes) {
|
|
183
|
+
const old = sa.shapes.find((x) => x.id === sh.id && x.ordinal === sh.ordinal);
|
|
184
|
+
if (!old) push({ kind: "added", slideId: sb.id, shapeId: sh.id });
|
|
185
|
+
else if (old.hash !== sh.hash) push({ kind: "changed", slideId: sb.id, shapeId: sh.id });
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
return { items, truncated: items.length >= MAX_CHANGES };
|
|
190
|
+
}
|
package/src/apply.js
ADDED
|
@@ -0,0 +1,387 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { FORMATS, MAX_DOC_BYTES, PRODUCT, REFUSED_EXTENSIONS, env } from "./constants.js";
|
|
4
|
+
import { checkRegularOwned, readDoc, replaceGuarded, sha256, Snapshots, WriteConflict, writeSiblingCopy } from "./fsutil.js";
|
|
5
|
+
import { hasDelivery, loadTicketRecord, parseTicket } from "./lease.js";
|
|
6
|
+
import { validatePackage } from "./package.js";
|
|
7
|
+
import { cleanFlag, hasControlChars } from "./sanitize.js";
|
|
8
|
+
import crypto from "node:crypto";
|
|
9
|
+
import { ensureStateDir, sessionKey } from "./paths.js";
|
|
10
|
+
import { demote, summarize, runOps } from "./ops/run.js";
|
|
11
|
+
import { validateOps } from "./ops/schema.js";
|
|
12
|
+
|
|
13
|
+
export const APPLY_EXIT = { ok: 0, error: 1, invalid: 2, not_applied: 3, partial: 4, write_refused: 5 };
|
|
14
|
+
const MAX_OPS_BYTES = 5 * 1024 * 1024;
|
|
15
|
+
|
|
16
|
+
export class ApplyError extends Error {
|
|
17
|
+
constructor(message, exit = APPLY_EXIT.error, report = null) {
|
|
18
|
+
super(message);
|
|
19
|
+
this.exit = exit;
|
|
20
|
+
this.report = report;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function parseApplyArgs(rest, inline = false) {
|
|
25
|
+
const a = { file: "", ops: "", dryRun: false, partial: false, batch: "", holder: "", lease: "", standalone: false, summary: false };
|
|
26
|
+
for (let i = 0; i < rest.length; i++) {
|
|
27
|
+
const x = rest[i];
|
|
28
|
+
const val = (name) => {
|
|
29
|
+
const v = x.includes("=") ? x.slice(x.indexOf("=") + 1) : rest[++i];
|
|
30
|
+
if (!v) throw new Error(`${name} wants a value`);
|
|
31
|
+
return v;
|
|
32
|
+
};
|
|
33
|
+
if (x === "--dry-run") a.dryRun = true;
|
|
34
|
+
else if (x === "--summary") a.summary = true;
|
|
35
|
+
else if (x === "--partial") a.partial = true;
|
|
36
|
+
else if (x === "--standalone") a.standalone = true;
|
|
37
|
+
else if (x === "--ops" || x.startsWith("--ops=")) a.ops = val("--ops");
|
|
38
|
+
else if (x === "--batch" || x.startsWith("--batch=")) a.batch = val("--batch");
|
|
39
|
+
else if (x === "--holder" || x.startsWith("--holder=")) a.holder = val("--holder");
|
|
40
|
+
else if (x === "--lease" || x.startsWith("--lease=")) a.lease = val("--lease");
|
|
41
|
+
else if (x.startsWith("-")) throw new Error(`unknown option ${x}`);
|
|
42
|
+
else if (!a.file) a.file = x;
|
|
43
|
+
else throw new Error(`unexpected argument ${x}`);
|
|
44
|
+
}
|
|
45
|
+
if (!a.file || (!a.ops && !inline)) throw new Error(`Usage: ${PRODUCT.bin} apply <file> --ops ops.json --lease <ticket> [--dry-run] [--partial] [--batch batch.json] (or --standalone when no review session is open for the file)`);
|
|
46
|
+
return a;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function readJsonFile(file, what) {
|
|
50
|
+
let st;
|
|
51
|
+
try {
|
|
52
|
+
st = fs.statSync(file);
|
|
53
|
+
} catch (err) {
|
|
54
|
+
throw new ApplyError(`cannot read ${what} ${file}: ${err.message}`, APPLY_EXIT.invalid);
|
|
55
|
+
}
|
|
56
|
+
if (!st.isFile() || st.size > MAX_OPS_BYTES) throw new ApplyError(`${what} ${file} is not a regular file under ${MAX_OPS_BYTES / 1024 / 1024} MB`, APPLY_EXIT.invalid);
|
|
57
|
+
try {
|
|
58
|
+
return JSON.parse(fs.readFileSync(file, "utf8"));
|
|
59
|
+
} catch (err) {
|
|
60
|
+
throw new ApplyError(`${what} ${file} is not valid JSON: ${err.message}`, APPLY_EXIT.invalid);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const anchorMap = (batch) => new Map((batch?.untrusted_document_evidence?.anchors || []).map((a) => [a.id, a]));
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* The file was changed by someone else: apply/commit report `status: "outside_change"` and where the agent's version was saved. Built from what the
|
|
68
|
+
* server says (it made the name from the session's own file path). The agent must not retry and must not write the original.
|
|
69
|
+
*/
|
|
70
|
+
const OUTSIDE_INSTRUCTION = "Someone changed this file outside Onionskin. Do not retry and do not write the original. Report it in your results (done) with the copy's name, then stop and wait for the next batch.";
|
|
71
|
+
function outsideChangeOf(j) {
|
|
72
|
+
if (j.code !== "conflict" || j.side !== "agent") return {};
|
|
73
|
+
return {
|
|
74
|
+
status: "outside_change",
|
|
75
|
+
outside_change: {
|
|
76
|
+
copy_path: typeof j.copy_path === "string" ? j.copy_path : null,
|
|
77
|
+
copy_name: typeof j.copy_name === "string" ? j.copy_name : null,
|
|
78
|
+
...(j.copy_error ? { copy_error: String(j.copy_error).slice(0, 200) } : {}),
|
|
79
|
+
instruction: OUTSIDE_INSTRUCTION,
|
|
80
|
+
},
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const refusal = (message) => new ApplyError(message, APPLY_EXIT.write_refused);
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Where a write may go, and under which credentials. Fails closed: a ticket, a delivered batch or a saved delivery for the file means the
|
|
88
|
+
* write goes through the live session or does not happen. Standalone writes (no review session at all) need the explicit --standalone flag
|
|
89
|
+
* and are refused while a live session or a saved delivery exists for the file.
|
|
90
|
+
* Returns {via: "session", claim} or {via: "standalone"}; throws ApplyError(write_refused).
|
|
91
|
+
*/
|
|
92
|
+
async function resolveWriteTarget({ a, real, server, session, up, ticket }) {
|
|
93
|
+
const live = !!session && session.state !== "closed";
|
|
94
|
+
const delivered = live && ["working", "queued"].includes(session.state);
|
|
95
|
+
const saved = hasDelivery(real);
|
|
96
|
+
const recover = `Run \`${PRODUCT.bin} status <file> --ticket\` (it answers only the agent that polled this batch) or poll again.`;
|
|
97
|
+
if (ticket) {
|
|
98
|
+
if (!up) throw refusal(`The ${PRODUCT.name} server is not running, so the delivery named by --lease cannot be checked. Nothing was written. ${recover}`);
|
|
99
|
+
if (!session) throw refusal(`The server has no session for this file, so the delivery named by --lease is gone. Nothing was written. ${recover}`);
|
|
100
|
+
if (session.state === "closed") throw refusal(`The session for this file is closed; the delivery named by --lease no longer exists. Nothing was written.`);
|
|
101
|
+
if (!delivered) throw refusal(`This file has an open ${PRODUCT.name} session in state "${session.state}": no batch is delivered, so the ticket is void. Nothing was written. Run \`${PRODUCT.bin} poll\` and wait for the user's Send.`);
|
|
102
|
+
if (session.delivered_batch !== ticket.batch_id) throw refusal(`The ticket belongs to batch ${ticket.batch_id}, but the delivered batch is ${session.delivered_batch}: your delivery was taken back, finished or handed on. Nothing was written. Run \`${PRODUCT.bin} poll\` again.`);
|
|
103
|
+
const holder = a.holder || env("HOLDER", "") || loadTicketRecord(ticket.batch_id)?.holder;
|
|
104
|
+
if (!holder) throw refusal(`Cannot tell which holder this ticket belongs to: set ${PRODUCT.envPrefix}_HOLDER or pass --holder. Nothing was written.`);
|
|
105
|
+
return { via: "session", claim: { holder, lease_token: ticket.token, batch_id: ticket.batch_id } };
|
|
106
|
+
}
|
|
107
|
+
if (a.standalone) {
|
|
108
|
+
if (live) throw refusal(`A ${PRODUCT.name} session is open for this file (state "${session.state}"), so a standalone write is refused: it would bypass the lease and the user's review. Use the ticket from \`poll\` (--lease).`);
|
|
109
|
+
if (saved) throw refusal(`A delivery is saved for this file but its session is not available; a standalone write is refused. ${recover}`);
|
|
110
|
+
return { via: "standalone" };
|
|
111
|
+
}
|
|
112
|
+
if (delivered || saved) throw refusal(`A batch is delivered for this file: pass the ticket printed in the batch's commands (--lease <batch id>:<token>). There is no fallback to "the last poll". ${recover}`);
|
|
113
|
+
if (live) throw refusal(`this file has an open ${PRODUCT.name} session in state "${session.state}": no batch is delivered to you, so ${PRODUCT.bin} will not write. Run \`${PRODUCT.bin} poll\` and wait for the user's Send (or use --dry-run).`);
|
|
114
|
+
throw refusal(`No ${PRODUCT.name} session is open for this file. To edit it without a review, pass --standalone; to work inside a review, run \`${PRODUCT.bin} open\` and \`poll\` first.`);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** The standalone write: lock, compare-and-swap against `expectSha`, snapshot of what is replaced, re-hash before the rename. Returns {snapshot, acl} or {refused}. */
|
|
118
|
+
function standaloneWrite(real, original, out, expectSha, label) {
|
|
119
|
+
ensureStateDir();
|
|
120
|
+
const snaps = new Snapshots(sessionKey(real));
|
|
121
|
+
if (!snaps.index().some((e) => e.original)) snaps.add(original, "original", { original: true });
|
|
122
|
+
let snapshot = null;
|
|
123
|
+
try {
|
|
124
|
+
const info = replaceGuarded(real, out, {
|
|
125
|
+
expectSha,
|
|
126
|
+
snapshotBefore: (disk) => {
|
|
127
|
+
snapshot = snaps.add(disk, label);
|
|
128
|
+
},
|
|
129
|
+
snapshotNewer: (newer) => snaps.add(newer, "newer version found while writing"),
|
|
130
|
+
});
|
|
131
|
+
return { snapshot, acl: info.acl };
|
|
132
|
+
} catch (err) {
|
|
133
|
+
if (err instanceof WriteConflict) {
|
|
134
|
+
let outside = { instruction: OUTSIDE_INSTRUCTION, copy_path: null, copy_name: null };
|
|
135
|
+
try {
|
|
136
|
+
const c = writeSiblingCopy(real, out);
|
|
137
|
+
outside = { ...outside, copy_path: c.path, copy_name: c.name };
|
|
138
|
+
} catch (e) {
|
|
139
|
+
outside.copy_error = `the copy could not be saved: ${e.code || e.message}`.slice(0, 200);
|
|
140
|
+
}
|
|
141
|
+
return { refused: "Someone changed this file outside Onionskin while apply was working; the original was left untouched and nothing was overwritten.", outside };
|
|
142
|
+
}
|
|
143
|
+
if (err.code === "ENOSPC_SNAP") return { refused: `no snapshot, nothing written: ${err.message}` };
|
|
144
|
+
if (["LOCK_BUSY", "ACL_NOT_PRESERVED"].includes(err.code)) return { refused: `${err.message}; nothing was written.` };
|
|
145
|
+
throw err;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* `onionskin apply`. `server` = {healthy(), req(options, body), json(text)} for the CLI socket.
|
|
151
|
+
* `inline` ({ops, batch}, used by `reply`) supplies the ops document and the delivered batch in memory instead of --ops / the session fetch;
|
|
152
|
+
* every check below runs on it exactly as on a file.
|
|
153
|
+
* Returns {exit, report}; throws ApplyError for failures before any op ran.
|
|
154
|
+
*/
|
|
155
|
+
export async function applyCommand(rest, server, inline = null) {
|
|
156
|
+
const a = parseApplyArgs(rest, !!inline);
|
|
157
|
+
let real;
|
|
158
|
+
try {
|
|
159
|
+
real = fs.realpathSync(path.resolve(a.file));
|
|
160
|
+
} catch {
|
|
161
|
+
throw new ApplyError(`File not found: ${JSON.stringify(a.file.slice(0, 200))}`);
|
|
162
|
+
}
|
|
163
|
+
if (hasControlChars(real)) throw new ApplyError("This file's path contains control or bidirectional-text characters. Rename or move the file and run apply again.");
|
|
164
|
+
const ext = path.extname(real).toLowerCase();
|
|
165
|
+
if (REFUSED_EXTENSIONS.has(ext)) throw new ApplyError(`${ext} (macro-enabled) files are refused`);
|
|
166
|
+
const format = ext.slice(1);
|
|
167
|
+
if (!FORMATS[format]) throw new ApplyError("Only .docx, .xlsx and .pptx files are supported");
|
|
168
|
+
|
|
169
|
+
const doc = inline ? inline.ops : readJsonFile(a.ops, "ops file");
|
|
170
|
+
const v = validateOps(doc);
|
|
171
|
+
if (!v.ok) throw new ApplyError("the ops file does not match the schema", APPLY_EXIT.invalid, { schema: "onionskin.apply-report/1", status: "invalid_ops", errors: v.errors });
|
|
172
|
+
|
|
173
|
+
checkRegularOwned(real);
|
|
174
|
+
let bytes;
|
|
175
|
+
try {
|
|
176
|
+
bytes = readDoc(real); // refuses by size before reading
|
|
177
|
+
} catch (err) {
|
|
178
|
+
if (err.code === "TOO_LARGE") throw new ApplyError(`document too large: ${err.message}`);
|
|
179
|
+
throw err;
|
|
180
|
+
}
|
|
181
|
+
try {
|
|
182
|
+
validatePackage(bytes, format);
|
|
183
|
+
} catch (err) {
|
|
184
|
+
throw new ApplyError(`Not a valid .${format}: ${err.message}`);
|
|
185
|
+
}
|
|
186
|
+
const baseSha = sha256(bytes);
|
|
187
|
+
|
|
188
|
+
// where the write must go: through the server when a session tracks this file (it owns the lease, the compare-and-swap and the snapshots)
|
|
189
|
+
let session = null;
|
|
190
|
+
let batch = inline?.batch ?? (a.batch ? readJsonFile(a.batch, "batch file") : null);
|
|
191
|
+
const up = await server.healthy();
|
|
192
|
+
if (up) {
|
|
193
|
+
const r = await server.req({ method: "GET", path: `/cli/status?file=${encodeURIComponent(real)}` });
|
|
194
|
+
if (r.status === 200) session = server.json(r.text);
|
|
195
|
+
if (session && !batch) {
|
|
196
|
+
const b = await server.req({ method: "GET", path: `/cli/batch?file=${encodeURIComponent(real)}` });
|
|
197
|
+
if (b.status === 200) batch = server.json(b.text).batch;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
// the only credential is the ticket (--lease): not the batch JSON, not whatever the last poll of this file saved
|
|
201
|
+
const ticket = parseTicket(a.lease);
|
|
202
|
+
if (a.lease && !ticket) throw new ApplyError("--lease wants the value printed in the batch's commands (<batch id>:<token>)", APPLY_EXIT.invalid);
|
|
203
|
+
if (ticket && a.standalone) throw new ApplyError("--lease and --standalone contradict each other", APPLY_EXIT.invalid);
|
|
204
|
+
let target = { via: "none" };
|
|
205
|
+
if (!a.dryRun) target = await resolveWriteTarget({ a, real, server, session, up, ticket });
|
|
206
|
+
const claim = target.claim;
|
|
207
|
+
const viaSession = target.via === "session";
|
|
208
|
+
|
|
209
|
+
const { results: ran, bytes: out, warnings, blocked } = await runOps({ bytes, format, name: path.basename(real), ops: doc.ops, partial: a.partial, anchors: anchorMap(batch) });
|
|
210
|
+
const results = ran;
|
|
211
|
+
const refuseWrite = (note, extra = {}) => {
|
|
212
|
+
// nothing reached disk, so no op may read `applied`
|
|
213
|
+
report.results = demote(report.results, note);
|
|
214
|
+
report.counts = summarize(report.results);
|
|
215
|
+
report.note = note;
|
|
216
|
+
if (a.dryRun) Object.assign(report, { would_write: false, would_write_partial: false });
|
|
217
|
+
return { exit: APPLY_EXIT.write_refused, report: Object.assign(report, extra) };
|
|
218
|
+
};
|
|
219
|
+
const counts = summarize(results);
|
|
220
|
+
const failed = results.length - counts.applied;
|
|
221
|
+
const report = {
|
|
222
|
+
schema: "onionskin.apply-report/1",
|
|
223
|
+
file: real,
|
|
224
|
+
format,
|
|
225
|
+
mode: a.partial ? "partial" : "atomic",
|
|
226
|
+
dry_run: a.dryRun,
|
|
227
|
+
written: false,
|
|
228
|
+
write_path: a.dryRun ? "none" : target.via,
|
|
229
|
+
base_sha256: baseSha,
|
|
230
|
+
counts,
|
|
231
|
+
results,
|
|
232
|
+
...(warnings.length ? { warnings: warnings.map(cleanFlag) } : {}),
|
|
233
|
+
};
|
|
234
|
+
const runId = `run_${crypto.randomBytes(4).toString("hex")}`;
|
|
235
|
+
let exit = failed === 0 ? APPLY_EXIT.ok : a.partial && counts.applied ? APPLY_EXIT.partial : APPLY_EXIT.not_applied;
|
|
236
|
+
|
|
237
|
+
if (viaSession) {
|
|
238
|
+
// tell the session what could not be applied (also when nothing gets written), so the user sees it with the run
|
|
239
|
+
// problems are keyed by op (index + name): a later run that applies the op clears an earlier failure for it
|
|
240
|
+
const problems = results.filter((r) => !["applied", "not_applied"].includes(r.status)).map((r) => ({ key: `${r.index}:${r.op}`, op: r.op, status: r.status, code: r.code, reason: r.reason }));
|
|
241
|
+
if (problems.length) await server.req({ method: "POST", path: "/cli/apply-report" }, { file: real, ...claim, run: runId, problems, applied: [] }).catch(() => {});
|
|
242
|
+
}
|
|
243
|
+
if (blocked) return refuseWrite("The engine's output failed the package check (a part, relationship, drawing or link was lost). Nothing was written.", { blocked_by_safety_check: blocked.map(cleanFlag) });
|
|
244
|
+
if (a.dryRun) {
|
|
245
|
+
// what a real run would do: atomic writes only when every op applies, --partial writes the ops that apply
|
|
246
|
+
const writes = (r) => !!r.bytes && r.results.some((x) => x.status === "applied");
|
|
247
|
+
const wouldWrite = a.partial ? writes({ bytes: out, results }) : failed === 0 && !!out;
|
|
248
|
+
const wouldWritePartial = a.partial ? wouldWrite : failed === 0 ? wouldWrite : writes(await runOps({ bytes, format, name: path.basename(real), ops: doc.ops, partial: true, anchors: anchorMap(batch) }));
|
|
249
|
+
report.would_write = wouldWrite;
|
|
250
|
+
report.would_write_partial = wouldWritePartial;
|
|
251
|
+
report.note = `dry run: nothing was written. A real run in ${report.mode} mode would ${wouldWrite ? "write the file" : "write nothing"}${a.partial ? "" : `; with --partial it would ${wouldWritePartial ? "write the ops that apply" : "write nothing"}`}.`;
|
|
252
|
+
return { exit, report };
|
|
253
|
+
}
|
|
254
|
+
if (!out) {
|
|
255
|
+
report.note = failed ? "nothing was written" : "no op changed the document";
|
|
256
|
+
return { exit, report };
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
if (viaSession) {
|
|
260
|
+
// the ops go with the bytes: the server keeps them so that a later merge of the user's edits can check how the file changed
|
|
261
|
+
const w = await server.req({ method: "POST", path: "/cli/agent-write" }, { file: real, base_sha256: baseSha, bytes_b64: out.toString("base64"), ops: doc.ops, partial: a.partial, ...claim });
|
|
262
|
+
const j = server.json(w.text);
|
|
263
|
+
if (w.status !== 200) {
|
|
264
|
+
return refuseWrite("The server refused the write; the file on disk is unchanged.", { write_error: { status: w.status, code: j.code || null, message: j.error || `server answered ${w.status}` }, ...outsideChangeOf(j) });
|
|
265
|
+
}
|
|
266
|
+
report.written = true;
|
|
267
|
+
report.new_sha256 = j.sha256;
|
|
268
|
+
report.lease_expires_at = j.lease_expires_at;
|
|
269
|
+
// only a write that landed clears an earlier failure of the same op (a blocked or refused write applied nothing)
|
|
270
|
+
const appliedKeys = results.filter((r) => r.status === "applied").map((r) => `${r.index}:${r.op}`);
|
|
271
|
+
if (appliedKeys.length) await server.req({ method: "POST", path: "/cli/apply-report" }, { file: real, ...claim, run: runId, problems: [], applied: appliedKeys }).catch(() => {});
|
|
272
|
+
report.note = `written through the ${PRODUCT.name} session (lease renewed, previous version snapshotted)`;
|
|
273
|
+
} else {
|
|
274
|
+
// standalone: the same lock, compare-and-swap and atomic write, plus a snapshot of the bytes we replace in the state dir
|
|
275
|
+
const w = standaloneWrite(real, bytes, out, baseSha, "before apply (standalone)");
|
|
276
|
+
if (w.refused) return refuseWrite(w.refused, w.outside ? { status: "outside_change", outside_change: w.outside } : {});
|
|
277
|
+
report.snapshot = w.snapshot;
|
|
278
|
+
report.acl = w.acl;
|
|
279
|
+
report.written = true;
|
|
280
|
+
report.new_sha256 = sha256(out);
|
|
281
|
+
report.note = `standalone: no active ${PRODUCT.name} session for this file (explicit --standalone), so no lease was involved. Written atomically; the previous version is snapshotted in the state dir (${report.snapshot.slice(0, 12)}).`;
|
|
282
|
+
}
|
|
283
|
+
return { exit, report };
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
export function parseCommitArgs(rest) {
|
|
287
|
+
const a = { file: "", from: "", lease: "", base: "", holder: "", standalone: false };
|
|
288
|
+
for (let i = 0; i < rest.length; i++) {
|
|
289
|
+
const x = rest[i];
|
|
290
|
+
const val = (name) => {
|
|
291
|
+
const v = x.includes("=") ? x.slice(x.indexOf("=") + 1) : rest[++i];
|
|
292
|
+
if (!v) throw new Error(`${name} wants a value`);
|
|
293
|
+
return v;
|
|
294
|
+
};
|
|
295
|
+
if (x === "--standalone") a.standalone = true;
|
|
296
|
+
else if (x === "--from" || x.startsWith("--from=")) a.from = val("--from");
|
|
297
|
+
else if (x === "--lease" || x.startsWith("--lease=")) a.lease = val("--lease");
|
|
298
|
+
else if (x === "--base" || x.startsWith("--base=")) a.base = val("--base");
|
|
299
|
+
else if (x === "--holder" || x.startsWith("--holder=")) a.holder = val("--holder");
|
|
300
|
+
else if (x.startsWith("-")) throw new Error(`unknown option ${x}`);
|
|
301
|
+
else if (!a.file) a.file = x;
|
|
302
|
+
else throw new Error(`unexpected argument ${x}`);
|
|
303
|
+
}
|
|
304
|
+
if (!a.file || !a.from) throw new Error(`Usage: ${PRODUCT.bin} commit <file> --from <candidate file> --lease <ticket> [--base <sha256>] (or --standalone --base <sha256> when no review session is open)`);
|
|
305
|
+
return a;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* `onionskin commit <file> --from <candidate>`: the only way a document edited with another tool (python-docx, openpyxl, python-pptx, ...)
|
|
310
|
+
* reaches the file. The agent edits a COPY; this submits the copy's bytes through the same authenticated write as `apply` (lease check,
|
|
311
|
+
* compare-and-swap, snapshot, locked atomic replace). The original path is never written by the agent.
|
|
312
|
+
* The base the candidate was edited from is, unless --base says otherwise, the hash the server last wrote or delivered for the batch;
|
|
313
|
+
* if the file moved since, the commit is refused with `conflict` and the agent starts over from a fresh copy.
|
|
314
|
+
*/
|
|
315
|
+
export async function commitCommand(rest, server) {
|
|
316
|
+
const a = parseCommitArgs(rest);
|
|
317
|
+
let real;
|
|
318
|
+
try {
|
|
319
|
+
real = fs.realpathSync(path.resolve(a.file));
|
|
320
|
+
} catch {
|
|
321
|
+
throw new ApplyError(`File not found: ${JSON.stringify(a.file.slice(0, 200))}`);
|
|
322
|
+
}
|
|
323
|
+
if (hasControlChars(real)) throw new ApplyError("This file's path contains control or bidirectional-text characters. Rename or move the file and run commit again.");
|
|
324
|
+
const ext = path.extname(real).toLowerCase();
|
|
325
|
+
if (REFUSED_EXTENSIONS.has(ext)) throw new ApplyError(`${ext} (macro-enabled) files are refused`);
|
|
326
|
+
const format = ext.slice(1);
|
|
327
|
+
if (!FORMATS[format]) throw new ApplyError("Only .docx, .xlsx and .pptx files are supported");
|
|
328
|
+
let candidatePath;
|
|
329
|
+
try {
|
|
330
|
+
candidatePath = fs.realpathSync(path.resolve(a.from));
|
|
331
|
+
} catch {
|
|
332
|
+
throw new ApplyError(`candidate file not found: ${JSON.stringify(a.from.slice(0, 200))}`, APPLY_EXIT.invalid);
|
|
333
|
+
}
|
|
334
|
+
if (candidatePath === real) throw new ApplyError("--from is the document itself: edit a COPY (cp the file to a temp path first) and commit that", APPLY_EXIT.invalid);
|
|
335
|
+
const cst = fs.statSync(candidatePath);
|
|
336
|
+
if (!cst.isFile() || cst.size > MAX_DOC_BYTES) throw new ApplyError(`candidate ${a.from} is not a regular file under ${MAX_DOC_BYTES / 1024 / 1024} MB`, APPLY_EXIT.invalid);
|
|
337
|
+
if (a.base && !/^[0-9a-f]{64}$/.test(a.base)) throw new ApplyError("--base wants a sha256 in lower-case hex", APPLY_EXIT.invalid);
|
|
338
|
+
const candidate = fs.readFileSync(candidatePath);
|
|
339
|
+
try {
|
|
340
|
+
validatePackage(candidate, format);
|
|
341
|
+
} catch (err) {
|
|
342
|
+
throw new ApplyError(`The candidate is not a valid .${format}: ${err.message}. Nothing was written.`, APPLY_EXIT.write_refused);
|
|
343
|
+
}
|
|
344
|
+
const ticket = parseTicket(a.lease);
|
|
345
|
+
if (a.lease && !ticket) throw new ApplyError("--lease wants the value printed in the batch's commands (<batch id>:<token>)", APPLY_EXIT.invalid);
|
|
346
|
+
if (ticket && a.standalone) throw new ApplyError("--lease and --standalone contradict each other", APPLY_EXIT.invalid);
|
|
347
|
+
|
|
348
|
+
let session = null;
|
|
349
|
+
const up = await server.healthy();
|
|
350
|
+
if (up) {
|
|
351
|
+
const r = await server.req({ method: "GET", path: `/cli/status?file=${encodeURIComponent(real)}` });
|
|
352
|
+
if (r.status === 200) session = server.json(r.text);
|
|
353
|
+
}
|
|
354
|
+
const target = await resolveWriteTarget({ a, real, server, session, up, ticket });
|
|
355
|
+
const report = { schema: "onionskin.commit-report/1", file: real, format, written: false, write_path: target.via, candidate_sha256: sha256(candidate) };
|
|
356
|
+
if (target.via === "session") {
|
|
357
|
+
const w = await server.req({ method: "POST", path: "/cli/commit" }, { file: real, bytes_b64: candidate.toString("base64"), ...(a.base ? { base_sha256: a.base } : {}), ...target.claim });
|
|
358
|
+
const j = server.json(w.text);
|
|
359
|
+
if (w.status !== 200) return { exit: APPLY_EXIT.write_refused, report: { ...report, note: "The server refused the commit; the file on disk is unchanged.", write_error: { status: w.status, code: j.code || null, message: j.error || `server answered ${w.status}` }, ...outsideChangeOf(j) } };
|
|
360
|
+
return { exit: APPLY_EXIT.ok, report: { ...report, written: true, new_sha256: j.sha256, lease_expires_at: j.lease_expires_at, note: `committed through the ${PRODUCT.name} session (lease renewed, previous version snapshotted)` } };
|
|
361
|
+
}
|
|
362
|
+
if (!a.base) throw new ApplyError("a standalone commit needs --base <sha256 of the file the candidate was edited from> so a newer version is never overwritten", APPLY_EXIT.invalid);
|
|
363
|
+
checkRegularOwned(real);
|
|
364
|
+
const w = standaloneWrite(real, readDoc(real), candidate, a.base, "before commit (standalone)");
|
|
365
|
+
if (w.refused) return { exit: APPLY_EXIT.write_refused, report: { ...report, note: w.refused, ...(w.outside ? { status: "outside_change", outside_change: w.outside } : {}) } };
|
|
366
|
+
return { exit: APPLY_EXIT.ok, report: { ...report, written: true, new_sha256: report.candidate_sha256, snapshot: w.snapshot, acl: w.acl, note: "standalone (explicit --standalone): written atomically; the previous version is snapshotted in the state dir" } };
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/** The compact form of an apply or commit report (`--summary`): per-op statuses, flags, written, ok. The full report is the default. */
|
|
370
|
+
export function summarizeReport(report, exit) {
|
|
371
|
+
const codes = (list) => (Array.isArray(list) ? list.map((f) => f.code).filter(Boolean) : undefined);
|
|
372
|
+
return {
|
|
373
|
+
schema: `${report.schema}-summary`,
|
|
374
|
+
ok: exit === 0,
|
|
375
|
+
exit,
|
|
376
|
+
...(report.mode ? { mode: report.mode } : {}),
|
|
377
|
+
...(report.dry_run !== undefined ? { dry_run: report.dry_run } : {}),
|
|
378
|
+
written: !!report.written,
|
|
379
|
+
...(report.would_write !== undefined ? { would_write: report.would_write, would_write_partial: report.would_write_partial } : {}),
|
|
380
|
+
...(report.counts ? { counts: report.counts } : {}),
|
|
381
|
+
...(report.results ? { ops: report.results.map((r) => ({ index: r.index, op: r.op, ...(r.id ? { id: r.id } : {}), status: r.status, ...(r.code ? { code: r.code } : {}) })) } : {}),
|
|
382
|
+
...(report.warnings ? { warnings: codes(report.warnings) } : {}),
|
|
383
|
+
...(report.blocked_by_safety_check ? { blocked_by_safety_check: codes(report.blocked_by_safety_check) } : {}),
|
|
384
|
+
...(report.status ? { status: report.status } : {}),
|
|
385
|
+
...(report.note ? { note: report.note } : {}),
|
|
386
|
+
};
|
|
387
|
+
}
|