@mostra/runtime 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +39 -2
- package/dist/bin.d.ts +1 -0
- package/dist/bin.js +236 -0
- package/dist/bin.js.map +1 -0
- package/dist/builder/child/main.d.ts +1 -0
- package/dist/builder/child/main.js +1408 -0
- package/dist/builder/child/main.js.map +1 -0
- package/dist/child-xrHmytks.js +49 -0
- package/dist/child-xrHmytks.js.map +1 -0
- package/dist/deps/child/install.d.ts +1 -0
- package/dist/deps/child/install.js +33 -0
- package/dist/deps/child/install.js.map +1 -0
- package/dist/index.d.ts +221 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +3 -0
- package/dist/instance-D7_UVdoN.js +15752 -0
- package/dist/instance-D7_UVdoN.js.map +1 -0
- package/dist/types-NjNy7gXX.js +57 -0
- package/dist/types-NjNy7gXX.js.map +1 -0
- package/package.json +87 -3
- package/src/actions/index.ts +622 -0
- package/src/addressing/index.ts +281 -0
- package/src/bin.ts +240 -0
- package/src/builder/child/dev.ts +383 -0
- package/src/builder/child/fields.ts +363 -0
- package/src/builder/child/main.ts +47 -0
- package/src/builder/child/plugins.ts +195 -0
- package/src/builder/child/scan.ts +459 -0
- package/src/builder/child/spa.ts +348 -0
- package/src/builder/coverage.ts +72 -0
- package/src/builder/index.ts +406 -0
- package/src/builder/types.ts +180 -0
- package/src/deps/child/install.ts +30 -0
- package/src/deps/index.ts +918 -0
- package/src/deps/installer.ts +321 -0
- package/src/deps/lock.ts +82 -0
- package/src/deps/scan.ts +266 -0
- package/src/deps/specifier.ts +64 -0
- package/src/deps/warm.ts +57 -0
- package/src/dev/index.ts +518 -0
- package/src/faults.ts +65 -0
- package/src/gate.ts +55 -0
- package/src/gateway/actions.ts +268 -0
- package/src/gateway/browser.ts +650 -0
- package/src/gateway/capabilities.ts +739 -0
- package/src/gateway/controls.ts +91 -0
- package/src/gateway/dev.ts +119 -0
- package/src/gateway/http.ts +229 -0
- package/src/gateway/index.ts +1209 -0
- package/src/gateway/integrity.ts +117 -0
- package/src/gateway/listener.ts +217 -0
- package/src/gateway/routes.ts +197 -0
- package/src/gateway/serve.ts +138 -0
- package/src/gc/index.ts +451 -0
- package/src/home/acquire.ts +276 -0
- package/src/home/index.ts +16 -0
- package/src/home/paths.ts +192 -0
- package/src/home/platform.ts +34 -0
- package/src/home/record.ts +76 -0
- package/src/home/settings.ts +113 -0
- package/src/index.ts +30 -0
- package/src/instance/index.ts +942 -0
- package/src/interaction/ephemeral.ts +300 -0
- package/src/interaction/events.ts +355 -0
- package/src/interaction/fields.ts +392 -0
- package/src/interaction/index.ts +1009 -0
- package/src/interaction/outbox.ts +493 -0
- package/src/interaction/policy.ts +26 -0
- package/src/interaction/results.ts +341 -0
- package/src/interaction/runs.ts +313 -0
- package/src/interaction/signals.ts +120 -0
- package/src/interaction/submissions.ts +585 -0
- package/src/interaction/subscriptions.ts +258 -0
- package/src/interaction/viewers.ts +173 -0
- package/src/interaction/wait.ts +201 -0
- package/src/ledger/index.ts +442 -0
- package/src/ledger/migrations.ts +583 -0
- package/src/ledger/requests.ts +105 -0
- package/src/ledger/types.ts +28 -0
- package/src/live/index.ts +573 -0
- package/src/log.ts +316 -0
- package/src/processes/child.ts +67 -0
- package/src/processes/environment.ts +64 -0
- package/src/processes/identity.ts +191 -0
- package/src/processes/index.ts +19 -0
- package/src/processes/manager.ts +543 -0
- package/src/protocol-server/client.ts +94 -0
- package/src/protocol-server/index.ts +91 -0
- package/src/protocol-server/server.ts +509 -0
- package/src/protocol-server/streams.ts +81 -0
- package/src/publish/checks.ts +92 -0
- package/src/publish/digest.ts +87 -0
- package/src/publish/index.ts +23 -0
- package/src/publish/manifest.ts +409 -0
- package/src/publish/methods.ts +96 -0
- package/src/publish/publisher.ts +913 -0
- package/src/publish/source.ts +272 -0
- package/src/publish/tar.ts +110 -0
- package/src/registry/index.ts +481 -0
- package/src/registry/store.ts +136 -0
- package/src/secrets/index.ts +223 -0
- package/src/service/idle.ts +64 -0
- package/src/service/index.ts +3 -0
- package/src/service/unit.ts +250 -0
- package/src/verify/fields.ts +125 -0
- package/src/verify/index.ts +913 -0
- package/src/verify/regression.ts +157 -0
- package/src/verify/runner.ts +230 -0
- package/src/verify/sandbox.ts +407 -0
- package/src/verify/typecheck.ts +371 -0
- package/src/workers/index.ts +17 -0
- package/src/workers/launcher.ts +260 -0
- package/src/workers/pool.ts +708 -0
|
@@ -0,0 +1,341 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Results (IN-11, INTERFACES §8): the complete submission as JSON and as Markdown for agents.
|
|
3
|
+
* Everything comes from the immutable submission row, its snapshot and the version it names, plus
|
|
4
|
+
* the deliveries' current states; never from the live draft (IN-06).
|
|
5
|
+
*/
|
|
6
|
+
import type { ArtifactLink, ArtifactManifest, DeliveryStatus, Results } from "@mostra/protocol";
|
|
7
|
+
import { createDiagnostic, RpcError } from "@mostra/protocol";
|
|
8
|
+
import type { LedgerDb } from "../ledger/index.ts";
|
|
9
|
+
import {
|
|
10
|
+
deliveriesOf,
|
|
11
|
+
overallDelivery,
|
|
12
|
+
type Snapshot,
|
|
13
|
+
type SnapshotField,
|
|
14
|
+
type SubmissionRow,
|
|
15
|
+
} from "./submissions.ts";
|
|
16
|
+
|
|
17
|
+
/** The field ID a review set's choice is kept under (D65): `review.<set>.choice`. */
|
|
18
|
+
export const CHOICE: RegExp = /^review\.(.+)\.choice$/;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Nests dotted field IDs into objects (D52): `reply.m1` becomes `{ reply: { m1 } }`. A value never
|
|
22
|
+
* gets keys merged into it: when `a` holds a value and `a.b` exists too, `a.b` stays a literal key
|
|
23
|
+
* beside it, so no answer is lost or altered.
|
|
24
|
+
*/
|
|
25
|
+
export function nestFields(
|
|
26
|
+
fields: Readonly<Record<string, SnapshotField>>,
|
|
27
|
+
): Record<string, unknown> {
|
|
28
|
+
// Objects without a prototype, written with defineProperty, so a field ID such as `__proto__`
|
|
29
|
+
// is an ordinary key.
|
|
30
|
+
const make = (): Record<string, unknown> => Object.create(null) as Record<string, unknown>;
|
|
31
|
+
const set = (node: Record<string, unknown>, key: string, value: unknown): void => {
|
|
32
|
+
Object.defineProperty(node, key, {
|
|
33
|
+
value,
|
|
34
|
+
enumerable: true,
|
|
35
|
+
writable: true,
|
|
36
|
+
configurable: true,
|
|
37
|
+
});
|
|
38
|
+
};
|
|
39
|
+
const root = make();
|
|
40
|
+
const made = new Set<object>([root]);
|
|
41
|
+
for (const id of Object.keys(fields).sort()) {
|
|
42
|
+
const value = (fields[id] as SnapshotField).value;
|
|
43
|
+
const parts = id.split(".");
|
|
44
|
+
let node = root;
|
|
45
|
+
let index = 0;
|
|
46
|
+
for (; index < parts.length - 1; index++) {
|
|
47
|
+
const key = parts[index] as string;
|
|
48
|
+
const next = Object.hasOwn(node, key) ? node[key] : undefined;
|
|
49
|
+
if (next === undefined) {
|
|
50
|
+
const child = make();
|
|
51
|
+
made.add(child);
|
|
52
|
+
set(node, key, child);
|
|
53
|
+
node = child;
|
|
54
|
+
} else if (typeof next === "object" && next !== null && made.has(next)) {
|
|
55
|
+
node = next as Record<string, unknown>;
|
|
56
|
+
} else {
|
|
57
|
+
break;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
const rest = parts.slice(index).join(".");
|
|
61
|
+
if (!Object.hasOwn(node, rest)) set(node, rest, value);
|
|
62
|
+
else set(root, id, value);
|
|
63
|
+
}
|
|
64
|
+
return root;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function notFound(message: string): RpcError {
|
|
68
|
+
return new RpcError(createDiagnostic("MOSTRA_SUBMIT_NOT_FOUND", { message }));
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* The submission an artifact's results are read from: the one named, or the latest. Throws
|
|
73
|
+
* `MOSTRA_SUBMIT_NOT_FOUND` when there is none.
|
|
74
|
+
*/
|
|
75
|
+
export function submissionFor(
|
|
76
|
+
db: LedgerDb,
|
|
77
|
+
artifactId: string,
|
|
78
|
+
submissionId: string | undefined,
|
|
79
|
+
): SubmissionRow {
|
|
80
|
+
const row =
|
|
81
|
+
submissionId === undefined
|
|
82
|
+
? db.get<SubmissionRow>(
|
|
83
|
+
"SELECT * FROM submission WHERE artifact_id = ? ORDER BY position DESC LIMIT 1",
|
|
84
|
+
artifactId,
|
|
85
|
+
)
|
|
86
|
+
: db.get<SubmissionRow>(
|
|
87
|
+
"SELECT * FROM submission WHERE id = ? AND artifact_id = ?",
|
|
88
|
+
submissionId,
|
|
89
|
+
artifactId,
|
|
90
|
+
);
|
|
91
|
+
if (!row) {
|
|
92
|
+
throw notFound(
|
|
93
|
+
submissionId === undefined
|
|
94
|
+
? `The artifact ${artifactId} has no submission yet.`
|
|
95
|
+
: `The artifact ${artifactId} has no submission ${submissionId}.`,
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
return row;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** The complete results of a submission (INTERFACES §8). */
|
|
102
|
+
export function buildResults(db: LedgerDb, row: SubmissionRow): Results {
|
|
103
|
+
const snapshot = JSON.parse(row.snapshot_json) as Snapshot;
|
|
104
|
+
const version = db.get<{ manifest_json: string }>(
|
|
105
|
+
"SELECT manifest_json FROM version WHERE id = ?",
|
|
106
|
+
row.version_id,
|
|
107
|
+
);
|
|
108
|
+
const manifest = version ? (JSON.parse(version.manifest_json) as ArtifactManifest) : undefined;
|
|
109
|
+
const artifactRow = db.get<{ title: string; family: string | null; links_json: string }>(
|
|
110
|
+
"SELECT title, family, links_json FROM artifact WHERE id = ?",
|
|
111
|
+
row.artifact_id,
|
|
112
|
+
);
|
|
113
|
+
const family = manifest ? manifest.family : (artifactRow?.family ?? undefined);
|
|
114
|
+
const links = manifest
|
|
115
|
+
? (manifest.links ?? [])
|
|
116
|
+
: (JSON.parse(artifactRow?.links_json ?? "[]") as ArtifactLink[]);
|
|
117
|
+
const deliveries: DeliveryStatus[] = deliveriesOf(db, row.id);
|
|
118
|
+
const draftFields = snapshot.draft.fields;
|
|
119
|
+
const stateFields = snapshot.state?.fields;
|
|
120
|
+
const describe = (id: string, field: SnapshotField, scope: "viewer" | "artifact") => ({
|
|
121
|
+
id,
|
|
122
|
+
...(field.label !== undefined ? { label: field.label } : {}),
|
|
123
|
+
...(field.required !== undefined ? { required: field.required } : {}),
|
|
124
|
+
...(field.sensitive ? { sensitive: true } : {}),
|
|
125
|
+
scope,
|
|
126
|
+
});
|
|
127
|
+
return {
|
|
128
|
+
artifact: {
|
|
129
|
+
id: row.artifact_id,
|
|
130
|
+
title: manifest?.title ?? artifactRow?.title ?? row.artifact_id,
|
|
131
|
+
...(manifest?.description !== undefined ? { description: manifest.description } : {}),
|
|
132
|
+
...(family !== undefined && family !== null ? { family } : {}),
|
|
133
|
+
links,
|
|
134
|
+
},
|
|
135
|
+
submission: {
|
|
136
|
+
id: row.id,
|
|
137
|
+
at: row.created_at,
|
|
138
|
+
epoch: row.epoch,
|
|
139
|
+
...(row.previous_id !== null ? { previous: row.previous_id } : {}),
|
|
140
|
+
policy: snapshot.policy,
|
|
141
|
+
channel: row.channel,
|
|
142
|
+
viewer: snapshot.viewer,
|
|
143
|
+
versionId: row.version_id,
|
|
144
|
+
version: snapshot.version,
|
|
145
|
+
viewId: row.view_id,
|
|
146
|
+
staleView: row.stale_view === 1,
|
|
147
|
+
...(row.latest_version_number !== null ? { latestVersion: row.latest_version_number } : {}),
|
|
148
|
+
draftRevision: String(row.draft_revision),
|
|
149
|
+
...(row.state_revision !== null ? { stateRevision: String(row.state_revision) } : {}),
|
|
150
|
+
digest: row.digest,
|
|
151
|
+
delivery: overallDelivery(deliveries),
|
|
152
|
+
deliveries,
|
|
153
|
+
},
|
|
154
|
+
answers: nestFields(draftFields),
|
|
155
|
+
fields: [
|
|
156
|
+
...Object.keys(draftFields)
|
|
157
|
+
.sort()
|
|
158
|
+
.map((id) => describe(id, draftFields[id] as SnapshotField, "viewer")),
|
|
159
|
+
...Object.keys(stateFields ?? {})
|
|
160
|
+
.sort()
|
|
161
|
+
.map((id) =>
|
|
162
|
+
describe(
|
|
163
|
+
id,
|
|
164
|
+
(stateFields as Record<string, SnapshotField>)[id] as SnapshotField,
|
|
165
|
+
"artifact",
|
|
166
|
+
),
|
|
167
|
+
),
|
|
168
|
+
],
|
|
169
|
+
...(stateFields ? { state: nestFields(stateFields) } : {}),
|
|
170
|
+
choices: Object.keys(draftFields)
|
|
171
|
+
.sort()
|
|
172
|
+
.flatMap((id) => {
|
|
173
|
+
const match = CHOICE.exec(id);
|
|
174
|
+
const field = draftFields[id] as SnapshotField;
|
|
175
|
+
// The trusted Choose keeps the candidate's label as the field's (D113).
|
|
176
|
+
return match && typeof field.value === "string"
|
|
177
|
+
? [
|
|
178
|
+
{
|
|
179
|
+
reviewSetId: match[1] as string,
|
|
180
|
+
candidateId: field.value,
|
|
181
|
+
...(field.label !== undefined ? { label: field.label } : {}),
|
|
182
|
+
},
|
|
183
|
+
]
|
|
184
|
+
: [];
|
|
185
|
+
}),
|
|
186
|
+
comments: [],
|
|
187
|
+
orphaned: snapshot.orphaned,
|
|
188
|
+
actions: snapshot.actions ?? [],
|
|
189
|
+
signals: snapshot.signals,
|
|
190
|
+
...(snapshot.signalsOmitted !== undefined ? { signalsOmitted: snapshot.signalsOmitted } : {}),
|
|
191
|
+
...(snapshot.signalsCompacted ? { signalsCompacted: true as const } : {}),
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Text from viewers and hosts is data in the Markdown, never structure (Claude review finding 4):
|
|
197
|
+
* labels and string values are JSON strings, identifiers and JSON are code spans whose delimiters
|
|
198
|
+
* outrun any backticks inside, multi-line text sits in a fence longer than any backtick run in it,
|
|
199
|
+
* and everything else is folded onto one line.
|
|
200
|
+
*/
|
|
201
|
+
const LINE_BREAKS = /\r\n|\r|\n|\u2028|\u2029/;
|
|
202
|
+
|
|
203
|
+
/** Control characters and line separators as spaces: the text stays on its line. */
|
|
204
|
+
function oneLine(text: string): string {
|
|
205
|
+
// biome-ignore lint/suspicious/noControlCharactersInRegex: replacing them is the point.
|
|
206
|
+
return text.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g, " ");
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** The longest run of backticks in `text`. */
|
|
210
|
+
function longestBacktickRun(text: string): number {
|
|
211
|
+
let longest = 0;
|
|
212
|
+
for (const run of text.match(/`+/g) ?? []) longest = Math.max(longest, run.length);
|
|
213
|
+
return longest;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** `text` as an inline code span that nothing inside can close. */
|
|
217
|
+
export function code(text: string): string {
|
|
218
|
+
const line = oneLine(text);
|
|
219
|
+
const ticks = "`".repeat(longestBacktickRun(line) + 1);
|
|
220
|
+
const pad = line.startsWith("`") || line.endsWith("`") || line.trim() === "" ? " " : "";
|
|
221
|
+
return `${ticks}${pad}${line}${pad}${ticks}`;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** `text` as a JSON string: quoted, with its line breaks and controls escaped. */
|
|
225
|
+
function quoted(text: string): string {
|
|
226
|
+
return oneLine(JSON.stringify(text));
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** A value as one Markdown line, or a fenced block for text with line breaks. */
|
|
230
|
+
function markdownValue(value: unknown): string {
|
|
231
|
+
if (typeof value === "string") {
|
|
232
|
+
if (!LINE_BREAKS.test(value)) return quoted(value);
|
|
233
|
+
const fence = "`".repeat(Math.max(3, longestBacktickRun(value) + 1));
|
|
234
|
+
const body = value
|
|
235
|
+
.split(LINE_BREAKS)
|
|
236
|
+
.map((line) => ` ${line}`)
|
|
237
|
+
.join("\n");
|
|
238
|
+
return `\n\n ${fence}text\n${body}\n ${fence}\n`;
|
|
239
|
+
}
|
|
240
|
+
return code(JSON.stringify(value));
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** A field's name: its label as a JSON string, then its ID as code. */
|
|
244
|
+
function fieldName(id: string, label: string | undefined): string {
|
|
245
|
+
return label !== undefined ? `${quoted(label)} (${code(id)})` : code(id);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
function fieldLines(fields: Readonly<Record<string, SnapshotField>>): string[] {
|
|
249
|
+
const ids = Object.keys(fields).sort();
|
|
250
|
+
if (ids.length === 0) return ["- (none)"];
|
|
251
|
+
return ids.map((id) => {
|
|
252
|
+
const field = fields[id] as SnapshotField;
|
|
253
|
+
return `- ${fieldName(id, field.label)}: ${markdownValue(field.value)}`;
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* Results as Markdown for agents (ROUND-2 §1.1): a header with the IDs, then answers by label,
|
|
259
|
+
* the artifact state, choices, comments with their crop paths, actions, signals, and what didn't
|
|
260
|
+
* carry over. Every section is present, with "(none)" when empty, so an agent never wonders
|
|
261
|
+
* whether a section was dropped. Viewers' and hosts' text is rendered as data, so no answer,
|
|
262
|
+
* label or reason can forge a section.
|
|
263
|
+
*/
|
|
264
|
+
export function resultsMarkdown(results: Results, snapshot: Snapshot): string {
|
|
265
|
+
const { submission } = results;
|
|
266
|
+
const viewer = submission.viewer.name ?? submission.viewer.ref ?? submission.viewer.id;
|
|
267
|
+
const signalNotes = [
|
|
268
|
+
...(results.signalsOmitted !== undefined
|
|
269
|
+
? [`- (${results.signalsOmitted} older signals of this view left out)`]
|
|
270
|
+
: []),
|
|
271
|
+
...(results.signalsCompacted ? ["- (some signals may have been removed by compaction)"] : []),
|
|
272
|
+
];
|
|
273
|
+
const lines = [
|
|
274
|
+
`# ${oneLine(results.artifact.title)}: submission ${submission.id}`,
|
|
275
|
+
"",
|
|
276
|
+
`- Artifact: ${results.artifact.id}${results.artifact.family ? ` (${code(results.artifact.family)})` : ""}`,
|
|
277
|
+
`- Version: ${submission.versionId} (version ${submission.version})${submission.staleView ? `, a stale view: version ${submission.latestVersion ?? "?"} was the latest` : ""}`,
|
|
278
|
+
`- View: ${submission.viewId}, channel ${submission.channel}, viewer ${quoted(viewer)} (${submission.viewer.id})`,
|
|
279
|
+
`- Submitted: ${submission.at}, epoch ${submission.epoch}${submission.previous ? ` (after ${submission.previous})` : ""}, policy ${submission.policy.policy}${submission.policy.policy === "once" ? ` ${submission.policy.scope ?? "per-artifact"}` : ""}`,
|
|
280
|
+
`- Draft revision ${submission.draftRevision}${submission.stateRevision !== undefined ? `, artifact state revision ${submission.stateRevision}` : ""}, digest ${submission.digest}`,
|
|
281
|
+
`- Delivery: ${submission.delivery}${submission.deliveries.length > 0 ? ` (${submission.deliveries.map((delivery) => `${delivery.owner === "" ? "built-in" : quoted(delivery.owner)}: ${delivery.state}${delivery.reason ? `, ${quoted(delivery.reason)}` : ""}`).join("; ")})` : ""}`,
|
|
282
|
+
...(results.artifact.links.length > 0
|
|
283
|
+
? [
|
|
284
|
+
`- Links: ${results.artifact.links.map((link) => `${code(link.rel)} ${code(link.artifact)}`).join(", ")}`,
|
|
285
|
+
]
|
|
286
|
+
: []),
|
|
287
|
+
"",
|
|
288
|
+
"## Answers",
|
|
289
|
+
...fieldLines(snapshot.draft.fields),
|
|
290
|
+
"",
|
|
291
|
+
"## Artifact state",
|
|
292
|
+
...(snapshot.state ? fieldLines(snapshot.state.fields) : ["- (none)"]),
|
|
293
|
+
"",
|
|
294
|
+
"## Choices",
|
|
295
|
+
...(results.choices.length > 0
|
|
296
|
+
? results.choices.map(
|
|
297
|
+
(choice) =>
|
|
298
|
+
`- ${code(choice.reviewSetId)}: ${quoted(choice.candidateId)}${choice.label ? ` (${quoted(choice.label)})` : ""}`,
|
|
299
|
+
)
|
|
300
|
+
: ["- (none)"]),
|
|
301
|
+
"",
|
|
302
|
+
"## Comments",
|
|
303
|
+
...(results.comments.length > 0
|
|
304
|
+
? results.comments.flatMap((comment) => [
|
|
305
|
+
`- Thread ${comment.threadId} (${comment.status}), crop ${code(comment.crop.path)}${comment.anchor.reviewId ? `, on ${code(comment.anchor.reviewId)}` : ""}${comment.anchor.page ? `, page ${code(comment.anchor.page)}` : ""}`,
|
|
306
|
+
...comment.messages.map(
|
|
307
|
+
(message) =>
|
|
308
|
+
` - ${quoted(message.author.name ?? message.author.id)} at ${message.at}: ${quoted(message.text)}`,
|
|
309
|
+
),
|
|
310
|
+
])
|
|
311
|
+
: ["- (none)"]),
|
|
312
|
+
"",
|
|
313
|
+
"## Actions run in this view",
|
|
314
|
+
...(results.actions.length > 0
|
|
315
|
+
? results.actions.map(
|
|
316
|
+
(run) => `- ${code(run.action)}: ${run.status} at ${run.at} (run ${run.runId})`,
|
|
317
|
+
)
|
|
318
|
+
: ["- (none)"]),
|
|
319
|
+
"",
|
|
320
|
+
"## Signals raised in this view",
|
|
321
|
+
...(results.signals.length > 0 || signalNotes.length > 0
|
|
322
|
+
? [
|
|
323
|
+
...signalNotes,
|
|
324
|
+
...results.signals.map(
|
|
325
|
+
(signal) =>
|
|
326
|
+
`- ${code(signal.name)} at ${signal.at}${signal.payload !== undefined ? `: ${code(JSON.stringify(signal.payload))}` : ""}`,
|
|
327
|
+
),
|
|
328
|
+
]
|
|
329
|
+
: ["- (none)"]),
|
|
330
|
+
"",
|
|
331
|
+
"## Not carried over from an earlier version",
|
|
332
|
+
...(results.orphaned.length > 0
|
|
333
|
+
? results.orphaned.map(
|
|
334
|
+
(orphan) =>
|
|
335
|
+
`- ${fieldName(orphan.id, orphan.label)} from version ${orphan.fromVersion}: ${markdownValue(orphan.value)}`,
|
|
336
|
+
)
|
|
337
|
+
: ["- (none)"]),
|
|
338
|
+
"",
|
|
339
|
+
];
|
|
340
|
+
return lines.join("\n");
|
|
341
|
+
}
|
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Action runs in the ledger (D24, D54, AC-02, AC-03; ARCHITECTURE §7): each invocation through
|
|
3
|
+
* `useAction` is recorded before any worker starts it, keyed so a double click, a second tab or a
|
|
4
|
+
* reload joins the run that exists, and every change of state appends its event in the same
|
|
5
|
+
* transaction. The log is capped at 1 MB with a marker (D47); the result's batches only grow while
|
|
6
|
+
* the run runs, and a finished run never changes again (a trigger refuses it).
|
|
7
|
+
*/
|
|
8
|
+
import {
|
|
9
|
+
type Actor,
|
|
10
|
+
type Batches,
|
|
11
|
+
createDiagnostic,
|
|
12
|
+
type Frame,
|
|
13
|
+
isFinalRunStatus,
|
|
14
|
+
RpcError,
|
|
15
|
+
RUN_LOG_MAX,
|
|
16
|
+
RUN_LOG_TRUNCATED,
|
|
17
|
+
RunId,
|
|
18
|
+
type RunProgress,
|
|
19
|
+
type RunState,
|
|
20
|
+
type RunStatus,
|
|
21
|
+
type WireError,
|
|
22
|
+
} from "@mostra/protocol";
|
|
23
|
+
import type { LedgerDb } from "../ledger/index.ts";
|
|
24
|
+
import { appendEvent } from "./events.ts";
|
|
25
|
+
|
|
26
|
+
/** An `action_run` row. */
|
|
27
|
+
export interface RunRow {
|
|
28
|
+
readonly id: string;
|
|
29
|
+
readonly artifact_id: string;
|
|
30
|
+
readonly version_id: string;
|
|
31
|
+
readonly view_id: string | null;
|
|
32
|
+
readonly viewer_id: string | null;
|
|
33
|
+
readonly action: string;
|
|
34
|
+
readonly args_json: string;
|
|
35
|
+
readonly key: string | null;
|
|
36
|
+
readonly client_key: string;
|
|
37
|
+
readonly status: RunStatus;
|
|
38
|
+
readonly reason: string | null;
|
|
39
|
+
readonly error_json: string | null;
|
|
40
|
+
readonly progress_json: string | null;
|
|
41
|
+
readonly log_text: string;
|
|
42
|
+
readonly log_lines: number;
|
|
43
|
+
readonly log_truncated: number;
|
|
44
|
+
readonly batches: number;
|
|
45
|
+
readonly result_size: number;
|
|
46
|
+
readonly started_at: string;
|
|
47
|
+
readonly finished_at: string | null;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** A run to record. */
|
|
51
|
+
export interface NewRun {
|
|
52
|
+
readonly artifactId: string;
|
|
53
|
+
readonly versionId: string;
|
|
54
|
+
readonly viewId: string;
|
|
55
|
+
readonly viewerId: string;
|
|
56
|
+
readonly fnId: string;
|
|
57
|
+
readonly args: Batches;
|
|
58
|
+
readonly key?: string;
|
|
59
|
+
readonly clientKey: string;
|
|
60
|
+
readonly actor: Actor;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** The run a request names, by ID, of one artifact. */
|
|
64
|
+
export function runById(db: LedgerDb, artifactId: string, runId: string): RunRow | undefined {
|
|
65
|
+
return db.get<RunRow>(
|
|
66
|
+
"SELECT * FROM action_run WHERE id = ? AND artifact_id = ?",
|
|
67
|
+
runId,
|
|
68
|
+
artifactId,
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** The run of an artifact, function and key, if one was ever started. */
|
|
73
|
+
export function runByKey(
|
|
74
|
+
db: LedgerDb,
|
|
75
|
+
artifactId: string,
|
|
76
|
+
fnId: string,
|
|
77
|
+
key: string,
|
|
78
|
+
): RunRow | undefined {
|
|
79
|
+
return db.get<RunRow>(
|
|
80
|
+
"SELECT * FROM action_run WHERE artifact_id = ? AND action = ? AND key = ?",
|
|
81
|
+
artifactId,
|
|
82
|
+
fnId,
|
|
83
|
+
key,
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Records a run as `queued` and appends `action.started`, or returns the run the request joins:
|
|
89
|
+
* the one its client key already started (a retried request), or the one its key names (AC-03).
|
|
90
|
+
*/
|
|
91
|
+
export function createOrJoinRun(db: LedgerDb, input: NewRun): { row: RunRow; joined: boolean } {
|
|
92
|
+
const retried = db.get<RunRow>(
|
|
93
|
+
"SELECT * FROM action_run WHERE artifact_id = ? AND client_key = ?",
|
|
94
|
+
input.artifactId,
|
|
95
|
+
input.clientKey,
|
|
96
|
+
);
|
|
97
|
+
if (retried) {
|
|
98
|
+
// A client key is one page's request: another viewer's never joins it, nor a request for
|
|
99
|
+
// another function (whose run its link may not be allowed to see, Opus review 9).
|
|
100
|
+
if (retried.viewer_id !== input.viewerId || retried.action !== input.fnId) {
|
|
101
|
+
throw new RpcError(
|
|
102
|
+
createDiagnostic("MOSTRA_HOST_INVALID_PARAMS", {
|
|
103
|
+
message: "This clientKey belongs to another request; send a new one.",
|
|
104
|
+
}),
|
|
105
|
+
);
|
|
106
|
+
}
|
|
107
|
+
return { row: retried, joined: true };
|
|
108
|
+
}
|
|
109
|
+
if (input.key !== undefined) {
|
|
110
|
+
const keyed = runByKey(db, input.artifactId, input.fnId, input.key);
|
|
111
|
+
if (keyed) return { row: keyed, joined: true };
|
|
112
|
+
}
|
|
113
|
+
const id = RunId.create();
|
|
114
|
+
const startedAt = new Date().toISOString();
|
|
115
|
+
db.run(
|
|
116
|
+
`INSERT INTO action_run (id, artifact_id, version_id, view_id, viewer_id, action, args_json, key,
|
|
117
|
+
client_key, status, started_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'queued', ?)`,
|
|
118
|
+
id,
|
|
119
|
+
input.artifactId,
|
|
120
|
+
input.versionId,
|
|
121
|
+
input.viewId,
|
|
122
|
+
input.viewerId,
|
|
123
|
+
input.fnId,
|
|
124
|
+
JSON.stringify(input.args),
|
|
125
|
+
input.key ?? null,
|
|
126
|
+
input.clientKey,
|
|
127
|
+
startedAt,
|
|
128
|
+
);
|
|
129
|
+
appendEvent(db, {
|
|
130
|
+
artifactId: input.artifactId,
|
|
131
|
+
type: "action.started",
|
|
132
|
+
actor: input.actor,
|
|
133
|
+
causation: { runId: id, viewId: input.viewId },
|
|
134
|
+
payload: {
|
|
135
|
+
runId: id,
|
|
136
|
+
action: input.fnId,
|
|
137
|
+
...(input.key !== undefined ? { key: input.key } : {}),
|
|
138
|
+
viewId: input.viewId,
|
|
139
|
+
},
|
|
140
|
+
});
|
|
141
|
+
return {
|
|
142
|
+
row: db.get<RunRow>("SELECT * FROM action_run WHERE id = ?", id) as RunRow,
|
|
143
|
+
joined: false,
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Moves a queued run to `running`, when its worker has it. */
|
|
148
|
+
export function markRunning(db: LedgerDb, runId: string): void {
|
|
149
|
+
db.run("UPDATE action_run SET status = 'running' WHERE id = ? AND status = 'queued'", runId);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** What a running run produced since the last flush. */
|
|
153
|
+
export interface RunOutput {
|
|
154
|
+
readonly lines: readonly string[];
|
|
155
|
+
readonly batches: readonly (readonly Frame[])[];
|
|
156
|
+
readonly progress?: RunProgress;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** The counts after a flush, and the lines and batches actually kept. */
|
|
160
|
+
export interface RunFlush {
|
|
161
|
+
readonly logFrom: number;
|
|
162
|
+
readonly log: readonly string[];
|
|
163
|
+
readonly batchFrom: number;
|
|
164
|
+
readonly batches: readonly (readonly Frame[])[];
|
|
165
|
+
readonly resultSize: number;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Appends a run's new log lines (until the 1 MB cap, then one marker line) and result batches,
|
|
170
|
+
* and keeps its latest progress. Does nothing to a finished run.
|
|
171
|
+
*/
|
|
172
|
+
export function appendRunOutput(
|
|
173
|
+
db: LedgerDb,
|
|
174
|
+
runId: string,
|
|
175
|
+
output: RunOutput,
|
|
176
|
+
): RunFlush | undefined {
|
|
177
|
+
const row = db.get<RunRow>("SELECT * FROM action_run WHERE id = ?", runId);
|
|
178
|
+
if (!row || isFinalRunStatus(row.status)) return undefined;
|
|
179
|
+
const kept: string[] = [];
|
|
180
|
+
let text = row.log_text;
|
|
181
|
+
let lines = row.log_lines;
|
|
182
|
+
let truncated = row.log_truncated === 1;
|
|
183
|
+
for (const raw of output.lines) {
|
|
184
|
+
for (const line of raw.split(/\r?\n/)) {
|
|
185
|
+
if (truncated) break;
|
|
186
|
+
if (text.length + line.length + 1 > RUN_LOG_MAX) {
|
|
187
|
+
truncated = true;
|
|
188
|
+
kept.push(RUN_LOG_TRUNCATED);
|
|
189
|
+
text += `${lines > 0 ? "\n" : ""}${RUN_LOG_TRUNCATED}`;
|
|
190
|
+
lines += 1;
|
|
191
|
+
break;
|
|
192
|
+
}
|
|
193
|
+
kept.push(line);
|
|
194
|
+
text += `${lines > 0 ? "\n" : ""}${line}`;
|
|
195
|
+
lines += 1;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
let size = row.result_size;
|
|
199
|
+
output.batches.forEach((batch, index) => {
|
|
200
|
+
const json = JSON.stringify(batch);
|
|
201
|
+
size += json.length;
|
|
202
|
+
db.run(
|
|
203
|
+
"INSERT INTO action_run_batch (run_id, seq, batch_json) VALUES (?, ?, ?)",
|
|
204
|
+
runId,
|
|
205
|
+
row.batches + index,
|
|
206
|
+
json,
|
|
207
|
+
);
|
|
208
|
+
});
|
|
209
|
+
db.run(
|
|
210
|
+
`UPDATE action_run SET log_text = ?, log_lines = ?, log_truncated = ?, batches = ?, result_size = ?,
|
|
211
|
+
progress_json = COALESCE(?, progress_json) WHERE id = ?`,
|
|
212
|
+
text,
|
|
213
|
+
lines,
|
|
214
|
+
truncated ? 1 : 0,
|
|
215
|
+
row.batches + output.batches.length,
|
|
216
|
+
size,
|
|
217
|
+
output.progress === undefined ? null : JSON.stringify(output.progress),
|
|
218
|
+
runId,
|
|
219
|
+
);
|
|
220
|
+
return {
|
|
221
|
+
logFrom: row.log_lines,
|
|
222
|
+
log: kept,
|
|
223
|
+
batchFrom: row.batches,
|
|
224
|
+
batches: output.batches,
|
|
225
|
+
resultSize: size,
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** How a run ended. */
|
|
230
|
+
export interface RunEnd {
|
|
231
|
+
readonly status: "succeeded" | "failed" | "cancelled";
|
|
232
|
+
readonly reason?: string;
|
|
233
|
+
readonly error?: WireError;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** Ends a run and appends `action.succeeded`, `action.failed` or `action.cancelled`. */
|
|
237
|
+
export function finishRun(db: LedgerDb, runId: string, end: RunEnd): RunRow | undefined {
|
|
238
|
+
const row = db.get<RunRow>("SELECT * FROM action_run WHERE id = ?", runId);
|
|
239
|
+
if (!row || isFinalRunStatus(row.status)) return row;
|
|
240
|
+
const finishedAt = new Date().toISOString();
|
|
241
|
+
db.run(
|
|
242
|
+
"UPDATE action_run SET status = ?, reason = ?, error_json = ?, finished_at = ? WHERE id = ?",
|
|
243
|
+
end.status,
|
|
244
|
+
end.reason ?? null,
|
|
245
|
+
end.error === undefined ? null : JSON.stringify(end.error),
|
|
246
|
+
finishedAt,
|
|
247
|
+
runId,
|
|
248
|
+
);
|
|
249
|
+
appendEvent(db, {
|
|
250
|
+
artifactId: row.artifact_id,
|
|
251
|
+
type: `action.${end.status}`,
|
|
252
|
+
actor: { kind: "mostra" },
|
|
253
|
+
causation: { runId },
|
|
254
|
+
payload: {
|
|
255
|
+
runId,
|
|
256
|
+
action: row.action,
|
|
257
|
+
...(end.reason !== undefined ? { reason: end.reason } : {}),
|
|
258
|
+
...(end.error?.code !== undefined ? { code: end.error.code } : {}),
|
|
259
|
+
},
|
|
260
|
+
});
|
|
261
|
+
return db.get<RunRow>("SELECT * FROM action_run WHERE id = ?", runId);
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/** The runs still open (queued, running or waiting), optionally of one version. */
|
|
265
|
+
export function openRuns(db: LedgerDb, versionId?: string): RunRow[] {
|
|
266
|
+
return versionId === undefined
|
|
267
|
+
? db.all<RunRow>("SELECT * FROM action_run WHERE status IN ('queued', 'running', 'waiting')")
|
|
268
|
+
: db.all<RunRow>(
|
|
269
|
+
"SELECT * FROM action_run WHERE status IN ('queued', 'running', 'waiting') AND version_id = ?",
|
|
270
|
+
versionId,
|
|
271
|
+
);
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/** A run as a page reads it: state, progress, the whole log and every batch so far. */
|
|
275
|
+
export function runState(
|
|
276
|
+
db: LedgerDb,
|
|
277
|
+
row: RunRow,
|
|
278
|
+
joined?: boolean,
|
|
279
|
+
held?: { readonly log: number; readonly batches: number },
|
|
280
|
+
): RunState {
|
|
281
|
+
// What the page holds already isn't read again (Opus review 14).
|
|
282
|
+
const batchFrom = Math.min(held?.batches ?? 0, row.batches);
|
|
283
|
+
const batches = db
|
|
284
|
+
.all<{ batch_json: string }>(
|
|
285
|
+
"SELECT batch_json FROM action_run_batch WHERE run_id = ? AND seq >= ? ORDER BY seq",
|
|
286
|
+
row.id,
|
|
287
|
+
batchFrom,
|
|
288
|
+
)
|
|
289
|
+
.map((entry) => JSON.parse(entry.batch_json) as Frame[]);
|
|
290
|
+
const lines = row.log_text === "" && row.log_lines === 0 ? [] : row.log_text.split("\n");
|
|
291
|
+
const logFrom = Math.min(held?.log ?? 0, lines.length);
|
|
292
|
+
const error = row.error_json === null ? undefined : (JSON.parse(row.error_json) as WireError);
|
|
293
|
+
return {
|
|
294
|
+
runId: row.id,
|
|
295
|
+
fnId: row.action,
|
|
296
|
+
...(row.key !== null ? { key: row.key } : {}),
|
|
297
|
+
status: row.status,
|
|
298
|
+
...(row.reason !== null ? { reason: row.reason } : {}),
|
|
299
|
+
...(row.progress_json !== null
|
|
300
|
+
? { progress: JSON.parse(row.progress_json) as RunProgress }
|
|
301
|
+
: {}),
|
|
302
|
+
log: logFrom === 0 ? lines : lines.slice(logFrom),
|
|
303
|
+
batches,
|
|
304
|
+
...(logFrom > 0 ? { logFrom } : {}),
|
|
305
|
+
...(batchFrom > 0 ? { batchFrom } : {}),
|
|
306
|
+
...(error
|
|
307
|
+
? { error: { message: error.message, ...(error.code ? { code: error.code } : {}) } }
|
|
308
|
+
: {}),
|
|
309
|
+
startedAt: row.started_at,
|
|
310
|
+
...(row.finished_at !== null ? { finishedAt: row.finished_at } : {}),
|
|
311
|
+
...(joined === undefined ? {} : { joined }),
|
|
312
|
+
};
|
|
313
|
+
}
|