@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/query.ts ADDED
@@ -0,0 +1,760 @@
1
+ // A read against the history, recorded as a run of its own (spec §9, informative).
2
+ //
3
+ // §9 asks a query for an observer and a purpose. What those are as data was decided in
4
+ // flyingrobots/parley#46 and is written up in `docs/topics/reader/README.md`: a read states an
5
+ // **asker** (who it is for), a **view** (the shape of the answer it wants) and a **budget** (the
6
+ // size of answer it will accept), over an explicit **window**. Three rules follow from that
7
+ // decision and are the whole of this module:
8
+ //
9
+ // 1. `asker.tool` and `view` are never inferred. §2.1 forbids inventing an identity, and there
10
+ // is no privileged view to fall back on, so a read that cannot state either is **refused**
11
+ // with a structured error rather than answered under a guess.
12
+ // 2. An accepted read is **recorded**: the `parley.query` event is emitted through the writer,
13
+ // so the read is a run with a receipt like any other parley program and the next reader can
14
+ // see what was asked. A refused read is not a run and records nothing: §9 records a question
15
+ // that was asked, and there is nothing to attribute a question nobody could state to.
16
+ // 3. The **window** is explicit and echoed in the answer. Two timestamps, inclusive at both
17
+ // ends, because a defaulted window is a different question answered as if it were yours.
18
+ //
19
+ // What this module does **not** do, and must not be read as doing:
20
+ //
21
+ // - **It does not filter by the view.** The view *orders* the answer — §9's purpose is the
22
+ // ranking function, not a filter applied afterwards — and the answer is still every record in
23
+ // the window. The rules are in `rank.ts`; the over-filtering §9 warns about is impossible
24
+ // here because nothing is dropped at any tier.
25
+ // - **It does not fetch what the digest left out.** The digest below bounds the answer to the
26
+ // budget and names what it dropped as a count, and names nothing else: the way to those
27
+ // records is a wider read. Opening the records a digest *does* name, by identity, is
28
+ // `openRecords` in `open.ts` (flyingrobots/parley#51).
29
+ //
30
+ // What it **does** do with the budget is the digest (flyingrobots/parley#50): the first response
31
+ // is a `parley.lens` record, bounded by `budget.records` and by `budget.bytes` when the query
32
+ // states one, carrying the asker, the view, the window and the budget applied, and reporting the
33
+ // records the ranking placed beyond the bound as a count — zero included, never absent. `digest.ts`
34
+ // holds the bound and `docs/topics/parley-read/README.md` states it.
35
+ //
36
+ // And it **declines** a read that cannot be answered within its budget (flyingrobots/parley#71).
37
+ // `budget.ms` is a deadline for the whole read, measured on the read's own clock from the call and
38
+ // checked between phases: after the load, after the ranking, and before the digest is written. A
39
+ // read past it at a check stops there. No read answers from a partial load, because a digest drawn
40
+ // from part of the history would carry an excluded count of records it never saw. A `bytes` budget
41
+ // too small even for a digest naming no records cannot be met either. In both cases the read is
42
+ // still a recorded run — the `parley.query` is already in its receipt — and it ends with one
43
+ // `parley.error`, code `query.over_budget`, stating the budget given, what was measured, and the
44
+ // budget that would have sufficed where that is known, then closes with status 2. A decline is not
45
+ // a refusal: a refusal is pure and pre-load, about a question nobody could state; a decline is a
46
+ // verdict about real history, and only a read that ran can give one.
47
+ import { resolve } from "node:path";
48
+ import { defineTool, main, type Run, type Sink } from "@flyingrobots/parley-emit";
49
+ import { LENS_SCHEMA, digestFor, sufficientBytes, type Digest } from "./digest.ts";
50
+ import { loadReceipts, type Load, type LoadOptions, type LoadedRecord } from "./load.ts";
51
+ import { repoReceiptDir, stateReceiptDir } from "./locate.ts";
52
+ import { rankRecords, type Ranking } from "./rank.ts";
53
+
54
+ /** The `parley.query` pair this reader emits; a change to the message moves this version. */
55
+ export const QUERY_SCHEMA = { id: "parley.query", version: "1.0.0" } as const;
56
+
57
+ /** The closed view vocabulary (flyingrobots/parley#46). Adding a token moves the two schema versions. */
58
+ export const VIEWS = ["what-ran", "what-failed", "what-changed", "how-it-decided", "everything"] as const;
59
+ export type View = (typeof VIEWS)[number];
60
+
61
+ /** The one documented default: a read that states no budget will accept twenty records. */
62
+ export const DEFAULT_BUDGET: Budget = { records: 20 };
63
+
64
+ /**
65
+ * The retention policy a read states (§5.1). A reader must never expire the history it reads, and
66
+ * the writer asks every tool for a count, so the count a read states is one no directory reaches.
67
+ */
68
+ export const NO_RETENTION = Number.MAX_SAFE_INTEGER;
69
+
70
+ export interface Asker {
71
+ /** The calling program, named as in §2.1. Never invented: a read that cannot name it is refused. */
72
+ readonly tool: string;
73
+ /** Absolute POSIX working directory the read was made from. */
74
+ readonly cwd?: string;
75
+ /** The caller's current task id. Not the session: a session is a working period, a task a unit of work in one. */
76
+ readonly task?: string;
77
+ }
78
+
79
+ export interface Budget {
80
+ readonly records: number;
81
+ readonly bytes?: number;
82
+ readonly ms?: number;
83
+ }
84
+
85
+ /** The stretch of history a read covers: POSIX milliseconds, inclusive at both ends. */
86
+ export interface QueryWindow {
87
+ readonly from: number;
88
+ readonly to: number;
89
+ }
90
+
91
+ /** What a caller asks for. Every field is optional here so that a missing one can be refused rather than rejected by a type. */
92
+ export interface QueryRequest {
93
+ readonly asker?: { readonly tool?: string; readonly cwd?: string; readonly task?: string };
94
+ readonly view?: string;
95
+ readonly budget?: { readonly records?: number; readonly bytes?: number; readonly ms?: number };
96
+ readonly window?: { readonly from?: number; readonly to?: number };
97
+ /** Free text, recorded and never parsed. Nothing in the answer branches on it. */
98
+ readonly note?: string;
99
+ }
100
+
101
+ export type QueryRefusalCode =
102
+ | "query.asker_unnamed"
103
+ | "query.asker_invalid"
104
+ | "query.view_missing"
105
+ | "query.view_unknown"
106
+ | "query.window_missing"
107
+ | "query.window_invalid"
108
+ | "query.window_inverted"
109
+ | "query.budget_invalid"
110
+ | "query.note_empty";
111
+
112
+ /**
113
+ * Why a read was refused. The field names are §6's: a caller that is itself a parley tool can hand
114
+ * one straight to `run.error`, and `code` satisfies §6's two-or-more-lowercase-segments rule.
115
+ */
116
+ export interface QueryRefusal {
117
+ readonly code: QueryRefusalCode;
118
+ readonly field: "asker" | "view" | "budget" | "window" | "note";
119
+ readonly problem: string;
120
+ readonly remedy: string;
121
+ /** What the refusal is measured against. */
122
+ readonly section: string;
123
+ }
124
+
125
+ /** A read that stated everything it had to. This is what gets recorded. */
126
+ export interface AcceptedQuery {
127
+ readonly asker: Asker;
128
+ readonly view: View;
129
+ readonly budget: Budget;
130
+ readonly window: QueryWindow;
131
+ readonly note?: string;
132
+ /** True when the budget is `DEFAULT_BUDGET` because the caller stated none (§9: a default is never invisible). */
133
+ readonly budgetDefaulted: boolean;
134
+ }
135
+
136
+ export interface QueryRefused {
137
+ readonly refused: true;
138
+ readonly refusals: readonly QueryRefusal[];
139
+ }
140
+
141
+ export type QueryPlan = { readonly refused: false; readonly query: AcceptedQuery } | QueryRefused;
142
+
143
+ export interface QueryAnswer {
144
+ readonly refused: false;
145
+ readonly declined: false;
146
+ /** The read's own run (§2.1): the run the query record belongs to, never a run being read. */
147
+ readonly run: string;
148
+ /** The receipt the read wrote, which is where the recorded query lives. */
149
+ readonly receipt: string;
150
+ /** The recorded query, by `(run, seq)`: what a `parley.lens` will name once there is one. */
151
+ readonly query: { readonly run: string; readonly seq: number };
152
+ readonly asker: Asker;
153
+ readonly view: View;
154
+ readonly budget: Budget;
155
+ readonly budgetDefaulted: boolean;
156
+ /** Echoed verbatim from the query, inclusive at both ends. */
157
+ readonly window: QueryWindow;
158
+ readonly note?: string;
159
+ /**
160
+ * The records the digest names, in full: the window ordered by the view — the failure surface
161
+ * of the runs that failed first when the view implies a change, then the view's own surface, then `(t, run, seq)`
162
+ * ascending — and cut at the budget. Never more than `budget.records` of them, and fewer when a
163
+ * stated `budget.bytes` cuts first. The records of a run folded into another of the same
164
+ * invocation and result are not among them (flyingrobots/parley#79). What the fold and the bound
165
+ * left out is `counts.excluded`, the fold's share `counts.folded`; it is named nowhere, so
166
+ * reaching it is a wider or narrower read, not a drill-down.
167
+ */
168
+ readonly records: readonly LoadedRecord[];
169
+ /** The digest this read answered with, exactly as the `parley.lens` record carries it. */
170
+ readonly digest: Digest;
171
+ /** The digest's line in UTF-8 bytes, its newline included, as the read wrote it. */
172
+ readonly digestBytes: number;
173
+ /**
174
+ * The ranking the digest was cut from: `records` and `ranked` hold what the digest names, in
175
+ * rank order, while `outcomes` and `counts` describe the **whole window** the digest was drawn
176
+ * from. The two are deliberately not the same population: a run's outcome is established from
177
+ * the window (§1.2a), so recomputing it from a bounded prefix would turn a run whose `end` the
178
+ * bound cut into an undetermined one, and a tier census of the window is what tells a caller
179
+ * the digest is not the whole of it.
180
+ */
181
+ readonly ranking: Ranking;
182
+ readonly counts: {
183
+ /** Records the load returned, the read's own run included. */
184
+ readonly scanned: number;
185
+ /** Records in the window, the digest's bound disregarded: the population the digest was drawn from. */
186
+ readonly inWindow: number;
187
+ /** Records the digest names. */
188
+ readonly answered: number;
189
+ /** Records of the window the digest does not name, the folded ones included. Zero is a count, not an absence (§9). */
190
+ readonly excluded: number;
191
+ /** How many of `excluded` were left out because their run was folded into another (flyingrobots/parley#79), not by the bound. */
192
+ readonly folded: number;
193
+ /** Records whose `t` is not a number, which cannot be placed in a window and are therefore not in the answer. */
194
+ readonly undated: number;
195
+ /** The read's own records, which a read does not answer itself with. */
196
+ readonly own: number;
197
+ };
198
+ /** The whole load behind the answer, so a caller sees the defects and quarantines too. */
199
+ readonly load: Load;
200
+ /** The protocol lines the read wrote to its own stdout, parsed. */
201
+ readonly lines: readonly Record<string, unknown>[];
202
+ /** The read's exit status (§3.4). */
203
+ readonly status: number;
204
+ }
205
+
206
+ /** The phase a deadline check follows. `open` is the drill-down's, after the ids are resolved. */
207
+ export type BudgetPhase = "load" | "rank" | "digest" | "open";
208
+
209
+ /** The one code a read declines with. Its `measured` and `limit` are the bound that declined. */
210
+ export const OVER_BUDGET = "query.over_budget" as const;
211
+
212
+ /**
213
+ * Why a read that ran could not answer within its budget, as the `parley.error` it reported states
214
+ * it (the error's `detail` carries `bound`, `phase`, `given`, `measured`, `sufficient` and
215
+ * `at_least` in snake case).
216
+ *
217
+ * - `bound` is the bound that declined: `ms` when the deadline passed, else `bytes`.
218
+ * - `measured` holds what was measured against each bound that could not be met: the elapsed
219
+ * milliseconds, rounded up, and the size of the smallest digest in bytes.
220
+ * - `sufficient` holds a budget that would have been enough for this read over this history: the
221
+ * elapsed time when the check that failed was the last one (nothing but writing was left, so this
222
+ * read would have passed every check under it; a re-read takes its own time), and the smallest
223
+ * digest's size, which is exact.
224
+ * - `atLeast` holds a budget known to be needed but not known to be enough: the elapsed time when
225
+ * the read stopped with phases still to run, which would have cost more.
226
+ */
227
+ export interface BudgetDecline {
228
+ readonly code: typeof OVER_BUDGET;
229
+ readonly bound: "ms" | "bytes";
230
+ readonly phase: BudgetPhase;
231
+ readonly problem: string;
232
+ readonly remedy: string;
233
+ /** The budget the read was given, exactly as it was recorded. */
234
+ readonly given: Budget;
235
+ readonly measured: { readonly ms?: number; readonly bytes?: number };
236
+ readonly sufficient: { readonly ms?: number; readonly bytes?: number };
237
+ readonly atLeast: { readonly ms?: number };
238
+ }
239
+
240
+ /** A read that ran, was recorded, and declined on budget grounds. It wrote no digest. */
241
+ export interface QueryDeclined {
242
+ readonly refused: false;
243
+ readonly declined: true;
244
+ readonly run: string;
245
+ readonly receipt: string;
246
+ readonly query: { readonly run: string; readonly seq: number };
247
+ readonly asker: Asker;
248
+ readonly view: View;
249
+ readonly budget: Budget;
250
+ readonly budgetDefaulted: boolean;
251
+ readonly window: QueryWindow;
252
+ readonly note?: string;
253
+ readonly decline: BudgetDecline;
254
+ /** The load the read made before it declined; a read always loads whole or not at all. */
255
+ readonly load: Load;
256
+ readonly lines: readonly Record<string, unknown>[];
257
+ /** 2: the run reported a structured error (§3.4). */
258
+ readonly status: number;
259
+ }
260
+
261
+ export type QueryOutcome = QueryAnswer | QueryDeclined | QueryRefused;
262
+
263
+ /**
264
+ * A read's deadline, on the read's own clock, from the reading taken when the read was called; `check`
265
+ * measures the elapsed time at a phase boundary and reports whether `budget.ms` has passed. The
266
+ * deadline is inclusive: elapsed time equal to `ms` is within it. With no `ms`, nothing passes.
267
+ */
268
+ export class Deadline {
269
+ /** `start` is a reading of `clock` already taken, so a caller can start the deadline before it knows `ms`. */
270
+ constructor(readonly ms: number | undefined, private readonly clock: () => number, private readonly start: number = clock()) {}
271
+ check(): { readonly elapsed: number; readonly passed: boolean } {
272
+ const raw = this.clock() - this.start;
273
+ // Reported in whole milliseconds, rounded up, so the figure stated is never less than the time
274
+ // spent and is a valid `budget.ms` (a positive integer) to hand back.
275
+ const elapsed = Math.max(1, Math.ceil(raw));
276
+ return { elapsed, passed: this.ms !== undefined && raw > this.ms };
277
+ }
278
+ }
279
+
280
+ /** The default clock: monotonic, so a wall-clock adjustment mid-read moves no deadline. */
281
+ export const MONOTONIC = (): number => performance.now();
282
+
283
+ const AFTER: Record<BudgetPhase, string> = {
284
+ load: "the load",
285
+ rank: "the ranking",
286
+ digest: "the ranking, before the digest was written",
287
+ open: "the ids were opened",
288
+ };
289
+
290
+ /**
291
+ * Build the decline for a deadline that passed and/or a byte bound that could not be met, report it
292
+ * on the run as a step and a `query.over_budget` error, and return it. `last` is whether the check
293
+ * was the read's last, which is what makes the elapsed time sufficient rather than a lower bound.
294
+ */
295
+ export function declineOnRun(
296
+ run: Run,
297
+ budget: Budget,
298
+ phase: BudgetPhase,
299
+ last: boolean,
300
+ over: { readonly elapsed?: number; readonly bytes?: number },
301
+ ): BudgetDecline {
302
+ const bound: "ms" | "bytes" = over.elapsed !== undefined ? "ms" : "bytes";
303
+ const measured = { ...(over.elapsed === undefined ? {} : { ms: over.elapsed }), ...(over.bytes === undefined ? {} : { bytes: over.bytes }) };
304
+ const sufficient = {
305
+ ...(over.elapsed !== undefined && last ? { ms: over.elapsed } : {}),
306
+ ...(over.bytes === undefined ? {} : { bytes: over.bytes }),
307
+ };
308
+ const atLeast = over.elapsed !== undefined && !last ? { ms: over.elapsed } : {};
309
+ const problems: string[] = [];
310
+ const remedies: string[] = [];
311
+ if (over.elapsed !== undefined) {
312
+ problems.push(`the read passed its ${budget.ms} ms deadline: ${over.elapsed} ms had elapsed by the end of ${AFTER[phase]}`);
313
+ remedies.push(last
314
+ ? `state budget.ms of ${over.elapsed} or more: by then everything but writing the answer was done`
315
+ : `state budget.ms above ${over.elapsed}: the read stopped with work still to do, so it needs more than that; the load reads every receipt in both locations whatever the window, so a narrower window does not shorten it`);
316
+ }
317
+ if (over.bytes !== undefined) {
318
+ problems.push(`budget.bytes of ${budget.bytes} cannot hold even a digest naming no records, whose line is ${over.bytes} bytes`);
319
+ remedies.push(`state budget.bytes of ${over.bytes} or more for a digest naming no records; each record it names adds its entry, and its run's section the first time that run is named`);
320
+ }
321
+ const problem = problems.join("; and ");
322
+ const remedy = remedies.join("; and ");
323
+ run.step(
324
+ `declined the read: ${problem}`,
325
+ "flyingrobots/parley#71: a read that cannot answer within its budget says so and names the budget that would; it never answers from a partial load and never writes a line over a stated bound",
326
+ { bound, phase, given: budget, measured, sufficient, at_least: atLeast },
327
+ );
328
+ run.error({
329
+ code: OVER_BUDGET,
330
+ problem,
331
+ measured: bound === "ms" ? over.elapsed! : over.bytes!,
332
+ limit: bound === "ms" ? budget.ms! : budget.bytes!,
333
+ remedy,
334
+ retryable: true,
335
+ detail: { bound, phase, given: budget, measured, sufficient, at_least: atLeast },
336
+ });
337
+ return { code: OVER_BUDGET, bound, phase, problem, remedy, given: budget, measured, sufficient, atLeast };
338
+ }
339
+
340
+ export interface QueryOptions extends LoadOptions {
341
+ /**
342
+ * The reading program's own identity, for the run the read records under. The default is this
343
+ * package; a host program that embeds the reader names itself here, and nothing is invented
344
+ * either way (§2.1). This is not the asker: the asker is who the read is *for*.
345
+ */
346
+ readonly tool?: { readonly name: string; readonly version: string };
347
+ /** Where the read's own protocol lines go. The default keeps them in the answer's `lines` and off the host's streams. */
348
+ readonly stdout?: Sink;
349
+ readonly stderr?: Sink;
350
+ /** Carried as `session` on the read's lines; never invented (§2.1). */
351
+ readonly session?: string;
352
+ /** The writer's clock, which stamps `t` on every line the read writes. */
353
+ readonly now?: () => number;
354
+ /**
355
+ * The clock `budget.ms` is measured on, in milliseconds; only differences between its readings
356
+ * matter. The default is monotonic (`performance.now`). It is read once when the read is called
357
+ * and once at each check, so a test can script it and no case has to sleep.
358
+ */
359
+ readonly clock?: () => number;
360
+ }
361
+
362
+ /** The reading program's default identity; the drill-down (`open.ts`) records under the same one. */
363
+ export const READER = { name: "parley-read", version: "0.1.0" } as const;
364
+
365
+ /** Collects the read's own lines and forwards them to a caller's sink when there is one. */
366
+ export class Tee implements Sink {
367
+ readonly lines: string[] = [];
368
+ constructor(private readonly to?: Sink) {}
369
+ write(line: string): void {
370
+ this.lines.push(line);
371
+ this.to?.write(line);
372
+ }
373
+ }
374
+
375
+ function refusal(code: QueryRefusalCode, field: QueryRefusal["field"], problem: string, remedy: string, section: string): QueryRefusal {
376
+ return { code, field, problem, remedy, section };
377
+ }
378
+
379
+ function positiveInteger(n: unknown): boolean {
380
+ return typeof n === "number" && Number.isInteger(n) && n >= 1;
381
+ }
382
+
383
+ /**
384
+ * Check a request and fill the one field that has a default. Pure: it reads nothing, writes
385
+ * nothing and records nothing, so a caller can ask whether a read would be accepted before making
386
+ * it.
387
+ */
388
+ export function planQuery(request: QueryRequest): QueryPlan {
389
+ const refusals: QueryRefusal[] = [];
390
+ const tool = request.asker?.tool;
391
+ if (typeof tool !== "string" || tool.length === 0) {
392
+ refusals.push(refusal(
393
+ "query.asker_unnamed", "asker",
394
+ "the read names no asker: asker.tool is absent or empty",
395
+ "name the calling program in asker.tool; it is one argument and it is never inferred, because §2.1 forbids inventing an identity",
396
+ "§2.1, §9",
397
+ ));
398
+ }
399
+ if (request.view === undefined) {
400
+ refusals.push(refusal(
401
+ "query.view_missing", "view",
402
+ "the read states no view, and there is no privileged view to fall back on",
403
+ `state one of: ${VIEWS.join(", ")}; a guessed view is a different answer to a different question, and the caller cannot see it`,
404
+ "§9",
405
+ ));
406
+ } else if (!(VIEWS as readonly string[]).includes(request.view)) {
407
+ refusals.push(refusal(
408
+ "query.view_unknown", "view",
409
+ `${JSON.stringify(request.view)} is not a view: the vocabulary is closed`,
410
+ `state one of: ${VIEWS.join(", ")}; extending the vocabulary moves the parley.query and parley.lens schema versions`,
411
+ "§9",
412
+ ));
413
+ }
414
+
415
+ const window = request.window;
416
+ if (window === undefined || window.from === undefined || window.to === undefined) {
417
+ refusals.push(refusal(
418
+ "query.window_missing", "window",
419
+ "the read states no window, or only one of its two bounds",
420
+ "state window.from and window.to as POSIX milliseconds, inclusive at both ends; 0 means the start of the history",
421
+ "§9",
422
+ ));
423
+ } else if (!Number.isInteger(window.from) || !Number.isInteger(window.to) || window.from < 0 || window.to < 0) {
424
+ refusals.push(refusal(
425
+ "query.window_invalid", "window",
426
+ "a window bound is not a non-negative integer number of POSIX milliseconds",
427
+ "state window.from and window.to as integers at or above 0",
428
+ "§1.3, §9",
429
+ ));
430
+ } else if (window.to < window.from) {
431
+ refusals.push(refusal(
432
+ "query.window_inverted", "window",
433
+ `the window ends before it begins: to ${window.to} is below from ${window.from}`,
434
+ "state a window whose to is at or after its from; a window that covers nothing is not a window",
435
+ "§9",
436
+ ));
437
+ }
438
+
439
+ let budget: Budget | undefined;
440
+ let budgetDefaulted = false;
441
+ if (request.budget === undefined) {
442
+ budget = DEFAULT_BUDGET;
443
+ budgetDefaulted = true;
444
+ } else {
445
+ const b = request.budget;
446
+ const bad = !positiveInteger(b.records)
447
+ || (b.bytes !== undefined && !positiveInteger(b.bytes))
448
+ || (b.ms !== undefined && !positiveInteger(b.ms));
449
+ if (bad) {
450
+ refusals.push(refusal(
451
+ "query.budget_invalid", "budget",
452
+ "a budget bound is not a positive integer: records is required, and a bound that admits nothing is not a bound",
453
+ "state budget.records as an integer of 1 or more, with bytes and ms optional and positive, or state no budget at all and take the documented default of 20 records",
454
+ "§9",
455
+ ));
456
+ } else {
457
+ budget = {
458
+ records: b.records!,
459
+ ...(b.bytes === undefined ? {} : { bytes: b.bytes }),
460
+ ...(b.ms === undefined ? {} : { ms: b.ms }),
461
+ };
462
+ }
463
+ }
464
+
465
+ const cwd = request.asker?.cwd;
466
+ if (cwd !== undefined && !(cwd.startsWith("/") && cwd.length >= 2)) {
467
+ refusals.push(refusal(
468
+ "query.asker_invalid", "asker",
469
+ `asker.cwd ${JSON.stringify(cwd)} is not an absolute POSIX path`,
470
+ "give asker.cwd as an absolute path, or omit it and let the read record the directory it read; v0.2 of the spec is POSIX-only",
471
+ "§4.5",
472
+ ));
473
+ }
474
+ if (request.asker?.task !== undefined && request.asker.task.length === 0) {
475
+ refusals.push(refusal(
476
+ "query.asker_invalid", "asker",
477
+ "asker.task is an empty string, which parley.query does not carry",
478
+ "omit the task, or give it the caller's task id",
479
+ "§4.5",
480
+ ));
481
+ }
482
+
483
+ if (request.note !== undefined && request.note.length === 0) {
484
+ refusals.push(refusal(
485
+ "query.note_empty", "note",
486
+ "the note is an empty string, which parley.query does not carry",
487
+ "omit the note, or give it text; it is recorded and never parsed",
488
+ "§4.5",
489
+ ));
490
+ }
491
+
492
+ if (refusals.length > 0) return { refused: true, refusals };
493
+
494
+ const asker: Asker = {
495
+ tool: tool!,
496
+ ...(request.asker?.cwd === undefined ? {} : { cwd: request.asker.cwd }),
497
+ ...(request.asker?.task === undefined ? {} : { task: request.asker.task }),
498
+ };
499
+ return {
500
+ refused: false,
501
+ query: {
502
+ asker,
503
+ view: request.view as View,
504
+ budget: budget!,
505
+ window: { from: window!.from!, to: window!.to! },
506
+ ...(request.note === undefined ? {} : { note: request.note }),
507
+ budgetDefaulted,
508
+ },
509
+ };
510
+ }
511
+
512
+ /** The `parley.query` payload for an accepted read. The writer owns the envelope (§1.3). */
513
+ export function queryRecord(query: AcceptedQuery): Record<string, unknown> {
514
+ return {
515
+ event: "query",
516
+ asker: query.asker,
517
+ view: query.view,
518
+ budget: query.budget,
519
+ window: query.window,
520
+ ...(query.note === undefined ? {} : { note: query.note }),
521
+ };
522
+ }
523
+
524
+ function inWindow(record: LoadedRecord, window: QueryWindow): boolean {
525
+ return typeof record.t === "number" && record.t >= window.from && record.t <= window.to;
526
+ }
527
+
528
+ /**
529
+ * Make a read: refuse it, or record it and answer it.
530
+ *
531
+ * A refused read returns its refusals and does nothing else — no run, no receipt, nothing written.
532
+ * An accepted read is a run of its own: the `parley.query` event goes through the writer into a
533
+ * receipt beside the ones being read, so the loader finds it on the next read, and the answer
534
+ * names it by `(run, seq)`.
535
+ *
536
+ * The answer is the window's records ordered by the view and **bounded by the budget**, excluding
537
+ * the read's own run: a read does not answer itself, and the record of it is there for the next
538
+ * one. The bound is the digest's (flyingrobots/parley#50): a second `parley.lens` record goes
539
+ * through the writer naming the asker, the view, the window, the budget applied and the records
540
+ * the digest holds, and reporting the rest of the ranking as a count. Nothing is dropped by the
541
+ * ranking itself — it reorders and never filters — so the count is exactly the tail of one total
542
+ * order. The tail is named nowhere, so a caller reaches it by reading again under a wider budget;
543
+ * `openRecords` opens what the digest does name (flyingrobots/parley#51).
544
+ */
545
+ export async function queryReceipts(request: QueryRequest, opts: QueryOptions = {}): Promise<QueryOutcome> {
546
+ // The deadline is the whole read's, so its clock starts before anything else does.
547
+ const clock = opts.clock ?? MONOTONIC;
548
+ const started = clock();
549
+ const cwd = resolve(opts.cwd ?? process.cwd());
550
+ // §9's inference, as flyingrobots/parley#46 settled it and flyingrobots/parley#61 decided in
551
+ // full: `asker.cwd` comes from the process when the caller does not state it. `asker.task` is
552
+ // never inferred at all — there is no environment variable for it — so it is taken from the
553
+ // request and omitted when the caller does not state it.
554
+ const plan = planQuery({ ...request, asker: { ...request.asker, cwd: request.asker?.cwd ?? cwd } });
555
+ if (plan.refused) return plan;
556
+ const query = plan.query;
557
+ const deadline = new Deadline(query.budget.ms, clock, started);
558
+
559
+ const env = opts.env ?? process.env;
560
+ const stdout = new Tee(opts.stdout);
561
+ const stderr = new Tee(opts.stderr);
562
+ const identity = opts.tool ?? READER;
563
+
564
+ const spec = defineTool({
565
+ name: identity.name,
566
+ version: identity.version,
567
+ commands: {
568
+ read: {
569
+ intent: "Answer a read against this working directory's receipt bundles, and record the read",
570
+ effects: {
571
+ reads: [`${repoReceiptDir(cwd)}/*`, `${stateReceiptDir({ ...opts, cwd })}/*`],
572
+ writes: [],
573
+ network: false,
574
+ idempotent: true,
575
+ },
576
+ secrets: [],
577
+ emits: [{ ...QUERY_SCHEMA }, { ...LENS_SCHEMA }],
578
+ },
579
+ },
580
+ // §5.1 asks every tool for a stated policy. A read states one that deletes nothing: expiring
581
+ // the receipts it was asked to read would destroy the history to answer a question about it.
582
+ retention: { count: NO_RETENTION },
583
+ });
584
+
585
+ let answer: Omit<QueryAnswer, "status" | "lines"> | Omit<QueryDeclined, "status" | "lines"> | undefined;
586
+ const status = await main(spec, [spec.name, "read"], (run) => {
587
+ const seq = run.result(queryRecord(query), QUERY_SCHEMA);
588
+ run.step(
589
+ "recorded the read before answering it",
590
+ "spec §9: a query is itself an event, so the store learns what was asked and a result can name the query it answers",
591
+ { view: query.view, window: query.window, budget: query.budget, budget_defaulted: query.budgetDefaulted },
592
+ );
593
+
594
+ 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 }) });
595
+ const recorded = {
596
+ refused: false as const,
597
+ declined: true as const,
598
+ run: run.id,
599
+ receipt: run.receiptPath,
600
+ query: { run: run.id, seq },
601
+ asker: query.asker,
602
+ view: query.view,
603
+ budget: query.budget,
604
+ budgetDefaulted: query.budgetDefaulted,
605
+ window: query.window,
606
+ ...(query.note === undefined ? {} : { note: query.note }),
607
+ load,
608
+ };
609
+ const afterLoad = deadline.check();
610
+ if (afterLoad.passed) {
611
+ answer = { ...recorded, decline: declineOnRun(run, query.budget, "load", false, { elapsed: afterLoad.elapsed }) };
612
+ return;
613
+ }
614
+
615
+ const all = load.bundles.flatMap((b) => b.records);
616
+ const own = all.filter((r) => r.run === run.id);
617
+ const others = all.filter((r) => r.run !== run.id);
618
+ const undated = others.filter((r) => typeof r.t !== "number");
619
+ // One place decides the order, and it is the ranking: `(t, run, seq)` ascending is the last
620
+ // part of its key, so sorting here first would be the same order computed twice and two
621
+ // places for it to drift.
622
+ const inside = others.filter((r) => inWindow(r, query.window));
623
+ const ranking = rankRecords(query, inside);
624
+
625
+ const ranked = run.step(
626
+ `ranked ${ranking.records.length} record(s) of the window by the ${query.view} view`,
627
+ "spec §9's purpose is the ranking function, not a filter: every record in the window is ranked, so the digest that follows cuts the tail of one total order and can say how long that tail was (flyingrobots/parley#49)",
628
+ {
629
+ scanned: all.length, in_window: ranking.records.length, undated: undated.length, own: own.length,
630
+ view: query.view, implies_change: ranking.impliesChange, tiers: ranking.counts,
631
+ },
632
+ );
633
+ const afterRank = deadline.check();
634
+ if (afterRank.passed) {
635
+ answer = { ...recorded, decline: declineOnRun(run, query.budget, "rank", false, { elapsed: afterRank.elapsed }) };
636
+ return;
637
+ }
638
+
639
+ // The digest's line is bounded in bytes before it is written, so the envelope it will be
640
+ // written with has to be known here. `run.result` and `run.step` each take one seq in order
641
+ // and return it, a read declares no secrets so no redaction line comes between them, and the
642
+ // one step below sits between this ranking step and the digest: the digest's seq is therefore
643
+ // `ranked + 2`, and `t` comes from the same clock the writer stamps with. RD-20c pins that
644
+ // reconstruction against the line the writer really wrote.
645
+ //
646
+ // The seq is measured an order of magnitude larger than that, which is one more digit and so
647
+ // one byte of headroom. It is not paranoia about the arithmetic above: the writer can raise a
648
+ // line of its own in between — a history stream that fails mid-run is a `warning` — and a seq
649
+ // that gained a digit would put the line one byte over a budget the caller stated. A stated
650
+ // bound that holds is worth a byte.
651
+ const envelope = { run: run.id, seq: (ranked + 2) * 10, t: (opts.now ?? Date.now)() };
652
+ const digested = digestFor(
653
+ query,
654
+ { run: run.id, seq },
655
+ ranking.records,
656
+ envelope,
657
+ // Each entry's outcome is the whole window's verdict on its run, not the prefix's.
658
+ ranking.outcomes,
659
+ );
660
+ const records = digested.records;
661
+ const named = new Set(records);
662
+
663
+ // The last check: the digest is built and only writing it is left. A byte bound that even an
664
+ // empty digest is over is declined here too, beside the deadline when both fail, so a caller
665
+ // learns every bound it has to move in one read.
666
+ const beforeDigest = deadline.check();
667
+ if (beforeDigest.passed || !digested.fits) {
668
+ answer = {
669
+ ...recorded,
670
+ decline: declineOnRun(run, query.budget, "digest", true, {
671
+ ...(beforeDigest.passed ? { elapsed: beforeDigest.elapsed } : {}),
672
+ ...(digested.fits ? {} : { bytes: sufficientBytes(query, { run: run.id, seq }, ranking.records.length, envelope, digested.folded) }),
673
+ }),
674
+ };
675
+ return;
676
+ }
677
+
678
+ run.step(
679
+ digested.excluded === 0
680
+ ? `answered with all ${records.length} ranked record(s): the budget cut nothing`
681
+ : `answered with ${records.length} of ${ranking.records.length} ranked record(s) and excluded ${digested.excluded}${digested.folded === 0 ? "" : `, ${digested.folded} of them folded into a run of the same invocation and result`}`,
682
+ "spec §9: a result is bounded and reports what it excluded, at least as a count, so a later reader cannot mistake a digest for the whole (flyingrobots/parley#50)",
683
+ {
684
+ records_bound: query.budget.records,
685
+ ...(query.budget.bytes === undefined ? {} : { bytes_bound: query.budget.bytes }),
686
+ named: records.length, excluded: digested.excluded, folded: digested.folded, loss_bound: digested.digest.loss.bound,
687
+ digest_bytes: digested.bytes,
688
+ },
689
+ );
690
+
691
+ const before = stdout.lines.length;
692
+ run.result(digested.digest as unknown as Record<string, unknown>, LENS_SCHEMA);
693
+ // The bytes the answer reports are the bytes that went out, not the reconstruction the bound
694
+ // was measured against; a stream the host replaced cannot hide a line the read wrote, because
695
+ // the read's own tee holds it.
696
+ const written = stdout.lines[before];
697
+ const digestBytes = written === undefined ? digested.bytes : Buffer.byteLength(written, "utf8");
698
+
699
+ answer = {
700
+ refused: false,
701
+ declined: false,
702
+ run: run.id,
703
+ receipt: run.receiptPath,
704
+ query: { run: run.id, seq },
705
+ asker: query.asker,
706
+ view: query.view,
707
+ budget: query.budget,
708
+ budgetDefaulted: query.budgetDefaulted,
709
+ window: query.window,
710
+ ...(query.note === undefined ? {} : { note: query.note }),
711
+ records,
712
+ digest: digested.digest,
713
+ digestBytes,
714
+ // The ranking's records stop where the digest does; its outcomes and counts describe the
715
+ // window the digest was drawn from (see `QueryAnswer.ranking`).
716
+ // A folded-away run's records are not in the digest, so the prefix is taken by identity.
717
+ ranking: { ...ranking, records, ranked: ranking.ranked.filter((r) => named.has(r.record)) },
718
+ counts: {
719
+ scanned: all.length,
720
+ inWindow: ranking.records.length,
721
+ answered: records.length,
722
+ excluded: digested.excluded,
723
+ folded: digested.folded,
724
+ undated: undated.length,
725
+ own: own.length,
726
+ },
727
+ load,
728
+ };
729
+ }, {
730
+ cwd,
731
+ env,
732
+ ...(opts.home === undefined ? {} : { home: opts.home }),
733
+ ...(opts.session === undefined ? {} : { session: opts.session }),
734
+ ...(opts.now === undefined ? {} : { now: opts.now }),
735
+ stdout,
736
+ stderr,
737
+ // What enters `inv` is the question, not the clock or the directory (§2.2): the view, the
738
+ // window and the budget, with the asker's tool and task. `asker.cwd` is left out on purpose —
739
+ // it moves with the process, and an `inv` that moves with the directory identifies nothing.
740
+ resolved: () => ({
741
+ command: "read",
742
+ view: query.view,
743
+ window: query.window,
744
+ budget: query.budget,
745
+ asker: { tool: query.asker.tool, ...(query.asker.task === undefined ? {} : { task: query.asker.task }) },
746
+ }),
747
+ });
748
+
749
+ const lines = stdout.lines
750
+ .map((l) => { try { return JSON.parse(l) as Record<string, unknown>; } catch { return null; } })
751
+ .filter((l): l is Record<string, unknown> => l !== null);
752
+
753
+ if (!answer) {
754
+ // The handler did not finish: the writer has already recorded why on the read's own streams
755
+ // and in its receipt, and the status says so. There is no answer to return and none is
756
+ // invented.
757
+ throw new Error(`the read did not complete: status ${status}; see the receipt it recorded`);
758
+ }
759
+ return { ...answer, lines, status };
760
+ }