@parcha/agentrun-serve 0.1.0-beta.59 → 0.1.0-beta.60
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 +77 -0
- package/README.md +188 -106
- package/dist/agent-delete.d.ts +6 -9
- package/dist/agent-delete.js +5 -3
- package/dist/agent-package.js +11 -1
- package/dist/api-only.d.ts +2 -2
- package/dist/api-only.js +3 -3
- package/dist/archil-routes.d.ts +4 -1
- package/dist/archil-routes.js +15 -12
- package/dist/archil-settings.d.ts +18 -8
- package/dist/archil-settings.js +35 -17
- package/dist/chatgpt-plan.d.ts +4 -2
- package/dist/chatgpt-plan.js +13 -3
- package/dist/claude-login-token.d.ts +5 -0
- package/dist/claude-login-token.js +8 -0
- package/dist/claude-login.d.ts +49 -3
- package/dist/claude-login.js +140 -10
- package/dist/cli-learning/connections.js +1 -1
- package/dist/console/assets/{backend-BztxEAvb.js → backend-QnwGVBeU.js} +1 -1
- package/dist/console/assets/index-DZi-muIj.js +629 -0
- package/dist/console/assets/{share-L84tlUDW.js → share-pz61zIn9.js} +2 -2
- package/dist/console/assets/{styles-CaRKlHke.js → styles-CcceGcu2.js} +31 -31
- package/dist/console/assets/styles-fjQBFfMv.css +1 -0
- package/dist/console/index.html +3 -3
- package/dist/console/share.html +3 -3
- package/dist/decisions.d.ts +1 -1
- package/dist/decisions.js +2 -2
- package/dist/factory-activity.d.ts +68 -0
- package/dist/factory-activity.js +153 -0
- package/dist/factory-runs.d.ts +11 -0
- package/dist/factory-runs.js +52 -0
- package/dist/filed-tool.d.ts +32 -0
- package/dist/filed-tool.js +122 -0
- package/dist/harness-keys.d.ts +1 -2
- package/dist/harness-keys.js +1 -2
- package/dist/harness-table.d.ts +4 -0
- package/dist/harness-table.js +4 -0
- package/dist/harness.js +6 -2
- package/dist/import-worker.js +2 -2
- package/dist/import.d.ts +9 -0
- package/dist/import.js +11 -1
- package/dist/key-refusal.d.ts +5 -0
- package/dist/key-refusal.js +25 -15
- package/dist/learn/audit.d.ts +20 -22
- package/dist/learn/audit.js +72 -55
- package/dist/learn/check.js +1 -1
- package/dist/learn/commit.d.ts +35 -43
- package/dist/learn/commit.js +62 -270
- package/dist/learn/compile.d.ts +4 -4
- package/dist/learn/compile.js +6 -7
- package/dist/learn/corrections.js +1 -1
- package/dist/learn/delete.d.ts +5 -12
- package/dist/learn/delete.js +17 -30
- package/dist/learn/forget-run.d.ts +16 -0
- package/dist/learn/forget-run.js +53 -0
- package/dist/learn/index.js +1 -1
- package/dist/learn/learning-of.d.ts +0 -4
- package/dist/learn/learning-of.js +0 -5
- package/dist/learn/{folder.d.ts → legacy/folder.d.ts} +2 -1
- package/dist/learn/{folder.js → legacy/folder.js} +4 -7
- package/dist/learn/legacy/place.d.ts +16 -0
- package/dist/{workspace/learning-workspace.js → learn/legacy/place.js} +12 -42
- package/dist/learn/legacy/scrub.d.ts +28 -0
- package/dist/learn/legacy/scrub.js +258 -0
- package/dist/learn/promote.d.ts +40 -66
- package/dist/learn/promote.js +69 -207
- package/dist/learn/reset-ledger.d.ts +18 -0
- package/dist/learn/reset-ledger.js +14 -0
- package/dist/learn/rows.d.ts +186 -0
- package/dist/learn/rows.js +376 -0
- package/dist/learn/workflow-draft.d.ts +4 -1
- package/dist/learn/workflow-draft.js +12 -2
- package/dist/learning-reset.d.ts +1 -1
- package/dist/learning-reset.js +9 -11
- package/dist/learning-routes.d.ts +60 -81
- package/dist/learning-routes.js +187 -360
- package/dist/learning-words.d.ts +2 -0
- package/dist/learning-words.js +2 -0
- package/dist/learning.d.ts +18 -24
- package/dist/learning.js +35 -66
- package/dist/mcp-gateway.d.ts +6 -0
- package/dist/mcp-gateway.js +44 -8
- package/dist/mcp-resources.d.ts +1 -1
- package/dist/native/discovery.d.ts +6 -0
- package/dist/native/discovery.js +14 -1
- package/dist/native/remote.d.ts +5 -0
- package/dist/native/remote.js +16 -0
- package/dist/native/runtime.js +3 -2
- package/dist/observation/observer.d.ts +6 -6
- package/dist/openapi.js +89 -29
- package/dist/place-offers.d.ts +3 -0
- package/dist/place-offers.js +3 -0
- package/dist/place.d.ts +33 -11
- package/dist/place.js +61 -26
- package/dist/purged-workflow.d.ts +0 -33
- package/dist/purged-workflow.js +3 -71
- package/dist/redact/match.d.ts +19 -4
- package/dist/redact/match.js +123 -30
- package/dist/run-launch.d.ts +3 -3
- package/dist/run-learning-served.d.ts +3 -3
- package/dist/run-learning-served.js +1 -1
- package/dist/run-listing.d.ts +1 -1
- package/dist/run-timeline-served.d.ts +1 -1
- package/dist/run-timeline-served.js +6 -5
- package/dist/runnable.js +25 -8
- package/dist/runner/adapter-run-spec.js +11 -20
- package/dist/runner/audit.d.ts +2 -4
- package/dist/runner/audit.js +28 -51
- package/dist/runner/cli-run-spec.js +8 -14
- package/dist/runner/compare-end.d.ts +0 -2
- package/dist/runner/compare-end.js +6 -2
- package/dist/runner/disk-free.d.ts +15 -4
- package/dist/runner/disk-free.js +25 -7
- package/dist/runner/feedback-round.d.ts +1 -1
- package/dist/runner/feedback-round.js +2 -2
- package/dist/runner/harness-loops.js +2 -3
- package/dist/runner/held.d.ts +0 -10
- package/dist/runner/held.js +0 -25
- package/dist/runner/journal-kinds.d.ts +4 -1
- package/dist/runner/journal-kinds.js +1 -1
- package/dist/runner/learned-first.d.ts +0 -2
- package/dist/runner/learned-first.js +3 -3
- package/dist/runner/learning-end.d.ts +12 -16
- package/dist/runner/learning-end.js +41 -75
- package/dist/runner/learning-seed.d.ts +13 -16
- package/dist/runner/learning-seed.js +13 -23
- package/dist/runner/main.js +1 -1
- package/dist/runner/mcp-run.d.ts +4 -0
- package/dist/runner/mcp-run.js +2 -0
- package/dist/runner/native-loop.js +2 -3
- package/dist/runner/promotion.d.ts +19 -28
- package/dist/runner/promotion.js +50 -69
- package/dist/runner/reflect-hook.d.ts +2 -2
- package/dist/runner/reflect-hook.js +4 -1
- package/dist/runner/run-child-host.d.ts +1 -9
- package/dist/runner/run-child-host.js +11 -67
- package/dist/runner/runner.d.ts +1 -1
- package/dist/runner/sdk-loop.js +2 -4
- package/dist/sdk/check.d.ts +1 -4
- package/dist/sdk/check.js +2 -3
- package/dist/sdk/runs.d.ts +20 -7
- package/dist/sdk/runs.js +105 -68
- package/dist/secrets.d.ts +4 -0
- package/dist/secrets.js +44 -10
- package/dist/server-fs.d.ts +1 -1
- package/dist/server-fs.js +1 -1
- package/dist/server-keys.d.ts +6 -0
- package/dist/server-keys.js +12 -0
- package/dist/server.d.ts +15 -15
- package/dist/server.js +214 -164
- package/dist/source-sync/auxiliary.js +2 -2
- package/dist/store/index.d.ts +1 -1
- package/dist/store/index.js +1 -1
- package/dist/store/postgres/migrations/0032_learning_rows.sql +65 -0
- package/dist/store/schema.d.ts +28 -2
- package/dist/store/schema.js +81 -5
- package/dist/store/sqlite/learning-rows.d.ts +23 -0
- package/dist/store/sqlite/learning-rows.js +559 -0
- package/dist/store/sqlite/store.d.ts +7 -1
- package/dist/store/sqlite/store.js +84 -18
- package/dist/store/store.d.ts +219 -6
- package/dist/store/store.js +13 -0
- package/dist/store-reads/journal.d.ts +33 -3
- package/dist/store-reads/journal.js +99 -4
- package/dist/store-reads/learning.d.ts +18 -22
- package/dist/store-reads/learning.js +35 -26
- package/dist/store-reads/loop.js +1 -1
- package/dist/store-view.d.ts +24 -2
- package/dist/store-view.js +40 -11
- package/dist/templates.d.ts +10 -2
- package/dist/templates.js +31 -4
- package/dist/tool-plane.d.ts +4 -2
- package/dist/tool-plane.js +9 -2
- package/dist/web-holds.d.ts +2 -0
- package/dist/web-holds.js +5 -2
- package/dist/web-run.js +2 -1
- package/dist/workspace/archil-exec.js +1 -1
- package/dist/workspace/archil.d.ts +1 -1
- package/dist/workspace/archil.js +1 -1
- package/dist/workspace/computer-deps.js +5 -3
- package/dist/workspace/computer-providers.d.ts +11 -1
- package/dist/workspace/computer-providers.js +29 -2
- package/dist/workspace/index.d.ts +1 -2
- package/dist/workspace/index.js +1 -2
- package/dist/workspace/paths.d.ts +0 -4
- package/dist/workspace/paths.js +0 -6
- package/dist/workspace/workspace.d.ts +1 -1
- package/dist/workspace/workspace.js +1 -1
- package/package.json +13 -13
- package/templates/TOOLS.md +46 -0
- package/dist/console/assets/index-LwNL4L9q.js +0 -619
- package/dist/console/assets/styles-DQo8rzY-.css +0 -1
- package/dist/workspace/learning-workspace.d.ts +0 -24
- /package/dist/learn/{learning.sh → legacy/learning.sh} +0 -0
|
@@ -0,0 +1,559 @@
|
|
|
1
|
+
// An agent's learning as versioned rows (schema.ts LEARNING_ROWS): the part of Store.learning that keeps its notes,
|
|
2
|
+
// workflows, promotions, grades and audits. Written once for SQLite and Postgres, over the store's connection and its
|
|
3
|
+
// Dialect: a save is one transaction, under the agent's lock on Postgres (SQLite's one writer lock holds it there), its
|
|
4
|
+
// compare and swap on the agent's newest version. An agent's reset or delete is plain deletes; a run's purge deletes its
|
|
5
|
+
// notes and rewrites each workflow version that held a file it wrote, file by file (rewriteWorkflow), and is a save of
|
|
6
|
+
// its own (the host's, kind `purged`), so a save computed before it is stale.
|
|
7
|
+
import { randomBytes } from "node:crypto";
|
|
8
|
+
import { LearningRecordRefused } from "../store.js";
|
|
9
|
+
import { learnedStatus, restoredLearned, retiredLearned, workflowRunOf, WORKFLOWS_DIR } from "../../learn/workflow-draft.js";
|
|
10
|
+
import { forgetRunIn, runsNamedIn } from "../../learn/forget-run.js";
|
|
11
|
+
import { resetLedgerKey, resetRevisionKey, withKept } from "../../learn/reset-ledger.js";
|
|
12
|
+
import { nativeCommandOwner } from "../native-command-owner.js";
|
|
13
|
+
const SAVE_COLUMNS = "version, id, at, kind, by_run, merge_key, change";
|
|
14
|
+
const ITEM_FACTS = "kind, name, version, by_run, change, person, pos, digest, writers, at";
|
|
15
|
+
const ITEM_COLUMNS = `${ITEM_FACTS}, body`;
|
|
16
|
+
const RECORD_COLUMNS = "seq, run_id, workflow, digest, data, at";
|
|
17
|
+
function saveOf(row) {
|
|
18
|
+
const change = JSON.parse(row.change);
|
|
19
|
+
const by = row.kind === "init" || row.kind === "purged" ? { host: row.kind } : change.by;
|
|
20
|
+
return { version: Number(row.version), id: row.id, at: Number(row.at), by, reason: change.reason ?? "", files: change.files ?? [], mergeKey: row.merge_key };
|
|
21
|
+
}
|
|
22
|
+
const factsOf = (row) => ({
|
|
23
|
+
kind: row.kind, name: row.name, version: Number(row.version), byRun: row.by_run, change: row.change,
|
|
24
|
+
person: Number(row.person) === 1, pos: Number(row.pos), digest: row.digest, writers: row.writers ? JSON.parse(row.writers) : null, at: Number(row.at),
|
|
25
|
+
});
|
|
26
|
+
const itemOf = (row) => ({ ...factsOf(row), body: row.body ?? null });
|
|
27
|
+
const recordOf = (row) => ({ seq: Number(row.seq), runId: row.run_id, workflow: row.workflow, digest: row.digest, data: JSON.parse(row.data), at: Number(row.at) });
|
|
28
|
+
/** A save's version id: 40 hex, random, the shape a git commit id had (what a run's seed and the log's `commit` name). */
|
|
29
|
+
const versionId = () => randomBytes(20).toString("hex");
|
|
30
|
+
/** The item rows newest at or before `version`: each item's live version there. */
|
|
31
|
+
const LIVE_AT = `SELECT ${ITEM_COLUMNS} FROM learning_items i
|
|
32
|
+
WHERE i.agent_id = ? AND i.version <= ? AND i.body IS NOT NULL
|
|
33
|
+
AND i.version = (SELECT MAX(j.version) FROM learning_items j WHERE j.agent_id = i.agent_id AND j.kind = i.kind AND j.name = i.name AND j.version <= ?)
|
|
34
|
+
ORDER BY i.kind, i.pos, i.name`;
|
|
35
|
+
async function atSave(db, agentId, save) {
|
|
36
|
+
const items = (await db.all(LIVE_AT, agentId, save.version, save.version)).map(itemOf);
|
|
37
|
+
const history = (await db.all(`SELECT ${ITEM_FACTS} FROM learning_items WHERE agent_id = ? AND version <= ? ORDER BY version`, agentId, save.version)).map(factsOf);
|
|
38
|
+
return { save, items, history };
|
|
39
|
+
}
|
|
40
|
+
const byBytes = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
|
|
41
|
+
const filesIn = (body) => (body === null ? {} : JSON.parse(body));
|
|
42
|
+
/** Workflow `name` of agent `agentId`, every version rewritten with run `runId`'s files taken out, inside the caller's
|
|
43
|
+
* transaction: each file at each version is its text as the versions say with the run's changes left out (a file the
|
|
44
|
+
* run changed is its text before, its writer before; one it deleted is there again; another writer's change of it
|
|
45
|
+
* stands), and a version that comes to hold what the one before it holds is deleted, as is one before any text. Its
|
|
46
|
+
* digest and run follow its workflow.json (a json text's digest as the version that held it says). The digests some
|
|
47
|
+
* version held before and none holds after (`lost`: their promotions and audits are of the run's text alone), the
|
|
48
|
+
* paths some version held before and none holds after (`taken`: the run's alone, so their names are its words too),
|
|
49
|
+
* whether no version is left (`gone`), and whether any row changed (`changed`). */
|
|
50
|
+
async function rewriteWorkflow(tx, agentId, runId, name) {
|
|
51
|
+
const rows = await tx.all(`SELECT i.version, i.body, i.writers, i.by_run, i.digest, i.person, i.change, s.kind AS save_kind, s.by_run AS save_run
|
|
52
|
+
FROM learning_items i JOIN learning_saves s ON s.agent_id = i.agent_id AND s.version = i.version
|
|
53
|
+
WHERE i.agent_id = ? AND i.kind = 'workflow' AND i.name = ? ORDER BY i.version`, agentId, name);
|
|
54
|
+
const json = `${WORKFLOWS_DIR}/${name}/workflow.json`;
|
|
55
|
+
const readme = `${WORKFLOWS_DIR}/${name}/README.md`;
|
|
56
|
+
const digests = new Map();
|
|
57
|
+
for (const row of rows) {
|
|
58
|
+
const text = filesIn(row.body)[json];
|
|
59
|
+
if (text !== undefined && row.digest !== null)
|
|
60
|
+
digests.set(text, row.digest);
|
|
61
|
+
}
|
|
62
|
+
const before = new Set(rows.flatMap((row) => (row.digest === null ? [] : [row.digest])));
|
|
63
|
+
const after = new Set();
|
|
64
|
+
const pathsBefore = new Set(rows.flatMap((row) => Object.keys(filesIn(row.body))));
|
|
65
|
+
const pathsAfter = new Set();
|
|
66
|
+
let changed = false;
|
|
67
|
+
const state = new Map();
|
|
68
|
+
// The version before's files and writers, as written (`was`), and as kept (`last`: undefined before the first).
|
|
69
|
+
let was = new Map();
|
|
70
|
+
let last;
|
|
71
|
+
for (const row of rows) {
|
|
72
|
+
const files = filesIn(row.body);
|
|
73
|
+
const writers = row.writers === null ? {} : JSON.parse(row.writers);
|
|
74
|
+
const now = new Map(Object.entries(files).map(([path, text]) => [path, { text, writer: Object.hasOwn(writers, path) ? (writers[path] ?? null) : row.by_run }]));
|
|
75
|
+
const saver = row.save_kind === "run" ? row.save_run : null;
|
|
76
|
+
for (const path of new Set([...was.keys(), ...now.keys()])) {
|
|
77
|
+
const [then, file] = [was.get(path), now.get(path)];
|
|
78
|
+
// A file this version changed: its text, or its writer (a run that wrote back bytes a version before held).
|
|
79
|
+
if (then?.text === file?.text && then?.writer === file?.writer)
|
|
80
|
+
continue;
|
|
81
|
+
if (file === undefined) {
|
|
82
|
+
if (saver !== runId)
|
|
83
|
+
state.delete(path);
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
if (file.writer !== runId)
|
|
87
|
+
state.set(path, file);
|
|
88
|
+
}
|
|
89
|
+
// A person's retire, and their restore, is the owner's decision on the workflow, not on the run's text: each stays on
|
|
90
|
+
// the version that comes back (its README.md retired, or restored, as the person's change writes it, its writer the
|
|
91
|
+
// text's), so the newest of them stands after the purge: a purge never serves again what the owner stopped, nor stops
|
|
92
|
+
// what they restored. A README.md that cannot be retired so reads retired already (learnedStatus); one that cannot be
|
|
93
|
+
// restored so stays retired (fail closed). A person's approve is not replayed: it was of the run's text, and the text
|
|
94
|
+
// that comes back is one the owner never approved.
|
|
95
|
+
const front = state.get(readme);
|
|
96
|
+
if (Number(row.person) === 1 && row.change === "retired" && front && learnedStatus(front.text) !== "retired") {
|
|
97
|
+
try {
|
|
98
|
+
state.set(readme, { text: retiredLearned(front.text), writer: front.writer });
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
// Unreadable front matter: retired as it reads.
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
else if (Number(row.person) === 1 && row.change === "restored" && front && learnedStatus(front.text) === "retired") {
|
|
105
|
+
try {
|
|
106
|
+
state.set(readme, { text: restoredLearned(front.text), writer: front.writer });
|
|
107
|
+
}
|
|
108
|
+
catch {
|
|
109
|
+
// Not restorable as it reads: it stays retired.
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
was = now;
|
|
113
|
+
const paths = [...state.keys()].sort(byBytes);
|
|
114
|
+
const body = paths.length ? JSON.stringify(Object.fromEntries(paths.map((path) => [path, state.get(path).text]))) : null;
|
|
115
|
+
const kept = paths.length ? Object.fromEntries(paths.map((path) => [path, state.get(path).writer])) : null;
|
|
116
|
+
const written = kept ? JSON.stringify(kept) : null;
|
|
117
|
+
if ((last === undefined && body === null) || (last !== undefined && last.body === body && last.writers === written)) {
|
|
118
|
+
await tx.run("DELETE FROM learning_items WHERE agent_id = ? AND kind = 'workflow' AND name = ? AND version = ?", agentId, name, row.version);
|
|
119
|
+
changed = true;
|
|
120
|
+
continue;
|
|
121
|
+
}
|
|
122
|
+
last = { body, writers: written };
|
|
123
|
+
for (const path of paths)
|
|
124
|
+
pathsAfter.add(path);
|
|
125
|
+
const digest = state.has(json) ? (digests.get(state.get(json).text) ?? null) : null;
|
|
126
|
+
if (digest !== null)
|
|
127
|
+
after.add(digest);
|
|
128
|
+
const by = kept ? workflowRunOf(name, kept) : null;
|
|
129
|
+
if (body !== row.body || written !== row.writers || by !== row.by_run || digest !== row.digest) {
|
|
130
|
+
await tx.run("UPDATE learning_items SET body = ?, writers = ?, by_run = ?, digest = ? WHERE agent_id = ? AND kind = 'workflow' AND name = ? AND version = ?", body, written, by, digest, agentId, name, row.version);
|
|
131
|
+
changed = true;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
return {
|
|
135
|
+
lost: [...before].filter((digest) => !after.has(digest)), taken: [...pathsBefore].filter((path) => !pathsAfter.has(path)).sort(byBytes),
|
|
136
|
+
gone: last === undefined || last.body === null, changed,
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
/** The save a promotion of workflow `name` at `digest` names (its `commit`, where its champion's text is read), read
|
|
140
|
+
* inside the caller's transaction: `commit` when workflow `name` there holds the digest; else the save of the newest
|
|
141
|
+
* version that holds it (a purge rewrote the save it named: a shared champion goes on serving); `commit` when none does
|
|
142
|
+
* (no record of such a digest is kept: the purge deleted them, and a write of one is refused). */
|
|
143
|
+
async function commitHolding(tx, agentId, name, digest, commit) {
|
|
144
|
+
const save = await tx.get("SELECT version FROM learning_saves WHERE agent_id = ? AND id = ?", agentId, commit);
|
|
145
|
+
const held = save && await tx.get("SELECT digest FROM learning_items WHERE agent_id = ? AND kind = 'workflow' AND name = ? AND version <= ? ORDER BY version DESC LIMIT 1", agentId, name, save.version);
|
|
146
|
+
if (held?.digest === digest)
|
|
147
|
+
return commit;
|
|
148
|
+
const holds = await tx.get(`SELECT s.id FROM learning_items i JOIN learning_saves s ON s.agent_id = i.agent_id AND s.version = i.version
|
|
149
|
+
WHERE i.agent_id = ? AND i.kind = 'workflow' AND i.name = ? AND i.digest = ? ORDER BY i.version DESC LIMIT 1`, agentId, name, digest);
|
|
150
|
+
return holds?.id ?? commit;
|
|
151
|
+
}
|
|
152
|
+
/** A promotion's data as its write keeps it, inside the caller's transaction (under the records' lock, which a run's
|
|
153
|
+
* purge takes after it marks the run purged): its `commit` a save that holds its digest (commitHolding), and each
|
|
154
|
+
* purged run's copies it holds blanked (forgetRunIn: a check that read a run's rows before its purge never writes them
|
|
155
|
+
* after it). Another kind's data as it is. */
|
|
156
|
+
async function keptData(tx, kind, agentId, record) {
|
|
157
|
+
if (kind !== "promotion" || !record.data || typeof record.data !== "object")
|
|
158
|
+
return record.data ?? null;
|
|
159
|
+
let data = record.data;
|
|
160
|
+
if (typeof data.commit === "string" && record.workflow !== null && record.digest !== null) {
|
|
161
|
+
const commit = await commitHolding(tx, agentId, record.workflow, record.digest, data.commit);
|
|
162
|
+
if (commit !== data.commit)
|
|
163
|
+
data = { ...data, commit };
|
|
164
|
+
}
|
|
165
|
+
for (const run of runsNamedIn(data)) {
|
|
166
|
+
if (await tx.get("SELECT 1 AS one FROM runs WHERE id = ? AND purged_at IS NOT NULL", run))
|
|
167
|
+
data = forgetRunIn(data, run);
|
|
168
|
+
}
|
|
169
|
+
return data;
|
|
170
|
+
}
|
|
171
|
+
/** Workflow `name`'s promotions that a purge kept (another version holds their digest), each moved, inside the caller's
|
|
172
|
+
* transaction, to the save of the newest version that holds it when the save it names (`commit`, where its text is
|
|
173
|
+
* read) holds it no more (commitHolding): a shared champion goes on serving. */
|
|
174
|
+
async function moveCommits(tx, agentId, name) {
|
|
175
|
+
const records = await tx.all("SELECT seq, digest, data FROM learning_records WHERE agent_id = ? AND kind = 'promotion' AND workflow = ?", agentId, name);
|
|
176
|
+
for (const record of records) {
|
|
177
|
+
const data = JSON.parse(record.data);
|
|
178
|
+
if (typeof data.commit !== "string" || record.digest === null)
|
|
179
|
+
continue;
|
|
180
|
+
const commit = await commitHolding(tx, agentId, name, record.digest, data.commit);
|
|
181
|
+
if (commit !== data.commit)
|
|
182
|
+
await tx.run("UPDATE learning_records SET data = ? WHERE agent_id = ? AND kind = 'promotion' AND seq = ?", JSON.stringify({ ...data, commit }), agentId, record.seq);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
/** Each promotion of agent `agentId` that holds run `runId`'s copies (a check's or an audit's disagreement naming it),
|
|
186
|
+
* blanked inside the caller's transaction (forgetRunIn): its decision, numbers and run ids stay. Only promotions copy
|
|
187
|
+
* another run's words today; the schema also allows `lifecycle` and `note` records, which no code writes yet. A PR
|
|
188
|
+
* that first writes a lifecycle or note record whose data names another run extends this scrub in the same PR. */
|
|
189
|
+
async function forgetRunRecords(tx, agentId, runId) {
|
|
190
|
+
const records = await tx.all("SELECT seq, data FROM learning_records WHERE agent_id = ? AND kind = 'promotion'", agentId);
|
|
191
|
+
for (const record of records) {
|
|
192
|
+
const data = JSON.parse(record.data);
|
|
193
|
+
if (!runsNamedIn(data).includes(runId))
|
|
194
|
+
continue;
|
|
195
|
+
await tx.run("UPDATE learning_records SET data = ? WHERE agent_id = ? AND kind = 'promotion' AND seq = ?", JSON.stringify(forgetRunIn(data, runId)), agentId, record.seq);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
/** Revision `name` at `digest` of agent `agentId` as the agent's reset ledger keeps it before a purge of run `runId`
|
|
199
|
+
* deletes its promotions (dropRunLearning), read inside the caller's transaction: its K, its newest promotion's
|
|
200
|
+
* check.compile_after (null when it names none), as keepResetLedger keeps a reset's; undefined when it has no promotion,
|
|
201
|
+
* or when no run but `runId` is billed against it (billedElsewhere). A gone workflow's name is the purged run's words
|
|
202
|
+
* (dropRunLearning scrubs it from other saves' reasons): the ledger keeps it only where another run's own ledger row,
|
|
203
|
+
* spend row or metrics name it already, so it names nothing the purge would take. */
|
|
204
|
+
async function keptRevision(tx, agentId, runId, name, digest, unledgered) {
|
|
205
|
+
const records = await tx.all("SELECT data FROM learning_records WHERE agent_id = ? AND kind = 'promotion' AND workflow = ? AND digest = ? ORDER BY seq", agentId, name, digest);
|
|
206
|
+
if (!records.length)
|
|
207
|
+
return undefined;
|
|
208
|
+
if (!(await billedElsewhere(tx, agentId, runId, name, digest, unledgered)))
|
|
209
|
+
return undefined;
|
|
210
|
+
const k = JSON.parse(records.at(-1).data)?.check?.compile_after;
|
|
211
|
+
return { workflow: name, digest, k: typeof k === "number" ? k : null };
|
|
212
|
+
}
|
|
213
|
+
/** Whether a run of agent `agentId` other than `runId` is billed against revision `name` at `digest` (learn/ledger.ts
|
|
214
|
+
* summarize spreads a revision's compile and check over its served runs), read inside the caller's transaction, with
|
|
215
|
+
* run `runId`'s own ledger and spend rows left out (its purge drops them after this, dropLedger): a ledger row names it
|
|
216
|
+
* (a run it served), a spend row names it (a compile turn, a check's replay, an audit's shadow), or, for an unpurged run
|
|
217
|
+
* with no ledger row (`unledgered`: one that ended before the ledger, whose reader records it from its metrics), its
|
|
218
|
+
* metrics name it. */
|
|
219
|
+
async function billedElsewhere(tx, agentId, runId, name, digest, unledgered) {
|
|
220
|
+
if (await tx.get("SELECT 1 AS one FROM learning_ledger WHERE agent_id = ? AND run_id <> ? AND workflow = ? AND digest = ?", agentId, runId, name, digest))
|
|
221
|
+
return true;
|
|
222
|
+
if (await tx.get("SELECT 1 AS one FROM learning_spend WHERE agent_id = ? AND run_id <> ? AND (of_run IS NULL OR of_run <> ?) AND workflow = ? AND digest = ?", agentId, runId, runId, name, digest))
|
|
223
|
+
return true;
|
|
224
|
+
return (await unledgered()).has(resetRevisionKey({ workflow: name, digest }));
|
|
225
|
+
}
|
|
226
|
+
/** The revisions run `runId` of agent `agentId` is billed against (by resetRevisionKey), read inside the caller's
|
|
227
|
+
* transaction before its rows go: its ledger row's, its spend rows' and an audit's spend row of it, and its metrics'. */
|
|
228
|
+
async function billedRevisions(tx, agentId, runId) {
|
|
229
|
+
const out = new Map();
|
|
230
|
+
const named = [
|
|
231
|
+
...(await tx.all("SELECT workflow, digest FROM learning_ledger WHERE agent_id = ? AND run_id = ?", agentId, runId)),
|
|
232
|
+
...(await tx.all("SELECT workflow, digest FROM learning_spend WHERE agent_id = ? AND (run_id = ? OR of_run = ?)", agentId, runId, runId)),
|
|
233
|
+
];
|
|
234
|
+
for (const { workflow, digest } of named)
|
|
235
|
+
if (workflow !== null && digest !== null)
|
|
236
|
+
out.set(resetRevisionKey({ workflow, digest }), { workflow, digest });
|
|
237
|
+
const row = await tx.get("SELECT metrics FROM runs WHERE id = ? AND agent_id = ?", runId, agentId);
|
|
238
|
+
const revision = revisionOfMetrics(row?.metrics ?? null);
|
|
239
|
+
if (revision)
|
|
240
|
+
out.set(resetRevisionKey(revision), revision);
|
|
241
|
+
return out;
|
|
242
|
+
}
|
|
243
|
+
/** The revision a run's metrics name (metrics.workflow and metrics.workflow_digest, as JSON text or parsed). */
|
|
244
|
+
function revisionOfMetrics(raw) {
|
|
245
|
+
const metrics = typeof raw === "string" ? JSON.parse(raw) : raw;
|
|
246
|
+
const { workflow, workflow_digest: digest } = (metrics && typeof metrics === "object" ? metrics : {});
|
|
247
|
+
return typeof workflow === "string" && typeof digest === "string" ? { workflow, digest } : undefined;
|
|
248
|
+
}
|
|
249
|
+
/** The revisions the metrics of agent `agentId`'s unpurged runs other than `runId` with no ledger row name (by
|
|
250
|
+
* resetRevisionKey), read inside the caller's transaction. */
|
|
251
|
+
async function unledgeredRevisions(tx, agentId, runId) {
|
|
252
|
+
const rows = await tx.all(`SELECT r.metrics FROM runs r WHERE r.agent_id = ? AND r.id <> ? AND r.purged_at IS NULL AND r.metrics IS NOT NULL
|
|
253
|
+
AND NOT EXISTS (SELECT 1 FROM learning_ledger l WHERE l.run_id = r.id)`, agentId, runId);
|
|
254
|
+
const out = new Set();
|
|
255
|
+
for (const row of rows) {
|
|
256
|
+
const revision = revisionOfMetrics(row.metrics);
|
|
257
|
+
if (revision)
|
|
258
|
+
out.add(resetRevisionKey(revision));
|
|
259
|
+
}
|
|
260
|
+
return out;
|
|
261
|
+
}
|
|
262
|
+
/** Agent `agentId`'s reset ledger changed inside the caller's transaction (a run's purge): the revisions `kept` added by
|
|
263
|
+
* the rule keepResetLedger adds a reset's by (withKept), and the ones `dropped` (by resetRevisionKey: no run is billed
|
|
264
|
+
* against them after the purge) taken out. Compare and set on the row as read, so a ledger write that lands between
|
|
265
|
+
* the read and the write (keepResetLedger's own compare and set) is read again, never lost. The loop is Postgres's: its
|
|
266
|
+
* UPDATE waits out a concurrent keepResetLedger and then matches 0 rows, and the next read in this READ COMMITTED
|
|
267
|
+
* transaction sees that write. On SQLite the purge's BEGIN IMMEDIATE holds the write lock from its start, so the first
|
|
268
|
+
* try always matches. The loop stays in the transaction: the purge's rows and the ledger change commit together. */
|
|
269
|
+
async function changeResetLedger(tx, agentId, kept, dropped, at) {
|
|
270
|
+
const key = resetLedgerKey(agentId);
|
|
271
|
+
for (let tries = 0; tries < 20; tries++) {
|
|
272
|
+
const row = await tx.get("SELECT value FROM settings WHERE key = ?", key);
|
|
273
|
+
const was = row === undefined ? undefined : JSON.parse(row.value);
|
|
274
|
+
const items = Array.isArray(was?.items) ? was.items : [];
|
|
275
|
+
const next = withKept(items, kept).filter((one) => !dropped.has(resetRevisionKey(one)));
|
|
276
|
+
if (row === undefined ? !next.length : JSON.stringify(next) === JSON.stringify(items))
|
|
277
|
+
return;
|
|
278
|
+
const encoded = JSON.stringify({ v: 1, items: next });
|
|
279
|
+
const done = row === undefined
|
|
280
|
+
? await tx.runCounted("INSERT INTO settings (key, value, connector_id, updated_at) VALUES (?, ?, ?, ?) ON CONFLICT (key) DO NOTHING", key, encoded, nativeCommandOwner(key, encoded), at)
|
|
281
|
+
: await tx.runCounted("UPDATE settings SET value = ?, connector_id = ?, updated_at = ? WHERE key = ? AND value = ?", encoded, nativeCommandOwner(key, encoded), at, key, row.value);
|
|
282
|
+
if (done === 1)
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
throw new Error(`${key} kept changing under this purge; try again`);
|
|
286
|
+
}
|
|
287
|
+
/** Run `runId`'s learning rows gone from its agent `agentId`'s, inside the caller's transaction (its purge, its
|
|
288
|
+
* delete), every statement scoped to that agent: each workflow it wrote a file of rewritten without its files
|
|
289
|
+
* (rewriteWorkflow), with the promotions and audits of each digest no version holds then (each such revision another
|
|
290
|
+
* run is still billed against kept first in the agent's reset ledger, its workflow, digest and K alone: keptRevision,
|
|
291
|
+
* so the runs that carry its spend read the same share after; and each revision the ledger holds that the run was
|
|
292
|
+
* billed against and no other run is after it, taken out of the ledger: changeResetLedger); its notes; its records (its
|
|
293
|
+
* grades and audits, a failed draft's hold); every other promotion's copies of it (forgetRunIn); and its saves' words (each save's version, id and merge key stay), a person's save left with no item (an
|
|
294
|
+
* approve of its draft, a removal of its line) with them: that save's words name what the run wrote. Every other save
|
|
295
|
+
* names none of the paths only it wrote, nor a workflow gone with it. When any row changed, the purge is a save of its
|
|
296
|
+
* own at the agent's newest version + 1 (the host's, kind `purged`, at `at`): a save computed before it is stale, and a
|
|
297
|
+
* run's merge read at a save before it is refused (save's `readAt`). Callers hold the agent's learning lock
|
|
298
|
+
* (`learning:<agent>`); this takes its records' lock (`learning.records:<agent>`) after it. */
|
|
299
|
+
export async function dropRunLearning(tx, agentId, runId, at) {
|
|
300
|
+
// The records' lock before any version changes: a promotion's write reads its digests under it (changeRecords).
|
|
301
|
+
await tx.dialect.lockKey(tx, `learning.records:${agentId}`);
|
|
302
|
+
const names = (await tx.all(`SELECT DISTINCT i.name FROM learning_items i JOIN learning_saves s ON s.agent_id = i.agent_id AND s.version = i.version
|
|
303
|
+
WHERE i.agent_id = ? AND i.kind = 'workflow' AND (s.by_run = ? OR i.by_run = ?) ORDER BY i.name`, agentId, runId, runId)).map((row) => row.name);
|
|
304
|
+
// The person's saves that wrote a version of the run's text, read before it goes.
|
|
305
|
+
const persons = new Set((await tx.all(`SELECT DISTINCT i.version FROM learning_items i JOIN learning_saves s ON s.agent_id = i.agent_id AND s.version = i.version
|
|
306
|
+
WHERE i.agent_id = ? AND s.kind = 'person' AND ((i.kind <> 'workflow' AND i.by_run = ?) OR (i.kind = 'workflow' AND i.name IN (SELECT j.name FROM learning_items j JOIN learning_saves r ON r.agent_id = j.agent_id AND r.version = j.version WHERE j.agent_id = ? AND j.kind = 'workflow' AND (r.by_run = ? OR j.by_run = ?))))`, agentId, runId, agentId, runId, runId)).map((row) => Number(row.version)));
|
|
307
|
+
const count = async (sql) => Number((await tx.get(sql, agentId, runId))?.n ?? 0);
|
|
308
|
+
let changed = (await count("SELECT COUNT(*) AS n FROM learning_items WHERE agent_id = ? AND kind <> 'workflow' AND by_run = ?")) > 0
|
|
309
|
+
|| (await count("SELECT COUNT(*) AS n FROM learning_saves WHERE agent_id = ? AND by_run = ?")) > 0;
|
|
310
|
+
const gone = [];
|
|
311
|
+
const taken = new Set();
|
|
312
|
+
// The revisions whose promotions go here that another run is still billed against, each with its K, for the agent's
|
|
313
|
+
// reset ledger: the cost read splits their spend at it (store-reads/learning.ts revisionsOf), as after a reset.
|
|
314
|
+
const kept = new Map();
|
|
315
|
+
let unledgered;
|
|
316
|
+
const unledgeredOnce = () => (unledgered ??= unledgeredRevisions(tx, agentId, runId));
|
|
317
|
+
// The revisions the run is billed against, read before its rows go: one the ledger kept that no other run is billed
|
|
318
|
+
// against after this purge leaves the ledger with it (its name was carried by purged runs alone).
|
|
319
|
+
const billed = await billedRevisions(tx, agentId, runId);
|
|
320
|
+
for (const name of names) {
|
|
321
|
+
const rewritten = await rewriteWorkflow(tx, agentId, runId, name);
|
|
322
|
+
for (const digest of rewritten.lost) {
|
|
323
|
+
const revision = await keptRevision(tx, agentId, runId, name, digest, unledgeredOnce);
|
|
324
|
+
if (revision)
|
|
325
|
+
kept.set(resetRevisionKey(revision), revision);
|
|
326
|
+
await tx.run("DELETE FROM learning_records WHERE agent_id = ? AND kind IN ('promotion', 'audit') AND workflow = ? AND digest = ?", agentId, name, digest);
|
|
327
|
+
}
|
|
328
|
+
if (rewritten.changed)
|
|
329
|
+
await moveCommits(tx, agentId, name);
|
|
330
|
+
if (rewritten.gone)
|
|
331
|
+
gone.push(name);
|
|
332
|
+
for (const path of rewritten.taken)
|
|
333
|
+
taken.add(path);
|
|
334
|
+
if (rewritten.changed)
|
|
335
|
+
changed = true;
|
|
336
|
+
}
|
|
337
|
+
// Every item of the run's but a workflow (rewritten above, file by file): its notes, and an item of a kind the schema
|
|
338
|
+
// allows that no code writes yet (`label`), so the first PR that writes one is covered here already.
|
|
339
|
+
await tx.run("DELETE FROM learning_items WHERE agent_id = ? AND kind <> 'workflow' AND by_run = ?", agentId, runId);
|
|
340
|
+
await tx.run("DELETE FROM learning_records WHERE agent_id = ? AND run_id = ?", agentId, runId);
|
|
341
|
+
await forgetRunRecords(tx, agentId, runId);
|
|
342
|
+
for (const version of persons) {
|
|
343
|
+
if (!(await tx.get("SELECT 1 AS one FROM learning_items WHERE agent_id = ? AND version = ?", agentId, version))) {
|
|
344
|
+
await tx.run("UPDATE learning_saves SET kind = 'purged', by_run = NULL, change = '{}' WHERE agent_id = ? AND version = ? AND kind = 'person'", agentId, version);
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
// A path only the run wrote (no version holds it now) and a workflow gone with it are the run's words: no other save,
|
|
348
|
+
// a run's or a person's, names one in its files, its `file` or its reason.
|
|
349
|
+
if (taken.size) {
|
|
350
|
+
const others = await tx.all("SELECT version, kind, change FROM learning_saves WHERE agent_id = ? AND kind IN ('run', 'person') AND (by_run IS NULL OR by_run <> ?)", agentId, runId);
|
|
351
|
+
for (const row of others) {
|
|
352
|
+
const change = JSON.parse(row.change);
|
|
353
|
+
const by = change.by && "person" in change.by ? change.by : undefined;
|
|
354
|
+
let reason = change.reason ?? "";
|
|
355
|
+
if (!by)
|
|
356
|
+
for (const name of gone)
|
|
357
|
+
reason = reason.replaceAll(`workflow ${name}`, "a workflow");
|
|
358
|
+
for (const path of taken)
|
|
359
|
+
reason = reason.replaceAll(path, "a file");
|
|
360
|
+
const kept = {
|
|
361
|
+
...change, files: (change.files ?? []).filter((path) => !taken.has(path)), reason,
|
|
362
|
+
...(by && taken.has(by.file) ? { by: { ...by, file: "" }, reason: `${by.person} by a person` } : {}),
|
|
363
|
+
};
|
|
364
|
+
if (JSON.stringify(kept) !== JSON.stringify(change))
|
|
365
|
+
await tx.run("UPDATE learning_saves SET change = ? WHERE agent_id = ? AND version = ?", JSON.stringify(kept), agentId, row.version);
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
await tx.run("UPDATE learning_saves SET kind = 'purged', by_run = NULL, change = '{}' WHERE agent_id = ? AND by_run = ?", agentId, runId);
|
|
369
|
+
const dropped = new Set();
|
|
370
|
+
for (const [one, { workflow, digest }] of billed) {
|
|
371
|
+
if (!kept.has(one) && !(await billedElsewhere(tx, agentId, runId, workflow, digest, unledgeredOnce)))
|
|
372
|
+
dropped.add(one);
|
|
373
|
+
}
|
|
374
|
+
if (kept.size || dropped.size)
|
|
375
|
+
await changeResetLedger(tx, agentId, kept, dropped, at);
|
|
376
|
+
if (!changed)
|
|
377
|
+
return;
|
|
378
|
+
const head = Number((await tx.get("SELECT MAX(version) AS v FROM learning_saves WHERE agent_id = ?", agentId))?.v ?? 0);
|
|
379
|
+
await tx.run("INSERT INTO learning_saves (agent_id, version, id, at, kind, by_run, merge_key, change) VALUES (?, ?, ?, ?, 'purged', NULL, NULL, '{}')", agentId, head + 1, versionId(), at);
|
|
380
|
+
}
|
|
381
|
+
/** Every learning row of agent `agentId` gone, inside the caller's transaction (a reset, its purge, its delete), under
|
|
382
|
+
* the agent's learning lock and then its records' lock, the order a run's purge takes them: a records write that read
|
|
383
|
+
* before it is in before it, never written after. */
|
|
384
|
+
export async function dropAgentLearning(tx, agentId) {
|
|
385
|
+
await tx.dialect.lockKey(tx, `learning:${agentId}`);
|
|
386
|
+
await tx.dialect.lockKey(tx, `learning.records:${agentId}`);
|
|
387
|
+
await tx.run("DELETE FROM learning_items WHERE agent_id = ?", agentId);
|
|
388
|
+
await tx.run("DELETE FROM learning_saves WHERE agent_id = ?", agentId);
|
|
389
|
+
await tx.run("DELETE FROM learning_records WHERE agent_id = ?", agentId);
|
|
390
|
+
}
|
|
391
|
+
/** Store.learning's rows, over `db`; `now`, the store's clock. */
|
|
392
|
+
export function learningRows(db, now) {
|
|
393
|
+
const d = db.dialect;
|
|
394
|
+
const saveBy = async (ex, agentId, where, ...params) => {
|
|
395
|
+
const row = await ex.get(`SELECT ${SAVE_COLUMNS} FROM learning_saves WHERE agent_id = ? AND ${where}`, agentId, ...params);
|
|
396
|
+
return row ? saveOf(row) : undefined;
|
|
397
|
+
};
|
|
398
|
+
const newest = (ex, agentId) => saveBy(ex, agentId, "version = (SELECT MAX(version) FROM learning_saves WHERE agent_id = ?)", agentId);
|
|
399
|
+
/** A record's columns from its data: the run it is of, its workflow and digest. */
|
|
400
|
+
const columnsOf = (record) => [record.runId, record.workflow, record.digest, JSON.stringify(record.data ?? null)];
|
|
401
|
+
/** Inserts `record` as its write keeps it (keptData); the data written. */
|
|
402
|
+
const insertRecord = async (tx, agentId, kind, record, seq, at) => {
|
|
403
|
+
const data = await keptData(tx, kind, agentId, record);
|
|
404
|
+
await tx.run(`INSERT INTO learning_records (agent_id, kind, seq, run_id, workflow, digest, data, at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, agentId, kind, seq, ...columnsOf({ ...record, data }), at);
|
|
405
|
+
return data;
|
|
406
|
+
};
|
|
407
|
+
const recordsIn = async (ex, agentId, kind) => (await ex.all(`SELECT ${RECORD_COLUMNS} FROM learning_records WHERE agent_id = ? AND kind = ? ORDER BY seq`, agentId, kind)).map(recordOf);
|
|
408
|
+
/** Whether a version of each workflow holds a digest, read inside the records' transaction (under its lock, which a
|
|
409
|
+
* purge takes before it changes a version). */
|
|
410
|
+
const heldIn = async (tx, agentId) => {
|
|
411
|
+
const held = new Set((await tx.all("SELECT DISTINCT name, digest FROM learning_items WHERE agent_id = ? AND kind = 'workflow' AND digest IS NOT NULL", agentId)).map((row) => `${row.name}\0${row.digest}`));
|
|
412
|
+
return (workflow, digest) => held.has(`${workflow}\0${digest}`);
|
|
413
|
+
};
|
|
414
|
+
/** The records a write adds (or moves to another run, workflow or digest), checked in its transaction: a promotion's or
|
|
415
|
+
* an audit's digest held by a version of its workflow (`anyDigest` aside: a failed draft's, which none holds), and no
|
|
416
|
+
* run purged. LearningRecordRefused otherwise, so the transaction writes nothing. */
|
|
417
|
+
const checkAdded = async (tx, agentId, kind, added, held, anyDigest) => {
|
|
418
|
+
if (!added.length)
|
|
419
|
+
return;
|
|
420
|
+
if (kind !== "grade") {
|
|
421
|
+
const unheld = added.filter((one) => one.workflow !== null && one.digest !== null && one.digest !== anyDigest && !held(one.workflow, one.digest));
|
|
422
|
+
if (unheld.length)
|
|
423
|
+
throw new LearningRecordRefused(agentId, unheld, "unheld");
|
|
424
|
+
}
|
|
425
|
+
const purged = [];
|
|
426
|
+
for (const one of added) {
|
|
427
|
+
if (one.runId !== null && (await tx.get("SELECT 1 AS one FROM runs WHERE id = ? AND purged_at IS NOT NULL", one.runId)))
|
|
428
|
+
purged.push(one);
|
|
429
|
+
}
|
|
430
|
+
if (purged.length)
|
|
431
|
+
throw new LearningRecordRefused(agentId, purged, "purged");
|
|
432
|
+
};
|
|
433
|
+
return {
|
|
434
|
+
seed: async (agentId) => {
|
|
435
|
+
const save = (await newest(db, agentId)) ?? (await db.transaction(async (tx) => {
|
|
436
|
+
await d.lockKey(tx, `learning:${agentId}`);
|
|
437
|
+
const there = await newest(tx, agentId);
|
|
438
|
+
if (there)
|
|
439
|
+
return there;
|
|
440
|
+
await tx.run(`INSERT INTO learning_saves (agent_id, version, id, at, kind, by_run, merge_key, change) VALUES (?, 1, ?, ?, 'init', NULL, NULL, '{}')`, agentId, versionId(), now());
|
|
441
|
+
return (await newest(tx, agentId));
|
|
442
|
+
}));
|
|
443
|
+
return atSave(db, agentId, save);
|
|
444
|
+
},
|
|
445
|
+
newest: async (agentId) => {
|
|
446
|
+
const save = await newest(db, agentId);
|
|
447
|
+
return save ? atSave(db, agentId, save) : undefined;
|
|
448
|
+
},
|
|
449
|
+
newestPurge: async (agentId) => (await db.get("SELECT id FROM learning_saves WHERE agent_id = ? AND kind = 'purged' ORDER BY version DESC LIMIT 1", agentId))?.id,
|
|
450
|
+
newestSave: async (agentId) => (await db.get("SELECT id FROM learning_saves WHERE agent_id = ? ORDER BY version DESC LIMIT 1", agentId))?.id,
|
|
451
|
+
itemsAt: async (agentId, id) => {
|
|
452
|
+
const save = await saveBy(db, agentId, "id = ?", id);
|
|
453
|
+
return save ? atSave(db, agentId, save) : undefined;
|
|
454
|
+
},
|
|
455
|
+
saves: async (agentId, { limit = 200, before } = {}) => {
|
|
456
|
+
const shown = "agent_id = ? AND kind IN ('run', 'person')";
|
|
457
|
+
const rows = await db.all(`SELECT ${SAVE_COLUMNS} FROM learning_saves WHERE ${shown}${before === undefined ? "" : " AND version < ?"} ORDER BY version DESC LIMIT ?`, agentId, ...(before === undefined ? [] : [before]), limit + 1);
|
|
458
|
+
const total = Number((await db.get(`SELECT COUNT(*) AS n FROM learning_saves WHERE ${shown}`, agentId))?.n ?? 0);
|
|
459
|
+
return { saves: rows.slice(0, limit).map(saveOf), more: rows.length > limit, total };
|
|
460
|
+
},
|
|
461
|
+
saveOf: (agentId, by) => ("id" in by ? saveBy(db, agentId, "id = ?", by.id) : saveBy(db, agentId, "merge_key = ?", by.mergeKey)),
|
|
462
|
+
versions: async (agentId, kind, name) => {
|
|
463
|
+
const rows = await db.all(`SELECT i.kind, i.name, i.version, i.body, i.by_run AS item_by_run, i.change AS item_change, i.person, i.pos, i.digest, i.writers, i.at, s.id, s.at AS save_at, s.kind AS save_kind, s.by_run, s.merge_key, s.change
|
|
464
|
+
FROM learning_items i JOIN learning_saves s ON s.agent_id = i.agent_id AND s.version = i.version
|
|
465
|
+
WHERE i.agent_id = ? AND i.kind = ? AND i.name = ? ORDER BY i.version DESC`, agentId, kind, name);
|
|
466
|
+
return rows.map((row) => ({ ...itemOf({ ...row, by_run: row.item_by_run, change: row.item_change }), save: saveOf({ ...row, kind: row.save_kind, at: row.save_at }) }));
|
|
467
|
+
},
|
|
468
|
+
diff: async (agentId, id) => {
|
|
469
|
+
const save = await saveBy(db, agentId, "id = ?", id);
|
|
470
|
+
if (!save || "host" in save.by)
|
|
471
|
+
return undefined;
|
|
472
|
+
const parent = await saveBy(db, agentId, "version = (SELECT MAX(version) FROM learning_saves WHERE agent_id = ? AND version < ?)", agentId, save.version);
|
|
473
|
+
const written = await db.all(`SELECT ${ITEM_COLUMNS} FROM learning_items WHERE agent_id = ? AND version = ? ORDER BY kind, pos, name`, agentId, save.version);
|
|
474
|
+
const items = [];
|
|
475
|
+
for (const row of written) {
|
|
476
|
+
const before = await db.get(`SELECT body FROM learning_items WHERE agent_id = ? AND kind = ? AND name = ? AND version = (SELECT MAX(version) FROM learning_items WHERE agent_id = ? AND kind = ? AND name = ? AND version < ?)`, agentId, row.kind, row.name, agentId, row.kind, row.name, save.version);
|
|
477
|
+
items.push({ kind: row.kind, name: row.name, before: before?.body ?? null, after: row.body ?? null });
|
|
478
|
+
}
|
|
479
|
+
return { save, parent, items };
|
|
480
|
+
},
|
|
481
|
+
save: (agentId, input) => db.transaction(async (tx) => {
|
|
482
|
+
await d.lockKey(tx, `learning:${agentId}`);
|
|
483
|
+
if (input.mergeKey !== undefined) {
|
|
484
|
+
const merged = await saveBy(tx, agentId, "merge_key = ?", input.mergeKey);
|
|
485
|
+
if (merged)
|
|
486
|
+
return { already: merged };
|
|
487
|
+
}
|
|
488
|
+
if (input.seed !== undefined && !(await saveBy(tx, agentId, "id = ?", input.seed)))
|
|
489
|
+
return { refused: { seed: input.seed } };
|
|
490
|
+
// A run's purge since a save the write read at rewrote that save's rows in place: what the write gives can't be
|
|
491
|
+
// told apart from the purged run's bytes (a file given back unchanged from its seed), so none of it is written.
|
|
492
|
+
if (input.readAt?.length) {
|
|
493
|
+
const purge = Number((await tx.get("SELECT MAX(version) AS v FROM learning_saves WHERE agent_id = ? AND kind = 'purged'", agentId))?.v ?? 0);
|
|
494
|
+
for (const id of input.readAt) {
|
|
495
|
+
const read = await saveBy(tx, agentId, "id = ?", id);
|
|
496
|
+
if (read && read.version < purge)
|
|
497
|
+
return { purged: { readAt: id } };
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
const head = Number((await tx.get("SELECT MAX(version) AS v FROM learning_saves WHERE agent_id = ?", agentId))?.v ?? 0);
|
|
501
|
+
if (head !== input.base)
|
|
502
|
+
return { stale: head };
|
|
503
|
+
const at = now();
|
|
504
|
+
const version = head + 1;
|
|
505
|
+
const id = versionId();
|
|
506
|
+
const change = { by: input.by, reason: input.reason, files: [...input.files] };
|
|
507
|
+
const byRun = "run" in input.by ? input.by.run : null;
|
|
508
|
+
await tx.run(`INSERT INTO learning_saves (agent_id, version, id, at, kind, by_run, merge_key, change) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, agentId, version, id, at, byRun === null ? "person" : "run", byRun, input.mergeKey ?? null, JSON.stringify(change));
|
|
509
|
+
for (const item of input.items) {
|
|
510
|
+
await tx.run(`INSERT INTO learning_items (agent_id, kind, name, version, body, by_run, change, person, pos, digest, writers, at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, agentId, item.kind, item.name, version, item.body, item.byRun, item.change, item.person ? 1 : 0, item.pos, item.digest, item.writers ? JSON.stringify(item.writers) : null, at);
|
|
511
|
+
}
|
|
512
|
+
return { saved: { version, id, at, by: input.by, reason: input.reason, files: [...input.files], mergeKey: input.mergeKey ?? null } };
|
|
513
|
+
}),
|
|
514
|
+
purgeRun: (agentId, runId) => db.transaction(async (tx) => {
|
|
515
|
+
await d.lockKey(tx, `learning:${agentId}`);
|
|
516
|
+
await dropRunLearning(tx, agentId, runId, now());
|
|
517
|
+
}),
|
|
518
|
+
reset: (agentId) => db.transaction((tx) => dropAgentLearning(tx, agentId)),
|
|
519
|
+
erase: (agentId) => db.transaction((tx) => dropAgentLearning(tx, agentId)),
|
|
520
|
+
records: (agentId, kind) => recordsIn(db, agentId, kind),
|
|
521
|
+
addRecord: (agentId, kind, record) => db.transaction(async (tx) => {
|
|
522
|
+
await d.lockKey(tx, `learning.records:${agentId}`);
|
|
523
|
+
await checkAdded(tx, agentId, kind, [record], await heldIn(tx, agentId));
|
|
524
|
+
const seq = Number((await tx.get("SELECT MAX(seq) AS s FROM learning_records WHERE agent_id = ? AND kind = ?", agentId, kind))?.s ?? 0) + 1;
|
|
525
|
+
const at = now();
|
|
526
|
+
const data = await insertRecord(tx, agentId, kind, record, seq, at);
|
|
527
|
+
return { seq, runId: record.runId, workflow: record.workflow, digest: record.digest, data: JSON.parse(JSON.stringify(data)), at };
|
|
528
|
+
}),
|
|
529
|
+
changeRecords: (agentId, kind, update, options) => db.transaction(async (tx) => {
|
|
530
|
+
await d.lockKey(tx, `learning.records:${agentId}`);
|
|
531
|
+
const before = await recordsIn(tx, agentId, kind);
|
|
532
|
+
const held = await heldIn(tx, agentId);
|
|
533
|
+
const answer = update(before, held);
|
|
534
|
+
if (!("records" in answer))
|
|
535
|
+
return answer.result;
|
|
536
|
+
const was = new Map(before.map((one) => [one.seq, one]));
|
|
537
|
+
const moved = (record, old) => !old || old.runId !== record.runId || old.workflow !== record.workflow || old.digest !== record.digest;
|
|
538
|
+
await checkAdded(tx, agentId, kind, answer.records.filter((record) => moved(record, record.seq === undefined ? undefined : was.get(record.seq))), held, options?.anyDigest);
|
|
539
|
+
const kept = new Set();
|
|
540
|
+
let next = Math.max(0, ...before.map((one) => one.seq)) + 1;
|
|
541
|
+
const at = now();
|
|
542
|
+
for (const record of answer.records) {
|
|
543
|
+
const old = record.seq === undefined ? undefined : was.get(record.seq);
|
|
544
|
+
if (!old) {
|
|
545
|
+
await insertRecord(tx, agentId, kind, record, next++, at);
|
|
546
|
+
continue;
|
|
547
|
+
}
|
|
548
|
+
kept.add(old.seq);
|
|
549
|
+
if (JSON.stringify(old.data) !== JSON.stringify(record.data ?? null) || old.runId !== record.runId || old.workflow !== record.workflow || old.digest !== record.digest) {
|
|
550
|
+
await tx.run("UPDATE learning_records SET run_id = ?, workflow = ?, digest = ?, data = ? WHERE agent_id = ? AND kind = ? AND seq = ?", ...columnsOf({ ...record, data: await keptData(tx, kind, agentId, record) }), agentId, kind, old.seq);
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
for (const one of before)
|
|
554
|
+
if (!kept.has(one.seq))
|
|
555
|
+
await tx.run("DELETE FROM learning_records WHERE agent_id = ? AND kind = ? AND seq = ?", agentId, kind, one.seq);
|
|
556
|
+
return answer.result;
|
|
557
|
+
}),
|
|
558
|
+
};
|
|
559
|
+
}
|
|
@@ -4,6 +4,11 @@ import { type StoreConnection } from "./connection.js";
|
|
|
4
4
|
export declare const DEFAULT_LEASE_MS = 30000;
|
|
5
5
|
/** The store's file in its data directory: only the store names it. */
|
|
6
6
|
export declare const STORE_FILE = "store.sqlite";
|
|
7
|
+
/** The oldest schema version this release brings up to SCHEMA_VERSION in place at its server's open (version 11,
|
|
8
|
+
* 0.1.0-beta.44 and before): every version from it to the one before SCHEMA_VERSION is upgraded, each step by the
|
|
9
|
+
* version it starts from; an older one is refused (SchemaVersionUnknown). The window follows SCHEMA_VERSION, so a new
|
|
10
|
+
* version never drops the one before it. */
|
|
11
|
+
export declare const OLDEST_UPGRADED = 11;
|
|
7
12
|
export type SqliteStoreOptions = (
|
|
8
13
|
/** The data directory (the server's and every runner's): the store's file is STORE_FILE in it. */
|
|
9
14
|
{
|
|
@@ -23,7 +28,8 @@ export type SqliteStoreOptions = (
|
|
|
23
28
|
busyTimeoutMs?: number;
|
|
24
29
|
};
|
|
25
30
|
/** The store's earlier versions the server upgrades in place at its open (openSqliteStore), which a runner waits for
|
|
26
|
-
* (StoreAwaitsServer); store-schema reports from the same set.
|
|
31
|
+
* (StoreAwaitsServer); store-schema reports from the same set. Every version from OLDEST_UPGRADED to the one before
|
|
32
|
+
* SCHEMA_VERSION, so a new version never drops the one before it. */
|
|
27
33
|
export declare const SQLITE_UPGRADES: ReadonlySet<number>;
|
|
28
34
|
/** The columns a runner of this build needs that an earlier build of this same version may not have: the server adds each
|
|
29
35
|
* at its start (openSqliteStore), and a runner on a file without one waits for that server (StoreAwaitsServer, in `why`'s
|