toolroll 0.9.129 → 0.9.130
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 +24 -0
- package/dist/agent-fence.js +0 -2
- package/dist/agents-board.js +0 -3
- package/dist/assignment.js +4 -3
- package/dist/backup-ui.js +6 -3
- package/dist/bounded-spawn.js +0 -1
- package/dist/browser/manifest.json +57 -0
- package/dist/browser/terminal.2a682d0b91a35288271c73b7ee253e524cca0917d17fbaf6733e80b7a767a37c.js.br +0 -0
- package/dist/browser/terminal.2a682d0b91a35288271c73b7ee253e524cca0917d17fbaf6733e80b7a767a37c.js.gz +0 -0
- package/dist/browser/terminal.4d1cf20c32ad7c2099df657358d540d5fd92bb55195a88121e74b28467238b42.css.br +0 -0
- package/dist/browser/terminal.4d1cf20c32ad7c2099df657358d540d5fd92bb55195a88121e74b28467238b42.css.gz +0 -0
- package/dist/browser/{workspace.js → workspace.9bd1db81d3c897045a5d82d4804e374e41e78b1b2cfd05d37b982a4ea0d02626.js} +25 -25
- package/dist/browser/workspace.9bd1db81d3c897045a5d82d4804e374e41e78b1b2cfd05d37b982a4ea0d02626.js.br +0 -0
- package/dist/browser/workspace.9bd1db81d3c897045a5d82d4804e374e41e78b1b2cfd05d37b982a4ea0d02626.js.gz +0 -0
- package/dist/browser/{workspace.css → workspace.a0752f935cfeaf16758d1085fe8f3e1719a7cd525b91a9c9943c789d65879a54.css} +1 -1
- package/dist/browser/workspace.a0752f935cfeaf16758d1085fe8f3e1719a7cd525b91a9c9943c789d65879a54.css.br +0 -0
- package/dist/browser/workspace.a0752f935cfeaf16758d1085fe8f3e1719a7cd525b91a9c9943c789d65879a54.css.gz +0 -0
- package/dist/browser-shell.js +271 -25
- package/dist/canvas-freshness.js +122 -0
- package/dist/canvas-fs.js +273 -0
- package/dist/canvas-reads.js +747 -0
- package/dist/canvas-state-key.js +45 -0
- package/dist/canvas-state-worker.js +12 -0
- package/dist/central-recovery-stage.js +3 -3
- package/dist/chat-actions.js +26 -0
- package/dist/chat-channel.js +4 -3
- package/dist/chat-task-actions.js +1 -1
- package/dist/chat-warmth.js +0 -1
- package/dist/check-report.js +0 -6
- package/dist/commit-extract.js +79 -40
- package/dist/companion/access.js +1 -0
- package/dist/companion/actions.js +79 -16
- package/dist/companion/canvas.js +141 -0
- package/dist/companion/chat-origin.js +92 -0
- package/dist/companion/chat.js +571 -0
- package/dist/companion/daemon.js +46 -5
- package/dist/companion/finish.js +51 -0
- package/dist/companion/reads.js +5 -1
- package/dist/companion/schema.js +64 -0
- package/dist/companion/service.js +1 -0
- package/dist/companion/store.js +1 -0
- package/dist/companion/webauthn.js +11 -2
- package/dist/console-instance.js +0 -4
- package/dist/contracts/console-api.js +1 -1
- package/dist/converse.js +0 -1
- package/dist/coordinator.js +1 -1
- package/dist/desktop-config.js +156 -0
- package/dist/desktop-host.js +6 -152
- package/dist/desktop-update.js +1 -1
- package/dist/finished-task-sql.js +14 -0
- package/dist/flexible-answers.js +0 -1
- package/dist/github-read.js +41 -0
- package/dist/guides.js +4 -3
- package/dist/lead-doors.js +50 -3
- package/dist/lead-queue-runtime.js +11 -2
- package/dist/lead-queue.js +25 -0
- package/dist/live-backup-change.js +93 -0
- package/dist/live-backup.js +75 -31
- package/dist/live-bus.js +3 -2
- package/dist/live-records.js +0 -1
- package/dist/local-owner.js +0 -1
- package/dist/model-choices.js +0 -11
- package/dist/nightly-check.js +0 -3
- package/dist/nightly-github.js +1 -2
- package/dist/notification-retention.js +119 -0
- package/dist/observations.js +0 -1
- package/dist/operate.js +17 -4
- package/dist/pull-request-flow.js +56 -15
- package/dist/qr.js +0 -25
- package/dist/release-adapters.js +12 -42
- package/dist/release-auto.js +17 -13
- package/dist/release-card.js +0 -4
- package/dist/release-cli.js +37 -2
- package/dist/release.js +13 -2
- package/dist/restore-retirement.js +4 -1
- package/dist/result-review.js +0 -3
- package/dist/retention-ui.js +1 -1
- package/dist/retention.js +14 -21
- package/dist/review-context.js +0 -5
- package/dist/route-rules.js +1 -5
- package/dist/sandbox-runtime.js +0 -1
- package/dist/scope.js +1 -13
- package/dist/scout.js +0 -6
- package/dist/serve.js +31 -7
- package/dist/server/kit.js +1 -0
- package/dist/server/live.js +9 -2
- package/dist/server/pages.js +3 -2
- package/dist/server/phone-engine-api.js +22 -2
- package/dist/server/render-pages.js +1 -11
- package/dist/server/render-results.js +0 -1
- package/dist/server/render-tasks.js +0 -68
- package/dist/server/route-table.js +1 -1
- package/dist/server/settings-phone.js +32 -9
- package/dist/server/settings-scripts.js +1 -1
- package/dist/server/settings-section-table.js +0 -3
- package/dist/server/settings-sections.js +4 -2
- package/dist/server/settings.js +20 -5
- package/dist/server/terminals.js +2 -1
- package/dist/store.js +20 -5
- package/dist/structured-output.js +0 -1
- package/dist/style-asset.js +20 -7
- package/dist/tailnet.js +0 -3
- package/dist/task-control.js +5 -0
- package/dist/task-sizing.js +0 -1
- package/dist/toolroll-update-cli.js +19 -3
- package/dist/toolroll-update-ui.js +2 -2
- package/dist/toolroll-update.js +95 -15
- package/package.json +1 -1
- package/dist/companion/webauthn-test-support.js +0 -44
- package/dist/contracts/contract-test.js +0 -55
- package/dist/unfenced-test-support.js +0 -6
- /package/dist/browser/{terminal.js → terminal.2a682d0b91a35288271c73b7ee253e524cca0917d17fbaf6733e80b7a767a37c.js} +0 -0
- /package/dist/browser/{terminal.css → terminal.4d1cf20c32ad7c2099df657358d540d5fd92bb55195a88121e74b28467238b42.css} +0 -0
package/dist/desktop-host.js
CHANGED
|
@@ -3,44 +3,20 @@ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync, realpat
|
|
|
3
3
|
import { dirname, join, resolve } from "node:path";
|
|
4
4
|
import { homedir, hostname } from "node:os";
|
|
5
5
|
import { fileURLToPath } from "node:url";
|
|
6
|
-
import {
|
|
7
|
-
import { openStore, openStoreNoMigrate, databasePath, readSchemaVersion, SCHEMA_VERSION } from "./store.js";
|
|
8
|
-
import { createRequire } from "node:module";
|
|
6
|
+
import { openStore, openStoreNoMigrate, databasePath } from "./store.js";
|
|
9
7
|
import { authenticateApprover, hashPassword } from "./scope.js";
|
|
10
8
|
import { runOperate, writeLoginFileDurably } from "./operate.js";
|
|
11
9
|
import { ensureSecretsDir, migrateLegacyLogin, savedLoginFile } from "./login-secrets.js";
|
|
12
|
-
import { daemonStatus, installLaunchdService, planDesktopService, stopLaunchdService } from "./daemon.js";
|
|
13
10
|
import { run as execRun } from "./exec.js";
|
|
14
|
-
import {
|
|
11
|
+
import { parseContainmentPolicy } from "./containment.js";
|
|
15
12
|
import { updateRepos, addRepos } from "./repos.js";
|
|
16
13
|
import { projectSelection } from "./project.js";
|
|
17
14
|
import { superviseController } from "./controller-supervisor.js";
|
|
18
|
-
import { normalizeRunnerName
|
|
15
|
+
import { normalizeRunnerName } from "./runner.js";
|
|
19
16
|
import { checkDesktopProjects, currentDesktopAccess } from "./desktop-access.js";
|
|
20
|
-
import {
|
|
21
|
-
import {
|
|
22
|
-
export
|
|
23
|
-
const config = JSON.parse(readFileSync(join(stateDir, "desktop.json"), "utf8"));
|
|
24
|
-
if (config.version !== 1 || typeof config.databaseFile !== "string" || !Array.isArray(config.repos) || config.repos.some(repo => typeof repo !== "string") || !Number.isInteger(config.port) || config.port < 1024 || config.port > 65535 || !/^[a-f0-9]{64}$/.test(config.identity))
|
|
25
|
-
throw new Error("Desktop configuration is invalid.");
|
|
26
|
-
if (config.runnerName !== undefined && (typeof config.runnerName !== "string" || !validRunnerName(config.runnerName)))
|
|
27
|
-
throw new Error("Desktop worker identity is invalid.");
|
|
28
|
-
if (config.containment !== undefined && (typeof config.containment !== "string" || !parseContainmentPolicy(config.containment).ok))
|
|
29
|
-
throw new Error("Desktop containment policy is invalid.");
|
|
30
|
-
if (config.databaseInitialized !== undefined && typeof config.databaseInitialized !== "boolean")
|
|
31
|
-
throw new Error("Desktop database setup state is invalid.");
|
|
32
|
-
config.repos = [...new Set(config.repos.map(repo => {
|
|
33
|
-
try {
|
|
34
|
-
return realpathSync(repo);
|
|
35
|
-
}
|
|
36
|
-
catch (error) {
|
|
37
|
-
if (["ENOENT", "EACCES", "EPERM"].includes(error.code ?? ""))
|
|
38
|
-
return resolve(repo);
|
|
39
|
-
throw error;
|
|
40
|
-
}
|
|
41
|
-
}))];
|
|
42
|
-
return config;
|
|
43
|
-
}
|
|
17
|
+
import { envValue } from "./names.js";
|
|
18
|
+
import { readDesktopConfig, desktopDatabaseStatus, verifyDesktopLiveness, desktopServiceCommand } from "./desktop-config.js";
|
|
19
|
+
export { readDesktopConfig, desktopDatabaseStatus, desktopServiceDefinition, verifyDesktopLiveness, desktopServiceCommand } from "./desktop-config.js";
|
|
44
20
|
export function writeDesktopConfig(stateDir, config) {
|
|
45
21
|
mkdirSync(stateDir, { recursive: true, mode: 0o700 });
|
|
46
22
|
const path = join(stateDir, "desktop.json");
|
|
@@ -105,30 +81,6 @@ export function openConfiguredDesktopStore(stateDir) {
|
|
|
105
81
|
throw error;
|
|
106
82
|
}
|
|
107
83
|
}
|
|
108
|
-
export function desktopDatabaseStatus(file) {
|
|
109
|
-
let db;
|
|
110
|
-
const result = (ready, message) => ({ ready, message, expectedSchema: SCHEMA_VERSION });
|
|
111
|
-
try {
|
|
112
|
-
db = new createRequire(import.meta.url)("node:sqlite").DatabaseSync(file, { readOnly: true });
|
|
113
|
-
db.exec("PRAGMA busy_timeout = 1000");
|
|
114
|
-
const schema = readSchemaVersion(db);
|
|
115
|
-
if (!schema.ok)
|
|
116
|
-
return result(false, `This app cannot use the saved task database: ${schema.problem}. Keep the database; use a compatible release or restore a verified backup separately.`);
|
|
117
|
-
if (schema.version === SCHEMA_VERSION)
|
|
118
|
-
return result(true, "The saved task database is compatible with this app.");
|
|
119
|
-
if (schema.version === null)
|
|
120
|
-
return result(false, "The task database has not been set up. Complete setup before starting work.");
|
|
121
|
-
if (schema.version < 0)
|
|
122
|
-
return result(false, "A database update did not finish. Keep the service stopped and complete the documented database upgrade before starting work.");
|
|
123
|
-
return result(false, `The saved tasks need a database upgrade (version ${schema.version} → ${SCHEMA_VERSION}). Keep the service stopped, back up the database, then complete the documented upgrade. This check changes nothing.`);
|
|
124
|
-
}
|
|
125
|
-
catch {
|
|
126
|
-
return result(false, "The saved task database cannot be read. Check that its disk is connected and accessible. If the file is damaged, keep it and restore a verified backup separately; do not create a replacement queue.");
|
|
127
|
-
}
|
|
128
|
-
finally {
|
|
129
|
-
db?.close();
|
|
130
|
-
}
|
|
131
|
-
}
|
|
132
84
|
async function readInput() {
|
|
133
85
|
let input = "";
|
|
134
86
|
for await (const part of process.stdin) {
|
|
@@ -169,104 +121,6 @@ export function pairDesktopLogin(store, file, login) {
|
|
|
169
121
|
if (!authenticateApprover(store, login.name, login.password).ok)
|
|
170
122
|
throw new Error("Another operator was created during setup. Sign in again.");
|
|
171
123
|
}
|
|
172
|
-
export function desktopServiceDefinition(stateDir, args) {
|
|
173
|
-
const runtimeDir = dirname(args.node);
|
|
174
|
-
const home = args.home ?? homedir();
|
|
175
|
-
return planDesktopService({
|
|
176
|
-
node: args.node,
|
|
177
|
-
helper: args.helper,
|
|
178
|
-
stateDir,
|
|
179
|
-
label: args.label,
|
|
180
|
-
associatedBundleId: args.bundleId ?? "com.standing-orders.desktop",
|
|
181
|
-
home,
|
|
182
|
-
environment: { ...envTwins("CONTAINMENT", args.containment ?? "observed"), ...(args.buildId ? envTwins("DESKTOP_BUILD", args.buildId) : {}) },
|
|
183
|
-
pathEnv: [runtimeDir, ...(args.providerBin ? [args.providerBin] : []), join(home, ".local", "bin"), "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin", "/usr/sbin", "/sbin"].join(":"),
|
|
184
|
-
});
|
|
185
|
-
}
|
|
186
|
-
export async function verifyDesktopLiveness(config, fetchImpl = fetch) {
|
|
187
|
-
const challenge = randomBytes(32).toString("hex");
|
|
188
|
-
try {
|
|
189
|
-
const response = await fetchImpl(`http://127.0.0.1:${config.port}/desktop/health?challenge=${challenge}`, { signal: AbortSignal.timeout(2_000) });
|
|
190
|
-
if (response.status !== 200)
|
|
191
|
-
return { alive: false, port: config.port, problem: `the controller answered ${response.status} on port ${config.port}` };
|
|
192
|
-
const body = (await response.json());
|
|
193
|
-
const expected = createHmac("sha256", Buffer.from(config.identity, "hex")).update(challenge).digest("hex");
|
|
194
|
-
if (body.proof !== expected)
|
|
195
|
-
return { alive: false, port: config.port, problem: `something on port ${config.port} is not this installation's controller` };
|
|
196
|
-
return { alive: true, port: config.port };
|
|
197
|
-
}
|
|
198
|
-
catch (error) {
|
|
199
|
-
return { alive: false, port: config.port, problem: `no controller answered on port ${config.port} (${error instanceof Error ? error.message : String(error)})` };
|
|
200
|
-
}
|
|
201
|
-
}
|
|
202
|
-
export async function desktopServiceCommand(verb, stateDir, config, argv, supervise = execRun) {
|
|
203
|
-
const read = (name) => {
|
|
204
|
-
const at = argv.indexOf(`--${name}`);
|
|
205
|
-
const value = at >= 0 ? argv[at + 1] : undefined;
|
|
206
|
-
if (value === undefined || value.startsWith("--"))
|
|
207
|
-
throw new Error(`${verb} needs --${name}.`);
|
|
208
|
-
return value;
|
|
209
|
-
};
|
|
210
|
-
const parsed = parseContainmentPolicy(config.containment ?? envValue(process.env, "CONTAINMENT"));
|
|
211
|
-
if (!parsed.ok)
|
|
212
|
-
throw new Error(parsed.problem);
|
|
213
|
-
const providerAt = argv.indexOf("--provider-bin");
|
|
214
|
-
const bundleAt = argv.indexOf("--bundle-id");
|
|
215
|
-
const buildAt = argv.indexOf("--build-id");
|
|
216
|
-
const definition = desktopServiceDefinition(stateDir, { node: read("node"), helper: read("helper"), label: read("label"), containment: parsed.policy, ...(providerAt >= 0 ? { providerBin: read("provider-bin") } : {}), ...(bundleAt >= 0 ? { bundleId: read("bundle-id") } : {}), ...(buildAt >= 0 ? { buildId: read("build-id") } : {}) });
|
|
217
|
-
if (verb === "service-start") {
|
|
218
|
-
if (argv.includes("--update-id")) {
|
|
219
|
-
const update = await import("./desktop-update.js");
|
|
220
|
-
const journal = update.readUpdateJournal(stateDir);
|
|
221
|
-
if (!journal || journal.id !== read("update-id") || update.updateStopRequested(journal))
|
|
222
|
-
throw new Error("This update is no longer allowed to start the background service.");
|
|
223
|
-
}
|
|
224
|
-
if (config.repos.length === 0)
|
|
225
|
-
throw new Error("Choose a repository in the desktop app first.");
|
|
226
|
-
const database = desktopDatabaseStatus(config.databaseFile);
|
|
227
|
-
if (!database.ready)
|
|
228
|
-
throw new Error(database.message);
|
|
229
|
-
const opened = openStoreNoMigrate(config.databaseFile);
|
|
230
|
-
if (!opened.ok)
|
|
231
|
-
throw new Error(opened.message);
|
|
232
|
-
try {
|
|
233
|
-
const updateAt = argv.indexOf("--update-id");
|
|
234
|
-
if (updateAdmissionPaused(opened.store.raw()) && (updateAt < 0 || !updateGateOwned(opened.store.raw(), read("update-id"))))
|
|
235
|
-
throw new Error(UPDATE_PAUSED);
|
|
236
|
-
}
|
|
237
|
-
finally {
|
|
238
|
-
opened.store.close();
|
|
239
|
-
}
|
|
240
|
-
if (!existsSync(definition.logPath))
|
|
241
|
-
writeFileSync(definition.logPath, "", { mode: 0o600 });
|
|
242
|
-
const started = await installLaunchdService(definition, supervise);
|
|
243
|
-
if (!started.ok)
|
|
244
|
-
throw new Error(started.message);
|
|
245
|
-
return { ok: true, action: started.action, changed: started.changed, label: definition.label, unit: definition.unitPath };
|
|
246
|
-
}
|
|
247
|
-
if (verb === "service-stop") {
|
|
248
|
-
if (!argv.includes("--update-id") && existsSync(join(stateDir, "desktop-update.json"))) {
|
|
249
|
-
try {
|
|
250
|
-
await (await import("./desktop-update.js")).requestUpdateStop(stateDir);
|
|
251
|
-
}
|
|
252
|
-
catch {
|
|
253
|
-
const recoveryLabel = `${definition.label}.update`;
|
|
254
|
-
const recoveryStopped = await stopLaunchdService({ ...definition, label: recoveryLabel, unitPath: join(dirname(definition.unitPath), `${recoveryLabel}.plist`) }, supervise);
|
|
255
|
-
console.error(recoveryStopped.ok ? "The update stop request could not be recorded, so automatic update recovery was disabled. Preserve the update files and check Update status before restarting." : "The update stop request and recovery-service stop could not be confirmed. Check Update status and service logs before leaving this installation unattended.");
|
|
256
|
-
}
|
|
257
|
-
}
|
|
258
|
-
const stopped = await stopLaunchdService(definition, supervise);
|
|
259
|
-
if (!stopped.ok)
|
|
260
|
-
throw new Error(stopped.message);
|
|
261
|
-
return { ok: true, wasLoaded: stopped.wasLoaded, label: definition.label };
|
|
262
|
-
}
|
|
263
|
-
if (verb === "service-status") {
|
|
264
|
-
const status = await daemonStatus(definition, supervise);
|
|
265
|
-
const liveness = status.state === "running" ? await verifyDesktopLiveness(config) : null;
|
|
266
|
-
return { ok: true, ...status, label: definition.label, liveness, database: desktopDatabaseStatus(config.databaseFile), containment: containmentStatus(effectiveContainment(parsed.policy, probeContainmentCapability())) };
|
|
267
|
-
}
|
|
268
|
-
throw new Error("Unknown desktop service operation.");
|
|
269
|
-
}
|
|
270
124
|
export async function desktopMain(argv, supervise = execRun) {
|
|
271
125
|
const stateArg = argv.indexOf("--state");
|
|
272
126
|
if (stateArg >= 0 && !argv[stateArg + 1])
|
package/dist/desktop-update.js
CHANGED
|
@@ -6,7 +6,7 @@ import { basename, dirname, isAbsolute, join, relative, resolve } from "node:pat
|
|
|
6
6
|
import { savedLoginFile } from "./login-secrets.js";
|
|
7
7
|
import { createRequire } from "node:module";
|
|
8
8
|
import { bundleHash, readDesktopBundle, verifyDesktopUpdateBundles } from "./desktop-bundle.js";
|
|
9
|
-
import { readDesktopConfig, desktopServiceCommand, desktopServiceDefinition, verifyDesktopLiveness } from "./desktop-
|
|
9
|
+
import { readDesktopConfig, desktopServiceCommand, desktopServiceDefinition, verifyDesktopLiveness } from "./desktop-config.js";
|
|
10
10
|
import { daemonStatus } from "./daemon.js";
|
|
11
11
|
import { run } from "./exec.js";
|
|
12
12
|
import { readSchemaVersion, SCHEMA_VERSION, Store } from "./store.js";
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { COMPLETION_ACTION } from "./result-completion.js";
|
|
2
|
+
export function finishedTask(r) {
|
|
3
|
+
return `EXISTS (SELECT 1 FROM task t WHERE t.id = ${r}.external_id AND ${r}.backend = 'built-in' AND (t.state = 'cancelled' OR (t.state = 'done' AND EXISTS (
|
|
4
|
+
SELECT 1 FROM action_ledger a WHERE a.action = '${COMPLETION_ACTION}' AND (a.task_id = ${r}.external_id OR a.run_id IN (SELECT id FROM run WHERE task_ref = ${r}.id))))))
|
|
5
|
+
AND NOT EXISTS (SELECT 1 FROM hold h WHERE h.task_ref = ${r}.id)
|
|
6
|
+
AND NOT EXISTS (SELECT 1 FROM run live WHERE live.task_ref = ${r}.id AND live.finished_at IS NULL)
|
|
7
|
+
AND NOT EXISTS (SELECT 1 FROM task_scope s WHERE s.task_id = ${r}.external_id AND s.candidate IS NOT NULL)
|
|
8
|
+
AND NOT EXISTS (WITH RECURSIVE family(ext) AS (
|
|
9
|
+
SELECT rv.external_id FROM task_ref rv WHERE rv.revision_of = ${r}.external_id
|
|
10
|
+
UNION SELECT rv.external_id FROM task_ref rv JOIN family ON rv.revision_of = family.ext)
|
|
11
|
+
SELECT 1 FROM family JOIN task tv ON tv.id = family.ext
|
|
12
|
+
WHERE NOT (tv.state = 'cancelled' OR (tv.state = 'done' AND EXISTS (SELECT 1 FROM action_ledger a WHERE a.action = '${COMPLETION_ACTION}'
|
|
13
|
+
AND (a.task_id = family.ext OR a.run_id IN (SELECT run.id FROM run JOIN task_ref x ON x.id = run.task_ref WHERE x.external_id = family.ext))))))`;
|
|
14
|
+
}
|
package/dist/flexible-answers.js
CHANGED
|
@@ -36,7 +36,6 @@ const WORDS = Object.freeze({
|
|
|
36
36
|
"scope-unshown": "This request couldn't be shown in full, so it can't be allowed. You can deny it. Nothing was sent.",
|
|
37
37
|
});
|
|
38
38
|
const refuse = (reason, state, message = WORDS[reason]) => state === undefined ? { ok: false, reason, message } : { ok: false, reason, message, state };
|
|
39
|
-
export const FLEXIBLE_ANSWER_UNCERTAIN = WORDS["uncertain"];
|
|
40
39
|
export function streamAnswerSender(stream) {
|
|
41
40
|
return (bytes, { deadlineMs, signal }) => new Promise(resolve => {
|
|
42
41
|
if (stream.destroyed || !stream.writable || signal.aborted) {
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { sleep } from "./sleep.js";
|
|
3
|
+
import { retryingExec } from "./release-net.js";
|
|
4
|
+
export const exec = (command, args, options = {}) => new Promise(done => {
|
|
5
|
+
const child = execFile(command, [...args], { cwd: options.cwd, env: options.env ?? process.env, timeout: options.timeoutMs ?? 120_000, maxBuffer: 64 * 1024 * 1024, encoding: "utf8" }, (error, stdout, stderr) => {
|
|
6
|
+
const failure = error;
|
|
7
|
+
const code = failure === null ? 0 : failure.code === "ENOENT" ? 127 : failure.killed === true ? 124 : typeof failure.code === "number" ? failure.code : 1;
|
|
8
|
+
done({ code, stdout: String(stdout ?? ""), stderr: String(stderr ?? "") });
|
|
9
|
+
});
|
|
10
|
+
child.stdin?.on("error", () => { });
|
|
11
|
+
if (options.input !== undefined)
|
|
12
|
+
child.stdin?.end(options.input);
|
|
13
|
+
else
|
|
14
|
+
child.stdin?.end();
|
|
15
|
+
});
|
|
16
|
+
export function ciEnv() {
|
|
17
|
+
const kept = Object.fromEntries(["HOME", "LANG", "LC_ALL", "TMPDIR", "USER", "LOGNAME", "GH_TOKEN", "GITHUB_TOKEN"].flatMap(name => process.env[name] === undefined ? [] : [[name, process.env[name]]]));
|
|
18
|
+
return { ...kept, PATH: "/usr/bin:/bin", GH_HOST: "github.com", GH_PROMPT_DISABLED: "1", GH_NO_UPDATE_NOTIFIER: "1" };
|
|
19
|
+
}
|
|
20
|
+
export function githubReads(run, gh, options = {}) {
|
|
21
|
+
return async (path, timeoutMs) => {
|
|
22
|
+
if (!/^repos\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_./?&=%-]+$/.test(path) || timeoutMs <= 0)
|
|
23
|
+
return { ok: false, why: "not a read this makes" };
|
|
24
|
+
const exec = options.retry === true ? retryingExec(run, { say: () => { }, sleep, budgetMs: timeoutMs }) : run;
|
|
25
|
+
let result;
|
|
26
|
+
try {
|
|
27
|
+
result = await exec(gh, ["api", "--hostname", "github.com", "--method", "GET", path], { cwd: "/", env: ciEnv(), timeoutMs });
|
|
28
|
+
}
|
|
29
|
+
catch (error) {
|
|
30
|
+
return { ok: false, why: String(error?.message ?? error).slice(0, 200) };
|
|
31
|
+
}
|
|
32
|
+
if (result.code !== 0)
|
|
33
|
+
return { ok: false, why: result.code === 124 ? "GitHub didn't answer in time" : result.code === 127 ? "gh isn't installed" : (result.stderr || result.stdout).trim().split("\n").slice(-1)[0].slice(0, 200) || `gh exited ${result.code}` };
|
|
34
|
+
try {
|
|
35
|
+
return { ok: true, body: JSON.parse(result.stdout) };
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
return { ok: false, why: "GitHub's answer couldn't be read" };
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
}
|
package/dist/guides.js
CHANGED
|
@@ -437,9 +437,10 @@ with a time limit.
|
|
|
437
437
|
entry (\`## <version>\`, in the format the top of CHANGELOG.md
|
|
438
438
|
describes). No tag or npm package has that version yet.
|
|
439
439
|
- \`gh\` is signed in, the console, worker and both CLI names
|
|
440
|
-
(\`toolroll\`, \`standing-orders\`) run one build
|
|
441
|
-
is a clone whose origin is
|
|
442
|
-
asked for in chat or written
|
|
440
|
+
(\`toolroll\`, \`standing-orders\`) run one build (\`toolroll update --yes\`
|
|
441
|
+
brings them together), and the gate checkout is a clone whose origin is
|
|
442
|
+
the GitHub repository. Credentials are never asked for in chat or written
|
|
443
|
+
to the release journal.
|
|
443
444
|
|
|
444
445
|
## What it does, in order
|
|
445
446
|
|
package/dist/lead-doors.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { executeSharedAction, sharedActionPayload, sharedActionAllowsChallenge, sharedActionNeedsReview, startFromTerminalWords, typedStartOpens } from './chat-actions.js';
|
|
1
|
+
import { executeSharedAction, sharedActionPayload, sharedActionAllowsChallenge, sharedActionNeedsReview, startFromTerminalWords, typedStartOpens, phoneSharedActionAllowed, PHONE_CARDS_LIVE, PHONE_CARDS_LATER, PHONE_NOT_CONFIRMABLE } from './chat-actions.js';
|
|
2
2
|
import { TYPED_START_REFUSED, typedStartCard, typedStartOf } from "./typed-start.js";
|
|
3
3
|
import { closedQuestionWords } from "./decision.js";
|
|
4
4
|
import { steerDestinationWords } from "./steer-status.js";
|
|
@@ -44,6 +44,7 @@ function payloadPlanning(payload) {
|
|
|
44
44
|
}
|
|
45
45
|
const VIA_WORDS = {
|
|
46
46
|
web: "From the lead chat", cli: "From the command line", telegram: "From Telegram", slack: "From Slack", discord: "From Discord", teams: "From Teams",
|
|
47
|
+
phone: "From the iPhone app",
|
|
47
48
|
};
|
|
48
49
|
const CARD_WORDS = {
|
|
49
50
|
task: "New task", next: "Queue priority", reserve: "Worker assignment", hold: "Pause work", unhold: "Resume work",
|
|
@@ -116,6 +117,11 @@ export function confirmLeadProposal(store, who, proposalId, now, options) {
|
|
|
116
117
|
}
|
|
117
118
|
if (proposal.kind === "control")
|
|
118
119
|
return { ok: false, kind: proposal.kind, reason: "not-confirmable", said: "Open the linked control to complete this action." };
|
|
120
|
+
if (options.via === "phone") {
|
|
121
|
+
const refusal = phoneDoorRefusal(proposal.kind, proposal.payload, options);
|
|
122
|
+
if (refusal !== null)
|
|
123
|
+
return { ok: false, kind: proposal.kind, reason: "not-confirmable", said: refusal };
|
|
124
|
+
}
|
|
119
125
|
if (options.typedStart !== undefined && proposal.kind !== "action")
|
|
120
126
|
return { ok: false, kind: proposal.kind, reason: "refused", said: TYPED_START_REFUSED };
|
|
121
127
|
if (proposal.kind === "action") {
|
|
@@ -129,7 +135,7 @@ export function confirmLeadProposal(store, who, proposalId, now, options) {
|
|
|
129
135
|
const typed = typedStartOpens(store, proposal.id, action, { via: options.via, ...(options.typedStart === undefined ? {} : { typedStart: options.typedStart }), authority: localDoor(options) ? "local-owner" : "full" });
|
|
130
136
|
if (options.typedStart !== undefined && !typed)
|
|
131
137
|
return { ok: false, kind: proposal.kind, reason: "refused", said: TYPED_START_REFUSED };
|
|
132
|
-
const challenged = options.via !== "web" && options.via !== "cli" && ((options.confirm === true && sharedActionAllowsChallenge(action, options.via)) || typed);
|
|
138
|
+
const challenged = options.via !== "web" && options.via !== "cli" && options.via !== "phone" && ((options.confirm === true && sharedActionAllowsChallenge(action, options.via)) || typed);
|
|
133
139
|
if (sharedActionNeedsReview(action) && !challenged && (options.via !== "web" || options.actionReview === undefined || options.confirm !== true))
|
|
134
140
|
return { ok: false, kind: proposal.kind, reason: "needs-confirm", said: "Review this action in the secure confirmation screen." };
|
|
135
141
|
}
|
|
@@ -287,6 +293,11 @@ export function confirmCoordinatorProposal(store, who, proposalId, now, options)
|
|
|
287
293
|
if (proposal.kind === "cancel") {
|
|
288
294
|
return { ok: false, kind: proposal.kind, reason: "not-confirmable", said: "Cancel from the task page." };
|
|
289
295
|
}
|
|
296
|
+
if (options.via === "phone") {
|
|
297
|
+
const refusal = phoneDoorRefusal(proposal.kind, proposal.payload, options);
|
|
298
|
+
if (refusal !== null)
|
|
299
|
+
return { ok: false, kind: proposal.kind, reason: "not-confirmable", said: refusal };
|
|
300
|
+
}
|
|
290
301
|
const needsConfirm = proposal.kind === "answer" && proposal.payload["reversible"] === false && options.confirm !== true;
|
|
291
302
|
if (needsConfirm)
|
|
292
303
|
return { ok: false, kind: proposal.kind, reason: "needs-confirm", said: "an irreversible choice must be confirmed explicitly" };
|
|
@@ -316,6 +327,11 @@ export function dismissCoordinatorProposal(store, who, proposalId, now) {
|
|
|
316
327
|
function executeProposal(store, actor, kind, payload, now, options) {
|
|
317
328
|
if (!isVerifiedApprover(actor) || !reproveApprover(store, actor).ok)
|
|
318
329
|
return { ok: false, kind, reason: "standing", said: "Your sign-in changed. Sign in again." };
|
|
330
|
+
if (options.via === "phone") {
|
|
331
|
+
const refusal = phoneDoorRefusal(kind, payload, options);
|
|
332
|
+
if (refusal !== null)
|
|
333
|
+
return { ok: false, kind, reason: "not-confirmable", said: refusal };
|
|
334
|
+
}
|
|
319
335
|
if (options.via !== "web" && options.via !== "cli") {
|
|
320
336
|
const solo = soloChatSeatRefusal(store, { provider: options.via, binding: options.binding, approver: actor.name });
|
|
321
337
|
if (solo !== null)
|
|
@@ -382,6 +398,8 @@ function executeProposal(store, actor, kind, payload, now, options) {
|
|
|
382
398
|
}
|
|
383
399
|
if (!chosen.reversible && options.confirm !== true)
|
|
384
400
|
return refuse("needs-confirm", "an irreversible choice must be confirmed explicitly");
|
|
401
|
+
if (options.via === "phone")
|
|
402
|
+
return refuse("not-confirmable", chosen.reversible ? PHONE_CARDS_LATER : PHONE_NOT_CONFIRMABLE);
|
|
385
403
|
const answered = store.answerDecision({ id: decision.id, choice: chosen.id, by: actor.name, via: options.via }, now);
|
|
386
404
|
if (!answered.ok || answered.duplicate === true) {
|
|
387
405
|
return !answered.ok && answered.reason !== "already-answered"
|
|
@@ -396,7 +414,7 @@ function executeProposal(store, actor, kind, payload, now, options) {
|
|
|
396
414
|
if (ref === null || !admitted(ref.repo))
|
|
397
415
|
return refuse("unknown-task", "no such task in your projects");
|
|
398
416
|
if (kind === "task_action") {
|
|
399
|
-
const result = applyChatTaskAction(store, actor, payload, now, options.via !== "cli", { deferSignal: options.deferSignal, via: options.via, person: options
|
|
417
|
+
const result = applyChatTaskAction(store, actor, payload, now, options.via !== "cli", { deferSignal: options.deferSignal, via: options.via, person: doorPerson(options), ...(options.evidenceRoot === undefined ? {} : { evidenceRoot: options.evidenceRoot }), ...(options.binding === undefined ? {} : { binding: options.binding }) });
|
|
400
418
|
return result.ok ? { ok: true, kind, taskId: result.taskId, said: result.said } : refuse("stale", result.message);
|
|
401
419
|
}
|
|
402
420
|
if (kind === "review") {
|
|
@@ -698,3 +716,32 @@ export function confirmTypedStart(store, who, typed, now, options) {
|
|
|
698
716
|
return settle("refused", null, outcome.ok ? TYPED_START_REFUSED : `${TYPED_START_REFUSED} (${outcome.said.replace(/\.$/, "")}.)`);
|
|
699
717
|
});
|
|
700
718
|
}
|
|
719
|
+
const PHONE_CARD_KINDS = new Set(["task", "next", "reserve", "hold", "steer", "answer", "task_action", "action"]);
|
|
720
|
+
export const PHONE_TASK_ACTIONS = new Set(["stop", "retry", "plan", "wait_for", "stop_waiting", "run_checks", "run_full_checks", "add_tests"]);
|
|
721
|
+
export function phoneConfirmable(kind, payload) {
|
|
722
|
+
if (!PHONE_CARD_KINDS.has(kind))
|
|
723
|
+
return false;
|
|
724
|
+
if (kind === "answer")
|
|
725
|
+
return payload["reversible"] !== false;
|
|
726
|
+
if (kind === "task_action")
|
|
727
|
+
return typeof payload["operation"] === "string" && PHONE_TASK_ACTIONS.has(payload["operation"]);
|
|
728
|
+
if (kind === "action") {
|
|
729
|
+
const action = sharedActionPayload(payload);
|
|
730
|
+
return action !== null && phoneSharedActionAllowed(action);
|
|
731
|
+
}
|
|
732
|
+
return true;
|
|
733
|
+
}
|
|
734
|
+
export function phoneDoorRefusal(kind, payload, options) {
|
|
735
|
+
if (options.person !== undefined || options.typedStart !== undefined)
|
|
736
|
+
return PHONE_NOT_CONFIRMABLE;
|
|
737
|
+
if (options.confirm !== undefined && !(kind === "answer" && payload["reversible"] !== false))
|
|
738
|
+
return PHONE_NOT_CONFIRMABLE;
|
|
739
|
+
if (!phoneConfirmable(kind, payload))
|
|
740
|
+
return PHONE_NOT_CONFIRMABLE;
|
|
741
|
+
return PHONE_CARDS_LIVE ? null : PHONE_CARDS_LATER;
|
|
742
|
+
}
|
|
743
|
+
export function doorPerson(options) {
|
|
744
|
+
if (options.via === "web")
|
|
745
|
+
return options.person === true;
|
|
746
|
+
return options.via !== "cli" && options.via !== "phone";
|
|
747
|
+
}
|
|
@@ -5,6 +5,8 @@ import { PersonalQueue } from "./lead-queue.js";
|
|
|
5
5
|
import { verifyApproverStanding } from "./principal.js";
|
|
6
6
|
import { updateAdmissionPaused } from "./desktop-update-gate.js";
|
|
7
7
|
import { TURN_WALL_CLOCK_MS } from "./converse.js";
|
|
8
|
+
import { withActor } from "./actor.js";
|
|
9
|
+
import { cancelFallenPhoneWork, PHONE_ORIGIN_GONE, phoneOriginStands } from "./companion/chat-origin.js";
|
|
8
10
|
export function leadTurnContext(store, context, names) {
|
|
9
11
|
if (context === null)
|
|
10
12
|
return undefined;
|
|
@@ -49,6 +51,8 @@ export function createPersonalQueueRuntime(options) {
|
|
|
49
51
|
const thread = store.getLeadThread(row.thread);
|
|
50
52
|
if (thread === null || thread.closedAt !== null)
|
|
51
53
|
return { ok: false, why: "Not sent: this conversation was closed before it ran." };
|
|
54
|
+
if (row.origin === "phone" && !phoneOriginStands(store, row.message))
|
|
55
|
+
return { ok: false, why: PHONE_ORIGIN_GONE };
|
|
52
56
|
if (row.context !== null && !options.contextStands(row.approver, row.context))
|
|
53
57
|
return { ok: false, why: "Not sent: the task it was about is no longer available." };
|
|
54
58
|
return { ok: true, who: verified.who };
|
|
@@ -78,7 +82,7 @@ export function createPersonalQueueRuntime(options) {
|
|
|
78
82
|
let held = false;
|
|
79
83
|
const session = store.getLeadSession(claim.session), thread = store.getLeadThread(claim.thread);
|
|
80
84
|
const context = leadTurnContext(store, claim.context, options.names);
|
|
81
|
-
outcome = await runLeadTurn({
|
|
85
|
+
outcome = await withActor({ account: claim.approver, lead: true }, () => (options.runTurn ?? runLeadTurn)({
|
|
82
86
|
store, who: proof.who, session, thread, config: provider.config, key: provider.key, message: claim.text, requestId: claim.requestId,
|
|
83
87
|
queuedMessageId: claim.message, queueClaim: { message: claim.message, runner: claim.runner, generation: claim.generation },
|
|
84
88
|
onAdmitted: turn => {
|
|
@@ -97,7 +101,7 @@ export function createPersonalQueueRuntime(options) {
|
|
|
97
101
|
},
|
|
98
102
|
...(options.fetcher === undefined ? {} : { fetcher: options.fetcher }),
|
|
99
103
|
...(options.subscriptionRunner === undefined ? {} : { subscriptionRunner: options.subscriptionRunner }),
|
|
100
|
-
});
|
|
104
|
+
}));
|
|
101
105
|
if (outcome.ok) {
|
|
102
106
|
queue.finish(claim, { status: "answered", turnId: outcome.turn }, clock());
|
|
103
107
|
return;
|
|
@@ -131,6 +135,7 @@ export function createPersonalQueueRuntime(options) {
|
|
|
131
135
|
passing = true;
|
|
132
136
|
try {
|
|
133
137
|
queue.reconcile(clock(), TURN_WALL_CLOCK_MS + 60_000);
|
|
138
|
+
cancelFallenPhoneWork(store, clock());
|
|
134
139
|
for (;;) {
|
|
135
140
|
const claim = queue.claimNext(runner, clock(), row => waiting.get(row.message) !== stamp(row));
|
|
136
141
|
if (claim === null)
|
|
@@ -153,6 +158,10 @@ export function createPersonalQueueRuntime(options) {
|
|
|
153
158
|
return;
|
|
154
159
|
scope.runInAsyncScope(() => { setImmediate(() => { void pass(); }); });
|
|
155
160
|
},
|
|
161
|
+
async drain() {
|
|
162
|
+
await pass();
|
|
163
|
+
await Promise.allSettled([...active]);
|
|
164
|
+
},
|
|
156
165
|
start() {
|
|
157
166
|
if (timer !== null || closed)
|
|
158
167
|
return;
|
package/dist/lead-queue.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
|
+
import { chatReceiptOf, insertChatOrigin } from "./companion/chat-origin.js";
|
|
2
3
|
export const LEAD_QUEUE_MAX_MESSAGES = 10;
|
|
3
4
|
export const LEAD_QUEUE_MAX_CHARS = 20_000;
|
|
4
5
|
export const LEAD_QUEUE_EXPIRY_MS = 7 * 86_400_000;
|
|
@@ -13,6 +14,7 @@ const readRow = (row) => ({
|
|
|
13
14
|
revision: Number(row["revision"]), generation: Number(row["generation"]), runner: row["runner"] === null ? null : String(row["runner"]),
|
|
14
15
|
turnId: row["turn_id"] === null ? null : Number(row["turn_id"]), error: row["error"] === null ? null : String(row["error"]),
|
|
15
16
|
createdAt: String(row["created_at"]), text: String(row["text"] ?? ""),
|
|
17
|
+
origin: row["origin"] === "phone" ? "phone" : "console",
|
|
16
18
|
});
|
|
17
19
|
const SELECT = "SELECT q.*, m.text FROM lead_queue q JOIN lead_message m ON m.id = q.message";
|
|
18
20
|
export class PersonalQueue {
|
|
@@ -98,6 +100,29 @@ export class PersonalQueue {
|
|
|
98
100
|
return true;
|
|
99
101
|
});
|
|
100
102
|
}
|
|
103
|
+
queueFromPhone(input, now) {
|
|
104
|
+
return this.store.transact(() => {
|
|
105
|
+
const receipt = chatReceiptOf(this.db, input.origin.deviceId, input.origin.idempotencyKey);
|
|
106
|
+
if (receipt !== null) {
|
|
107
|
+
const row = receipt.requestHash === input.origin.requestHash ? this.get(receipt.message) : null;
|
|
108
|
+
return row === null ? { kind: "conflict" } : { kind: "queued", row, already: true };
|
|
109
|
+
}
|
|
110
|
+
const waiting = this.backlog(input.approver);
|
|
111
|
+
if (waiting.length >= LEAD_QUEUE_MAX_MESSAGES)
|
|
112
|
+
return { kind: "full", message: `${LEAD_QUEUE_MAX_MESSAGES} messages are already waiting. Wait for a reply, then send again.` };
|
|
113
|
+
if (waiting.reduce((sum, one) => sum + one.text.length, 0) + input.text.length > LEAD_QUEUE_MAX_CHARS) {
|
|
114
|
+
return { kind: "full", message: "The messages waiting are already long. Wait for a reply, then send again." };
|
|
115
|
+
}
|
|
116
|
+
const hash = leadQueuePayloadHash(input.thread, input.text, input.context);
|
|
117
|
+
const message = this.store.appendLeadMessage({ thread: input.thread, turn: null, role: "operator", text: input.text, pending: true }, now);
|
|
118
|
+
this.db.prepare(`INSERT INTO lead_queue (message, thread, approver, approver_generation, session, ceiling_digest, request_id, payload_hash, context_json, status, created_at, origin)
|
|
119
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'queued', ?, 'phone')`).run(message, input.thread, input.approver, input.approverGeneration, input.session, input.ceilingDigest, input.requestId, hash, input.context === null ? null : JSON.stringify(canonical(input.context)), now.toISOString());
|
|
120
|
+
insertChatOrigin(this.db, { ...input.origin, message, createdAt: now.toISOString() });
|
|
121
|
+
this.store.recordAction({ at: now.toISOString(), actor: input.approver, repo: null, taskId: input.context?.task ?? null, runId: null,
|
|
122
|
+
action: "phone chat message", outcome: "queued", source: "request", detail: `device ${input.origin.deviceId} · message ${message}` });
|
|
123
|
+
return { kind: "queued", row: this.get(message), already: false };
|
|
124
|
+
});
|
|
125
|
+
}
|
|
101
126
|
defer(claim, error) {
|
|
102
127
|
return Number(this.db.prepare(`UPDATE lead_queue SET status = 'queued', generation = generation + 1, revision = revision + 1, runner = NULL, claimed_at = NULL, error = ?
|
|
103
128
|
WHERE message = ? AND status = 'running' AND turn_id IS NULL AND runner = ? AND generation = ?`).run(error, claim.message, claim.runner, claim.generation).changes) === 1;
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { Worker } from "node:worker_threads";
|
|
2
|
+
export const LIVE_FULL_CHECK_EVERY_MS = 86_400_000;
|
|
3
|
+
export const QUICK_SUFFIX = ".quick.db";
|
|
4
|
+
export function liveCheckOf(file) {
|
|
5
|
+
return file.endsWith(QUICK_SUFFIX) ? "quick" : "integrity";
|
|
6
|
+
}
|
|
7
|
+
export const LIVE_ONLY_TABLES = Object.freeze(["live_backup", "service_lifecycle", "latency_timeline", "agent_view", "run_efficiency"]);
|
|
8
|
+
export const LIVENESS_COLUMNS = Object.freeze({
|
|
9
|
+
runner: ["heartbeat_at"], claim: ["heartbeat_at", "expires_at"], watch_lease: ["heartbeat_at", "expires_at"], watch_episode: ["ticks"],
|
|
10
|
+
provider_readiness: ["observed_at"], web_session: ["last_seen"], backup_lease: ["holder", "held_until"],
|
|
11
|
+
});
|
|
12
|
+
export const EXACT_TABLES = Object.freeze({
|
|
13
|
+
schema_version: [], service_cursor: [], wake: [], sqlite_sequence: [],
|
|
14
|
+
notification_delivery: [], push_delivery: [], chat_message_ref: [], team_read: [], team_request: [],
|
|
15
|
+
chat_runtime: ["owner", "lease_until", "generation", "heartbeat", "retry_at"],
|
|
16
|
+
});
|
|
17
|
+
export const MARKER_SOURCE = `
|
|
18
|
+
function backupMarker(db, crypto) {
|
|
19
|
+
const LIVE_ONLY = new Set(${JSON.stringify(LIVE_ONLY_TABLES)});
|
|
20
|
+
const EXACT = ${JSON.stringify(EXACT_TABLES)};
|
|
21
|
+
const LIVENESS = ${JSON.stringify(LIVENESS_COLUMNS)};
|
|
22
|
+
const quote = name => '"' + String(name).replaceAll('"', '""') + '"';
|
|
23
|
+
const plain = (key, value) => typeof value === "bigint" ? String(value) : value instanceof Uint8Array ? Buffer.from(value).toString("base64") : value;
|
|
24
|
+
const hash = crypto.createHash("sha256");
|
|
25
|
+
const put = (...parts) => { hash.update(JSON.stringify(parts, plain)); hash.update("\\n"); };
|
|
26
|
+
db.exec("BEGIN");
|
|
27
|
+
try {
|
|
28
|
+
// The schema itself, not its cookie: an online backup doesn't carry the cookie over, and the marker must read the
|
|
29
|
+
// same on the copy as on the database it copied.
|
|
30
|
+
put("user_version", db.prepare("PRAGMA user_version").get().user_version);
|
|
31
|
+
for (const one of db.prepare("SELECT type, name, tbl_name, sql FROM sqlite_master ORDER BY type, name").all()) put("schema", one.type, one.name, one.tbl_name, one.sql);
|
|
32
|
+
const objects = db.prepare("SELECT type, name, tbl_name, sql FROM sqlite_master WHERE type IN ('table', 'index') ORDER BY name").all();
|
|
33
|
+
const owner = new Map(objects.map(one => [one.name, one.tbl_name]));
|
|
34
|
+
const tables = new Set(objects.filter(one => one.type === "table").map(one => one.name));
|
|
35
|
+
for (const table of Object.keys(EXACT).sort()) {
|
|
36
|
+
if (!tables.has(table)) { put("absent", table); continue; }
|
|
37
|
+
const columns = db.prepare("PRAGMA table_info(" + quote(table) + ")").all().map(row => row.name).filter(column => !EXACT[table].includes(column));
|
|
38
|
+
const rows = db.prepare("SELECT " + columns.map(quote).join(", ") + " FROM " + quote(table) + " ORDER BY rowid");
|
|
39
|
+
rows.setReturnArrays?.(true);
|
|
40
|
+
put("rows", table, columns);
|
|
41
|
+
for (const row of rows.iterate()) {
|
|
42
|
+
if (table === "sqlite_sequence" && LIVE_ONLY.has(Array.isArray(row) ? row[0] : row.name)) continue;
|
|
43
|
+
put(row);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
// Every other real table: rows, highest rowid, and each column's total length (liveness columns aside).
|
|
47
|
+
for (const one of objects) {
|
|
48
|
+
if (one.type !== "table" || one.name.startsWith("sqlite_") || LIVE_ONLY.has(one.name) || Object.hasOwn(EXACT, one.name)) continue;
|
|
49
|
+
if (/^CREATE\\s+VIRTUAL\\b/i.test(one.sql ?? "")) continue; // its shadow tables are real tables, read here
|
|
50
|
+
const skip = LIVENESS[one.name] ?? [];
|
|
51
|
+
const columns = db.prepare("PRAGMA table_info(" + quote(one.name) + ")").all().map(row => row.name).filter(column => !skip.includes(column));
|
|
52
|
+
const rowid = !/WITHOUT\\s+ROWID/i.test(one.sql ?? "");
|
|
53
|
+
const parts = ["count(*)", rowid ? "max(rowid)" : "NULL", ...columns.map(column => "total(length(" + quote(column) + "))")];
|
|
54
|
+
const totals = db.prepare("SELECT " + parts.join(", ") + " FROM " + quote(one.name));
|
|
55
|
+
totals.setReturnArrays?.(true);
|
|
56
|
+
put("table", one.name, columns, totals.get());
|
|
57
|
+
}
|
|
58
|
+
for (const tree of db.prepare("SELECT name, pageno, ncell, payload, unused FROM dbstat WHERE aggregate = TRUE ORDER BY name").all()) {
|
|
59
|
+
const table = owner.get(tree.name) ?? tree.name;
|
|
60
|
+
if (LIVE_ONLY.has(table) || Object.hasOwn(EXACT, table)) continue;
|
|
61
|
+
put("tree", tree.name, tree.pageno, tree.ncell, tree.payload, tree.unused);
|
|
62
|
+
}
|
|
63
|
+
} finally { db.exec("COMMIT"); }
|
|
64
|
+
return hash.digest("hex");
|
|
65
|
+
}
|
|
66
|
+
`;
|
|
67
|
+
const MARKER_THREAD = `
|
|
68
|
+
const { workerData, parentPort } = require("node:worker_threads");
|
|
69
|
+
const { DatabaseSync } = require("node:sqlite");
|
|
70
|
+
const crypto = require("node:crypto");
|
|
71
|
+
${MARKER_SOURCE}
|
|
72
|
+
try {
|
|
73
|
+
const db = new DatabaseSync(workerData.source, { readOnly: true });
|
|
74
|
+
try { db.exec("PRAGMA busy_timeout = 5000"); parentPort.postMessage({ ok: true, marker: backupMarker(db, crypto) }); } finally { db.close(); }
|
|
75
|
+
} catch (error) {
|
|
76
|
+
parentPort.postMessage({ ok: false, problem: String((error && error.message) || error).slice(0, 300) });
|
|
77
|
+
}
|
|
78
|
+
`;
|
|
79
|
+
export function markerOffThread(source) {
|
|
80
|
+
return new Promise(done => {
|
|
81
|
+
const thread = new Worker(MARKER_THREAD, { eval: true, workerData: { source } });
|
|
82
|
+
let settled = false;
|
|
83
|
+
const finish = (answer) => { if (!settled) {
|
|
84
|
+
settled = true;
|
|
85
|
+
done(answer);
|
|
86
|
+
} };
|
|
87
|
+
thread.once("message", (message) => finish(message.ok && typeof message.marker === "string"
|
|
88
|
+
? { ok: true, marker: message.marker } : { ok: false, problem: message.problem ?? "the change check failed" }));
|
|
89
|
+
thread.once("error", (error) => finish({ ok: false, problem: String(error.message).slice(0, 300) }));
|
|
90
|
+
thread.once("exit", () => finish({ ok: false, problem: "the change check stopped before it finished" }));
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
export const newLiveCopyMemory = () => ({ covered: null, lookedAt: null });
|