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

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",
@@ -308,6 +309,12 @@ var CALLER_RECOVERABLE_NEXT_ACTION_VALUES = [
308
309
  // (never connected, revoked, or expired). The caller runs that exact
309
310
  // Operation, completes the consent it hands back, and retries the same call.
310
311
  "connect_personal_account",
312
+ // The refusal names the caller's own preferences update step: the read
313
+ // needs a personal connection the caller holds but has not selected in
314
+ // Ceal preferences, or has not confirmed through the initial review. The
315
+ // caller reads personal.preferences.get, runs personal.preferences.update
316
+ // at the current revision to select it, and retries the same call.
317
+ "update_personal_preferences",
311
318
  // The provider or Gateway named a bounded wait; the caller waits that long
312
319
  // and submits the same read again.
313
320
  "retry_after",
@@ -448,6 +455,9 @@ var CEAL_OPERATION_READINESS_VALUES = vocabulary(["ready", "degraded", "unavaila
448
455
  var CEAL_TARGET_REQUIREMENTS = vocabulary(["required", "optional", "none"]);
449
456
  var CEAL_AUDIT_OUTCOMES = vocabulary(["succeeded", "denied", "failed"]);
450
457
  var CEAL_GATEWAY_PROVIDER_STEP_OUTCOMES = vocabulary(["completed", "rejected", "throttled", "failed"]);
458
+ var CEAL_GATEWAY_CORPUS_READ_PROVIDERS = vocabulary(["slack", "google_drive", "notion"]);
459
+ var CEAL_GATEWAY_CORPUS_READ_OUTCOMES = vocabulary(["answered_from_corpus", "live_fallback"]);
460
+ var CEAL_GATEWAY_CORPUS_READ_FALLBACK_REASONS = vocabulary(["uncovered_window", "stale", "not_organization_public", "partition_missing"]);
451
461
  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
462
  var CEAL_GATEWAY_READ_REUSE_UNAVAILABLE_REASONS = vocabulary(["not_reported", "storage_unavailable", "coverage_incomplete", "freshness_refresh_required", "not_reusable", "bypassed"]);
453
463
  var CEAL_GATEWAY_DERIVED_STORE_FAILURE_CLASSES = vocabulary(["storage_unavailable", "decode_mismatch", "write_conflict", "quota", "store_error"]);
@@ -488,6 +498,21 @@ var CEAL_GATEWAY_ORGANIZATION_ROUTE_FACT_CALL_KEYS = Object.freeze([
488
498
  ]);
489
499
 
490
500
  // packages/ceal-client-protocol/src/gateway-validation-primitives.ts
501
+ var POSIX_HOME_ROOTS = [["/", "home"].join(""), ["/", "Users"].join("")];
502
+ var WINDOWS_HOME_ROOT = ["C:", "\\", "Users"].join("");
503
+ var USER_SEGMENT_BODY = "[^/\\\\ \\t\\r\\n\"'`${}]+";
504
+ var POSIX_SEGMENT_END = "(?:/|$|(?=[\\s\"'`]))";
505
+ var WINDOWS_SEGMENT_END = "(?:\\\\+|$|(?=[\\s\"'`]))";
506
+ var WINDOWS_USER_SEGMENT_BODY = "[^\\\\ \\t\\r\\n\"'`${}]+";
507
+ var ABSOLUTE_PATH_BOUNDARY = "(?<![A-Za-z0-9_])";
508
+ function escapePathPattern(value) {
509
+ return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
510
+ }
511
+ function machineHomePathPatterns(flags) {
512
+ const posix5 = `${ABSOLUTE_PATH_BOUNDARY}(?:${POSIX_HOME_ROOTS.map(escapePathPattern).join("|")})/${USER_SEGMENT_BODY}${POSIX_SEGMENT_END}`;
513
+ const windows = `${ABSOLUTE_PATH_BOUNDARY}${escapePathPattern(WINDOWS_HOME_ROOT)}\\\\+${WINDOWS_USER_SEGMENT_BODY}${WINDOWS_SEGMENT_END}`;
514
+ return [new RegExp(posix5, flags), new RegExp(windows, flags)];
515
+ }
491
516
  var CealProtocolValidationError = class extends Error {
492
517
  name = "CealProtocolValidationError";
493
518
  code;
@@ -839,10 +864,13 @@ var LOCAL_COMMAND_INVALID = "The local command or argument is invalid.";
839
864
  var LOCAL_TRANSPORT_INCOMPLETE = "The local Ceal transport could not complete; report this as a gap.";
840
865
  var GATEWAY_TRANSPORT_UNAVAILABLE = "The Gateway transport is unavailable; ask an administrator to restore Gateway availability.";
841
866
  var HOST_AUTHENTICATION_UNAVAILABLE = "The Host could not authenticate this invocation; report this as a gap.";
842
- var CLIENT_HOST_RELEASE_MISMATCH = "Install or upgrade the Ceal CLI and Host Relay to the same release as the Gateway, then retry.";
867
+ var CEAL_CLIENT_UPGRADE_COMMAND = "npm install -g @corca-org/ceal";
868
+ var CLIENT_HOST_RELEASE_MISMATCH = `Install or upgrade the Ceal CLI and Host Relay to the same release as the Gateway, then retry. Update with \`${CEAL_CLIENT_UPGRADE_COMMAND}\`.`;
843
869
  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
- 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.";
870
+ var HOST_CONTEXT_UNAVAILABLE = "The Host could not select this turn right now; the Host may be restarting. Wait briefly and retry the same command. If you know you are in an ephemeral side conversation, `ceal --standalone ...` uses your configured Ceal session/Gateway permissions without Host session/turn correlation. Otherwise return to the original regular conversation. Host refusal never switches modes. If the retry still fails, report intended Host calls as a gap.";
871
+ var HOST_RELAY_RESTARTING = "The Host Relay is temporarily unavailable while the Host restarts; wait briefly and retry the same command. If the retry still fails, report this as a gap.";
845
872
  var SESSION_CONTEXT_UNAVAILABLE = "The local Gateway session context is unavailable.";
873
+ 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
874
  function guidance(message, next_action, http_status, retryable = false, redaction_class = "model_safe") {
847
875
  return Object.freeze({ message, next_action, http_status, retryable, redaction_class });
848
876
  }
@@ -863,13 +891,21 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
863
891
  context_not_selected: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
864
892
  context_store_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
865
893
  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),
894
+ refresh_invalid: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
895
+ refresh_expired: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
896
+ refresh_replayed: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
897
+ refresh_revoked: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
898
+ 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),
899
+ 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),
900
+ 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),
901
+ // A stored session that predates the authority-epoch commitment carries no
902
+ // epoch to compare, so it can never refresh: adopt a fresh session instead.
903
+ authority_epoch_unknown: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
904
+ refresh_inactive: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 410),
905
+ 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),
906
+ 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),
907
+ refresh_state_unavailable: guidance("The Gateway session state store is temporarily unavailable; retry the same refresh attempt when it is available.", "retry", 503, true),
908
+ refresh_recovery_expired: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 410),
873
909
  refresh_custody_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
874
910
  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
911
  local_output_exists: guidance("The selected local output path already exists; nothing was written to it.", "choose_new_output_path", 400),
@@ -884,10 +920,8 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
884
920
  resource_stream_failed: guidance("The provider resource stream failed; ask an administrator to inspect the Gateway failure log.", "ask_admin", 500),
885
921
  gateway_unavailable: guidance(GATEWAY_TRANSPORT_UNAVAILABLE, "ask_admin", 503, true),
886
922
  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),
923
+ // The serving gate answers before refresh execution, so retrying the same attempt is safe.
924
+ [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
925
  gateway_internal_error: guidance("The Gateway failed without exposing internal state; report this as a gap.", "answer_with_gap", 500),
892
926
  // The serving gate emits this code with no message; the sentence is the owner-normalized form of the
893
927
  // `gateway_internal_error` guidance (decided with the operator 2026-10-13).
@@ -899,6 +933,8 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
899
933
  // The safe move varies by request. Keep the sentence conditional on the
900
934
  // same `retryable` and `next_action` facts the response exposes.
901
935
  unknown_outcome: guidance("The transport outcome is unknown; use retryable and next_action to decide whether it can be repeated.", "answer_with_gap", 500),
936
+ // 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.
937
+ 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
938
  // Restored verbatim from the retired `localFailureText`
903
939
  // `refresh_unknown_outcome` case: a refresh that ends unknown leaves the
904
940
  // session context unavailable, so the caller repairs or adopts the
@@ -989,7 +1025,7 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
989
1025
  host_session_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 401),
990
1026
  // The bounded Host reason does not prove ephemerality. A Host refusal never
991
1027
  // changes mode; standalone remains the separate Client authority path.
992
- host_context_unavailable: guidance(HOST_CONTEXT_UNAVAILABLE, "answer_with_gap", 401),
1028
+ host_context_unavailable: guidance(HOST_CONTEXT_UNAVAILABLE, "retry", 401, true),
993
1029
  host_context_activation_wait_exhausted: guidance("The Host selected this turn, but its invocation context did not activate before the bounded wait ended. Wait for the supplied retry_after_ms value, then retry the same command.", "retry_after", 401, true),
994
1030
  host_invocation_context_stale: guidance("The Host turn changed while this invocation was authenticating. Its command cannot be rebound safely; report this invocation as a gap.", "answer_with_gap", 401),
995
1031
  host_invocation_context_expired: guidance("The Host invocation context expired before authentication completed. This invocation cannot be retried in the expired turn; report it as a gap.", "answer_with_gap", 401),
@@ -1006,7 +1042,7 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
1006
1042
  // Moved from the retired `CEAL_HOST_AUTHENTICATION_POLICY` remedy: the
1007
1043
  // sandboxed Relay socket names the run-alone retry.
1008
1044
  host_relay_permission_denied: guidance("An agent sandbox denied the Host Relay socket; run `ceal` as the only command, with no pipe, redirect, or `&&`, so the Host allow rule runs it outside the sandbox.", "rerun_outside_agent_sandbox", 403),
1009
- host_relay_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 503),
1045
+ host_relay_unavailable: guidance(HOST_RELAY_RESTARTING, "retry", 503, true),
1010
1046
  host_mint_transient_retryable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 503, true),
1011
1047
  host_mint_failed: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 500),
1012
1048
  host_relay_failed: guidance(HOST_INSTALL_REPAIR, "install_ceal_host", 502),
@@ -1254,7 +1290,7 @@ var CEAL_OPERATION_JSON_SCHEMA_BUDGET = Object.freeze({
1254
1290
  max_literal_nodes: 512
1255
1291
  });
1256
1292
 
1257
- // packages/ceal-client-protocol/src/operation-json-schema.ts
1293
+ // packages/ceal-client-protocol/src/operation-json-schema-leaf-validators.ts
1258
1294
  var JSON_DESCRIPTION_CONTROL_CHARACTER = new RegExp("\\p{Cc}", "u");
1259
1295
 
1260
1296
  // packages/ceal-client-protocol/src/operation-contract-validation.ts
@@ -1401,7 +1437,8 @@ var CEAL_OPERATION_ID_PLACEHOLDER = "<operation-id>";
1401
1437
  var CEAL_OPERATION_INPUT_PLACEHOLDER = "<json-object>";
1402
1438
  var MODEL_INVOCATION_BASE_ARGUMENTS = [CEAL_OPERATION_INVOKE_COMMAND, CEAL_OPERATION_ID_PLACEHOLDER].join(" ");
1403
1439
  var CEAL_MODEL_INVOCATION_ARGUMENTS = [MODEL_INVOCATION_BASE_ARGUMENTS, CEAL_OPERATION_INPUT_FLAG, shellSingleQuoted(CEAL_OPERATION_INPUT_PLACEHOLDER)].join(" ");
1404
- var CEAL_MODEL_INPUT_SOURCE_GUIDANCE = `For caller-owned fields, add ${CEAL_OPERATION_INPUT_FLAG} ${shellSingleQuoted(CEAL_OPERATION_INPUT_PLACEHOLDER)}. Use inline JSON for short input; for longer or generated input, put exactly one JSON object in a caller-owned regular non-symlink UTF-8 JSON file and pass --input @path; relative paths resolve from the command working directory.`;
1440
+ var CEAL_MODEL_INPUT_SOURCE_BASE_GUIDANCE = `For caller-owned fields, add ${CEAL_OPERATION_INPUT_FLAG} ${shellSingleQuoted(CEAL_OPERATION_INPUT_PLACEHOLDER)}. Use inline JSON for short input; for longer or generated input, put exactly one JSON object in a caller-owned regular non-symlink UTF-8 JSON file and pass --input @path; relative paths resolve from the command working directory.`;
1441
+ var CEAL_MODEL_INPUT_SOURCE_GUIDANCE = `${CEAL_MODEL_INPUT_SOURCE_BASE_GUIDANCE} On Windows, write the JSON file first; use the program's .cmd launcher with --input and only one quoted @path argument.`;
1405
1442
  function shellSingleQuoted(value) {
1406
1443
  return `'${value.replaceAll("'", "'\\''")}'`;
1407
1444
  }
@@ -1548,6 +1585,8 @@ var CEAL_ACTIVITY_TIMESTAMP_BASES = vocabulary([
1548
1585
  "review_submitted",
1549
1586
  "comment_created",
1550
1587
  "reaction_created",
1588
+ "pull_request_merged",
1589
+ "release_published",
1551
1590
  "ceal_write_completed",
1552
1591
  "event_start",
1553
1592
  "all_day_start",
@@ -1559,7 +1598,7 @@ var CEAL_ACTIVITY_TIMESTAMP_BASES = vocabulary([
1559
1598
  "page_last_edited",
1560
1599
  "resource_modified"
1561
1600
  ]);
1562
- var CEAL_ACTIVITY_CONNECTOR_KINDS = vocabulary(["slack", "github", "google-calendar", "google-drive", "notion"]);
1601
+ var CEAL_ACTIVITY_CONNECTOR_KINDS = vocabulary(["slack", "github", "google-calendar", "google-drive", "google-mail", "notion"]);
1563
1602
  var CEAL_ACTIVITY_UNSUPPORTED_EVENT_KIND_CODE = "unsupported_event_kind";
1564
1603
  var CEAL_ACTIVITY_GAP_CODES = vocabulary([
1565
1604
  "provider_page_budget",
@@ -1580,6 +1619,8 @@ var CEAL_ACTIVITY_EVENT_KINDS = vocabulary([
1580
1619
  "github.pull_request.opened",
1581
1620
  "github.issue.edited",
1582
1621
  "github.pull_request.edited",
1622
+ "github.pull_request.merged",
1623
+ "github.release.published",
1583
1624
  "github.review.submitted",
1584
1625
  "github.issue_comment.created",
1585
1626
  "github.review_comment.created",
@@ -1593,6 +1634,7 @@ var CEAL_ACTIVITY_EVENT_KINDS = vocabulary([
1593
1634
  "drive.file.created",
1594
1635
  "drive.file.modified",
1595
1636
  "drive.file.viewed",
1637
+ "mail.sent",
1596
1638
  "notion.page.created",
1597
1639
  "notion.page.edited"
1598
1640
  ]);
@@ -1606,6 +1648,8 @@ var CEAL_ACTIVITY_EVENT_TIMESTAMP_BASIS_MAP = Object.freeze({
1606
1648
  "github.review_comment.created": "comment_created",
1607
1649
  "github.issue.opened": "resource_created",
1608
1650
  "github.pull_request.opened": "resource_created",
1651
+ "github.pull_request.merged": "pull_request_merged",
1652
+ "github.release.published": "release_published",
1609
1653
  "github.issue.edited": "resource_modified",
1610
1654
  "github.pull_request.edited": "resource_modified",
1611
1655
  "github.reaction.created": "reaction_created",
@@ -1616,6 +1660,7 @@ var CEAL_ACTIVITY_EVENT_TIMESTAMP_BASIS_MAP = Object.freeze({
1616
1660
  "drive.file.created": "file_created",
1617
1661
  "drive.file.modified": "file_modified_by_me",
1618
1662
  "drive.file.viewed": "file_viewed_by_me",
1663
+ "mail.sent": "message_created",
1619
1664
  "notion.page.created": "page_created",
1620
1665
  "notion.page.edited": "page_last_edited"
1621
1666
  });
@@ -1726,6 +1771,8 @@ var CEAL_REFRESH_FAILURE_CODES = vocabulary([
1726
1771
  "principal_inactive",
1727
1772
  "authority_replaced",
1728
1773
  "refresh_recovery_unavailable",
1774
+ "refresh_recovery_outcome_unavailable",
1775
+ "refresh_state_unavailable",
1729
1776
  "refresh_recovery_expired",
1730
1777
  // The serving gate answers this while the Gateway is still starting and the
1731
1778
  // refresh was never attempted; the same attempt stays retryable. It is never
@@ -2375,9 +2422,11 @@ var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
2375
2422
  invalid_arguments: Object.freeze({ classification: "host_arguments_invalid", next_action: "answer_with_gap" }),
2376
2423
  options_invalid: Object.freeze({ classification: "host_configuration_invalid", next_action: "answer_with_gap" }),
2377
2424
  session_unavailable: Object.freeze({ classification: "host_session_unavailable", next_action: "answer_with_gap" }),
2378
- // This reason cannot distinguish a Codex side conversation from a missing
2379
- // context in a regular session, so guidance must leave that choice to the caller.
2380
- context_unavailable: Object.freeze({ classification: "host_context_unavailable", next_action: "answer_with_gap" }),
2425
+ // A missing turn right after a Host restart clears by itself once the
2426
+ // watcher reactivates the turn, so the caller waits briefly and retries;
2427
+ // a caller that knows it is in an ephemeral side conversation keeps the
2428
+ // standalone fallback the guidance names second.
2429
+ context_unavailable: Object.freeze({ classification: "host_context_unavailable", next_action: "retry" }),
2381
2430
  activation_wait_exhausted: Object.freeze({ classification: "host_context_activation_wait_exhausted", next_action: "retry_after" }),
2382
2431
  context_replaced: Object.freeze({ classification: "host_invocation_context_stale", next_action: "answer_with_gap" }),
2383
2432
  // `no_binding` now means the producer has no real current Host session. The
@@ -2394,7 +2443,7 @@ var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
2394
2443
  gateway_response_invalid: Object.freeze({ classification: "host_mint_gateway_response_invalid", next_action: "answer_with_gap" }),
2395
2444
  producer_frame_invalid: Object.freeze({ classification: "host_producer_frame_invalid", next_action: "ask_admin" }),
2396
2445
  relay_permission_denied: Object.freeze({ classification: "host_relay_permission_denied", next_action: "rerun_outside_agent_sandbox" }),
2397
- relay_unavailable: Object.freeze({ classification: "host_relay_unavailable", next_action: "answer_with_gap" }),
2446
+ relay_unavailable: Object.freeze({ classification: "host_relay_unavailable", next_action: "retry" }),
2398
2447
  transient_retryable: Object.freeze({ classification: "host_mint_transient_retryable", next_action: "retry" }),
2399
2448
  mint_failed: Object.freeze({ classification: "host_mint_failed", next_action: "answer_with_gap" }),
2400
2449
  relay_failed: Object.freeze({ classification: "host_relay_failed", next_action: "install_ceal_host" }),
@@ -2487,6 +2536,211 @@ var CEAL_SUPPORTED_GATEWAY_PROTOCOL_RANGE = Object.freeze({
2487
2536
  maximum: CEAL_PROTOCOL_VERSION
2488
2537
  });
2489
2538
 
2539
+ // packages/ceal-client-protocol/src/operator-diagnostic.ts
2540
+ var OPERATOR_DIAGNOSTIC_MAX_BYTES = 2048;
2541
+ var OPERATOR_DIAGNOSTIC_MAX_CAUSES = 8;
2542
+ var OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT = 512;
2543
+ var OPERATOR_DIAGNOSTIC_PATH_LIMIT = 1024;
2544
+ var OPERATOR_DIAGNOSTIC_STREAM_TAIL_LIMIT = 256;
2545
+ var OPERATOR_DIAGNOSTIC_HOME_PATHS = machineHomePathPatterns("gu");
2546
+ function redactOperatorDiagnosticSecrets(value) {
2547
+ 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]");
2548
+ }
2549
+ function redactOperatorDiagnosticText(value) {
2550
+ const normalized = normalizeCealSingleLineText(value);
2551
+ return normalizeCealSingleLineText(redactOperatorDiagnosticSecrets(redactFilePaths(redactHomePaths(redactUrls(normalized)))));
2552
+ }
2553
+ function renderOperatorDiagnostic(value) {
2554
+ const state = collectDiagnosticState(value);
2555
+ const fields = [
2556
+ state.status === void 0 ? void 0 : `status=${JSON.stringify(safeDiagnosticText(state.status))}`,
2557
+ state.exitCode === void 0 ? void 0 : `exit_code=${state.exitCode}`,
2558
+ state.stdout === void 0 ? void 0 : `stdout_tail=${JSON.stringify(tail(state.stdout))}`,
2559
+ state.stderr === void 0 ? void 0 : `stderr_tail=${JSON.stringify(tail(state.stderr))}`,
2560
+ state.causes.length === 0 ? void 0 : `causes=${state.causes.map(formatCause).join(" <- ")}`
2561
+ ].filter((field) => field !== void 0);
2562
+ const rendered = fields.length === 0 ? "unknown_failure" : fields.join(" ");
2563
+ return truncateUtf8(rendered, OPERATOR_DIAGNOSTIC_MAX_BYTES);
2564
+ }
2565
+ function collectDiagnosticState(value) {
2566
+ const state = { causes: [], status: void 0, exitCode: void 0, stdout: void 0, stderr: void 0 };
2567
+ const visited = /* @__PURE__ */ new Set(), pending = [value];
2568
+ while (pending.length > 0 && state.causes.length < OPERATOR_DIAGNOSTIC_MAX_CAUSES) {
2569
+ const current = pending.shift();
2570
+ if (current !== void 0) visitDiagnosticNode(current, state, pending, visited);
2571
+ }
2572
+ return state;
2573
+ }
2574
+ function visitDiagnosticNode(current, state, pending, visited) {
2575
+ if (isObject(current)) {
2576
+ if (visited.has(current)) return;
2577
+ visited.add(current);
2578
+ }
2579
+ captureProcessEvidence(current, state);
2580
+ appendCause(current, state.causes);
2581
+ enqueueCauseChildren(current, state.causes.length, pending);
2582
+ }
2583
+ function captureProcessEvidence(current, state) {
2584
+ if (state.status === void 0) state.status = safeStatus(read(current, "status"));
2585
+ if (state.exitCode === void 0) state.exitCode = safeExitCode(read(current, "exitCode")) ?? safeExitCode(read(current, "status")) ?? safeExitCode(read(current, "code"));
2586
+ if (state.stdout === void 0) state.stdout = outputText(read(current, "stdout"));
2587
+ if (state.stderr === void 0) state.stderr = outputText(read(current, "stderr"));
2588
+ }
2589
+ function appendCause(current, causes) {
2590
+ const errors = read(current, "errors");
2591
+ if (current instanceof Error && (!(current instanceof AggregateError) || !Array.isArray(errors) || errors.length === 0)) {
2592
+ causes.push(errorCause(current));
2593
+ return;
2594
+ }
2595
+ if (!isObject(current)) {
2596
+ const message = safeText(current);
2597
+ if (message !== void 0) causes.push(Object.freeze({ error_class: typeof current, message }));
2598
+ }
2599
+ }
2600
+ function errorCause(error) {
2601
+ const name = safeText(read(error, "name")) ?? "Error";
2602
+ const message = safeText(read(error, "message"));
2603
+ const codeValue = read(error, "code");
2604
+ const code2 = typeof codeValue === "number" && Number.isFinite(codeValue) ? codeValue : safeText(codeValue);
2605
+ const errnoValue = read(error, "errno");
2606
+ const errno = typeof errnoValue === "number" && Number.isSafeInteger(errnoValue) ? errnoValue : void 0;
2607
+ const syscall = safeText(read(error, "syscall"));
2608
+ const path = safePath(read(error, "path"));
2609
+ 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 } });
2610
+ }
2611
+ function enqueueCauseChildren(current, causeCount, pending) {
2612
+ const cause = read(current, "cause");
2613
+ if (cause !== void 0) pending.push(cause);
2614
+ const errors = read(current, "errors");
2615
+ if (Array.isArray(errors)) pending.push(...errors.slice(0, OPERATOR_DIAGNOSTIC_MAX_CAUSES - causeCount));
2616
+ }
2617
+ function isObject(value) {
2618
+ return typeof value === "object" && value !== null;
2619
+ }
2620
+ function formatCause(cause) {
2621
+ const fields = [
2622
+ cause.error_class,
2623
+ cause.code === void 0 ? void 0 : `code=${JSON.stringify(safeDiagnosticText(cause.code))}`,
2624
+ cause.errno === void 0 ? void 0 : `errno=${cause.errno}`,
2625
+ cause.syscall === void 0 ? void 0 : `syscall=${JSON.stringify(cause.syscall)}`,
2626
+ cause.path === void 0 ? void 0 : `path=${JSON.stringify(cause.path)}`,
2627
+ cause.message === void 0 ? void 0 : `message=${cause.message}`
2628
+ ].filter((field) => field !== void 0);
2629
+ return fields.join(" ");
2630
+ }
2631
+ function tail(value) {
2632
+ const clipped = value.length <= OPERATOR_DIAGNOSTIC_STREAM_TAIL_LIMIT ? value : `…${value.slice(-OPERATOR_DIAGNOSTIC_STREAM_TAIL_LIMIT)}`;
2633
+ return safeDiagnosticText(clipped);
2634
+ }
2635
+ function safeText(value) {
2636
+ if (typeof value !== "string") return void 0;
2637
+ const safe = safeDiagnosticText(value);
2638
+ if (safe.length === 0) return void 0;
2639
+ if (safe.length <= OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT) return safe;
2640
+ const head = Math.floor(OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT / 2);
2641
+ const tail2 = OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT - head - 1;
2642
+ return `${safe.slice(0, head)}…${safe.slice(-tail2)}`;
2643
+ }
2644
+ function safePath(value) {
2645
+ if (typeof value !== "string") return void 0;
2646
+ const safe = safeDiagnosticText(value);
2647
+ if (safe.length === 0) return void 0;
2648
+ if (safe.length <= OPERATOR_DIAGNOSTIC_PATH_LIMIT) return safe;
2649
+ const head = Math.floor(OPERATOR_DIAGNOSTIC_PATH_LIMIT / 2);
2650
+ const tail2 = OPERATOR_DIAGNOSTIC_PATH_LIMIT - head - 1;
2651
+ return `${safe.slice(0, head)}…${safe.slice(-tail2)}`;
2652
+ }
2653
+ function safeDiagnosticText(value) {
2654
+ return redactOperatorDiagnosticText(String(value));
2655
+ }
2656
+ function outputText(value) {
2657
+ if (typeof value === "string") return redactOperatorDiagnosticText(value);
2658
+ if (value instanceof Uint8Array) {
2659
+ try {
2660
+ return redactOperatorDiagnosticText(new TextDecoder().decode(value));
2661
+ } catch {
2662
+ return void 0;
2663
+ }
2664
+ }
2665
+ return void 0;
2666
+ }
2667
+ function safeStatus(value) {
2668
+ if (typeof value === "number" && Number.isFinite(value)) return value;
2669
+ return typeof value === "string" ? safeText(value) : void 0;
2670
+ }
2671
+ function safeExitCode(value) {
2672
+ return typeof value === "number" && Number.isSafeInteger(value) ? value : void 0;
2673
+ }
2674
+ function read(value, key) {
2675
+ if (typeof value !== "object" && typeof value !== "function" || value === null) return void 0;
2676
+ try {
2677
+ return Reflect.get(value, key);
2678
+ } catch {
2679
+ return void 0;
2680
+ }
2681
+ }
2682
+ function redactHomePaths(value) {
2683
+ const paths = [
2684
+ ...OPERATOR_DIAGNOSTIC_HOME_PATHS.flatMap((pattern) => [...value.matchAll(pattern)].map((match) => homePathRange(value, match, matchedHomePrefixLength(match[0])))),
2685
+ ...configuredHomePathPatterns().flatMap(({ pattern, prefixLength }) => [...value.matchAll(pattern)].map((match) => homePathRange(value, match, prefixLength)))
2686
+ ];
2687
+ paths.sort((left, right) => left.start - right.start || right.end - left.end);
2688
+ let output = "";
2689
+ let cursor = 0;
2690
+ for (const path of paths) {
2691
+ if (path.start < cursor) continue;
2692
+ output += `${value.slice(cursor, path.start)}[home path redacted]${value.slice(path.prefixEnd, path.end)}`;
2693
+ cursor = path.end;
2694
+ }
2695
+ return output + value.slice(cursor);
2696
+ }
2697
+ function configuredHomePathPatterns() {
2698
+ const homes = [...new Set([process.env.HOME, process.env.USERPROFILE].filter((home) => home !== void 0 && home.length > 0))];
2699
+ return homes.flatMap((home) => {
2700
+ const root = home.replace(/[\\/]+$/gu, "");
2701
+ if (root.length === 0 || root === "/" || /^[A-Za-z]:$/u.test(root)) return [];
2702
+ const pattern = new RegExp(`(?<![A-Za-z0-9_])${escapePathPattern(root)}(?=$|[\\\\/\\s"'\`<>(){}\\[\\],;])`, /^[A-Za-z]:[\\/]/u.test(root) ? "giu" : "gu");
2703
+ return [{ pattern, prefixLength: root.length }];
2704
+ });
2705
+ }
2706
+ function matchedHomePrefixLength(value) {
2707
+ let separators = 0;
2708
+ for (let index = 0; index < value.length; index += 1) {
2709
+ if (value[index] !== "/" && value[index] !== "\\") continue;
2710
+ separators += 1;
2711
+ if (separators === 3) return index;
2712
+ }
2713
+ return value.length;
2714
+ }
2715
+ function redactUrls(value) {
2716
+ return value.replaceAll(/https?:\/\/[^\s"'<>]+/giu, "[url redacted]");
2717
+ }
2718
+ function redactFilePaths(value) {
2719
+ return value.replaceAll(/(?<![A-Za-z0-9._-]|\[home path redacted\])(?:[A-Za-z]:[\\/]|\\\\[^\\\s]+\\|\/)[^:\r\n"'<>]*?(?=:\d+(?::\d+)?(?:[:\s]|$)|[\r\n]|["'])/gu, "[path redacted]");
2720
+ }
2721
+ function homePathRange(value, match, prefixLength) {
2722
+ const index = match.index;
2723
+ if (index === void 0) return { start: value.length, end: value.length, prefixEnd: value.length };
2724
+ const start = index;
2725
+ let end = start + match[0].length;
2726
+ const quote = start > 0 && (value[start - 1] === "'" || value[start - 1] === '"') ? value[start - 1] : void 0;
2727
+ if (quote !== void 0) {
2728
+ const closing = value.indexOf(quote, end);
2729
+ if (closing >= 0) end = closing;
2730
+ }
2731
+ while (end < value.length && !/[\s"'`<>(){}[\],;]/u.test(value[end] ?? "")) end += 1;
2732
+ return { start, end, prefixEnd: Math.min(start + prefixLength, end) };
2733
+ }
2734
+ function truncateUtf8(value, maxBytes) {
2735
+ if (byteLength(value) <= maxBytes) return value;
2736
+ let output = "";
2737
+ for (const character of value) {
2738
+ if (byteLength(`${output}${character}…`) > maxBytes) break;
2739
+ output += character;
2740
+ }
2741
+ return `${output}…`;
2742
+ }
2743
+
2490
2744
  // packages/ceal-client-protocol/src/admin-projection-vocabulary.ts
2491
2745
  var ADMIN_PROJECTION_STATES = vocabulary(["ready", "empty", "partial", "unknown"]);
2492
2746
  var ADMIN_VIEW_KINDS = vocabulary(["request_detail", "resource_access_timeline", "weekly_usage"]);
@@ -2689,8 +2943,8 @@ function invalid2(message) {
2689
2943
  }
2690
2944
 
2691
2945
  // host/claude/src/claude-outbox.ts
2692
- import { mkdir as mkdir4, readdir, readFile, unlink as unlink3 } from "node:fs/promises";
2693
- import { isAbsolute as isAbsolute4, join as join4 } from "node:path";
2946
+ import { mkdir as mkdir4, readFile, unlink as unlink3 } from "node:fs/promises";
2947
+ import { isAbsolute as isAbsolute5, join as join5 } from "node:path";
2694
2948
 
2695
2949
  // host/invocation-context.ts
2696
2950
  var HOST_INVOCATION_TURN_SELECTION_SCHEMA = "ceal.host_invocation_turn_selection.v1";
@@ -2759,13 +3013,86 @@ var HOST_PRODUCER_FRAME_ERROR_CODES = [
2759
3013
 
2760
3014
  // host/relay/src/host-producer-core.ts
2761
3015
  import { createHash as createHash5 } from "node:crypto";
3016
+ import { readdir } from "node:fs/promises";
2762
3017
 
2763
3018
  // host/secure-file.ts
2764
3019
  import { execFile } from "node:child_process";
2765
3020
  import { constants } from "node:fs";
2766
3021
  import { lstat, open } from "node:fs/promises";
2767
- import { dirname, join as join2, win32 } from "node:path";
3022
+ import { dirname, join as join3, win32 } from "node:path";
2768
3023
  import { fileURLToPath } from "node:url";
3024
+
3025
+ // host/spawn-working-directory.ts
3026
+ import { mkdirSync } from "node:fs";
3027
+ import { tmpdir } from "node:os";
3028
+ import { isAbsolute as isAbsolute2, join as join2, normalize, parse, sep } from "node:path";
3029
+ function resolveCealSpawnWorkingDirectory(stateRoot, keepOutside = []) {
3030
+ const candidates = [];
3031
+ const explicit = candidateDir(stateRoot);
3032
+ if (explicit !== void 0) candidates.push(explicit);
3033
+ const fallback = defaultHostStateRoot();
3034
+ if (fallback !== void 0 && !candidates.some((candidate) => sameDir(candidate, fallback))) candidates.push(fallback);
3035
+ const temporary = candidateDir(join2(tmpdir(), "ceal-spawn-cwd"));
3036
+ if (temporary !== void 0 && !candidates.some((candidate) => sameDir(candidate, temporary))) candidates.push(temporary);
3037
+ for (const dir of candidates) {
3038
+ if (!keptOutside(dir, keepOutside)) continue;
3039
+ try {
3040
+ mkdirSync(dir, { recursive: true, mode: 448 });
3041
+ return dir;
3042
+ } catch {
3043
+ continue;
3044
+ }
3045
+ }
3046
+ return tmpdir();
3047
+ }
3048
+ function candidateDir(dir) {
3049
+ if (dir === void 0 || dir === "") return void 0;
3050
+ if (!isAbsolute2(dir) || normalize(dir) !== dir || parse(dir).root === dir) return void 0;
3051
+ return normalize(dir);
3052
+ }
3053
+ function defaultHostStateRoot() {
3054
+ if (process.platform === "win32") {
3055
+ const localAppData = nonEmptyEnv("LOCALAPPDATA");
3056
+ if (localAppData === void 0) return void 0;
3057
+ return candidateDir(join2(localAppData, "Ceal", "Host"));
3058
+ }
3059
+ if (process.platform === "darwin") {
3060
+ const home2 = nonEmptyEnv("HOME");
3061
+ if (home2 === void 0) return void 0;
3062
+ return candidateDir(join2(home2, "Library", "Application Support", "Ceal", "Host"));
3063
+ }
3064
+ const xdg = nonEmptyEnv("XDG_STATE_HOME");
3065
+ if (xdg !== void 0) {
3066
+ const root = candidateDir(join2(xdg, "ceal", "host"));
3067
+ if (root !== void 0) return root;
3068
+ }
3069
+ const home = nonEmptyEnv("HOME");
3070
+ if (home === void 0) return void 0;
3071
+ return candidateDir(join2(home, ".local", "state", "ceal", "host"));
3072
+ }
3073
+ function nonEmptyEnv(name) {
3074
+ const value = process.env[name];
3075
+ return value === void 0 || value === "" ? void 0 : value;
3076
+ }
3077
+ function keptOutside(dir, keepOutside) {
3078
+ for (const tree of keepOutside) {
3079
+ const clean = candidateDir(tree);
3080
+ if (clean === void 0) continue;
3081
+ if (insideDir(dir, clean)) return false;
3082
+ }
3083
+ return true;
3084
+ }
3085
+ function insideDir(dir, tree) {
3086
+ if (sameDir(dir, tree)) return true;
3087
+ if (process.platform === "win32") return dir.toLowerCase().startsWith(tree.toLowerCase() + sep);
3088
+ return dir.startsWith(tree + sep);
3089
+ }
3090
+ function sameDir(left, right) {
3091
+ if (process.platform === "win32") return left.toLowerCase() === right.toLowerCase();
3092
+ return left === right;
3093
+ }
3094
+
3095
+ // host/secure-file.ts
2769
3096
  var SecureFileCustodyError = class extends Error {
2770
3097
  name = "SecureFileCustodyError";
2771
3098
  reason;
@@ -2864,7 +3191,7 @@ async function runSecurefsCommand(args, maxBytes, custody, stdin) {
2864
3191
  const executable = custody.securefs_executable ?? resolveInstalledHostExecutable(process.platform);
2865
3192
  const processArgs = [...custody.securefs_args_prefix ?? [], ...args];
2866
3193
  return await new Promise((resolve2, reject) => {
2867
- const child = execFile(executable, processArgs, { encoding: "buffer", windowsHide: true, timeout: WINDOWS_SECUREFS_TIMEOUT_MS, maxBuffer: maxBytes + WINDOWS_SECUREFS_DIAGNOSTIC_BYTES }, (error, stdout, stderr) => {
3194
+ const child = execFile(executable, processArgs, { encoding: "buffer", windowsHide: true, timeout: WINDOWS_SECUREFS_TIMEOUT_MS, maxBuffer: maxBytes + WINDOWS_SECUREFS_DIAGNOSTIC_BYTES, cwd: resolveCealSpawnWorkingDirectory() }, (error, stdout, stderr) => {
2868
3195
  const exitCode = error === null ? 0 : typeof error.code === "number" ? error.code : null;
2869
3196
  if (exitCode === null) {
2870
3197
  reject(new SecureFileCustodyError("unavailable", "The installed Windows Host securefs command could not run."));
@@ -2893,7 +3220,7 @@ function securefsRefusal(stderr) {
2893
3220
  }
2894
3221
  function resolveInstalledHostExecutable(platform) {
2895
3222
  const privateRuntimeRoot = dirname(fileURLToPath(import.meta.url));
2896
- return platform === "win32" ? win32.join(privateRuntimeRoot, "..", "..", "bin", "ceal-host.exe") : join2(privateRuntimeRoot, "..", "..", "bin", "ceal-host");
3223
+ return platform === "win32" ? win32.join(privateRuntimeRoot, "..", "..", "bin", "ceal-host.exe") : join3(privateRuntimeRoot, "..", "..", "bin", "ceal-host");
2897
3224
  }
2898
3225
  function isRecord2(value) {
2899
3226
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -2917,7 +3244,7 @@ async function isPrivateDirectory(path, platform = process.platform, custody = {
2917
3244
 
2918
3245
  // host/service-log.ts
2919
3246
  import { copyFile, mkdir, stat, truncate, appendFile } from "node:fs/promises";
2920
- import { dirname as dirname2, isAbsolute as isAbsolute2, posix, win32 as win322 } from "node:path";
3247
+ import { dirname as dirname2, isAbsolute as isAbsolute3, posix, win32 as win322 } from "node:path";
2921
3248
 
2922
3249
  // host/service-log-delivery.ts
2923
3250
  var HOST_SERVICE_LOG_DELIVERY_SCHEMA = "ceal.host_service_log_delivery.v1";
@@ -3083,7 +3410,7 @@ async function persistHostServiceLogLine(line, environment = process.env) {
3083
3410
  await appendHostServiceLogLine(path, line).catch(() => void 0);
3084
3411
  }
3085
3412
  async function appendHostServiceLogLine(path, line) {
3086
- if (!isAbsolute2(path)) return;
3413
+ if (!isAbsolute3(path)) return;
3087
3414
  await ensureHostServiceLogDirectory(path);
3088
3415
  await appendFile(path, line);
3089
3416
  }
@@ -3146,9 +3473,9 @@ async function readTranscriptCompleteChunk(handle, offset, size) {
3146
3473
  let lastNewline = -1;
3147
3474
  while (position < size) {
3148
3475
  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);
3476
+ const read2 = await handle.read(buffer, 0, buffer.length, position);
3477
+ if (read2.bytesRead === 0) break;
3478
+ const chunk = buffer.subarray(0, read2.bytesRead);
3152
3479
  chunks.push(chunk);
3153
3480
  const newline = chunk.lastIndexOf(10);
3154
3481
  if (newline >= 0) lastNewline = total + newline;
@@ -3307,6 +3634,14 @@ var HostTranscriptWatcher = class {
3307
3634
  return transcriptCursorBoundsReason(handle, cursor, size);
3308
3635
  }
3309
3636
  };
3637
+ async function listHostOutboxDirectoryNames(directory) {
3638
+ try {
3639
+ return await readdir(directory);
3640
+ } catch (error) {
3641
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") return [];
3642
+ throw error;
3643
+ }
3644
+ }
3310
3645
  var HostProducerDrainCore = class {
3311
3646
  host;
3312
3647
  now;
@@ -3321,15 +3656,15 @@ var HostProducerDrainCore = class {
3321
3656
  return run;
3322
3657
  }
3323
3658
  async drainLocked() {
3324
- const read = await this.host.listEnvelopes();
3659
+ const read2 = await this.host.listEnvelopes();
3325
3660
  let removed = 0;
3326
3661
  let expired = 0;
3327
- for (const envelope of read.entries) {
3662
+ for (const envelope of read2.entries) {
3328
3663
  if (Date.parse(this.host.expiresAtOf(envelope)) <= this.now().getTime()) expired += 1;
3329
3664
  else removed += 1;
3330
3665
  await this.host.removeEnvelope(envelope);
3331
3666
  }
3332
- return { removed, expired, malformed: read.malformed };
3667
+ return { removed, expired, malformed: read2.malformed };
3333
3668
  }
3334
3669
  };
3335
3670
 
@@ -3468,7 +3803,7 @@ function errorCode(error) {
3468
3803
  import { createHash as createHash6 } from "node:crypto";
3469
3804
  import { constants as constants2 } from "node:fs";
3470
3805
  import { mkdir as mkdir3, open as open3, opendir, unlink as unlink2 } from "node:fs/promises";
3471
- import { dirname as dirname4, join as join3 } from "node:path";
3806
+ import { dirname as dirname4, join as join4 } from "node:path";
3472
3807
  var HOST_USAGE_FACTS_STATE_SCHEMA = "ceal.host_usage_facts_state.v1";
3473
3808
  var HOST_USAGE_FACTS_STATE_MAX_BYTES = 256 * 1024;
3474
3809
  var HOST_USAGE_FACTS_MAX_SOURCE_CURSORS = CEAL_HOST_USAGE_BATCH_MAX_SOURCE_RANGES;
@@ -3488,9 +3823,9 @@ var HostUsageFactsStore = class {
3488
3823
  afterBatchPublish;
3489
3824
  sessionDirectoryCursor;
3490
3825
  constructor(options) {
3491
- this.root = join3(options.outbox_dir, "usage-facts");
3492
- this.sessions = join3(this.root, "sessions");
3493
- this.batches = join3(this.root, "batches");
3826
+ this.root = join4(options.outbox_dir, "usage-facts");
3827
+ this.sessions = join4(this.root, "sessions");
3828
+ this.batches = join4(this.root, "batches");
3494
3829
  this.platform = options.platform ?? process.platform;
3495
3830
  this.custody = options.secure_file_custody ?? {};
3496
3831
  this.afterPendingWrite = options.afterPendingWrite;
@@ -3507,7 +3842,6 @@ var HostUsageFactsStore = class {
3507
3842
  await cursor?.close();
3508
3843
  }
3509
3844
  async readState(producer, hostSourceRef, hostSessionRef) {
3510
- await this.prepare();
3511
3845
  const path = this.sessionPath(producer, hostSourceRef, hostSessionRef);
3512
3846
  const value = await readOptionalJson(path, HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
3513
3847
  if (value === null) return null;
@@ -3565,11 +3899,15 @@ var HostUsageFactsStore = class {
3565
3899
  }
3566
3900
  /** Remove unreferenced local batch objects in bounded pieces after settling any exact pending transition. */
3567
3901
  async sweepOrphanedBatches(state) {
3568
- await this.prepare();
3569
3902
  const directoryPath = this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref);
3570
- await preparePrivateDirectory(directoryPath, this.platform, this.custody);
3571
3903
  const expected = expectedBatchNames(state);
3572
- const directory = await opendir(directoryPath);
3904
+ let directory;
3905
+ try {
3906
+ directory = await opendir(directoryPath);
3907
+ } catch (error) {
3908
+ if (errorCode2(error) === "ENOENT") return 0;
3909
+ throw error;
3910
+ }
3573
3911
  let inspected = 0;
3574
3912
  let deleted = 0;
3575
3913
  try {
@@ -3578,7 +3916,7 @@ var HostUsageFactsStore = class {
3578
3916
  if (entry === null) break;
3579
3917
  inspected += 1;
3580
3918
  if (!isOrphanBatchEntry(entry, expected)) continue;
3581
- await unlink2(join3(directoryPath, entry.name));
3919
+ await unlink2(join4(directoryPath, entry.name));
3582
3920
  deleted += 1;
3583
3921
  }
3584
3922
  } finally {
@@ -3606,10 +3944,9 @@ var HostUsageFactsStore = class {
3606
3944
  });
3607
3945
  }
3608
3946
  async nextUploadCandidate(producer, hostSourceRef) {
3609
- await this.prepare();
3610
3947
  const names = await this.readNextSessionNames();
3611
3948
  for (const name of names) {
3612
- const state = await readOptionalJson(join3(this.sessions, name), HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
3949
+ const state = await readOptionalJson(join4(this.sessions, name), HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
3613
3950
  if (state === null) continue;
3614
3951
  validateStateOwner(state, producer, hostSourceRef);
3615
3952
  let validated = state;
@@ -3624,7 +3961,14 @@ var HostUsageFactsStore = class {
3624
3961
  return null;
3625
3962
  }
3626
3963
  async readNextSessionNames() {
3627
- this.sessionDirectoryCursor ??= await opendir(this.sessions);
3964
+ if (this.sessionDirectoryCursor === void 0) {
3965
+ try {
3966
+ this.sessionDirectoryCursor = await opendir(this.sessions);
3967
+ } catch (error) {
3968
+ if (errorCode2(error) === "ENOENT") return [];
3969
+ throw error;
3970
+ }
3971
+ }
3628
3972
  const names = [];
3629
3973
  let inspected = 0;
3630
3974
  while (inspected < HOST_USAGE_FACTS_UPLOAD_SCAN_SESSIONS) {
@@ -3779,25 +4123,25 @@ var HostUsageFactsStore = class {
3779
4123
  const gate = new Promise((resolve2) => {
3780
4124
  release = resolve2;
3781
4125
  });
3782
- const tail = previous.then(() => gate);
3783
- SESSION_TRANSITION_TAILS.set(key, tail);
4126
+ const tail2 = previous.then(() => gate);
4127
+ SESSION_TRANSITION_TAILS.set(key, tail2);
3784
4128
  await previous;
3785
4129
  try {
3786
4130
  return await run();
3787
4131
  } finally {
3788
4132
  release?.();
3789
- if (SESSION_TRANSITION_TAILS.get(key) === tail) SESSION_TRANSITION_TAILS.delete(key);
4133
+ if (SESSION_TRANSITION_TAILS.get(key) === tail2) SESSION_TRANSITION_TAILS.delete(key);
3790
4134
  }
3791
4135
  }
3792
4136
  sessionPath(producer, hostSourceRef, hostSessionRef) {
3793
- return join3(this.sessions, `${sha2562(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`);
4137
+ return join4(this.sessions, `${sha2562(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`);
3794
4138
  }
3795
4139
  batchSessionDirectory(producer, hostSourceRef, hostSessionRef) {
3796
4140
  const sessionName = `${sha2562(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`;
3797
- return join3(this.batches, sessionName.slice(0, -5));
4141
+ return join4(this.batches, sessionName.slice(0, -5));
3798
4142
  }
3799
4143
  batchPath(state, batchRef) {
3800
- return join3(this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref), batchFileName(batchRef));
4144
+ return join4(this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref), batchFileName(batchRef));
3801
4145
  }
3802
4146
  };
3803
4147
  function serializeBatch(batch) {
@@ -4047,29 +4391,46 @@ var HostUsageTranscriptSourceError = class extends Error {
4047
4391
  this.name = "HostUsageTranscriptSourceError";
4048
4392
  }
4049
4393
  };
4050
- async function readHostUsageTranscriptSource(read) {
4394
+ async function readHostUsageTranscriptSource(read2) {
4051
4395
  try {
4052
- return await read();
4396
+ return await read2();
4053
4397
  } catch (error) {
4054
4398
  throw new HostUsageTranscriptSourceError({ cause: error });
4055
4399
  }
4056
4400
  }
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;
4401
+ var HostUsageRegistrationCapture = class {
4402
+ nextIndex = 0;
4403
+ producer;
4404
+ diagnosticSink;
4405
+ constructor(producer, diagnosticSink) {
4406
+ this.producer = producer;
4407
+ this.diagnosticSink = diagnosticSink;
4408
+ }
4409
+ async captureNext(registrations, capture) {
4410
+ let failed = false;
4411
+ let captured = false;
4412
+ const onFailure = () => {
4068
4413
  failed = true;
4414
+ };
4415
+ for (let attempt = 0; attempt < registrations.length; attempt += 1) {
4416
+ const index = (this.nextIndex + attempt) % registrations.length;
4417
+ const registration = registrations[index];
4418
+ if (registration === void 0) continue;
4419
+ try {
4420
+ captured = await capture(registration, onFailure);
4421
+ if (captured) {
4422
+ this.nextIndex = (index + 1) % registrations.length;
4423
+ break;
4424
+ }
4425
+ } catch (error) {
4426
+ if (!(error instanceof HostUsageTranscriptSourceError)) throw error;
4427
+ onFailure();
4428
+ }
4069
4429
  }
4430
+ if (failed) writeHostServiceDiagnostic(this.producer, "usage_capture_failed", void 0, "capture_failed", this.diagnosticSink);
4431
+ return captured;
4070
4432
  }
4071
- return { captured: false, nextIndex: startIndex, failed };
4072
- }
4433
+ };
4073
4434
  async function openHostUsageTranscriptCursor(input) {
4074
4435
  const handle = await readHostUsageTranscriptSource(() => openNoFollow(input.path, constants3.O_RDONLY));
4075
4436
  let source;
@@ -4326,6 +4687,10 @@ var HostUsageFactsUploader = class {
4326
4687
  async close() {
4327
4688
  await this.store.close();
4328
4689
  }
4690
+ /** The start owner prepares the store once, so idle ticks below never re-prepare. */
4691
+ async prepare() {
4692
+ await this.store.prepare();
4693
+ }
4329
4694
  async uploadOne(signal) {
4330
4695
  const candidate = await this.store.nextUploadCandidate(this.options.producer, this.options.host_source_ref);
4331
4696
  if (candidate === null) return false;
@@ -4348,6 +4713,11 @@ var HostUsageFactsUploader = class {
4348
4713
  };
4349
4714
  async function runHostUsageFactsUploader(options, signal, wait = waitForAbort) {
4350
4715
  const uploader = new HostUsageFactsUploader(options);
4716
+ try {
4717
+ await uploader.prepare();
4718
+ } catch {
4719
+ writeHostServiceDiagnostic(options.producer, "usage_upload_failed", void 0, "upload_failed");
4720
+ }
4351
4721
  let delay = 500;
4352
4722
  let failures = 0;
4353
4723
  try {
@@ -4392,7 +4762,7 @@ var RELAY_PIPE_FRAME_BYTES = Uint32Array.BYTES_PER_ELEMENT;
4392
4762
  var HOST_RELAY_IPC_LENGTH_BYTES = Uint32Array.BYTES_PER_ELEMENT;
4393
4763
 
4394
4764
  // host/claude/src/claude-invocation-context.ts
4395
- import { isAbsolute as isAbsolute3 } from "node:path";
4765
+ import { isAbsolute as isAbsolute4 } from "node:path";
4396
4766
  function claudeInvocationContextFromTurn(identity, promptRef, expiresAt, workingDirectory, turnGenerationRef) {
4397
4767
  return invocationContextFromTurn(identity, promptRef, expiresAt, { schema_version: CLAUDE_INVOCATION_CONTEXT_SCHEMA_VERSION, validate: validateClaudeHostInvocationContext, working_directory: workingDirectory, turn_generation_ref: turnGenerationRef });
4398
4768
  }
@@ -4421,7 +4791,7 @@ function optionalSafeRef(value) {
4421
4791
  return value === void 0 || safeRef2(value);
4422
4792
  }
4423
4793
  function optionalDirectory(value) {
4424
- return value === void 0 || typeof value === "string" && isAbsolute3(value) && !value.includes("\0") && value.length <= 4096;
4794
+ return value === void 0 || typeof value === "string" && isAbsolute4(value) && !value.includes("\0") && value.length <= 4096;
4425
4795
  }
4426
4796
  function safeRef2(value) {
4427
4797
  return typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test(value);
@@ -4446,14 +4816,14 @@ var ClaudeOutboxStore = class {
4446
4816
  activeContexts;
4447
4817
  turnSelections;
4448
4818
  constructor(directory) {
4449
- if (!isAbsolute4(directory)) throw new ClaudeHostError("configuration", "Claude outbox directory must be absolute.");
4819
+ if (!isAbsolute5(directory)) throw new ClaudeHostError("configuration", "Claude outbox directory must be absolute.");
4450
4820
  this.directory = directory;
4451
- this.envelopes = join4(directory, "envelopes");
4452
- this.sessions = join4(directory, "sessions");
4453
- this.registrations = join4(directory, "transcript-registrations");
4454
- this.cursors = join4(directory, "transcript-cursors");
4455
- this.activeContexts = join4(directory, "active-contexts");
4456
- this.turnSelections = join4(directory, "turn-selections");
4821
+ this.envelopes = join5(directory, "envelopes");
4822
+ this.sessions = join5(directory, "sessions");
4823
+ this.registrations = join5(directory, "transcript-registrations");
4824
+ this.cursors = join5(directory, "transcript-cursors");
4825
+ this.activeContexts = join5(directory, "active-contexts");
4826
+ this.turnSelections = join5(directory, "turn-selections");
4457
4827
  }
4458
4828
  async prepare() {
4459
4829
  for (const path of [this.envelopes, this.sessions, this.registrations, this.cursors, this.activeContexts, this.turnSelections]) {
@@ -4481,6 +4851,7 @@ var ClaudeOutboxStore = class {
4481
4851
  const path = this.activeContextPath(identity);
4482
4852
  const active = await readProjectionFile(path);
4483
4853
  if (active === null || active.prompt_ref !== promptRef || active.identity.host_turn_ref !== identity.host_turn_ref) return false;
4854
+ await this.prepare();
4484
4855
  const updated = { ...active, turn_generation_ref: turnGenerationRef };
4485
4856
  validateClaudeHostInvocationContext(updated);
4486
4857
  await durableAtomicReplace(path, JSON.stringify(updated));
@@ -4493,17 +4864,15 @@ var ClaudeOutboxStore = class {
4493
4864
  */
4494
4865
  async readRawInvocationContext(hostSourceRef, hostSessionRef) {
4495
4866
  if (!SAFE_REF2.test(hostSourceRef) || !SAFE_REF2.test(hostSessionRef)) throw new ClaudeHostError("invalid_input", "Claude Host context identity or clock is invalid.");
4496
- await this.prepare();
4497
4867
  const context = await readLatestSessionProjection(this.activeContextPath({ host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }), hostSourceRef, hostSessionRef, readProjectionFile);
4498
4868
  return context;
4499
4869
  }
4500
4870
  async listInvocationContexts(now = /* @__PURE__ */ new Date()) {
4501
- await this.prepare();
4502
4871
  const contexts = [];
4503
- for (const name of await readdir(this.activeContexts)) {
4872
+ for (const name of await listHostOutboxDirectoryNames(this.activeContexts)) {
4504
4873
  if (!name.endsWith(".json")) continue;
4505
4874
  try {
4506
- const value = JSON.parse(await readFile(join4(this.activeContexts, name), "utf8"));
4875
+ const value = JSON.parse(await readFile(join5(this.activeContexts, name), "utf8"));
4507
4876
  validateClaudeHostInvocationContext(value);
4508
4877
  if (Date.parse(value.expires_at) > now.getTime()) contexts.push(value);
4509
4878
  } catch {
@@ -4517,13 +4886,12 @@ var ClaudeOutboxStore = class {
4517
4886
  await durableAtomicReplace(this.envelopePath(entry.submission_ref), JSON.stringify(entry));
4518
4887
  }
4519
4888
  async listEnvelopes() {
4520
- await this.prepare();
4521
4889
  const entries = [];
4522
4890
  let malformed = 0;
4523
- for (const name of await readdir(this.envelopes)) {
4891
+ for (const name of await listHostOutboxDirectoryNames(this.envelopes)) {
4524
4892
  if (!name.endsWith(".json")) continue;
4525
4893
  try {
4526
- const value = JSON.parse(await readFile(join4(this.envelopes, name), "utf8"));
4894
+ const value = JSON.parse(await readFile(join5(this.envelopes, name), "utf8"));
4527
4895
  validateEnvelope(value);
4528
4896
  entries.push(value);
4529
4897
  } catch {
@@ -4544,13 +4912,12 @@ var ClaudeOutboxStore = class {
4544
4912
  async saveSession(snapshot) {
4545
4913
  validateSession(snapshot);
4546
4914
  await this.prepare();
4547
- await durableAtomicReplace(join4(this.sessions, `${cealRequestSha256({ source: snapshot.host_source_ref, session: snapshot.host_session_ref })}.json`), JSON.stringify(snapshot));
4915
+ await durableAtomicReplace(join5(this.sessions, `${cealRequestSha256({ source: snapshot.host_source_ref, session: snapshot.host_session_ref })}.json`), JSON.stringify(snapshot));
4548
4916
  }
4549
4917
  async readSession(sourceRef, sessionRef) {
4550
4918
  if (!SAFE_REF2.test(sourceRef) || !SAFE_REF2.test(sessionRef)) throw new ClaudeHostError("invalid_input", "Claude session identity is invalid.");
4551
- await this.prepare();
4552
4919
  try {
4553
- const value = JSON.parse(await readFile(join4(this.sessions, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`), "utf8"));
4920
+ const value = JSON.parse(await readFile(join5(this.sessions, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`), "utf8"));
4554
4921
  validateSession(value);
4555
4922
  return value;
4556
4923
  } catch (error) {
@@ -4579,13 +4946,18 @@ var ClaudeOutboxStore = class {
4579
4946
  await this.removeStateFile(this.registrationPath(registration.host_source_ref, registration.host_session_ref));
4580
4947
  await this.removeStateFile(this.cursorPath(registration.host_source_ref, registration.host_session_ref));
4581
4948
  }
4949
+ async readTranscriptRegistration(hostSourceRef, hostSessionRef) {
4950
+ if (!SAFE_REF2.test(hostSourceRef) || !SAFE_REF2.test(hostSessionRef)) throw new ClaudeHostError("invalid_input", "Claude transcript session identity is invalid.");
4951
+ const registration = await this.readRegistrationFile(this.registrationPath(hostSourceRef, hostSessionRef));
4952
+ 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.");
4953
+ return registration;
4954
+ }
4582
4955
  async listTranscriptRegistrations() {
4583
- await this.prepare();
4584
4956
  const registrations = [];
4585
- for (const name of await readdir(this.registrations)) {
4957
+ for (const name of await listHostOutboxDirectoryNames(this.registrations)) {
4586
4958
  if (!name.endsWith(".json")) continue;
4587
4959
  try {
4588
- const value = JSON.parse(await readFile(join4(this.registrations, name), "utf8"));
4960
+ const value = JSON.parse(await readFile(join5(this.registrations, name), "utf8"));
4589
4961
  validateRegistration(value);
4590
4962
  registrations.push(value);
4591
4963
  } catch {
@@ -4595,7 +4967,6 @@ var ClaudeOutboxStore = class {
4595
4967
  }
4596
4968
  async readInvocationTurnSelection(hostSourceRef, hostSessionRef) {
4597
4969
  if (!SAFE_REF2.test(hostSourceRef) || !SAFE_REF2.test(hostSessionRef)) throw new ClaudeHostError("invalid_input", "Claude Host turn selection identity is invalid.");
4598
- await this.prepare();
4599
4970
  try {
4600
4971
  const value = JSON.parse(await readFile(this.turnSelectionPath(hostSourceRef, hostSessionRef), "utf8"));
4601
4972
  if (!isHostInvocationTurnSelection(value) || value.host_source_ref !== hostSourceRef || value.host_session_ref !== hostSessionRef) throw new ClaudeHostError("storage", "Claude Host turn selection is malformed.");
@@ -4607,7 +4978,6 @@ var ClaudeOutboxStore = class {
4607
4978
  }
4608
4979
  async readTranscriptCursor(registration) {
4609
4980
  validateRegistration(registration);
4610
- await this.prepare();
4611
4981
  try {
4612
4982
  const value = JSON.parse(await readFile(this.cursorPath(registration.host_source_ref, registration.host_session_ref), "utf8"));
4613
4983
  validateCursor(value);
@@ -4623,16 +4993,16 @@ var ClaudeOutboxStore = class {
4623
4993
  await durableAtomicReplace(this.cursorPath(cursor.host_source_ref, cursor.host_session_ref), JSON.stringify(cursor));
4624
4994
  }
4625
4995
  envelopePath(ref) {
4626
- return join4(this.envelopes, `${cealRequestSha256(ref)}.json`);
4996
+ return join5(this.envelopes, `${cealRequestSha256(ref)}.json`);
4627
4997
  }
4628
4998
  registrationPath(sourceRef, sessionRef) {
4629
- return join4(this.registrations, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
4999
+ return join5(this.registrations, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
4630
5000
  }
4631
5001
  turnSelectionPath(sourceRef, sessionRef) {
4632
- return join4(this.turnSelections, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
5002
+ return join5(this.turnSelections, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
4633
5003
  }
4634
5004
  cursorPath(sourceRef, sessionRef) {
4635
- return join4(this.cursors, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
5005
+ return join5(this.cursors, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
4636
5006
  }
4637
5007
  async readRegistrationFile(path) {
4638
5008
  try {
@@ -4652,7 +5022,7 @@ var ClaudeOutboxStore = class {
4652
5022
  }
4653
5023
  }
4654
5024
  activeContextPath(identity) {
4655
- return join4(this.activeContexts, `${invocationContextKey(identity)}.json`);
5025
+ return join5(this.activeContexts, `${invocationContextKey(identity)}.json`);
4656
5026
  }
4657
5027
  };
4658
5028
  function validateInvocationContextReadArguments(hostSourceRef, hostSessionRef, now) {
@@ -4728,7 +5098,7 @@ function validateRegistration(value) {
4728
5098
  if (!timestamp2(value.registered_at) || !timestamp2(value.expires_at)) throw new ClaudeHostError("storage", "Claude transcript registration timestamps are malformed.");
4729
5099
  }
4730
5100
  function validateRegistrationPaths(cwd, transcriptPath) {
4731
- if (cwd !== void 0 && (typeof cwd !== "string" || !isAbsolute4(cwd) || cwd.length > CLAUDE_TRANSCRIPT_PATH_MAX_CHARACTERS || cwd.includes("\0"))) {
5101
+ if (cwd !== void 0 && (typeof cwd !== "string" || !isAbsolute5(cwd) || cwd.length > CLAUDE_TRANSCRIPT_PATH_MAX_CHARACTERS || cwd.includes("\0"))) {
4732
5102
  throw new ClaudeHostError("storage", "Claude transcript registration working directory is malformed.");
4733
5103
  }
4734
5104
  if (typeof transcriptPath !== "string" || transcriptPath.length === 0 || transcriptPath.length > CLAUDE_TRANSCRIPT_PATH_MAX_CHARACTERS) {
@@ -4826,10 +5196,42 @@ function sameKeys2(value, required, optional = []) {
4826
5196
 
4827
5197
  // host/claude/src/claude-transcript-watcher.ts
4828
5198
  import { readdir as readdir2 } from "node:fs/promises";
4829
- import { join as join5 } from "node:path";
5199
+ import { isDeepStrictEqual } from "node:util";
5200
+ import { join as join6 } from "node:path";
5201
+
5202
+ // host/claude/src/claude-subagent-overflow-checkpoint.ts
5203
+ var ClaudeSubagentOverflowCheckpoint = class {
5204
+ observed = /* @__PURE__ */ new Map();
5205
+ prune(registrations) {
5206
+ const current = new Set(registrations.map(registrationKey));
5207
+ for (const key of this.observed.keys()) if (!current.has(key)) this.observed.delete(key);
5208
+ }
5209
+ clear(registration) {
5210
+ this.observed.delete(registrationKey(registration));
5211
+ }
5212
+ /** Names follow the producer's sorted inventory; only omitted names define overflow. */
5213
+ async observe(registration, names, report) {
5214
+ const key = registrationKey(registration);
5215
+ if (names.length <= CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES) {
5216
+ this.clear(registration);
5217
+ return false;
5218
+ }
5219
+ const digest2 = transcriptObjectSha256(names.slice(CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES));
5220
+ if (this.observed.get(key) === digest2) return false;
5221
+ if (!await report()) return false;
5222
+ this.observed.set(key, digest2);
5223
+ return true;
5224
+ }
5225
+ };
5226
+ function registrationKey(registration) {
5227
+ return JSON.stringify([registration.host_source_ref, registration.host_session_ref, registration.transcript_path]);
5228
+ }
5229
+
5230
+ // host/claude/src/claude-transcript-watcher.ts
4830
5231
  var TOKEN_OBSERVATION_SOURCE = "claude_transcript.message.usage";
4831
5232
  var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
4832
5233
  store;
5234
+ overflow = new ClaudeSubagentOverflowCheckpoint();
4833
5235
  diagnostic;
4834
5236
  constructor(options) {
4835
5237
  super(options, {
@@ -4844,7 +5246,9 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
4844
5246
  return registration.transcript_path;
4845
5247
  }
4846
5248
  async listRegistrations() {
4847
- return this.store.listTranscriptRegistrations();
5249
+ const registrations = await this.store.listTranscriptRegistrations();
5250
+ this.overflow.prune(registrations);
5251
+ return registrations;
4848
5252
  }
4849
5253
  async scanOpened(handle, registration) {
4850
5254
  const { size, device, inode } = await ownedClaudeTranscriptFile(handle);
@@ -4856,7 +5260,7 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
4856
5260
  }
4857
5261
  if (preflight.checkpointPending) await this.store.writeTranscriptCursor({ ...cursor, updated_at: this.stamp() });
4858
5262
  const draft = mutableCursor(cursor);
4859
- await this.scanOpenedTranscript(registration, handle, draft, size, device, inode);
5263
+ await this.scanOpenedTranscript(registration, handle, cursor, draft, size, device, inode);
4860
5264
  return { records: draft.consumed, enqueued: draft.enqueued, quarantined: false };
4861
5265
  }
4862
5266
  async scanFailed(handle, registration, error) {
@@ -4893,7 +5297,7 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
4893
5297
  updated_at: this.stamp()
4894
5298
  };
4895
5299
  }
4896
- async scanOpenedTranscript(registration, handle, draft, size, device, inode) {
5300
+ async scanOpenedTranscript(registration, handle, previous, draft, size, device, inode) {
4897
5301
  const main2 = await this.readChunk(handle, draft.offset, size);
4898
5302
  if (main2 !== "empty" && main2 !== "partial") {
4899
5303
  await this.consumeMainChunk(registration, main2, draft);
@@ -4901,7 +5305,7 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
4901
5305
  }
4902
5306
  draft.consumed += await this.consumeSubagents(registration, draft);
4903
5307
  await this.emitOpenTerminal(registration, draft);
4904
- await this.commitCursor(registration, handle, draft, device, inode);
5308
+ await this.commitCursor(registration, handle, previous, draft, device, inode);
4905
5309
  }
4906
5310
  async preflight(registration, handle, size, device, inode) {
4907
5311
  const existing = await this.store.readTranscriptCursor(registration);
@@ -5061,15 +5465,24 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
5061
5465
  try {
5062
5466
  names = (await readdir2(directory)).filter((name) => name.endsWith(".jsonl") && !name.endsWith(".meta.json")).sort();
5063
5467
  } catch (error) {
5064
- if (isMissingTranscriptError(error) || isNotDirectory(error)) return 0;
5468
+ if (isMissingTranscriptError(error) || isNotDirectory(error)) {
5469
+ this.overflow.clear(registration);
5470
+ return 0;
5471
+ }
5065
5472
  throw new ClaudeHostError("payload_rejected", "Claude subagent transcript directory is unavailable.");
5066
5473
  }
5067
5474
  const listed = new Set(names);
5068
5475
  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
- }
5476
+ await this.overflow.observe(registration, names, () => {
5477
+ const line = `Claude ignored subagent transcripts past its file bound: transcript_path=${JSON.stringify(registration.transcript_path)}, files=${names.length}.`;
5478
+ try {
5479
+ this.log(line);
5480
+ } catch {
5481
+ return false;
5482
+ }
5483
+ return true;
5484
+ });
5485
+ names = names.slice(0, CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES);
5073
5486
  let consumed = 0;
5074
5487
  for (const name of names) {
5075
5488
  consumed += await this.consumeSubagentFile(draft, directory, name);
@@ -5077,7 +5490,7 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
5077
5490
  return consumed;
5078
5491
  }
5079
5492
  async consumeSubagentFile(draft, directory, name) {
5080
- const path = join5(directory, name);
5493
+ const path = join6(directory, name);
5081
5494
  let handle;
5082
5495
  try {
5083
5496
  handle = await openNoFollow(path);
@@ -5158,9 +5571,9 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
5158
5571
  expires_at: this.expire(this.outboxRetentionMs)
5159
5572
  });
5160
5573
  }
5161
- async commitCursor(registration, handle, draft, device, inode) {
5574
+ async commitCursor(registration, handle, previous, draft, device, inode) {
5162
5575
  const anchor = await this.readAnchor(handle, draft.offset, CLAUDE_TRANSCRIPT_ANCHOR_BYTES);
5163
- await this.store.writeTranscriptCursor({
5576
+ const cursor = {
5164
5577
  schema_version: CLAUDE_TRANSCRIPT_CURSOR_SCHEMA_VERSION,
5165
5578
  host_source_ref: registration.host_source_ref,
5166
5579
  host_session_ref: registration.host_session_ref,
@@ -5177,7 +5590,9 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
5177
5590
  ...draft.session_observed ? { session_observed: true } : {},
5178
5591
  status: "active",
5179
5592
  updated_at: this.stamp()
5180
- });
5593
+ };
5594
+ if (sameCursorContent(cursor, previous)) return;
5595
+ await this.store.writeTranscriptCursor(cursor);
5181
5596
  }
5182
5597
  async activateContext(identity, promptRef, turnGenerationRef, expiresAt) {
5183
5598
  try {
@@ -5228,6 +5643,9 @@ function mutableCursor(cursor) {
5228
5643
  enqueued: 0
5229
5644
  };
5230
5645
  }
5646
+ function sameCursorContent(left, right) {
5647
+ return isDeepStrictEqual({ ...left, updated_at: void 0 }, { ...right, updated_at: void 0 });
5648
+ }
5231
5649
  function zeroCounts() {
5232
5650
  return { input: 0, cached_input: 0, cache_write_input: 0, output: 0 };
5233
5651
  }
@@ -5321,7 +5739,7 @@ function isAssistantUsageLine(record5) {
5321
5739
  }
5322
5740
  function subagentsDirectory(transcriptPath) {
5323
5741
  const stem = transcriptPath.endsWith(".jsonl") ? transcriptPath.slice(0, -".jsonl".length) : transcriptPath;
5324
- return join5(stem, "subagents");
5742
+ return join6(stem, "subagents");
5325
5743
  }
5326
5744
  function observationRef(hostSourceRef, event, identity, value) {
5327
5745
  return cealHostObservationRef("claude", transcriptObjectSha256({ host_source_ref: hostSourceRef, event, identity, value }));
@@ -5361,30 +5779,25 @@ function isSymlinkTranscript(error) {
5361
5779
  import { createHash as createHash8 } from "node:crypto";
5362
5780
  import { constants as constants5 } from "node:fs";
5363
5781
  import { readdir as readdir3 } from "node:fs/promises";
5364
- import { join as join6 } from "node:path";
5782
+ import { join as join7 } from "node:path";
5365
5783
  var ClaudeUsageFactsCapturer = class {
5366
5784
  sources;
5367
5785
  usage;
5368
5786
  now;
5369
- diagnosticSink;
5370
- nextRegistrationIndex = 0;
5787
+ registrations;
5371
5788
  nextSourceSlot = "main";
5372
5789
  nextSubagentIndex = 0;
5790
+ overflow = new ClaudeSubagentOverflowCheckpoint();
5373
5791
  constructor(options) {
5374
5792
  this.sources = new ClaudeOutboxStore(options.outbox_dir);
5375
5793
  this.usage = new HostUsageFactsStore({ outbox_dir: options.outbox_dir, ...options.store_options });
5376
5794
  this.now = options.now ?? (() => /* @__PURE__ */ new Date());
5377
- this.diagnosticSink = options.diagnostic_sink;
5795
+ this.registrations = new HostUsageRegistrationCapture("claude", options.diagnostic_sink);
5378
5796
  }
5379
5797
  async captureNext() {
5380
5798
  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;
5799
+ this.overflow.prune(registrations);
5800
+ return await this.registrations.captureNext(registrations, (registration, onFailure) => this.captureRegistration(registration, onFailure));
5388
5801
  }
5389
5802
  async captureRegistration(registration, onFailure) {
5390
5803
  const sources = this.nextSourceSlot === "main" ? ["main", "subagent"] : ["subagent", "main"];
@@ -5431,13 +5844,14 @@ var ClaudeUsageFactsCapturer = class {
5431
5844
  }
5432
5845
  async captureSubagent(registration, onFailure) {
5433
5846
  const names = await readSubagentNames(registration);
5847
+ if (names.length <= CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES) this.overflow.clear(registration);
5434
5848
  let state = await this.usage.readState("claude", registration.host_source_ref, registration.host_session_ref);
5435
5849
  if (state === null) return false;
5436
5850
  state = await this.usage.recoverPending(state);
5437
5851
  if (state.quarantined_reason !== void 0) return false;
5438
5852
  if (await this.retireMissingSubagent(state, names)) return true;
5439
5853
  if (await this.captureListedSubagents(registration, names, state, onFailure)) return true;
5440
- return await this.recordExcessSubagentGap(state, names);
5854
+ return await this.recordExcessSubagentGap(registration, state, names);
5441
5855
  }
5442
5856
  async retireMissingSubagent(state, names) {
5443
5857
  const liveSlots = new Set(names.slice(0, CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES).map(subagentSlot));
@@ -5448,14 +5862,14 @@ var ClaudeUsageFactsCapturer = class {
5448
5862
  }
5449
5863
  return false;
5450
5864
  }
5451
- async recordExcessSubagentGap(state, names) {
5452
- const excessCount = names.length - CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES;
5453
- if (excessCount <= 0) return false;
5865
+ async recordExcessSubagentGap(registration, state, names) {
5454
5866
  const mainCursor = state.cursors.main;
5455
5867
  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;
5868
+ return await this.overflow.observe(registration, names, async () => {
5869
+ 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 };
5870
+ await this.usage.commitScanTransition(state, "main", mainCursor, mainCursor, null, [gap]);
5871
+ return true;
5872
+ });
5459
5873
  }
5460
5874
  async captureListedSubagents(registration, names, state, onFailure) {
5461
5875
  const candidates = names.slice(0, CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES);
@@ -5478,7 +5892,7 @@ var ClaudeUsageFactsCapturer = class {
5478
5892
  async captureSubagentFile(registration, name, state) {
5479
5893
  let handle;
5480
5894
  try {
5481
- const opened = await readHostUsageTranscriptSource(() => openNoFollow(join6(subagentsDirectory(registration.transcript_path), name), constants5.O_RDONLY));
5895
+ const opened = await readHostUsageTranscriptSource(() => openNoFollow(join7(subagentsDirectory(registration.transcript_path), name), constants5.O_RDONLY));
5482
5896
  handle = opened;
5483
5897
  const file = await readHostUsageTranscriptSource(() => ownedClaudeTranscriptFile(opened));
5484
5898
  const sourceRef = sourceFileRef(registration, file.device, file.inode);
@@ -5733,18 +6147,18 @@ import { createHash as createHash9, randomUUID } from "node:crypto";
5733
6147
  import { readdir as readdir4 } from "node:fs/promises";
5734
6148
  import { constants as constants6 } from "node:fs";
5735
6149
  import { homedir } from "node:os";
5736
- import { isAbsolute as isAbsolute5, join as join8, relative, resolve } from "node:path";
6150
+ import { isAbsolute as isAbsolute6, join as join9, relative, resolve } from "node:path";
5737
6151
 
5738
6152
  // host/claude/src/claude-runtime-paths.ts
5739
- import { join as join7 } from "node:path";
6153
+ import { join as join8 } from "node:path";
5740
6154
  var CLAUDE_CONFIG_DIRECTORY_ENVIRONMENT = "CLAUDE_CONFIG_DIR";
5741
6155
  var CLAUDE_HOME_DEFAULT_DIRECTORY = ".claude";
5742
6156
  var CLAUDE_PROJECTS_DIRECTORY = "projects";
5743
6157
  function resolveClaudeConfigHome(environment, home) {
5744
- return environment[CLAUDE_CONFIG_DIRECTORY_ENVIRONMENT] || join7(home, CLAUDE_HOME_DEFAULT_DIRECTORY);
6158
+ return environment[CLAUDE_CONFIG_DIRECTORY_ENVIRONMENT] || join8(home, CLAUDE_HOME_DEFAULT_DIRECTORY);
5745
6159
  }
5746
6160
  function resolveClaudeProjectsRoot(environment, home) {
5747
- return join7(resolveClaudeConfigHome(environment, home), CLAUDE_PROJECTS_DIRECTORY);
6161
+ return join8(resolveClaudeConfigHome(environment, home), CLAUDE_PROJECTS_DIRECTORY);
5748
6162
  }
5749
6163
 
5750
6164
  // host/claude/src/claude-adapter.ts
@@ -5794,8 +6208,8 @@ var ClaudeHookAdapter = class {
5794
6208
  registered_at: observedAt,
5795
6209
  expires_at: expiresAt
5796
6210
  };
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) {
6211
+ const existing = await this.store.readTranscriptRegistration(registration.host_source_ref, registration.host_session_ref);
6212
+ if (existing === null) {
5799
6213
  await this.store.writeTranscriptCursor((await captureClaudeTranscriptBaseline(registration, this.now, void 0, this.platform, this.custody)).cursor);
5800
6214
  }
5801
6215
  await this.store.registerTranscript(registration);
@@ -5828,11 +6242,11 @@ var ClaudeHookAdapter = class {
5828
6242
  const promptRef = hostProducerPromptRef(createHash9("sha256").update(input.prompt, "utf8").digest("hex"));
5829
6243
  const turnGenerationRef = this.randomUuid();
5830
6244
  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);
6245
+ const existing = await this.store.readTranscriptRegistration(registration.host_source_ref, registration.host_session_ref);
5832
6246
  const baseline = await captureClaudeTranscriptBaseline(registration, this.now, input.prompt, this.platform, this.custody);
5833
6247
  const transcriptTurnRef = baseline.current_turn_ref;
5834
6248
  await this.store.writeInvocationTurnSelection(selection);
5835
- if (existing === void 0) await this.store.writeTranscriptCursor(baseline.cursor);
6249
+ if (existing === null) await this.store.writeTranscriptCursor(baseline.cursor);
5836
6250
  else await refreshCurrentTurnCursor(this.store, registration, baseline, promptRef, turnGenerationRef, transcriptTurnRef);
5837
6251
  await this.store.registerTranscript(registration);
5838
6252
  return { event: input.event, disposition: "ignored", reason: "transcript_registered", local_session_ref: hostSessionRef, ...transcriptTurnRef === void 0 ? {} : { local_turn_ref: transcriptTurnRef } };
@@ -5842,11 +6256,11 @@ function sessionObservationValue(input) {
5842
6256
  return { status: "started", host_kind: "claude", source: input.source, model: input.model ?? "unavailable", decoder_evidence_version: "claude-code-2.1.258" };
5843
6257
  }
5844
6258
  function sourceBoundTranscriptPath(path, transcriptsRoot, platform = process.platform) {
5845
- if (!isAbsolute5(path) || !isAbsolute5(transcriptsRoot)) throw new ClaudeHostError("configuration", "Claude transcript registration paths must be absolute.");
6259
+ if (!isAbsolute6(path) || !isAbsolute6(transcriptsRoot)) throw new ClaudeHostError("configuration", "Claude transcript registration paths must be absolute.");
5846
6260
  const transcript = resolve(path);
5847
6261
  const root = resolve(transcriptsRoot);
5848
6262
  const child = relative(root, transcript);
5849
- if (child === "" || child === ".." || child.startsWith(`..${platform === "win32" ? "\\" : "/"}`) || isAbsolute5(child)) {
6263
+ if (child === "" || child === ".." || child.startsWith(`..${platform === "win32" ? "\\" : "/"}`) || isAbsolute6(child)) {
5850
6264
  throw new ClaudeHostError("invalid_input", "Claude transcript path is outside the configured transcripts root.");
5851
6265
  }
5852
6266
  return transcript;
@@ -5915,8 +6329,10 @@ var CLAUDE_BASELINE_SCAN_LINES = 128;
5915
6329
  async function readRecentClaudeTranscriptLines(handle, size) {
5916
6330
  if (size === 0) return null;
5917
6331
  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);
6332
+ const readStart = Math.max(0, start - 1);
6333
+ const tail2 = Buffer.alloc(size - readStart);
6334
+ await handle.read(tail2, 0, tail2.length, readStart);
6335
+ const buffer = tail2.subarray(start - readStart);
5920
6336
  const lines = [];
5921
6337
  let lineStart = 0;
5922
6338
  for (let index = 0; index < buffer.length; index += 1) {
@@ -5926,7 +6342,7 @@ async function readRecentClaudeTranscriptLines(handle, size) {
5926
6342
  }
5927
6343
  if (lineStart < buffer.length) lines.push({ start: start + lineStart, text: buffer.subarray(lineStart).toString("utf8"), complete: false });
5928
6344
  if (lines.length === 0) return null;
5929
- const whole = start > 0 ? lines.slice(1) : lines;
6345
+ const whole = start === 0 || tail2[0] === 10 ? lines : lines.slice(1);
5930
6346
  if (whole.length === 0) return null;
5931
6347
  return whole.slice(-CLAUDE_BASELINE_SCAN_LINES);
5932
6348
  }
@@ -5979,7 +6395,7 @@ async function readClaudeSubagentBaseline(transcriptPath, platform, custody) {
5979
6395
  async function readClaudeSubagentSeed(directory, name, platform, custody) {
5980
6396
  let handle;
5981
6397
  try {
5982
- handle = await openNoFollow(join8(directory, name), constants6.O_RDONLY, void 0, platform, custody);
6398
+ handle = await openNoFollow(join9(directory, name), constants6.O_RDONLY, void 0, platform, custody);
5983
6399
  const stats = await handle.stat();
5984
6400
  if (!stats.isFile()) throw new ClaudeHostError("storage", "Claude subagent baseline source is not a regular file.");
5985
6401
  if (platform !== "win32" && !isSelfOwned(stats.uid, platform, handle)) throw new ClaudeHostError("storage", "Claude subagent baseline source is owned by another user.");
@@ -6056,11 +6472,14 @@ var ClaudeProducer = class {
6056
6472
  };
6057
6473
 
6058
6474
  // host/claude/src/claude-producer-runtime.ts
6059
- async function drainClaudeProducerOnce(options) {
6060
- const scan = await new ClaudeTranscriptWatcher({
6061
- outbox_dir: options.outbox_dir,
6475
+ function createClaudeProducerWatcher(outboxDir) {
6476
+ return new ClaudeTranscriptWatcher({
6477
+ outbox_dir: outboxDir,
6062
6478
  diagnostic: (event, failure_kind, cause) => writeHostServiceDiagnostic("claude", event, failure_kind, cause)
6063
- }).scanOnce().catch((error) => {
6479
+ });
6480
+ }
6481
+ async function drainClaudeProducerOnce(options) {
6482
+ const scan = await (options.watcher ?? createClaudeProducerWatcher(options.outbox_dir)).scanOnce().catch((error) => {
6064
6483
  writeHostServiceDiagnostic("claude", "watcher_scan_failed", claudeTranscriptScanFailureKind(error), claudeTranscriptScanCause(void 0, error));
6065
6484
  throw error;
6066
6485
  });
@@ -6070,7 +6489,7 @@ async function drainClaudeProducerOnce(options) {
6070
6489
 
6071
6490
  // host/claude/src/claude-hook-runner.ts
6072
6491
  import { homedir as homedir2 } from "node:os";
6073
- import { join as join9 } from "node:path";
6492
+ import { join as join10 } from "node:path";
6074
6493
 
6075
6494
  // host/producer-service.ts
6076
6495
  import { posix as posix4, win32 as win325 } from "node:path";
@@ -6248,7 +6667,7 @@ function parseCanonicalJson(text, error) {
6248
6667
  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
6668
  return value;
6250
6669
  } catch (parseError) {
6251
- throw error("invalid_config", refusalFacts([{ name: "parse_error", value: parseError }, { name: "config_bytes", value: Buffer.byteLength(text, "utf8"), expected: "canonical JSON" }]));
6670
+ throw error("invalid_config", `parse_error=${renderOperatorDiagnostic(parseError)}; ${refusalFact("config_bytes", Buffer.byteLength(text, "utf8"), "canonical JSON")}`);
6252
6671
  }
6253
6672
  }
6254
6673
  function firstDifferenceIndex(left, right) {
@@ -6310,7 +6729,7 @@ var CLAUDE_PRODUCER_DESCRIPTOR = {
6310
6729
  producer_id: "claude",
6311
6730
  extra_paths: [CLAUDE_TRANSCRIPTS_ROOT],
6312
6731
  config: (shared, extras) => ({ ...shared, claude_transcripts_root: hostProducerExtraPath(extras, CLAUDE_TRANSCRIPTS_ROOT) }),
6313
- runtime_options: (config) => Object.freeze({ outbox_dir: config.outbox_dir }),
6732
+ runtime_options: (config) => Object.freeze({ outbox_dir: config.outbox_dir, watcher: createClaudeProducerWatcher(config.outbox_dir) }),
6314
6733
  drain: drainClaudeProducerOnce,
6315
6734
  background: (config, signal, dependencies) => {
6316
6735
  const capturer = new ClaudeUsageFactsCapturer({ outbox_dir: config.outbox_dir });
@@ -6359,7 +6778,7 @@ async function installedClaudeHookRunnerOptions(args, custody = {}) {
6359
6778
  }
6360
6779
  function standaloneClaudeHookRunnerOptions(overrides) {
6361
6780
  const claudeHome = resolveClaudeConfigHome(process.env, homedir2());
6362
- return { outbox_dir: overrides?.outbox_dir ?? join9(claudeHome, ".ceal", "claude-observation-outbox"), claude_transcripts_root: resolveClaudeProjectsRoot(process.env, homedir2()) };
6781
+ return { outbox_dir: overrides?.outbox_dir ?? join10(claudeHome, ".ceal", "claude-observation-outbox"), claude_transcripts_root: resolveClaudeProjectsRoot(process.env, homedir2()) };
6363
6782
  }
6364
6783
  function hasHostConfigArgument(args) {
6365
6784
  return args.some((argument) => argument === HOST_PRODUCER_CONFIG_FLAG || argument.startsWith(`${HOST_PRODUCER_CONFIG_FLAG}=`));