@flyingrobots/parley-read 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/src/locate.ts ADDED
@@ -0,0 +1,70 @@
1
+ // Where receipts are, for a given working directory (spec §5, §5.2).
2
+ //
3
+ // A writer resolves its receipt location once at startup: `.parley/receipts/<run>.jsonl` under the
4
+ // invocation's **initial** working directory when hygiene can be established there, and otherwise
5
+ // `$XDG_STATE_HOME/parley/<repo-hash>/receipts/<run>.jsonl`, where `<repo-hash>` is a digest of
6
+ // the canonical path of the git worktree root. Either location may hold runs, so a reader looks in
7
+ // both.
8
+ //
9
+ // The repo-hash derivation and the state-directory base come from the writer
10
+ // (`@flyingrobots/parley-emit`) rather than being written out a second time here: a reader that
11
+ // derives the key differently by a byte looks in an empty directory and reports, honestly and
12
+ // uselessly, that there are no receipts.
13
+ import { realpathSync, statSync } from "node:fs";
14
+ import { homedir } from "node:os";
15
+ import { join, resolve } from "node:path";
16
+ import { repoRoot, sha256, stateBase } from "@flyingrobots/parley-emit";
17
+
18
+ /**
19
+ * Which of the spec's two locations a bundle came from; `history` is a segment of the shared
20
+ * stream (§8), and `other` is a path a caller named itself.
21
+ */
22
+ export type Where = "repo" | "state" | "history" | "other";
23
+
24
+ export interface ReceiptLocation {
25
+ readonly where: "repo" | "state";
26
+ readonly dir: string;
27
+ /** Whether the directory exists. A location that does not exist is not an error: the writer never needed it. */
28
+ readonly present: boolean;
29
+ }
30
+
31
+ export interface LocateOptions {
32
+ /** The working directory whose receipts to find; defaults to the process's. */
33
+ readonly cwd?: string;
34
+ readonly env?: Record<string, string | undefined>;
35
+ readonly home?: string;
36
+ }
37
+
38
+ /** `<cwd>/.parley/receipts` — the writer's default, under the working directory it was invoked in. */
39
+ export function repoReceiptDir(cwd: string): string {
40
+ return join(resolve(cwd), ".parley", "receipts");
41
+ }
42
+
43
+ /** The state-directory fallback for this working directory's repository (§5). */
44
+ export function stateReceiptDir(opts: LocateOptions = {}): string {
45
+ const cwd = resolve(opts.cwd ?? process.cwd());
46
+ const key = sha256(canonicalPath(repoRoot(cwd))).slice(0, 16);
47
+ return join(stateBase(opts.env ?? process.env, opts.home ?? homedir()), "parley", key, "receipts");
48
+ }
49
+
50
+ /** Both locations the writer could have chosen for this working directory, repo first. Creates nothing. */
51
+ export function receiptLocations(opts: LocateOptions = {}): ReceiptLocation[] {
52
+ const cwd = resolve(opts.cwd ?? process.cwd());
53
+ const dirs: { where: "repo" | "state"; dir: string }[] = [
54
+ { where: "repo", dir: repoReceiptDir(cwd) },
55
+ { where: "state", dir: stateReceiptDir({ ...opts, cwd }) },
56
+ ];
57
+ return dirs.map(({ where, dir }) => ({ where, dir, present: isDirectory(dir) }));
58
+ }
59
+
60
+ export function isDirectory(path: string): boolean {
61
+ try { return statSync(path).isDirectory(); } catch { return false; }
62
+ }
63
+
64
+ export function isFile(path: string): boolean {
65
+ try { return statSync(path).isFile(); } catch { return false; }
66
+ }
67
+
68
+ function canonicalPath(path: string): string {
69
+ try { return realpathSync(path); } catch { return path; }
70
+ }
package/src/open.ts ADDED
@@ -0,0 +1,435 @@
1
+ // The drill-down: full records by `(run, seq)` (spec §9, informative; flyingrobots/parley#51).
2
+ //
3
+ // A digest names records by identity and holds none of them, because §9 keeps a result small and
4
+ // "projecting down is cheap, expanding back up may be impossible within a budget". This is the way
5
+ // back up: a caller hands in the `(run, seq)` pairs a `parley.lens` names and gets each record in
6
+ // full, with an outcome per id.
7
+ //
8
+ // Four rules, and the reasons for them:
9
+ //
10
+ // 1. **A drill-down is a recorded read.** It reads history, so by the reasoning of
11
+ // flyingrobots/parley#48 it states an asker, a view and a window, is refused without them,
12
+ // and is recorded through the writer as a `parley.query` event — the same message, with
13
+ // `records` naming the ids it opens. The store then learns which records were opened as well
14
+ // as which questions were asked. The view and window are recorded and **select nothing**: the
15
+ // ids are opened by identity whatever their `t`, in the order asked.
16
+ // 2. **One outcome per id asked, never a throw.** An id is `opened`, or `sidecar_unavailable`
17
+ // when it is a sidecar or a record stored in one and the stored bytes could not be
18
+ // established, or `run_not_found` / `seq_not_found` when half of it does not resolve. One
19
+ // broken id does not lose the others.
20
+ // 3. **The loader's rulings travel with the record.** Every id whose run resolved carries its
21
+ // bundle's replay ruling, so a record whose bundle is unavailable for replay still opens — the
22
+ // failed run's `error` is usually the record a reader most needs — and says so (§2.3, §5.4).
23
+ // 4. **The deadline is a read's.** `budget.ms` is checked as `queryReceipts` checks it, from
24
+ // the call, after the load and after the ids are opened (flyingrobots/parley#71). A drill-down
25
+ // past it declines with the same `query.over_budget` error and returns no records: opening
26
+ // some ids and not others by the clock would make an id's outcome depend on how busy the
27
+ // machine was, which no caller can act on. `budget.bytes` never declines here, because the
28
+ // answer is not a line: an id past it is that id's `over_budget` outcome instead (flyingrobots/parley#78).
29
+ //
30
+ // A sidecar's contents are checked by the loader, not here: the declared `bytes` and `sha256` are
31
+ // compared with the stored bytes before the record is restored (§5), and this module reports the
32
+ // loader's resolution rather than reading the file a second time.
33
+ import { resolve } from "node:path";
34
+ import { defineTool, main } from "@flyingrobots/parley-emit";
35
+ import type { RecordRef } from "./digest.ts";
36
+ import { loadReceipts, type Bundle, type Load, type LoadedRecord, type Replay, type SidecarResolution } from "./load.ts";
37
+ import { repoReceiptDir, stateReceiptDir } from "./locate.ts";
38
+ import {
39
+ Deadline, MONOTONIC, NO_RETENTION, QUERY_SCHEMA, READER, Tee, declineOnRun, planQuery, queryRecord,
40
+ type AcceptedQuery, type Asker, type BudgetDecline, type QueryOptions, type QueryRefusal, type QueryRequest, type QueryWindow, type View,
41
+ } from "./query.ts";
42
+
43
+ export type OpenRefusalCode = QueryRefusal["code"] | "open.records_missing" | "open.records_invalid";
44
+
45
+ /** Why a drill-down was refused: §6's fields, as a query's refusal carries them. */
46
+ export interface OpenRefusal {
47
+ readonly code: OpenRefusalCode;
48
+ readonly field: QueryRefusal["field"] | "records";
49
+ readonly problem: string;
50
+ readonly remedy: string;
51
+ readonly section: string;
52
+ }
53
+
54
+ export interface OpenRefused {
55
+ readonly refused: true;
56
+ readonly refusals: readonly OpenRefusal[];
57
+ }
58
+
59
+ /**
60
+ * What a caller asks for. The record bound is the ids themselves (`records: n` for `n` ids asked);
61
+ * a caller may state `bytes`, the most the opened records may occupy together
62
+ * (flyingrobots/parley#78), and `ms`, the read's deadline (flyingrobots/parley#71).
63
+ */
64
+ export interface OpenRequest {
65
+ readonly asker?: QueryRequest["asker"];
66
+ readonly view?: string;
67
+ readonly window?: QueryRequest["window"];
68
+ readonly note?: string;
69
+ /** The records to open, by `(run, seq)`, as a `parley.lens` names them. */
70
+ readonly records?: readonly { readonly run?: unknown; readonly seq?: unknown }[];
71
+ /** Optional bounds: `bytes` on the size of what opens (whole records up to it, `over_budget` past it), `ms` on the whole drill-down. */
72
+ readonly budget?: { readonly bytes?: number; readonly ms?: number };
73
+ }
74
+
75
+ export type OpenOutcomeKind = "opened" | "over_budget" | "sidecar_unavailable" | "run_not_found" | "seq_not_found";
76
+
77
+ /** What the loader established about the bundle an id's run resolved to. */
78
+ export interface BundleRuling {
79
+ readonly terminated: boolean;
80
+ readonly status: number | null;
81
+ readonly redacted: boolean;
82
+ readonly replay: Replay;
83
+ }
84
+
85
+ /** One id's outcome. */
86
+ export interface Opened {
87
+ readonly id: RecordRef;
88
+ readonly outcome: OpenOutcomeKind;
89
+ /**
90
+ * The record at that `(run, seq)`, in full, when there is one. For `sidecar_unavailable` this is
91
+ * the `sidecar` pointer and nothing more: the contents it stands for are not claimed.
92
+ */
93
+ readonly record?: LoadedRecord;
94
+ /** When the id names a `sidecar` event whose stored bytes are intact: the record it holds, in full. */
95
+ readonly held?: LoadedRecord;
96
+ /** The sidecar involved, when the id is one or is stored in one. */
97
+ readonly sidecar?: SidecarResolution;
98
+ /**
99
+ * For `over_budget`: the size the record would have occupied, in bytes, as `recordBytes` defines
100
+ * it. No record, and no part of one, is returned beside it.
101
+ */
102
+ readonly bytes?: number;
103
+ /** The bundle's rulings, whenever the id's run resolved. */
104
+ readonly bundle?: BundleRuling;
105
+ /** For any outcome but `opened`: what went wrong, and what a caller can do about it. */
106
+ readonly problem?: string;
107
+ readonly remedy?: string;
108
+ }
109
+
110
+ export interface OpenAnswer {
111
+ readonly refused: false;
112
+ readonly declined: false;
113
+ /** The drill-down's own run, never a run being read. */
114
+ readonly run: string;
115
+ readonly receipt: string;
116
+ /** The recorded `parley.query`, by `(run, seq)`. */
117
+ readonly query: RecordRef;
118
+ readonly asker: Asker;
119
+ readonly view: View;
120
+ readonly window: QueryWindow;
121
+ readonly note?: string;
122
+ /** The budget applied and recorded: `{records: n}` for `n` ids asked, with `bytes` and `ms` when the caller stated them. */
123
+ readonly budget: { readonly records: number; readonly bytes?: number; readonly ms?: number };
124
+ /** The ids asked, in the order asked, exactly as recorded. */
125
+ readonly records: readonly RecordRef[];
126
+ /** One outcome per id asked, in the same order. */
127
+ readonly opened: readonly Opened[];
128
+ readonly counts: {
129
+ readonly asked: number;
130
+ readonly opened: number;
131
+ readonly overBudget: number;
132
+ readonly sidecarUnavailable: number;
133
+ readonly runNotFound: number;
134
+ readonly seqNotFound: number;
135
+ };
136
+ readonly load: Load;
137
+ readonly lines: readonly Record<string, unknown>[];
138
+ readonly status: number;
139
+ }
140
+
141
+ /** A drill-down that ran, was recorded, and passed its deadline. It opened nothing. */
142
+ export interface OpenDeclined {
143
+ readonly refused: false;
144
+ readonly declined: true;
145
+ readonly run: string;
146
+ readonly receipt: string;
147
+ readonly query: RecordRef;
148
+ readonly asker: Asker;
149
+ readonly view: View;
150
+ readonly window: QueryWindow;
151
+ readonly note?: string;
152
+ readonly budget: { readonly records: number; readonly bytes?: number; readonly ms?: number };
153
+ readonly records: readonly RecordRef[];
154
+ readonly decline: BudgetDecline;
155
+ readonly load: Load;
156
+ readonly lines: readonly Record<string, unknown>[];
157
+ readonly status: number;
158
+ }
159
+
160
+ export type OpenOutcome = OpenAnswer | OpenDeclined | OpenRefused;
161
+
162
+ /** The same options a read takes: the loader's, plus the reading program's identity and its sinks. */
163
+ export type OpenOptions = QueryOptions;
164
+
165
+
166
+ const isRef = (r: { readonly run?: unknown; readonly seq?: unknown }): boolean =>
167
+ r !== null && typeof r === "object" && typeof r.run === "string" && r.run.length > 0
168
+ && typeof r.seq === "number" && Number.isInteger(r.seq) && r.seq >= 0;
169
+
170
+ export type OpenPlan = { readonly refused: false; readonly query: AcceptedQuery; readonly records: readonly RecordRef[] } | OpenRefused;
171
+
172
+ /**
173
+ * The refusal rules for a drill-down, as a pure function: a query's rules for the asker, the view,
174
+ * the window and the note, and two of its own for the ids.
175
+ */
176
+ export function planOpen(request: OpenRequest): OpenPlan {
177
+ const ids = request.records;
178
+ // The record bound is the ids: one record per id asked, stated rather than defaulted. A byte
179
+ // bound is the caller's, and is validated by the query's own rule for a budget.
180
+ const n = Array.isArray(ids) && ids.length > 0 ? ids.length : 1;
181
+ const bytes = request.budget?.bytes;
182
+ const ms = request.budget?.ms;
183
+ const plan = planQuery({
184
+ ...(request.asker === undefined ? {} : { asker: request.asker }),
185
+ ...(request.view === undefined ? {} : { view: request.view }),
186
+ ...(request.window === undefined ? {} : { window: request.window }),
187
+ ...(request.note === undefined ? {} : { note: request.note }),
188
+ budget: { records: n, ...(bytes === undefined ? {} : { bytes }), ...(ms === undefined ? {} : { ms }) },
189
+ });
190
+ const refusals: OpenRefusal[] = plan.refused ? [...plan.refusals] : [];
191
+ if (!Array.isArray(ids) || ids.length === 0) {
192
+ refusals.push({
193
+ code: "open.records_missing", field: "records",
194
+ problem: "the drill-down names no records to open",
195
+ remedy: "name at least one record by (run, seq), as a parley.lens names them in its records",
196
+ section: "§9",
197
+ });
198
+ } else if (!ids.every(isRef)) {
199
+ refusals.push({
200
+ code: "open.records_invalid", field: "records",
201
+ problem: "a record is not named by a non-empty run and a non-negative integer seq",
202
+ remedy: "name each record as {run, seq}, exactly as a parley.lens carries it",
203
+ section: "§1.3",
204
+ });
205
+ }
206
+ if (refusals.length > 0 || plan.refused || !Array.isArray(ids)) return { refused: true, refusals };
207
+ return { refused: false, query: plan.query, records: ids.map((r) => ({ run: r.run as string, seq: r.seq as number })) };
208
+ }
209
+
210
+ /** UTF-8 bytes of a record's JSON as the drill-down returns it, envelope fields and all. */
211
+ export function recordBytes(r: LoadedRecord | undefined): number {
212
+ return r === undefined ? 0 : Buffer.byteLength(JSON.stringify(r), "utf8");
213
+ }
214
+
215
+ /**
216
+ * What an outcome occupies against a byte bound: the `record` and the `held` record it carries,
217
+ * each by `recordBytes`. A record stored in a sidecar is sized by its contents, which the loader
218
+ * has already restored into it; the pointer opened by its own `seq` carries both. An outcome that
219
+ * returns no contents (`sidecar_unavailable`, the not-found pair) costs nothing.
220
+ */
221
+ export function openedBytes(o: Opened): number {
222
+ return o.outcome === "opened" ? recordBytes(o.record) + recordBytes(o.held) : 0;
223
+ }
224
+
225
+ /**
226
+ * Apply a byte bound to outcomes in the order asked. Each id is judged against what remains, so a
227
+ * small record after an over-budget one may still fit and nothing is skipped silently; the bound is
228
+ * inclusive. An over-budget id keeps its bundle's ruling, names its size and holds no contents.
229
+ */
230
+ export function applyBudget(outcomes: readonly Opened[], bytes: number | undefined): Opened[] {
231
+ if (bytes === undefined) return [...outcomes];
232
+ let used = 0;
233
+ return outcomes.map((o) => {
234
+ const cost = openedBytes(o);
235
+ if (cost === 0 || used + cost <= bytes) { used += cost; return o; }
236
+ return {
237
+ id: o.id, outcome: "over_budget" as const, bytes: cost,
238
+ ...(o.bundle === undefined ? {} : { bundle: o.bundle }),
239
+ problem: `the record occupies ${cost} bytes and ${bytes - used} of the ${bytes}-byte budget remain, so it is not returned: a record is whole or absent`,
240
+ remedy: "ask for it again alone or under a larger budget.bytes; an id past the bound is not lost, and later ids that fit were still opened",
241
+ };
242
+ });
243
+ }
244
+
245
+ function ruling(bundle: Bundle): BundleRuling {
246
+ return { terminated: bundle.terminated, status: bundle.status, redacted: bundle.redacted, replay: bundle.replay };
247
+ }
248
+
249
+ function sidecarProblem(s: SidecarResolution): string {
250
+ return s.state === "unchecked"
251
+ ? `the sidecar at ${s.path} was not resolved, so its contents are not established either way`
252
+ : `the sidecar at ${s.path} holding seq ${s.source} is ${s.state.replace("_", " ")}, so the record it stands for cannot be opened`;
253
+ }
254
+
255
+ /** Resolve one id against the load. Pure over the load: it reads nothing further. */
256
+ export function openOne(id: RecordRef, bundles: ReadonlyMap<string, Bundle>): Opened {
257
+ const bundle = bundles.get(id.run);
258
+ if (!bundle) {
259
+ return {
260
+ id, outcome: "run_not_found",
261
+ problem: `no receipt in either location holds run ${id.run}`,
262
+ remedy: "check the working directory the read was made against: receipts are found under the initial working directory of the run that wrote them (§5)",
263
+ };
264
+ }
265
+ const bundleRuling = ruling(bundle);
266
+ const record = bundle.records.find((r) => r.seq === id.seq);
267
+ // A sidecar involved in this id: the id is the `sidecar` event, or the record it holds.
268
+ const sidecar = bundle.sidecars.find((s) => s.seq === id.seq) ?? bundle.sidecars.find((s) => s.source === id.seq);
269
+ if (sidecar && sidecar.state !== "intact") {
270
+ // The pointer is what there is; the contents are not claimed. When the id was the record the
271
+ // sidecar holds, the pointer is its stand-in (§5), so it is the record returned.
272
+ const pointer = bundle.records.find((r) => r.seq === sidecar.seq);
273
+ return {
274
+ id, outcome: "sidecar_unavailable",
275
+ ...(pointer === undefined ? {} : { record: pointer }),
276
+ sidecar, bundle: bundleRuling,
277
+ problem: sidecarProblem(sidecar),
278
+ remedy: sidecar.state === "unchecked"
279
+ ? "open it again with sidecar resolution on"
280
+ : "the receipt and its sidecars are one bundle (§5): restore the bundle from wherever it was copied whole",
281
+ };
282
+ }
283
+ if (!record) {
284
+ return {
285
+ id, outcome: "seq_not_found", bundle: bundleRuling,
286
+ problem: `run ${id.run} holds no record at seq ${id.seq}`,
287
+ remedy: "name a seq the run's receipt holds; a quarantined line has no seq and cannot be opened (§1.4)",
288
+ };
289
+ }
290
+ if (sidecar && sidecar.seq === id.seq) {
291
+ const held = bundle.records.find((r) => r.seq === sidecar.source);
292
+ return { id, outcome: "opened", record, ...(held === undefined ? {} : { held }), sidecar, bundle: bundleRuling };
293
+ }
294
+ return { id, outcome: "opened", record, ...(sidecar === undefined ? {} : { sidecar }), bundle: bundleRuling };
295
+ }
296
+
297
+ /**
298
+ * Open records by identity: refuse, or record the drill-down and answer it with one outcome per id.
299
+ *
300
+ * A refused drill-down writes nothing. An accepted one is a run of its own, like a query: its
301
+ * `parley.query` record names the ids, a `receipt.step` states what it found, and its own records
302
+ * are never in its answer.
303
+ */
304
+ export async function openRecords(request: OpenRequest, opts: OpenOptions = {}): Promise<OpenOutcome> {
305
+ const clock = opts.clock ?? MONOTONIC;
306
+ const started = clock();
307
+ const cwd = resolve(opts.cwd ?? process.cwd());
308
+ const plan = planOpen({ ...request, asker: { ...request.asker, cwd: request.asker?.cwd ?? cwd } });
309
+ if (plan.refused) return plan;
310
+ const { query, records: ids } = plan;
311
+ const deadline = new Deadline(query.budget.ms, clock, started);
312
+ const budget = { records: ids.length, ...(query.budget.bytes === undefined ? {} : { bytes: query.budget.bytes }), ...(query.budget.ms === undefined ? {} : { ms: query.budget.ms }) };
313
+
314
+ const env = opts.env ?? process.env;
315
+ const stdout = new Tee(opts.stdout);
316
+ const stderr = new Tee(opts.stderr);
317
+ const identity = opts.tool ?? READER;
318
+
319
+ const spec = defineTool({
320
+ name: identity.name,
321
+ version: identity.version,
322
+ commands: {
323
+ open: {
324
+ intent: "Open records by (run, seq) from this working directory's receipt bundles, and record the drill-down",
325
+ effects: {
326
+ reads: [`${repoReceiptDir(cwd)}/*`, `${stateReceiptDir({ ...opts, cwd })}/*`],
327
+ writes: [],
328
+ network: false,
329
+ idempotent: true,
330
+ },
331
+ secrets: [],
332
+ emits: [{ ...QUERY_SCHEMA }],
333
+ },
334
+ },
335
+ retention: { count: NO_RETENTION },
336
+ });
337
+
338
+ let answer: Omit<OpenAnswer, "status" | "lines"> | Omit<OpenDeclined, "status" | "lines"> | undefined;
339
+ const status = await main(spec, [spec.name, "open"], (run) => {
340
+ const seq = run.result({ ...queryRecord(query), records: ids }, QUERY_SCHEMA);
341
+ run.step(
342
+ `recorded the drill-down into ${ids.length} record(s) before opening them`,
343
+ "spec §9: reading history is an act, so opening records is recorded like any other read, and the next reader can see which records were opened (flyingrobots/parley#51)",
344
+ { view: query.view, window: query.window, asked: ids.length },
345
+ );
346
+
347
+ const load = loadReceipts({ cwd, env, ...(opts.home === undefined ? {} : { home: opts.home }), ...(opts.sidecars === undefined ? {} : { sidecars: opts.sidecars }), ...(opts.validate === undefined ? {} : { validate: opts.validate }), ...(opts.history === undefined ? {} : { history: opts.history }) });
348
+ // A read does not answer itself: its own bundle is not among those an id can resolve to.
349
+ const recorded = {
350
+ refused: false as const, declined: true as const,
351
+ run: run.id, receipt: run.receiptPath, query: { run: run.id, seq },
352
+ asker: query.asker, view: query.view, window: query.window,
353
+ ...(query.note === undefined ? {} : { note: query.note }),
354
+ budget, records: ids, load,
355
+ };
356
+ const afterLoad = deadline.check();
357
+ if (afterLoad.passed) {
358
+ answer = { ...recorded, decline: declineOnRun(run, budget, "load", false, { elapsed: afterLoad.elapsed }) };
359
+ return;
360
+ }
361
+ const bundles = new Map(load.bundles.filter((b) => b.run !== run.id).map((b) => [b.run, b]));
362
+ const opened = applyBudget(ids.map((id) => openOne(id, bundles)), query.budget.bytes);
363
+ const afterOpen = deadline.check();
364
+ if (afterOpen.passed) {
365
+ answer = { ...recorded, decline: declineOnRun(run, budget, "open", true, { elapsed: afterOpen.elapsed }) };
366
+ return;
367
+ }
368
+ const count = (k: OpenOutcomeKind) => opened.filter((o) => o.outcome === k).length;
369
+ const counts = {
370
+ asked: ids.length,
371
+ opened: count("opened"),
372
+ overBudget: count("over_budget"),
373
+ sidecarUnavailable: count("sidecar_unavailable"),
374
+ runNotFound: count("run_not_found"),
375
+ seqNotFound: count("seq_not_found"),
376
+ };
377
+
378
+ run.step(
379
+ `opened ${counts.opened} of ${counts.asked} record(s)`,
380
+ "an id that does not resolve, or whose sidecar cannot be established, is that id's outcome rather than a failure of the read: one broken id must not lose the others",
381
+ {
382
+ asked: counts.asked, opened: counts.opened, over_budget: counts.overBudget, sidecar_unavailable: counts.sidecarUnavailable,
383
+ run_not_found: counts.runNotFound, seq_not_found: counts.seqNotFound,
384
+ replay_unavailable: opened.filter((o) => o.bundle?.replay.unavailable === true).length,
385
+ },
386
+ );
387
+
388
+ answer = {
389
+ refused: false,
390
+ declined: false,
391
+ run: run.id,
392
+ receipt: run.receiptPath,
393
+ query: { run: run.id, seq },
394
+ asker: query.asker,
395
+ view: query.view,
396
+ window: query.window,
397
+ ...(query.note === undefined ? {} : { note: query.note }),
398
+ budget,
399
+ records: ids,
400
+ opened,
401
+ counts,
402
+ load,
403
+ };
404
+ }, {
405
+ cwd,
406
+ env,
407
+ ...(opts.home === undefined ? {} : { home: opts.home }),
408
+ ...(opts.session === undefined ? {} : { session: opts.session }),
409
+ ...(opts.now === undefined ? {} : { now: opts.now }),
410
+ stdout,
411
+ stderr,
412
+ // What enters `inv` is the question (§2.2): the ids, the view and the window, with the asker's
413
+ // tool and task. `asker.cwd` moves with the process, so it is left out, as a query leaves it.
414
+ resolved: () => ({
415
+ command: "open",
416
+ records: ids,
417
+ view: query.view,
418
+ window: query.window,
419
+ ...(query.budget.bytes === undefined && query.budget.ms === undefined ? {} : {
420
+ budget: {
421
+ ...(query.budget.bytes === undefined ? {} : { bytes: query.budget.bytes }),
422
+ ...(query.budget.ms === undefined ? {} : { ms: query.budget.ms }),
423
+ },
424
+ }),
425
+ asker: { tool: query.asker.tool, ...(query.asker.task === undefined ? {} : { task: query.asker.task }) },
426
+ }),
427
+ });
428
+
429
+ const lines = stdout.lines
430
+ .map((l) => { try { return JSON.parse(l) as Record<string, unknown>; } catch { return null; } })
431
+ .filter((l): l is Record<string, unknown> => l !== null);
432
+
433
+ if (!answer) throw new Error(`the drill-down did not complete: status ${status}; see the receipt it recorded`);
434
+ return { ...answer, lines, status };
435
+ }