@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.
@@ -2207,7 +2207,7 @@ var client_wire_contract_default = {
2207
2207
  },
2208
2208
  command_request: {
2209
2209
  schema_name: "ceal.command_request",
2210
- fields: ["schema_version", "argv", "operation", "client_nonce", "context_token", "request_context"],
2210
+ fields: ["schema_version", "argv", "operation", "client_nonce", "context_token", "request_context", "materialize_result"],
2211
2211
  absolute_transport_max_bytes: 65536
2212
2212
  },
2213
2213
  command_resolution: {
@@ -2253,7 +2253,7 @@ var client_wire_contract_default = {
2253
2253
  },
2254
2254
  command_response: {
2255
2255
  schema_name: "ceal.command_response",
2256
- fields: ["schema_version", "exit_code", "document", "operation_id", "visible_output_max_bytes", "local_delivery", "verified_artifact", "request_context"],
2256
+ fields: ["schema_version", "exit_code", "document", "operation_id", "visible_output_max_bytes", "local_delivery", "verified_artifact", "request_context", "result_file"],
2257
2257
  descriptor_field: "verified_artifact",
2258
2258
  request_context_field: "request_context",
2259
2259
  required_fields: [
@@ -2266,7 +2266,8 @@ var client_wire_contract_default = {
2266
2266
  "visible_output_max_bytes",
2267
2267
  "local_delivery",
2268
2268
  "verified_artifact",
2269
- "request_context"
2269
+ "request_context",
2270
+ "result_file"
2270
2271
  ],
2271
2272
  bare_document_fields: [
2272
2273
  "invocation",
@@ -2535,6 +2536,9 @@ var CEAL_OPERATION_READINESS_VALUES = vocabulary(["ready", "degraded", "unavaila
2535
2536
  var CEAL_TARGET_REQUIREMENTS = vocabulary(["required", "optional", "none"]);
2536
2537
  var CEAL_AUDIT_OUTCOMES = vocabulary(["succeeded", "denied", "failed"]);
2537
2538
  var CEAL_GATEWAY_PROVIDER_STEP_OUTCOMES = vocabulary(["completed", "rejected", "throttled", "failed"]);
2539
+ var CEAL_GATEWAY_CORPUS_READ_PROVIDERS = vocabulary(["slack", "google_drive", "notion"]);
2540
+ var CEAL_GATEWAY_CORPUS_READ_OUTCOMES = vocabulary(["answered_from_corpus", "live_fallback"]);
2541
+ var CEAL_GATEWAY_CORPUS_READ_FALLBACK_REASONS = vocabulary(["uncovered_window", "stale", "not_organization_public", "partition_missing"]);
2538
2542
  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"]);
2539
2543
  var CEAL_GATEWAY_READ_REUSE_UNAVAILABLE_REASONS = vocabulary(["not_reported", "storage_unavailable", "coverage_incomplete", "freshness_refresh_required", "not_reusable", "bypassed"]);
2540
2544
  var CEAL_GATEWAY_DERIVED_STORE_FAILURE_CLASSES = vocabulary(["storage_unavailable", "decode_mismatch", "write_conflict", "quota", "store_error"]);
@@ -2575,6 +2579,21 @@ var CEAL_GATEWAY_ORGANIZATION_ROUTE_FACT_CALL_KEYS = Object.freeze([
2575
2579
  ]);
2576
2580
 
2577
2581
  // packages/ceal-client-protocol/src/gateway-validation-primitives.ts
2582
+ var POSIX_HOME_ROOTS = [["/", "home"].join(""), ["/", "Users"].join("")];
2583
+ var WINDOWS_HOME_ROOT = ["C:", "\\", "Users"].join("");
2584
+ var USER_SEGMENT_BODY = "[^/\\\\ \\t\\r\\n\"'`${}]+";
2585
+ var POSIX_SEGMENT_END = "(?:/|$|(?=[\\s\"'`]))";
2586
+ var WINDOWS_SEGMENT_END = "(?:\\\\+|$|(?=[\\s\"'`]))";
2587
+ var WINDOWS_USER_SEGMENT_BODY = "[^\\\\ \\t\\r\\n\"'`${}]+";
2588
+ var ABSOLUTE_PATH_BOUNDARY = "(?<![A-Za-z0-9_])";
2589
+ function escapePathPattern(value) {
2590
+ return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
2591
+ }
2592
+ function machineHomePathPatterns(flags) {
2593
+ const posix12 = `${ABSOLUTE_PATH_BOUNDARY}(?:${POSIX_HOME_ROOTS.map(escapePathPattern).join("|")})/${USER_SEGMENT_BODY}${POSIX_SEGMENT_END}`;
2594
+ const windows = `${ABSOLUTE_PATH_BOUNDARY}${escapePathPattern(WINDOWS_HOME_ROOT)}\\\\+${WINDOWS_USER_SEGMENT_BODY}${WINDOWS_SEGMENT_END}`;
2595
+ return [new RegExp(posix12, flags), new RegExp(windows, flags)];
2596
+ }
2578
2597
  var CealProtocolValidationError = class extends Error {
2579
2598
  name = "CealProtocolValidationError";
2580
2599
  code;
@@ -2930,6 +2949,7 @@ var CLIENT_HOST_RELEASE_MISMATCH = "Install or upgrade the Ceal CLI and Host Rel
2930
2949
  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.";
2931
2950
  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.";
2932
2951
  var SESSION_CONTEXT_UNAVAILABLE = "The local Gateway session context is unavailable.";
2952
+ var SESSION_ADOPT_RECOVERY = "The refresh Session is no longer usable. Run `ceal session adopt --gateway <origin> --email <email>` to complete mailbox-confirmed recovery.";
2933
2953
  function guidance(message, next_action, http_status, retryable = false, redaction_class = "model_safe") {
2934
2954
  return Object.freeze({ message, next_action, http_status, retryable, redaction_class });
2935
2955
  }
@@ -2950,13 +2970,18 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
2950
2970
  context_not_selected: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
2951
2971
  context_store_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
2952
2972
  context_store_conflict: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
2953
- refresh_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
2954
- refresh_expired: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
2955
- refresh_replayed: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
2956
- refresh_revoked: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
2957
- person_inactive: guidance("The Person is inactive, so the Gateway refused this refresh without revoking the Session family.", "ask_admin", 403),
2958
- principal_inactive: guidance("The Principal is inactive, so the Gateway refused this refresh without revoking the Session family.", "ask_admin", 403),
2959
- refresh_recovery_unavailable: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
2973
+ refresh_invalid: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
2974
+ refresh_expired: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
2975
+ refresh_replayed: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
2976
+ refresh_revoked: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
2977
+ 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),
2978
+ 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),
2979
+ 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),
2980
+ refresh_inactive: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 410),
2981
+ 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),
2982
+ 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),
2983
+ refresh_state_unavailable: guidance("The Gateway session state store is temporarily unavailable; retry the same refresh attempt when it is available.", "retry", 503, true),
2984
+ refresh_recovery_expired: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 410),
2960
2985
  refresh_custody_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
2961
2986
  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),
2962
2987
  local_output_exists: guidance("The selected local output path already exists; nothing was written to it.", "choose_new_output_path", 400),
@@ -2971,10 +2996,8 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
2971
2996
  resource_stream_failed: guidance("The provider resource stream failed; ask an administrator to inspect the Gateway failure log.", "ask_admin", 500),
2972
2997
  gateway_unavailable: guidance(GATEWAY_TRANSPORT_UNAVAILABLE, "ask_admin", 503, true),
2973
2998
  contract_mismatch: guidance(CLIENT_HOST_RELEASE_MISMATCH, "upgrade_ceal_client", 409),
2974
- // `gateway_starting` is the one retryable envelope the serving gate answers on every route while starting
2975
- // (`cli/internal/client/gateway_startup_wait.go` re-drives it); the sentence is the client default that renders
2976
- // when the wait ends still unserved, moved from the `localFailureText` default branch.
2977
- [CEAL_GATEWAY_STARTING_FAILURE_CODE]: guidance(LOCAL_TRANSPORT_INCOMPLETE, "answer_with_gap", 503, true),
2999
+ // The serving gate answers before refresh execution, so retrying the same attempt is safe.
3000
+ [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),
2978
3001
  gateway_internal_error: guidance("The Gateway failed without exposing internal state; report this as a gap.", "answer_with_gap", 500),
2979
3002
  // The serving gate emits this code with no message; the sentence is the owner-normalized form of the
2980
3003
  // `gateway_internal_error` guidance (decided with the operator 2026-10-13).
@@ -2986,6 +3009,8 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
2986
3009
  // The safe move varies by request. Keep the sentence conditional on the
2987
3010
  // same `retryable` and `next_action` facts the response exposes.
2988
3011
  unknown_outcome: guidance("The transport outcome is unknown; use retryable and next_action to decide whether it can be repeated.", "answer_with_gap", 500),
3012
+ // 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.
3013
+ 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),
2989
3014
  // Restored verbatim from the retired `localFailureText`
2990
3015
  // `refresh_unknown_outcome` case: a refresh that ends unknown leaves the
2991
3016
  // session context unavailable, so the caller repairs or adopts the
@@ -3642,6 +3667,8 @@ var CEAL_ACTIVITY_TIMESTAMP_BASES = vocabulary([
3642
3667
  "review_submitted",
3643
3668
  "comment_created",
3644
3669
  "reaction_created",
3670
+ "pull_request_merged",
3671
+ "release_published",
3645
3672
  "ceal_write_completed",
3646
3673
  "event_start",
3647
3674
  "all_day_start",
@@ -3653,7 +3680,7 @@ var CEAL_ACTIVITY_TIMESTAMP_BASES = vocabulary([
3653
3680
  "page_last_edited",
3654
3681
  "resource_modified"
3655
3682
  ]);
3656
- var CEAL_ACTIVITY_CONNECTOR_KINDS = vocabulary(["slack", "github", "google-calendar", "google-drive", "notion"]);
3683
+ var CEAL_ACTIVITY_CONNECTOR_KINDS = vocabulary(["slack", "github", "google-calendar", "google-drive", "google-mail", "notion"]);
3657
3684
  var CEAL_ACTIVITY_UNSUPPORTED_EVENT_KIND_CODE = "unsupported_event_kind";
3658
3685
  var CEAL_ACTIVITY_GAP_CODES = vocabulary([
3659
3686
  "provider_page_budget",
@@ -3674,6 +3701,8 @@ var CEAL_ACTIVITY_EVENT_KINDS = vocabulary([
3674
3701
  "github.pull_request.opened",
3675
3702
  "github.issue.edited",
3676
3703
  "github.pull_request.edited",
3704
+ "github.pull_request.merged",
3705
+ "github.release.published",
3677
3706
  "github.review.submitted",
3678
3707
  "github.issue_comment.created",
3679
3708
  "github.review_comment.created",
@@ -3687,6 +3716,7 @@ var CEAL_ACTIVITY_EVENT_KINDS = vocabulary([
3687
3716
  "drive.file.created",
3688
3717
  "drive.file.modified",
3689
3718
  "drive.file.viewed",
3719
+ "mail.sent",
3690
3720
  "notion.page.created",
3691
3721
  "notion.page.edited"
3692
3722
  ]);
@@ -3700,6 +3730,8 @@ var CEAL_ACTIVITY_EVENT_TIMESTAMP_BASIS_MAP = Object.freeze({
3700
3730
  "github.review_comment.created": "comment_created",
3701
3731
  "github.issue.opened": "resource_created",
3702
3732
  "github.pull_request.opened": "resource_created",
3733
+ "github.pull_request.merged": "pull_request_merged",
3734
+ "github.release.published": "release_published",
3703
3735
  "github.issue.edited": "resource_modified",
3704
3736
  "github.pull_request.edited": "resource_modified",
3705
3737
  "github.reaction.created": "reaction_created",
@@ -3710,6 +3742,7 @@ var CEAL_ACTIVITY_EVENT_TIMESTAMP_BASIS_MAP = Object.freeze({
3710
3742
  "drive.file.created": "file_created",
3711
3743
  "drive.file.modified": "file_modified_by_me",
3712
3744
  "drive.file.viewed": "file_viewed_by_me",
3745
+ "mail.sent": "message_created",
3713
3746
  "notion.page.created": "page_created",
3714
3747
  "notion.page.edited": "page_last_edited"
3715
3748
  });
@@ -3820,6 +3853,8 @@ var CEAL_REFRESH_FAILURE_CODES = vocabulary([
3820
3853
  "principal_inactive",
3821
3854
  "authority_replaced",
3822
3855
  "refresh_recovery_unavailable",
3856
+ "refresh_recovery_outcome_unavailable",
3857
+ "refresh_state_unavailable",
3823
3858
  "refresh_recovery_expired",
3824
3859
  // The serving gate answers this while the Gateway is still starting and the
3825
3860
  // refresh was never attempted; the same attempt stays retryable. It is never
@@ -4582,6 +4617,211 @@ var CEAL_SUPPORTED_GATEWAY_PROTOCOL_RANGE = Object.freeze({
4582
4617
  maximum: CEAL_PROTOCOL_VERSION
4583
4618
  });
4584
4619
 
4620
+ // packages/ceal-client-protocol/src/operator-diagnostic.ts
4621
+ var OPERATOR_DIAGNOSTIC_MAX_BYTES = 2048;
4622
+ var OPERATOR_DIAGNOSTIC_MAX_CAUSES = 8;
4623
+ var OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT = 512;
4624
+ var OPERATOR_DIAGNOSTIC_PATH_LIMIT = 1024;
4625
+ var OPERATOR_DIAGNOSTIC_STREAM_TAIL_LIMIT = 256;
4626
+ var OPERATOR_DIAGNOSTIC_HOME_PATHS = machineHomePathPatterns("gu");
4627
+ function redactOperatorDiagnosticSecrets(value) {
4628
+ 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]");
4629
+ }
4630
+ function redactOperatorDiagnosticText(value) {
4631
+ const normalized = normalizeCealSingleLineText(value);
4632
+ return normalizeCealSingleLineText(redactOperatorDiagnosticSecrets(redactFilePaths(redactHomePaths(redactUrls(normalized)))));
4633
+ }
4634
+ function renderOperatorDiagnostic(value) {
4635
+ const state = collectDiagnosticState(value);
4636
+ const fields = [
4637
+ state.status === void 0 ? void 0 : `status=${JSON.stringify(safeDiagnosticText(state.status))}`,
4638
+ state.exitCode === void 0 ? void 0 : `exit_code=${state.exitCode}`,
4639
+ state.stdout === void 0 ? void 0 : `stdout_tail=${JSON.stringify(tail(state.stdout))}`,
4640
+ state.stderr === void 0 ? void 0 : `stderr_tail=${JSON.stringify(tail(state.stderr))}`,
4641
+ state.causes.length === 0 ? void 0 : `causes=${state.causes.map(formatCause).join(" <- ")}`
4642
+ ].filter((field) => field !== void 0);
4643
+ const rendered = fields.length === 0 ? "unknown_failure" : fields.join(" ");
4644
+ return truncateUtf8(rendered, OPERATOR_DIAGNOSTIC_MAX_BYTES);
4645
+ }
4646
+ function collectDiagnosticState(value) {
4647
+ const state = { causes: [], status: void 0, exitCode: void 0, stdout: void 0, stderr: void 0 };
4648
+ const visited = /* @__PURE__ */ new Set(), pending = [value];
4649
+ while (pending.length > 0 && state.causes.length < OPERATOR_DIAGNOSTIC_MAX_CAUSES) {
4650
+ const current = pending.shift();
4651
+ if (current !== void 0) visitDiagnosticNode(current, state, pending, visited);
4652
+ }
4653
+ return state;
4654
+ }
4655
+ function visitDiagnosticNode(current, state, pending, visited) {
4656
+ if (isObject(current)) {
4657
+ if (visited.has(current)) return;
4658
+ visited.add(current);
4659
+ }
4660
+ captureProcessEvidence(current, state);
4661
+ appendCause(current, state.causes);
4662
+ enqueueCauseChildren(current, state.causes.length, pending);
4663
+ }
4664
+ function captureProcessEvidence(current, state) {
4665
+ if (state.status === void 0) state.status = safeStatus(read(current, "status"));
4666
+ if (state.exitCode === void 0) state.exitCode = safeExitCode(read(current, "exitCode")) ?? safeExitCode(read(current, "status")) ?? safeExitCode(read(current, "code"));
4667
+ if (state.stdout === void 0) state.stdout = outputText(read(current, "stdout"));
4668
+ if (state.stderr === void 0) state.stderr = outputText(read(current, "stderr"));
4669
+ }
4670
+ function appendCause(current, causes) {
4671
+ const errors = read(current, "errors");
4672
+ if (current instanceof Error && (!(current instanceof AggregateError) || !Array.isArray(errors) || errors.length === 0)) {
4673
+ causes.push(errorCause(current));
4674
+ return;
4675
+ }
4676
+ if (!isObject(current)) {
4677
+ const message = safeText(current);
4678
+ if (message !== void 0) causes.push(Object.freeze({ error_class: typeof current, message }));
4679
+ }
4680
+ }
4681
+ function errorCause(error) {
4682
+ const name = safeText(read(error, "name")) ?? "Error";
4683
+ const message = safeText(read(error, "message"));
4684
+ const codeValue = read(error, "code");
4685
+ const code2 = typeof codeValue === "number" && Number.isFinite(codeValue) ? codeValue : safeText(codeValue);
4686
+ const errnoValue = read(error, "errno");
4687
+ const errno = typeof errnoValue === "number" && Number.isSafeInteger(errnoValue) ? errnoValue : void 0;
4688
+ const syscall = safeText(read(error, "syscall"));
4689
+ const path = safePath(read(error, "path"));
4690
+ 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 } });
4691
+ }
4692
+ function enqueueCauseChildren(current, causeCount, pending) {
4693
+ const cause = read(current, "cause");
4694
+ if (cause !== void 0) pending.push(cause);
4695
+ const errors = read(current, "errors");
4696
+ if (Array.isArray(errors)) pending.push(...errors.slice(0, OPERATOR_DIAGNOSTIC_MAX_CAUSES - causeCount));
4697
+ }
4698
+ function isObject(value) {
4699
+ return typeof value === "object" && value !== null;
4700
+ }
4701
+ function formatCause(cause) {
4702
+ const fields = [
4703
+ cause.error_class,
4704
+ cause.code === void 0 ? void 0 : `code=${JSON.stringify(safeDiagnosticText(cause.code))}`,
4705
+ cause.errno === void 0 ? void 0 : `errno=${cause.errno}`,
4706
+ cause.syscall === void 0 ? void 0 : `syscall=${JSON.stringify(cause.syscall)}`,
4707
+ cause.path === void 0 ? void 0 : `path=${JSON.stringify(cause.path)}`,
4708
+ cause.message === void 0 ? void 0 : `message=${cause.message}`
4709
+ ].filter((field) => field !== void 0);
4710
+ return fields.join(" ");
4711
+ }
4712
+ function tail(value) {
4713
+ const clipped = value.length <= OPERATOR_DIAGNOSTIC_STREAM_TAIL_LIMIT ? value : `…${value.slice(-OPERATOR_DIAGNOSTIC_STREAM_TAIL_LIMIT)}`;
4714
+ return safeDiagnosticText(clipped);
4715
+ }
4716
+ function safeText(value) {
4717
+ if (typeof value !== "string") return void 0;
4718
+ const safe = safeDiagnosticText(value);
4719
+ if (safe.length === 0) return void 0;
4720
+ if (safe.length <= OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT) return safe;
4721
+ const head = Math.floor(OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT / 2);
4722
+ const tail2 = OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT - head - 1;
4723
+ return `${safe.slice(0, head)}…${safe.slice(-tail2)}`;
4724
+ }
4725
+ function safePath(value) {
4726
+ if (typeof value !== "string") return void 0;
4727
+ const safe = safeDiagnosticText(value);
4728
+ if (safe.length === 0) return void 0;
4729
+ if (safe.length <= OPERATOR_DIAGNOSTIC_PATH_LIMIT) return safe;
4730
+ const head = Math.floor(OPERATOR_DIAGNOSTIC_PATH_LIMIT / 2);
4731
+ const tail2 = OPERATOR_DIAGNOSTIC_PATH_LIMIT - head - 1;
4732
+ return `${safe.slice(0, head)}…${safe.slice(-tail2)}`;
4733
+ }
4734
+ function safeDiagnosticText(value) {
4735
+ return redactOperatorDiagnosticText(String(value));
4736
+ }
4737
+ function outputText(value) {
4738
+ if (typeof value === "string") return redactOperatorDiagnosticText(value);
4739
+ if (value instanceof Uint8Array) {
4740
+ try {
4741
+ return redactOperatorDiagnosticText(new TextDecoder().decode(value));
4742
+ } catch {
4743
+ return void 0;
4744
+ }
4745
+ }
4746
+ return void 0;
4747
+ }
4748
+ function safeStatus(value) {
4749
+ if (typeof value === "number" && Number.isFinite(value)) return value;
4750
+ return typeof value === "string" ? safeText(value) : void 0;
4751
+ }
4752
+ function safeExitCode(value) {
4753
+ return typeof value === "number" && Number.isSafeInteger(value) ? value : void 0;
4754
+ }
4755
+ function read(value, key) {
4756
+ if (typeof value !== "object" && typeof value !== "function" || value === null) return void 0;
4757
+ try {
4758
+ return Reflect.get(value, key);
4759
+ } catch {
4760
+ return void 0;
4761
+ }
4762
+ }
4763
+ function redactHomePaths(value) {
4764
+ const paths = [
4765
+ ...OPERATOR_DIAGNOSTIC_HOME_PATHS.flatMap((pattern) => [...value.matchAll(pattern)].map((match) => homePathRange(value, match, matchedHomePrefixLength(match[0])))),
4766
+ ...configuredHomePathPatterns().flatMap(({ pattern, prefixLength }) => [...value.matchAll(pattern)].map((match) => homePathRange(value, match, prefixLength)))
4767
+ ];
4768
+ paths.sort((left, right) => left.start - right.start || right.end - left.end);
4769
+ let output = "";
4770
+ let cursor = 0;
4771
+ for (const path of paths) {
4772
+ if (path.start < cursor) continue;
4773
+ output += `${value.slice(cursor, path.start)}[home path redacted]${value.slice(path.prefixEnd, path.end)}`;
4774
+ cursor = path.end;
4775
+ }
4776
+ return output + value.slice(cursor);
4777
+ }
4778
+ function configuredHomePathPatterns() {
4779
+ const homes = [...new Set([process.env.HOME, process.env.USERPROFILE].filter((home) => home !== void 0 && home.length > 0))];
4780
+ return homes.flatMap((home) => {
4781
+ const root = home.replace(/[\\/]+$/gu, "");
4782
+ if (root.length === 0 || root === "/" || /^[A-Za-z]:$/u.test(root)) return [];
4783
+ const pattern = new RegExp(`(?<![A-Za-z0-9_])${escapePathPattern(root)}(?=$|[\\\\/\\s"'\`<>(){}\\[\\],;])`, /^[A-Za-z]:[\\/]/u.test(root) ? "giu" : "gu");
4784
+ return [{ pattern, prefixLength: root.length }];
4785
+ });
4786
+ }
4787
+ function matchedHomePrefixLength(value) {
4788
+ let separators = 0;
4789
+ for (let index = 0; index < value.length; index += 1) {
4790
+ if (value[index] !== "/" && value[index] !== "\\") continue;
4791
+ separators += 1;
4792
+ if (separators === 3) return index;
4793
+ }
4794
+ return value.length;
4795
+ }
4796
+ function redactUrls(value) {
4797
+ return value.replaceAll(/https?:\/\/[^\s"'<>]+/giu, "[url redacted]");
4798
+ }
4799
+ function redactFilePaths(value) {
4800
+ return value.replaceAll(/(?<![A-Za-z0-9._-]|\[home path redacted\])(?:[A-Za-z]:[\\/]|\\\\[^\\\s]+\\|\/)[^:\r\n"'<>]*?(?=:\d+(?::\d+)?(?:[:\s]|$)|[\r\n]|["'])/gu, "[path redacted]");
4801
+ }
4802
+ function homePathRange(value, match, prefixLength) {
4803
+ const index = match.index;
4804
+ if (index === void 0) return { start: value.length, end: value.length, prefixEnd: value.length };
4805
+ const start = index;
4806
+ let end = start + match[0].length;
4807
+ const quote = start > 0 && (value[start - 1] === "'" || value[start - 1] === '"') ? value[start - 1] : void 0;
4808
+ if (quote !== void 0) {
4809
+ const closing = value.indexOf(quote, end);
4810
+ if (closing >= 0) end = closing;
4811
+ }
4812
+ while (end < value.length && !/[\s"'`<>(){}[\],;]/u.test(value[end] ?? "")) end += 1;
4813
+ return { start, end, prefixEnd: Math.min(start + prefixLength, end) };
4814
+ }
4815
+ function truncateUtf8(value, maxBytes) {
4816
+ if (byteLength(value) <= maxBytes) return value;
4817
+ let output = "";
4818
+ for (const character of value) {
4819
+ if (byteLength(`${output}${character}…`) > maxBytes) break;
4820
+ output += character;
4821
+ }
4822
+ return `${output}…`;
4823
+ }
4824
+
4585
4825
  // packages/ceal-client-protocol/src/admin-projection-vocabulary.ts
4586
4826
  var ADMIN_PROJECTION_STATES = vocabulary(["ready", "empty", "partial", "unknown"]);
4587
4827
  var ADMIN_VIEW_KINDS = vocabulary(["request_detail", "resource_access_timeline", "weekly_usage"]);
@@ -4673,11 +4913,11 @@ function withRelayEndpointLock(endpoint, run) {
4673
4913
  const gate = new Promise((resolve) => {
4674
4914
  release = resolve;
4675
4915
  });
4676
- const tail = prior.then(() => gate);
4677
- relayEndpointLocks.set(endpoint, tail);
4916
+ const tail2 = prior.then(() => gate);
4917
+ relayEndpointLocks.set(endpoint, tail2);
4678
4918
  return prior.then(run).finally(() => {
4679
4919
  release?.();
4680
- if (relayEndpointLocks.get(endpoint) === tail) relayEndpointLocks.delete(endpoint);
4920
+ if (relayEndpointLocks.get(endpoint) === tail2) relayEndpointLocks.delete(endpoint);
4681
4921
  });
4682
4922
  }
4683
4923
  function currentUid(fallback) {
@@ -5358,7 +5598,7 @@ function parseCanonicalJson(text, error) {
5358
5598
  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) }])}`);
5359
5599
  return value;
5360
5600
  } catch (parseError) {
5361
- throw error("invalid_config", refusalFacts([{ name: "parse_error", value: parseError }, { name: "config_bytes", value: Buffer.byteLength(text, "utf8"), expected: "canonical JSON" }]));
5601
+ throw error("invalid_config", `parse_error=${renderOperatorDiagnostic(parseError)}; ${refusalFact("config_bytes", Buffer.byteLength(text, "utf8"), "canonical JSON")}`);
5362
5602
  }
5363
5603
  }
5364
5604
  function firstDifferenceIndex(left, right) {
@@ -5869,14 +6109,14 @@ var HostUsageFactsStore = class {
5869
6109
  const gate = new Promise((resolve) => {
5870
6110
  release = resolve;
5871
6111
  });
5872
- const tail = previous.then(() => gate);
5873
- SESSION_TRANSITION_TAILS.set(key, tail);
6112
+ const tail2 = previous.then(() => gate);
6113
+ SESSION_TRANSITION_TAILS.set(key, tail2);
5874
6114
  await previous;
5875
6115
  try {
5876
6116
  return await run();
5877
6117
  } finally {
5878
6118
  release?.();
5879
- if (SESSION_TRANSITION_TAILS.get(key) === tail) SESSION_TRANSITION_TAILS.delete(key);
6119
+ if (SESSION_TRANSITION_TAILS.get(key) === tail2) SESSION_TRANSITION_TAILS.delete(key);
5880
6120
  }
5881
6121
  }
5882
6122
  sessionPath(producer, hostSourceRef, hostSessionRef) {
@@ -6460,9 +6700,9 @@ async function readTranscriptCompleteChunk(handle, offset, size) {
6460
6700
  let lastNewline = -1;
6461
6701
  while (position < size) {
6462
6702
  const buffer = Buffer.alloc(Math.min(HOST_TRANSCRIPT_READ_CHUNK_BYTES, size - position));
6463
- const read = await handle.read(buffer, 0, buffer.length, position);
6464
- if (read.bytesRead === 0) break;
6465
- const chunk = buffer.subarray(0, read.bytesRead);
6703
+ const read2 = await handle.read(buffer, 0, buffer.length, position);
6704
+ if (read2.bytesRead === 0) break;
6705
+ const chunk = buffer.subarray(0, read2.bytesRead);
6466
6706
  chunks.push(chunk);
6467
6707
  const newline = chunk.lastIndexOf(10);
6468
6708
  if (newline >= 0) lastNewline = total + newline;
@@ -6635,15 +6875,15 @@ var HostProducerDrainCore = class {
6635
6875
  return run;
6636
6876
  }
6637
6877
  async drainLocked() {
6638
- const read = await this.host.listEnvelopes();
6878
+ const read2 = await this.host.listEnvelopes();
6639
6879
  let removed = 0;
6640
6880
  let expired = 0;
6641
- for (const envelope of read.entries) {
6881
+ for (const envelope of read2.entries) {
6642
6882
  if (Date.parse(this.host.expiresAtOf(envelope)) <= this.now().getTime()) expired += 1;
6643
6883
  else removed += 1;
6644
6884
  await this.host.removeEnvelope(envelope);
6645
6885
  }
6646
- return { removed, expired, malformed: read.malformed };
6886
+ return { removed, expired, malformed: read2.malformed };
6647
6887
  }
6648
6888
  };
6649
6889
 
@@ -6731,29 +6971,46 @@ var HostUsageTranscriptSourceError = class extends Error {
6731
6971
  this.name = "HostUsageTranscriptSourceError";
6732
6972
  }
6733
6973
  };
6734
- async function readHostUsageTranscriptSource(read) {
6974
+ async function readHostUsageTranscriptSource(read2) {
6735
6975
  try {
6736
- return await read();
6976
+ return await read2();
6737
6977
  } catch (error) {
6738
6978
  throw new HostUsageTranscriptSourceError({ cause: error });
6739
6979
  }
6740
6980
  }
6741
- async function captureNextHostUsageRegistration(registrations, startIndex, capture) {
6742
- if (registrations.length === 0) return { captured: false, nextIndex: startIndex, failed: false };
6743
- let failed = false;
6744
- for (let attempt = 0; attempt < registrations.length; attempt += 1) {
6745
- const index = (startIndex + attempt) % registrations.length;
6746
- const registration = registrations[index];
6747
- if (registration === void 0) continue;
6748
- try {
6749
- if (await capture(registration)) return { captured: true, nextIndex: (index + 1) % registrations.length, failed };
6750
- } catch (error) {
6751
- if (!(error instanceof HostUsageTranscriptSourceError)) throw error;
6981
+ var HostUsageRegistrationCapture = class {
6982
+ nextIndex = 0;
6983
+ producer;
6984
+ diagnosticSink;
6985
+ constructor(producer, diagnosticSink) {
6986
+ this.producer = producer;
6987
+ this.diagnosticSink = diagnosticSink;
6988
+ }
6989
+ async captureNext(registrations, capture) {
6990
+ let failed = false;
6991
+ let captured = false;
6992
+ const onFailure = () => {
6752
6993
  failed = true;
6994
+ };
6995
+ for (let attempt = 0; attempt < registrations.length; attempt += 1) {
6996
+ const index = (this.nextIndex + attempt) % registrations.length;
6997
+ const registration = registrations[index];
6998
+ if (registration === void 0) continue;
6999
+ try {
7000
+ captured = await capture(registration, onFailure);
7001
+ if (captured) {
7002
+ this.nextIndex = (index + 1) % registrations.length;
7003
+ break;
7004
+ }
7005
+ } catch (error) {
7006
+ if (!(error instanceof HostUsageTranscriptSourceError)) throw error;
7007
+ onFailure();
7008
+ }
6753
7009
  }
7010
+ if (failed) writeHostServiceDiagnostic(this.producer, "usage_capture_failed", void 0, "capture_failed", this.diagnosticSink);
7011
+ return captured;
6754
7012
  }
6755
- return { captured: false, nextIndex: startIndex, failed };
6756
- }
7013
+ };
6757
7014
  async function openHostUsageTranscriptCursor(input) {
6758
7015
  const handle = await readHostUsageTranscriptSource(() => openNoFollow(input.path, constants6.O_RDONLY));
6759
7016
  let source;
@@ -7055,6 +7312,13 @@ var ClaudeOutboxStore = class {
7055
7312
  await this.removeStateFile(this.registrationPath(registration.host_source_ref, registration.host_session_ref));
7056
7313
  await this.removeStateFile(this.cursorPath(registration.host_source_ref, registration.host_session_ref));
7057
7314
  }
7315
+ async readTranscriptRegistration(hostSourceRef, hostSessionRef) {
7316
+ if (!SAFE_REF4.test(hostSourceRef) || !SAFE_REF4.test(hostSessionRef)) throw new ClaudeHostError("invalid_input", "Claude transcript session identity is invalid.");
7317
+ await this.prepare();
7318
+ const registration = await this.readRegistrationFile(this.registrationPath(hostSourceRef, hostSessionRef));
7319
+ 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.");
7320
+ return registration;
7321
+ }
7058
7322
  async listTranscriptRegistrations() {
7059
7323
  await this.prepare();
7060
7324
  const registrations = [];
@@ -7324,6 +7588,7 @@ var ClaudeProducer = class {
7324
7588
 
7325
7589
  // host/claude/src/claude-transcript-watcher.ts
7326
7590
  import { readdir as readdir2 } from "node:fs/promises";
7591
+ import { isDeepStrictEqual } from "node:util";
7327
7592
  import { join as join5 } from "node:path";
7328
7593
 
7329
7594
  // host/claude/src/claude-decoder.ts
@@ -7409,10 +7674,39 @@ function record4(value) {
7409
7674
  return value !== null && typeof value === "object" && !Array.isArray(value);
7410
7675
  }
7411
7676
 
7677
+ // host/claude/src/claude-subagent-overflow-checkpoint.ts
7678
+ var ClaudeSubagentOverflowCheckpoint = class {
7679
+ observed = /* @__PURE__ */ new Map();
7680
+ prune(registrations) {
7681
+ const current = new Set(registrations.map(registrationKey));
7682
+ for (const key of this.observed.keys()) if (!current.has(key)) this.observed.delete(key);
7683
+ }
7684
+ clear(registration) {
7685
+ this.observed.delete(registrationKey(registration));
7686
+ }
7687
+ /** Names follow the producer's sorted inventory; only omitted names define overflow. */
7688
+ async observe(registration, names, report) {
7689
+ const key = registrationKey(registration);
7690
+ if (names.length <= CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES) {
7691
+ this.clear(registration);
7692
+ return false;
7693
+ }
7694
+ const digest2 = transcriptObjectSha256(names.slice(CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES));
7695
+ if (this.observed.get(key) === digest2) return false;
7696
+ if (!await report()) return false;
7697
+ this.observed.set(key, digest2);
7698
+ return true;
7699
+ }
7700
+ };
7701
+ function registrationKey(registration) {
7702
+ return JSON.stringify([registration.host_source_ref, registration.host_session_ref, registration.transcript_path]);
7703
+ }
7704
+
7412
7705
  // host/claude/src/claude-transcript-watcher.ts
7413
7706
  var TOKEN_OBSERVATION_SOURCE = "claude_transcript.message.usage";
7414
7707
  var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
7415
7708
  store;
7709
+ overflow = new ClaudeSubagentOverflowCheckpoint();
7416
7710
  diagnostic;
7417
7711
  constructor(options) {
7418
7712
  super(options, {
@@ -7427,7 +7721,9 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
7427
7721
  return registration.transcript_path;
7428
7722
  }
7429
7723
  async listRegistrations() {
7430
- return this.store.listTranscriptRegistrations();
7724
+ const registrations = await this.store.listTranscriptRegistrations();
7725
+ this.overflow.prune(registrations);
7726
+ return registrations;
7431
7727
  }
7432
7728
  async scanOpened(handle, registration) {
7433
7729
  const { size, device, inode } = await ownedClaudeTranscriptFile(handle);
@@ -7439,7 +7735,7 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
7439
7735
  }
7440
7736
  if (preflight.checkpointPending) await this.store.writeTranscriptCursor({ ...cursor, updated_at: this.stamp() });
7441
7737
  const draft = mutableCursor(cursor);
7442
- await this.scanOpenedTranscript(registration, handle, draft, size, device, inode);
7738
+ await this.scanOpenedTranscript(registration, handle, cursor, draft, size, device, inode);
7443
7739
  return { records: draft.consumed, enqueued: draft.enqueued, quarantined: false };
7444
7740
  }
7445
7741
  async scanFailed(handle, registration, error) {
@@ -7476,7 +7772,7 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
7476
7772
  updated_at: this.stamp()
7477
7773
  };
7478
7774
  }
7479
- async scanOpenedTranscript(registration, handle, draft, size, device, inode) {
7775
+ async scanOpenedTranscript(registration, handle, previous, draft, size, device, inode) {
7480
7776
  const main = await this.readChunk(handle, draft.offset, size);
7481
7777
  if (main !== "empty" && main !== "partial") {
7482
7778
  await this.consumeMainChunk(registration, main, draft);
@@ -7484,7 +7780,7 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
7484
7780
  }
7485
7781
  draft.consumed += await this.consumeSubagents(registration, draft);
7486
7782
  await this.emitOpenTerminal(registration, draft);
7487
- await this.commitCursor(registration, handle, draft, device, inode);
7783
+ await this.commitCursor(registration, handle, previous, draft, device, inode);
7488
7784
  }
7489
7785
  async preflight(registration, handle, size, device, inode) {
7490
7786
  const existing = await this.store.readTranscriptCursor(registration);
@@ -7644,15 +7940,24 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
7644
7940
  try {
7645
7941
  names = (await readdir2(directory)).filter((name) => name.endsWith(".jsonl") && !name.endsWith(".meta.json")).sort();
7646
7942
  } catch (error) {
7647
- if (isMissingTranscriptError(error) || isNotDirectory(error)) return 0;
7943
+ if (isMissingTranscriptError(error) || isNotDirectory(error)) {
7944
+ this.overflow.clear(registration);
7945
+ return 0;
7946
+ }
7648
7947
  throw new ClaudeHostError("payload_rejected", "Claude subagent transcript directory is unavailable.");
7649
7948
  }
7650
7949
  const listed = new Set(names);
7651
7950
  for (const name of Object.keys(draft.subagents)) if (!listed.has(name)) delete draft.subagents[name];
7652
- if (names.length > CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES) {
7653
- this.log(`Claude ignored subagent transcripts past its file bound: transcript_path=${JSON.stringify(registration.transcript_path)}, files=${names.length}.`);
7654
- names = names.slice(0, CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES);
7655
- }
7951
+ await this.overflow.observe(registration, names, () => {
7952
+ const line = `Claude ignored subagent transcripts past its file bound: transcript_path=${JSON.stringify(registration.transcript_path)}, files=${names.length}.`;
7953
+ try {
7954
+ this.log(line);
7955
+ } catch {
7956
+ return false;
7957
+ }
7958
+ return true;
7959
+ });
7960
+ names = names.slice(0, CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES);
7656
7961
  let consumed = 0;
7657
7962
  for (const name of names) {
7658
7963
  consumed += await this.consumeSubagentFile(draft, directory, name);
@@ -7741,9 +8046,9 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
7741
8046
  expires_at: this.expire(this.outboxRetentionMs)
7742
8047
  });
7743
8048
  }
7744
- async commitCursor(registration, handle, draft, device, inode) {
8049
+ async commitCursor(registration, handle, previous, draft, device, inode) {
7745
8050
  const anchor = await this.readAnchor(handle, draft.offset, CLAUDE_TRANSCRIPT_ANCHOR_BYTES);
7746
- await this.store.writeTranscriptCursor({
8051
+ const cursor = {
7747
8052
  schema_version: CLAUDE_TRANSCRIPT_CURSOR_SCHEMA_VERSION,
7748
8053
  host_source_ref: registration.host_source_ref,
7749
8054
  host_session_ref: registration.host_session_ref,
@@ -7760,7 +8065,9 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
7760
8065
  ...draft.session_observed ? { session_observed: true } : {},
7761
8066
  status: "active",
7762
8067
  updated_at: this.stamp()
7763
- });
8068
+ };
8069
+ if (sameCursorContent(cursor, previous)) return;
8070
+ await this.store.writeTranscriptCursor(cursor);
7764
8071
  }
7765
8072
  async activateContext(identity, promptRef, turnGenerationRef, expiresAt) {
7766
8073
  try {
@@ -7811,6 +8118,9 @@ function mutableCursor(cursor) {
7811
8118
  enqueued: 0
7812
8119
  };
7813
8120
  }
8121
+ function sameCursorContent(left, right) {
8122
+ return isDeepStrictEqual({ ...left, updated_at: void 0 }, { ...right, updated_at: void 0 });
8123
+ }
7814
8124
  function zeroCounts() {
7815
8125
  return { input: 0, cached_input: 0, cache_write_input: 0, output: 0 };
7816
8126
  }
@@ -7941,11 +8251,14 @@ function isSymlinkTranscript(error) {
7941
8251
  }
7942
8252
 
7943
8253
  // host/claude/src/claude-producer-runtime.ts
7944
- async function drainClaudeProducerOnce(options) {
7945
- const scan = await new ClaudeTranscriptWatcher({
7946
- outbox_dir: options.outbox_dir,
8254
+ function createClaudeProducerWatcher(outboxDir) {
8255
+ return new ClaudeTranscriptWatcher({
8256
+ outbox_dir: outboxDir,
7947
8257
  diagnostic: (event, failure_kind, cause) => writeHostServiceDiagnostic("claude", event, failure_kind, cause)
7948
- }).scanOnce().catch((error) => {
8258
+ });
8259
+ }
8260
+ async function drainClaudeProducerOnce(options) {
8261
+ const scan = await (options.watcher ?? createClaudeProducerWatcher(options.outbox_dir)).scanOnce().catch((error) => {
7949
8262
  writeHostServiceDiagnostic("claude", "watcher_scan_failed", claudeTranscriptScanFailureKind(error), claudeTranscriptScanCause(void 0, error));
7950
8263
  throw error;
7951
8264
  });
@@ -7962,25 +8275,20 @@ var ClaudeUsageFactsCapturer = class {
7962
8275
  sources;
7963
8276
  usage;
7964
8277
  now;
7965
- diagnosticSink;
7966
- nextRegistrationIndex = 0;
8278
+ registrations;
7967
8279
  nextSourceSlot = "main";
7968
8280
  nextSubagentIndex = 0;
8281
+ overflow = new ClaudeSubagentOverflowCheckpoint();
7969
8282
  constructor(options) {
7970
8283
  this.sources = new ClaudeOutboxStore(options.outbox_dir);
7971
8284
  this.usage = new HostUsageFactsStore({ outbox_dir: options.outbox_dir, ...options.store_options });
7972
8285
  this.now = options.now ?? (() => /* @__PURE__ */ new Date());
7973
- this.diagnosticSink = options.diagnostic_sink;
8286
+ this.registrations = new HostUsageRegistrationCapture("claude", options.diagnostic_sink);
7974
8287
  }
7975
8288
  async captureNext() {
7976
8289
  const registrations = await this.sources.listTranscriptRegistrations();
7977
- let failed = false;
7978
- const result = await captureNextHostUsageRegistration(registrations, this.nextRegistrationIndex, (registration) => this.captureRegistration(registration, () => {
7979
- failed = true;
7980
- }));
7981
- this.nextRegistrationIndex = result.nextIndex;
7982
- if (failed || result.failed) writeHostServiceDiagnostic("claude", "usage_capture_failed", void 0, "capture_failed", this.diagnosticSink);
7983
- return result.captured;
8290
+ this.overflow.prune(registrations);
8291
+ return await this.registrations.captureNext(registrations, (registration, onFailure) => this.captureRegistration(registration, onFailure));
7984
8292
  }
7985
8293
  async captureRegistration(registration, onFailure) {
7986
8294
  const sources = this.nextSourceSlot === "main" ? ["main", "subagent"] : ["subagent", "main"];
@@ -8027,13 +8335,14 @@ var ClaudeUsageFactsCapturer = class {
8027
8335
  }
8028
8336
  async captureSubagent(registration, onFailure) {
8029
8337
  const names = await readSubagentNames(registration);
8338
+ if (names.length <= CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES) this.overflow.clear(registration);
8030
8339
  let state = await this.usage.readState("claude", registration.host_source_ref, registration.host_session_ref);
8031
8340
  if (state === null) return false;
8032
8341
  state = await this.usage.recoverPending(state);
8033
8342
  if (state.quarantined_reason !== void 0) return false;
8034
8343
  if (await this.retireMissingSubagent(state, names)) return true;
8035
8344
  if (await this.captureListedSubagents(registration, names, state, onFailure)) return true;
8036
- return await this.recordExcessSubagentGap(state, names);
8345
+ return await this.recordExcessSubagentGap(registration, state, names);
8037
8346
  }
8038
8347
  async retireMissingSubagent(state, names) {
8039
8348
  const liveSlots = new Set(names.slice(0, CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES).map(subagentSlot));
@@ -8044,14 +8353,14 @@ var ClaudeUsageFactsCapturer = class {
8044
8353
  }
8045
8354
  return false;
8046
8355
  }
8047
- async recordExcessSubagentGap(state, names) {
8048
- const excessCount = names.length - CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES;
8049
- if (excessCount <= 0) return false;
8356
+ async recordExcessSubagentGap(registration, state, names) {
8050
8357
  const mainCursor = state.cursors.main;
8051
8358
  if (mainCursor === void 0) return false;
8052
- const gap = { reason: "unsupported_source_shape", source_file_ref: null, start_offset: null, end_offset: null, omitted_count: excessCount };
8053
- await this.usage.commitScanTransition(state, "main", mainCursor, mainCursor, null, [gap]);
8054
- return true;
8359
+ return await this.overflow.observe(registration, names, async () => {
8360
+ 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 };
8361
+ await this.usage.commitScanTransition(state, "main", mainCursor, mainCursor, null, [gap]);
8362
+ return true;
8363
+ });
8055
8364
  }
8056
8365
  async captureListedSubagents(registration, names, state, onFailure) {
8057
8366
  const candidates = names.slice(0, CLAUDE_TRANSCRIPT_MAX_SUBAGENT_FILES);
@@ -8332,7 +8641,7 @@ var CLAUDE_PRODUCER_DESCRIPTOR = {
8332
8641
  producer_id: "claude",
8333
8642
  extra_paths: [CLAUDE_TRANSCRIPTS_ROOT],
8334
8643
  config: (shared, extras) => ({ ...shared, claude_transcripts_root: hostProducerExtraPath(extras, CLAUDE_TRANSCRIPTS_ROOT) }),
8335
- runtime_options: (config) => Object.freeze({ outbox_dir: config.outbox_dir }),
8644
+ runtime_options: (config) => Object.freeze({ outbox_dir: config.outbox_dir, watcher: createClaudeProducerWatcher(config.outbox_dir) }),
8336
8645
  drain: drainClaudeProducerOnce,
8337
8646
  background: (config, signal, dependencies) => {
8338
8647
  const capturer = new ClaudeUsageFactsCapturer({ outbox_dir: config.outbox_dir });
@@ -8565,6 +8874,13 @@ var CodexOutboxStore = class {
8565
8874
  await removeOwnerState(this.registrationPath(registration.host_source_ref, registration.host_session_ref), "registration");
8566
8875
  await removeOwnerState(this.cursorPath(registration.host_source_ref, registration.host_session_ref), "cursor");
8567
8876
  }
8877
+ async readTranscriptRegistration(hostSourceRef, hostSessionRef) {
8878
+ const path = this.registrationPath(hostSourceRef, hostSessionRef);
8879
+ await this.prepare();
8880
+ const registration = await readOptionalJson2(path, validateRegistration2);
8881
+ if (registration !== null && (registration.host_source_ref !== hostSourceRef || registration.host_session_ref !== hostSessionRef)) throw storageError("Codex transcript registration identity does not match its session.");
8882
+ return registration;
8883
+ }
8568
8884
  async listTranscriptRegistrations() {
8569
8885
  await this.prepare();
8570
8886
  const registrations = [];
@@ -8591,16 +8907,16 @@ var CodexOutboxStore = class {
8591
8907
  }
8592
8908
  async findByAlias(sourceRef, sessionRef, alias) {
8593
8909
  if (!SAFE_REF5.test(sourceRef) || !SAFE_REF5.test(sessionRef) || !SAFE_REF5.test(alias)) return null;
8594
- const read = await this.list();
8595
- const envelope = findEnvelopeByAlias(read.entries, sourceRef, sessionRef, alias);
8910
+ const read2 = await this.list();
8911
+ const envelope = findEnvelopeByAlias(read2.entries, sourceRef, sessionRef, alias);
8596
8912
  if (envelope !== null) return envelopeMatch(envelope);
8597
8913
  await this.prepare();
8598
8914
  return null;
8599
8915
  }
8600
8916
  async hasPriorTurn(sourceRef, sessionRef) {
8601
8917
  if (!SAFE_REF5.test(sourceRef) || !SAFE_REF5.test(sessionRef)) return false;
8602
- const read = await this.list();
8603
- if (read.entries.some((entry) => entry.identity.host_source_ref === sourceRef && entry.identity.host_session_ref === sessionRef)) return true;
8918
+ const read2 = await this.list();
8919
+ if (read2.entries.some((entry) => entry.identity.host_source_ref === sourceRef && entry.identity.host_session_ref === sessionRef)) return true;
8604
8920
  return false;
8605
8921
  }
8606
8922
  entryPath(submissionRef2) {
@@ -8656,7 +8972,7 @@ async function writeAtomicJson(path, value) {
8656
8972
  if (text === void 0) throw storageError("Codex owner state cannot be serialized.");
8657
8973
  const temp = `${path}.${process.pid}.${Math.random().toString(16).slice(2)}.tmp`;
8658
8974
  try {
8659
- const handle = await open4(temp, "wx");
8975
+ const handle = await open4(temp, "wx", 384);
8660
8976
  try {
8661
8977
  await handle.writeFile(text, "utf8");
8662
8978
  await handle.sync();
@@ -8698,13 +9014,20 @@ async function readOptionalJson2(path, validate) {
8698
9014
  }
8699
9015
  async function ensureOwnerDirectory(path) {
8700
9016
  try {
8701
- await stat2(path);
9017
+ try {
9018
+ const stats2 = await stat2(path);
9019
+ if (!stats2.isDirectory()) throw storageError("Codex owner state path is not a directory.");
9020
+ return;
9021
+ } catch (error) {
9022
+ if (!isNotFound2(error)) throw error;
9023
+ }
9024
+ await mkdir6(path, { recursive: true, mode: 448 });
9025
+ const stats = await stat2(path);
9026
+ if (!stats.isDirectory()) throw storageError("Codex owner state path is not a directory.");
8702
9027
  } catch (error) {
8703
- if (!isNotFound2(error)) throw storageError("Codex owner state directory is unavailable.");
8704
- await mkdir6(path, { recursive: true });
9028
+ if (error instanceof CodexHostAdapterError) throw error;
9029
+ throw storageError("Codex owner state directory is unavailable.");
8705
9030
  }
8706
- const stats = await stat2(path);
8707
- if (!stats.isDirectory()) throw storageError("Codex owner state path is not a directory.");
8708
9031
  }
8709
9032
  async function readOwnerStateFile(path) {
8710
9033
  let handle;
@@ -9518,20 +9841,16 @@ var CodexUsageFactsCapturer = class {
9518
9841
  sources;
9519
9842
  usage;
9520
9843
  now;
9521
- diagnosticSink;
9522
- nextRegistrationIndex = 0;
9844
+ registrations;
9523
9845
  constructor(options) {
9524
9846
  this.sources = new CodexOutboxStore(options.outbox_dir);
9525
9847
  this.usage = new HostUsageFactsStore({ outbox_dir: options.outbox_dir, ...options.store_options });
9526
9848
  this.now = options.now ?? (() => /* @__PURE__ */ new Date());
9527
- this.diagnosticSink = options.diagnostic_sink;
9849
+ this.registrations = new HostUsageRegistrationCapture("codex", options.diagnostic_sink);
9528
9850
  }
9529
9851
  async captureNext() {
9530
9852
  const registrations = await this.sources.listTranscriptRegistrations();
9531
- const result = await captureNextHostUsageRegistration(registrations, this.nextRegistrationIndex, (registration) => this.captureRegistration(registration));
9532
- this.nextRegistrationIndex = result.nextIndex;
9533
- if (result.failed) writeHostServiceDiagnostic("codex", "usage_capture_failed", void 0, "capture_failed", this.diagnosticSink);
9534
- return result.captured;
9853
+ return await this.registrations.captureNext(registrations, (registration) => this.captureRegistration(registration));
9535
9854
  }
9536
9855
  async captureRegistration(registration) {
9537
9856
  const prepared = await openHostUsageTranscriptCursor({
@@ -10317,7 +10636,7 @@ function boundedDiagnosticLines(lines) {
10317
10636
  let totalBytes = 0;
10318
10637
  for (const line of lines.slice(0, HOST_RUNTIME_CONTROL_MAX_DIAGNOSTIC_LINES)) {
10319
10638
  const safe = normalizeDiagnosticLine(line);
10320
- const value = truncateUtf8(safe, HOST_RUNTIME_CONTROL_MAX_DIAGNOSTIC_LINE_BYTES);
10639
+ const value = truncateUtf82(safe, HOST_RUNTIME_CONTROL_MAX_DIAGNOSTIC_LINE_BYTES);
10321
10640
  const bytes = Buffer2.byteLength(value, "utf8") + (bounded.length === 0 ? 0 : 1);
10322
10641
  if (totalBytes + bytes > HOST_RUNTIME_CONTROL_MAX_DIAGNOSTIC_BYTES) break;
10323
10642
  bounded.push(value);
@@ -10327,16 +10646,13 @@ function boundedDiagnosticLines(lines) {
10327
10646
  }
10328
10647
  function normalizeDiagnosticLine(line) {
10329
10648
  let normalized = "";
10330
- for (const character of redactDiagnosticSecrets(line)) {
10649
+ for (const character of redactOperatorDiagnosticSecrets(line)) {
10331
10650
  const point = character.codePointAt(0) ?? 0;
10332
10651
  normalized += point <= 31 || point === 127 ? " " : character;
10333
10652
  }
10334
10653
  return normalized.replace(/\s+/gu, " ").trim();
10335
10654
  }
10336
- function redactDiagnosticSecrets(value) {
10337
- 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*)(?:"[^"]*"|'[^']*'|[^\s,;}]+)/giu, "$1[redacted]");
10338
- }
10339
- function truncateUtf8(value, maxBytes) {
10655
+ function truncateUtf82(value, maxBytes) {
10340
10656
  if (Buffer2.byteLength(value, "utf8") <= maxBytes) return value;
10341
10657
  let output = "";
10342
10658
  let bytes = 0;
@@ -10418,7 +10734,7 @@ function formatWindowsPowerShellCmdScriptCommand(launcherPath2, args, environmen
10418
10734
  const commandProcessor = windowsSystemCommandProcessor(environment);
10419
10735
  validateWindowsCmdScriptVector(commandProcessor, [], "cmd");
10420
10736
  const command = `${quoteWindowsArgument(launcherPath2)} ${args.map(quoteWindowsArgument).join(" ")}`.trimEnd();
10421
- const invocation = ["&", commandProcessor, "/d", "/v:off", "/s", "/c", `"${command}"`].map((value, index) => index === 0 ? value : quotePowerShellLiteral(value)).join(" ");
10737
+ const invocation = ["&", commandProcessor, "/d", "/v:off", "/s", "/c", command].map((value, index) => index === 0 ? value : quotePowerShellLiteral(value)).join(" ");
10422
10738
  return boundedHostCommand(`$LASTEXITCODE = 1; ${invocation}; exit $LASTEXITCODE`);
10423
10739
  }
10424
10740
  function validateWindowsCmdScriptVector(launcherPath2, args, consumer) {
@@ -10493,7 +10809,7 @@ function hostEntryCommand({ entryRoot, module: module2, configFlag, configFile,
10493
10809
  }
10494
10810
  async function installHostEntryLinks(entryRoot, targets, platform = process.platform, custody = {}, renameRetry = {}) {
10495
10811
  assertAbsolute(entryRoot, targets);
10496
- assertWindowsBatchTargetsAscii(targets, platform);
10812
+ assertWindowsEntryPaths(entryRoot, targets, platform);
10497
10813
  await assertEntryRootProven(entryRoot, platform, custody);
10498
10814
  await Promise.all([assertCanonicalDirectory(targets.runtime, "runtime"), assertCanonicalDirectory(targets.services, "services")]);
10499
10815
  if (platform === "win32") await assertLegacyLinkOrAbsent(join10(entryRoot, HOST_ENTRY_RUNTIME_LAUNCHER));
@@ -10501,9 +10817,14 @@ async function installHostEntryLinks(entryRoot, targets, platform = process.plat
10501
10817
  await preparePrivateEntryRoot(entryRoot);
10502
10818
  return reconcileEntryLaunchers(entryRoot, targets, platform, custody, renameRetry);
10503
10819
  }
10504
- function assertWindowsBatchTargetsAscii(targets, platform) {
10820
+ function assertWindowsEntryPaths(entryRoot, targets, platform) {
10505
10821
  if (platform !== "win32") return;
10506
10822
  if (hasNonAsciiCharacter(targets.runtime) || hasNonAsciiCharacter(targets.services)) throw new HostEntryLinkError("entry_target_invalid", "Windows Host launcher targets must use ASCII paths.", ["target_non_ascii"]);
10823
+ try {
10824
+ validateHostCommandVector({ executable: launcherPath(entryRoot, platform), args: [] });
10825
+ } catch {
10826
+ throw new HostEntryLinkError("entry_target_invalid", "Windows Host entry path cannot be serialized safely as a hook command.", ["entry_command_invalid"]);
10827
+ }
10507
10828
  }
10508
10829
  function hasNonAsciiCharacter(value) {
10509
10830
  for (const character of value) if (character.charCodeAt(0) > 127) return true;
@@ -11091,7 +11412,7 @@ async function installClaudeLocalCapability(path, authenticationCommand, custody
11091
11412
  try {
11092
11413
  validateHostCommandVector(authenticationCommand);
11093
11414
  } catch (error) {
11094
- throw new ClaudeHostError("configuration", `Claude invocation authentication command vector is invalid or unsafe: ${refusalFact("error", error)}.`);
11415
+ throw new ClaudeHostError("configuration", `Claude invocation authentication command vector is invalid or unsafe: ${renderOperatorDiagnostic(error)}.`);
11095
11416
  }
11096
11417
  await inspectExecutable(authenticationCommand.executable);
11097
11418
  const next = claudeLocalCapabilityDescriptor(authenticationCommand);
@@ -11127,7 +11448,7 @@ async function removeClaudeLocalCapability(path, authenticationCommand, custody
11127
11448
  validateHostCommandVector(authenticationCommand);
11128
11449
  descriptor2 = claudeLocalCapabilityDescriptor(authenticationCommand);
11129
11450
  } catch (error) {
11130
- throw new ClaudeHostError("configuration", `Claude invocation authentication command vector is invalid or unsafe: ${refusalFact("error", error)}.`);
11451
+ throw new ClaudeHostError("configuration", `Claude invocation authentication command vector is invalid or unsafe: ${renderOperatorDiagnostic(error)}.`);
11131
11452
  }
11132
11453
  const result = await removeOwnedLocalCapability(path, descriptor2, custody);
11133
11454
  if (result === "unsafe" || result === "unavailable") throw new ClaudeHostError("storage", `Claude local capability descriptor ${result === "unsafe" ? "is unsafe" : "custody could not be proved"}.`);
@@ -11267,7 +11588,7 @@ function validateOptions(options) {
11267
11588
  validateHostCommandVector(command);
11268
11589
  managedEntry(command, "SessionStart");
11269
11590
  } catch (error) {
11270
- throw new ClaudeHostError("configuration", `Claude hook command vector is invalid or unsafe: ${refusalFact("error", error)}.`);
11591
+ throw new ClaudeHostError("configuration", `Claude hook command vector is invalid or unsafe: ${renderOperatorDiagnostic(error)}.`);
11271
11592
  }
11272
11593
  return { ...options, settings_path: settingsPath };
11273
11594
  }
@@ -11486,7 +11807,7 @@ function validateInstallerOptions(options) {
11486
11807
  try {
11487
11808
  validateHostCommandVector(resolveHookCommand2(options));
11488
11809
  } catch (error) {
11489
- throw new CodexHostAdapterError("configuration", `Codex hook command vector is invalid or unsafe: ${refusalFact("error", error)}.`);
11810
+ throw new CodexHostAdapterError("configuration", `Codex hook command vector is invalid or unsafe: ${renderOperatorDiagnostic(error)}.`);
11490
11811
  }
11491
11812
  if (options.feature_enabled === false) throw new CodexHostAdapterError("unsupported", `Codex ${CODEX_HOOK_FEATURE} feature is disabled.`);
11492
11813
  return { ...options, config_path: configPath };
@@ -11509,7 +11830,7 @@ async function validateAuthenticationCommand(command) {
11509
11830
  try {
11510
11831
  validateHostCommandVector(command);
11511
11832
  } catch (error) {
11512
- throw configurationError(`Codex invocation authentication command vector is invalid or unsafe: ${refusalFact("error", error)}.`);
11833
+ throw configurationError(`Codex invocation authentication command vector is invalid or unsafe: ${renderOperatorDiagnostic(error)}.`);
11513
11834
  }
11514
11835
  try {
11515
11836
  const stats = await lstat9(command.executable);
@@ -12091,7 +12412,7 @@ async function requireHostRuntimeManagerPreflight(options) {
12091
12412
  async function requireCurrentAccountHome(options) {
12092
12413
  const environment = options.environment ?? process.env;
12093
12414
  const environmentName = options.platform === "win32" ? "USERPROFILE" : "HOME";
12094
- const configuredHome = environment[environmentName];
12415
+ const configuredHome = environmentValue(environment, environmentName, options.platform);
12095
12416
  let accountHome = options.account_home;
12096
12417
  if (accountHome === void 0) {
12097
12418
  try {
@@ -12220,7 +12541,7 @@ function assertCommand(command) {
12220
12541
  try {
12221
12542
  validateHostCommandVector(command, "direct-exec");
12222
12543
  } catch (error) {
12223
- throw new HostRuntimeServiceContractError("invalid_observation", `Host service command observation is invalid (${refusalFact("error", error)}).`);
12544
+ throw new HostRuntimeServiceContractError("invalid_observation", `Host service command observation is invalid (${renderOperatorDiagnostic(error)}).`);
12224
12545
  }
12225
12546
  }
12226
12547
  function absoluteNormalizedPath(value, label, path) {
@@ -12915,7 +13236,7 @@ function validateWindowsService(prefix, service) {
12915
13236
  try {
12916
13237
  validateHostCommandVector(service.command, "direct-exec");
12917
13238
  } catch (error) {
12918
- throw invalidServiceSet(`Windows service command vectors must satisfy the Host command contract: ${refusalFact("error", error)}.`);
13239
+ throw invalidServiceSet(`Windows service command vectors must satisfy the Host command contract: ${renderOperatorDiagnostic(error)}.`);
12919
13240
  }
12920
13241
  if (!win3211.isAbsolute(service.command.executable) || win3211.normalize(service.command.executable) !== service.command.executable) throw invalidServiceSet("Windows service executables must be absolute normalized paths.");
12921
13242
  const expectedNode = win3211.join(prefix, ...HOST_BUNDLE_PRIVATE_RUNTIME_ROOT.split("/"), "node", "bin", "node.exe");
@@ -13058,17 +13379,22 @@ function Find-WantedService([string]$component) {
13058
13379
  return $null
13059
13380
  }
13060
13381
 
13061
- function Stop-CealTaskIfRunning($task) {
13062
- if ([int]$task.State -ne 4) { return }
13382
+ function Test-CealTaskActive($task) {
13383
+ # TASK_STATE_QUEUED (2) still owns an instance that may start; READY (3) does not.
13384
+ return [int]$task.State -in 2,4
13385
+ }
13386
+
13387
+ function Stop-CealTaskIfActive($task) {
13388
+ if (-not (Test-CealTaskActive $task)) { return }
13063
13389
  try { $task.Stop(0) }
13064
- catch { if ([int]$task.State -eq 4) { throw } }
13390
+ catch { if (Test-CealTaskActive $task) { throw } }
13065
13391
  }
13066
13392
 
13067
13393
  function Stop-CealTaskAndWait($task, [string]$operation) {
13068
- Stop-CealTaskIfRunning $task
13394
+ Stop-CealTaskIfActive $task
13069
13395
  $stopDeadline = (Get-Date).AddMilliseconds(${WINDOWS_TASK_STOP_WAIT_MS})
13070
- while ([int]$task.State -eq 4 -and (Get-Date) -lt $stopDeadline) { Start-Sleep -Milliseconds ${WINDOWS_TASK_STATE_POLL_INTERVAL_MS} }
13071
- if ([int]$task.State -eq 4) { throw ('The Ceal Host task did not stop before ' + $operation + '.') }
13396
+ while ((Test-CealTaskActive $task) -and (Get-Date) -lt $stopDeadline) { Start-Sleep -Milliseconds ${WINDOWS_TASK_STATE_POLL_INTERVAL_MS} }
13397
+ if (Test-CealTaskActive $task) { throw ('The Ceal Host task did not stop before ' + $operation + '.') }
13072
13398
  }
13073
13399
 
13074
13400
  function Test-CealSid([string]$value) {
@@ -13132,7 +13458,7 @@ if ([string]$request.operation -ceq 'reconcile') {
13132
13458
  if ($null -ne $task) { Stop-CealTaskAndWait $task 'replacement' }
13133
13459
  $task = Register-CealTask $wanted
13134
13460
  }
13135
- if ($task.State -ne 4) { [void]$task.Run($null) }
13461
+ if (-not (Test-CealTaskActive $task)) { [void]$task.Run($null) }
13136
13462
  }
13137
13463
  @{ schema_version = 'ceal.host_windows_service_result.v1'; ok = $true } | ConvertTo-Json -Compress
13138
13464
  exit 0
@@ -13161,8 +13487,9 @@ if ([string]$request.operation -ceq 'inspect') {
13161
13487
  $wanted = Find-WantedService $component
13162
13488
  $task = Find-CealTask $component
13163
13489
  if ($null -eq $task) { [ordered]@{ component = $component; state = 'absent'; definition_matches = $false }; continue }
13164
- $state = switch ([int]$task.State) { 4 { 'running' } 1 { 'stopped' } 2 { 'stopped' } 3 { 'stopped' } default { 'unknown' } }
13165
- [ordered]@{ component = $component; state = $state; definition_matches = [bool](Test-CealDefinition $task $wanted); last_task_result = [long]$task.LastTaskResult; startup_pending = ([int]$task.State -eq 2) }
13490
+ $taskState = [int]$task.State
13491
+ $state = switch ($taskState) { 4 { 'running' } 1 { 'stopped' } 2 { 'stopped' } 3 { 'stopped' } default { 'unknown' } }
13492
+ [ordered]@{ component = $component; state = $state; definition_matches = [bool](Test-CealDefinition $task $wanted); last_task_result = [long]$task.LastTaskResult; startup_pending = ($taskState -eq 2) }
13166
13493
  }
13167
13494
  [ordered]@{ schema_version = 'ceal.host_windows_service_result.v1'; ok = $true; observations = @($observations) } | ConvertTo-Json -Compress -Depth 5
13168
13495
  exit 0
@@ -13603,7 +13930,7 @@ async function ownedUnitPresent(path, identity, component) {
13603
13930
  } catch (error) {
13604
13931
  if (hasCode(error, "ENOENT")) return false;
13605
13932
  if (isAdapterError(error)) throw error;
13606
- throw projectionError(refusalFact("error", error));
13933
+ throw projectionError(renderOperatorDiagnostic(error));
13607
13934
  }
13608
13935
  }
13609
13936
  async function replaceOwnedUnit(directory, identity, service) {
@@ -13622,7 +13949,7 @@ async function replaceOwnedUnit(directory, identity, service) {
13622
13949
  await syncDirectory3(directory);
13623
13950
  } catch (error) {
13624
13951
  await unlink10(temporary).catch(() => void 0);
13625
- throw projectionError(refusalFact("error", error));
13952
+ throw projectionError(renderOperatorDiagnostic(error));
13626
13953
  }
13627
13954
  }
13628
13955
  async function removeOwnedUnit(directory, identity, component) {
@@ -13769,10 +14096,12 @@ function createInstalledHostRuntimeControlDependencies(options = {}) {
13769
14096
  const environment = options.environment ?? process.env;
13770
14097
  const platform = options.platform ?? process.platform;
13771
14098
  const owner = new InstalledHostRuntimeConfigurationOwner(resolveStateRoot(environment, platform), platform, options.custody ?? {});
14099
+ const codexHome = environmentValue(environment, "CODEX_HOME", platform);
14100
+ const claudeHome = environmentValue(environment, "CLAUDE_CONFIG_DIR", platform);
13772
14101
  const hooks = options.hooks ?? new InstalledHostRuntimeHookAdapter({
13773
- user_home: (platform === "win32" ? environment.USERPROFILE : environment.HOME) ?? homedir5(),
13774
- ...environment.CODEX_HOME === void 0 ? {} : { codex_home: environment.CODEX_HOME },
13775
- ...environment.CLAUDE_CONFIG_DIR === void 0 ? {} : { claude_home: environment.CLAUDE_CONFIG_DIR },
14102
+ user_home: environmentValue(environment, platform === "win32" ? "USERPROFILE" : "HOME", platform) ?? homedir5(),
14103
+ ...codexHome === void 0 ? {} : { codex_home: codexHome },
14104
+ ...claudeHome === void 0 ? {} : { claude_home: claudeHome },
13776
14105
  state_root: owner.stateRoot,
13777
14106
  custody: options.custody,
13778
14107
  config_paths: { codex: owner.configPaths.codex, claude: owner.configPaths.claude }
@@ -14015,7 +14344,7 @@ function processFailure(error) {
14015
14344
  return { exit_code: code2, stdout, stderr, ...timedOut ? { timed_out: true } : {} };
14016
14345
  }
14017
14346
  function resolveStateRoot(environment, platform) {
14018
- const value = environment[STATE_ROOT_ENVIRONMENT];
14347
+ const value = environmentValue(environment, STATE_ROOT_ENVIRONMENT, platform);
14019
14348
  const path = platform === "win32" ? win3212 : posix11;
14020
14349
  if (value === void 0 || value.length === 0 || value.length > HOST_STATE_ROOT_MAX_CHARACTERS || value.includes("\0") || !path.isAbsolute(value) || path.normalize(value) !== value || path.parse(value).root === value) throw new InstalledHostRuntimeCompositionError("state_root_unavailable", `The Go-owned Host state root is unavailable (${refusalFact("state_root", value, `a normalized absolute non-root path of at most ${HOST_STATE_ROOT_MAX_CHARACTERS} characters`)}).`);
14021
14350
  return value;