@picassohq/cli 0.0.0-stage → 1.0.2
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/agents/browser_agent.yaml +53 -0
- package/agents/code_reviewer.yaml +49 -0
- package/agents/codebase_investigator.yaml +70 -0
- package/agents/design_auditor.yaml +50 -0
- package/agents/devex_auditor.yaml +50 -0
- package/agents/doc_writer.yaml +54 -0
- package/agents/engineering_architect.yaml +51 -0
- package/agents/generalist.yaml +55 -0
- package/agents/migration_planner.yaml +51 -0
- package/agents/product_reviewer.yaml +48 -0
- package/agents/qa_operator.yaml +52 -0
- package/agents/release_engineer.yaml +50 -0
- package/agents/security_auditor.yaml +62 -0
- package/agents/test_writer.yaml +52 -0
- package/assets/first-light-lockup.png +0 -0
- package/assets/first-light-tagline.png +0 -0
- package/assets/house/README.md +26 -0
- package/assets/house/auraone-banner.png +0 -0
- package/assets/house/auraone-logo.png +0 -0
- package/assets/house/kiro-prism-banner.png +0 -0
- package/assets/house/kiro-prism-logo.png +0 -0
- package/assets/house/picasso-banner.png +0 -0
- package/assets/house/picasso-logo.png +0 -0
- package/assets/wordmark-app.png +0 -0
- package/assets/wordmark-tight.png +0 -0
- package/assets/wordmark.png +0 -0
- package/design/styles.css +1042 -0
- package/dist/build-info.json +37 -0
- package/dist/index.js +3062 -0
- package/goals/cli-hardening.yaml +40 -0
- package/goals/repo-maintenance.yaml +40 -0
- package/package.json +49 -4
- package/runtime/dsh/picasso-ecosystem.community.amendments.yml +24 -0
- package/runtime/dsh/picasso-ecosystem.community.json +185 -0
- package/runtime/dsh/picasso-ecosystem.community.patch.yml +40 -0
- package/runtime/dsh/picasso-ecosystem.cordis.patch.yml +143 -0
- package/runtime/dsh/picasso-isolation.patch.yml +25 -0
- package/runtime/dsh/picasso-providers.patch.yml +373 -0
- package/runtime/dsh/picasso-runtime.cordis.yml +738 -0
- package/runtime/dsh/picasso-sdk.patch.yml +204 -0
- package/runtime/engine-manifest.json +215 -0
- package/runtime/package.json +6 -0
- package/runtime/packages/picasso-cache-probe/cordis.patch.yml +5 -0
- package/runtime/packages/picasso-cache-probe/index.js +477 -0
- package/runtime/packages/picasso-cache-probe/package.json +38 -0
- package/runtime/packages/picasso-commands/cordis.patch.yml +4 -0
- package/runtime/packages/picasso-commands/fresh-review.js +573 -0
- package/runtime/packages/picasso-commands/index.js +497 -0
- package/runtime/packages/picasso-commands/package.json +28 -0
- package/runtime/packages/picasso-instructions/conflicts.js +115 -0
- package/runtime/packages/picasso-instructions/formats.js +145 -0
- package/runtime/packages/picasso-instructions/frontmatter.js +175 -0
- package/runtime/packages/picasso-instructions/glob.js +114 -0
- package/runtime/packages/picasso-instructions/globals.js +90 -0
- package/runtime/packages/picasso-instructions/imports.js +123 -0
- package/runtime/packages/picasso-instructions/index.js +326 -0
- package/runtime/packages/picasso-instructions/modes.js +64 -0
- package/runtime/packages/picasso-instructions/package.json +30 -0
- package/runtime/packages/picasso-instructions/parse.js +134 -0
- package/runtime/packages/picasso-instructions/report.js +161 -0
- package/runtime/packages/picasso-instructions/resolve.js +939 -0
- package/runtime/packages/picasso-instructions/scan.js +181 -0
- package/runtime/packages/picasso-instructions/settings.js +150 -0
- package/runtime/packages/picasso-instructions/skills.js +345 -0
- package/runtime/packages/picasso-lean-context/cordis.patch.yml +13 -0
- package/runtime/packages/picasso-lean-context/index.js +6280 -0
- package/runtime/packages/picasso-lean-context/package.json +26 -0
- package/runtime/packages/picasso-lean-context/read-image-recovery.js +306 -0
- package/runtime/packages/picasso-lean-context/timeline.js +418 -0
- package/runtime/packages/picasso-librarian/classify.js +146 -0
- package/runtime/packages/picasso-librarian/cordis.patch.yml +10 -0
- package/runtime/packages/picasso-librarian/index.js +878 -0
- package/runtime/packages/picasso-librarian/notes.js +159 -0
- package/runtime/packages/picasso-librarian/package.json +34 -0
- package/runtime/packages/picasso-librarian/state.js +478 -0
- package/runtime/packages/picasso-memory/index.js +1184 -0
- package/runtime/packages/picasso-memory/package.json +21 -0
- package/runtime/packages/picasso-model-router/connections.js +912 -0
- package/runtime/packages/picasso-model-router/cordis.patch.yml +17 -0
- package/runtime/packages/picasso-model-router/index.js +1083 -0
- package/runtime/packages/picasso-model-router/package.json +30 -0
- package/runtime/packages/picasso-options/cordis.patch.yml +4 -0
- package/runtime/packages/picasso-options/index.js +263 -0
- package/runtime/packages/picasso-options/package.json +28 -0
- package/runtime/packages/picasso-progress-reports/cordis.patch.yml +10 -0
- package/runtime/packages/picasso-progress-reports/index.js +267 -0
- package/runtime/packages/picasso-progress-reports/package.json +30 -0
- package/runtime/packages/picasso-progress-reports/report.js +235 -0
- package/runtime/packages/picasso-sdk-server/aside.js +142 -0
- package/runtime/packages/picasso-sdk-server/connections.js +38 -0
- package/runtime/packages/picasso-sdk-server/context-timeline.js +27 -0
- package/runtime/packages/picasso-sdk-server/egress-gate.js +520 -0
- package/runtime/packages/picasso-sdk-server/failure-policy.js +246 -0
- package/runtime/packages/picasso-sdk-server/file-input.js +169 -0
- package/runtime/packages/picasso-sdk-server/goal.js +131 -0
- package/runtime/packages/picasso-sdk-server/ignore-file.js +458 -0
- package/runtime/packages/picasso-sdk-server/ignore-plugin.js +12 -0
- package/runtime/packages/picasso-sdk-server/ignore-sandbox.js +122 -0
- package/runtime/packages/picasso-sdk-server/ignore-snapshot.js +131 -0
- package/runtime/packages/picasso-sdk-server/image-input.js +44 -0
- package/runtime/packages/picasso-sdk-server/index.js +891 -0
- package/runtime/packages/picasso-sdk-server/instructions.js +34 -0
- package/runtime/packages/picasso-sdk-server/jobs.js +113 -0
- package/runtime/packages/picasso-sdk-server/mcp-gate.js +51 -0
- package/runtime/packages/picasso-sdk-server/model-selection.js +162 -0
- package/runtime/packages/picasso-sdk-server/package.json +50 -0
- package/runtime/packages/picasso-sdk-server/picasso-records.js +50 -0
- package/runtime/packages/picasso-sdk-server/provider-reload.js +84 -0
- package/runtime/packages/picasso-sdk-server/queue.js +322 -0
- package/runtime/packages/picasso-sdk-server/requester.js +43 -0
- package/runtime/packages/picasso-sdk-server/rewind.js +108 -0
- package/runtime/packages/picasso-sdk-server/schedule.js +187 -0
- package/runtime/packages/picasso-sdk-server/session-grants.js +35 -0
- package/runtime/packages/picasso-sdk-server/session-state.js +118 -0
- package/runtime/packages/picasso-sdk-server/shell-paths.js +869 -0
- package/runtime/packages/picasso-sdk-server/stream-deltas.js +211 -0
- package/runtime/packages/picasso-sdk-server/team-tasks.js +451 -0
- package/runtime/packages/picasso-sdk-server/tool-output.js +128 -0
- package/runtime/packages/picasso-sdk-server/tools-list.js +51 -0
- package/runtime/packages/picasso-sdk-server/wave2-hooks.js +612 -0
- package/runtime/packages/picasso-sdk-server/workspace-archive.js +170 -0
- package/runtime/packages/picasso-sdk-server/workspace-restore.js +180 -0
- package/runtime/packages/picasso-web-search/backends.js +412 -0
- package/runtime/packages/picasso-web-search/config.js +121 -0
- package/runtime/packages/picasso-web-search/cordis.patch.yml +7 -0
- package/runtime/packages/picasso-web-search/failure.js +116 -0
- package/runtime/packages/picasso-web-search/format.js +42 -0
- package/runtime/packages/picasso-web-search/index.js +71 -0
- package/runtime/packages/picasso-web-search/package.json +38 -0
- package/runtime/packages/picasso-web-search/router.js +156 -0
- package/runtime/packages/picasso-x-reader/circle.js +324 -0
- package/runtime/packages/picasso-x-reader/command.js +169 -0
- package/runtime/packages/picasso-x-reader/cordis.patch.yml +8 -0
- package/runtime/packages/picasso-x-reader/index.js +170 -0
- package/runtime/packages/picasso-x-reader/package.json +39 -0
- package/runtime/packages/picasso-x-reader/read.js +370 -0
- package/runtime/packages/picasso-x-reader/rewrite.js +38 -0
- package/runtime/packages/picasso-x-reader/settings.js +131 -0
- package/runtime/packages/picasso-x-reader/urls.js +154 -0
- package/runtime/packages/picasso-x-reader/xmd.js +512 -0
- package/runtime/plugins/picasso-auth-bridge/index.js +380 -0
- package/runtime/plugins/picasso-auth-bridge/package.json +28 -0
- package/runtime/plugins/picasso-auto-approve/index.js +1003 -0
- package/runtime/plugins/picasso-auto-approve/package.json +28 -0
- package/runtime/plugins/picasso-browser/index.js +424 -0
- package/runtime/plugins/picasso-browser/package.json +28 -0
- package/runtime/plugins/picasso-checkpoints/evidence.js +210 -0
- package/runtime/plugins/picasso-checkpoints/index.js +885 -0
- package/runtime/plugins/picasso-checkpoints/package.json +29 -0
- package/runtime/plugins/picasso-commands/fresh-review.js +573 -0
- package/runtime/plugins/picasso-commands/index.js +497 -0
- package/runtime/plugins/picasso-commands/package.json +28 -0
- package/runtime/plugins/picasso-instructions/conflicts.js +115 -0
- package/runtime/plugins/picasso-instructions/formats.js +145 -0
- package/runtime/plugins/picasso-instructions/frontmatter.js +175 -0
- package/runtime/plugins/picasso-instructions/glob.js +114 -0
- package/runtime/plugins/picasso-instructions/globals.js +90 -0
- package/runtime/plugins/picasso-instructions/imports.js +123 -0
- package/runtime/plugins/picasso-instructions/index.js +326 -0
- package/runtime/plugins/picasso-instructions/modes.js +64 -0
- package/runtime/plugins/picasso-instructions/package.json +30 -0
- package/runtime/plugins/picasso-instructions/parse.js +134 -0
- package/runtime/plugins/picasso-instructions/report.js +161 -0
- package/runtime/plugins/picasso-instructions/resolve.js +939 -0
- package/runtime/plugins/picasso-instructions/scan.js +181 -0
- package/runtime/plugins/picasso-instructions/settings.js +150 -0
- package/runtime/plugins/picasso-instructions/skills.js +345 -0
- package/runtime/plugins/picasso-lean-context/index.js +6280 -0
- package/runtime/plugins/picasso-lean-context/package.json +26 -0
- package/runtime/plugins/picasso-lean-context/read-image-recovery.js +306 -0
- package/runtime/plugins/picasso-lean-context/timeline.js +418 -0
- package/runtime/plugins/picasso-librarian/classify.js +146 -0
- package/runtime/plugins/picasso-librarian/index.js +878 -0
- package/runtime/plugins/picasso-librarian/notes.js +159 -0
- package/runtime/plugins/picasso-librarian/package.json +34 -0
- package/runtime/plugins/picasso-librarian/state.js +478 -0
- package/runtime/plugins/picasso-lifecycle-hooks/index.js +186 -0
- package/runtime/plugins/picasso-lifecycle-hooks/package.json +25 -0
- package/runtime/plugins/picasso-mail/inbox.js +207 -0
- package/runtime/plugins/picasso-mail/index.js +293 -0
- package/runtime/plugins/picasso-mail/package.json +22 -0
- package/runtime/plugins/picasso-memory/index.js +1184 -0
- package/runtime/plugins/picasso-memory/package.json +21 -0
- package/runtime/plugins/picasso-model-router/connections.js +912 -0
- package/runtime/plugins/picasso-model-router/index.js +1083 -0
- package/runtime/plugins/picasso-model-router/package.json +30 -0
- package/runtime/plugins/picasso-options/index.js +263 -0
- package/runtime/plugins/picasso-options/package.json +28 -0
- package/runtime/plugins/picasso-progress-reports/index.js +267 -0
- package/runtime/plugins/picasso-progress-reports/package.json +30 -0
- package/runtime/plugins/picasso-progress-reports/report.js +235 -0
- package/runtime/plugins/picasso-provider-models/index.js +436 -0
- package/runtime/plugins/picasso-provider-models/package.json +28 -0
- package/runtime/plugins/picasso-repo-index/index.js +1850 -0
- package/runtime/plugins/picasso-repo-index/package.json +28 -0
- package/runtime/plugins/picasso-schedule-pause/index.js +344 -0
- package/runtime/plugins/picasso-schedule-pause/package.json +28 -0
- package/runtime/plugins/picasso-session-lifecycle/index.js +796 -0
- package/runtime/plugins/picasso-session-lifecycle/package.json +28 -0
- package/runtime/plugins/picasso-trackers/index.js +895 -0
- package/runtime/plugins/picasso-trackers/package.json +28 -0
- package/runtime/plugins/picasso-web-search/backends.js +412 -0
- package/runtime/plugins/picasso-web-search/config.js +121 -0
- package/runtime/plugins/picasso-web-search/failure.js +116 -0
- package/runtime/plugins/picasso-web-search/format.js +42 -0
- package/runtime/plugins/picasso-web-search/index.js +71 -0
- package/runtime/plugins/picasso-web-search/package.json +38 -0
- package/runtime/plugins/picasso-web-search/router.js +156 -0
- package/runtime/plugins/picasso-x-reader/circle.js +324 -0
- package/runtime/plugins/picasso-x-reader/command.js +169 -0
- package/runtime/plugins/picasso-x-reader/index.js +170 -0
- package/runtime/plugins/picasso-x-reader/package.json +39 -0
- package/runtime/plugins/picasso-x-reader/read.js +370 -0
- package/runtime/plugins/picasso-x-reader/rewrite.js +38 -0
- package/runtime/plugins/picasso-x-reader/settings.js +131 -0
- package/runtime/plugins/picasso-x-reader/urls.js +154 -0
- package/runtime/plugins/picasso-x-reader/xmd.js +512 -0
- package/runtime/relay/attachment-text.mjs +737 -0
- package/runtime/relay/companion/companion.css +126 -0
- package/runtime/relay/companion/companion.js +648 -0
- package/runtime/relay/companion/icon.svg +5 -0
- package/runtime/relay/companion/index.html +25 -0
- package/runtime/relay/companion/manifest.json +13 -0
- package/runtime/relay/companion/sw.js +41 -0
- package/runtime/relay/main.mjs +38580 -0
- package/runtime/relay/model-listing.mjs +614 -0
- package/runtime/relay/versions-routes.mjs +1400 -0
- package/runtime/verify-plugins.mjs +205 -0
- package/runtime-lock/package-lock.json +10779 -0
- package/runtime-lock/package.json +7 -0
- package/scripts/install-runtime.mjs +400 -0
- package/README.md +0 -3
|
@@ -0,0 +1,885 @@
|
|
|
1
|
+
// @picasso/checkpoints — per-turn file snapshots so "edit a past turn" can revert the agent's changes.
|
|
2
|
+
//
|
|
3
|
+
// Modelled on dsh's own @deepseek-ai/dsh-workspace-changes, but durable: snapshots and metadata live under config
|
|
4
|
+
// `root` (the relay mounts `dshHomePath('checkpoints')`) and survive Host restarts. Two workspace shapes:
|
|
5
|
+
//
|
|
6
|
+
// git the turn's work tree is written as a private tree object through a scratch index seeded from the repo's
|
|
7
|
+
// index, with GIT_OBJECT_DIRECTORY under root and GIT_ALTERNATE_OBJECT_DIRECTORIES = the repo's objects.
|
|
8
|
+
// Nothing in the user's .git (index, objects, refs, config) is ever written; the private index lives in a
|
|
9
|
+
// temp dir per snapshot. changed(n) = `diff-tree -r -M -z --name-status` S_n E_n.
|
|
10
|
+
// files outside a repo there is no snapshot to lean on: each fs write/edit intent stores a content-addressed
|
|
11
|
+
// pre-image of the resolved path once per turn, and turn end stores the after-image. Shell edits outside
|
|
12
|
+
// git are not covered (documented limitation).
|
|
13
|
+
//
|
|
14
|
+
// Remote service `checkpoints` (direct methods):
|
|
15
|
+
// preview(sessionId, turn) -> {files:[{path, status}], edited:[path], kind}
|
|
16
|
+
// evidence(sessionId, turn, {throughTurn}?) -> read-only evidence view (evidence.js; never restores/writes)
|
|
17
|
+
// restore(sessionId, turn) -> {restored:[path], skipped:[path], edited:[path], undoId}
|
|
18
|
+
// undoRestore(undoId) -> {restored:[path]}
|
|
19
|
+
// recover() -> {pending:[{undoId, sessionId, state, kind, paths}]}
|
|
20
|
+
// adopt(fromSessionId, toSessionId, beforeTurn) -> {} (copy turns < beforeTurn to the fork's record)
|
|
21
|
+
// drop(sessionId) -> {}
|
|
22
|
+
//
|
|
23
|
+
// status values: 'added' | 'modified' | 'deleted' — the file's disk state relative to S_turn. `edited` marks files
|
|
24
|
+
// whose current content differs from E_m (m = the latest recorded turn that changed them): the person touched them
|
|
25
|
+
// since the agent last did, so reverting would overwrite their edits.
|
|
26
|
+
import { createHash } from 'node:crypto';
|
|
27
|
+
import { access, chmod, lstat, mkdir, mkdtemp, readFile, realpath, rename, rm, stat, symlink, writeFile, copyFile, readdir } from 'node:fs/promises';
|
|
28
|
+
import { existsSync } from 'node:fs';
|
|
29
|
+
import { dirname, isAbsolute, join, resolve } from 'node:path';
|
|
30
|
+
import { homedir, tmpdir, userInfo } from 'node:os';
|
|
31
|
+
import { collectEvidence } from './evidence.js';
|
|
32
|
+
|
|
33
|
+
export const name = 'picasso-checkpoints';
|
|
34
|
+
export const dshTarget = '0.2.2-rc.3';
|
|
35
|
+
export const inject = ['subprocess', 'fs'];
|
|
36
|
+
|
|
37
|
+
export const SERVICE_KEY = 'checkpoints';
|
|
38
|
+
const REMOTE_METHOD_DESCRIPTOR = '@deepseek-ai/dsh-typert-protocol/remote-methods';
|
|
39
|
+
const MAX_FILE_BYTES = 8 * 1024 * 1024;
|
|
40
|
+
const GIT_TIMEOUT_MS = 30_000;
|
|
41
|
+
/** Directories never snapshotted in `full` mode (plus the workspace's own .gitignore, read from the tree). */
|
|
42
|
+
const FULL_EXCLUDES = ['node_modules', '.venv', 'venv', 'dist', 'build', '.next', 'target', 'DerivedData', '.cache', '.turbo', 'Pods', '.gradle'];
|
|
43
|
+
const FULL_MAX_FILES = 20_000;
|
|
44
|
+
const FULL_MAX_BYTES = 500 * 1024 * 1024;
|
|
45
|
+
|
|
46
|
+
/** `full` mode's budget: count files/bytes under `root`, skipping FULL_EXCLUDES dirs; bails the moment a cap trips. */
|
|
47
|
+
async function fullWithinBudget(root, maxFiles = FULL_MAX_FILES, maxBytes = FULL_MAX_BYTES) {
|
|
48
|
+
const skip = new Set(FULL_EXCLUDES);
|
|
49
|
+
let files = 0;
|
|
50
|
+
let bytes = 0;
|
|
51
|
+
const walk = async (dir) => {
|
|
52
|
+
for (const entry of await readdir(dir, { withFileTypes: true }).catch(() => [])) {
|
|
53
|
+
if (files > maxFiles || bytes > maxBytes) return;
|
|
54
|
+
if (entry.name === '.git') continue;
|
|
55
|
+
const path = join(dir, entry.name);
|
|
56
|
+
if (entry.isDirectory()) {
|
|
57
|
+
if (skip.has(entry.name)) continue;
|
|
58
|
+
await walk(path);
|
|
59
|
+
} else if (entry.isFile()) {
|
|
60
|
+
files += 1;
|
|
61
|
+
bytes += (await stat(path).catch(() => ({ size: 0 }))).size;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
await walk(root);
|
|
66
|
+
return files <= maxFiles && bytes <= maxBytes;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const isRecord = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
70
|
+
const isMissing = (e) => e !== null && typeof e === 'object' && e.code === 'ENOENT';
|
|
71
|
+
|
|
72
|
+
export class CheckpointsError extends Error {
|
|
73
|
+
constructor(code, message, details = {}) {
|
|
74
|
+
super(message);
|
|
75
|
+
this.name = 'RemoteError';
|
|
76
|
+
this.code = `${SERVICE_KEY}/${code}`;
|
|
77
|
+
this.details = details;
|
|
78
|
+
this.isDSHRemoteError = true;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// ── Git ───────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
83
|
+
|
|
84
|
+
/** Resolve a real git. `/usr/bin/git` on macOS can be the Xcode stub; confirm via `xcode-select -p` first. */
|
|
85
|
+
export async function resolveGit(subprocess) {
|
|
86
|
+
let executable;
|
|
87
|
+
try {
|
|
88
|
+
executable = await subprocess.resolveExecutable('git');
|
|
89
|
+
} catch {
|
|
90
|
+
return undefined;
|
|
91
|
+
}
|
|
92
|
+
if (process.platform === 'darwin' && executable === '/usr/bin/git') {
|
|
93
|
+
try {
|
|
94
|
+
const handle = await subprocessSpawn(subprocess, ['/usr/bin/xcode-select', '-p']);
|
|
95
|
+
if ((await handle.done).exitCode !== 0) return undefined;
|
|
96
|
+
} catch {
|
|
97
|
+
return undefined;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return executable;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function subprocessSpawn(subprocess, argv, options = {}) {
|
|
104
|
+
return subprocess.spawn({
|
|
105
|
+
argv,
|
|
106
|
+
cwd: options.cwd,
|
|
107
|
+
stdio: {
|
|
108
|
+
stdin: 'ignore',
|
|
109
|
+
stdout: { maxBytes: 16 * 1024 * 1024 },
|
|
110
|
+
stderr: { maxBytes: 16 * 1024 },
|
|
111
|
+
},
|
|
112
|
+
graceMs: 2_000,
|
|
113
|
+
signal: options.signal,
|
|
114
|
+
env: { GIT_CONFIG_COUNT: '0', GIT_TERMINAL_PROMPT: '0', GIT_OPTIONAL_LOCKS: '0', LC_ALL: 'C', ...options.env },
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
async function gitRun(subprocess, executable, args, options = {}) {
|
|
119
|
+
const timeout = AbortSignal.timeout(options.timeoutMs ?? GIT_TIMEOUT_MS);
|
|
120
|
+
const signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout;
|
|
121
|
+
const handle = await subprocessSpawn(subprocess, [executable, ...args], { ...options, signal });
|
|
122
|
+
const outcome = await handle.done;
|
|
123
|
+
if (signal.aborted) throw new CheckpointsError('git-timeout', `git ${args.join(' ')} timed out`);
|
|
124
|
+
return {
|
|
125
|
+
exitCode: outcome.exitCode,
|
|
126
|
+
stdout: handle.collected?.stdout?.readFrom(0)?.text ?? '',
|
|
127
|
+
stderr: handle.collected?.stderr?.readFrom(0)?.text ?? '',
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function gitOk(result, what) {
|
|
132
|
+
if (result.exitCode !== 0) throw new CheckpointsError('git-failed', `${what} failed: ${result.stderr.trim()}`);
|
|
133
|
+
return result;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Locate the repository enclosing `cwd` and its private object directory (persistent, under `objectsRoot`).
|
|
138
|
+
* The repo's own objects are alternates only — reads work, writes never land there.
|
|
139
|
+
*/
|
|
140
|
+
async function locateGit(subprocess, executable, cwd, objectsRoot, signal) {
|
|
141
|
+
const found = await gitRun(subprocess, executable, ['rev-parse', '--show-toplevel', '--absolute-git-dir', '--git-path', 'objects'], { cwd, signal });
|
|
142
|
+
if (found.exitCode === 128 && /not a git repository/i.test(found.stderr)) return undefined;
|
|
143
|
+
const [root, gitDir, repoObjects] = gitOk(found, 'git rev-parse').stdout.split('\n').map((l) => resolve(cwd, l));
|
|
144
|
+
const repoKey = createHash('sha256').update(root).digest('hex').slice(0, 24);
|
|
145
|
+
const objects = join(objectsRoot, repoKey);
|
|
146
|
+
await mkdir(objects, { recursive: true });
|
|
147
|
+
return { root, gitDir, repoKey, env: { GIT_OBJECT_DIRECTORY: objects, GIT_ALTERNATE_OBJECT_DIRECTORIES: repoObjects } };
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** The whole work tree (tracked + untracked, not ignored) as a private tree object; the repo stays untouched. */
|
|
151
|
+
async function snapshotTree(subprocess, executable, ws, signal) {
|
|
152
|
+
const scratch = await mkdtemp(join(tmpdir(), 'picasso-checkpoints-'));
|
|
153
|
+
try {
|
|
154
|
+
const index = join(scratch, 'index');
|
|
155
|
+
await copyFile(join(ws.gitDir, 'index'), index).catch((e) => {
|
|
156
|
+
if (!isMissing(e)) throw e;
|
|
157
|
+
});
|
|
158
|
+
const env = { ...ws.env, GIT_INDEX_FILE: index };
|
|
159
|
+
const added = await gitRun(subprocess, executable, ['add', '--all', '--ignore-errors'], { cwd: ws.root, env, signal });
|
|
160
|
+
if (added.exitCode !== 1) gitOk(added, 'git add');
|
|
161
|
+
return gitOk(await gitRun(subprocess, executable, ['write-tree'], { cwd: ws.root, env, signal }), 'git write-tree').stdout.trim();
|
|
162
|
+
} finally {
|
|
163
|
+
await rm(scratch, { recursive: true, force: true });
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** `diff-tree -r -M -z --name-status` between two snapshot trees. */
|
|
168
|
+
async function diffTrees(subprocess, executable, ws, before, after, signal) {
|
|
169
|
+
if (before === after) return [];
|
|
170
|
+
const result = gitOk(await gitRun(subprocess, executable, ['diff-tree', '-r', '-M', '-z', '--name-status', before, after], { cwd: ws.root, env: ws.env, signal }), 'git diff-tree');
|
|
171
|
+
const fields = result.stdout.split('\0').filter((f) => f !== '');
|
|
172
|
+
const entries = [];
|
|
173
|
+
for (let i = 0; i < fields.length; i += 1) {
|
|
174
|
+
const status = fields[i];
|
|
175
|
+
if (status.startsWith('R') || status.startsWith('C')) {
|
|
176
|
+
entries.push({ status: 'modified', path: fields[i + 2] ?? fields[i + 1], oldPath: fields[i + 1] });
|
|
177
|
+
i += 2;
|
|
178
|
+
} else {
|
|
179
|
+
entries.push({ status: status === 'A' ? 'added' : status === 'D' ? 'deleted' : 'modified', path: fields[i + 1] });
|
|
180
|
+
i += 1;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
return entries;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** What a snapshot tree holds at `path`: a blob (with its mode), a symlink (mode 120000), a gitlink, or undefined. */
|
|
187
|
+
async function treeEntry(subprocess, executable, ws, tree, path, signal) {
|
|
188
|
+
const out = gitOk(await gitRun(subprocess, executable, ['ls-tree', '-z', '-l', tree, '--', path], { cwd: ws.root, env: { ...ws.env, GIT_LITERAL_PATHSPECS: '1' }, signal }), 'git ls-tree').stdout.split('\0')[0];
|
|
189
|
+
const match = /^(\d+) (\S+) ([0-9a-f]+) +(-|\d+)\t/.exec(out);
|
|
190
|
+
if (!match) return undefined;
|
|
191
|
+
if (match[1] === '160000' || match[2] === 'commit') return { gitlink: true };
|
|
192
|
+
if (match[2] !== 'blob') return undefined;
|
|
193
|
+
return { mode: match[1], oid: match[3], symlink: match[1] === '120000', size: match[4] === '-' ? 0 : Number(match[4]) };
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
async function blobBytes(subprocess, executable, ws, oid, signal) {
|
|
197
|
+
const handle = await subprocessSpawn(subprocess, [executable, 'cat-file', 'blob', oid], { cwd: ws.root, env: ws.env, signal });
|
|
198
|
+
const outcome = await handle.done;
|
|
199
|
+
if (outcome.exitCode !== 0) throw new CheckpointsError('git-failed', 'git cat-file failed');
|
|
200
|
+
const text = handle.collected?.stdout?.readFrom(0)?.text;
|
|
201
|
+
return text === undefined ? undefined : Buffer.from(text, 'utf8');
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// ── File captures (non-git) ────────────────────────────────────────────────────────────────────────────────────
|
|
205
|
+
|
|
206
|
+
/** A content-addressed copy of `path` under `capturesDir`, or {absent:true}. */
|
|
207
|
+
async function captureFile(path, capturesDir) {
|
|
208
|
+
let bytes;
|
|
209
|
+
try {
|
|
210
|
+
bytes = await readFile(path);
|
|
211
|
+
} catch (error) {
|
|
212
|
+
if (isMissing(error)) return { absent: true };
|
|
213
|
+
if (error.code === 'EISDIR') return undefined; // directories are never captured
|
|
214
|
+
throw error;
|
|
215
|
+
}
|
|
216
|
+
if (bytes.length > MAX_FILE_BYTES) return undefined;
|
|
217
|
+
const mode = (await stat(path)).mode & 0o777;
|
|
218
|
+
const file = join(capturesDir, createHash('sha1').update(bytes).digest('hex'));
|
|
219
|
+
await mkdir(capturesDir, { recursive: true });
|
|
220
|
+
// AO-011.04: atomic capture — a process killed mid-write must not leave a
|
|
221
|
+
// truncated content-addressed file that every future 'wx' capture reuses.
|
|
222
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
223
|
+
await writeFile(tmp, bytes, { flag: 'wx' }).catch(async (e) => {
|
|
224
|
+
if (e.code !== 'EEXIST') throw e;
|
|
225
|
+
});
|
|
226
|
+
await rename(tmp, file).catch(async (e) => {
|
|
227
|
+
// Another capture may have committed the same content concurrently.
|
|
228
|
+
await rm(tmp, { force: true }).catch(() => undefined);
|
|
229
|
+
await access(file);
|
|
230
|
+
if (e.code !== 'EEXIST') throw e;
|
|
231
|
+
});
|
|
232
|
+
return { file, mode };
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
const sameCapture = (a, b) => (a?.absent === true && b?.absent === true) || (a?.file !== undefined && a.file === b?.file);
|
|
236
|
+
|
|
237
|
+
// ── Per-session recorder ───────────────────────────────────────────────────────────────────────────────────────
|
|
238
|
+
|
|
239
|
+
function freshTurn(turn) {
|
|
240
|
+
return { turn, baseline: undefined, captures: new Map(), done: false };
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
class Recorder {
|
|
244
|
+
constructor(service, sessionId, cwd) {
|
|
245
|
+
this.service = service;
|
|
246
|
+
this.sessionId = sessionId;
|
|
247
|
+
this.cwd = cwd;
|
|
248
|
+
this.chain = Promise.resolve();
|
|
249
|
+
this.state = freshTurn(0);
|
|
250
|
+
this.repo = undefined; // undefined = not looked up yet; null = non-git; object = located
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
enqueue(task) {
|
|
254
|
+
const run = this.chain.then(() => task().catch((e) => this.service.warn(`checkpoints: ${String(e)}`)));
|
|
255
|
+
this.chain = run;
|
|
256
|
+
return run;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
start(turn) {
|
|
260
|
+
const state = freshTurn(turn);
|
|
261
|
+
this.state = state;
|
|
262
|
+
this.enqueue(async () => {
|
|
263
|
+
const repo = await this.service.locate(this, this.cwd);
|
|
264
|
+
state.baseline = repo === null || repo === undefined ? { kind: 'files' }
|
|
265
|
+
: repo.kind === 'full' ? { kind: 'full', ws: repo, S: await snapshotTree(this.service.subprocess, this.service.git, repo) }
|
|
266
|
+
: { kind: 'git', ws: repo, S: await snapshotTree(this.service.subprocess, this.service.git, repo) };
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** The fs-intent pre-image: once per path per turn. */
|
|
271
|
+
capture(path) {
|
|
272
|
+
const state = this.state;
|
|
273
|
+
this.enqueue(async () => {
|
|
274
|
+
const absolute = resolve(path);
|
|
275
|
+
if (state.captures.has(absolute)) return;
|
|
276
|
+
const image = await captureFile(absolute, this.service.sessionDir(this.service.capturesDir, this.sessionId));
|
|
277
|
+
if (image !== undefined) state.captures.set(absolute, image);
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
end(turn) {
|
|
282
|
+
const state = this.state;
|
|
283
|
+
if (turn !== state.turn || state.done) return;
|
|
284
|
+
state.done = true;
|
|
285
|
+
this.enqueue(async () => {
|
|
286
|
+
const baseline = state.baseline;
|
|
287
|
+
if (baseline === undefined) return; // start() never resolved
|
|
288
|
+
const meta = await this.service.readMeta(this.sessionId);
|
|
289
|
+
const entry = { cwd: this.cwd, kind: baseline.kind, mode: baseline.kind === 'files' ? 'files' : baseline.kind === 'full' ? 'full' : 'git', changed: [] };
|
|
290
|
+
if (baseline.kind === 'files' && this.fellBackFromFull === true) entry.fellBackFrom = 'full';
|
|
291
|
+
if (baseline.kind === 'git' || baseline.kind === 'full') {
|
|
292
|
+
const { ws } = baseline;
|
|
293
|
+
entry.repo = ws.repoKey;
|
|
294
|
+
entry.repoRoot = ws.root;
|
|
295
|
+
entry.S = baseline.S;
|
|
296
|
+
entry.E = await snapshotTree(this.service.subprocess, this.service.git, ws);
|
|
297
|
+
for (const d of await diffTrees(this.service.subprocess, this.service.git, ws, baseline.S, entry.E)) {
|
|
298
|
+
entry.changed.push({ path: d.path, status: d.status, ...(d.oldPath ? { oldPath: d.oldPath } : {}) });
|
|
299
|
+
}
|
|
300
|
+
await this.service.noteRepo(ws.repoKey, ws.root);
|
|
301
|
+
} else {
|
|
302
|
+
const captures = {};
|
|
303
|
+
for (const [absolute, before] of state.captures) {
|
|
304
|
+
const after = await captureFile(absolute, this.service.sessionDir(this.service.capturesDir, this.sessionId));
|
|
305
|
+
if (after === undefined || sameCapture(before, after)) continue;
|
|
306
|
+
const status = before.absent ? 'added' : after.absent ? 'deleted' : 'modified';
|
|
307
|
+
entry.changed.push({ path: absolute, status });
|
|
308
|
+
captures[absolute] = { before, after };
|
|
309
|
+
}
|
|
310
|
+
entry.captures = captures;
|
|
311
|
+
}
|
|
312
|
+
meta.turns[String(state.turn)] = entry;
|
|
313
|
+
await this.service.writeMeta(this.sessionId, meta);
|
|
314
|
+
});
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
settled() {
|
|
318
|
+
return this.chain;
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
// ── Service ──────────────────────────────────────────────────────────────────────────────────────────────────
|
|
323
|
+
|
|
324
|
+
export class Checkpoints {
|
|
325
|
+
/**
|
|
326
|
+
* `options.root` — the persistence root (required in production via `dshHomePath('checkpoints')`).
|
|
327
|
+
* `options.subprocess` — the host's subprocess capability (resolveExecutable + spawn); tests inject a child_process
|
|
328
|
+
* adapter. `options.now` is injectable.
|
|
329
|
+
*/
|
|
330
|
+
constructor(options = {}) {
|
|
331
|
+
this.root = options.root ?? join(tmpdir(), 'picasso-checkpoints');
|
|
332
|
+
this.subprocess = options.subprocess;
|
|
333
|
+
this.now = options.now ?? Date.now;
|
|
334
|
+
this.warn = options.warn ?? ((m) => console.warn(m));
|
|
335
|
+
this.fullMaxFiles = options.fullMaxFiles ?? FULL_MAX_FILES;
|
|
336
|
+
this.fullMaxBytes = options.fullMaxBytes ?? FULL_MAX_BYTES;
|
|
337
|
+
this.capturesDir = join(this.root, 'captures');
|
|
338
|
+
this.sessionsDir = join(this.root, 'sessions');
|
|
339
|
+
this.objectsRoot = join(this.root, 'objects');
|
|
340
|
+
this.undoDir = join(this.root, 'undo');
|
|
341
|
+
this.reposFile = join(this.root, 'repos.json');
|
|
342
|
+
this.git = undefined; // resolved lazily, once
|
|
343
|
+
this.gitPromise = undefined;
|
|
344
|
+
this.recorders = new Map(); // session object -> Recorder
|
|
345
|
+
this.byId = new Map(); // sessionId -> Recorder
|
|
346
|
+
this.tail = Promise.resolve();
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
serial(body) {
|
|
350
|
+
const run = this.tail.then(body, body);
|
|
351
|
+
this.tail = run.catch(() => undefined);
|
|
352
|
+
return run;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
// ── wiring ────────────────────────────────────────────────────────────────────────────────────────────────
|
|
356
|
+
|
|
357
|
+
/** The git executable, resolved once; undefined when the host has no usable git. */
|
|
358
|
+
async gitBin() {
|
|
359
|
+
this.gitPromise ??= resolveGit(this.subprocess);
|
|
360
|
+
this.git = await this.gitPromise;
|
|
361
|
+
return this.git;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/** Locate the repo for a recorder once per session; null means non-git and is remembered. */
|
|
365
|
+
async locate(recorder, cwd) {
|
|
366
|
+
if (recorder.repo !== undefined) return recorder.repo;
|
|
367
|
+
const bin = await this.gitBin();
|
|
368
|
+
if (bin === undefined) { recorder.repo = null; return null; }
|
|
369
|
+
const real = await realpath(cwd).catch(() => cwd);
|
|
370
|
+
const ws = await locateGit(this.subprocess, bin, real, this.objectsRoot);
|
|
371
|
+
if (ws !== undefined) { recorder.repo = ws; return ws; }
|
|
372
|
+
// Non-git: the whole-workspace snapshot runs through the same git plumbing with a private bare GIT_DIR, but
|
|
373
|
+
// only for workspaces that stay inside the budget — /, ~, and oversized trees keep intent capture.
|
|
374
|
+
recorder.repo = await this.fullWs(real);
|
|
375
|
+
// AO-011.04: record the explicit full→intent fallback on the turn entry so
|
|
376
|
+
// the reduced-visibility capture mode is auditable, not silent.
|
|
377
|
+
if (recorder.repo === null) recorder.fellBackFromFull = true;
|
|
378
|
+
return recorder.repo;
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
recorderFor(session) {
|
|
382
|
+
let recorder = this.recorders.get(session);
|
|
383
|
+
if (recorder === undefined) {
|
|
384
|
+
const cwd = session?.header?.cwd;
|
|
385
|
+
if (typeof cwd !== 'string' || !cwd) return undefined;
|
|
386
|
+
recorder = new Recorder(this, session.id, cwd);
|
|
387
|
+
this.recorders.set(session, recorder);
|
|
388
|
+
this.byId.set(session.id, recorder);
|
|
389
|
+
}
|
|
390
|
+
return recorder;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
forget(session) {
|
|
394
|
+
this.recorders.delete(session);
|
|
395
|
+
if (session?.id) this.byId.delete(session.id);
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/**
|
|
399
|
+
* A non-git workspace's private snapshot repo: `<objectsRoot>/wt-<sha1(cwd)>` as a bare GIT_DIR with the
|
|
400
|
+
* workspace as work tree, its own info/exclude plus the tree's .gitignore. `null` = stay on intent capture.
|
|
401
|
+
*/
|
|
402
|
+
async fullWs(cwd, signal) {
|
|
403
|
+
const bin = await this.gitBin();
|
|
404
|
+
if (bin === undefined) return null;
|
|
405
|
+
// The sandboxed app's homedir() is the container; getpwuid's is the real one. Refuse either and any
|
|
406
|
+
// ancestor of the real home (/Users, /Users/<name> included).
|
|
407
|
+
const realHome = (() => { try { return userInfo().homedir; } catch { return undefined; } })();
|
|
408
|
+
const homes = [homedir(), realHome].filter((h) => typeof h === 'string' && h.length > 0);
|
|
409
|
+
if (cwd === '/' || homes.some((home) => cwd === home || home.startsWith(cwd + '/'))) return null;
|
|
410
|
+
if (!(await fullWithinBudget(cwd, this.fullMaxFiles, this.fullMaxBytes))) return null;
|
|
411
|
+
const key = `wt-${createHash('sha1').update(cwd).digest('hex').slice(0, 16)}`;
|
|
412
|
+
const dir = join(this.objectsRoot, key);
|
|
413
|
+
if (!existsSync(join(dir, 'objects'))) {
|
|
414
|
+
await mkdir(join(dir, 'info'), { recursive: true });
|
|
415
|
+
await writeFile(join(dir, 'info', 'exclude'), `${FULL_EXCLUDES.map((d) => `${d}/`).join('\n')}\n`, 'utf8');
|
|
416
|
+
gitOk(await gitRun(this.subprocess, bin, ['init', '--bare', dir], { signal }), 'git init');
|
|
417
|
+
}
|
|
418
|
+
return { kind: 'full', root: cwd, gitDir: dir, repoKey: key, env: { GIT_DIR: dir, GIT_WORK_TREE: cwd } };
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
// ── persistence ───────────────────────────────────────────────────────────────────────────────────────────
|
|
422
|
+
|
|
423
|
+
metaPath(sessionId) {
|
|
424
|
+
return join(this.sessionsDir, `${encodeURIComponent(sessionId)}.json`);
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/** Session ids join into directory names the same way metaPath encodes them. */
|
|
428
|
+
sessionDir(base, sessionId) {
|
|
429
|
+
return join(base, encodeURIComponent(sessionId));
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
async readMeta(sessionId) {
|
|
433
|
+
try {
|
|
434
|
+
const meta = JSON.parse(await readFile(this.metaPath(sessionId), 'utf8'));
|
|
435
|
+
return isRecord(meta) && isRecord(meta.turns) ? meta : { version: 1, sessionId, turns: {} };
|
|
436
|
+
} catch {
|
|
437
|
+
return { version: 1, sessionId, turns: {} };
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
async writeMeta(sessionId, meta) {
|
|
442
|
+
await mkdir(this.sessionsDir, { recursive: true });
|
|
443
|
+
const file = this.metaPath(sessionId);
|
|
444
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
445
|
+
await writeFile(tmp, `${JSON.stringify(meta)}\n`, { mode: 0o600 });
|
|
446
|
+
await (await import('node:fs/promises')).rename(tmp, file);
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
async noteRepo(repoKey, root) {
|
|
450
|
+
await mkdir(this.objectsRoot, { recursive: true });
|
|
451
|
+
let repos = {};
|
|
452
|
+
try { repos = JSON.parse(await readFile(this.reposFile, 'utf8')); } catch { /* fresh */ }
|
|
453
|
+
if (!isRecord(repos[repoKey]) || repos[repoKey].root !== root) {
|
|
454
|
+
repos[repoKey] = { root };
|
|
455
|
+
await writeFile(this.reposFile, JSON.stringify(repos), 'utf8');
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
// ── content access ────────────────────────────────────────────────────────────────────────────────────────
|
|
460
|
+
|
|
461
|
+
/** A git workspace view of a recorded turn: private objects under root, the repo's objects as alternates. */
|
|
462
|
+
async gitWs(entry, signal) {
|
|
463
|
+
const bin = await this.gitBin();
|
|
464
|
+
if (bin === undefined) throw new CheckpointsError('git-unavailable', 'git is not available on this host.');
|
|
465
|
+
if (entry.kind === 'full') {
|
|
466
|
+
return { root: entry.repoRoot, gitDir: join(this.objectsRoot, entry.repo), env: { GIT_DIR: join(this.objectsRoot, entry.repo), GIT_WORK_TREE: entry.repoRoot } };
|
|
467
|
+
}
|
|
468
|
+
const lines = gitOk(await gitRun(this.subprocess, bin, ['rev-parse', '--absolute-git-dir', '--git-path', 'objects'], { cwd: entry.repoRoot, signal }), 'git rev-parse').stdout.split('\n');
|
|
469
|
+
return {
|
|
470
|
+
root: entry.repoRoot,
|
|
471
|
+
gitDir: resolve(entry.repoRoot, lines[0]),
|
|
472
|
+
env: { GIT_OBJECT_DIRECTORY: join(this.objectsRoot, entry.repo), GIT_ALTERNATE_OBJECT_DIRECTORIES: resolve(entry.repoRoot, lines[1] ?? 'objects') },
|
|
473
|
+
};
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
/** A turn entry's content for `path`: {absent} | {file} (files kind) or {mode, oid, ws} (git kind). */
|
|
477
|
+
async sideOf(entry, path, which, signal) {
|
|
478
|
+
if (entry.kind === 'git' || entry.kind === 'full') {
|
|
479
|
+
const hit = await treeEntry(this.subprocess, await this.gitBin(), await this.gitWs(entry, signal), which === 'S' ? entry.S : entry.E, path, signal);
|
|
480
|
+
return hit === undefined ? { absent: true } : hit;
|
|
481
|
+
}
|
|
482
|
+
const capture = entry.captures?.[path]?.[which === 'S' ? 'before' : 'after'];
|
|
483
|
+
if (capture === undefined) return { absent: true };
|
|
484
|
+
return capture;
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
async bytesOf(entry, path, which, signal) {
|
|
488
|
+
const side = await this.sideOf(entry, path, which, signal);
|
|
489
|
+
if (side.absent === true) return undefined;
|
|
490
|
+
if (side.file !== undefined) return readFile(side.file);
|
|
491
|
+
return blobBytes(this.subprocess, await this.gitBin(), side.ws ?? await this.gitWs(entry, signal), side.oid, signal);
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
/** All paths ∪ changed(n) for n >= turn; `first`/`last` are the entries of the earliest/latest changing turn. */
|
|
495
|
+
async changedSince(sessionId, turn) {
|
|
496
|
+
const meta = await this.readMeta(sessionId);
|
|
497
|
+
const byPath = new Map();
|
|
498
|
+
const keys = Object.keys(meta.turns).map(Number).filter((n) => n >= turn).sort((a, b) => a - b);
|
|
499
|
+
for (const n of keys) {
|
|
500
|
+
const entry = meta.turns[String(n)];
|
|
501
|
+
for (const change of entry.changed ?? []) {
|
|
502
|
+
const hit = byPath.get(change.path);
|
|
503
|
+
byPath.set(change.path, { first: hit?.first ?? entry, last: entry, status: change.status });
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
const start = meta.turns[String(turn)];
|
|
507
|
+
return { meta, byPath, start };
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
/** `files`: state on disk relative to S_turn; `edited`: disk drifted since the agent's last touch (E_m). */
|
|
511
|
+
async preview(sessionId, turn) {
|
|
512
|
+
const { byPath, start } = await this.changedSince(sessionId, turn);
|
|
513
|
+
if (start === undefined) return { files: [], edited: [], kind: 'none' };
|
|
514
|
+
const kind = start.kind;
|
|
515
|
+
const files = [];
|
|
516
|
+
const edited = [];
|
|
517
|
+
for (const [path, { last }] of byPath) {
|
|
518
|
+
const absolute = isAbsolute(path) ? path : resolve(last.repoRoot ?? last.cwd, path);
|
|
519
|
+
const [sContent, disk] = await Promise.all([
|
|
520
|
+
this.bytesOf(start, path, 'S').catch(() => undefined),
|
|
521
|
+
// A directory at the path is a write-time conflict (dirFileConflict
|
|
522
|
+
// skips it), not diffable content — never a fatal read.
|
|
523
|
+
readFile(absolute).catch((e) => (isMissing(e) || e?.code === 'EISDIR' ? undefined : Promise.reject(e))),
|
|
524
|
+
]);
|
|
525
|
+
const sHas = sContent !== undefined;
|
|
526
|
+
const dHas = disk !== undefined;
|
|
527
|
+
if (sHas && !dHas) files.push({ path, status: 'deleted' });
|
|
528
|
+
else if (!sHas && dHas) files.push({ path, status: 'added' });
|
|
529
|
+
else if (sHas && dHas && (!sContent.equals(disk) || await this.modeDrifted(start, path, absolute))) files.push({ path, status: 'modified' });
|
|
530
|
+
if (!dHas) continue;
|
|
531
|
+
const eContent = await this.bytesOf(last, path, 'E').catch(() => undefined);
|
|
532
|
+
if (eContent !== undefined && !eContent.equals(disk)) edited.push(path);
|
|
533
|
+
}
|
|
534
|
+
files.sort((a, b) => (a.path < b.path ? -1 : 1));
|
|
535
|
+
edited.sort();
|
|
536
|
+
return { files, edited, kind, mode: start.mode ?? (start.kind === 'git' ? 'git' : 'files') };
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
/**
|
|
540
|
+
* Read-only evidence for turns >= `turn` (ATD-P007): private snapshot refs (never repository commits), changed
|
|
541
|
+
* paths, coverage mode (git / non-git-full / files-only), diff stats, pruned/missing refs and — via `preview` —
|
|
542
|
+
* the current disk state. Serialised behind restores so it never observes a half-applied restore.
|
|
543
|
+
*/
|
|
544
|
+
async evidence(sessionId, turn, options = {}) {
|
|
545
|
+
return this.serial(() => collectEvidence(this, sessionId, turn, options, { gitRun, builtinExcludes: FULL_EXCLUDES }));
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
/**
|
|
549
|
+
* Write each listed path back to its S_turn content (or delete it when absent there). The current content of
|
|
550
|
+
* every touched path is saved as `undoId` BEFORE any file moves — a mid-restore failure then rolls back from
|
|
551
|
+
* that record in place, and a process killed mid-restore leaves a durable `in-progress` record `recover()`
|
|
552
|
+
* reports (AO-011.04). Entries git cannot replay (symlinks are restored, but gitlinks and file/dir conflicts)
|
|
553
|
+
* come back in `skipped`; `edited` lists paths whose disk content had drifted from E_m (concurrent user
|
|
554
|
+
* edits the restore overwrote — visible, never silently lost).
|
|
555
|
+
*/
|
|
556
|
+
async restore(sessionId, turn) {
|
|
557
|
+
return this.serial(async () => {
|
|
558
|
+
const { byPath, start } = await this.changedSince(sessionId, turn);
|
|
559
|
+
if (start === undefined) throw new CheckpointsError('no-checkpoint', `No checkpoint for turn ${turn}.`, { sessionId, turn });
|
|
560
|
+
const undoId = `u-${this.now()}-${createHash('sha1').update(String(Math.random())).digest('hex').slice(0, 8)}`;
|
|
561
|
+
const restored = [];
|
|
562
|
+
const skipped = [];
|
|
563
|
+
|
|
564
|
+
if (start.kind === 'git' || start.kind === 'full') {
|
|
565
|
+
const bin = await this.gitBin();
|
|
566
|
+
const ws = await this.gitWs(start);
|
|
567
|
+
const edited = await this.editedSinceLastAgentTouch(byPath);
|
|
568
|
+
const undo = { id: undoId, sessionId, kind: start.kind, repo: start.repo, repoRoot: start.repoRoot, tree: await snapshotTree(this.subprocess, bin, ws), paths: [...byPath.keys()], ...(edited.length === 0 ? {} : { edited }), state: 'in-progress' };
|
|
569
|
+
await this.writeUndo(undo);
|
|
570
|
+
try {
|
|
571
|
+
for (const [path] of byPath) {
|
|
572
|
+
const absolute = resolve(start.repoRoot, path);
|
|
573
|
+
const s = await treeEntry(this.subprocess, bin, ws, start.S, path);
|
|
574
|
+
if (s?.gitlink === true) { skipped.push(path); continue; }
|
|
575
|
+
if (await this.dirFileConflict(absolute, s !== undefined)) { skipped.push(path); continue; }
|
|
576
|
+
await this.writeGitEntry(absolute, s, bin, ws);
|
|
577
|
+
restored.push(path);
|
|
578
|
+
}
|
|
579
|
+
} catch (error) {
|
|
580
|
+
// Roll back through the durable record — and never swallow a rollback
|
|
581
|
+
// failure: it is surfaced on the thrown error and in the journal.
|
|
582
|
+
const rollbackError = await this.applyUndoRecord(undo).then(() => undefined, (e) => e);
|
|
583
|
+
await this.markUndo(undo.id, rollbackError === undefined ? 'rolled-back' : 'rollback-failed', rollbackError);
|
|
584
|
+
if (rollbackError !== undefined) {
|
|
585
|
+
throw new CheckpointsError('restore-failed', `${error instanceof Error ? error.message : String(error)}; rollback also failed: ${rollbackError instanceof Error ? rollbackError.message : String(rollbackError)}`, { undoId, rollbackError: String(rollbackError) });
|
|
586
|
+
}
|
|
587
|
+
throw error;
|
|
588
|
+
}
|
|
589
|
+
await this.markUndo(undoId, 'applied');
|
|
590
|
+
return { restored, skipped, edited, undoId };
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
const edited = await this.editedSinceLastAgentTouch(byPath);
|
|
594
|
+
const undo = { id: undoId, sessionId, kind: 'files', paths: [], ...(edited.length === 0 ? {} : { edited }), state: 'in-progress' };
|
|
595
|
+
for (const [path] of byPath) {
|
|
596
|
+
const disk = await captureFile(path, join(this.capturesDir, 'undo'));
|
|
597
|
+
undo.paths.push({ path, ...(disk ?? { absent: true }) });
|
|
598
|
+
}
|
|
599
|
+
await this.writeUndo(undo);
|
|
600
|
+
try {
|
|
601
|
+
for (const [path, { first }] of byPath) {
|
|
602
|
+
const before = first.captures?.[path]?.before;
|
|
603
|
+
if (before === undefined || before.absent === true) {
|
|
604
|
+
await rm(path, { force: true });
|
|
605
|
+
} else {
|
|
606
|
+
await mkdir(dirname(path), { recursive: true });
|
|
607
|
+
await writeFile(path, await readFile(before.file));
|
|
608
|
+
if (before.mode !== undefined) await chmod(path, before.mode);
|
|
609
|
+
}
|
|
610
|
+
restored.push(path);
|
|
611
|
+
}
|
|
612
|
+
} catch (error) {
|
|
613
|
+
const rollbackError = await this.applyUndoRecord(undo).then(() => undefined, (e) => e);
|
|
614
|
+
await this.markUndo(undo.id, rollbackError === undefined ? 'rolled-back' : 'rollback-failed', rollbackError);
|
|
615
|
+
if (rollbackError !== undefined) {
|
|
616
|
+
throw new CheckpointsError('restore-failed', `${error instanceof Error ? error.message : String(error)}; rollback also failed: ${rollbackError instanceof Error ? rollbackError.message : String(rollbackError)}`, { undoId, rollbackError: String(rollbackError) });
|
|
617
|
+
}
|
|
618
|
+
throw error;
|
|
619
|
+
}
|
|
620
|
+
await this.markUndo(undoId, 'applied');
|
|
621
|
+
return { restored, skipped, edited, undoId };
|
|
622
|
+
});
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
/** Paths whose disk content drifted from E_m — concurrent user edits the restore is about to overwrite. */
|
|
626
|
+
async editedSinceLastAgentTouch(byPath) {
|
|
627
|
+
const edited = [];
|
|
628
|
+
for (const [path, { last }] of byPath) {
|
|
629
|
+
const absolute = isAbsolute(path) ? path : resolve(last.repoRoot ?? last.cwd, path);
|
|
630
|
+
const disk = await readFile(absolute).catch((e) => (isMissing(e) || e?.code === 'EISDIR' ? undefined : Promise.reject(e)));
|
|
631
|
+
if (disk === undefined) continue;
|
|
632
|
+
const eContent = await this.bytesOf(last, path, 'E').catch(() => undefined);
|
|
633
|
+
if (eContent !== undefined && !eContent.equals(disk)) edited.push(path);
|
|
634
|
+
}
|
|
635
|
+
edited.sort();
|
|
636
|
+
return edited;
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
/** A git entry's exec bit vs the file on disk — mode-only changes must still preview as modified. */
|
|
640
|
+
async modeDrifted(entry, path, absolute) {
|
|
641
|
+
if (entry.kind !== 'git' && entry.kind !== 'full') return false;
|
|
642
|
+
try {
|
|
643
|
+
const side = await this.sideOf(entry, path, 'S');
|
|
644
|
+
if (side.absent === true || side.symlink === true) return false;
|
|
645
|
+
const diskMode = (await lstat(absolute)).mode & 0o111;
|
|
646
|
+
return (side.mode === '100755') !== (diskMode !== 0);
|
|
647
|
+
} catch {
|
|
648
|
+
return false;
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
/** A directory at the restore target is never deleted or overwritten; other non-files are skipped too. */
|
|
653
|
+
async dirFileConflict(absolute, sHasFile) {
|
|
654
|
+
const stats = await lstat(absolute).catch(() => undefined);
|
|
655
|
+
if (stats === undefined) return false;
|
|
656
|
+
if (stats.isDirectory()) return true;
|
|
657
|
+
if (!stats.isFile() && !stats.isSymbolicLink() && sHasFile) return true; // fifo/socket/device
|
|
658
|
+
return false;
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
/** Materialise a snapshot-tree entry at `absolute`: file (with chmod) or symlink; absent entry deletes. */
|
|
662
|
+
async writeGitEntry(absolute, s, bin, ws) {
|
|
663
|
+
if (s === undefined) {
|
|
664
|
+
await rm(absolute, { force: true });
|
|
665
|
+
return;
|
|
666
|
+
}
|
|
667
|
+
const bytes = await blobBytes(this.subprocess, bin, ws, s.oid);
|
|
668
|
+
if (bytes === undefined) throw new CheckpointsError('restore-failed', `Could not read ${absolute} from its checkpoint.`);
|
|
669
|
+
if (s.symlink === true) {
|
|
670
|
+
await rm(absolute, { force: true });
|
|
671
|
+
await symlink(bytes.toString('utf8'), absolute);
|
|
672
|
+
return;
|
|
673
|
+
}
|
|
674
|
+
await mkdir(dirname(absolute), { recursive: true });
|
|
675
|
+
await writeFile(absolute, bytes);
|
|
676
|
+
await chmod(absolute, s.mode === '100755' ? 0o755 : 0o644);
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
/** Atomic write: tmp file + rename, so a crash never leaves a torn journal entry (AO-011.04). */
|
|
680
|
+
async writeUndo(undo) {
|
|
681
|
+
await mkdir(this.undoDir, { recursive: true });
|
|
682
|
+
const file = join(this.undoDir, `${undo.id}.json`);
|
|
683
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
684
|
+
await writeFile(tmp, JSON.stringify(undo), { mode: 0o600 });
|
|
685
|
+
await rename(tmp, file);
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
/** Re-stamp a journal record's lifecycle state (`applied`, `rolled-back`, `rollback-failed`, `undone`). */
|
|
689
|
+
async markUndo(undoId, state, detail) {
|
|
690
|
+
const undo = await this.readUndo(undoId).catch(() => undefined);
|
|
691
|
+
if (undo === undefined) return;
|
|
692
|
+
await this.writeUndo({
|
|
693
|
+
...undo,
|
|
694
|
+
state,
|
|
695
|
+
...(detail === undefined ? {} : { detail: detail instanceof Error ? detail.message : String(detail) }),
|
|
696
|
+
});
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
async readUndo(undoId) {
|
|
700
|
+
if (!/^u-\d+-[0-9a-f]{8}$/.test(undoId)) {
|
|
701
|
+
throw new CheckpointsError('bad-request', `Malformed undo id ${String(undoId).slice(0, 64)}.`, { undoId });
|
|
702
|
+
}
|
|
703
|
+
let undo;
|
|
704
|
+
try {
|
|
705
|
+
undo = JSON.parse(await readFile(join(this.undoDir, `${undoId}.json`), 'utf8'));
|
|
706
|
+
} catch {
|
|
707
|
+
throw new CheckpointsError('no-undo', `No undo record ${undoId}.`, { undoId });
|
|
708
|
+
}
|
|
709
|
+
if (!isRecord(undo) || typeof undo.id !== 'string' || typeof undo.kind !== 'string' || !Array.isArray(undo.paths)) {
|
|
710
|
+
throw new CheckpointsError('no-undo', `Undo record ${undoId} is unreadable.`, { undoId });
|
|
711
|
+
}
|
|
712
|
+
return undo;
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
/**
|
|
716
|
+
* Durable recovery scan (AO-011.04): undo records left `in-progress` or
|
|
717
|
+
* `rollback-failed` by a crashed restore — each can be replayed with
|
|
718
|
+
* `undoRestore(undoId)` to return the workspace to its pre-restore content.
|
|
719
|
+
*/
|
|
720
|
+
async recover() {
|
|
721
|
+
const pending = [];
|
|
722
|
+
for (const file of await readdir(this.undoDir).catch(() => [])) {
|
|
723
|
+
if (!file.endsWith('.json')) continue;
|
|
724
|
+
try {
|
|
725
|
+
const undo = JSON.parse(await readFile(join(this.undoDir, file), 'utf8'));
|
|
726
|
+
if (!isRecord(undo) || typeof undo.id !== 'string') continue;
|
|
727
|
+
if (undo.state === 'in-progress' || undo.state === 'rollback-failed') {
|
|
728
|
+
pending.push({
|
|
729
|
+
undoId: undo.id,
|
|
730
|
+
sessionId: undo.sessionId,
|
|
731
|
+
state: undo.state,
|
|
732
|
+
kind: undo.kind,
|
|
733
|
+
paths: (undo.paths ?? []).map((entry) => (typeof entry === 'string' ? entry : entry.path)),
|
|
734
|
+
...(undo.detail === undefined ? {} : { detail: undo.detail }),
|
|
735
|
+
});
|
|
736
|
+
}
|
|
737
|
+
} catch { /* unreadable journal entry: skip */ }
|
|
738
|
+
}
|
|
739
|
+
return { pending };
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
/** Apply a persisted undo record: git tree entries or captured files. Shared by restore rollback and undoRestore. */
|
|
743
|
+
async applyUndoRecord(undo) {
|
|
744
|
+
if (undo.kind === 'git' || undo.kind === 'full') {
|
|
745
|
+
const bin = await this.gitBin();
|
|
746
|
+
const ws = await this.gitWs({ kind: undo.kind, repo: undo.repo, repoRoot: undo.repoRoot });
|
|
747
|
+
const restored = [];
|
|
748
|
+
for (const path of undo.paths) {
|
|
749
|
+
const absolute = resolve(undo.repoRoot, path);
|
|
750
|
+
const s = await treeEntry(this.subprocess, bin, ws, undo.tree, path);
|
|
751
|
+
if (s?.gitlink === true || await this.dirFileConflict(absolute, s !== undefined)) continue;
|
|
752
|
+
await this.writeGitEntry(absolute, s, bin, ws);
|
|
753
|
+
restored.push(path);
|
|
754
|
+
}
|
|
755
|
+
return restored;
|
|
756
|
+
}
|
|
757
|
+
const restored = [];
|
|
758
|
+
for (const entry of undo.paths) {
|
|
759
|
+
if (entry.absent === true || entry.file === undefined) await rm(entry.path, { force: true });
|
|
760
|
+
else {
|
|
761
|
+
await mkdir(dirname(entry.path), { recursive: true });
|
|
762
|
+
await writeFile(entry.path, await readFile(entry.file));
|
|
763
|
+
if (entry.mode !== undefined) await chmod(entry.path, entry.mode);
|
|
764
|
+
}
|
|
765
|
+
restored.push(entry.path);
|
|
766
|
+
}
|
|
767
|
+
return restored;
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
async repoRootOf(repoKey) {
|
|
771
|
+
try {
|
|
772
|
+
const repos = JSON.parse(await readFile(this.reposFile, 'utf8'));
|
|
773
|
+
return repos[repoKey]?.root;
|
|
774
|
+
} catch {
|
|
775
|
+
return undefined;
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
/**
|
|
780
|
+
* Restore the paths an `undoId` recorded; the record stays so a retry cannot
|
|
781
|
+
* make it worse. Applying a record that was already undone is idempotent —
|
|
782
|
+
* it rewrites the same captured content (AO-011.04).
|
|
783
|
+
*/
|
|
784
|
+
async undoRestore(undoId) {
|
|
785
|
+
return this.serial(async () => {
|
|
786
|
+
const undo = await this.readUndo(undoId);
|
|
787
|
+
const restored = await this.applyUndoRecord(undo);
|
|
788
|
+
await this.markUndo(undoId, 'undone');
|
|
789
|
+
return { restored };
|
|
790
|
+
});
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
/** The fork inherits the checkpoints before the edited turn (object stores are shared per repo). */
|
|
794
|
+
async adopt(fromSessionId, toSessionId, beforeTurn) {
|
|
795
|
+
return this.serial(async () => {
|
|
796
|
+
const from = await this.readMeta(fromSessionId);
|
|
797
|
+
const to = await this.readMeta(toSessionId);
|
|
798
|
+
for (const [key, entry] of Object.entries(from.turns)) {
|
|
799
|
+
if (Number(key) < beforeTurn) to.turns[key] = entry;
|
|
800
|
+
}
|
|
801
|
+
await this.writeMeta(toSessionId, to);
|
|
802
|
+
return {};
|
|
803
|
+
});
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
/** Remove a session's record; a repo's private objects go once no session references them. */
|
|
807
|
+
async drop(sessionId) {
|
|
808
|
+
return this.serial(async () => {
|
|
809
|
+
let meta;
|
|
810
|
+
try { meta = JSON.parse(await readFile(this.metaPath(sessionId), 'utf8')); } catch { meta = undefined; }
|
|
811
|
+
await rm(this.metaPath(sessionId), { force: true });
|
|
812
|
+
const repos = new Set();
|
|
813
|
+
for (const entry of Object.values(meta?.turns ?? {})) if (entry?.repo) repos.add(entry.repo);
|
|
814
|
+
if (repos.size > 0) {
|
|
815
|
+
for (const file of await readdir(this.sessionsDir).catch(() => [])) {
|
|
816
|
+
try {
|
|
817
|
+
const other = JSON.parse(await readFile(join(this.sessionsDir, file), 'utf8'));
|
|
818
|
+
for (const entry of Object.values(other.turns ?? {})) repos.delete(entry?.repo);
|
|
819
|
+
} catch { /* corrupt file: keep its objects */ }
|
|
820
|
+
}
|
|
821
|
+
for (const repoKey of repos) await rm(join(this.objectsRoot, repoKey), { recursive: true, force: true });
|
|
822
|
+
}
|
|
823
|
+
return {};
|
|
824
|
+
});
|
|
825
|
+
}
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
/** The gateway's source-mode Remote markers. */
|
|
829
|
+
Object.defineProperty(Checkpoints.prototype, REMOTE_METHOD_DESCRIPTOR, {
|
|
830
|
+
configurable: true,
|
|
831
|
+
value: Object.freeze({
|
|
832
|
+
version: 1,
|
|
833
|
+
methods: Object.freeze(['preview', 'evidence', 'restore', 'undoRestore', 'recover', 'adopt', 'drop'].map((method) => Object.freeze({ method, invocation: Object.freeze({ kind: 'direct' }) }))),
|
|
834
|
+
}),
|
|
835
|
+
});
|
|
836
|
+
|
|
837
|
+
/** Cordis entry: per-session recorders driven by turn + fs-intent hooks; `checkpoints` Remote service. */
|
|
838
|
+
export function apply(ctx, config) {
|
|
839
|
+
const service = new Checkpoints({
|
|
840
|
+
root: config?.root ?? join(process.env.DSH_HOME ?? tmpdir(), 'checkpoints'),
|
|
841
|
+
subprocess: ctx.subprocess,
|
|
842
|
+
warn: (m) => ctx.logger?.warn?.(m),
|
|
843
|
+
...(config?.fullMaxFiles !== undefined ? { fullMaxFiles: config.fullMaxFiles } : {}),
|
|
844
|
+
...(config?.fullMaxBytes !== undefined ? { fullMaxBytes: config.fullMaxBytes } : {}),
|
|
845
|
+
});
|
|
846
|
+
service.typertRemote = Object.freeze({ service, serviceKey: SERVICE_KEY, namespace: SERVICE_KEY });
|
|
847
|
+
ctx.provide(SERVICE_KEY, service);
|
|
848
|
+
|
|
849
|
+
const mutations = new WeakMap();
|
|
850
|
+
ctx.on('session/event', (session, event) => {
|
|
851
|
+
if (event.type === 'turn/start') service.recorderFor(session)?.start(event.data.turn);
|
|
852
|
+
else if (event.type === 'turn/end') service.recorders.get(session)?.end(event.data.turn);
|
|
853
|
+
});
|
|
854
|
+
ctx.on('agent/turn-stopping', async ({ agent, turn }) => {
|
|
855
|
+
await service.recorders.get(agent?.session)?.end(turn);
|
|
856
|
+
await service.recorders.get(agent?.session)?.settled();
|
|
857
|
+
});
|
|
858
|
+
ctx.on('session/disposed', (session) => service.forget(session));
|
|
859
|
+
const capture = async (target, actor) => {
|
|
860
|
+
const recorder = actor === undefined ? undefined : mutations.get(actor);
|
|
861
|
+
if (recorder === undefined) return;
|
|
862
|
+
recorder.capture(ctx.fs.processPath(target));
|
|
863
|
+
await recorder.settled();
|
|
864
|
+
};
|
|
865
|
+
ctx.on('fs/write-intent', async (target, actor, next) => {
|
|
866
|
+
const intent = await next();
|
|
867
|
+
await capture(target, actor);
|
|
868
|
+
return intent;
|
|
869
|
+
}, { prepend: true });
|
|
870
|
+
ctx.on('fs/edit-intent', async (target, actor, next) => {
|
|
871
|
+
const intent = await next();
|
|
872
|
+
await capture(target, actor);
|
|
873
|
+
return intent;
|
|
874
|
+
}, { prepend: true });
|
|
875
|
+
// A tool must never overtake the turn-start baseline: settle the queue before it runs.
|
|
876
|
+
ctx.on('tools/pre-execute', async (exec, next) => {
|
|
877
|
+
const session = exec.agent?.session;
|
|
878
|
+
const recorder = session === undefined ? undefined : service.recorders.get(session);
|
|
879
|
+
if (recorder !== undefined) {
|
|
880
|
+
mutations.set(exec, recorder);
|
|
881
|
+
await recorder.settled();
|
|
882
|
+
}
|
|
883
|
+
return next();
|
|
884
|
+
});
|
|
885
|
+
}
|