@staix/agent-hub 0.37.0 → 0.38.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.
Files changed (43) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/README.md +1 -1
  3. package/docs/design/guidance-probes.md +365 -0
  4. package/docs/dogfood.md +2 -1
  5. package/docs/operations.md +13 -5
  6. package/docs/profiles.md +1 -1
  7. package/docs/quickstart.md +7 -1
  8. package/docs/security.md +6 -2
  9. package/docs/verification/2026-11-11-0.38.0.md +41 -0
  10. package/docs/verification/2026-11-11-guidance-probe-t3-1226.md +85 -0
  11. package/docs/verification/2026-11-11-guidance-probe-t4-1226.md +65 -0
  12. package/docs/verified.json +18 -18
  13. package/package.json +1 -1
  14. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  15. package/plugins/agent-hub/kimi-hook.js +45 -23
  16. package/plugins/agent-hub/server.js +46 -23
  17. package/src/adapters/claude-channel.ts +2 -1
  18. package/src/adapters/local-probe.ts +65 -6
  19. package/src/cli/help.ts +1 -1
  20. package/src/cli/init.ts +3 -1
  21. package/src/cli/main.ts +23 -8
  22. package/src/cli/output.ts +8 -4
  23. package/src/cli/upgrade-runtime.ts +1 -1
  24. package/src/hub/bus.ts +2 -2
  25. package/src/hub/control-client.ts +1 -1
  26. package/src/hub/daemon.ts +30 -8
  27. package/src/hub/envelope.ts +6 -1
  28. package/src/hub/guidance-probe-store.ts +345 -14
  29. package/src/hub/guidance-probes.ts +338 -4
  30. package/src/hub/manager.ts +24 -1
  31. package/src/hub/operational-authority.ts +3 -2
  32. package/src/hub/person-command.ts +25 -0
  33. package/src/hub/supervision.ts +3 -2
  34. package/src/hub/tasks.ts +48 -3
  35. package/src/local/probe-types.ts +2 -0
  36. package/src/local/probe-workspace.ts +191 -2
  37. package/src/ui/guidance-panel.ts +34 -2
  38. package/src/ui/guidance-view.ts +33 -0
  39. package/src/ui/plugin.ts +10 -3
  40. package/templates/AGENTS.block.md +14 -14
  41. package/templates/profiles/general.json +1 -1
  42. package/templates/profiles/research.json +1 -1
  43. package/templates/profiles/writing.json +1 -1
@@ -85,6 +85,8 @@ export interface ProbeSessionCoverage {
85
85
  inputFrameSha256: string | null; inputFrameBytes: number; launchExposed: boolean; preLaunchFailure: boolean;
86
86
  modelCalls: number; modelUsageKnown: number; toolCalls: number; toolUsageKnown: number;
87
87
  usageUnknown: boolean; coverageVerified: boolean;
88
+ /** Tokens this session alone observed (T3). Optional: sessions written before it have none, which reads as 0 known tokens only when no model call ran unobserved. */
89
+ tokensObserved?: number;
88
90
  }
89
91
  export interface ProbeUsageObservation { admission: ProbeEffectAdmission; observed: number | null; observationSha256: string }
90
92
  export interface ProbeCancellation { key: ProbeKey; expectedRevision: number; host: ProbeHostBinding }
@@ -92,8 +94,11 @@ export interface ProbeCounters {
92
94
  workerAttempts: number; editorAttempts: number; modelCalls: number; toolCalls: number; tokensReserved: number; tokensObservedKnown: number;
93
95
  inputBytes: number; scratchBytes: number; outputBytes: number; elapsedHighWaterMs: number; usageUnknown: boolean;
94
96
  }
97
+ /** Why a session settled, recorded once when it settled so a receipt is derived from the session's own facts and never from experiment state that moves later. */
98
+ export type ProbeCloseCause = "none" | "cancel" | "elapsed" | "hold" | "crash";
95
99
  export interface ProbeSession {
96
100
  slotId: string; generation: number; revision: number; state: ProbeSessionState; candidateArtifactSha256: string | null;
101
+ closeCause?: ProbeCloseCause;
97
102
  child?: ProbeChildBinding;
98
103
  start?: ProbeStartSelector;
99
104
  coverage: ProbeSessionCoverage;
@@ -108,6 +113,8 @@ export interface ProbeFakeObservation {
108
113
  reservation: ProbeReservation; outcome: "closed_fixture" | "failed_known" | "unknown"; servedModel: string | null;
109
114
  inputFrameHash: string | null;
110
115
  workerEffectiveInputHash: string | null; nonGuidanceInputSha256: string | null; candidateArtifactSha256: string | null; usage: "known_fixture" | "unknown";
116
+ /** What the host measured of the finished session (T3). The adapter cannot supply `startedAt`: the host samples it when it exposes the launch. */
117
+ measured?: Omit<ProbeMeasuredSession, "startedAt">;
111
118
  }
112
119
  export interface ProbeFakeStop { reservation: ProbeReservation }
113
120
  export interface ProbeFakeStopObservation { reservation: ProbeReservation; stopped: "known_fixture" | "unknown" }
@@ -123,12 +130,18 @@ export interface ProbeFakeEffects {
123
130
  export interface GuidanceProbeFakePorts {
124
131
  launch(input: ProbeFakeLaunch, effects: ProbeFakeEffects, signal: AbortSignal): Promise<ProbeFakeObservation>;
125
132
  stop(input: ProbeFakeStop, signal: AbortSignal): Promise<ProbeFakeStopObservation>;
133
+ /**
134
+ * Remove output the port itself retained for a launch whose measurement the host did not seal with that record: an observation that did not match the
135
+ * reservation (a fallback model, for one), a failed seal, a settlement that lost its clock. Without it that directory has no row, so no prune could ever
136
+ * reach it. The port removes only what it created, by the identity it captured, and never throws into the host.
137
+ */
138
+ discardRetained?(retained: ProbeRetainedRecord): void;
126
139
  }
127
140
  export interface ProbePublicReceipt extends ProbeReceipt { experimentId: string; taskId: number; evidence: "declaration" | "fixture" | "unknown" }
128
141
  export interface ProbePublicStatus extends ProbePublicReceipt { counters: ProbeCounters; cancelRequested: boolean; notNeeded: number; comparable: boolean; authoring: "admitted_fixture" | "uncontrolled" | "unknown" }
129
142
  export type GuidanceProbeCommand = { op: "register"; file: string; json: boolean }
130
143
  | { op: "start"; id: string; revision: number; variantId?: string; json: boolean }
131
- | { op: "show"; id: string; json: boolean } | { op: "cancel"; id: string; revision: number; json: boolean };
144
+ | { op: "show"; id: string; json: boolean } | { op: "receipts"; id: string; json: boolean } | { op: "cancel"; id: string; revision: number; json: boolean };
132
145
 
133
146
  export class GuidanceProbeError extends Error {
134
147
  constructor(readonly reason: "invalid" | "changed" | "budget" | "held" | "runner" | "storage") {
@@ -307,8 +320,8 @@ export function parseGuidanceProbeRegistration(value: unknown): ProbeRegistratio
307
320
  }
308
321
 
309
322
  export function parseGuidanceProbeCommand(args: readonly string[]): GuidanceProbeCommand | undefined {
310
- const op = args[0]; if (!["register", "start", "show", "cancel"].includes(op ?? "")) return undefined;
311
- const fields = new Map<string, string>(), allowed = op === "register" ? ["--file"] : op === "show" ? ["--id"] : op === "start" ? ["--id", "--revision", "--variant"] : ["--id", "--revision"];
323
+ const op = args[0]; if (!["register", "start", "show", "receipts", "cancel"].includes(op ?? "")) return undefined;
324
+ const fields = new Map<string, string>(), allowed = op === "register" ? ["--file"] : op === "show" || op === "receipts" ? ["--id"] : op === "start" ? ["--id", "--revision", "--variant"] : ["--id", "--revision"];
312
325
  let json = false;
313
326
  for (let index = 1; index < args.length; index++) {
314
327
  const key = args[index]!; if (key === "--json" && !json) { json = true; continue; }
@@ -316,7 +329,7 @@ export function parseGuidanceProbeCommand(args: readonly string[]): GuidanceProb
316
329
  }
317
330
  if (op === "register") return fields.has("--file") ? { op, file: fields.get("--file")!, json } : undefined;
318
331
  const id = fields.get("--id"); if (!probeSha256(id)) return undefined;
319
- if (op === "show") return { op, id, json };
332
+ if (op === "show" || op === "receipts") return { op, id, json };
320
333
  const raw = fields.get("--revision"), revision = raw && /^(?:0|[1-9][0-9]*)$/.test(raw) ? Number(raw) : NaN;
321
334
  if (!probeInteger(revision)) return undefined;
322
335
  if (op === "cancel") return { op, id, revision, json };
@@ -356,3 +369,324 @@ export function guidanceProbeWorkerFrame(task: string, baselineContext: string,
356
369
  return JSON.stringify({ task, baselineContext, systemPolicy, guidance });
357
370
  }
358
371
  export const guidanceProbeNonGuidanceInputHash = (task: string, baselineContext: string, systemPolicy: string): string => probeHash(JSON.stringify({ task, baselineContext, systemPolicy }));
372
+
373
+ // ---------------------------------------------------------------------------------------------------------------------------------------------------------------
374
+ // T3 (#1226): host-observed receipts, the outcome denominator and comparability. Contract: docs/design/guidance-probes.md "T3 receipts, reconcile and cleanup contract".
375
+ // Everything here is pure: no storage, process or clock. The Store seals and hydrates; these functions only shape, check and classify.
376
+ // ---------------------------------------------------------------------------------------------------------------------------------------------------------------
377
+
378
+ /** Retained output is eligible for a prune this long after its receipt seals. A constant, not a setting; nothing deletes automatically. */
379
+ export const PROBE_RETENTION_DAYS = 14;
380
+ export const PROBE_RETENTION_MS = PROBE_RETENTION_DAYS * 24 * 60 * 60 * 1000;
381
+ /**
382
+ * The bounds of one receipt, and the largest valid receipt they allow. `receiptBytes` is DERIVED from them, never chosen: a session that meets every success
383
+ * condition and writes 64 files with the longest allowed names must still seal as a success, so the byte bound can never sit below the largest valid manifest.
384
+ * A name is at most `nameBytes` UTF-8 bytes; in JSON each of those bytes can cost two (a quote or a backslash), plus the surrounding quotes. Control and format
385
+ * characters are refused outright (`probeOutputName`), so no byte costs more than two. `FIXED_RECEIPT_BYTES` covers every other field at its own maximum:
386
+ * three bounded ids and model names, eight digests, the counters, the limits array and the keys (measured at about 3 KB; the test builds the real maximum).
387
+ */
388
+ const OUTPUT_NAME_BYTES = 256, OUTPUT_ENTRIES = 64;
389
+ const NAME_JSON_BYTES = 2 * OUTPUT_NAME_BYTES + 2;
390
+ const ENTRY_JSON_BYTES = NAME_JSON_BYTES + 160, EXCLUDED_JSON_BYTES = NAME_JSON_BYTES + 64, FIXED_RECEIPT_BYTES = 4096;
391
+ export const PROBE_OUTPUT_LIMITS = Object.freeze({ entries: OUTPUT_ENTRIES, fileBytes: 1024 * 1024, nameBytes: OUTPUT_NAME_BYTES,
392
+ receiptBytes: FIXED_RECEIPT_BYTES + OUTPUT_ENTRIES * (ENTRY_JSON_BYTES + 1) + OUTPUT_ENTRIES * (EXCLUDED_JSON_BYTES + 1) });
393
+ /** The one name check for an output path in a manifest, an exclusion or a retained record: bounded, relative, no control or format characters, no `..`. */
394
+ export const probeOutputName = (value: unknown): value is string => executionText(value, PROBE_OUTPUT_LIMITS.nameBytes) && !/\p{Cf}/u.test(value)
395
+ && !value.startsWith("/") && !value.split("/").includes("..");
396
+
397
+ export type ProbeReceiptState = "succeeded" | "failed" | "cancelled" | "timed_out" | "unavailable" | "unknown";
398
+ export type ProbeReceiptLimit = "usage_unknown" | "served_model_unobserved" | "served_model_mismatch" | "teardown_unverified" | "output_truncated" | "storage_over_cap" | "coverage_unverified";
399
+ export type ProbeExcludedReason = "not_regular" | "linked" | "outside_declared_writes" | "over_file_cap" | "over_total_cap" | "changed_while_read" | "over_entry_cap" | "over_depth" | "over_walk_cap" | "invalid_name";
400
+ export interface ProbeOutputEntry { relative: string; sha256: string; bytes: number }
401
+ export interface ProbeOutputExcluded { relative: string; reason: ProbeExcludedReason }
402
+ export interface ProbeOutputManifestV1 { v: 1; entries: readonly ProbeOutputEntry[]; excluded: readonly ProbeOutputExcluded[]; totalBytes: number }
403
+ export interface ProbeReceiptUsage { modelCalls: number; modelUsageKnown: number; toolCalls: number; toolUsageKnown: number; tokensObserved: number | null }
404
+ /** The host's immutable record of one finished session. Every field is host-computed; none is a provider claim. */
405
+ export interface ProbeReceiptV1 {
406
+ v: 1;
407
+ experimentId: string;
408
+ slotId: string;
409
+ generation: number;
410
+ revision: number;
411
+ requestedModel: string;
412
+ servedModel: string | null;
413
+ inputFrameSha256: string | null;
414
+ workerEffectiveInputSha256: string | null;
415
+ nonGuidanceInputSha256: string | null;
416
+ guidanceSha256: string | null;
417
+ /** The host's own fingerprints read at seal time. `null` when the host never observed them (a crash reconcile): never copied from the declaration. */
418
+ runtimeSha256: string | null;
419
+ toolsetSha256: string | null;
420
+ modelConfigSha256: string | null;
421
+ startedAt: number;
422
+ endedAt: number;
423
+ elapsedMs: number;
424
+ state: ProbeReceiptState;
425
+ usage: ProbeReceiptUsage;
426
+ limits: readonly ProbeReceiptLimit[];
427
+ output: ProbeOutputManifestV1;
428
+ /** Seal time plus PROBE_RETENTION_MS. A prune never removes retained output before this instant. */
429
+ expiresAt: number;
430
+ digest: string;
431
+ }
432
+ export type ProbeIncomparableReason = "served_model_mismatch" | "served_model_unobserved" | "input_drift" | "usage_unknown" | "incomplete_coverage"
433
+ | "teardown_unverified" | "authoring_uncontrolled" | "missing_receipt";
434
+ export interface ProbeComparability { comparable: boolean; reasons: readonly ProbeIncomparableReason[] }
435
+ /** Private status: the outcome denominator by receipt state, plus slots that never started. Never part of the public projection (T4 owns that). */
436
+ export interface ProbeOutcomeCounts { succeeded: number; failed: number; cancelled: number; timed_out: number; unavailable: number; unknown: number; planned: number; not_needed: number }
437
+
438
+ const RECEIPT_STATES: readonly ProbeReceiptState[] = ["succeeded", "failed", "cancelled", "timed_out", "unavailable", "unknown"];
439
+ const RECEIPT_LIMITS: readonly ProbeReceiptLimit[] = ["usage_unknown", "served_model_unobserved", "served_model_mismatch", "teardown_unverified", "output_truncated", "storage_over_cap", "coverage_unverified"];
440
+ const EXCLUDED_REASONS: readonly ProbeExcludedReason[] = ["not_regular", "linked", "outside_declared_writes", "over_file_cap", "over_total_cap", "changed_while_read", "over_entry_cap", "over_depth", "over_walk_cap", "invalid_name"];
441
+
442
+ /** Digest over the canonical record without its own digest field. */
443
+ export function probeReceiptDigest(receipt: Omit<ProbeReceiptV1, "digest">): string {
444
+ return probeHash(guidanceProbeCanonical(receipt, PROBE_OUTPUT_LIMITS.receiptBytes));
445
+ }
446
+ const nullableSha = (value: unknown): boolean => value === null || probeSha256(value);
447
+ /** Closed, inert parse. Returns undefined for any shape, bound or digest violation; never repairs. */
448
+ export function parseProbeReceipt(value: unknown): ProbeReceiptV1 | undefined {
449
+ try {
450
+ const f = object(inert(value, PROBE_OUTPUT_LIMITS.receiptBytes), ["v", "experimentId", "slotId", "generation", "revision", "requestedModel", "servedModel", "inputFrameSha256",
451
+ "workerEffectiveInputSha256", "nonGuidanceInputSha256", "guidanceSha256", "runtimeSha256", "toolsetSha256", "modelConfigSha256", "startedAt", "endedAt", "elapsedMs", "state",
452
+ "usage", "limits", "output", "expiresAt", "digest"]);
453
+ required(f.v === 1 && identity(f.experimentId) && identity(f.slotId) && probeInteger(f.generation) && probeInteger(f.revision));
454
+ required(f.requestedModel === GUIDANCE_PROBE_MODEL && (f.servedModel === null || typeof f.servedModel === "string" && Buffer.byteLength(f.servedModel) <= 256));
455
+ required(nullableSha(f.inputFrameSha256) && nullableSha(f.workerEffectiveInputSha256) && nullableSha(f.nonGuidanceInputSha256) && nullableSha(f.guidanceSha256));
456
+ required(nullableSha(f.runtimeSha256) && nullableSha(f.toolsetSha256) && nullableSha(f.modelConfigSha256));
457
+ // elapsed time is wall time between the Store's trusted-clock samples, so it can never exceed the span between them.
458
+ required(probeInteger(f.startedAt) && probeInteger(f.endedAt) && probeInteger(f.elapsedMs) && f.endedAt >= f.startedAt && f.elapsedMs <= f.endedAt - f.startedAt
459
+ && probeInteger(f.expiresAt) && f.expiresAt === f.endedAt + PROBE_RETENTION_MS);
460
+ required(RECEIPT_STATES.includes(f.state as ProbeReceiptState));
461
+ const usage = object(f.usage, ["modelCalls", "modelUsageKnown", "toolCalls", "toolUsageKnown", "tokensObserved"]);
462
+ required(probeInteger(usage.modelCalls) && probeInteger(usage.modelUsageKnown) && usage.modelUsageKnown <= usage.modelCalls
463
+ && probeInteger(usage.toolCalls) && probeInteger(usage.toolUsageKnown) && usage.toolUsageKnown <= usage.toolCalls && (usage.tokensObserved === null || probeInteger(usage.tokensObserved)));
464
+ required(Array.isArray(f.limits) && f.limits.length <= RECEIPT_LIMITS.length && new Set(f.limits).size === f.limits.length && f.limits.every(item => RECEIPT_LIMITS.includes(item as ProbeReceiptLimit)));
465
+ const output = object(f.output, ["v", "entries", "excluded", "totalBytes"]);
466
+ required(output.v === 1 && Array.isArray(output.entries) && output.entries.length <= PROBE_OUTPUT_LIMITS.entries && Array.isArray(output.excluded) && output.excluded.length <= PROBE_OUTPUT_LIMITS.entries
467
+ && probeInteger(output.totalBytes));
468
+ let total = 0; const names = new Set<string>();
469
+ for (const entry of output.entries as unknown[]) {
470
+ const e = object(entry, ["relative", "sha256", "bytes"]);
471
+ required(probeOutputName(e.relative) && probeSha256(e.sha256) && probeInteger(e.bytes) && e.bytes <= PROBE_OUTPUT_LIMITS.fileBytes && !names.has(e.relative));
472
+ names.add(e.relative as string); total += e.bytes as number;
473
+ }
474
+ required(total === output.totalBytes);
475
+ for (const entry of output.excluded as unknown[]) {
476
+ const e = object(entry, ["relative", "reason"]);
477
+ required(probeOutputName(e.relative) && EXCLUDED_REASONS.includes(e.reason as ProbeExcludedReason));
478
+ }
479
+ required(probeSha256(f.digest));
480
+ const { digest, ...rest } = f as unknown as ProbeReceiptV1;
481
+ required(probeReceiptDigest(rest) === digest);
482
+ // A success is never recorded alongside a limit or an exclusion that the contract says forbids it.
483
+ if (f.state === "succeeded") required((f.limits as unknown[]).length === 0 && (output.excluded as unknown[]).length === 0 && f.servedModel === GUIDANCE_PROBE_MODEL);
484
+ return f as unknown as ProbeReceiptV1;
485
+ } catch { return undefined; }
486
+ }
487
+
488
+ /**
489
+ * Pure comparability over an experiment's receipts and the slots that should have produced them (AC4). One reason is enough to make the
490
+ * pair incomparable; reasons are listed, not ranked. Never an upgrade of the older inline expression: every case that expression called
491
+ * incomparable is incomparable here too.
492
+ */
493
+ export function classifyProbeComparability(input: {
494
+ slots: readonly { slotId: string; role: ProbeSlot["role"]; arm: ProbeSlot["arm"]; reserved: boolean; coverageVerified: boolean; authoring?: "admitted_fixture" | "uncontrolled" }[];
495
+ receipts: readonly ProbeReceiptV1[];
496
+ /** The manifest's runtime fingerprints, which every receipt must match. */
497
+ runtime: { runtimeSha256: string; toolsetSha256: string; modelConfigSha256: string };
498
+ holds: boolean;
499
+ }): ProbeComparability {
500
+ const reasons = new Set<ProbeIncomparableReason>();
501
+ if (input.holds) reasons.add("usage_unknown");
502
+ const bySlot = new Map(input.receipts.map(item => [item.slotId, item]));
503
+ for (const slot of input.slots) {
504
+ if (!slot.reserved) continue;
505
+ if (slot.authoring === "uncontrolled") reasons.add("authoring_uncontrolled");
506
+ if (!slot.coverageVerified) reasons.add("incomplete_coverage");
507
+ const receipt = bySlot.get(slot.slotId);
508
+ if (!receipt) { reasons.add("missing_receipt"); continue; }
509
+ if (receipt.servedModel === null) reasons.add("served_model_unobserved");
510
+ else if (receipt.servedModel !== receipt.requestedModel) reasons.add("served_model_mismatch");
511
+ // A fingerprint the host never observed is drift it cannot rule out; one that differs from the declaration is drift.
512
+ if (receipt.runtimeSha256 !== input.runtime.runtimeSha256 || receipt.toolsetSha256 !== input.runtime.toolsetSha256 || receipt.modelConfigSha256 !== input.runtime.modelConfigSha256) reasons.add("input_drift");
513
+ if (receipt.limits.includes("usage_unknown") || receipt.usage.tokensObserved === null || receipt.usage.modelUsageKnown !== receipt.usage.modelCalls || receipt.usage.toolUsageKnown !== receipt.usage.toolCalls) reasons.add("usage_unknown");
514
+ if (receipt.limits.includes("teardown_unverified")) reasons.add("teardown_unverified");
515
+ if (receipt.state !== "succeeded") reasons.add("incomplete_coverage");
516
+ }
517
+ // Worker arms differ only in the admitted guidance slot: any other input byte differing is drift.
518
+ const workers = input.receipts.filter(item => input.slots.some(slot => slot.slotId === item.slotId && slot.role === "worker"));
519
+ const baseline = workers[0];
520
+ for (const worker of workers) if (baseline && (worker.nonGuidanceInputSha256 === null || worker.nonGuidanceInputSha256 !== baseline.nonGuidanceInputSha256)) reasons.add("input_drift");
521
+ return { comparable: reasons.size === 0, reasons: [...reasons].sort() };
522
+ }
523
+
524
+ /** The outcome denominator: every reserved slot counts, whatever became of it. Slots never started are reported apart, never as success or failure. */
525
+ export function probeOutcomeCounts(slots: readonly { slotId: string; state: ProbeSessionState }[], receipts: readonly ProbeReceiptV1[]): ProbeOutcomeCounts {
526
+ const counts: ProbeOutcomeCounts = { succeeded: 0, failed: 0, cancelled: 0, timed_out: 0, unavailable: 0, unknown: 0, planned: 0, not_needed: 0 };
527
+ const bySlot = new Map(receipts.map(item => [item.slotId, item]));
528
+ for (const slot of slots) {
529
+ if (slot.state === "planned") { counts.planned++; continue; }
530
+ if (slot.state === "not_needed") { counts.not_needed++; continue; }
531
+ // A reserved slot with no sealed receipt is unknown: the host cannot vouch for it. It is never counted as failed.
532
+ counts[bySlot.get(slot.slotId)?.state ?? "unknown"]++;
533
+ }
534
+ return counts;
535
+ }
536
+
537
+ /** What the host measured about one finished session, before the Store adds the fields only it can know. None of this comes from the provider. */
538
+ export interface ProbeMeasuredSession {
539
+ /** Store-trusted-clock sample taken when this session's launch was exposed, as reported back by the host that took it. Never the experiment's first reservation. */
540
+ startedAt: number;
541
+ servedModel: string | null;
542
+ workerEffectiveInputSha256: string | null;
543
+ nonGuidanceInputSha256: string | null;
544
+ /** True only when the peer, the confinement and every owned child reported known quiescence, and the output was collected after that point. */
545
+ teardownVerified: boolean;
546
+ /** The host's own runtime, toolset and model-config fingerprints at seal time, or null when it could not read them. Never the declaration's. */
547
+ runtime: { runtimeSha256: string; toolsetSha256: string; modelConfigSha256: string } | null;
548
+ cancelled: boolean;
549
+ timedOut: boolean;
550
+ /** The session could not start or reach the model for a host-known reason (for example confinement unavailable). */
551
+ unavailable: boolean;
552
+ /** Limits the host observed itself, such as `output_truncated`. The Store adds the ones it can derive. */
553
+ limits: readonly ProbeReceiptLimit[];
554
+ /** Bytes the session actually left in scratch, measured, not the declared reservation. */
555
+ scratchBytes: number;
556
+ output: ProbeOutputManifestV1;
557
+ /** The host-created retention directory for `output`, if any. Stored beside the receipt, never inside it. */
558
+ retained?: ProbeRetainedRecord;
559
+ }
560
+ /** Stored rows hold a canonical receipt, which is bounded well below this; the SQL length check guards against a hostile row. */
561
+ export const PROBE_RECEIPT_ROW_BYTES = PROBE_OUTPUT_LIMITS.receiptBytes;
562
+ /**
563
+ * The runtime half of the 1 GiB cap: output past the slot's declared bound is not retained, hashed or counted as the session's output. Entries are
564
+ * kept in order until the bound would be crossed; the rest are recorded as excluded, so the receipt can never claim more than was declared.
565
+ */
566
+ export function capOutput(output: ProbeOutputManifestV1, maximum: number): ProbeOutputManifestV1 {
567
+ const entries: ProbeOutputEntry[] = [], excluded: ProbeOutputExcluded[] = [...output.excluded];
568
+ let total = 0;
569
+ for (const entry of output.entries) {
570
+ if (entries.length >= PROBE_OUTPUT_LIMITS.entries || total + entry.bytes > maximum) { excluded.push({ relative: entry.relative, reason: entries.length >= PROBE_OUTPUT_LIMITS.entries ? "over_entry_cap" : "over_total_cap" }); continue; }
571
+ entries.push(entry); total += entry.bytes;
572
+ }
573
+ return { v: 1, entries, excluded: excluded.slice(0, PROBE_OUTPUT_LIMITS.entries), totalBytes: total };
574
+ }
575
+
576
+ /**
577
+ * A retained output directory the host created, with the identity it recorded at creation. Kept beside the receipt in its own column and out of the
578
+ * digested receipt body: a receipt never carries a physical path. Prune acts on nothing that is not recorded here and still matches by identity.
579
+ */
580
+ /**
581
+ * A host-created retention directory and the identity of each file in it. Inode numbers are recycled (Linux reuses one straight after an unlink), so a file's
582
+ * identity is its device, inode AND change time in nanoseconds: a replacement created later always has a later `ctimeNs`, even when it reuses the inode.
583
+ * ponytail: ctime granularity is the filesystem's (a few milliseconds on Linux), so a replacement created in the very same tick as the original with a recycled
584
+ * inode would match; retention-to-prune is days, so the window is the retention call itself. A per-file content hash re-check at prune is the upgrade path.
585
+ * ponytail: a directory has no stable change time (it moves with every entry), so its identity is device and inode only. Deleting a replaced empty directory
586
+ * under the host's own random-named retention root is the ceiling; a stable directory identity (a host-written marker file) is the upgrade path.
587
+ */
588
+ export interface ProbeRetainedRecord { directory: string; dev: number; ino: number; files: readonly { relative: string; dev: number; ino: number; bytes: number; ctimeNs: string }[] }
589
+ /** The filesystem half of prune, injected so the Store (src/hub) never imports src/local. Both calls are identity-checked by their implementation. */
590
+ export interface ProbeRetentionFs {
591
+ preview(retained: ProbeRetainedRecord): { remove: { relative: string; bytes: number }[]; keep: { relative: string; reason: string }[] };
592
+ remove(retained: ProbeRetainedRecord): { removed: string[]; kept: { relative: string; reason: string }[] };
593
+ }
594
+ export function parseProbeRetained(value: unknown): ProbeRetainedRecord | undefined {
595
+ try {
596
+ const f = object(inert(value, PROBE_OUTPUT_LIMITS.receiptBytes), ["directory", "dev", "ino", "files"]);
597
+ required(typeof f.directory === "string" && f.directory.startsWith("/") && Buffer.byteLength(f.directory) <= 1024 && !/[\u0000-\u001f]/.test(f.directory));
598
+ required(probeInteger(f.dev) && probeInteger(f.ino) && Array.isArray(f.files) && f.files.length <= PROBE_OUTPUT_LIMITS.entries);
599
+ const seen = new Set<string>();
600
+ for (const item of f.files as unknown[]) {
601
+ const e = object(item, ["relative", "dev", "ino", "bytes", "ctimeNs"]);
602
+ required(probeOutputName(e.relative) && probeInteger(e.dev) && probeInteger(e.ino) && probeInteger(e.bytes) && e.bytes <= PROBE_OUTPUT_LIMITS.fileBytes && !seen.has(e.relative)
603
+ && typeof e.ctimeNs === "string" && /^[0-9]{1,24}$/.test(e.ctimeNs));
604
+ seen.add(e.relative as string);
605
+ }
606
+ return f as unknown as ProbeRetainedRecord;
607
+ } catch { return undefined; }
608
+ }
609
+ export type ProbePruneKeepReason = "experiment_active" | "experiment_held" | "not_expired" | "already_pruned" | "no_retained_output" | "directory_replaced_or_missing" | "identity_changed" | "not_empty";
610
+ export interface ProbePrunePlan {
611
+ /** SHA-256 over the canonical plan: a prune takes this and refuses if the owned set changed since the person saw it. */
612
+ digest: string;
613
+ retainedBytes: number;
614
+ slots: readonly { slotId: string; expiresAt: number; remove: readonly { relative: string; bytes: number }[]; keep: readonly { relative: string; reason: ProbePruneKeepReason }[] }[];
615
+ }
616
+ export interface ProbePruneResult { pruned: readonly string[]; kept: readonly { slotId: string; relative: string; reason: ProbePruneKeepReason }[]; planDigest: string }
617
+
618
+ // ---------------------------------------------------------------------------------------------------------------------------------------------------------------
619
+ // T4 (#1226): the producer receipt reader and export. Contract: docs/design/guidance-probes.md "T4 producer status and receipt export".
620
+ // ---------------------------------------------------------------------------------------------------------------------------------------------------------------
621
+
622
+ /** Where a slot's retained output stands. It never names a path: a physical location is private to the host. */
623
+ export type ProbeRetentionState = "none" | "retained" | "pruned";
624
+ export interface ProbeExportSlot {
625
+ slotId: string; stage: ProbeStage; role: ProbeSlot["role"]; arm: ProbeSlot["arm"];
626
+ /** The session's own state, so a slot that never started (`planned`, `not_needed`) is visible beside the ones that did. */
627
+ state: ProbeSessionState;
628
+ /** The verbatim sealed receipt, digest-checked on every read. `null` when the slot has none, or when a name in it did not pass the privacy screen. */
629
+ receipt: ProbeReceiptV1 | null;
630
+ /** The receipt's own digest, kept when the receipt is withheld so the consumer can still cite it. `null` only when the slot has no receipt. */
631
+ receiptDigest: string | null;
632
+ withheld: boolean;
633
+ retention: ProbeRetentionState;
634
+ }
635
+ /**
636
+ * What a producer or a receipt consumer reads about one experiment. Everything in it is host-observed or host-computed from sealed receipts; a fixture
637
+ * run is `evidence: "fixture"`, and nothing here claims a live trial, sampling control, provider behaviour or model quality. Unknown stays unknown: a
638
+ * usage gap is `usage_unknown`, an unobserved served model is `served_model_unobserved`, and a slot with no receipt is `unknown` in the denominator.
639
+ */
640
+ export interface ProbeReceiptExport {
641
+ v: 1;
642
+ status: ProbePublicStatus;
643
+ /** The stricter of the older public expression and the sealed-receipt verdict, as in `show`. */
644
+ comparable: boolean;
645
+ /** Why the sealed receipts alone are not comparable. Empty when they are. */
646
+ reasons: readonly ProbeIncomparableReason[];
647
+ /** The full outcome denominator: every reserved slot counts, failed, cancelled, timed out and unavailable included. */
648
+ counts: ProbeOutcomeCounts;
649
+ slots: readonly ProbeExportSlot[];
650
+ }
651
+ /** The largest valid export: every slot with the largest valid receipt, plus the status and the counters. Derived, never chosen. */
652
+ export const PROBE_EXPORT_BYTES = GUIDANCE_PROBE_LIMITS.slots * (PROBE_OUTPUT_LIMITS.receiptBytes + 1024) + 4096;
653
+ const STAGES: readonly ProbeStage[] = ["baseline", "proposal1", "candidate1", "proposal2", "candidate2", "compose", "successor", "select", "reflect"];
654
+ const SLOT_ROLES: readonly ProbeSlot["role"][] = ["worker", "proposal", "compose", "select", "reflect"];
655
+ const SLOT_ARMS: readonly ProbeSlot["arm"][] = ["baseline", "candidate1", "candidate2", "successor", "none"];
656
+ const SESSION_STATES: readonly ProbeSessionState[] = ["planned", "reserved", "running", "failed_known", "closed_fixture", "not_needed", "unknown_held"];
657
+ const INCOMPARABLE_REASONS: readonly ProbeIncomparableReason[] = ["served_model_mismatch", "served_model_unobserved", "input_drift", "usage_unknown", "incomplete_coverage",
658
+ "teardown_unverified", "authoring_uncontrolled", "missing_receipt"];
659
+ const COUNT_KEYS: readonly (keyof ProbeOutcomeCounts)[] = ["succeeded", "failed", "cancelled", "timed_out", "unavailable", "unknown", "planned", "not_needed"];
660
+ /** Closed, inert, bounded parse of a receipt export. Every embedded receipt is re-verified by `parseProbeReceipt`, so a tampered receipt never parses. */
661
+ export function parseGuidanceProbeReceiptExport(value: unknown): ProbeReceiptExport | undefined {
662
+ try {
663
+ const f = object(inert(value, PROBE_EXPORT_BYTES), ["v", "status", "comparable", "reasons", "counts", "slots"]);
664
+ required(f.v === 1);
665
+ const status = parseGuidanceProbePublicStatus(f.status); required(status);
666
+ required(typeof f.comparable === "boolean" && Array.isArray(f.reasons) && f.reasons.length <= INCOMPARABLE_REASONS.length && new Set(f.reasons).size === f.reasons.length
667
+ && f.reasons.every(item => INCOMPARABLE_REASONS.includes(item as ProbeIncomparableReason)));
668
+ // The flag can only be stricter than the sealed verdict: a comparable export never lists a reason, and never outranks the public status.
669
+ required(!(f.comparable && ((f.reasons as unknown[]).length > 0 || !status!.comparable)));
670
+ const counts = object(f.counts, COUNT_KEYS);
671
+ required(COUNT_KEYS.every(key => probeInteger(counts[key])));
672
+ const slots = f.slots; required(Array.isArray(slots) && slots.length <= GUIDANCE_PROBE_LIMITS.slots);
673
+ const seen = new Set<string>(); let withReceipt = 0;
674
+ for (const item of slots as unknown[]) {
675
+ const s = object(item, ["slotId", "stage", "role", "arm", "state", "receipt", "receiptDigest", "withheld", "retention"]);
676
+ required(identity(s.slotId) && !seen.has(s.slotId as string) && STAGES.includes(s.stage as ProbeStage) && SLOT_ROLES.includes(s.role as ProbeSlot["role"])
677
+ && SLOT_ARMS.includes(s.arm as ProbeSlot["arm"]) && SESSION_STATES.includes(s.state as ProbeSessionState) && typeof s.withheld === "boolean"
678
+ && ["none", "retained", "pruned"].includes(s.retention as string));
679
+ seen.add(s.slotId as string);
680
+ if (s.receipt === null) {
681
+ // A withheld receipt still names its digest; a slot with no receipt has neither, and is never marked withheld.
682
+ required(s.withheld ? probeSha256(s.receiptDigest) : s.receiptDigest === null);
683
+ } else {
684
+ const receipt = parseProbeReceipt(s.receipt); required(receipt && !s.withheld && receipt.slotId === s.slotId && s.receiptDigest === receipt.digest);
685
+ withReceipt++;
686
+ }
687
+ }
688
+ const total = COUNT_KEYS.reduce((sum, key) => sum + (counts[key] as number), 0);
689
+ required(total === (slots as unknown[]).length && withReceipt <= total);
690
+ return f as unknown as ProbeReceiptExport;
691
+ } catch { return undefined; }
692
+ }
@@ -1,4 +1,5 @@
1
1
  import { parseGuidanceListQuery, parseGuidanceIdQuery, parseGuidancePageResult, parseGuidanceDiffResult } from "./guidance-variants.ts";
2
+ import { parseGuidanceProbeReceiptExport, probeSha256 } from "./guidance-probes.ts";
2
3
  import type { ActionMeta, InboxAnswers } from "@staix/agent-console/contract";
3
4
  import { assertExecutableRuntimeRoot } from "./project-runtime-state.ts";
4
5
  import { BACKLOG_SPLIT_SCREEN_TIMEOUT_MS } from "./planning.ts";
@@ -257,7 +258,29 @@ export function projectConsole(options: { registry: Registry; lifecycle: Lifecyc
257
258
  } catch { return { ok: false, error: "guidance read is unavailable; refresh the task scope or upgrade the hub before retrying" }; }
258
259
  finally { client?.close(); }
259
260
  };
260
- return { list, act, answer, receipt, consoleControl, lineage, guidance };
261
+ /** Producer-only read port for one probe experiment; never forwards an action, an actor or a person-metadata claim, and writes nothing in the hub. */
262
+ const guidanceProbe = async (target: { projectId: unknown; instanceId: unknown }, input: unknown) => {
263
+ if (options.stopping?.()) return { ok: false, error: "guidance probe status is unavailable while the manager stops; reconnect before retrying" };
264
+ const project = typeof target.projectId === "string" ? registry.get(target.projectId) : undefined;
265
+ if (!project || typeof target.instanceId !== "string" || !target.instanceId) return { ok: false, error: "select a running project and current instance before reading a guidance probe" };
266
+ // A closed query: exactly one exact registered content id. Any other field is refused here rather than forwarded.
267
+ if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).some(key => key !== "id") || !probeSha256((input as { id?: unknown }).id))
268
+ return { ok: false, error: "invalid guidance probe query; use the exact 64-character probe id" };
269
+ const id = (input as { id: string }).id;
270
+ let client: ControlClient | undefined;
271
+ try {
272
+ client = await ControlClient.connect(project.stateDir, { role: "console", projectId: project.id, projectRoot: project.root, instanceId: target.instanceId });
273
+ if (!client.features.includes("guidance_probe_receipts")) return { ok: false, error: "running hub lacks guidance_probe_receipts; upgrade and restart the hub before reading a guidance probe" };
274
+ const result = await client.request({ t: "guidance_probe_receipts", id }, options.forwardTimeoutMs?.("guidance_probe_receipts", 10_000) ?? 10_000);
275
+ if (result.ok !== true) return { ok: false, error: typeof result.error === "string" ? result.error.slice(0, 512) : "guidance probe status is unavailable; refresh the probe id and the current daemon before retrying" };
276
+ const receipts = parseGuidanceProbeReceiptExport(result.receipts);
277
+ // The reply must be the experiment that was asked for: a well-formed export of another probe never satisfies this selection.
278
+ if (!receipts || receipts.status.id !== id) return { ok: false, error: "guidance probe receipts are malformed, fail their digest check or name another probe; do not rely on them" };
279
+ return { ok: true, receipts };
280
+ } catch { return { ok: false, error: "guidance probe status is unavailable; refresh the probe id or upgrade the hub before retrying" }; }
281
+ finally { client?.close(); }
282
+ };
283
+ return { list, act, answer, receipt, consoleControl, lineage, guidance, guidanceProbe };
261
284
  }
262
285
 
263
286
  export async function startManager(options: ManagerOptions = {}): Promise<ManagerHandle> {
@@ -32,7 +32,7 @@ export type ConductorLocalAction = typeof CONDUCTOR_LOCAL_ACTIONS[number];
32
32
  export const conductorLocalAction = (value:unknown): value is ConductorLocalAction => typeof value==="string" && (CONDUCTOR_LOCAL_ACTIONS as readonly string[]).includes(value);
33
33
  /** Daemon-authorized labels. Recovery labels pass the initial role check, then require their separate per-operation proof. */
34
34
  export const CONDUCTOR_DAEMON_OPERATIONS = ["roster add","roster remove","stop","queue show","queue resolve","queue discard","settings set","doctor orphans kill","logs","export",
35
- "board import","intake approve","schedule run","schedule pause","schedule resume","goal link","task unassign","guidance probe register","guidance probe start","guidance probe show","guidance probe cancel","restart","upgrade","recovery resume","recovery abort"] as const;
35
+ "board import","intake approve","schedule run","schedule pause","schedule resume","goal link","task unassign","guidance probe register","guidance probe start","guidance probe show","guidance probe receipts","guidance probe cancel","restart","upgrade","recovery resume","recovery abort"] as const;
36
36
  /**
37
37
  * #933: forms whose effect runs in the CLI process itself (local files). The daemon admits and audits them once at the handshake (`admit`),
38
38
  * after the CLI has validated their arguments. Recovery-bearing restart/upgrade forms use the separate source-issued continuation proof.
@@ -96,6 +96,7 @@ export function conductorOperation(command:string,args:readonly string[]): Condu
96
96
  case "register": return "guidance probe register";
97
97
  case "start": return "guidance probe start";
98
98
  case "show": return "guidance probe show";
99
+ case "receipts": return "guidance probe receipts";
99
100
  case "cancel": return "guidance probe cancel";
100
101
  }
101
102
  }
@@ -129,7 +130,7 @@ export function operationalRequestLabel(value:unknown):string|undefined {
129
130
  if(message.t==="task" && typeof message.op==="string" && Object.hasOwn(CONDUCTOR_TASK_OPS,message.op))return CONDUCTOR_TASK_OPS[message.op];
130
131
  if (typeof message.t === "string" && message.t.startsWith("guidance_probe_")) {
131
132
  const operation = message.t.slice("guidance_probe_".length);
132
- return ["register", "start", "show", "cancel"].includes(operation) ? `guidance probe ${operation}` : undefined;
133
+ return ["register", "start", "show", "receipts", "cancel"].includes(operation) ? `guidance probe ${operation}` : undefined;
133
134
  }
134
135
  if(message.t==="queue" && typeof message.op==="string" && ["show","resolve","discard"].includes(message.op))return `queue ${message.op}`;
135
136
  if(message.t==="settings_set"||message.t==="settings_preview")return "settings set";
@@ -0,0 +1,25 @@
1
+ /**
2
+ * #1399: a command the hub hands a person runs as printed. The first relay of `ahub queue resolve <id>` failed on its two required flags, the second on the
3
+ * revision and on which checkout hosts the hub, so every hint is built here with the values the hub already knows.
4
+ */
5
+ export interface DeliveryHint { id: string; revision?: number; state?: string; peer?: string; senders?: readonly string[]; kinds?: readonly string[] }
6
+
7
+ const word = (value: string) => value.replace(/[^\w.,:@~-]/g, "");
8
+ const shellPath = (path: string) => /^[\w./@:+-]+$/.test(path) ? path : `'${path.replace(/'/g, `'\\''`)}'`;
9
+
10
+ /** The other actions the row's state allows, one clause each: the hub cannot tell whether the peer handled an uncertain delivery. */
11
+ export const queueResolveChoices = (state?: string): string => state === "failed"
12
+ ? "discard drops it; use --action completed instead if it was already handled"
13
+ : "retry sends it again; use --action completed instead if the peer already handled it, or discard if it is stale";
14
+
15
+ /** `[cd <project> && ]ahub queue resolve <id> [--revision N] --action <suggested> --reason "<kind> from <sender> to <peer>"`. */
16
+ export function queueResolveCommand(row: DeliveryHint, project?: string): string {
17
+ const kinds = [...new Set(row.kinds ?? [])].map(word).filter(Boolean).join(","), senders = [...new Set(row.senders ?? [])].map(word).filter(Boolean).join(",");
18
+ const reason = [kinds, senders && `from ${senders}`, row.peer && `to ${word(row.peer)}`].filter(Boolean).join(" ") || "settled by the person";
19
+ return `${project ? `cd ${shellPath(project)} && ` : ""}ahub queue resolve ${row.id}${Number.isSafeInteger(row.revision) ? ` --revision ${row.revision}` : ""} --action ${row.state === "failed" ? "discard" : "retry"} --reason "${reason}"`;
20
+ }
21
+
22
+ /** The CLI's own argument rule for `ahub queue resolve`, shared with the test that proves a hint passes it. */
23
+ export function queueResolveArgsValid(action: string | undefined, reason: string | undefined, revision: string | undefined, extra: readonly string[]): boolean {
24
+ return !extra.length && ["completed", "retry", "discard"].includes(action ?? "") && !!reason?.trim() && (revision === undefined || (/^\d+$/.test(revision) && Number.isSafeInteger(Number(revision))));
25
+ }
@@ -1,3 +1,4 @@
1
+ import { queueResolveCommand } from "./person-command.ts";
1
2
  import { isClosedTaskState, type HistoryEntry, type Task, type TaskMoveReason, type TaskStall } from "./board.ts";
2
3
  import { sanitize, type Kind, type Priority } from "./envelope.ts";
3
4
 
@@ -139,11 +140,11 @@ export class SupervisionFeed {
139
140
  return sent;
140
141
  }
141
142
 
142
- needsReview(peer: string, deliveryId: string): boolean {
143
+ needsReview(peer: string, deliveryId: string, command: string | (() => string) = () => queueResolveCommand({ id: deliveryId, peer })): boolean { // a thunk is built only when the notice is sent, not on every tick
143
144
  const conductor = this.recipient();
144
145
  const key = `${conductor}:${peer}:${deliveryId}`;
145
146
  if (!conductor || this.holds.has(key)) return false;
146
- const sent = this.send(`hold:${peer}:${deliveryId}`, `${peer}: needs_review hold; delivery ${deliveryId}; ask the person to resolve it with ahub queue resolve`, "important");
147
+ const sent = this.send(`hold:${peer}:${deliveryId}`, `${peer}: needs_review hold; delivery ${deliveryId}; give the person this command exactly as printed: ${typeof command === "string" ? command : command()}`, "important");
147
148
  if (sent) this.holds.add(key);
148
149
  return sent;
149
150
  }
package/src/hub/tasks.ts CHANGED
@@ -3,8 +3,9 @@ import { pathCandidates } from "@staix/agent-mem";
3
3
  import { renderGuidanceVariantV1 } from "./guidance-variants.ts";
4
4
  import { GuidanceProbeFixtureHost, type GuidanceProbeStore } from "./guidance-probe-store.ts";
5
5
  import { GuidanceProbeError, GUIDANCE_PROBE_STOP_TIMEOUT_MS, GUIDANCE_PROBE_FENCE_INTERVAL_MS, guidanceProbeCanonical, guidanceProbeManifestKey,
6
- parseGuidanceProbeRegistration, probeHash, probeSha256, probeInteger, probeSessionGeneration,
6
+ parseGuidanceProbeRegistration, parseGuidanceProbeReceiptExport, probeHash, probeSha256, probeInteger, probeSessionGeneration,
7
7
  type ProbeChildBinding, type ProbeStoredState, type ProbePublicReceipt, type ProbePublicStatus, type ProbeHostBinding,
8
+ type ProbeReceiptExport, type ProbeExportSlot, type ProbeReceiptV1, type ProbeRetentionState,
8
9
  type ProbeAdmissionRecheck, type ProbeReservation, type ProbeSlot, type GuidanceProbeFakePorts, type GuidanceProbeManifestV1, type ProbeWorkerFramePreparer } from "./guidance-probes.ts";
9
10
  import { GuidanceVariantError, GUIDANCE_PAGE_MAX_RECORDS, GUIDANCE_REPLY_MAX_BYTES, guidanceVariantSectionDiff, guidanceProtectedSectionNames, parseGuidancePageResult, parseGuidanceDiffResult, parseGuidanceListQuery, parseGuidanceIdQuery, guidancePageCursor, guidancePageAfter, guidanceVariantMetadata, parseGuidanceVariantV1, validateGuidanceVariantV1, parseGuidanceSelector, type GuidanceVariantV1, type GuidanceStoredRecord, type GuidanceSelector, type GuidanceIdSelector, type GuidanceWriteFence, type GuidanceWriteReceipt, type GuidanceCurrent, type GuidancePublicRecord, type GuidancePageResult, type GuidanceDiffResult, type GuidanceReadResult } from "./guidance-variants.ts";
10
11
  import { buildEntryDiagnostic } from "./build-entry.ts";
@@ -3019,7 +3020,7 @@ export class Tasks {
3019
3020
  if (excluded.includes(peer)) continue;
3020
3021
  const queue = this.d.bus.queueSummary(peer), wip = this.wip(peer, task.id), limit = this.wipLimit(peer);
3021
3022
  if (wip >= limit) parts.push(`${peer} WIP full (${wip}/${limit}); no eligible planner WIP capacity`);
3022
- else if (queue.heldBy) parts.push(`${peer} has a held queue (a delivery is held; resolve it with ahub queue list)`);
3023
+ else if (queue.heldBy) parts.push(`${peer} has a held queue (delivery ${queue.heldBy} is held; ahub queue show ${queue.heldBy} prints the full resolve command for the person)`);
3023
3024
  else if (queue.needsReview > 0) parts.push(`${peer} has ${queue.needsReview} delivery(ies) in needs_review`);
3024
3025
  const refusal = queueBackpressure(peer, pressure.queueBackpressure, peerEntry(pressure.queues, peer), pressure.now ?? NaN);
3025
3026
  if (refusal) parts.push(`${peer} ${refusal.reason}`);
@@ -5129,7 +5130,50 @@ export class Tasks {
5129
5130
  }
5130
5131
  async guidanceProbeShow(by: PeerId, id: string): Promise<ProbePublicStatus> {
5131
5132
  const request = this.guidanceProbeRequest(by), state = this.guidanceProbeState(by, id, request.check);
5132
- request.check(); return this.guidanceProbeProjection(state);
5133
+ request.check();
5134
+ const status = this.guidanceProbeProjection(state);
5135
+ // T3 (#1226): the sealed receipts can only make the verdict stricter, never grant one the older expression refused. The reasons and the denominator stay in
5136
+ // the store's private status; public show keeps just this flag. A store that cannot be read is not comparable.
5137
+ if (!status.comparable) return status;
5138
+ let sealedComparable = false;
5139
+ try { sealedComparable = this.d.guidanceProbes!.store.outcome({ projectKey: this.guidanceProject(), id: state.receipt.id })?.comparability.comparable === true; } catch { /* fail closed */ }
5140
+ return sealedComparable ? status : { ...status, comparable: false };
5141
+ }
5142
+ /**
5143
+ * T4 (#1226): the producer receipt reader and export. The same person/conductor, session and task fences as `guidanceProbeShow`, and read-only: it launches,
5144
+ * reserves, writes and prunes nothing. It carries the status, the outcome denominator and the sealed receipts, each re-verified against its own digest by the
5145
+ * Store, so a tampered row refuses the whole read instead of being skipped. Output names are model-written, so each receipt passes the same screen as any
5146
+ * other public field; one that fails is replaced by its digest alone and the slot says `withheld`. A retained directory is a state, never a path.
5147
+ */
5148
+ async guidanceProbeReceipts(by: PeerId, id: string): Promise<ProbeReceiptExport> {
5149
+ const request = this.guidanceProbeRequest(by), state = this.guidanceProbeState(by, id, request.check);
5150
+ request.check();
5151
+ const store = this.d.guidanceProbes!.store, key = { projectKey: this.guidanceProject(), id: state.receipt.id };
5152
+ const status = await this.guidanceProbeShow(by, id);
5153
+ let receipts: ProbeReceiptV1[], outcome: ReturnType<GuidanceProbeStore["outcome"]>, retention: Map<string, ProbeRetentionState>;
5154
+ try { receipts = store.receipts(key); outcome = store.outcome(key); retention = store.retentionStates(key); }
5155
+ catch (error) { if (error instanceof GuidanceProbeError) throw error; throw new GuidanceProbeError("storage"); }
5156
+ if (!outcome) throw new GuidanceProbeError("storage");
5157
+ request.check();
5158
+ const bySlot = new Map(receipts.map(item => [item.slotId, item]));
5159
+ const slots: ProbeExportSlot[] = state.registration.manifest.slots.map((slot, index) => {
5160
+ const session = state.sessions[index]!, receipt = bySlot.get(slot.id);
5161
+ const shown = receipt !== undefined && this.guidanceProbeReceiptClear(receipt);
5162
+ return { slotId: slot.id, stage: slot.stage, role: slot.role, arm: slot.arm, state: session.state, receipt: shown ? receipt : null,
5163
+ receiptDigest: receipt?.digest ?? null, withheld: receipt !== undefined && !shown, retention: retention.get(slot.id) ?? "none" };
5164
+ });
5165
+ // The sealed verdict can only make the public one stricter, exactly as in `show`: a status that already refused stays refused.
5166
+ const comparable = status.comparable && outcome.comparability.comparable;
5167
+ const result: ProbeReceiptExport = { v: 1, status: { ...status, comparable }, comparable, reasons: outcome.comparability.reasons, counts: outcome.counts, slots };
5168
+ // What leaves this process is what the consumer's parser will accept: a result that does not round-trip is a storage fault, never a partial answer.
5169
+ const checked = parseGuidanceProbeReceiptExport(JSON.parse(JSON.stringify(result)));
5170
+ if (!checked) throw new GuidanceProbeError("storage");
5171
+ return checked;
5172
+ }
5173
+ /** Every free-text name a receipt carries (output paths, exclusions, the served model) must pass the public-field screen; the digest alone is kept otherwise. */
5174
+ private guidanceProbeReceiptClear(receipt: ProbeReceiptV1): boolean {
5175
+ const names = [receipt.experimentId, receipt.slotId, receipt.servedModel ?? "", ...receipt.output.entries.map(item => item.relative), ...receipt.output.excluded.map(item => item.relative)];
5176
+ return names.every(text => text === "" || this.guidanceFieldAllowed(text));
5133
5177
  }
5134
5178
  async guidanceProbeStart(by: PeerId, id: string, revision: number, variantId?: string): Promise<ProbePublicReceipt> {
5135
5179
  const request = this.guidanceProbeRequest(by), state = this.guidanceProbeState(by, id, request.check);
@@ -5180,6 +5224,7 @@ export class Tasks {
5180
5224
  return dependency.fakePorts!.launch(input, effects, signal);
5181
5225
  },
5182
5226
  stop: (input, signal) => dependency.fakePorts!.stop(input, signal),
5227
+ ...(dependency.fakePorts.discardRetained ? { discardRetained: record => dependency.fakePorts!.discardRetained!(record) } : {}),
5183
5228
  };
5184
5229
  let reserved = false, returned = false;
5185
5230
  const runner = new GuidanceProbeFixtureHost(dependency.store, { ports, revalidate: current, now: () => this.d.now?.() ?? Date.now(),
@@ -79,6 +79,8 @@ export interface ProbeLocalAdapterOptions {
79
79
  current(): void;
80
80
  /** Private minted-resource ownership notification, never an ordinary observer or authority source. */
81
81
  workspaceOwned?: (workspace: ProbeWorkspace) => void;
82
+ /** Host-owned directory (outside every workspace) where a session's declared output is retained. Without it nothing is retained, only hashed. */
83
+ retentionRoot?: string;
82
84
  fixture?: ProbeLocalFixturePorts;
83
85
  }
84
86
  export interface ProbeLocalAdapter {