@corca-org/ceal-host-win32-x64 1.0.23 → 1.0.24

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.
@@ -120,7 +120,7 @@ var client_wire_contract_default = {
120
120
  },
121
121
  command_request: {
122
122
  schema_name: "ceal.command_request",
123
- fields: ["schema_version", "argv", "operation", "client_nonce", "context_token", "request_context"],
123
+ fields: ["schema_version", "argv", "operation", "client_nonce", "context_token", "request_context", "materialize_result"],
124
124
  absolute_transport_max_bytes: 65536
125
125
  },
126
126
  command_resolution: {
@@ -166,7 +166,7 @@ var client_wire_contract_default = {
166
166
  },
167
167
  command_response: {
168
168
  schema_name: "ceal.command_response",
169
- fields: ["schema_version", "exit_code", "document", "operation_id", "visible_output_max_bytes", "local_delivery", "verified_artifact", "request_context"],
169
+ fields: ["schema_version", "exit_code", "document", "operation_id", "visible_output_max_bytes", "local_delivery", "verified_artifact", "request_context", "result_file"],
170
170
  descriptor_field: "verified_artifact",
171
171
  request_context_field: "request_context",
172
172
  required_fields: [
@@ -179,7 +179,8 @@ var client_wire_contract_default = {
179
179
  "visible_output_max_bytes",
180
180
  "local_delivery",
181
181
  "verified_artifact",
182
- "request_context"
182
+ "request_context",
183
+ "result_file"
183
184
  ],
184
185
  bare_document_fields: [
185
186
  "invocation",
@@ -448,6 +449,9 @@ var CEAL_OPERATION_READINESS_VALUES = vocabulary(["ready", "degraded", "unavaila
448
449
  var CEAL_TARGET_REQUIREMENTS = vocabulary(["required", "optional", "none"]);
449
450
  var CEAL_AUDIT_OUTCOMES = vocabulary(["succeeded", "denied", "failed"]);
450
451
  var CEAL_GATEWAY_PROVIDER_STEP_OUTCOMES = vocabulary(["completed", "rejected", "throttled", "failed"]);
452
+ var CEAL_GATEWAY_CORPUS_READ_PROVIDERS = vocabulary(["slack", "google_drive", "notion"]);
453
+ var CEAL_GATEWAY_CORPUS_READ_OUTCOMES = vocabulary(["answered_from_corpus", "live_fallback"]);
454
+ var CEAL_GATEWAY_CORPUS_READ_FALLBACK_REASONS = vocabulary(["uncovered_window", "stale", "not_organization_public", "partition_missing"]);
451
455
  var CEAL_GATEWAY_READ_REUSE_DISPOSITIONS = vocabulary(["response_cache_hit", "corpus_hit", "corpus_hit_after_revalidation", "corpus_partial_provider_supplement", "provider_direct", "provider_continuation", "reuse_unavailable"]);
452
456
  var CEAL_GATEWAY_READ_REUSE_UNAVAILABLE_REASONS = vocabulary(["not_reported", "storage_unavailable", "coverage_incomplete", "freshness_refresh_required", "not_reusable", "bypassed"]);
453
457
  var CEAL_GATEWAY_DERIVED_STORE_FAILURE_CLASSES = vocabulary(["storage_unavailable", "decode_mismatch", "write_conflict", "quota", "store_error"]);
@@ -488,6 +492,21 @@ var CEAL_GATEWAY_ORGANIZATION_ROUTE_FACT_CALL_KEYS = Object.freeze([
488
492
  ]);
489
493
 
490
494
  // packages/ceal-client-protocol/src/gateway-validation-primitives.ts
495
+ var POSIX_HOME_ROOTS = [["/", "home"].join(""), ["/", "Users"].join("")];
496
+ var WINDOWS_HOME_ROOT = ["C:", "\\", "Users"].join("");
497
+ var USER_SEGMENT_BODY = "[^/\\\\ \\t\\r\\n\"'`${}]+";
498
+ var POSIX_SEGMENT_END = "(?:/|$|(?=[\\s\"'`]))";
499
+ var WINDOWS_SEGMENT_END = "(?:\\\\+|$|(?=[\\s\"'`]))";
500
+ var WINDOWS_USER_SEGMENT_BODY = "[^\\\\ \\t\\r\\n\"'`${}]+";
501
+ var ABSOLUTE_PATH_BOUNDARY = "(?<![A-Za-z0-9_])";
502
+ function escapePathPattern(value) {
503
+ return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
504
+ }
505
+ function machineHomePathPatterns(flags) {
506
+ const posix5 = `${ABSOLUTE_PATH_BOUNDARY}(?:${POSIX_HOME_ROOTS.map(escapePathPattern).join("|")})/${USER_SEGMENT_BODY}${POSIX_SEGMENT_END}`;
507
+ const windows = `${ABSOLUTE_PATH_BOUNDARY}${escapePathPattern(WINDOWS_HOME_ROOT)}\\\\+${WINDOWS_USER_SEGMENT_BODY}${WINDOWS_SEGMENT_END}`;
508
+ return [new RegExp(posix5, flags), new RegExp(windows, flags)];
509
+ }
491
510
  var CealProtocolValidationError = class extends Error {
492
511
  name = "CealProtocolValidationError";
493
512
  code;
@@ -843,6 +862,7 @@ var CLIENT_HOST_RELEASE_MISMATCH = "Install or upgrade the Ceal CLI and Host Rel
843
862
  var HOST_INSTALL_REPAIR = "The local Host or Relay is missing, stale, or unavailable. Run `ceal-host install`, then `ceal-host discovery sync`, and retry from a new producer conversation.";
844
863
  var HOST_CONTEXT_UNAVAILABLE = "The Host could not select this turn; reason uncertain. Host mode is unavailable in an ephemeral side conversation. When you know you are in one, `ceal --standalone ...` uses your configured Ceal session/Gateway permissions, without Host session/turn correlation or Host usage attribution. Unknown-outcome `repeat_request` needs the same Host turn or explicit `--request-context`. Otherwise return to the original regular conversation. Host refusal never switches modes; report intended Host calls as a gap.";
845
864
  var SESSION_CONTEXT_UNAVAILABLE = "The local Gateway session context is unavailable.";
865
+ var SESSION_ADOPT_RECOVERY = "The refresh Session is no longer usable. Run `ceal session adopt --gateway <origin> --email <email>` to complete mailbox-confirmed recovery.";
846
866
  function guidance(message, next_action, http_status, retryable = false, redaction_class = "model_safe") {
847
867
  return Object.freeze({ message, next_action, http_status, retryable, redaction_class });
848
868
  }
@@ -863,13 +883,18 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
863
883
  context_not_selected: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
864
884
  context_store_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
865
885
  context_store_conflict: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
866
- refresh_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
867
- refresh_expired: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
868
- refresh_replayed: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
869
- refresh_revoked: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
870
- person_inactive: guidance("The Person is inactive, so the Gateway refused this refresh without revoking the Session family.", "ask_admin", 403),
871
- principal_inactive: guidance("The Principal is inactive, so the Gateway refused this refresh without revoking the Session family.", "ask_admin", 403),
872
- refresh_recovery_unavailable: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
886
+ refresh_invalid: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
887
+ refresh_expired: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
888
+ refresh_replayed: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
889
+ refresh_revoked: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
890
+ person_inactive: guidance("The Person is inactive, so the Gateway refused this refresh without revoking the Session family. Ask an Admin to reactivate the Person, then retry this same session refresh.", "ask_admin", 403),
891
+ principal_inactive: guidance("The Principal is inactive, so the Gateway refused this refresh without revoking the Session family. Ask an Admin to reactivate the Principal, then retry this same session refresh.", "ask_admin", 403),
892
+ authority_replaced: guidance("The Gateway authority has been replaced; this session is no longer valid here. Run `ceal session adopt --gateway <origin> --email <email>` against the current Gateway to complete mailbox-confirmed recovery.", "repair_or_adopt_session", 409),
893
+ refresh_inactive: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 410),
894
+ refresh_recovery_unavailable: guidance("The Gateway's durable refresh-recovery key is unavailable. Retry the same refresh attempt after the key is available.", "retry", 503, true),
895
+ refresh_recovery_outcome_unavailable: guidance("The Gateway could not safely recover the outcome of a prior refresh. Ask an administrator to inspect the Gateway session state before retrying or adopting this session.", "ask_admin", 503),
896
+ refresh_state_unavailable: guidance("The Gateway session state store is temporarily unavailable; retry the same refresh attempt when it is available.", "retry", 503, true),
897
+ refresh_recovery_expired: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 410),
873
898
  refresh_custody_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
874
899
  session_store_unwritable: guidance("The Ceal client could not write its local session store; the operating system refused the write (EACCES, EPERM, or EROFS). rerun_outside_agent_sandbox reruns it with escalated execution.", "rerun_outside_agent_sandbox", 500),
875
900
  local_output_exists: guidance("The selected local output path already exists; nothing was written to it.", "choose_new_output_path", 400),
@@ -884,10 +909,8 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
884
909
  resource_stream_failed: guidance("The provider resource stream failed; ask an administrator to inspect the Gateway failure log.", "ask_admin", 500),
885
910
  gateway_unavailable: guidance(GATEWAY_TRANSPORT_UNAVAILABLE, "ask_admin", 503, true),
886
911
  contract_mismatch: guidance(CLIENT_HOST_RELEASE_MISMATCH, "upgrade_ceal_client", 409),
887
- // `gateway_starting` is the one retryable envelope the serving gate answers on every route while starting
888
- // (`cli/internal/client/gateway_startup_wait.go` re-drives it); the sentence is the client default that renders
889
- // when the wait ends still unserved, moved from the `localFailureText` default branch.
890
- [CEAL_GATEWAY_STARTING_FAILURE_CODE]: guidance(LOCAL_TRANSPORT_INCOMPLETE, "answer_with_gap", 503, true),
912
+ // The serving gate answers before refresh execution, so retrying the same attempt is safe.
913
+ [CEAL_GATEWAY_STARTING_FAILURE_CODE]: guidance("The Gateway is still starting; the refresh was not attempted and the refresh token was not consumed. Retry the same refresh attempt after the Gateway is serving.", "retry", 503, true),
891
914
  gateway_internal_error: guidance("The Gateway failed without exposing internal state; report this as a gap.", "answer_with_gap", 500),
892
915
  // The serving gate emits this code with no message; the sentence is the owner-normalized form of the
893
916
  // `gateway_internal_error` guidance (decided with the operator 2026-10-13).
@@ -899,6 +922,8 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
899
922
  // The safe move varies by request. Keep the sentence conditional on the
900
923
  // same `retryable` and `next_action` facts the response exposes.
901
924
  unknown_outcome: guidance("The transport outcome is unknown; use retryable and next_action to decide whether it can be repeated.", "answer_with_gap", 500),
925
+ // A provider write the Gateway command deadline cut after its dispatch: the write left and its receipt is still settling, so the caller reads the receipt instead of repeating the write.
926
+ write_in_progress: guidance("The provider write was dispatched but the Gateway command deadline cut the wait before its outcome settled. Do not repeat the write; read the durable receipt named by write_request_ref with write_receipt.get.", "write_receipt.get", 500),
902
927
  // Restored verbatim from the retired `localFailureText`
903
928
  // `refresh_unknown_outcome` case: a refresh that ends unknown leaves the
904
929
  // session context unavailable, so the caller repairs or adopts the
@@ -1548,6 +1573,8 @@ var CEAL_ACTIVITY_TIMESTAMP_BASES = vocabulary([
1548
1573
  "review_submitted",
1549
1574
  "comment_created",
1550
1575
  "reaction_created",
1576
+ "pull_request_merged",
1577
+ "release_published",
1551
1578
  "ceal_write_completed",
1552
1579
  "event_start",
1553
1580
  "all_day_start",
@@ -1559,7 +1586,7 @@ var CEAL_ACTIVITY_TIMESTAMP_BASES = vocabulary([
1559
1586
  "page_last_edited",
1560
1587
  "resource_modified"
1561
1588
  ]);
1562
- var CEAL_ACTIVITY_CONNECTOR_KINDS = vocabulary(["slack", "github", "google-calendar", "google-drive", "notion"]);
1589
+ var CEAL_ACTIVITY_CONNECTOR_KINDS = vocabulary(["slack", "github", "google-calendar", "google-drive", "google-mail", "notion"]);
1563
1590
  var CEAL_ACTIVITY_UNSUPPORTED_EVENT_KIND_CODE = "unsupported_event_kind";
1564
1591
  var CEAL_ACTIVITY_GAP_CODES = vocabulary([
1565
1592
  "provider_page_budget",
@@ -1580,6 +1607,8 @@ var CEAL_ACTIVITY_EVENT_KINDS = vocabulary([
1580
1607
  "github.pull_request.opened",
1581
1608
  "github.issue.edited",
1582
1609
  "github.pull_request.edited",
1610
+ "github.pull_request.merged",
1611
+ "github.release.published",
1583
1612
  "github.review.submitted",
1584
1613
  "github.issue_comment.created",
1585
1614
  "github.review_comment.created",
@@ -1593,6 +1622,7 @@ var CEAL_ACTIVITY_EVENT_KINDS = vocabulary([
1593
1622
  "drive.file.created",
1594
1623
  "drive.file.modified",
1595
1624
  "drive.file.viewed",
1625
+ "mail.sent",
1596
1626
  "notion.page.created",
1597
1627
  "notion.page.edited"
1598
1628
  ]);
@@ -1606,6 +1636,8 @@ var CEAL_ACTIVITY_EVENT_TIMESTAMP_BASIS_MAP = Object.freeze({
1606
1636
  "github.review_comment.created": "comment_created",
1607
1637
  "github.issue.opened": "resource_created",
1608
1638
  "github.pull_request.opened": "resource_created",
1639
+ "github.pull_request.merged": "pull_request_merged",
1640
+ "github.release.published": "release_published",
1609
1641
  "github.issue.edited": "resource_modified",
1610
1642
  "github.pull_request.edited": "resource_modified",
1611
1643
  "github.reaction.created": "reaction_created",
@@ -1616,6 +1648,7 @@ var CEAL_ACTIVITY_EVENT_TIMESTAMP_BASIS_MAP = Object.freeze({
1616
1648
  "drive.file.created": "file_created",
1617
1649
  "drive.file.modified": "file_modified_by_me",
1618
1650
  "drive.file.viewed": "file_viewed_by_me",
1651
+ "mail.sent": "message_created",
1619
1652
  "notion.page.created": "page_created",
1620
1653
  "notion.page.edited": "page_last_edited"
1621
1654
  });
@@ -1726,6 +1759,8 @@ var CEAL_REFRESH_FAILURE_CODES = vocabulary([
1726
1759
  "principal_inactive",
1727
1760
  "authority_replaced",
1728
1761
  "refresh_recovery_unavailable",
1762
+ "refresh_recovery_outcome_unavailable",
1763
+ "refresh_state_unavailable",
1729
1764
  "refresh_recovery_expired",
1730
1765
  // The serving gate answers this while the Gateway is still starting and the
1731
1766
  // refresh was never attempted; the same attempt stays retryable. It is never
@@ -2487,6 +2522,211 @@ var CEAL_SUPPORTED_GATEWAY_PROTOCOL_RANGE = Object.freeze({
2487
2522
  maximum: CEAL_PROTOCOL_VERSION
2488
2523
  });
2489
2524
 
2525
+ // packages/ceal-client-protocol/src/operator-diagnostic.ts
2526
+ var OPERATOR_DIAGNOSTIC_MAX_BYTES = 2048;
2527
+ var OPERATOR_DIAGNOSTIC_MAX_CAUSES = 8;
2528
+ var OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT = 512;
2529
+ var OPERATOR_DIAGNOSTIC_PATH_LIMIT = 1024;
2530
+ var OPERATOR_DIAGNOSTIC_STREAM_TAIL_LIMIT = 256;
2531
+ var OPERATOR_DIAGNOSTIC_HOME_PATHS = machineHomePathPatterns("gu");
2532
+ function redactOperatorDiagnosticSecrets(value) {
2533
+ return value.replace(/\bBearer\s+[A-Za-z0-9._~+/=-]+/giu, "Bearer [redacted]").replace(/(["']?(?:authorization|[A-Za-z0-9_-]*(?:token|secret|credential|password|key))["']?\s*[:=]\s*)(?!(?:"unknown"|'unknown'|unknown\b))(?:"[^"]*"|'[^']*'|[^\s,;}]+)/giu, "$1[redacted]");
2534
+ }
2535
+ function redactOperatorDiagnosticText(value) {
2536
+ const normalized = normalizeCealSingleLineText(value);
2537
+ return normalizeCealSingleLineText(redactOperatorDiagnosticSecrets(redactFilePaths(redactHomePaths(redactUrls(normalized)))));
2538
+ }
2539
+ function renderOperatorDiagnostic(value) {
2540
+ const state = collectDiagnosticState(value);
2541
+ const fields = [
2542
+ state.status === void 0 ? void 0 : `status=${JSON.stringify(safeDiagnosticText(state.status))}`,
2543
+ state.exitCode === void 0 ? void 0 : `exit_code=${state.exitCode}`,
2544
+ state.stdout === void 0 ? void 0 : `stdout_tail=${JSON.stringify(tail(state.stdout))}`,
2545
+ state.stderr === void 0 ? void 0 : `stderr_tail=${JSON.stringify(tail(state.stderr))}`,
2546
+ state.causes.length === 0 ? void 0 : `causes=${state.causes.map(formatCause).join(" <- ")}`
2547
+ ].filter((field) => field !== void 0);
2548
+ const rendered = fields.length === 0 ? "unknown_failure" : fields.join(" ");
2549
+ return truncateUtf8(rendered, OPERATOR_DIAGNOSTIC_MAX_BYTES);
2550
+ }
2551
+ function collectDiagnosticState(value) {
2552
+ const state = { causes: [], status: void 0, exitCode: void 0, stdout: void 0, stderr: void 0 };
2553
+ const visited = /* @__PURE__ */ new Set(), pending = [value];
2554
+ while (pending.length > 0 && state.causes.length < OPERATOR_DIAGNOSTIC_MAX_CAUSES) {
2555
+ const current = pending.shift();
2556
+ if (current !== void 0) visitDiagnosticNode(current, state, pending, visited);
2557
+ }
2558
+ return state;
2559
+ }
2560
+ function visitDiagnosticNode(current, state, pending, visited) {
2561
+ if (isObject(current)) {
2562
+ if (visited.has(current)) return;
2563
+ visited.add(current);
2564
+ }
2565
+ captureProcessEvidence(current, state);
2566
+ appendCause(current, state.causes);
2567
+ enqueueCauseChildren(current, state.causes.length, pending);
2568
+ }
2569
+ function captureProcessEvidence(current, state) {
2570
+ if (state.status === void 0) state.status = safeStatus(read(current, "status"));
2571
+ if (state.exitCode === void 0) state.exitCode = safeExitCode(read(current, "exitCode")) ?? safeExitCode(read(current, "status")) ?? safeExitCode(read(current, "code"));
2572
+ if (state.stdout === void 0) state.stdout = outputText(read(current, "stdout"));
2573
+ if (state.stderr === void 0) state.stderr = outputText(read(current, "stderr"));
2574
+ }
2575
+ function appendCause(current, causes) {
2576
+ const errors = read(current, "errors");
2577
+ if (current instanceof Error && (!(current instanceof AggregateError) || !Array.isArray(errors) || errors.length === 0)) {
2578
+ causes.push(errorCause(current));
2579
+ return;
2580
+ }
2581
+ if (!isObject(current)) {
2582
+ const message = safeText(current);
2583
+ if (message !== void 0) causes.push(Object.freeze({ error_class: typeof current, message }));
2584
+ }
2585
+ }
2586
+ function errorCause(error) {
2587
+ const name = safeText(read(error, "name")) ?? "Error";
2588
+ const message = safeText(read(error, "message"));
2589
+ const codeValue = read(error, "code");
2590
+ const code2 = typeof codeValue === "number" && Number.isFinite(codeValue) ? codeValue : safeText(codeValue);
2591
+ const errnoValue = read(error, "errno");
2592
+ const errno = typeof errnoValue === "number" && Number.isSafeInteger(errnoValue) ? errnoValue : void 0;
2593
+ const syscall = safeText(read(error, "syscall"));
2594
+ const path = safePath(read(error, "path"));
2595
+ return Object.freeze({ error_class: name, ...message === void 0 ? {} : { message }, ...code2 === void 0 ? {} : { code: code2 }, ...errno === void 0 ? {} : { errno }, ...syscall === void 0 ? {} : { syscall }, ...path === void 0 ? {} : { path } });
2596
+ }
2597
+ function enqueueCauseChildren(current, causeCount, pending) {
2598
+ const cause = read(current, "cause");
2599
+ if (cause !== void 0) pending.push(cause);
2600
+ const errors = read(current, "errors");
2601
+ if (Array.isArray(errors)) pending.push(...errors.slice(0, OPERATOR_DIAGNOSTIC_MAX_CAUSES - causeCount));
2602
+ }
2603
+ function isObject(value) {
2604
+ return typeof value === "object" && value !== null;
2605
+ }
2606
+ function formatCause(cause) {
2607
+ const fields = [
2608
+ cause.error_class,
2609
+ cause.code === void 0 ? void 0 : `code=${JSON.stringify(safeDiagnosticText(cause.code))}`,
2610
+ cause.errno === void 0 ? void 0 : `errno=${cause.errno}`,
2611
+ cause.syscall === void 0 ? void 0 : `syscall=${JSON.stringify(cause.syscall)}`,
2612
+ cause.path === void 0 ? void 0 : `path=${JSON.stringify(cause.path)}`,
2613
+ cause.message === void 0 ? void 0 : `message=${cause.message}`
2614
+ ].filter((field) => field !== void 0);
2615
+ return fields.join(" ");
2616
+ }
2617
+ function tail(value) {
2618
+ const clipped = value.length <= OPERATOR_DIAGNOSTIC_STREAM_TAIL_LIMIT ? value : `…${value.slice(-OPERATOR_DIAGNOSTIC_STREAM_TAIL_LIMIT)}`;
2619
+ return safeDiagnosticText(clipped);
2620
+ }
2621
+ function safeText(value) {
2622
+ if (typeof value !== "string") return void 0;
2623
+ const safe = safeDiagnosticText(value);
2624
+ if (safe.length === 0) return void 0;
2625
+ if (safe.length <= OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT) return safe;
2626
+ const head = Math.floor(OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT / 2);
2627
+ const tail2 = OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT - head - 1;
2628
+ return `${safe.slice(0, head)}…${safe.slice(-tail2)}`;
2629
+ }
2630
+ function safePath(value) {
2631
+ if (typeof value !== "string") return void 0;
2632
+ const safe = safeDiagnosticText(value);
2633
+ if (safe.length === 0) return void 0;
2634
+ if (safe.length <= OPERATOR_DIAGNOSTIC_PATH_LIMIT) return safe;
2635
+ const head = Math.floor(OPERATOR_DIAGNOSTIC_PATH_LIMIT / 2);
2636
+ const tail2 = OPERATOR_DIAGNOSTIC_PATH_LIMIT - head - 1;
2637
+ return `${safe.slice(0, head)}…${safe.slice(-tail2)}`;
2638
+ }
2639
+ function safeDiagnosticText(value) {
2640
+ return redactOperatorDiagnosticText(String(value));
2641
+ }
2642
+ function outputText(value) {
2643
+ if (typeof value === "string") return redactOperatorDiagnosticText(value);
2644
+ if (value instanceof Uint8Array) {
2645
+ try {
2646
+ return redactOperatorDiagnosticText(new TextDecoder().decode(value));
2647
+ } catch {
2648
+ return void 0;
2649
+ }
2650
+ }
2651
+ return void 0;
2652
+ }
2653
+ function safeStatus(value) {
2654
+ if (typeof value === "number" && Number.isFinite(value)) return value;
2655
+ return typeof value === "string" ? safeText(value) : void 0;
2656
+ }
2657
+ function safeExitCode(value) {
2658
+ return typeof value === "number" && Number.isSafeInteger(value) ? value : void 0;
2659
+ }
2660
+ function read(value, key) {
2661
+ if (typeof value !== "object" && typeof value !== "function" || value === null) return void 0;
2662
+ try {
2663
+ return Reflect.get(value, key);
2664
+ } catch {
2665
+ return void 0;
2666
+ }
2667
+ }
2668
+ function redactHomePaths(value) {
2669
+ const paths = [
2670
+ ...OPERATOR_DIAGNOSTIC_HOME_PATHS.flatMap((pattern) => [...value.matchAll(pattern)].map((match) => homePathRange(value, match, matchedHomePrefixLength(match[0])))),
2671
+ ...configuredHomePathPatterns().flatMap(({ pattern, prefixLength }) => [...value.matchAll(pattern)].map((match) => homePathRange(value, match, prefixLength)))
2672
+ ];
2673
+ paths.sort((left, right) => left.start - right.start || right.end - left.end);
2674
+ let output = "";
2675
+ let cursor = 0;
2676
+ for (const path of paths) {
2677
+ if (path.start < cursor) continue;
2678
+ output += `${value.slice(cursor, path.start)}[home path redacted]${value.slice(path.prefixEnd, path.end)}`;
2679
+ cursor = path.end;
2680
+ }
2681
+ return output + value.slice(cursor);
2682
+ }
2683
+ function configuredHomePathPatterns() {
2684
+ const homes = [...new Set([process.env.HOME, process.env.USERPROFILE].filter((home) => home !== void 0 && home.length > 0))];
2685
+ return homes.flatMap((home) => {
2686
+ const root = home.replace(/[\\/]+$/gu, "");
2687
+ if (root.length === 0 || root === "/" || /^[A-Za-z]:$/u.test(root)) return [];
2688
+ const pattern = new RegExp(`(?<![A-Za-z0-9_])${escapePathPattern(root)}(?=$|[\\\\/\\s"'\`<>(){}\\[\\],;])`, /^[A-Za-z]:[\\/]/u.test(root) ? "giu" : "gu");
2689
+ return [{ pattern, prefixLength: root.length }];
2690
+ });
2691
+ }
2692
+ function matchedHomePrefixLength(value) {
2693
+ let separators = 0;
2694
+ for (let index = 0; index < value.length; index += 1) {
2695
+ if (value[index] !== "/" && value[index] !== "\\") continue;
2696
+ separators += 1;
2697
+ if (separators === 3) return index;
2698
+ }
2699
+ return value.length;
2700
+ }
2701
+ function redactUrls(value) {
2702
+ return value.replaceAll(/https?:\/\/[^\s"'<>]+/giu, "[url redacted]");
2703
+ }
2704
+ function redactFilePaths(value) {
2705
+ return value.replaceAll(/(?<![A-Za-z0-9._-]|\[home path redacted\])(?:[A-Za-z]:[\\/]|\\\\[^\\\s]+\\|\/)[^:\r\n"'<>]*?(?=:\d+(?::\d+)?(?:[:\s]|$)|[\r\n]|["'])/gu, "[path redacted]");
2706
+ }
2707
+ function homePathRange(value, match, prefixLength) {
2708
+ const index = match.index;
2709
+ if (index === void 0) return { start: value.length, end: value.length, prefixEnd: value.length };
2710
+ const start = index;
2711
+ let end = start + match[0].length;
2712
+ const quote = start > 0 && (value[start - 1] === "'" || value[start - 1] === '"') ? value[start - 1] : void 0;
2713
+ if (quote !== void 0) {
2714
+ const closing = value.indexOf(quote, end);
2715
+ if (closing >= 0) end = closing;
2716
+ }
2717
+ while (end < value.length && !/[\s"'`<>(){}[\],;]/u.test(value[end] ?? "")) end += 1;
2718
+ return { start, end, prefixEnd: Math.min(start + prefixLength, end) };
2719
+ }
2720
+ function truncateUtf8(value, maxBytes) {
2721
+ if (byteLength(value) <= maxBytes) return value;
2722
+ let output = "";
2723
+ for (const character of value) {
2724
+ if (byteLength(`${output}${character}…`) > maxBytes) break;
2725
+ output += character;
2726
+ }
2727
+ return `${output}…`;
2728
+ }
2729
+
2490
2730
  // packages/ceal-client-protocol/src/admin-projection-vocabulary.ts
2491
2731
  var ADMIN_PROJECTION_STATES = vocabulary(["ready", "empty", "partial", "unknown"]);
2492
2732
  var ADMIN_VIEW_KINDS = vocabulary(["request_detail", "resource_access_timeline", "weekly_usage"]);
@@ -3146,9 +3386,9 @@ async function readTranscriptCompleteChunk(handle, offset, size) {
3146
3386
  let lastNewline = -1;
3147
3387
  while (position < size) {
3148
3388
  const buffer = Buffer.alloc(Math.min(HOST_TRANSCRIPT_READ_CHUNK_BYTES, size - position));
3149
- const read = await handle.read(buffer, 0, buffer.length, position);
3150
- if (read.bytesRead === 0) break;
3151
- const chunk = buffer.subarray(0, read.bytesRead);
3389
+ const read2 = await handle.read(buffer, 0, buffer.length, position);
3390
+ if (read2.bytesRead === 0) break;
3391
+ const chunk = buffer.subarray(0, read2.bytesRead);
3152
3392
  chunks.push(chunk);
3153
3393
  const newline = chunk.lastIndexOf(10);
3154
3394
  if (newline >= 0) lastNewline = total + newline;
@@ -3321,15 +3561,15 @@ var HostProducerDrainCore = class {
3321
3561
  return run;
3322
3562
  }
3323
3563
  async drainLocked() {
3324
- const read = await this.host.listEnvelopes();
3564
+ const read2 = await this.host.listEnvelopes();
3325
3565
  let removed = 0;
3326
3566
  let expired = 0;
3327
- for (const envelope of read.entries) {
3567
+ for (const envelope of read2.entries) {
3328
3568
  if (Date.parse(this.host.expiresAtOf(envelope)) <= this.now().getTime()) expired += 1;
3329
3569
  else removed += 1;
3330
3570
  await this.host.removeEnvelope(envelope);
3331
3571
  }
3332
- return { removed, expired, malformed: read.malformed };
3572
+ return { removed, expired, malformed: read2.malformed };
3333
3573
  }
3334
3574
  };
3335
3575
 
@@ -3779,14 +4019,14 @@ var HostUsageFactsStore = class {
3779
4019
  const gate = new Promise((resolve2) => {
3780
4020
  release = resolve2;
3781
4021
  });
3782
- const tail = previous.then(() => gate);
3783
- SESSION_TRANSITION_TAILS.set(key, tail);
4022
+ const tail2 = previous.then(() => gate);
4023
+ SESSION_TRANSITION_TAILS.set(key, tail2);
3784
4024
  await previous;
3785
4025
  try {
3786
4026
  return await run();
3787
4027
  } finally {
3788
4028
  release?.();
3789
- if (SESSION_TRANSITION_TAILS.get(key) === tail) SESSION_TRANSITION_TAILS.delete(key);
4029
+ if (SESSION_TRANSITION_TAILS.get(key) === tail2) SESSION_TRANSITION_TAILS.delete(key);
3790
4030
  }
3791
4031
  }
3792
4032
  sessionPath(producer, hostSourceRef, hostSessionRef) {
@@ -4047,29 +4287,46 @@ var HostUsageTranscriptSourceError = class extends Error {
4047
4287
  this.name = "HostUsageTranscriptSourceError";
4048
4288
  }
4049
4289
  };
4050
- async function readHostUsageTranscriptSource(read) {
4290
+ async function readHostUsageTranscriptSource(read2) {
4051
4291
  try {
4052
- return await read();
4292
+ return await read2();
4053
4293
  } catch (error) {
4054
4294
  throw new HostUsageTranscriptSourceError({ cause: error });
4055
4295
  }
4056
4296
  }
4057
- async function captureNextHostUsageRegistration(registrations, startIndex, capture) {
4058
- if (registrations.length === 0) return { captured: false, nextIndex: startIndex, failed: false };
4059
- let failed = false;
4060
- for (let attempt = 0; attempt < registrations.length; attempt += 1) {
4061
- const index = (startIndex + attempt) % registrations.length;
4062
- const registration = registrations[index];
4063
- if (registration === void 0) continue;
4064
- try {
4065
- if (await capture(registration)) return { captured: true, nextIndex: (index + 1) % registrations.length, failed };
4066
- } catch (error) {
4067
- if (!(error instanceof HostUsageTranscriptSourceError)) throw error;
4297
+ var HostUsageRegistrationCapture = class {
4298
+ nextIndex = 0;
4299
+ producer;
4300
+ diagnosticSink;
4301
+ constructor(producer, diagnosticSink) {
4302
+ this.producer = producer;
4303
+ this.diagnosticSink = diagnosticSink;
4304
+ }
4305
+ async captureNext(registrations, capture) {
4306
+ let failed = false;
4307
+ let captured = false;
4308
+ const onFailure = () => {
4068
4309
  failed = true;
4310
+ };
4311
+ for (let attempt = 0; attempt < registrations.length; attempt += 1) {
4312
+ const index = (this.nextIndex + attempt) % registrations.length;
4313
+ const registration = registrations[index];
4314
+ if (registration === void 0) continue;
4315
+ try {
4316
+ captured = await capture(registration, onFailure);
4317
+ if (captured) {
4318
+ this.nextIndex = (index + 1) % registrations.length;
4319
+ break;
4320
+ }
4321
+ } catch (error) {
4322
+ if (!(error instanceof HostUsageTranscriptSourceError)) throw error;
4323
+ onFailure();
4324
+ }
4069
4325
  }
4326
+ if (failed) writeHostServiceDiagnostic(this.producer, "usage_capture_failed", void 0, "capture_failed", this.diagnosticSink);
4327
+ return captured;
4070
4328
  }
4071
- return { captured: false, nextIndex: startIndex, failed };
4072
- }
4329
+ };
4073
4330
  async function openHostUsageTranscriptCursor(input) {
4074
4331
  const handle = await readHostUsageTranscriptSource(() => openNoFollow(input.path, constants3.O_RDONLY));
4075
4332
  let source;
@@ -4579,6 +4836,13 @@ var ClaudeOutboxStore = class {
4579
4836
  await this.removeStateFile(this.registrationPath(registration.host_source_ref, registration.host_session_ref));
4580
4837
  await this.removeStateFile(this.cursorPath(registration.host_source_ref, registration.host_session_ref));
4581
4838
  }
4839
+ async readTranscriptRegistration(hostSourceRef, hostSessionRef) {
4840
+ if (!SAFE_REF2.test(hostSourceRef) || !SAFE_REF2.test(hostSessionRef)) throw new ClaudeHostError("invalid_input", "Claude transcript session identity is invalid.");
4841
+ await this.prepare();
4842
+ const registration = await this.readRegistrationFile(this.registrationPath(hostSourceRef, hostSessionRef));
4843
+ if (registration !== null && (registration.host_source_ref !== hostSourceRef || registration.host_session_ref !== hostSessionRef)) throw new ClaudeHostError("storage", "Claude transcript registration identity does not match its session.");
4844
+ return registration;
4845
+ }
4582
4846
  async listTranscriptRegistrations() {
4583
4847
  await this.prepare();
4584
4848
  const registrations = [];
@@ -4826,10 +5090,42 @@ function sameKeys2(value, required, optional = []) {
4826
5090
 
4827
5091
  // host/claude/src/claude-transcript-watcher.ts
4828
5092
  import { readdir as readdir2 } from "node:fs/promises";
5093
+ import { isDeepStrictEqual } from "node:util";
4829
5094
  import { join as join5 } from "node:path";
5095
+
5096
+ // host/claude/src/claude-subagent-overflow-checkpoint.ts
5097
+ var ClaudeSubagentOverflowCheckpoint = class {
5098
+ observed = /* @__PURE__ */ new Map();
5099
+ prune(registrations) {
5100
+ const current = new Set(registrations.map(registrationKey));
5101
+ for (const key of this.observed.keys()) if (!current.has(key)) this.observed.delete(key);
5102
+ }
5103
+ clear(registration) {
5104
+ this.observed.delete(registrationKey(registration));
5105
+ }
5106
+ /** Names follow the producer's sorted inventory; only omitted names define overflow. */
5107
+ async observe(registration, names, report) {
5108
+ const key = registrationKey(registration);
5109
+ if (names.length <= CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES) {
5110
+ this.clear(registration);
5111
+ return false;
5112
+ }
5113
+ const digest2 = transcriptObjectSha256(names.slice(CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES));
5114
+ if (this.observed.get(key) === digest2) return false;
5115
+ if (!await report()) return false;
5116
+ this.observed.set(key, digest2);
5117
+ return true;
5118
+ }
5119
+ };
5120
+ function registrationKey(registration) {
5121
+ return JSON.stringify([registration.host_source_ref, registration.host_session_ref, registration.transcript_path]);
5122
+ }
5123
+
5124
+ // host/claude/src/claude-transcript-watcher.ts
4830
5125
  var TOKEN_OBSERVATION_SOURCE = "claude_transcript.message.usage";
4831
5126
  var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
4832
5127
  store;
5128
+ overflow = new ClaudeSubagentOverflowCheckpoint();
4833
5129
  diagnostic;
4834
5130
  constructor(options) {
4835
5131
  super(options, {
@@ -4844,7 +5140,9 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
4844
5140
  return registration.transcript_path;
4845
5141
  }
4846
5142
  async listRegistrations() {
4847
- return this.store.listTranscriptRegistrations();
5143
+ const registrations = await this.store.listTranscriptRegistrations();
5144
+ this.overflow.prune(registrations);
5145
+ return registrations;
4848
5146
  }
4849
5147
  async scanOpened(handle, registration) {
4850
5148
  const { size, device, inode } = await ownedClaudeTranscriptFile(handle);
@@ -4856,7 +5154,7 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
4856
5154
  }
4857
5155
  if (preflight.checkpointPending) await this.store.writeTranscriptCursor({ ...cursor, updated_at: this.stamp() });
4858
5156
  const draft = mutableCursor(cursor);
4859
- await this.scanOpenedTranscript(registration, handle, draft, size, device, inode);
5157
+ await this.scanOpenedTranscript(registration, handle, cursor, draft, size, device, inode);
4860
5158
  return { records: draft.consumed, enqueued: draft.enqueued, quarantined: false };
4861
5159
  }
4862
5160
  async scanFailed(handle, registration, error) {
@@ -4893,7 +5191,7 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
4893
5191
  updated_at: this.stamp()
4894
5192
  };
4895
5193
  }
4896
- async scanOpenedTranscript(registration, handle, draft, size, device, inode) {
5194
+ async scanOpenedTranscript(registration, handle, previous, draft, size, device, inode) {
4897
5195
  const main2 = await this.readChunk(handle, draft.offset, size);
4898
5196
  if (main2 !== "empty" && main2 !== "partial") {
4899
5197
  await this.consumeMainChunk(registration, main2, draft);
@@ -4901,7 +5199,7 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
4901
5199
  }
4902
5200
  draft.consumed += await this.consumeSubagents(registration, draft);
4903
5201
  await this.emitOpenTerminal(registration, draft);
4904
- await this.commitCursor(registration, handle, draft, device, inode);
5202
+ await this.commitCursor(registration, handle, previous, draft, device, inode);
4905
5203
  }
4906
5204
  async preflight(registration, handle, size, device, inode) {
4907
5205
  const existing = await this.store.readTranscriptCursor(registration);
@@ -5061,15 +5359,24 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
5061
5359
  try {
5062
5360
  names = (await readdir2(directory)).filter((name) => name.endsWith(".jsonl") && !name.endsWith(".meta.json")).sort();
5063
5361
  } catch (error) {
5064
- if (isMissingTranscriptError(error) || isNotDirectory(error)) return 0;
5362
+ if (isMissingTranscriptError(error) || isNotDirectory(error)) {
5363
+ this.overflow.clear(registration);
5364
+ return 0;
5365
+ }
5065
5366
  throw new ClaudeHostError("payload_rejected", "Claude subagent transcript directory is unavailable.");
5066
5367
  }
5067
5368
  const listed = new Set(names);
5068
5369
  for (const name of Object.keys(draft.subagents)) if (!listed.has(name)) delete draft.subagents[name];
5069
- if (names.length > CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES) {
5070
- this.log(`Claude ignored subagent transcripts past its file bound: transcript_path=${JSON.stringify(registration.transcript_path)}, files=${names.length}.`);
5071
- names = names.slice(0, CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES);
5072
- }
5370
+ await this.overflow.observe(registration, names, () => {
5371
+ const line = `Claude ignored subagent transcripts past its file bound: transcript_path=${JSON.stringify(registration.transcript_path)}, files=${names.length}.`;
5372
+ try {
5373
+ this.log(line);
5374
+ } catch {
5375
+ return false;
5376
+ }
5377
+ return true;
5378
+ });
5379
+ names = names.slice(0, CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES);
5073
5380
  let consumed = 0;
5074
5381
  for (const name of names) {
5075
5382
  consumed += await this.consumeSubagentFile(draft, directory, name);
@@ -5158,9 +5465,9 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
5158
5465
  expires_at: this.expire(this.outboxRetentionMs)
5159
5466
  });
5160
5467
  }
5161
- async commitCursor(registration, handle, draft, device, inode) {
5468
+ async commitCursor(registration, handle, previous, draft, device, inode) {
5162
5469
  const anchor = await this.readAnchor(handle, draft.offset, CLAUDE_TRANSCRIPT_ANCHOR_BYTES);
5163
- await this.store.writeTranscriptCursor({
5470
+ const cursor = {
5164
5471
  schema_version: CLAUDE_TRANSCRIPT_CURSOR_SCHEMA_VERSION,
5165
5472
  host_source_ref: registration.host_source_ref,
5166
5473
  host_session_ref: registration.host_session_ref,
@@ -5177,7 +5484,9 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
5177
5484
  ...draft.session_observed ? { session_observed: true } : {},
5178
5485
  status: "active",
5179
5486
  updated_at: this.stamp()
5180
- });
5487
+ };
5488
+ if (sameCursorContent(cursor, previous)) return;
5489
+ await this.store.writeTranscriptCursor(cursor);
5181
5490
  }
5182
5491
  async activateContext(identity, promptRef, turnGenerationRef, expiresAt) {
5183
5492
  try {
@@ -5228,6 +5537,9 @@ function mutableCursor(cursor) {
5228
5537
  enqueued: 0
5229
5538
  };
5230
5539
  }
5540
+ function sameCursorContent(left, right) {
5541
+ return isDeepStrictEqual({ ...left, updated_at: void 0 }, { ...right, updated_at: void 0 });
5542
+ }
5231
5543
  function zeroCounts() {
5232
5544
  return { input: 0, cached_input: 0, cache_write_input: 0, output: 0 };
5233
5545
  }
@@ -5366,25 +5678,20 @@ var ClaudeUsageFactsCapturer = class {
5366
5678
  sources;
5367
5679
  usage;
5368
5680
  now;
5369
- diagnosticSink;
5370
- nextRegistrationIndex = 0;
5681
+ registrations;
5371
5682
  nextSourceSlot = "main";
5372
5683
  nextSubagentIndex = 0;
5684
+ overflow = new ClaudeSubagentOverflowCheckpoint();
5373
5685
  constructor(options) {
5374
5686
  this.sources = new ClaudeOutboxStore(options.outbox_dir);
5375
5687
  this.usage = new HostUsageFactsStore({ outbox_dir: options.outbox_dir, ...options.store_options });
5376
5688
  this.now = options.now ?? (() => /* @__PURE__ */ new Date());
5377
- this.diagnosticSink = options.diagnostic_sink;
5689
+ this.registrations = new HostUsageRegistrationCapture("claude", options.diagnostic_sink);
5378
5690
  }
5379
5691
  async captureNext() {
5380
5692
  const registrations = await this.sources.listTranscriptRegistrations();
5381
- let failed = false;
5382
- const result = await captureNextHostUsageRegistration(registrations, this.nextRegistrationIndex, (registration) => this.captureRegistration(registration, () => {
5383
- failed = true;
5384
- }));
5385
- this.nextRegistrationIndex = result.nextIndex;
5386
- if (failed || result.failed) writeHostServiceDiagnostic("claude", "usage_capture_failed", void 0, "capture_failed", this.diagnosticSink);
5387
- return result.captured;
5693
+ this.overflow.prune(registrations);
5694
+ return await this.registrations.captureNext(registrations, (registration, onFailure) => this.captureRegistration(registration, onFailure));
5388
5695
  }
5389
5696
  async captureRegistration(registration, onFailure) {
5390
5697
  const sources = this.nextSourceSlot === "main" ? ["main", "subagent"] : ["subagent", "main"];
@@ -5431,13 +5738,14 @@ var ClaudeUsageFactsCapturer = class {
5431
5738
  }
5432
5739
  async captureSubagent(registration, onFailure) {
5433
5740
  const names = await readSubagentNames(registration);
5741
+ if (names.length <= CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES) this.overflow.clear(registration);
5434
5742
  let state = await this.usage.readState("claude", registration.host_source_ref, registration.host_session_ref);
5435
5743
  if (state === null) return false;
5436
5744
  state = await this.usage.recoverPending(state);
5437
5745
  if (state.quarantined_reason !== void 0) return false;
5438
5746
  if (await this.retireMissingSubagent(state, names)) return true;
5439
5747
  if (await this.captureListedSubagents(registration, names, state, onFailure)) return true;
5440
- return await this.recordExcessSubagentGap(state, names);
5748
+ return await this.recordExcessSubagentGap(registration, state, names);
5441
5749
  }
5442
5750
  async retireMissingSubagent(state, names) {
5443
5751
  const liveSlots = new Set(names.slice(0, CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES).map(subagentSlot));
@@ -5448,14 +5756,14 @@ var ClaudeUsageFactsCapturer = class {
5448
5756
  }
5449
5757
  return false;
5450
5758
  }
5451
- async recordExcessSubagentGap(state, names) {
5452
- const excessCount = names.length - CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES;
5453
- if (excessCount <= 0) return false;
5759
+ async recordExcessSubagentGap(registration, state, names) {
5454
5760
  const mainCursor = state.cursors.main;
5455
5761
  if (mainCursor === void 0) return false;
5456
- const gap = { reason: "unsupported_source_shape", source_file_ref: null, start_offset: null, end_offset: null, omitted_count: excessCount };
5457
- await this.usage.commitScanTransition(state, "main", mainCursor, mainCursor, null, [gap]);
5458
- return true;
5762
+ return await this.overflow.observe(registration, names, async () => {
5763
+ const gap = { reason: "unsupported_source_shape", source_file_ref: null, start_offset: null, end_offset: null, omitted_count: names.length - CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES };
5764
+ await this.usage.commitScanTransition(state, "main", mainCursor, mainCursor, null, [gap]);
5765
+ return true;
5766
+ });
5459
5767
  }
5460
5768
  async captureListedSubagents(registration, names, state, onFailure) {
5461
5769
  const candidates = names.slice(0, CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES);
@@ -5794,8 +6102,8 @@ var ClaudeHookAdapter = class {
5794
6102
  registered_at: observedAt,
5795
6103
  expires_at: expiresAt
5796
6104
  };
5797
- const existing = (await this.store.listTranscriptRegistrations()).find((candidate) => candidate.host_source_ref === registration.host_source_ref && candidate.host_session_ref === registration.host_session_ref);
5798
- if (existing === void 0) {
6105
+ const existing = await this.store.readTranscriptRegistration(registration.host_source_ref, registration.host_session_ref);
6106
+ if (existing === null) {
5799
6107
  await this.store.writeTranscriptCursor((await captureClaudeTranscriptBaseline(registration, this.now, void 0, this.platform, this.custody)).cursor);
5800
6108
  }
5801
6109
  await this.store.registerTranscript(registration);
@@ -5828,11 +6136,11 @@ var ClaudeHookAdapter = class {
5828
6136
  const promptRef = hostProducerPromptRef(createHash9("sha256").update(input.prompt, "utf8").digest("hex"));
5829
6137
  const turnGenerationRef = this.randomUuid();
5830
6138
  const selection = { schema_version: HOST_INVOCATION_TURN_SELECTION_SCHEMA, host_source_ref: this.optionsSourceRef, host_session_ref: hostSessionRef, prompt_ref: promptRef, turn_generation_ref: turnGenerationRef };
5831
- const existing = (await this.store.listTranscriptRegistrations()).find((candidate) => candidate.host_source_ref === registration.host_source_ref && candidate.host_session_ref === registration.host_session_ref);
6139
+ const existing = await this.store.readTranscriptRegistration(registration.host_source_ref, registration.host_session_ref);
5832
6140
  const baseline = await captureClaudeTranscriptBaseline(registration, this.now, input.prompt, this.platform, this.custody);
5833
6141
  const transcriptTurnRef = baseline.current_turn_ref;
5834
6142
  await this.store.writeInvocationTurnSelection(selection);
5835
- if (existing === void 0) await this.store.writeTranscriptCursor(baseline.cursor);
6143
+ if (existing === null) await this.store.writeTranscriptCursor(baseline.cursor);
5836
6144
  else await refreshCurrentTurnCursor(this.store, registration, baseline, promptRef, turnGenerationRef, transcriptTurnRef);
5837
6145
  await this.store.registerTranscript(registration);
5838
6146
  return { event: input.event, disposition: "ignored", reason: "transcript_registered", local_session_ref: hostSessionRef, ...transcriptTurnRef === void 0 ? {} : { local_turn_ref: transcriptTurnRef } };
@@ -5915,8 +6223,10 @@ var CLAUDE_BASELINE_SCAN_LINES = 128;
5915
6223
  async function readRecentClaudeTranscriptLines(handle, size) {
5916
6224
  if (size === 0) return null;
5917
6225
  const start = Math.max(0, size - CLAUDE_BASELINE_SCAN_BYTES);
5918
- const buffer = Buffer.alloc(size - start);
5919
- await handle.read(buffer, 0, buffer.length, start);
6226
+ const readStart = Math.max(0, start - 1);
6227
+ const tail2 = Buffer.alloc(size - readStart);
6228
+ await handle.read(tail2, 0, tail2.length, readStart);
6229
+ const buffer = tail2.subarray(start - readStart);
5920
6230
  const lines = [];
5921
6231
  let lineStart = 0;
5922
6232
  for (let index = 0; index < buffer.length; index += 1) {
@@ -5926,7 +6236,7 @@ async function readRecentClaudeTranscriptLines(handle, size) {
5926
6236
  }
5927
6237
  if (lineStart < buffer.length) lines.push({ start: start + lineStart, text: buffer.subarray(lineStart).toString("utf8"), complete: false });
5928
6238
  if (lines.length === 0) return null;
5929
- const whole = start > 0 ? lines.slice(1) : lines;
6239
+ const whole = start === 0 || tail2[0] === 10 ? lines : lines.slice(1);
5930
6240
  if (whole.length === 0) return null;
5931
6241
  return whole.slice(-CLAUDE_BASELINE_SCAN_LINES);
5932
6242
  }
@@ -6056,11 +6366,14 @@ var ClaudeProducer = class {
6056
6366
  };
6057
6367
 
6058
6368
  // host/claude/src/claude-producer-runtime.ts
6059
- async function drainClaudeProducerOnce(options) {
6060
- const scan = await new ClaudeTranscriptWatcher({
6061
- outbox_dir: options.outbox_dir,
6369
+ function createClaudeProducerWatcher(outboxDir) {
6370
+ return new ClaudeTranscriptWatcher({
6371
+ outbox_dir: outboxDir,
6062
6372
  diagnostic: (event, failure_kind, cause) => writeHostServiceDiagnostic("claude", event, failure_kind, cause)
6063
- }).scanOnce().catch((error) => {
6373
+ });
6374
+ }
6375
+ async function drainClaudeProducerOnce(options) {
6376
+ const scan = await (options.watcher ?? createClaudeProducerWatcher(options.outbox_dir)).scanOnce().catch((error) => {
6064
6377
  writeHostServiceDiagnostic("claude", "watcher_scan_failed", claudeTranscriptScanFailureKind(error), claudeTranscriptScanCause(void 0, error));
6065
6378
  throw error;
6066
6379
  });
@@ -6248,7 +6561,7 @@ function parseCanonicalJson(text, error) {
6248
6561
  if (canonical !== text.trim()) throw new Error(`noncanonical: ${refusalFacts([{ name: "config_bytes", value: Buffer.byteLength(text.trim(), "utf8"), expected: `the ${Buffer.byteLength(canonical, "utf8")} bytes of its canonical form` }, { name: "first_difference_index", value: firstDifferenceIndex(text.trim(), canonical) }])}`);
6249
6562
  return value;
6250
6563
  } catch (parseError) {
6251
- throw error("invalid_config", refusalFacts([{ name: "parse_error", value: parseError }, { name: "config_bytes", value: Buffer.byteLength(text, "utf8"), expected: "canonical JSON" }]));
6564
+ throw error("invalid_config", `parse_error=${renderOperatorDiagnostic(parseError)}; ${refusalFact("config_bytes", Buffer.byteLength(text, "utf8"), "canonical JSON")}`);
6252
6565
  }
6253
6566
  }
6254
6567
  function firstDifferenceIndex(left, right) {
@@ -6310,7 +6623,7 @@ var CLAUDE_PRODUCER_DESCRIPTOR = {
6310
6623
  producer_id: "claude",
6311
6624
  extra_paths: [CLAUDE_TRANSCRIPTS_ROOT],
6312
6625
  config: (shared, extras) => ({ ...shared, claude_transcripts_root: hostProducerExtraPath(extras, CLAUDE_TRANSCRIPTS_ROOT) }),
6313
- runtime_options: (config) => Object.freeze({ outbox_dir: config.outbox_dir }),
6626
+ runtime_options: (config) => Object.freeze({ outbox_dir: config.outbox_dir, watcher: createClaudeProducerWatcher(config.outbox_dir) }),
6314
6627
  drain: drainClaudeProducerOnce,
6315
6628
  background: (config, signal, dependencies) => {
6316
6629
  const capturer = new ClaudeUsageFactsCapturer({ outbox_dir: config.outbox_dir });