@ascenda-one/claude-code-hooks 0.1.15 → 0.1.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -207,6 +207,102 @@ var require_workMilestoneClassifier = __commonJS({
207
207
  }
208
208
  });
209
209
 
210
+ // ../packages/tool-kit/out/autonomyBand.js
211
+ var require_autonomyBand = __commonJS({
212
+ "../packages/tool-kit/out/autonomyBand.js"(exports) {
213
+ "use strict";
214
+ Object.defineProperty(exports, "__esModule", { value: true });
215
+ exports.autonomyBand = autonomyBand;
216
+ function autonomyBand(mode) {
217
+ if (typeof mode !== "string")
218
+ return "unknown";
219
+ return BAND_BY_MODE[mode] ?? "unknown";
220
+ }
221
+ var BAND_BY_MODE = {
222
+ plan: "planning",
223
+ default: "supervised",
224
+ accept_edits: "edits_auto",
225
+ // Two tokens, one band — and the reason the tokens stayed two. They differ
226
+ // in how the user arrived at the posture rather than in how much the agent
227
+ // may then do unasked, so today they read the same. If that ever stops being
228
+ // true, this line changes and the whole corpus re-reads correctly, because
229
+ // the wire never collapsed them.
230
+ auto: "delegated",
231
+ dont_ask: "delegated",
232
+ bypass_permissions: "unsupervised"
233
+ };
234
+ }
235
+ });
236
+
237
+ // ../packages/tool-kit/out/modelClassifier.js
238
+ var require_modelClassifier = __commonJS({
239
+ "../packages/tool-kit/out/modelClassifier.js"(exports) {
240
+ "use strict";
241
+ Object.defineProperty(exports, "__esModule", { value: true });
242
+ exports.classifyModelClass = classifyModelClass2;
243
+ function classifyModelClass2(raw) {
244
+ const candidate = raw;
245
+ if (candidate === void 0 || candidate === null)
246
+ return void 0;
247
+ if (typeof candidate !== "string")
248
+ return "unknown";
249
+ const value = candidate.trim().toLowerCase();
250
+ if (!value)
251
+ return void 0;
252
+ if (ROUTER_SENTINEL.test(value))
253
+ return "router:auto";
254
+ const vendor = readModelVendor(value);
255
+ if (vendor === void 0)
256
+ return "unknown";
257
+ for (const [pattern, modelClass] of TIER_PATTERNS_BY_VENDOR[vendor]) {
258
+ if (pattern.test(value))
259
+ return modelClass;
260
+ }
261
+ return UNKNOWN_TIER_BY_VENDOR[vendor];
262
+ }
263
+ function readModelVendor(value) {
264
+ for (const [pattern, vendor] of VENDOR_PATTERNS) {
265
+ if (pattern.test(value))
266
+ return vendor;
267
+ }
268
+ return void 0;
269
+ }
270
+ var ROUTER_SENTINEL = /^(?:[a-z0-9][a-z0-9._-]*\/)?(?:auto|default)$/;
271
+ var VENDOR_PATTERNS = [
272
+ [/\b(anthropic|claude|opus|sonnet|haiku|fable)\b/, "anthropic"],
273
+ [/\b(openai|gpt|o[1-9])\b/, "openai"],
274
+ [/\b(google|gemini|vertex)\b/, "google"],
275
+ // xAI carries no corporate prefix in any observed id — the family name is
276
+ // the whole marker, exactly as `claude` and `gemini` are for theirs.
277
+ [/\b(xai|grok)\b/, "xai"],
278
+ [/\b(ollama|llamacpp|on[-_]?device|local)\b/, "local"]
279
+ ];
280
+ var TIER_PATTERNS_BY_VENDOR = {
281
+ anthropic: [
282
+ [/\bopus\b/, "anthropic:opus"],
283
+ [/\bsonnet\b/, "anthropic:sonnet"],
284
+ [/\bhaiku\b/, "anthropic:haiku"],
285
+ [/\bfable\b/, "anthropic:fable"]
286
+ ],
287
+ openai: [[/\bgpt\b/, "openai:gpt"]],
288
+ google: [[/\bgemini\b/, "google:gemini"]],
289
+ // One tier for now. The line's coding variants (`grok-code-fast-1`) are the
290
+ // same tier word plus a suffix, and splitting them off would be inventing a
291
+ // distinction the ids do not yet draw — `<vendor>:unknown` is waiting for
292
+ // the day one does.
293
+ xai: [[/\bgrok\b/, "xai:grok"]],
294
+ local: [[/\b(ollama|llamacpp|on[-_]?device)\b/, "local:on_device"]]
295
+ };
296
+ var UNKNOWN_TIER_BY_VENDOR = {
297
+ anthropic: "anthropic:unknown",
298
+ openai: "openai:unknown",
299
+ google: "google:unknown",
300
+ xai: "xai:unknown",
301
+ local: "local:unknown"
302
+ };
303
+ }
304
+ });
305
+
210
306
  // ../packages/tool-kit/out/buckets.js
211
307
  var require_buckets = __commonJS({
212
308
  "../packages/tool-kit/out/buckets.js"(exports) {
@@ -301,89 +397,6 @@ var require_afterHours = __commonJS({
301
397
  }
302
398
  });
303
399
 
304
- // ../packages/tool-kit/out/payload.js
305
- var require_payload = __commonJS({
306
- "../packages/tool-kit/out/payload.js"(exports) {
307
- "use strict";
308
- Object.defineProperty(exports, "__esModule", { value: true });
309
- exports.getString = getString3;
310
- exports.getNumber = getNumber2;
311
- exports.getNested = getNested2;
312
- exports.getNestedString = getNestedString3;
313
- exports.getNestedNumber = getNestedNumber2;
314
- exports.inferOutcome = inferOutcome2;
315
- exports.outcomeForHook = outcomeForHook2;
316
- exports.looksLikeCorrection = looksLikeCorrection2;
317
- function getString3(input, keys) {
318
- for (const key of keys) {
319
- const value = input[key];
320
- if (typeof value === "string" && value.trim())
321
- return value;
322
- }
323
- return void 0;
324
- }
325
- function getNumber2(input, keys) {
326
- for (const key of keys) {
327
- const value = input[key];
328
- if (typeof value === "number" && Number.isFinite(value))
329
- return value;
330
- }
331
- return void 0;
332
- }
333
- function getNested2(input, path3) {
334
- let current = input;
335
- for (const segment of path3) {
336
- if (!current || typeof current !== "object")
337
- return void 0;
338
- current = current[segment];
339
- }
340
- return current;
341
- }
342
- function getNestedString3(input, paths) {
343
- for (const path3 of paths) {
344
- const value = getNested2(input, path3);
345
- if (typeof value === "string" && value.trim())
346
- return value;
347
- }
348
- return void 0;
349
- }
350
- function getNestedNumber2(input, paths) {
351
- for (const path3 of paths) {
352
- const value = getNested2(input, path3);
353
- if (typeof value === "number" && Number.isFinite(value))
354
- return value;
355
- }
356
- return void 0;
357
- }
358
- function inferOutcome2(input) {
359
- const exitCode = getNumber2(input, ["exitCode", "exit_code", "status"]) ?? getNestedNumber2(input, [["tool_response", "exitCode"], ["tool_response", "exit_code"], ["result", "exitCode"], ["result", "exit_code"]]);
360
- if (typeof exitCode === "number")
361
- return exitCode === 0 ? "success" : "failure";
362
- const error = getString3(input, ["error", "errorMessage"]) ?? getNestedString3(input, [["tool_response", "error"], ["result", "error"]]);
363
- if (error)
364
- return "failure";
365
- return "unknown";
366
- }
367
- function outcomeForHook2(hookName, input) {
368
- if (hookName === "PostToolUseFailure") {
369
- const interrupted = input["is_interrupt"] === true || getNested2(input, ["tool_response", "interrupted"]) === true;
370
- return interrupted ? "cancelled" : "failure";
371
- }
372
- if (hookName === "PostToolUse") {
373
- if (getNested2(input, ["tool_response", "interrupted"]) === true)
374
- return "cancelled";
375
- return "success";
376
- }
377
- return "unknown";
378
- }
379
- function looksLikeCorrection2(text) {
380
- if (!text)
381
- return false;
382
- return /\b(wrong|incorrect|try again|fix|not what i asked|that's not|that is not|redo|regenerate|you missed|doesn't work|does not work)\b/i.test(text);
383
- }
384
- }
385
- });
386
-
387
400
  // ../packages/tool-contract/out/metricKeys.js
388
401
  var require_metricKeys = __commonJS({
389
402
  "../packages/tool-contract/out/metricKeys.js"(exports) {
@@ -423,6 +436,42 @@ var require_metricKeys = __commonJS({
423
436
  linesChangedBucket: { readBy: ["backend"], backendAliases: ["linesChangedBucket", "lines_changed_bucket"] },
424
437
  // ── Read by the local handoff only ──────────────────────────────────────
425
438
  activeMinutes: { readBy: ["handoff"], unit: "minutes" },
439
+ /**
440
+ * The two halves of `activeMinutes`, and deliberately two keys.
441
+ *
442
+ * They partition it exactly, so a reader can add them — but there is no
443
+ * third key holding the sum, because the sum is `activeMinutes` and it
444
+ * already exists. Presenting one combined "active" figure in place of these
445
+ * is the thing the split was added to stop: an hour of typing and an hour of
446
+ * watching an agent work are not the same hour, and a single number says
447
+ * they are.
448
+ */
449
+ handsOnMinutes: {
450
+ readBy: ["handoff"],
451
+ unit: "minutes",
452
+ note: "Active time immediately preceding a human prompt \u2014 the only interval a transcript can show a person present for, because the prompt at its end is the evidence."
453
+ },
454
+ agentSupervisingMinutes: {
455
+ readBy: ["handoff"],
456
+ unit: "minutes",
457
+ note: "The remaining active time: the agent was working and the person was not typing. NOT a claim that anyone watched it \u2014 nothing in a transcript could show that. Never render as attention."
458
+ },
459
+ // The split's honesty counters. Read by neither the backend nor the handoff
460
+ // on purpose: they exist so a thin or posture-blind session can be told from
461
+ // a complete one, and a reader that ignores them is choosing to, rather than
462
+ // being unable to.
463
+ activeSplitInstants: {
464
+ readBy: ["diagnostic"],
465
+ note: "Distinct timestamps the split ran over, after collapsing ties. The denominator: two minutes off four instants and off four hundred are not the same measurement."
466
+ },
467
+ activeSplitUndatedLines: {
468
+ readBy: ["diagnostic"],
469
+ note: "Known lines carrying a timestamp that would not parse. Absent from the timeline, so both halves are short by an unknown amount and only this says so."
470
+ },
471
+ activeSplitUnposturedInstants: {
472
+ readBy: ["diagnostic"],
473
+ note: "Instants reached before any permissionMode had been declared. Their supervising time lands in the unknown band, which is a blind spot rather than a posture."
474
+ },
426
475
  afterHoursRequests: { readBy: ["handoff"] },
427
476
  approximateLintErrorsCount: { readBy: ["handoff"] },
428
477
  canceledCount: { readBy: ["handoff"] },
@@ -436,6 +485,11 @@ var require_metricKeys = __commonJS({
436
485
  unit: "tokens",
437
486
  note: "The measured quantity, with no assumed denominator. Prefer this to the ratio for any within-person baseline."
438
487
  },
488
+ contextWindowTokens: {
489
+ readBy: ["handoff"],
490
+ unit: "tokens",
491
+ note: "Codex only: the model_context_window the rollout itself recorded \u2014 the real denominator its contextWindowPeakPct was computed against. Claude Code records no window and its ratio assumes 200k; absent here means the store never said."
492
+ },
439
493
  date: { readBy: ["handoff"] },
440
494
  errorCount: { readBy: ["handoff"] },
441
495
  filesChangedCount: { readBy: ["handoff"] },
@@ -519,6 +573,10 @@ var require_metricKeys = __commonJS({
519
573
  unparsedLines: { readBy: ["diagnostic"] },
520
574
  unreadableChatSessionFiles: { readBy: ["diagnostic"] },
521
575
  unreadableHistoryFiles: { readBy: ["diagnostic"] },
576
+ unreadableRolloutFiles: {
577
+ readBy: ["diagnostic"],
578
+ note: "Codex only: rollout files the extractor meant to read and could not open. Summed into the import's read-failure warning, so a store that is partly unreadable says so rather than reporting a short window as the whole."
579
+ },
522
580
  unrecognisedChatSessionFiles: { readBy: ["diagnostic"] }
523
581
  };
524
582
  function backendMetricKeys() {
@@ -532,7 +590,7 @@ var require_out = __commonJS({
532
590
  "../packages/tool-contract/out/index.js"(exports) {
533
591
  "use strict";
534
592
  Object.defineProperty(exports, "__esModule", { value: true });
535
- exports.backendMetricKeys = exports.METRIC_KEYS = exports.ASCENDA_SEMANTIC_PROVENANCE = exports.ASCENDA_HISTORICAL_CONSENT_SCOPE = exports.ASCENDA_COLLABORATION_CONSENT_SCOPE = exports.ASCENDA_SEMANTIC_CONSENT_SCOPE = exports.ASCENDA_PROVENANCE = exports.ASCENDA_CONSENT_SCOPE = exports.EVENT_WORKLOAD_CATEGORY = exports.COLLABORATION_EVENT_TYPES = exports.SEMANTIC_WORK_SIGNAL_EVENT_TYPES = void 0;
593
+ exports.backendMetricKeys = exports.METRIC_KEYS = exports.ASCENDA_SEMANTIC_PROVENANCE = exports.ASCENDA_HISTORICAL_CONSENT_SCOPE = exports.ASCENDA_COLLABORATION_CONSENT_SCOPE = exports.ASCENDA_SEMANTIC_CONSENT_SCOPE = exports.ASCENDA_PROVENANCE = exports.ASCENDA_CONSENT_SCOPE = exports.EVENT_WORKLOAD_CATEGORY = exports.TOOL_EVENT_DELIVERED_STATUSES = exports.IDEMPOTENCY_KEY_MAX_LENGTH = exports.EVENT_METADATA_FIELDS = exports.COLLABORATION_EVENT_TYPES = exports.SEMANTIC_WORK_SIGNAL_EVENT_TYPES = void 0;
536
594
  exports.SEMANTIC_WORK_SIGNAL_EVENT_TYPES = [
537
595
  "approach_churn_detected",
538
596
  "goal_drift_detected",
@@ -546,6 +604,39 @@ var require_out = __commonJS({
546
604
  "review_given",
547
605
  "pull_request_opened"
548
606
  ];
607
+ exports.EVENT_METADATA_FIELDS = [
608
+ "language",
609
+ "fileType",
610
+ "durationBucket",
611
+ "tokenPressureBucket",
612
+ "linesChangedBucket",
613
+ "commandClass",
614
+ "gitAction",
615
+ "milestoneKind",
616
+ "branchHash",
617
+ "autonomyMode",
618
+ "modelClass",
619
+ "modelId",
620
+ "userModified",
621
+ "outcome",
622
+ "trigger",
623
+ "promptClass",
624
+ "reason",
625
+ "afterHours",
626
+ "activity",
627
+ "message",
628
+ "host",
629
+ "toolName",
630
+ "simulated",
631
+ "relatedEventType",
632
+ "skillVersion",
633
+ "taskFingerprint",
634
+ "importKey",
635
+ "extractionId",
636
+ "importSchema"
637
+ ];
638
+ exports.IDEMPOTENCY_KEY_MAX_LENGTH = 128;
639
+ exports.TOOL_EVENT_DELIVERED_STATUSES = ["accepted", "duplicate"];
549
640
  exports.EVENT_WORKLOAD_CATEGORY = {
550
641
  create_focus_session: "creation",
551
642
  ai_prompt_submitted: "creation",
@@ -601,6 +692,98 @@ var require_out = __commonJS({
601
692
  }
602
693
  });
603
694
 
695
+ // ../packages/tool-kit/out/payload.js
696
+ var require_payload = __commonJS({
697
+ "../packages/tool-kit/out/payload.js"(exports) {
698
+ "use strict";
699
+ Object.defineProperty(exports, "__esModule", { value: true });
700
+ exports.mintIdempotencyKey = mintIdempotencyKey;
701
+ exports.getString = getString3;
702
+ exports.getNumber = getNumber2;
703
+ exports.getNested = getNested2;
704
+ exports.getNestedString = getNestedString3;
705
+ exports.getNestedNumber = getNestedNumber2;
706
+ exports.inferOutcome = inferOutcome2;
707
+ exports.outcomeForHook = outcomeForHook2;
708
+ exports.looksLikeCorrection = looksLikeCorrection2;
709
+ var node_crypto_1 = __require("node:crypto");
710
+ var tool_contract_1 = require_out();
711
+ function mintIdempotencyKey() {
712
+ const key = (0, node_crypto_1.randomUUID)();
713
+ if (key.length > tool_contract_1.IDEMPOTENCY_KEY_MAX_LENGTH)
714
+ throw new Error("idempotency key exceeds the wire limit");
715
+ return key;
716
+ }
717
+ function getString3(input, keys) {
718
+ for (const key of keys) {
719
+ const value = input[key];
720
+ if (typeof value === "string" && value.trim())
721
+ return value;
722
+ }
723
+ return void 0;
724
+ }
725
+ function getNumber2(input, keys) {
726
+ for (const key of keys) {
727
+ const value = input[key];
728
+ if (typeof value === "number" && Number.isFinite(value))
729
+ return value;
730
+ }
731
+ return void 0;
732
+ }
733
+ function getNested2(input, path3) {
734
+ let current = input;
735
+ for (const segment of path3) {
736
+ if (!current || typeof current !== "object")
737
+ return void 0;
738
+ current = current[segment];
739
+ }
740
+ return current;
741
+ }
742
+ function getNestedString3(input, paths) {
743
+ for (const path3 of paths) {
744
+ const value = getNested2(input, path3);
745
+ if (typeof value === "string" && value.trim())
746
+ return value;
747
+ }
748
+ return void 0;
749
+ }
750
+ function getNestedNumber2(input, paths) {
751
+ for (const path3 of paths) {
752
+ const value = getNested2(input, path3);
753
+ if (typeof value === "number" && Number.isFinite(value))
754
+ return value;
755
+ }
756
+ return void 0;
757
+ }
758
+ function inferOutcome2(input) {
759
+ const exitCode = getNumber2(input, ["exitCode", "exit_code", "status"]) ?? getNestedNumber2(input, [["tool_response", "exitCode"], ["tool_response", "exit_code"], ["result", "exitCode"], ["result", "exit_code"]]);
760
+ if (typeof exitCode === "number")
761
+ return exitCode === 0 ? "success" : "failure";
762
+ const error = getString3(input, ["error", "errorMessage"]) ?? getNestedString3(input, [["tool_response", "error"], ["result", "error"]]);
763
+ if (error)
764
+ return "failure";
765
+ return "unknown";
766
+ }
767
+ function outcomeForHook2(hookName, input) {
768
+ if (hookName === "PostToolUseFailure") {
769
+ const interrupted = input["is_interrupt"] === true || getNested2(input, ["tool_response", "interrupted"]) === true;
770
+ return interrupted ? "cancelled" : "failure";
771
+ }
772
+ if (hookName === "PostToolUse") {
773
+ if (getNested2(input, ["tool_response", "interrupted"]) === true)
774
+ return "cancelled";
775
+ return "success";
776
+ }
777
+ return "unknown";
778
+ }
779
+ function looksLikeCorrection2(text) {
780
+ if (!text)
781
+ return false;
782
+ return /\b(wrong|incorrect|try again|fix|not what i asked|that's not|that is not|redo|regenerate|you missed|doesn't work|does not work)\b/i.test(text);
783
+ }
784
+ }
785
+ });
786
+
604
787
  // ../packages/tool-kit/out/eventLog.js
605
788
  var require_eventLog = __commonJS({
606
789
  "../packages/tool-kit/out/eventLog.js"(exports) {
@@ -647,7 +830,7 @@ var require_eventLog = __commonJS({
647
830
  exports.expandUserPath = expandUserPath;
648
831
  exports.resolveEventLogPath = resolveEventLogPath2;
649
832
  exports.appendEventLog = appendEventLog2;
650
- var fs4 = __importStar(__require("fs"));
833
+ var fs3 = __importStar(__require("fs"));
651
834
  var os2 = __importStar(__require("os"));
652
835
  var path3 = __importStar(__require("path"));
653
836
  exports.EVENT_LOG_ENV_VAR = "ASCENDA_EVENT_LOG_FILE";
@@ -669,19 +852,19 @@ var require_eventLog = __commonJS({
669
852
  try {
670
853
  rotateIfLarge(logFilePath);
671
854
  const dir = path3.dirname(logFilePath);
672
- fs4.mkdirSync(dir, { recursive: true, mode: 448 });
673
- fs4.appendFileSync(logFilePath, `${JSON.stringify(entry)}
855
+ fs3.mkdirSync(dir, { recursive: true, mode: 448 });
856
+ fs3.appendFileSync(logFilePath, `${JSON.stringify(entry)}
674
857
  `, { encoding: "utf8", mode: 384 });
675
858
  if (process.platform !== "win32")
676
- fs4.chmodSync(logFilePath, 384);
859
+ fs3.chmodSync(logFilePath, 384);
677
860
  } catch {
678
861
  }
679
862
  }
680
863
  function rotateIfLarge(logFilePath) {
681
864
  try {
682
- if (fs4.statSync(logFilePath).size < MAX_BYTES)
865
+ if (fs3.statSync(logFilePath).size < MAX_BYTES)
683
866
  return;
684
- fs4.renameSync(logFilePath, `${logFilePath}.1`);
867
+ fs3.renameSync(logFilePath, `${logFilePath}.1`);
685
868
  } catch {
686
869
  }
687
870
  }
@@ -701,6 +884,7 @@ var require_http = __commonJS({
701
884
  exports.postToolEvent = postToolEvent;
702
885
  exports.postToolEventsBatch = postToolEventsBatch;
703
886
  exports.parseIngestResponse = parseIngestResponse;
887
+ var tool_contract_1 = require_out();
704
888
  var AscendaApiError2 = class extends Error {
705
889
  status;
706
890
  errorCode;
@@ -743,6 +927,35 @@ var require_http = __commonJS({
743
927
  throw new AscendaApiError2(response.status, void 0, await response.text());
744
928
  return await response.json();
745
929
  }
930
+ function isDeliveredStatus(value) {
931
+ return typeof value === "string" && tool_contract_1.TOOL_EVENT_DELIVERED_STATUSES.includes(value);
932
+ }
933
+ function readSuccessBody(body) {
934
+ let parsed;
935
+ try {
936
+ parsed = JSON.parse(body);
937
+ } catch {
938
+ return { duplicates: 0 };
939
+ }
940
+ if (!parsed || typeof parsed !== "object")
941
+ return { duplicates: 0 };
942
+ const single = parsed.status;
943
+ if (isDeliveredStatus(single))
944
+ return { duplicates: single === "duplicate" ? 1 : 0 };
945
+ const raw = parsed.results;
946
+ if (!Array.isArray(raw))
947
+ return { duplicates: 0 };
948
+ const results = [];
949
+ for (const item of raw) {
950
+ if (!item || typeof item !== "object")
951
+ continue;
952
+ const { index, status, reason } = item;
953
+ if (typeof index !== "number" || typeof status !== "string")
954
+ continue;
955
+ results.push({ index, status, ...typeof reason === "string" ? { reason } : {} });
956
+ }
957
+ return { duplicates: results.filter((item) => item.status === "duplicate").length, results };
958
+ }
746
959
  function isRetryableStatus(status) {
747
960
  return status === 408 || status === 429 || status !== void 0 && status >= 500 && status <= 599;
748
961
  }
@@ -769,8 +982,20 @@ var require_http = __commonJS({
769
982
  }
770
983
  }
771
984
  async function parseIngestResponse(response) {
772
- if (response.ok)
773
- return { result: "accepted", httpStatus: response.status };
985
+ if (response.ok) {
986
+ const outcome = { result: "accepted", httpStatus: response.status };
987
+ let read = { duplicates: 0 };
988
+ try {
989
+ read = readSuccessBody(await response.text());
990
+ } catch {
991
+ read = { duplicates: 0 };
992
+ }
993
+ return {
994
+ ...outcome,
995
+ ...read.duplicates > 0 ? { duplicates: read.duplicates } : {},
996
+ ...read.results !== void 0 ? { results: read.results } : {}
997
+ };
998
+ }
774
999
  const body = await response.text();
775
1000
  let errorCode;
776
1001
  try {
@@ -835,9 +1060,10 @@ var require_tokenStore = __commonJS({
835
1060
  exports.ascendaHome = ascendaHome3;
836
1061
  exports.defaultTokenFilePath = defaultTokenFilePath4;
837
1062
  exports.persistEventWriteToken = persistEventWriteToken4;
1063
+ exports.listPersistedToolInstallationIds = listPersistedToolInstallationIds2;
838
1064
  exports.readTokenFile = readTokenFile3;
839
1065
  exports.sanitizeFilePart = sanitizeFilePart;
840
- var fs4 = __importStar(__require("fs"));
1066
+ var fs3 = __importStar(__require("fs"));
841
1067
  var os2 = __importStar(__require("os"));
842
1068
  var path3 = __importStar(__require("path"));
843
1069
  function ascendaHome3() {
@@ -848,18 +1074,44 @@ var require_tokenStore = __commonJS({
848
1074
  }
849
1075
  function persistEventWriteToken4(tokenFilePath, token) {
850
1076
  const dir = path3.dirname(tokenFilePath);
851
- fs4.mkdirSync(dir, { recursive: true, mode: 448 });
852
- fs4.writeFileSync(tokenFilePath, token, { encoding: "utf8", mode: 384 });
1077
+ fs3.mkdirSync(dir, { recursive: true, mode: 448 });
1078
+ fs3.writeFileSync(tokenFilePath, token, { encoding: "utf8", mode: 384 });
853
1079
  if (process.platform !== "win32") {
854
- fs4.chmodSync(dir, 448);
855
- fs4.chmodSync(tokenFilePath, 384);
1080
+ fs3.chmodSync(dir, 448);
1081
+ fs3.chmodSync(tokenFilePath, 384);
1082
+ }
1083
+ }
1084
+ function listPersistedToolInstallationIds2(toolType) {
1085
+ const prefix = `${sanitizeFilePart(toolType)}_`;
1086
+ const dir = path3.join(ascendaHome3(), "tokens");
1087
+ let names;
1088
+ try {
1089
+ names = fs3.readdirSync(dir);
1090
+ } catch {
1091
+ return [];
1092
+ }
1093
+ const ids = [];
1094
+ for (const name of names.sort()) {
1095
+ if (!name.startsWith(prefix) || name.length === prefix.length)
1096
+ continue;
1097
+ const file = path3.join(dir, name);
1098
+ try {
1099
+ if (!fs3.statSync(file).isFile())
1100
+ continue;
1101
+ } catch {
1102
+ continue;
1103
+ }
1104
+ if (readTokenFile3(file) === void 0)
1105
+ continue;
1106
+ ids.push(`${toolType}:${name.slice(prefix.length)}`);
856
1107
  }
1108
+ return ids;
857
1109
  }
858
1110
  function readTokenFile3(tokenFilePath) {
859
1111
  try {
860
- if (!fs4.existsSync(tokenFilePath))
1112
+ if (!fs3.existsSync(tokenFilePath))
861
1113
  return void 0;
862
- const value = fs4.readFileSync(tokenFilePath, "utf8").trim();
1114
+ const value = fs3.readFileSync(tokenFilePath, "utf8").trim();
863
1115
  return value || void 0;
864
1116
  } catch {
865
1117
  return void 0;
@@ -914,11 +1166,14 @@ var require_stateStore = __commonJS({
914
1166
  }();
915
1167
  Object.defineProperty(exports, "__esModule", { value: true });
916
1168
  exports.defaultStateFilePath = defaultStateFilePath2;
1169
+ exports.unresolvedToolInstallationId = unresolvedToolInstallationId2;
1170
+ exports.unresolvedStateFilePath = unresolvedStateFilePath2;
917
1171
  exports.readCollectorState = readCollectorState2;
918
- exports.recordSendOutcome = recordSendOutcome;
1172
+ exports.recordSendOutcome = recordSendOutcome2;
1173
+ exports.recordOutboxDiscard = recordOutboxDiscard;
919
1174
  exports.shouldAnnounceFailure = shouldAnnounceFailure2;
920
1175
  exports.markFailureNotified = markFailureNotified2;
921
- var fs4 = __importStar(__require("fs"));
1176
+ var fs3 = __importStar(__require("fs"));
922
1177
  var os2 = __importStar(__require("os"));
923
1178
  var path3 = __importStar(__require("path"));
924
1179
  var tokenStore_1 = require_tokenStore();
@@ -927,11 +1182,17 @@ var require_stateStore = __commonJS({
927
1182
  const base = dir ? dir : path3.join(os2.homedir(), ".ascenda", "state");
928
1183
  return path3.join(base, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.json`);
929
1184
  }
1185
+ function unresolvedToolInstallationId2(toolType) {
1186
+ return `${toolType}:unresolved`;
1187
+ }
1188
+ function unresolvedStateFilePath2(toolType) {
1189
+ return defaultStateFilePath2(unresolvedToolInstallationId2(toolType));
1190
+ }
930
1191
  function readCollectorState2(stateFilePath) {
931
1192
  try {
932
- if (!fs4.existsSync(stateFilePath))
1193
+ if (!fs3.existsSync(stateFilePath))
933
1194
  return void 0;
934
- const raw = fs4.readFileSync(stateFilePath, "utf8").trim();
1195
+ const raw = fs3.readFileSync(stateFilePath, "utf8").trim();
935
1196
  if (!raw)
936
1197
  return void 0;
937
1198
  const parsed = JSON.parse(raw);
@@ -942,7 +1203,7 @@ var require_stateStore = __commonJS({
942
1203
  return void 0;
943
1204
  }
944
1205
  }
945
- function recordSendOutcome(stateFilePath, toolInstallationId, outcome, detail = {}) {
1206
+ function recordSendOutcome2(stateFilePath, toolInstallationId, outcome, detail = {}) {
946
1207
  const now = (/* @__PURE__ */ new Date()).toISOString();
947
1208
  const previous = readCollectorState2(stateFilePath);
948
1209
  const accepted = outcome === "accepted";
@@ -959,7 +1220,28 @@ var require_stateStore = __commonJS({
959
1220
  // the one already open. Carrying `notifiedFailingSince` across a
960
1221
  // continuing episode is what keeps the notice to once per outage.
961
1222
  ...accepted ? {} : { failingSince: previous?.failingSince ?? now },
962
- ...accepted ? {} : previous?.notifiedFailingSince !== void 0 ? { notifiedFailingSince: previous.notifiedFailingSince } : {}
1223
+ ...accepted ? {} : previous?.notifiedFailingSince !== void 0 ? { notifiedFailingSince: previous.notifiedFailingSince } : {},
1224
+ // Cumulative by design: a send outcome, success included, never erases
1225
+ // the record of what the outbox had to throw away.
1226
+ ...previous?.outboxDiscarded !== void 0 ? { outboxDiscarded: previous.outboxDiscarded } : {}
1227
+ };
1228
+ writeStateFile(stateFilePath, next);
1229
+ return next;
1230
+ }
1231
+ function recordOutboxDiscard(stateFilePath, toolInstallationId, discard) {
1232
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1233
+ const previous = readCollectorState2(stateFilePath);
1234
+ const next = {
1235
+ ...previous ?? { lastAttemptAt: now, consecutiveFailures: 0 },
1236
+ toolInstallationId,
1237
+ lastOutcome: "outbox_discarded",
1238
+ outboxDiscarded: {
1239
+ total: (previous?.outboxDiscarded?.total ?? 0) + discard.count,
1240
+ lastAt: now,
1241
+ lastCount: discard.count,
1242
+ lastReasons: discard.reasons,
1243
+ ...discard.oldestQueuedAt !== void 0 ? { lastOldestQueuedAt: discard.oldestQueuedAt } : {}
1244
+ }
963
1245
  };
964
1246
  writeStateFile(stateFilePath, next);
965
1247
  return next;
@@ -978,16 +1260,16 @@ var require_stateStore = __commonJS({
978
1260
  const temporaryPath = `${stateFilePath}.${process.pid}.tmp`;
979
1261
  try {
980
1262
  const dir = path3.dirname(stateFilePath);
981
- fs4.mkdirSync(dir, { recursive: true, mode: 448 });
982
- fs4.writeFileSync(temporaryPath, `${JSON.stringify(state, null, 2)}
1263
+ fs3.mkdirSync(dir, { recursive: true, mode: 448 });
1264
+ fs3.writeFileSync(temporaryPath, `${JSON.stringify(state, null, 2)}
983
1265
  `, { encoding: "utf8", mode: 384 });
984
- fs4.renameSync(temporaryPath, stateFilePath);
1266
+ fs3.renameSync(temporaryPath, stateFilePath);
985
1267
  if (process.platform !== "win32")
986
- fs4.chmodSync(stateFilePath, 384);
1268
+ fs3.chmodSync(stateFilePath, 384);
987
1269
  } catch {
988
1270
  try {
989
- if (fs4.existsSync(temporaryPath))
990
- fs4.unlinkSync(temporaryPath);
1271
+ if (fs3.existsSync(temporaryPath))
1272
+ fs3.unlinkSync(temporaryPath);
991
1273
  } catch {
992
1274
  }
993
1275
  }
@@ -999,19 +1281,241 @@ var require_stateStore = __commonJS({
999
1281
  }
1000
1282
  });
1001
1283
 
1002
- // ../packages/tool-kit/out/eventSender.js
1003
- var require_eventSender = __commonJS({
1004
- "../packages/tool-kit/out/eventSender.js"(exports) {
1284
+ // ../packages/tool-kit/out/outbox.js
1285
+ var require_outbox = __commonJS({
1286
+ "../packages/tool-kit/out/outbox.js"(exports) {
1005
1287
  "use strict";
1006
- Object.defineProperty(exports, "__esModule", { value: true });
1007
- exports.AscendaEventSender = exports.AscendaSemanticEventError = void 0;
1288
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
1289
+ if (k2 === void 0) k2 = k;
1290
+ var desc = Object.getOwnPropertyDescriptor(m, k);
1291
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
1292
+ desc = { enumerable: true, get: function() {
1293
+ return m[k];
1294
+ } };
1295
+ }
1296
+ Object.defineProperty(o, k2, desc);
1297
+ } : function(o, m, k, k2) {
1298
+ if (k2 === void 0) k2 = k;
1299
+ o[k2] = m[k];
1300
+ });
1301
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
1302
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
1303
+ } : function(o, v) {
1304
+ o["default"] = v;
1305
+ });
1306
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
1307
+ var ownKeys = function(o) {
1308
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
1309
+ var ar = [];
1310
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
1311
+ return ar;
1312
+ };
1313
+ return ownKeys(o);
1314
+ };
1315
+ return function(mod) {
1316
+ if (mod && mod.__esModule) return mod;
1317
+ var result = {};
1318
+ if (mod != null) {
1319
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
1320
+ }
1321
+ __setModuleDefault(result, mod);
1322
+ return result;
1323
+ };
1324
+ }();
1325
+ Object.defineProperty(exports, "__esModule", { value: true });
1326
+ exports.DEFAULT_OUTBOX_DRAIN_BATCH_SIZE = exports.DEFAULT_OUTBOX_MAX_AGE_MS = exports.DEFAULT_OUTBOX_MAX_ENTRIES = exports.OUTBOX_DRAIN_ENV_VAR = void 0;
1327
+ exports.outboxDrainEnabled = outboxDrainEnabled2;
1328
+ exports.defaultOutboxFilePath = defaultOutboxFilePath2;
1329
+ exports.appendToOutbox = appendToOutbox;
1330
+ exports.readOutboxSummary = readOutboxSummary2;
1331
+ exports.claimOutbox = claimOutbox;
1332
+ exports.enforceOutboxBounds = enforceOutboxBounds;
1333
+ var fs3 = __importStar(__require("fs"));
1334
+ var path3 = __importStar(__require("path"));
1335
+ var stateStore_1 = require_stateStore();
1336
+ var tokenStore_1 = require_tokenStore();
1337
+ exports.OUTBOX_DRAIN_ENV_VAR = "ASCENDA_OUTBOX_DRAIN";
1338
+ exports.DEFAULT_OUTBOX_MAX_ENTRIES = 1e4;
1339
+ exports.DEFAULT_OUTBOX_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1e3;
1340
+ exports.DEFAULT_OUTBOX_DRAIN_BATCH_SIZE = 100;
1341
+ var ORPHANED_CLAIM_AGE_MS = 6e4;
1342
+ var CLAIM_SUFFIX = ".draining";
1343
+ function outboxDrainEnabled2(env = process.env) {
1344
+ const value = env[exports.OUTBOX_DRAIN_ENV_VAR]?.trim().toLowerCase();
1345
+ return value === "1" || value === "true" || value === "yes" || value === "on";
1346
+ }
1347
+ function defaultOutboxFilePath2(toolInstallationId) {
1348
+ const dir = path3.dirname((0, stateStore_1.defaultStateFilePath)(toolInstallationId));
1349
+ return path3.join(dir, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.outbox.jsonl`);
1350
+ }
1351
+ function appendToOutbox(outboxFilePath, payload, now = /* @__PURE__ */ new Date()) {
1352
+ try {
1353
+ const dir = path3.dirname(outboxFilePath);
1354
+ fs3.mkdirSync(dir, { recursive: true, mode: 448 });
1355
+ const entry = { queuedAt: now.toISOString(), payload };
1356
+ fs3.appendFileSync(outboxFilePath, `${JSON.stringify(entry)}
1357
+ `, { encoding: "utf8", mode: 384 });
1358
+ if (process.platform !== "win32")
1359
+ fs3.chmodSync(outboxFilePath, 384);
1360
+ return true;
1361
+ } catch {
1362
+ return false;
1363
+ }
1364
+ }
1365
+ function readOutboxSummary2(outboxFilePath) {
1366
+ const files = [outboxFilePath, ...listClaimFiles(outboxFilePath)].filter((file) => fs3.existsSync(file));
1367
+ if (files.length === 0)
1368
+ return void 0;
1369
+ let depth = 0;
1370
+ let unreadableLines = 0;
1371
+ let oldestQueuedAt;
1372
+ for (const file of files) {
1373
+ const { entries, unreadable } = readEntries(file);
1374
+ depth += entries.length;
1375
+ unreadableLines += unreadable;
1376
+ for (const entry of entries) {
1377
+ if (oldestQueuedAt === void 0 || entry.queuedAt < oldestQueuedAt)
1378
+ oldestQueuedAt = entry.queuedAt;
1379
+ }
1380
+ }
1381
+ return { depth, unreadableLines, ...oldestQueuedAt !== void 0 ? { oldestQueuedAt } : {} };
1382
+ }
1383
+ function claimOutbox(outboxFilePath, now = Date.now()) {
1384
+ const claimPath = `${outboxFilePath}.${process.pid}${CLAIM_SUFFIX}`;
1385
+ const claimed = [];
1386
+ try {
1387
+ fs3.renameSync(outboxFilePath, claimPath);
1388
+ claimed.push(claimPath);
1389
+ } catch {
1390
+ }
1391
+ let orphanIndex = 0;
1392
+ for (const orphan of listClaimFiles(outboxFilePath)) {
1393
+ if (claimed.includes(orphan))
1394
+ continue;
1395
+ try {
1396
+ if (now - fs3.statSync(orphan).mtimeMs < ORPHANED_CLAIM_AGE_MS)
1397
+ continue;
1398
+ const mine = `${claimPath}.${orphanIndex++}`;
1399
+ fs3.renameSync(orphan, mine);
1400
+ claimed.push(mine);
1401
+ } catch {
1402
+ }
1403
+ }
1404
+ if (claimed.length === 0)
1405
+ return void 0;
1406
+ const entries = [];
1407
+ let unreadable = 0;
1408
+ for (const file of claimed) {
1409
+ const read = readEntries(file);
1410
+ entries.push(...read.entries);
1411
+ unreadable += read.unreadable;
1412
+ }
1413
+ entries.sort((a, b) => a.queuedAt < b.queuedAt ? -1 : a.queuedAt > b.queuedAt ? 1 : 0);
1414
+ let released = false;
1415
+ return {
1416
+ entries,
1417
+ unreadable,
1418
+ release(remainder) {
1419
+ if (released)
1420
+ return;
1421
+ released = true;
1422
+ if (remainder.length > 0) {
1423
+ try {
1424
+ fs3.mkdirSync(path3.dirname(outboxFilePath), { recursive: true, mode: 448 });
1425
+ fs3.appendFileSync(outboxFilePath, remainder.map((entry) => `${JSON.stringify(entry)}
1426
+ `).join(""), { encoding: "utf8", mode: 384 });
1427
+ if (process.platform !== "win32")
1428
+ fs3.chmodSync(outboxFilePath, 384);
1429
+ } catch {
1430
+ return;
1431
+ }
1432
+ }
1433
+ for (const file of claimed) {
1434
+ try {
1435
+ fs3.unlinkSync(file);
1436
+ } catch {
1437
+ }
1438
+ }
1439
+ }
1440
+ };
1441
+ }
1442
+ function enforceOutboxBounds(entries, bounds, now = Date.now()) {
1443
+ const reasons = {};
1444
+ let oldestQueuedAt;
1445
+ const cutoff = new Date(now - bounds.maxAgeMs).toISOString();
1446
+ const fresh = [];
1447
+ for (const entry of entries) {
1448
+ if (entry.queuedAt < cutoff) {
1449
+ reasons.age = (reasons.age ?? 0) + 1;
1450
+ if (oldestQueuedAt === void 0 || entry.queuedAt < oldestQueuedAt)
1451
+ oldestQueuedAt = entry.queuedAt;
1452
+ } else {
1453
+ fresh.push(entry);
1454
+ }
1455
+ }
1456
+ const excess = Math.max(0, fresh.length - bounds.maxEntries);
1457
+ if (excess > 0) {
1458
+ reasons.count = excess;
1459
+ const first = fresh[0]?.queuedAt;
1460
+ if (first !== void 0 && (oldestQueuedAt === void 0 || first < oldestQueuedAt))
1461
+ oldestQueuedAt = first;
1462
+ }
1463
+ const kept = excess > 0 ? fresh.slice(excess) : fresh;
1464
+ const count = Object.values(reasons).reduce((sum, n) => sum + (n ?? 0), 0);
1465
+ return { kept, discarded: { count, reasons, ...oldestQueuedAt !== void 0 ? { oldestQueuedAt } : {} } };
1466
+ }
1467
+ function listClaimFiles(outboxFilePath) {
1468
+ const dir = path3.dirname(outboxFilePath);
1469
+ const prefix = `${path3.basename(outboxFilePath)}.`;
1470
+ try {
1471
+ return fs3.readdirSync(dir).filter((name) => name.startsWith(prefix) && name.includes(CLAIM_SUFFIX)).map((name) => path3.join(dir, name)).sort();
1472
+ } catch {
1473
+ return [];
1474
+ }
1475
+ }
1476
+ function readEntries(file) {
1477
+ let raw;
1478
+ try {
1479
+ raw = fs3.readFileSync(file, "utf8");
1480
+ } catch {
1481
+ return { entries: [], unreadable: 0 };
1482
+ }
1483
+ const entries = [];
1484
+ let unreadable = 0;
1485
+ for (const line of raw.split("\n")) {
1486
+ if (!line.trim())
1487
+ continue;
1488
+ try {
1489
+ const parsed = JSON.parse(line);
1490
+ if (!parsed || typeof parsed !== "object" || typeof parsed.queuedAt !== "string" || !parsed.payload || typeof parsed.payload !== "object") {
1491
+ unreadable += 1;
1492
+ continue;
1493
+ }
1494
+ entries.push({ queuedAt: parsed.queuedAt, payload: parsed.payload });
1495
+ } catch {
1496
+ unreadable += 1;
1497
+ }
1498
+ }
1499
+ return { entries, unreadable };
1500
+ }
1501
+ }
1502
+ });
1503
+
1504
+ // ../packages/tool-kit/out/eventSender.js
1505
+ var require_eventSender = __commonJS({
1506
+ "../packages/tool-kit/out/eventSender.js"(exports) {
1507
+ "use strict";
1508
+ Object.defineProperty(exports, "__esModule", { value: true });
1509
+ exports.AscendaEventSender = exports.AscendaSemanticEventError = void 0;
1008
1510
  exports.buildEventPayload = buildEventPayload2;
1009
1511
  var afterHours_1 = require_afterHours();
1010
1512
  var tool_contract_1 = require_out();
1011
1513
  var eventLog_1 = require_eventLog();
1012
1514
  var http_1 = require_http();
1515
+ var outbox_1 = require_outbox();
1013
1516
  var tokenStore_1 = require_tokenStore();
1014
1517
  var stateStore_1 = require_stateStore();
1518
+ var payload_1 = require_payload();
1015
1519
  var AscendaSemanticEventError = class extends Error {
1016
1520
  constructor(message) {
1017
1521
  super(message);
@@ -1024,6 +1528,7 @@ var require_eventSender = __commonJS({
1024
1528
  toolInstallationId: identity.toolInstallationId,
1025
1529
  source: identity.source,
1026
1530
  occurredAt: (/* @__PURE__ */ new Date()).toISOString(),
1531
+ idempotencyKey: (0, payload_1.mintIdempotencyKey)(),
1027
1532
  utcOffsetMinutes: (0, afterHours_1.utcOffsetMinutesAt)(/* @__PURE__ */ new Date()),
1028
1533
  sessionId: identity.sessionId ?? void 0,
1029
1534
  workspaceHash: identity.workspaceHash ?? void 0,
@@ -1041,6 +1546,9 @@ var require_eventSender = __commonJS({
1041
1546
  config;
1042
1547
  eventWriteToken;
1043
1548
  lastState;
1549
+ lastDrain;
1550
+ /** One outbox pass per sender, i.e. per hook process. The hook is on the user's critical path. */
1551
+ outboxServiced = false;
1044
1552
  constructor(config) {
1045
1553
  this.config = config;
1046
1554
  this.eventWriteToken = config.eventWriteToken;
@@ -1079,6 +1587,7 @@ var require_eventSender = __commonJS({
1079
1587
  source: this.config.source,
1080
1588
  eventType: mapped.eventType,
1081
1589
  occurredAt: (/* @__PURE__ */ new Date()).toISOString(),
1590
+ idempotencyKey: (0, payload_1.mintIdempotencyKey)(),
1082
1591
  utcOffsetMinutes: (0, afterHours_1.utcOffsetMinutesAt)(/* @__PURE__ */ new Date()),
1083
1592
  severity: "low",
1084
1593
  sessionId: this.config.sessionId ?? void 0,
@@ -1109,6 +1618,7 @@ var require_eventSender = __commonJS({
1109
1618
  source: this.config.source,
1110
1619
  eventType: mapped.eventType,
1111
1620
  occurredAt: (/* @__PURE__ */ new Date()).toISOString(),
1621
+ idempotencyKey: (0, payload_1.mintIdempotencyKey)(),
1112
1622
  utcOffsetMinutes: (0, afterHours_1.utcOffsetMinutesAt)(/* @__PURE__ */ new Date()),
1113
1623
  severity: "low",
1114
1624
  sessionId: this.config.sessionId ?? void 0,
@@ -1127,15 +1637,30 @@ var require_eventSender = __commonJS({
1127
1637
  * deliberate: Claude Code, Codex, the GitHub collector and the MCP server all
1128
1638
  * send through this method, and the defect being fixed showed up in three
1129
1639
  * separate components because each was left to notice its own failures.
1640
+ *
1641
+ * The outbox is serviced first, once per process. If that pass just watched
1642
+ * the ingest door refuse a batch, the live event is not offered to the same
1643
+ * door a second time in the same instant: it inherits the pass's outcome,
1644
+ * and a retryable one puts it straight in the queue. That is what keeps a
1645
+ * hook during an outage to one bounded round trip instead of three.
1130
1646
  */
1131
1647
  async post(payload) {
1132
- const outcome = await this.attempt(payload);
1648
+ const halted = await this.serviceOutbox();
1649
+ let outcome;
1650
+ let queued = false;
1651
+ if (halted) {
1652
+ outcome = halted;
1653
+ queued = this.isRetryable(outcome) && this.enqueue(payload);
1654
+ } else {
1655
+ outcome = await this.attempt(payload);
1656
+ queued = this.isRetryable(outcome) && this.enqueue(payload);
1657
+ }
1133
1658
  this.lastState = (0, stateStore_1.recordSendOutcome)(this.stateFilePath(), this.config.toolInstallationId, outcome.result, {
1134
1659
  httpStatus: outcome.httpStatus,
1135
1660
  errorCode: outcome.errorCode,
1136
- detail: outcome.detail
1661
+ detail: queued ? withNote(outcome.detail, "queued in outbox") : outcome.detail
1137
1662
  });
1138
- this.log(payload, outcome.result);
1663
+ this.log(payload, outcome.result, queued ? "queued" : void 0);
1139
1664
  return outcome.result;
1140
1665
  }
1141
1666
  /**
@@ -1144,6 +1669,15 @@ var require_eventSender = __commonJS({
1144
1669
  * error gets one retry, because the common cases (a restarting instance, a
1145
1670
  * proxy blip, a 429) clear in well under a second and the alternative is
1146
1671
  * losing the event outright.
1672
+ *
1673
+ * Both recoveries resend the same `payload` object, so the `idempotencyKey`
1674
+ * minted at construction is what the server sees on every attempt. That is
1675
+ * what lets a retry of a request the server actually processed (a timeout
1676
+ * after the write, a 502 from a proxy in front of a 200) come back
1677
+ * `duplicate` instead of landing twice. Never rebuild the payload here.
1678
+ *
1679
+ * When the retry fails too, the caller queues the payload: anything longer
1680
+ * than the pause here is the outbox's job, not another in-process wait.
1147
1681
  */
1148
1682
  async attempt(payload) {
1149
1683
  const outcome = await (0, http_1.postToolEvent)(this.config.apiBaseUrl, this.eventWriteToken, payload, this.signal());
@@ -1152,12 +1686,138 @@ var require_eventSender = __commonJS({
1152
1686
  return outcome;
1153
1687
  return (0, http_1.postToolEvent)(this.config.apiBaseUrl, this.eventWriteToken, payload, this.signal());
1154
1688
  }
1155
- if (outcome.result === "transport_error" && (outcome.httpStatus === void 0 || (0, http_1.isRetryableStatus)(outcome.httpStatus))) {
1689
+ if (this.isRetryable(outcome)) {
1156
1690
  await new Promise((resolve2) => setTimeout(resolve2, RETRY_DELAY_MS));
1157
1691
  return (0, http_1.postToolEvent)(this.config.apiBaseUrl, this.eventWriteToken, payload, this.signal());
1158
1692
  }
1159
1693
  return outcome;
1160
1694
  }
1695
+ /** A failure that never reached a verdict. Replaying can change the answer. */
1696
+ isRetryable(outcome) {
1697
+ return outcome.result === "transport_error" && (outcome.httpStatus === void 0 || (0, http_1.isRetryableStatus)(outcome.httpStatus));
1698
+ }
1699
+ /**
1700
+ * Keeps a refused payload for a later drain. Returns whether it is now on
1701
+ * disk; when it is not (read-only home, full disk) the event is lost and the
1702
+ * journal's detail says so instead of implying it was kept.
1703
+ */
1704
+ enqueue(payload) {
1705
+ return (0, outbox_1.appendToOutbox)(this.outboxFilePath(), payload);
1706
+ }
1707
+ /**
1708
+ * One pass over the outbox: claim it, apply the bounds, and — when sending
1709
+ * is enabled — offer one batch, oldest first, to the batch door.
1710
+ *
1711
+ * Entries are deleted on `accepted` or `duplicate`, decided on `status`
1712
+ * alone; `reason` is for a person reading their logs. A per-item `rejected`
1713
+ * is a verdict, and replaying a verdict cannot change it, so those are
1714
+ * discarded and journaled rather than kept forever. A whole-batch
1715
+ * `validation_failed` is the same verdict for every item. Anything else
1716
+ * stops the pass with everything still on disk, and is returned so the live
1717
+ * send can skip a door that just refused.
1718
+ *
1719
+ * Never loops, never backs off, never sends more than one batch: the next
1720
+ * hook invocation is usually seconds away, and a hook sitting in a retry
1721
+ * loop delays the tool call the user is waiting on.
1722
+ */
1723
+ async serviceOutbox() {
1724
+ if (this.outboxServiced)
1725
+ return void 0;
1726
+ this.outboxServiced = true;
1727
+ const sendEnabled = this.config.outboxDrain ?? (0, outbox_1.outboxDrainEnabled)();
1728
+ const claimed = (0, outbox_1.claimOutbox)(this.outboxFilePath());
1729
+ if (!claimed) {
1730
+ this.lastDrain = { found: 0, discarded: 0, delivered: 0, remaining: 0, sendEnabled };
1731
+ return void 0;
1732
+ }
1733
+ const found = claimed.entries.length + claimed.unreadable;
1734
+ const { kept, discarded } = (0, outbox_1.enforceOutboxBounds)(claimed.entries, {
1735
+ maxEntries: this.config.outboxMaxEntries ?? outbox_1.DEFAULT_OUTBOX_MAX_ENTRIES,
1736
+ maxAgeMs: this.config.outboxMaxAgeMs ?? outbox_1.DEFAULT_OUTBOX_MAX_AGE_MS
1737
+ });
1738
+ if (claimed.unreadable > 0) {
1739
+ discarded.count += claimed.unreadable;
1740
+ discarded.reasons.unreadable = claimed.unreadable;
1741
+ }
1742
+ let discardedTotal = this.journalDiscard(discarded);
1743
+ if (!sendEnabled || kept.length === 0) {
1744
+ claimed.release(kept);
1745
+ this.lastDrain = { found, discarded: discardedTotal, delivered: 0, remaining: kept.length, sendEnabled };
1746
+ return void 0;
1747
+ }
1748
+ const batchSize = this.config.outboxDrainBatchSize ?? outbox_1.DEFAULT_OUTBOX_DRAIN_BATCH_SIZE;
1749
+ const batch = kept.slice(0, batchSize);
1750
+ const rest = kept.slice(batchSize);
1751
+ const outcome = await this.attemptBatch(batch.map((entry) => entry.payload));
1752
+ let delivered = [];
1753
+ let rejected = [];
1754
+ let undecided = [];
1755
+ let halted;
1756
+ if (outcome.result === "accepted") {
1757
+ if (outcome.results === void 0) {
1758
+ delivered = batch;
1759
+ } else {
1760
+ const byIndex = new Map(outcome.results.map((item) => [item.index, item.status]));
1761
+ for (const [index, entry] of batch.entries()) {
1762
+ const status = byIndex.get(index);
1763
+ if (status !== void 0 && tool_contract_1.TOOL_EVENT_DELIVERED_STATUSES.includes(status))
1764
+ delivered.push(entry);
1765
+ else if (status === "rejected")
1766
+ rejected.push(entry);
1767
+ else
1768
+ undecided.push(entry);
1769
+ }
1770
+ }
1771
+ } else if (outcome.result === "validation_failed") {
1772
+ rejected = batch;
1773
+ } else {
1774
+ undecided = batch;
1775
+ halted = outcome;
1776
+ }
1777
+ if (rejected.length > 0) {
1778
+ discardedTotal += this.journalDiscard({ count: rejected.length, reasons: { rejected: rejected.length }, oldestQueuedAt: rejected[0]?.queuedAt });
1779
+ }
1780
+ if (!halted) {
1781
+ this.lastState = (0, stateStore_1.recordSendOutcome)(this.stateFilePath(), this.config.toolInstallationId, outcome.result, {
1782
+ httpStatus: outcome.httpStatus,
1783
+ errorCode: outcome.errorCode,
1784
+ detail: withNote(outcome.detail, `outbox drain: ${delivered.length} delivered`)
1785
+ });
1786
+ }
1787
+ for (const entry of delivered)
1788
+ this.log(entry.payload, "accepted", "drained");
1789
+ const remainder = [...undecided, ...rest];
1790
+ claimed.release(remainder);
1791
+ this.lastDrain = {
1792
+ found,
1793
+ discarded: discardedTotal,
1794
+ delivered: delivered.length,
1795
+ remaining: remainder.length,
1796
+ sendEnabled,
1797
+ ...halted ? { halted: halted.result } : {}
1798
+ };
1799
+ return halted;
1800
+ }
1801
+ /** The batch door, with the same single token renewal as the live path and no in-process retry. */
1802
+ async attemptBatch(payloads) {
1803
+ const outcome = await (0, http_1.postToolEventsBatch)(this.config.apiBaseUrl, this.eventWriteToken, payloads, this.signal());
1804
+ if (outcome.result !== "auth_failed")
1805
+ return outcome;
1806
+ if (!await this.renewEventToken())
1807
+ return outcome;
1808
+ return (0, http_1.postToolEventsBatch)(this.config.apiBaseUrl, this.eventWriteToken, payloads, this.signal());
1809
+ }
1810
+ journalDiscard(discard) {
1811
+ if (discard.count === 0)
1812
+ return 0;
1813
+ const reasons = discard.reasons;
1814
+ this.lastState = (0, stateStore_1.recordOutboxDiscard)(this.stateFilePath(), this.config.toolInstallationId, {
1815
+ count: discard.count,
1816
+ reasons,
1817
+ oldestQueuedAt: discard.oldestQueuedAt
1818
+ });
1819
+ return discard.count;
1820
+ }
1161
1821
  /**
1162
1822
  * The state written by the most recent send, so a caller can decide whether
1163
1823
  * to surface a one-time notice without re-reading the journal it just wrote.
@@ -1165,10 +1825,16 @@ var require_eventSender = __commonJS({
1165
1825
  get state() {
1166
1826
  return this.lastState;
1167
1827
  }
1828
+ /** What this sender's one outbox pass did; undefined before the first send. */
1829
+ get drain() {
1830
+ return this.lastDrain;
1831
+ }
1168
1832
  stateFilePath() {
1169
1833
  return this.config.stateFilePath ?? (0, stateStore_1.defaultStateFilePath)(this.config.toolInstallationId);
1170
1834
  }
1171
- /** Never throws: a renewal that errors is a failed renewal, not a failed turn. */
1835
+ outboxFilePath() {
1836
+ return this.config.outboxFilePath ?? (0, outbox_1.defaultOutboxFilePath)(this.config.toolInstallationId);
1837
+ }
1172
1838
  /**
1173
1839
  * Every send path funnels through {@link post}, so semantic and
1174
1840
  * collaboration signals are logged on the same terms as host events — the
@@ -1178,12 +1844,13 @@ var require_eventSender = __commonJS({
1178
1844
  * It is now `transport_error` through the ordinary path, because the
1179
1845
  * transport returns that outcome instead of throwing.
1180
1846
  */
1181
- log(payload, delivery) {
1847
+ log(payload, delivery, outbox) {
1182
1848
  const logFile = this.config.eventLogFile === void 0 ? (0, eventLog_1.resolveEventLogPath)() : this.config.eventLogFile;
1183
1849
  if (!logFile)
1184
1850
  return;
1185
- (0, eventLog_1.appendEventLog)(logFile, { loggedAt: (/* @__PURE__ */ new Date()).toISOString(), delivery, payload });
1851
+ (0, eventLog_1.appendEventLog)(logFile, { loggedAt: (/* @__PURE__ */ new Date()).toISOString(), delivery, payload, ...outbox ? { outbox } : {} });
1186
1852
  }
1853
+ /** Never throws: a renewal that errors is a failed renewal, not a failed turn. */
1187
1854
  async renewEventToken() {
1188
1855
  try {
1189
1856
  const renewed = await (0, http_1.renewToolToken)(this.config.apiBaseUrl, this.eventWriteToken, this.signal());
@@ -1201,6 +1868,9 @@ var require_eventSender = __commonJS({
1201
1868
  }
1202
1869
  };
1203
1870
  exports.AscendaEventSender = AscendaEventSender2;
1871
+ function withNote(detail, note) {
1872
+ return detail ? `${detail} (${note})` : note;
1873
+ }
1204
1874
  }
1205
1875
  });
1206
1876
 
@@ -1250,7 +1920,7 @@ var require_contextRegistry = __commonJS({
1250
1920
  exports.readWorkContextRegistry = readWorkContextRegistry;
1251
1921
  exports.recordWorkContext = recordWorkContext2;
1252
1922
  exports.recordWorkContextAlias = recordWorkContextAlias;
1253
- var fs4 = __importStar(__require("fs"));
1923
+ var fs3 = __importStar(__require("fs"));
1254
1924
  var os2 = __importStar(__require("os"));
1255
1925
  var path3 = __importStar(__require("path"));
1256
1926
  var MAX_PATHS_PER_ENTRY = 8;
@@ -1259,7 +1929,7 @@ var require_contextRegistry = __commonJS({
1259
1929
  }
1260
1930
  function readWorkContextRegistry(registryFilePath = workContextRegistryFilePath()) {
1261
1931
  try {
1262
- const parsed = JSON.parse(fs4.readFileSync(registryFilePath, "utf8"));
1932
+ const parsed = JSON.parse(fs3.readFileSync(registryFilePath, "utf8"));
1263
1933
  if (parsed && parsed.version === 1 && parsed.contexts && typeof parsed.contexts === "object") {
1264
1934
  return parsed;
1265
1935
  }
@@ -1336,13 +2006,276 @@ var require_contextRegistry = __commonJS({
1336
2006
  }
1337
2007
  function writeRegistry(registryFilePath, registry) {
1338
2008
  const dir = path3.dirname(registryFilePath);
1339
- fs4.mkdirSync(dir, { recursive: true, mode: 448 });
2009
+ fs3.mkdirSync(dir, { recursive: true, mode: 448 });
1340
2010
  const tmp = `${registryFilePath}.${process.pid}.tmp`;
1341
- fs4.writeFileSync(tmp, `${JSON.stringify(registry, null, 2)}
2011
+ fs3.writeFileSync(tmp, `${JSON.stringify(registry, null, 2)}
1342
2012
  `, { encoding: "utf8", mode: 384 });
1343
- fs4.renameSync(tmp, registryFilePath);
2013
+ fs3.renameSync(tmp, registryFilePath);
1344
2014
  if (process.platform !== "win32") {
1345
- fs4.chmodSync(registryFilePath, 384);
2015
+ fs3.chmodSync(registryFilePath, 384);
2016
+ }
2017
+ }
2018
+ }
2019
+ });
2020
+
2021
+ // ../packages/tool-kit/out/credentials.js
2022
+ var require_credentials = __commonJS({
2023
+ "../packages/tool-kit/out/credentials.js"(exports) {
2024
+ "use strict";
2025
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
2026
+ if (k2 === void 0) k2 = k;
2027
+ var desc = Object.getOwnPropertyDescriptor(m, k);
2028
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
2029
+ desc = { enumerable: true, get: function() {
2030
+ return m[k];
2031
+ } };
2032
+ }
2033
+ Object.defineProperty(o, k2, desc);
2034
+ } : function(o, m, k, k2) {
2035
+ if (k2 === void 0) k2 = k;
2036
+ o[k2] = m[k];
2037
+ });
2038
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
2039
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
2040
+ } : function(o, v) {
2041
+ o["default"] = v;
2042
+ });
2043
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
2044
+ var ownKeys = function(o) {
2045
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
2046
+ var ar = [];
2047
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
2048
+ return ar;
2049
+ };
2050
+ return ownKeys(o);
2051
+ };
2052
+ return function(mod) {
2053
+ if (mod && mod.__esModule) return mod;
2054
+ var result = {};
2055
+ if (mod != null) {
2056
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
2057
+ }
2058
+ __setModuleDefault(result, mod);
2059
+ return result;
2060
+ };
2061
+ }();
2062
+ Object.defineProperty(exports, "__esModule", { value: true });
2063
+ exports.credentialsFilePath = credentialsFilePath2;
2064
+ exports.readMachineCredentials = readMachineCredentials2;
2065
+ exports.writeMachineCredentials = writeMachineCredentials;
2066
+ exports.writeTopLevelCredentials = writeTopLevelCredentials2;
2067
+ exports.readHostCredentials = readHostCredentials;
2068
+ exports.writeHostCredentials = writeHostCredentials;
2069
+ exports.removeHostCredentials = removeHostCredentials;
2070
+ var fs3 = __importStar(__require("fs"));
2071
+ var path3 = __importStar(__require("path"));
2072
+ var tokenStore_1 = require_tokenStore();
2073
+ function credentialsFilePath2() {
2074
+ return path3.join((0, tokenStore_1.ascendaHome)(), "credentials.json");
2075
+ }
2076
+ function readMachineCredentials2() {
2077
+ try {
2078
+ const raw = fs3.readFileSync(credentialsFilePath2(), "utf8").trim();
2079
+ if (!raw)
2080
+ return void 0;
2081
+ const parsed = JSON.parse(raw);
2082
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
2083
+ return void 0;
2084
+ return parsed;
2085
+ } catch {
2086
+ return void 0;
2087
+ }
2088
+ }
2089
+ function writeMachineCredentials(credentials) {
2090
+ const file = credentialsFilePath2();
2091
+ fs3.mkdirSync(path3.dirname(file), { recursive: true, mode: 448 });
2092
+ fs3.writeFileSync(file, `${JSON.stringify(credentials, null, 2)}
2093
+ `, { encoding: "utf8", mode: 384 });
2094
+ if (process.platform !== "win32") {
2095
+ fs3.chmodSync(path3.dirname(file), 448);
2096
+ fs3.chmodSync(file, 384);
2097
+ }
2098
+ }
2099
+ function writeTopLevelCredentials2(credentials) {
2100
+ const existing = readMachineCredentials2();
2101
+ writeMachineCredentials({ ...credentials, ...existing?.tools ? { tools: existing.tools } : {} });
2102
+ }
2103
+ function readHostCredentials(host) {
2104
+ const entry = readMachineCredentials2()?.tools?.[host];
2105
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
2106
+ return void 0;
2107
+ return entry;
2108
+ }
2109
+ function writeHostCredentials(host, credentials) {
2110
+ const existing = readMachineCredentials2() ?? {};
2111
+ writeMachineCredentials({ ...existing, tools: { ...existing.tools ?? {}, [host]: credentials } });
2112
+ }
2113
+ function removeHostCredentials(host) {
2114
+ const existing = readMachineCredentials2();
2115
+ if (!existing?.tools || !(host in existing.tools))
2116
+ return;
2117
+ const tools = { ...existing.tools };
2118
+ delete tools[host];
2119
+ const next = { ...existing };
2120
+ if (Object.keys(tools).length)
2121
+ next.tools = tools;
2122
+ else
2123
+ delete next.tools;
2124
+ writeMachineCredentials(next);
2125
+ }
2126
+ }
2127
+ });
2128
+
2129
+ // ../packages/tool-kit/out/forgeProject.js
2130
+ var require_forgeProject = __commonJS({
2131
+ "../packages/tool-kit/out/forgeProject.js"(exports) {
2132
+ "use strict";
2133
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
2134
+ if (k2 === void 0) k2 = k;
2135
+ var desc = Object.getOwnPropertyDescriptor(m, k);
2136
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
2137
+ desc = { enumerable: true, get: function() {
2138
+ return m[k];
2139
+ } };
2140
+ }
2141
+ Object.defineProperty(o, k2, desc);
2142
+ } : function(o, m, k, k2) {
2143
+ if (k2 === void 0) k2 = k;
2144
+ o[k2] = m[k];
2145
+ });
2146
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
2147
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
2148
+ } : function(o, v) {
2149
+ o["default"] = v;
2150
+ });
2151
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
2152
+ var ownKeys = function(o) {
2153
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
2154
+ var ar = [];
2155
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
2156
+ return ar;
2157
+ };
2158
+ return ownKeys(o);
2159
+ };
2160
+ return function(mod) {
2161
+ if (mod && mod.__esModule) return mod;
2162
+ var result = {};
2163
+ if (mod != null) {
2164
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
2165
+ }
2166
+ __setModuleDefault(result, mod);
2167
+ return result;
2168
+ };
2169
+ }();
2170
+ Object.defineProperty(exports, "__esModule", { value: true });
2171
+ exports.forgeProjectHash = forgeProjectHash;
2172
+ exports.parseForgeFullName = parseForgeFullName;
2173
+ exports.readForgeFullName = readForgeFullName;
2174
+ exports.forgeFullNameFromConfig = forgeFullNameFromConfig;
2175
+ exports.recordForgeProjectAlias = recordForgeProjectAlias2;
2176
+ var fs3 = __importStar(__require("fs"));
2177
+ var path3 = __importStar(__require("path"));
2178
+ var contextRegistry_1 = require_contextRegistry();
2179
+ function forgeProjectHash(value) {
2180
+ let h = 2166136261;
2181
+ for (let i = 0; i < value.length; i++) {
2182
+ h ^= value.charCodeAt(i);
2183
+ h = Math.imul(h, 16777619) >>> 0;
2184
+ }
2185
+ return h.toString(16).padStart(8, "0");
2186
+ }
2187
+ function parseForgeFullName(remoteUrl) {
2188
+ if (!remoteUrl)
2189
+ return null;
2190
+ const trimmed = remoteUrl.trim();
2191
+ if (!trimmed)
2192
+ return null;
2193
+ const scp = /^(?:[^@/]+@)?([^/:]+):(.+)$/.exec(trimmed);
2194
+ const scheme = /^([a-z][a-z0-9+.-]*):\/\/(?:[^@/]*@)?([^/:]+)(?::\d+)?\/(.+)$/i.exec(trimmed);
2195
+ let host;
2196
+ let repoPath;
2197
+ if (scheme) {
2198
+ host = scheme[2];
2199
+ repoPath = scheme[3];
2200
+ } else if (scp && !/^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed)) {
2201
+ host = scp[1];
2202
+ repoPath = scp[2];
2203
+ } else {
2204
+ return null;
2205
+ }
2206
+ const normalizedHost = host.toLowerCase().replace(/^www\./, "");
2207
+ if (normalizedHost !== "github.com")
2208
+ return null;
2209
+ const segments = repoPath.split("/").filter((segment) => segment.length > 0);
2210
+ if (segments.length < 2)
2211
+ return null;
2212
+ const owner = segments[0];
2213
+ const repo = segments[1].replace(/\.git$/, "");
2214
+ if (!owner || !repo)
2215
+ return null;
2216
+ return `${owner}/${repo}`;
2217
+ }
2218
+ function readForgeFullName(repositoryRoot) {
2219
+ if (!repositoryRoot)
2220
+ return null;
2221
+ let config;
2222
+ try {
2223
+ config = fs3.readFileSync(path3.join(repositoryRoot, ".git", "config"), "utf8");
2224
+ } catch {
2225
+ return null;
2226
+ }
2227
+ return forgeFullNameFromConfig(config);
2228
+ }
2229
+ function forgeFullNameFromConfig(config) {
2230
+ const remotes = /* @__PURE__ */ new Map();
2231
+ let currentRemote = null;
2232
+ for (const rawLine of config.split(/\r?\n/)) {
2233
+ const line = rawLine.trim();
2234
+ if (!line || line.startsWith("#") || line.startsWith(";"))
2235
+ continue;
2236
+ const section = /^\[([^\]]*)\]$/.exec(line);
2237
+ if (section) {
2238
+ const remote = /^remote\s+"(.*)"$/.exec(section[1].trim());
2239
+ currentRemote = remote ? remote[1] : null;
2240
+ continue;
2241
+ }
2242
+ if (!currentRemote)
2243
+ continue;
2244
+ const entry = /^url\s*=\s*(.*)$/.exec(line);
2245
+ if (entry && !remotes.has(currentRemote))
2246
+ remotes.set(currentRemote, entry[1].trim());
2247
+ }
2248
+ const ordered = [
2249
+ ...remotes.has("origin") ? ["origin"] : [],
2250
+ ...remotes.has("upstream") ? ["upstream"] : [],
2251
+ ...[...remotes.keys()].filter((name) => name !== "origin" && name !== "upstream")
2252
+ ];
2253
+ for (const name of ordered) {
2254
+ const fullName = parseForgeFullName(remotes.get(name));
2255
+ if (fullName)
2256
+ return fullName;
2257
+ }
2258
+ return null;
2259
+ }
2260
+ function recordForgeProjectAlias2(context, options) {
2261
+ try {
2262
+ if (!context?.projectHash || !context.projectLabel || !context.projectPath)
2263
+ return false;
2264
+ const fullName = readForgeFullName(context.projectPath);
2265
+ if (!fullName)
2266
+ return false;
2267
+ const variants = [fullName, fullName.toLowerCase()].filter((value, index, all) => all.indexOf(value) === index);
2268
+ let wrote = false;
2269
+ for (const variant of variants) {
2270
+ const hash = forgeProjectHash(variant);
2271
+ if (hash === context.projectHash || hash === context.workspaceHash)
2272
+ continue;
2273
+ if ((0, contextRegistry_1.recordWorkContextAlias)(hash, context.projectLabel, context.projectPath, options))
2274
+ wrote = true;
2275
+ }
2276
+ return wrote;
2277
+ } catch {
2278
+ return false;
1346
2279
  }
1347
2280
  }
1348
2281
  }
@@ -1394,7 +2327,7 @@ var require_salt = __commonJS({
1394
2327
  exports.readOrCreateMachineSalt = readOrCreateMachineSalt;
1395
2328
  exports.hashWithMachineSalt = hashWithMachineSalt;
1396
2329
  var crypto2 = __importStar(__require("crypto"));
1397
- var fs4 = __importStar(__require("fs"));
2330
+ var fs3 = __importStar(__require("fs"));
1398
2331
  var os2 = __importStar(__require("os"));
1399
2332
  var path3 = __importStar(__require("path"));
1400
2333
  function machineSaltFilePath() {
@@ -1406,19 +2339,19 @@ var require_salt = __commonJS({
1406
2339
  if (hit)
1407
2340
  return hit;
1408
2341
  const dir = path3.dirname(saltFilePath);
1409
- fs4.mkdirSync(dir, { recursive: true, mode: 448 });
2342
+ fs3.mkdirSync(dir, { recursive: true, mode: 448 });
1410
2343
  let salt;
1411
2344
  try {
1412
2345
  salt = crypto2.randomBytes(32).toString("hex");
1413
- fs4.writeFileSync(saltFilePath, salt, { encoding: "utf8", mode: 384, flag: "wx" });
2346
+ fs3.writeFileSync(saltFilePath, salt, { encoding: "utf8", mode: 384, flag: "wx" });
1414
2347
  } catch (error) {
1415
2348
  if (error.code !== "EEXIST")
1416
2349
  throw error;
1417
- salt = fs4.readFileSync(saltFilePath, "utf8").trim();
2350
+ salt = fs3.readFileSync(saltFilePath, "utf8").trim();
1418
2351
  }
1419
2352
  if (process.platform !== "win32") {
1420
- fs4.chmodSync(dir, 448);
1421
- fs4.chmodSync(saltFilePath, 384);
2353
+ fs3.chmodSync(dir, 448);
2354
+ fs3.chmodSync(saltFilePath, 384);
1422
2355
  }
1423
2356
  cache.set(saltFilePath, salt);
1424
2357
  return salt;
@@ -1474,7 +2407,11 @@ var require_workContext = __commonJS({
1474
2407
  }();
1475
2408
  Object.defineProperty(exports, "__esModule", { value: true });
1476
2409
  exports.deriveWorkContext = deriveWorkContext2;
1477
- var fs4 = __importStar(__require("fs"));
2410
+ exports.normalizeBranchName = normalizeBranchName;
2411
+ exports.deriveBranchHash = deriveBranchHash;
2412
+ exports.readBranchName = readBranchName;
2413
+ exports.deriveBranchHashForCwd = deriveBranchHashForCwd2;
2414
+ var fs3 = __importStar(__require("fs"));
1478
2415
  var path3 = __importStar(__require("path"));
1479
2416
  var salt_1 = require_salt();
1480
2417
  var MAX_WALK_DEPTH = 64;
@@ -1488,6 +2425,8 @@ var require_workContext = __commonJS({
1488
2425
  } catch {
1489
2426
  roots = null;
1490
2427
  }
2428
+ if (!roots)
2429
+ roots = inferRootsFromPath(startPath);
1491
2430
  const workspacePath = roots?.checkoutRoot ?? startPath;
1492
2431
  const workspaceLabel = basenameOf(workspacePath);
1493
2432
  if (!workspaceLabel)
@@ -1504,21 +2443,24 @@ var require_workContext = __commonJS({
1504
2443
  };
1505
2444
  }
1506
2445
  function resolveRepositoryRoots(startDir) {
1507
- if (!fs4.existsSync(startDir))
2446
+ if (!fs3.existsSync(startDir))
1508
2447
  return null;
1509
2448
  let dir = startDir;
1510
2449
  for (let depth = 0; depth < MAX_WALK_DEPTH; depth++) {
1511
2450
  const dotGit = path3.join(dir, ".git");
1512
2451
  let stat = null;
1513
2452
  try {
1514
- stat = fs4.statSync(dotGit);
2453
+ stat = fs3.statSync(dotGit);
1515
2454
  } catch {
1516
2455
  stat = null;
1517
2456
  }
1518
2457
  if (stat?.isDirectory())
1519
- return { checkoutRoot: dir, canonicalRoot: dir };
1520
- if (stat?.isFile())
1521
- return { checkoutRoot: dir, canonicalRoot: worktreeParentRoot(dotGit, dir) ?? dir };
2458
+ return { checkoutRoot: dir, canonicalRoot: dir, gitDir: dotGit };
2459
+ if (stat?.isFile()) {
2460
+ const gitDir = readGitdirPointer(dotGit, dir);
2461
+ const canonicalRoot = (gitDir ? worktreeParentRoot(gitDir) : null) ?? dir;
2462
+ return { checkoutRoot: dir, canonicalRoot, gitDir };
2463
+ }
1522
2464
  const parent = path3.dirname(dir);
1523
2465
  if (parent === dir)
1524
2466
  return null;
@@ -1526,22 +2468,45 @@ var require_workContext = __commonJS({
1526
2468
  }
1527
2469
  return null;
1528
2470
  }
1529
- function worktreeParentRoot(dotGitFile, containingDir) {
1530
- let gitdir;
2471
+ function readGitdirPointer(dotGitFile, containingDir) {
1531
2472
  try {
1532
- const match = /^gitdir:\s*(.+)\s*$/m.exec(fs4.readFileSync(dotGitFile, "utf8"));
2473
+ const match = /^gitdir:\s*(.+)\s*$/m.exec(fs3.readFileSync(dotGitFile, "utf8"));
1533
2474
  if (!match)
1534
2475
  return null;
1535
- gitdir = match[1].trim();
2476
+ return path3.resolve(containingDir, match[1].trim());
1536
2477
  } catch {
1537
2478
  return null;
1538
2479
  }
1539
- const resolved = path3.resolve(containingDir, gitdir);
2480
+ }
2481
+ function worktreeParentRoot(resolvedGitDir) {
1540
2482
  const marker = `${path3.sep}.git${path3.sep}worktrees${path3.sep}`;
1541
- const idx = resolved.indexOf(marker);
2483
+ const idx = resolvedGitDir.indexOf(marker);
1542
2484
  if (idx === -1)
1543
2485
  return null;
1544
- return resolved.slice(0, idx);
2486
+ return resolvedGitDir.slice(0, idx);
2487
+ }
2488
+ function inferRootsFromPath(startPath) {
2489
+ const sep = startPath.includes("\\") && !startPath.includes("/") ? "\\" : "/";
2490
+ const leading = /^[\\/]/.test(startPath) ? sep : "";
2491
+ const segments = startPath.split(/[\\/]/).filter(Boolean);
2492
+ const join3 = (count) => leading + segments.slice(0, count).join(sep);
2493
+ for (let i = 0; i + 2 < segments.length; i++) {
2494
+ if (segments[i] === ".claude" && segments[i + 1] === "worktrees") {
2495
+ if (i === 0)
2496
+ return null;
2497
+ return { checkoutRoot: join3(i + 3), canonicalRoot: join3(i), gitDir: null };
2498
+ }
2499
+ }
2500
+ for (let i = 0; i + 1 < segments.length; i++) {
2501
+ const folder = segments[i];
2502
+ const suffix = ["-worktrees", "-wt"].find((s) => folder.endsWith(s) && folder.length > s.length);
2503
+ if (!suffix)
2504
+ continue;
2505
+ const repoName = folder.slice(0, -suffix.length);
2506
+ const canonicalRoot = leading + [...segments.slice(0, i), repoName].join(sep);
2507
+ return { checkoutRoot: join3(i + 2), canonicalRoot, gitDir: null };
2508
+ }
2509
+ return null;
1545
2510
  }
1546
2511
  function stripTrailingSeparators(value) {
1547
2512
  let end = value.length;
@@ -1549,9 +2514,58 @@ var require_workContext = __commonJS({
1549
2514
  end--;
1550
2515
  return value.slice(0, end);
1551
2516
  }
1552
- function basenameOf(value) {
1553
- const segment = value.split(/[\\/]/).filter(Boolean).pop() ?? null;
1554
- return segment && segment.length > 0 ? segment : null;
2517
+ function basenameOf(value) {
2518
+ const segment = value.split(/[\\/]/).filter(Boolean).pop() ?? null;
2519
+ return segment && segment.length > 0 ? segment : null;
2520
+ }
2521
+ var REFS_HEADS_PREFIX = "refs/heads/";
2522
+ function normalizeBranchName(branch) {
2523
+ if (!branch)
2524
+ return null;
2525
+ let name = branch.trim();
2526
+ if (name.startsWith(REFS_HEADS_PREFIX))
2527
+ name = name.slice(REFS_HEADS_PREFIX.length).trim();
2528
+ if (!name || name === "HEAD")
2529
+ return null;
2530
+ return name;
2531
+ }
2532
+ function deriveBranchHash(branch, saltFilePath) {
2533
+ const name = normalizeBranchName(branch);
2534
+ if (!name)
2535
+ return null;
2536
+ try {
2537
+ return (0, salt_1.hashWithMachineSalt)(name, saltFilePath);
2538
+ } catch {
2539
+ return null;
2540
+ }
2541
+ }
2542
+ function readBranchName(cwd) {
2543
+ if (!cwd || !cwd.trim())
2544
+ return null;
2545
+ let gitDir = null;
2546
+ try {
2547
+ gitDir = resolveRepositoryRoots(stripTrailingSeparators(cwd.trim()))?.gitDir ?? null;
2548
+ } catch {
2549
+ gitDir = null;
2550
+ }
2551
+ if (!gitDir)
2552
+ return null;
2553
+ let head;
2554
+ try {
2555
+ head = fs3.readFileSync(path3.join(gitDir, "HEAD"), "utf8").trim();
2556
+ } catch {
2557
+ return null;
2558
+ }
2559
+ const match = /^ref:\s*(.+)$/.exec(head);
2560
+ if (!match)
2561
+ return null;
2562
+ const ref = match[1].trim();
2563
+ if (!ref.startsWith(REFS_HEADS_PREFIX))
2564
+ return null;
2565
+ return normalizeBranchName(ref);
2566
+ }
2567
+ function deriveBranchHashForCwd2(cwd, saltFilePath) {
2568
+ return deriveBranchHash(readBranchName(cwd), saltFilePath);
1555
2569
  }
1556
2570
  }
1557
2571
  });
@@ -1561,35 +2575,69 @@ var require_hookAdapter = __commonJS({
1561
2575
  "../packages/tool-kit/out/hookAdapter.js"(exports) {
1562
2576
  "use strict";
1563
2577
  Object.defineProperty(exports, "__esModule", { value: true });
1564
- exports.DEFAULT_API_BASE_URL = void 0;
2578
+ exports.MissingInstallationIdError = exports.DEFAULT_API_BASE_URL = void 0;
2579
+ exports.resolveCliAgentInstallationId = resolveCliAgentInstallationId;
1565
2580
  exports.resolveContextHashes = resolveContextHashes;
1566
2581
  exports.loadCliAgentConfig = loadCliAgentConfig;
1567
2582
  exports.deliverHookEvents = deliverHookEvents;
1568
2583
  var contextRegistry_1 = require_contextRegistry();
2584
+ var credentials_1 = require_credentials();
2585
+ var forgeProject_1 = require_forgeProject();
1569
2586
  var eventLog_1 = require_eventLog();
1570
2587
  var eventSender_1 = require_eventSender();
2588
+ var stateStore_1 = require_stateStore();
1571
2589
  var tokenStore_1 = require_tokenStore();
1572
2590
  var workContext_1 = require_workContext();
1573
2591
  exports.DEFAULT_API_BASE_URL = "https://api.ascenda.one";
2592
+ var MissingInstallationIdError2 = class extends Error {
2593
+ /** The token files that were considered — none, or too many to pick from. */
2594
+ candidates;
2595
+ toolType;
2596
+ constructor(toolType, candidates, setupCommand) {
2597
+ super(candidates.length === 0 ? `Not configured: no ASCENDA_TOOL_INSTALLATION_ID, no pairing in ~/.ascenda/credentials.json, and no ${toolType} token in ~/.ascenda/tokens/. Run: ${setupCommand}` : `Not configured: no ASCENDA_TOOL_INSTALLATION_ID, no pairing in ~/.ascenda/credentials.json, and ${candidates.length} ${toolType} tokens in ~/.ascenda/tokens/ (${candidates.join(", ")}) \u2014 refusing to guess. Export ASCENDA_TOOL_INSTALLATION_ID to choose one, or run: ${setupCommand}`);
2598
+ this.name = "MissingInstallationIdError";
2599
+ this.toolType = toolType;
2600
+ this.candidates = candidates;
2601
+ }
2602
+ };
2603
+ exports.MissingInstallationIdError = MissingInstallationIdError2;
2604
+ function resolveCliAgentInstallationId(toolType, identity = {}) {
2605
+ const fromEnv = process.env.ASCENDA_TOOL_INSTALLATION_ID?.trim();
2606
+ if (fromEnv)
2607
+ return { toolInstallationId: qualify(toolType, fromEnv), source: "env" };
2608
+ const fromCredentials = identity.host ? (0, credentials_1.readHostCredentials)(identity.host)?.toolInstallationId?.trim() : void 0;
2609
+ if (fromCredentials)
2610
+ return { toolInstallationId: qualify(toolType, fromCredentials), source: "credentials" };
2611
+ const candidates = (0, tokenStore_1.listPersistedToolInstallationIds)(toolType);
2612
+ if (candidates.length === 1)
2613
+ return { toolInstallationId: candidates[0], source: "disk" };
2614
+ throw new MissingInstallationIdError2(toolType, candidates, identity.setupCommand ?? defaultSetupCommand(identity.host));
2615
+ }
2616
+ function defaultSetupCommand(host) {
2617
+ return host ? `npx @ascenda-one/${host.replace(/_cli$/, "")}-hooks setup` : "the agent's setup command";
2618
+ }
2619
+ function qualify(toolType, value) {
2620
+ return value.includes(":") ? value : `${toolType}:${value}`;
2621
+ }
1574
2622
  function resolveContextHashes(cwd) {
1575
2623
  const workspaceOverride = process.env.ASCENDA_WORKSPACE_HASH?.trim() || null;
1576
2624
  const projectOverride = process.env.ASCENDA_PROJECT_HASH?.trim() || null;
1577
2625
  if (workspaceOverride && projectOverride)
1578
2626
  return { workspaceHash: workspaceOverride, projectHash: projectOverride };
1579
2627
  const context = (0, workContext_1.deriveWorkContext)(cwd ?? process.cwd());
1580
- if (context)
2628
+ if (context) {
1581
2629
  (0, contextRegistry_1.recordWorkContext)(context);
2630
+ (0, forgeProject_1.recordForgeProjectAlias)(context);
2631
+ }
1582
2632
  return {
1583
2633
  workspaceHash: workspaceOverride ?? context?.workspaceHash ?? null,
1584
2634
  projectHash: projectOverride ?? context?.projectHash ?? null
1585
2635
  };
1586
2636
  }
1587
- function loadCliAgentConfig(toolType, sessionIdFromHook, cwd) {
1588
- const apiBaseUrl = (process.env.ASCENDA_API_BASE_URL ?? exports.DEFAULT_API_BASE_URL).replace(/\/$/, "");
1589
- const toolInstallationIdRaw = process.env.ASCENDA_TOOL_INSTALLATION_ID;
1590
- if (!toolInstallationIdRaw)
1591
- throw new Error("Missing ASCENDA_TOOL_INSTALLATION_ID");
1592
- const toolInstallationId = toolInstallationIdRaw.trim().includes(":") ? toolInstallationIdRaw.trim() : `${toolType}:${toolInstallationIdRaw.trim()}`;
2637
+ function loadCliAgentConfig(toolType, sessionIdFromHook, cwd, identity = {}) {
2638
+ const credentials = identity.host ? (0, credentials_1.readHostCredentials)(identity.host) : void 0;
2639
+ const apiBaseUrl = (process.env.ASCENDA_API_BASE_URL ?? credentials?.apiBaseUrl ?? exports.DEFAULT_API_BASE_URL).replace(/\/$/, "");
2640
+ const { toolInstallationId } = resolveCliAgentInstallationId(toolType, identity);
1593
2641
  const tokenFilePath = process.env.ASCENDA_EVENT_WRITE_TOKEN_FILE ?? (0, tokenStore_1.defaultTokenFilePath)(toolInstallationId);
1594
2642
  const fileToken = (0, tokenStore_1.readTokenFile)(tokenFilePath);
1595
2643
  const eventWriteToken = fileToken ?? process.env.ASCENDA_EVENT_WRITE_TOKEN;
@@ -1603,7 +2651,10 @@ var require_hookAdapter = __commonJS({
1603
2651
  toolInstallationId,
1604
2652
  eventWriteToken,
1605
2653
  tokenFilePath,
1606
- sessionId: process.env.ASCENDA_SESSION_ID ?? sessionIdFromHook ?? null,
2654
+ // An empty ASCENDA_SESSION_ID is "unset", not "override with nothing":
2655
+ // read raw, `ASCENDA_SESSION_ID=""` beat a real hook session and shipped
2656
+ // an empty string, grouping unrelated rows under a value naming no session.
2657
+ sessionId: process.env.ASCENDA_SESSION_ID?.trim() || sessionIdFromHook || null,
1607
2658
  workspaceHash: contextHashes.workspaceHash,
1608
2659
  projectHash: contextHashes.projectHash,
1609
2660
  // Agents await command hooks; fail fast rather than stall the user's turn.
@@ -1616,8 +2667,10 @@ var require_hookAdapter = __commonJS({
1616
2667
  const notice = options.onNotice ?? ((message) => console.error(message));
1617
2668
  let config;
1618
2669
  try {
1619
- config = loadCliAgentConfig(options.toolType, options.sessionId, options.cwd);
2670
+ config = loadCliAgentConfig(options.toolType, options.sessionId, options.cwd, options);
1620
2671
  } catch (error) {
2672
+ if (error instanceof MissingInstallationIdError2)
2673
+ journalSkippedSend2(options.host, error);
1621
2674
  const logFile = (0, eventLog_1.resolveEventLogPath)();
1622
2675
  if (!logFile)
1623
2676
  throw error;
@@ -1657,13 +2710,19 @@ var require_hookAdapter = __commonJS({
1657
2710
  } else if (result === "auth_failed") {
1658
2711
  notice("Ascenda telemetry paused: connection revoked or expired. Re-pair via an Ascenda IDE extension or pairing-sim.");
1659
2712
  } else if (result === "transport_error") {
1660
- notice("Ascenda telemetry paused: the ingest endpoint could not be reached. Your work is unaffected.");
2713
+ notice("Ascenda telemetry paused: the ingest endpoint could not be reached; the event is kept in the outbox. Your work is unaffected.");
1661
2714
  } else {
1662
2715
  notice(`Ascenda telemetry rejected: ${result}`);
1663
2716
  }
1664
2717
  return;
1665
2718
  }
1666
2719
  }
2720
+ function journalSkippedSend2(host, error) {
2721
+ const who = host ? `${host}: ` : "";
2722
+ (0, stateStore_1.recordSendOutcome)((0, stateStore_1.unresolvedStateFilePath)(error.toolType), (0, stateStore_1.unresolvedToolInstallationId)(error.toolType), "skipped_no_installation_id", {
2723
+ detail: error.candidates.length === 0 ? `${who}no ASCENDA_TOOL_INSTALLATION_ID, no credentials.json pairing, no ${error.toolType} token file` : `${who}no ASCENDA_TOOL_INSTALLATION_ID, no credentials.json pairing, ${error.candidates.length} ${error.toolType} token files (${error.candidates.join(", ")})`
2724
+ });
2725
+ }
1667
2726
  function parsePositiveInt(value) {
1668
2727
  const n = Number(value);
1669
2728
  return Number.isInteger(n) && n > 0 ? n : void 0;
@@ -1671,6 +2730,387 @@ var require_hookAdapter = __commonJS({
1671
2730
  }
1672
2731
  });
1673
2732
 
2733
+ // ../packages/tool-kit/out/cliAgentSetup.js
2734
+ var require_cliAgentSetup = __commonJS({
2735
+ "../packages/tool-kit/out/cliAgentSetup.js"(exports) {
2736
+ "use strict";
2737
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
2738
+ if (k2 === void 0) k2 = k;
2739
+ var desc = Object.getOwnPropertyDescriptor(m, k);
2740
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
2741
+ desc = { enumerable: true, get: function() {
2742
+ return m[k];
2743
+ } };
2744
+ }
2745
+ Object.defineProperty(o, k2, desc);
2746
+ } : function(o, m, k, k2) {
2747
+ if (k2 === void 0) k2 = k;
2748
+ o[k2] = m[k];
2749
+ });
2750
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
2751
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
2752
+ } : function(o, v) {
2753
+ o["default"] = v;
2754
+ });
2755
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
2756
+ var ownKeys = function(o) {
2757
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
2758
+ var ar = [];
2759
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
2760
+ return ar;
2761
+ };
2762
+ return ownKeys(o);
2763
+ };
2764
+ return function(mod) {
2765
+ if (mod && mod.__esModule) return mod;
2766
+ var result = {};
2767
+ if (mod != null) {
2768
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
2769
+ }
2770
+ __setModuleDefault(result, mod);
2771
+ return result;
2772
+ };
2773
+ }();
2774
+ Object.defineProperty(exports, "__esModule", { value: true });
2775
+ exports.isCliAgentManagementCommand = isCliAgentManagementCommand;
2776
+ exports.cliAgentHookBinPath = cliAgentHookBinPath;
2777
+ exports.runCliAgentSetup = runCliAgentSetup;
2778
+ exports.writeHookSettings = writeHookSettings;
2779
+ exports.findStaleHookCommands = findStaleHookCommands2;
2780
+ var crypto2 = __importStar(__require("crypto"));
2781
+ var fs3 = __importStar(__require("fs"));
2782
+ var os2 = __importStar(__require("os"));
2783
+ var path3 = __importStar(__require("path"));
2784
+ var credentials_1 = require_credentials();
2785
+ var hookAdapter_1 = require_hookAdapter();
2786
+ var http_1 = require_http();
2787
+ var tokenStore_1 = require_tokenStore();
2788
+ var MANAGEMENT_COMMANDS2 = /* @__PURE__ */ new Set(["setup", "install", "status", "uninstall", "-h", "--help"]);
2789
+ function isCliAgentManagementCommand(argument) {
2790
+ return argument !== void 0 && MANAGEMENT_COMMANDS2.has(argument);
2791
+ }
2792
+ function cliAgentHookBinPath(binaryName) {
2793
+ return path3.join((0, tokenStore_1.ascendaHome)(), "bin", binaryName);
2794
+ }
2795
+ function usage(spec) {
2796
+ return `${spec.binaryName} setup \u2014 wire ${spec.displayName} to Ascenda telemetry
2797
+
2798
+ npx ${spec.packageName} setup [options]
2799
+ npx ${spec.packageName} status
2800
+ npx ${spec.packageName} uninstall
2801
+
2802
+ Options
2803
+ --api-base-url <url> ingest host (default ${hookAdapter_1.DEFAULT_API_BASE_URL})
2804
+ --local [port] shorthand for the local dev server (default port 4477)
2805
+ --tool-installation-id <id> reuse an existing pairing instead of creating one
2806
+ --token <eventWriteToken> reuse an existing token (stored 0600, never printed)
2807
+ --scope project|user where hooks are registered (default project)
2808
+ --project-dir <path> project root for --scope project (default cwd)
2809
+ --dry-run print what would change, write nothing
2810
+ -h, --help
2811
+ `;
2812
+ }
2813
+ async function runCliAgentSetup(argv, spec) {
2814
+ let options;
2815
+ try {
2816
+ options = parseArgs2(argv, spec);
2817
+ } catch (error) {
2818
+ console.error(error instanceof Error ? error.message : String(error));
2819
+ return 1;
2820
+ }
2821
+ if (options.action === "help") {
2822
+ console.log(usage(spec));
2823
+ return 0;
2824
+ }
2825
+ if (options.action === "status")
2826
+ return printStatus2(options, spec);
2827
+ if (options.action === "uninstall")
2828
+ return uninstall2(options, spec);
2829
+ const apiBaseUrl = (options.apiBaseUrl ?? (0, credentials_1.readHostCredentials)(spec.host)?.apiBaseUrl ?? hookAdapter_1.DEFAULT_API_BASE_URL).replace(/\/$/, "");
2830
+ console.log(`Ascenda setup for ${spec.displayName} \u2014 ${apiBaseUrl}`);
2831
+ const identity = await resolveIdentity2(apiBaseUrl, options, spec);
2832
+ if (!identity)
2833
+ return 1;
2834
+ console.log(` pairing ${identity.toolInstallationId}${identity.paired ? " (new)" : " (existing)"}`);
2835
+ const binary = installBinary2(spec, options.dryRun);
2836
+ console.log(` hook binary ${binary}`);
2837
+ if (!options.dryRun) {
2838
+ (0, credentials_1.writeHostCredentials)(spec.host, { apiBaseUrl, toolInstallationId: identity.toolInstallationId, pairedAt: (/* @__PURE__ */ new Date()).toISOString() });
2839
+ }
2840
+ console.log(` credentials ${(0, credentials_1.credentialsFilePath)()} (tools.${spec.host})`);
2841
+ const settingsFile = spec.settings.settingsPath(options.scope, options.projectDir);
2842
+ const written = writeHookSettings(settingsFile, binary, spec, options.dryRun);
2843
+ if (written === null)
2844
+ return 1;
2845
+ console.log(` hooks ${settingsFile} (${spec.hookEvents.length} events${written ? "" : ", already current"})`);
2846
+ if (options.dryRun) {
2847
+ console.log("\nDry run \u2014 nothing was written.");
2848
+ return 0;
2849
+ }
2850
+ console.log(`
2851
+ Done. ${spec.restartHint}`);
2852
+ console.log(`Check anytime: npx ${spec.packageName} status`);
2853
+ return 0;
2854
+ }
2855
+ function parseArgs2(argv, spec) {
2856
+ const options = {
2857
+ scope: "project",
2858
+ projectDir: process.cwd(),
2859
+ dryRun: false,
2860
+ action: "install"
2861
+ };
2862
+ for (let i = 0; i < argv.length; i++) {
2863
+ const arg = argv[i];
2864
+ const next = () => {
2865
+ const value = argv[++i];
2866
+ if (value === void 0)
2867
+ throw new Error(`${arg} needs a value`);
2868
+ return value;
2869
+ };
2870
+ switch (arg) {
2871
+ case "setup":
2872
+ case "install":
2873
+ options.action = "install";
2874
+ break;
2875
+ case "status":
2876
+ options.action = "status";
2877
+ break;
2878
+ case "uninstall":
2879
+ options.action = "uninstall";
2880
+ break;
2881
+ case "--api-base-url":
2882
+ options.apiBaseUrl = next();
2883
+ break;
2884
+ case "--local": {
2885
+ const peek = argv[i + 1];
2886
+ const port = peek && /^\d+$/.test(peek) ? argv[++i] : "4477";
2887
+ options.apiBaseUrl = `http://localhost:${port}`;
2888
+ break;
2889
+ }
2890
+ case "--tool-installation-id":
2891
+ options.toolInstallationId = next();
2892
+ break;
2893
+ case "--token":
2894
+ options.token = next();
2895
+ break;
2896
+ case "--scope": {
2897
+ const value = next();
2898
+ if (value !== "project" && value !== "user")
2899
+ throw new Error(`--scope must be project or user, got ${value}`);
2900
+ options.scope = value;
2901
+ break;
2902
+ }
2903
+ case "--project-dir":
2904
+ options.projectDir = path3.resolve(next());
2905
+ break;
2906
+ case "--dry-run":
2907
+ options.dryRun = true;
2908
+ break;
2909
+ case "-h":
2910
+ case "--help":
2911
+ options.action = "help";
2912
+ break;
2913
+ default:
2914
+ throw new Error(`unknown argument: ${arg}
2915
+
2916
+ ${usage(spec)}`);
2917
+ }
2918
+ }
2919
+ return options;
2920
+ }
2921
+ async function resolveIdentity2(apiBaseUrl, options, spec) {
2922
+ const existingId = options.toolInstallationId ?? (0, credentials_1.readHostCredentials)(spec.host)?.toolInstallationId;
2923
+ if (existingId && options.token) {
2924
+ if (!options.dryRun)
2925
+ (0, tokenStore_1.persistEventWriteToken)((0, tokenStore_1.defaultTokenFilePath)(existingId), options.token);
2926
+ return { toolInstallationId: existingId, paired: false };
2927
+ }
2928
+ if (existingId && (0, tokenStore_1.readTokenFile)((0, tokenStore_1.defaultTokenFilePath)(existingId))) {
2929
+ return { toolInstallationId: existingId, paired: false };
2930
+ }
2931
+ if (options.dryRun) {
2932
+ return { toolInstallationId: existingId ?? `${spec.toolType}:<paired at run time>`, paired: false };
2933
+ }
2934
+ const toolInstallationId = existingId ?? `${spec.toolType}:${crypto2.randomUUID()}`;
2935
+ let session;
2936
+ try {
2937
+ session = await (0, http_1.createPairingSession)(apiBaseUrl, toolInstallationId, spec.toolType, `${spec.displayName} on ${os2.hostname()}`);
2938
+ } catch (error) {
2939
+ console.error(`
2940
+ Could not reach ${apiBaseUrl} to pair: ${error instanceof Error ? error.message : String(error)}`);
2941
+ console.error("Start the local dev server and use --local, or pass --api-base-url for your backend.");
2942
+ return void 0;
2943
+ }
2944
+ const token = await pollForToken2(apiBaseUrl, session.pairingSessionId, session.code, session.expiresAt);
2945
+ if (!token)
2946
+ return void 0;
2947
+ (0, tokenStore_1.persistEventWriteToken)((0, tokenStore_1.defaultTokenFilePath)(toolInstallationId), token);
2948
+ return { toolInstallationId, paired: true };
2949
+ }
2950
+ async function pollForToken2(apiBaseUrl, pairingSessionId, code, expiresAt) {
2951
+ const deadline = Math.min(Date.parse(expiresAt) || Date.now() + 3e5, Date.now() + 3e5);
2952
+ let announced = false;
2953
+ while (Date.now() < deadline) {
2954
+ const status = await (0, http_1.getPairingStatus)(apiBaseUrl, pairingSessionId);
2955
+ if (status.status === "paired" && status.eventWriteToken)
2956
+ return status.eventWriteToken;
2957
+ if (status.status === "expired" || status.status === "cancelled") {
2958
+ console.error(`
2959
+ Pairing ${status.status}. Run setup again.`);
2960
+ return void 0;
2961
+ }
2962
+ if (!announced) {
2963
+ console.log(`
2964
+ Confirm in the Ascenda app \u2014 code ${code}`);
2965
+ console.log(" Waiting...");
2966
+ announced = true;
2967
+ }
2968
+ await new Promise((resolve2) => setTimeout(resolve2, 2e3));
2969
+ }
2970
+ console.error("\nPairing timed out. Run setup again.");
2971
+ return void 0;
2972
+ }
2973
+ function installBinary2(spec, dryRun) {
2974
+ const target = cliAgentHookBinPath(spec.binaryName);
2975
+ if (dryRun)
2976
+ return target;
2977
+ const source = process.argv[1];
2978
+ fs3.mkdirSync(path3.dirname(target), { recursive: true });
2979
+ if (path3.resolve(source) !== path3.resolve(target)) {
2980
+ fs3.copyFileSync(source, target);
2981
+ }
2982
+ if (process.platform !== "win32")
2983
+ fs3.chmodSync(target, 493);
2984
+ return target;
2985
+ }
2986
+ function writeHookSettings(settingsFile, binary, spec, dryRun) {
2987
+ let settings = { ...spec.settings.scaffold ?? {} };
2988
+ const exists = fs3.existsSync(settingsFile);
2989
+ if (exists) {
2990
+ const raw = fs3.readFileSync(settingsFile, "utf8").trim();
2991
+ if (raw) {
2992
+ try {
2993
+ settings = JSON.parse(raw);
2994
+ } catch {
2995
+ console.error(`
2996
+ ${settingsFile} is not valid JSON. Fix or move it, then run setup again.`);
2997
+ return null;
2998
+ }
2999
+ }
3000
+ }
3001
+ const command = hookCommand2(binary);
3002
+ const hooks = { ...settings.hooks ?? {} };
3003
+ for (const event of spec.hookEvents) {
3004
+ const kept = (hooks[event] ?? []).filter((entry) => !isOurs2(entry, spec));
3005
+ hooks[event] = [...kept, spec.settings.entry(command, event)];
3006
+ }
3007
+ const updated = { ...settings, hooks };
3008
+ const serialised = `${JSON.stringify(updated, null, 2)}
3009
+ `;
3010
+ if (exists && fs3.readFileSync(settingsFile, "utf8") === serialised)
3011
+ return false;
3012
+ if (dryRun) {
3013
+ console.log(`
3014
+ --- ${settingsFile} (dry run) ---
3015
+ ${serialised}`);
3016
+ return true;
3017
+ }
3018
+ if (exists)
3019
+ fs3.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
3020
+ fs3.mkdirSync(path3.dirname(settingsFile), { recursive: true });
3021
+ fs3.writeFileSync(settingsFile, serialised, "utf8");
3022
+ return true;
3023
+ }
3024
+ function hookCommand2(binary) {
3025
+ return `"${process.execPath}" "${binary}"`;
3026
+ }
3027
+ function isOurs2(entry, spec) {
3028
+ const command = spec.settings.commandOf(entry);
3029
+ return typeof command === "string" && command.includes(spec.binaryName);
3030
+ }
3031
+ function findStaleHookCommands2(settings, binary, spec) {
3032
+ const stale = /* @__PURE__ */ new Set();
3033
+ for (const entries of Object.values(settings.hooks ?? {})) {
3034
+ for (const entry of entries ?? []) {
3035
+ const command = spec.settings.commandOf(entry);
3036
+ if (typeof command !== "string")
3037
+ continue;
3038
+ if (!/ascenda/i.test(command) || command.includes(binary))
3039
+ continue;
3040
+ stale.add(command);
3041
+ }
3042
+ }
3043
+ return [...stale];
3044
+ }
3045
+ function readSettings(settingsFile) {
3046
+ try {
3047
+ return JSON.parse(fs3.readFileSync(settingsFile, "utf8"));
3048
+ } catch {
3049
+ return {};
3050
+ }
3051
+ }
3052
+ function printStatus2(options, spec) {
3053
+ const credentials = (0, credentials_1.readHostCredentials)(spec.host);
3054
+ const settingsFile = spec.settings.settingsPath(options.scope, options.projectDir);
3055
+ const binary = cliAgentHookBinPath(spec.binaryName);
3056
+ const tokenFile = credentials?.toolInstallationId ? (0, tokenStore_1.defaultTokenFilePath)(credentials.toolInstallationId) : void 0;
3057
+ const settings = readSettings(settingsFile);
3058
+ const registered = spec.hookEvents.filter((event) => (settings.hooks?.[event] ?? []).some((entry) => isOurs2(entry, spec))).length;
3059
+ const stale = findStaleHookCommands2(settings, binary, spec);
3060
+ console.log(`api base url ${credentials?.apiBaseUrl ?? "\u2014 not configured"}`);
3061
+ console.log(`pairing ${credentials?.toolInstallationId ?? "\u2014 not paired"}`);
3062
+ console.log(`token ${tokenFile && (0, tokenStore_1.readTokenFile)(tokenFile) ? "present" : "\u2014 missing"}`);
3063
+ console.log(`hook binary ${fs3.existsSync(binary) ? binary : "\u2014 not installed"}`);
3064
+ console.log(`hooks ${registered}/${spec.hookEvents.length} registered in ${settingsFile}`);
3065
+ if (stale.length) {
3066
+ console.log(`stale hooks ${stale.length} not pointing at the installed binary \u2014 each one fails silently per event:`);
3067
+ for (const command of stale)
3068
+ console.log(` ${command}`);
3069
+ console.log(` Remove them from ${settingsFile} by hand; setup cannot tell them from a hook you wrote.`);
3070
+ }
3071
+ const healthy = credentials?.toolInstallationId && registered === spec.hookEvents.length && fs3.existsSync(binary) && !stale.length;
3072
+ return healthy ? 0 : 1;
3073
+ }
3074
+ function uninstall2(options, spec) {
3075
+ const settingsFile = spec.settings.settingsPath(options.scope, options.projectDir);
3076
+ if (fs3.existsSync(settingsFile)) {
3077
+ try {
3078
+ const settings = JSON.parse(fs3.readFileSync(settingsFile, "utf8"));
3079
+ const hooks = { ...settings.hooks ?? {} };
3080
+ for (const event of Object.keys(hooks)) {
3081
+ const kept = hooks[event].filter((entry) => !isOurs2(entry, spec));
3082
+ if (kept.length)
3083
+ hooks[event] = kept;
3084
+ else
3085
+ delete hooks[event];
3086
+ }
3087
+ const updated = { ...settings, hooks };
3088
+ if (!Object.keys(hooks).length)
3089
+ delete updated.hooks;
3090
+ fs3.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
3091
+ fs3.writeFileSync(settingsFile, `${JSON.stringify(updated, null, 2)}
3092
+ `, "utf8");
3093
+ console.log(`hooks removed from ${settingsFile}`);
3094
+ } catch {
3095
+ console.error(`could not parse ${settingsFile} \u2014 remove the ascenda hook entries by hand`);
3096
+ return 1;
3097
+ }
3098
+ }
3099
+ const binary = cliAgentHookBinPath(spec.binaryName);
3100
+ if (fs3.existsSync(binary)) {
3101
+ fs3.rmSync(binary);
3102
+ console.log(`removed ${binary}`);
3103
+ }
3104
+ if ((0, credentials_1.readHostCredentials)(spec.host)) {
3105
+ (0, credentials_1.removeHostCredentials)(spec.host);
3106
+ console.log(`removed tools.${spec.host} from ${(0, credentials_1.credentialsFilePath)()}`);
3107
+ }
3108
+ console.log(`tokens left in ${path3.join((0, tokenStore_1.ascendaHome)(), "tokens")} \u2014 revoke in the Ascenda app to invalidate them`);
3109
+ return 0;
3110
+ }
3111
+ }
3112
+ });
3113
+
1674
3114
  // ../packages/tool-kit/out/turnState.js
1675
3115
  var require_turnState = __commonJS({
1676
3116
  "../packages/tool-kit/out/turnState.js"(exports) {
@@ -1715,7 +3155,7 @@ var require_turnState = __commonJS({
1715
3155
  Object.defineProperty(exports, "__esModule", { value: true });
1716
3156
  exports.recordTurnStart = recordTurnStart;
1717
3157
  exports.consumeTurnDurationMs = consumeTurnDurationMs;
1718
- var fs4 = __importStar(__require("fs"));
3158
+ var fs3 = __importStar(__require("fs"));
1719
3159
  var os2 = __importStar(__require("os"));
1720
3160
  var path3 = __importStar(__require("path"));
1721
3161
  var stateDir = () => process.env.ASCENDA_STATE_DIR ?? path3.join(os2.homedir(), ".ascenda", "state");
@@ -1729,8 +3169,8 @@ var require_turnState = __commonJS({
1729
3169
  if (!sessionId)
1730
3170
  return;
1731
3171
  try {
1732
- fs4.mkdirSync(stateDir(), { recursive: true });
1733
- fs4.writeFileSync(turnFile(agent, sessionId), String(now), { encoding: "utf8", mode: 384 });
3172
+ fs3.mkdirSync(stateDir(), { recursive: true });
3173
+ fs3.writeFileSync(turnFile(agent, sessionId), String(now), { encoding: "utf8", mode: 384 });
1734
3174
  } catch {
1735
3175
  }
1736
3176
  }
@@ -1739,8 +3179,8 @@ var require_turnState = __commonJS({
1739
3179
  return void 0;
1740
3180
  const file = turnFile(agent, sessionId);
1741
3181
  try {
1742
- const started = Number(fs4.readFileSync(file, "utf8").trim());
1743
- fs4.rmSync(file, { force: true });
3182
+ const started = Number(fs3.readFileSync(file, "utf8").trim());
3183
+ fs3.rmSync(file, { force: true });
1744
3184
  if (!Number.isFinite(started) || started <= 0 || started > now)
1745
3185
  return void 0;
1746
3186
  return now - started;
@@ -1797,7 +3237,7 @@ var require_liveBus = __commonJS({
1797
3237
  exports.liveBusSocketPath = liveBusSocketPath;
1798
3238
  exports.bucketPromptSize = bucketPromptSize2;
1799
3239
  exports.emitLiveSignal = emitLiveSignal2;
1800
- var fs4 = __importStar(__require("fs"));
3240
+ var fs3 = __importStar(__require("fs"));
1801
3241
  var net = __importStar(__require("net"));
1802
3242
  var os2 = __importStar(__require("os"));
1803
3243
  var path3 = __importStar(__require("path"));
@@ -1819,7 +3259,7 @@ var require_liveBus = __commonJS({
1819
3259
  const candidates = liveBusSocketCandidates();
1820
3260
  for (const candidate of candidates) {
1821
3261
  try {
1822
- if (fs4.statSync(candidate).isSocket())
3262
+ if (fs3.statSync(candidate).isSocket())
1823
3263
  return candidate;
1824
3264
  } catch {
1825
3265
  }
@@ -1884,8 +3324,9 @@ var require_out2 = __commonJS({
1884
3324
  "../packages/tool-kit/out/index.js"(exports) {
1885
3325
  "use strict";
1886
3326
  Object.defineProperty(exports, "__esModule", { value: true });
1887
- exports.readWorkContextRegistry = exports.recordWorkContextAlias = exports.recordWorkContext = exports.deriveWorkContext = exports.hashWithMachineSalt = exports.readOrCreateMachineSalt = exports.machineSaltFilePath = exports.markFailureNotified = exports.shouldAnnounceFailure = exports.recordSendOutcome = exports.readCollectorState = exports.defaultStateFilePath = exports.readTokenFile = exports.persistEventWriteToken = exports.defaultTokenFilePath = exports.ascendaHome = exports.recordTurnStart = exports.consumeTurnDurationMs = exports.resolveContextHashes = exports.loadCliAgentConfig = exports.deliverHookEvents = exports.DEFAULT_API_BASE_URL = exports.resolveEventLogPath = exports.expandUserPath = exports.appendEventLog = exports.EVENT_LOG_ENV_VAR = exports.buildEventPayload = exports.AscendaSemanticEventError = exports.AscendaEventSender = exports.looksLikeCorrection = exports.outcomeForHook = exports.inferOutcome = exports.getNestedNumber = exports.getNestedString = exports.getNested = exports.getNumber = exports.getString = exports.localHourAt = exports.utcOffsetMinutesAt = exports.BUSINESS_DAY = exports.isOutsideBusinessHours = exports.isAfterHours = exports.bucketDurationMs = exports.bucketLinesChanged = exports.invitesDebrief = exports.classifyWorkMilestone = exports.isReworkGitAction = exports.classifyGitAction = exports.isVerificationCommand = exports.classifyCommand = void 0;
1888
- exports.isRetryableStatus = exports.parseIngestResponse = exports.postToolEventsBatch = exports.postToolEvent = exports.renewToolToken = exports.getPairingStatus = exports.createPairingSession = exports.AscendaApiError = exports.liveBusSocketCandidates = exports.liveBusSocketPath = exports.bucketPromptSize = exports.emitLiveSignal = exports.workContextRegistryFilePath = void 0;
3327
+ exports.consumeTurnDurationMs = exports.writeTopLevelCredentials = exports.writeMachineCredentials = exports.writeHostCredentials = exports.removeHostCredentials = exports.readMachineCredentials = exports.readHostCredentials = exports.credentialsFilePath = exports.writeHookSettings = exports.runCliAgentSetup = exports.isCliAgentManagementCommand = exports.findStaleHookCommands = exports.cliAgentHookBinPath = exports.resolveContextHashes = exports.resolveCliAgentInstallationId = exports.loadCliAgentConfig = exports.deliverHookEvents = exports.MissingInstallationIdError = exports.DEFAULT_API_BASE_URL = exports.resolveEventLogPath = exports.expandUserPath = exports.appendEventLog = exports.EVENT_LOG_ENV_VAR = exports.buildEventPayload = exports.AscendaSemanticEventError = exports.AscendaEventSender = exports.mintIdempotencyKey = exports.looksLikeCorrection = exports.outcomeForHook = exports.inferOutcome = exports.getNestedNumber = exports.getNestedString = exports.getNested = exports.getNumber = exports.getString = exports.localHourAt = exports.utcOffsetMinutesAt = exports.BUSINESS_DAY = exports.isOutsideBusinessHours = exports.isAfterHours = exports.bucketDurationMs = exports.bucketLinesChanged = exports.classifyModelClass = exports.autonomyBand = exports.invitesDebrief = exports.classifyWorkMilestone = exports.isReworkGitAction = exports.classifyGitAction = exports.isVerificationCommand = exports.classifyCommand = void 0;
3328
+ exports.postToolEvent = exports.renewToolToken = exports.getPairingStatus = exports.createPairingSession = exports.AscendaApiError = exports.liveBusSocketCandidates = exports.liveBusSocketPath = exports.bucketPromptSize = exports.emitLiveSignal = exports.recordForgeProjectAlias = exports.forgeFullNameFromConfig = exports.readForgeFullName = exports.parseForgeFullName = exports.forgeProjectHash = exports.workContextRegistryFilePath = exports.readWorkContextRegistry = exports.recordWorkContextAlias = exports.recordWorkContext = exports.readBranchName = exports.normalizeBranchName = exports.deriveBranchHashForCwd = exports.deriveBranchHash = exports.deriveWorkContext = exports.hashWithMachineSalt = exports.readOrCreateMachineSalt = exports.machineSaltFilePath = exports.enforceOutboxBounds = exports.claimOutbox = exports.readOutboxSummary = exports.appendToOutbox = exports.defaultOutboxFilePath = exports.outboxDrainEnabled = exports.DEFAULT_OUTBOX_DRAIN_BATCH_SIZE = exports.DEFAULT_OUTBOX_MAX_AGE_MS = exports.DEFAULT_OUTBOX_MAX_ENTRIES = exports.OUTBOX_DRAIN_ENV_VAR = exports.recordOutboxDiscard = exports.unresolvedToolInstallationId = exports.unresolvedStateFilePath = exports.markFailureNotified = exports.shouldAnnounceFailure = exports.recordSendOutcome = exports.readCollectorState = exports.defaultStateFilePath = exports.readTokenFile = exports.persistEventWriteToken = exports.listPersistedToolInstallationIds = exports.defaultTokenFilePath = exports.ascendaHome = exports.recordTurnStart = void 0;
3329
+ exports.isRetryableStatus = exports.parseIngestResponse = exports.postToolEventsBatch = void 0;
1889
3330
  var commandClassifier_1 = require_commandClassifier();
1890
3331
  Object.defineProperty(exports, "classifyCommand", { enumerable: true, get: function() {
1891
3332
  return commandClassifier_1.classifyCommand;
@@ -1907,6 +3348,14 @@ var require_out2 = __commonJS({
1907
3348
  Object.defineProperty(exports, "invitesDebrief", { enumerable: true, get: function() {
1908
3349
  return workMilestoneClassifier_1.invitesDebrief;
1909
3350
  } });
3351
+ var autonomyBand_1 = require_autonomyBand();
3352
+ Object.defineProperty(exports, "autonomyBand", { enumerable: true, get: function() {
3353
+ return autonomyBand_1.autonomyBand;
3354
+ } });
3355
+ var modelClassifier_1 = require_modelClassifier();
3356
+ Object.defineProperty(exports, "classifyModelClass", { enumerable: true, get: function() {
3357
+ return modelClassifier_1.classifyModelClass;
3358
+ } });
1910
3359
  var buckets_1 = require_buckets();
1911
3360
  Object.defineProperty(exports, "bucketLinesChanged", { enumerable: true, get: function() {
1912
3361
  return buckets_1.bucketLinesChanged;
@@ -1955,6 +3404,9 @@ var require_out2 = __commonJS({
1955
3404
  Object.defineProperty(exports, "looksLikeCorrection", { enumerable: true, get: function() {
1956
3405
  return payload_1.looksLikeCorrection;
1957
3406
  } });
3407
+ Object.defineProperty(exports, "mintIdempotencyKey", { enumerable: true, get: function() {
3408
+ return payload_1.mintIdempotencyKey;
3409
+ } });
1958
3410
  var eventSender_1 = require_eventSender();
1959
3411
  Object.defineProperty(exports, "AscendaEventSender", { enumerable: true, get: function() {
1960
3412
  return eventSender_1.AscendaEventSender;
@@ -1982,15 +3434,59 @@ var require_out2 = __commonJS({
1982
3434
  Object.defineProperty(exports, "DEFAULT_API_BASE_URL", { enumerable: true, get: function() {
1983
3435
  return hookAdapter_1.DEFAULT_API_BASE_URL;
1984
3436
  } });
3437
+ Object.defineProperty(exports, "MissingInstallationIdError", { enumerable: true, get: function() {
3438
+ return hookAdapter_1.MissingInstallationIdError;
3439
+ } });
1985
3440
  Object.defineProperty(exports, "deliverHookEvents", { enumerable: true, get: function() {
1986
3441
  return hookAdapter_1.deliverHookEvents;
1987
3442
  } });
1988
3443
  Object.defineProperty(exports, "loadCliAgentConfig", { enumerable: true, get: function() {
1989
3444
  return hookAdapter_1.loadCliAgentConfig;
1990
3445
  } });
3446
+ Object.defineProperty(exports, "resolveCliAgentInstallationId", { enumerable: true, get: function() {
3447
+ return hookAdapter_1.resolveCliAgentInstallationId;
3448
+ } });
1991
3449
  Object.defineProperty(exports, "resolveContextHashes", { enumerable: true, get: function() {
1992
3450
  return hookAdapter_1.resolveContextHashes;
1993
3451
  } });
3452
+ var cliAgentSetup_1 = require_cliAgentSetup();
3453
+ Object.defineProperty(exports, "cliAgentHookBinPath", { enumerable: true, get: function() {
3454
+ return cliAgentSetup_1.cliAgentHookBinPath;
3455
+ } });
3456
+ Object.defineProperty(exports, "findStaleHookCommands", { enumerable: true, get: function() {
3457
+ return cliAgentSetup_1.findStaleHookCommands;
3458
+ } });
3459
+ Object.defineProperty(exports, "isCliAgentManagementCommand", { enumerable: true, get: function() {
3460
+ return cliAgentSetup_1.isCliAgentManagementCommand;
3461
+ } });
3462
+ Object.defineProperty(exports, "runCliAgentSetup", { enumerable: true, get: function() {
3463
+ return cliAgentSetup_1.runCliAgentSetup;
3464
+ } });
3465
+ Object.defineProperty(exports, "writeHookSettings", { enumerable: true, get: function() {
3466
+ return cliAgentSetup_1.writeHookSettings;
3467
+ } });
3468
+ var credentials_1 = require_credentials();
3469
+ Object.defineProperty(exports, "credentialsFilePath", { enumerable: true, get: function() {
3470
+ return credentials_1.credentialsFilePath;
3471
+ } });
3472
+ Object.defineProperty(exports, "readHostCredentials", { enumerable: true, get: function() {
3473
+ return credentials_1.readHostCredentials;
3474
+ } });
3475
+ Object.defineProperty(exports, "readMachineCredentials", { enumerable: true, get: function() {
3476
+ return credentials_1.readMachineCredentials;
3477
+ } });
3478
+ Object.defineProperty(exports, "removeHostCredentials", { enumerable: true, get: function() {
3479
+ return credentials_1.removeHostCredentials;
3480
+ } });
3481
+ Object.defineProperty(exports, "writeHostCredentials", { enumerable: true, get: function() {
3482
+ return credentials_1.writeHostCredentials;
3483
+ } });
3484
+ Object.defineProperty(exports, "writeMachineCredentials", { enumerable: true, get: function() {
3485
+ return credentials_1.writeMachineCredentials;
3486
+ } });
3487
+ Object.defineProperty(exports, "writeTopLevelCredentials", { enumerable: true, get: function() {
3488
+ return credentials_1.writeTopLevelCredentials;
3489
+ } });
1994
3490
  var turnState_1 = require_turnState();
1995
3491
  Object.defineProperty(exports, "consumeTurnDurationMs", { enumerable: true, get: function() {
1996
3492
  return turnState_1.consumeTurnDurationMs;
@@ -2005,6 +3501,9 @@ var require_out2 = __commonJS({
2005
3501
  Object.defineProperty(exports, "defaultTokenFilePath", { enumerable: true, get: function() {
2006
3502
  return tokenStore_1.defaultTokenFilePath;
2007
3503
  } });
3504
+ Object.defineProperty(exports, "listPersistedToolInstallationIds", { enumerable: true, get: function() {
3505
+ return tokenStore_1.listPersistedToolInstallationIds;
3506
+ } });
2008
3507
  Object.defineProperty(exports, "persistEventWriteToken", { enumerable: true, get: function() {
2009
3508
  return tokenStore_1.persistEventWriteToken;
2010
3509
  } });
@@ -2027,6 +3526,46 @@ var require_out2 = __commonJS({
2027
3526
  Object.defineProperty(exports, "markFailureNotified", { enumerable: true, get: function() {
2028
3527
  return stateStore_1.markFailureNotified;
2029
3528
  } });
3529
+ Object.defineProperty(exports, "unresolvedStateFilePath", { enumerable: true, get: function() {
3530
+ return stateStore_1.unresolvedStateFilePath;
3531
+ } });
3532
+ Object.defineProperty(exports, "unresolvedToolInstallationId", { enumerable: true, get: function() {
3533
+ return stateStore_1.unresolvedToolInstallationId;
3534
+ } });
3535
+ Object.defineProperty(exports, "recordOutboxDiscard", { enumerable: true, get: function() {
3536
+ return stateStore_1.recordOutboxDiscard;
3537
+ } });
3538
+ var outbox_1 = require_outbox();
3539
+ Object.defineProperty(exports, "OUTBOX_DRAIN_ENV_VAR", { enumerable: true, get: function() {
3540
+ return outbox_1.OUTBOX_DRAIN_ENV_VAR;
3541
+ } });
3542
+ Object.defineProperty(exports, "DEFAULT_OUTBOX_MAX_ENTRIES", { enumerable: true, get: function() {
3543
+ return outbox_1.DEFAULT_OUTBOX_MAX_ENTRIES;
3544
+ } });
3545
+ Object.defineProperty(exports, "DEFAULT_OUTBOX_MAX_AGE_MS", { enumerable: true, get: function() {
3546
+ return outbox_1.DEFAULT_OUTBOX_MAX_AGE_MS;
3547
+ } });
3548
+ Object.defineProperty(exports, "DEFAULT_OUTBOX_DRAIN_BATCH_SIZE", { enumerable: true, get: function() {
3549
+ return outbox_1.DEFAULT_OUTBOX_DRAIN_BATCH_SIZE;
3550
+ } });
3551
+ Object.defineProperty(exports, "outboxDrainEnabled", { enumerable: true, get: function() {
3552
+ return outbox_1.outboxDrainEnabled;
3553
+ } });
3554
+ Object.defineProperty(exports, "defaultOutboxFilePath", { enumerable: true, get: function() {
3555
+ return outbox_1.defaultOutboxFilePath;
3556
+ } });
3557
+ Object.defineProperty(exports, "appendToOutbox", { enumerable: true, get: function() {
3558
+ return outbox_1.appendToOutbox;
3559
+ } });
3560
+ Object.defineProperty(exports, "readOutboxSummary", { enumerable: true, get: function() {
3561
+ return outbox_1.readOutboxSummary;
3562
+ } });
3563
+ Object.defineProperty(exports, "claimOutbox", { enumerable: true, get: function() {
3564
+ return outbox_1.claimOutbox;
3565
+ } });
3566
+ Object.defineProperty(exports, "enforceOutboxBounds", { enumerable: true, get: function() {
3567
+ return outbox_1.enforceOutboxBounds;
3568
+ } });
2030
3569
  var salt_1 = require_salt();
2031
3570
  Object.defineProperty(exports, "machineSaltFilePath", { enumerable: true, get: function() {
2032
3571
  return salt_1.machineSaltFilePath;
@@ -2041,6 +3580,18 @@ var require_out2 = __commonJS({
2041
3580
  Object.defineProperty(exports, "deriveWorkContext", { enumerable: true, get: function() {
2042
3581
  return workContext_1.deriveWorkContext;
2043
3582
  } });
3583
+ Object.defineProperty(exports, "deriveBranchHash", { enumerable: true, get: function() {
3584
+ return workContext_1.deriveBranchHash;
3585
+ } });
3586
+ Object.defineProperty(exports, "deriveBranchHashForCwd", { enumerable: true, get: function() {
3587
+ return workContext_1.deriveBranchHashForCwd;
3588
+ } });
3589
+ Object.defineProperty(exports, "normalizeBranchName", { enumerable: true, get: function() {
3590
+ return workContext_1.normalizeBranchName;
3591
+ } });
3592
+ Object.defineProperty(exports, "readBranchName", { enumerable: true, get: function() {
3593
+ return workContext_1.readBranchName;
3594
+ } });
2044
3595
  var contextRegistry_1 = require_contextRegistry();
2045
3596
  Object.defineProperty(exports, "recordWorkContext", { enumerable: true, get: function() {
2046
3597
  return contextRegistry_1.recordWorkContext;
@@ -2054,6 +3605,22 @@ var require_out2 = __commonJS({
2054
3605
  Object.defineProperty(exports, "workContextRegistryFilePath", { enumerable: true, get: function() {
2055
3606
  return contextRegistry_1.workContextRegistryFilePath;
2056
3607
  } });
3608
+ var forgeProject_1 = require_forgeProject();
3609
+ Object.defineProperty(exports, "forgeProjectHash", { enumerable: true, get: function() {
3610
+ return forgeProject_1.forgeProjectHash;
3611
+ } });
3612
+ Object.defineProperty(exports, "parseForgeFullName", { enumerable: true, get: function() {
3613
+ return forgeProject_1.parseForgeFullName;
3614
+ } });
3615
+ Object.defineProperty(exports, "readForgeFullName", { enumerable: true, get: function() {
3616
+ return forgeProject_1.readForgeFullName;
3617
+ } });
3618
+ Object.defineProperty(exports, "forgeFullNameFromConfig", { enumerable: true, get: function() {
3619
+ return forgeProject_1.forgeFullNameFromConfig;
3620
+ } });
3621
+ Object.defineProperty(exports, "recordForgeProjectAlias", { enumerable: true, get: function() {
3622
+ return forgeProject_1.recordForgeProjectAlias;
3623
+ } });
2057
3624
  var liveBus_1 = require_liveBus();
2058
3625
  Object.defineProperty(exports, "emitLiveSignal", { enumerable: true, get: function() {
2059
3626
  return liveBus_1.emitLiveSignal;
@@ -2096,40 +3663,25 @@ var require_out2 = __commonJS({
2096
3663
  });
2097
3664
 
2098
3665
  // src/paths.ts
2099
- import * as fs from "fs";
2100
3666
  import * as path from "path";
2101
3667
  function hookBinPath() {
2102
3668
  return path.join((0, import_tool_kit3.ascendaHome)(), "bin", "ascenda-claude-hook");
2103
3669
  }
2104
- function credentialsFilePath() {
2105
- return path.join((0, import_tool_kit3.ascendaHome)(), "credentials.json");
2106
- }
2107
3670
  function readCredentials() {
2108
- try {
2109
- const raw = fs.readFileSync(credentialsFilePath(), "utf8").trim();
2110
- if (!raw) return void 0;
2111
- const parsed = JSON.parse(raw);
2112
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return void 0;
2113
- return parsed;
2114
- } catch {
2115
- return void 0;
2116
- }
3671
+ const credentials = (0, import_tool_kit3.readMachineCredentials)();
3672
+ if (!credentials) return void 0;
3673
+ const { tools: _tools, ...topLevel } = credentials;
3674
+ return topLevel;
2117
3675
  }
2118
3676
  function writeCredentials(credentials) {
2119
- const file = credentialsFilePath();
2120
- fs.mkdirSync(path.dirname(file), { recursive: true, mode: 448 });
2121
- fs.writeFileSync(file, `${JSON.stringify(credentials, null, 2)}
2122
- `, { encoding: "utf8", mode: 384 });
2123
- if (process.platform !== "win32") {
2124
- fs.chmodSync(path.dirname(file), 448);
2125
- fs.chmodSync(file, 384);
2126
- }
3677
+ (0, import_tool_kit3.writeTopLevelCredentials)(credentials);
2127
3678
  }
2128
- var import_tool_kit3;
3679
+ var import_tool_kit3, import_tool_kit4;
2129
3680
  var init_paths = __esm({
2130
3681
  "src/paths.ts"() {
2131
3682
  "use strict";
2132
3683
  import_tool_kit3 = __toESM(require_out2(), 1);
3684
+ import_tool_kit4 = __toESM(require_out2(), 1);
2133
3685
  }
2134
3686
  });
2135
3687
 
@@ -2159,37 +3711,53 @@ var init_types = __esm({
2159
3711
  });
2160
3712
 
2161
3713
  // src/config.ts
3714
+ function resolveOutboxFilePath(toolInstallationId) {
3715
+ return process.env.ASCENDA_OUTBOX_FILE ?? (0, import_tool_kit5.defaultOutboxFilePath)(toolInstallationId);
3716
+ }
2162
3717
  function resolveStateFilePath(toolInstallationId) {
2163
- return process.env.ASCENDA_STATE_FILE ?? (0, import_tool_kit4.defaultStateFilePath)(toolInstallationId);
3718
+ return process.env.ASCENDA_STATE_FILE ?? (toolInstallationId ? (0, import_tool_kit5.defaultStateFilePath)(toolInstallationId) : (0, import_tool_kit5.unresolvedStateFilePath)(ASCENDA_TOOL_TYPE));
3719
+ }
3720
+ function resolveToolInstallationId(credentials = readCredentials()) {
3721
+ const fromEnv = process.env.ASCENDA_TOOL_INSTALLATION_ID?.trim();
3722
+ if (fromEnv) return { toolInstallationId: normalizeToolInstallationId(fromEnv), source: "env" };
3723
+ const fromCredentials = credentials?.toolInstallationId?.trim();
3724
+ if (fromCredentials) return { toolInstallationId: normalizeToolInstallationId(fromCredentials), source: "credentials" };
3725
+ const candidates = (0, import_tool_kit5.listPersistedToolInstallationIds)(ASCENDA_TOOL_TYPE);
3726
+ if (candidates.length === 1) return { toolInstallationId: candidates[0], source: "disk" };
3727
+ throw new MissingInstallationIdError(candidates);
2164
3728
  }
2165
3729
  function loadConfigFromEnv() {
2166
3730
  const credentials = readCredentials();
2167
3731
  const apiBaseUrl = (process.env.ASCENDA_API_BASE_URL ?? credentials?.apiBaseUrl ?? DEFAULT_API_BASE_URL).replace(/\/$/, "");
2168
- const toolInstallationIdRaw = process.env.ASCENDA_TOOL_INSTALLATION_ID ?? credentials?.toolInstallationId;
2169
- if (!toolInstallationIdRaw) {
2170
- throw new Error("Not configured: no ASCENDA_TOOL_INSTALLATION_ID and no pairing in ~/.ascenda/credentials.json. Run: npx @ascenda-one/claude-code-hooks setup");
2171
- }
2172
- const toolInstallationId = normalizeToolInstallationId(toolInstallationIdRaw);
2173
- const tokenFilePath = process.env.ASCENDA_EVENT_WRITE_TOKEN_FILE ?? (0, import_tool_kit4.defaultTokenFilePath)(toolInstallationId);
2174
- const fileToken = (0, import_tool_kit4.readTokenFile)(tokenFilePath);
3732
+ const { toolInstallationId } = resolveToolInstallationId(credentials);
3733
+ const tokenFilePath = process.env.ASCENDA_EVENT_WRITE_TOKEN_FILE ?? (0, import_tool_kit5.defaultTokenFilePath)(toolInstallationId);
3734
+ const fileToken = (0, import_tool_kit5.readTokenFile)(tokenFilePath);
2175
3735
  const eventWriteToken = fileToken ?? process.env.ASCENDA_EVENT_WRITE_TOKEN;
2176
3736
  if (!eventWriteToken) throw new Error("Missing ASCENDA_EVENT_WRITE_TOKEN (or token file)");
2177
- if (!fileToken) (0, import_tool_kit4.persistEventWriteToken)(tokenFilePath, eventWriteToken);
3737
+ if (!fileToken) (0, import_tool_kit5.persistEventWriteToken)(tokenFilePath, eventWriteToken);
2178
3738
  return {
2179
3739
  apiBaseUrl,
2180
3740
  toolInstallationId,
2181
3741
  eventWriteToken,
2182
3742
  tokenFilePath,
2183
3743
  stateFilePath: resolveStateFilePath(toolInstallationId),
2184
- sessionId: process.env.ASCENDA_SESSION_ID ?? null,
3744
+ outboxFilePath: resolveOutboxFilePath(toolInstallationId),
3745
+ // Override only. When unset, main() fills it from the hook payload's own
3746
+ // `session_id`, exactly as it does the context hashes below — see there.
3747
+ //
3748
+ // Through `envOverride` rather than read raw: `ASCENDA_SESSION_ID=""` used
3749
+ // to produce an empty-string session on the wire, which is neither an
3750
+ // override nor an absence — it groups every such row together under a
3751
+ // value that names no session.
3752
+ sessionId: envOverride("ASCENDA_SESSION_ID"),
2185
3753
  // Overrides only. When unset, main() fills these from the hook payload's
2186
3754
  // own cwd — the payload knows where the work happened; the environment
2187
3755
  // this hook inherits does not have to.
2188
- workspaceHash: envHashOverride("ASCENDA_WORKSPACE_HASH"),
2189
- projectHash: envHashOverride("ASCENDA_PROJECT_HASH")
3756
+ workspaceHash: envOverride("ASCENDA_WORKSPACE_HASH"),
3757
+ projectHash: envOverride("ASCENDA_PROJECT_HASH")
2190
3758
  };
2191
3759
  }
2192
- function envHashOverride(name) {
3760
+ function envOverride(name) {
2193
3761
  const value = process.env[name]?.trim();
2194
3762
  return value ? value : null;
2195
3763
  }
@@ -2199,14 +3767,25 @@ function normalizeToolInstallationId(value) {
2199
3767
  if (trimmed.startsWith("claude_tool_")) return `${ASCENDA_TOOL_TYPE}:${trimmed.slice("claude_tool_".length)}`;
2200
3768
  return `${ASCENDA_TOOL_TYPE}:${trimmed}`;
2201
3769
  }
2202
- var import_tool_kit4, DEFAULT_API_BASE_URL;
3770
+ var import_tool_kit5, DEFAULT_API_BASE_URL, MissingInstallationIdError;
2203
3771
  var init_config = __esm({
2204
3772
  "src/config.ts"() {
2205
3773
  "use strict";
2206
- import_tool_kit4 = __toESM(require_out2(), 1);
3774
+ import_tool_kit5 = __toESM(require_out2(), 1);
2207
3775
  init_paths();
2208
3776
  init_types();
2209
3777
  DEFAULT_API_BASE_URL = "https://api.ascenda.one";
3778
+ MissingInstallationIdError = class extends Error {
3779
+ /** The token files that were considered — none, or too many to pick from. */
3780
+ candidates;
3781
+ constructor(candidates) {
3782
+ super(
3783
+ candidates.length === 0 ? "Not configured: no ASCENDA_TOOL_INSTALLATION_ID, no pairing in ~/.ascenda/credentials.json, and no claude_code token in ~/.ascenda/tokens/. Run: npx @ascenda-one/claude-code-hooks setup" : `Not configured: no ASCENDA_TOOL_INSTALLATION_ID, no pairing in ~/.ascenda/credentials.json, and ${candidates.length} claude_code tokens in ~/.ascenda/tokens/ (${candidates.join(", ")}) \u2014 refusing to guess. Export ASCENDA_TOOL_INSTALLATION_ID to choose one, or run: npx @ascenda-one/claude-code-hooks setup`
3784
+ );
3785
+ this.name = "MissingInstallationIdError";
3786
+ this.candidates = candidates;
3787
+ }
3788
+ };
2210
3789
  }
2211
3790
  });
2212
3791
 
@@ -2218,7 +3797,7 @@ __export(setup_exports, {
2218
3797
  writeSettings: () => writeSettings
2219
3798
  });
2220
3799
  import * as crypto from "crypto";
2221
- import * as fs2 from "fs";
3800
+ import * as fs from "fs";
2222
3801
  import * as os from "os";
2223
3802
  import * as path2 from "path";
2224
3803
  async function runSetup(argv) {
@@ -2245,7 +3824,7 @@ async function runSetup(argv) {
2245
3824
  if (!options.dryRun) {
2246
3825
  writeCredentials({ apiBaseUrl, toolInstallationId: identity.toolInstallationId, pairedAt: (/* @__PURE__ */ new Date()).toISOString() });
2247
3826
  }
2248
- console.log(` credentials ${credentialsFilePath()}`);
3827
+ console.log(` credentials ${(0, import_tool_kit4.credentialsFilePath)()}`);
2249
3828
  const settingsFile = settingsPath(options);
2250
3829
  const written = writeSettings(settingsFile, binary, options.dryRun);
2251
3830
  if (written === null) return 1;
@@ -2325,10 +3904,10 @@ ${USAGE}`);
2325
3904
  async function resolveIdentity(apiBaseUrl, options) {
2326
3905
  const existingId = options.toolInstallationId ?? readCredentials()?.toolInstallationId;
2327
3906
  if (existingId && options.token) {
2328
- if (!options.dryRun) (0, import_tool_kit7.persistEventWriteToken)((0, import_tool_kit7.defaultTokenFilePath)(existingId), options.token);
3907
+ if (!options.dryRun) (0, import_tool_kit8.persistEventWriteToken)((0, import_tool_kit8.defaultTokenFilePath)(existingId), options.token);
2329
3908
  return { toolInstallationId: existingId, paired: false };
2330
3909
  }
2331
- if (existingId && (0, import_tool_kit7.readTokenFile)((0, import_tool_kit7.defaultTokenFilePath)(existingId))) {
3910
+ if (existingId && (0, import_tool_kit8.readTokenFile)((0, import_tool_kit8.defaultTokenFilePath)(existingId))) {
2332
3911
  return { toolInstallationId: existingId, paired: false };
2333
3912
  }
2334
3913
  if (options.dryRun) {
@@ -2337,7 +3916,7 @@ async function resolveIdentity(apiBaseUrl, options) {
2337
3916
  const toolInstallationId = existingId ?? `${ASCENDA_TOOL_TYPE}:${crypto.randomUUID()}`;
2338
3917
  let session;
2339
3918
  try {
2340
- session = await (0, import_tool_kit7.createPairingSession)(apiBaseUrl, toolInstallationId, ASCENDA_TOOL_TYPE, `Claude Code on ${os.hostname()}`);
3919
+ session = await (0, import_tool_kit8.createPairingSession)(apiBaseUrl, toolInstallationId, ASCENDA_TOOL_TYPE, `Claude Code on ${os.hostname()}`);
2341
3920
  } catch (error) {
2342
3921
  console.error(`
2343
3922
  Could not reach ${apiBaseUrl} to pair: ${error instanceof Error ? error.message : String(error)}`);
@@ -2346,14 +3925,14 @@ Could not reach ${apiBaseUrl} to pair: ${error instanceof Error ? error.message
2346
3925
  }
2347
3926
  const token = await pollForToken(apiBaseUrl, session.pairingSessionId, session.code, session.expiresAt);
2348
3927
  if (!token) return void 0;
2349
- (0, import_tool_kit7.persistEventWriteToken)((0, import_tool_kit7.defaultTokenFilePath)(toolInstallationId), token);
3928
+ (0, import_tool_kit8.persistEventWriteToken)((0, import_tool_kit8.defaultTokenFilePath)(toolInstallationId), token);
2350
3929
  return { toolInstallationId, paired: true };
2351
3930
  }
2352
3931
  async function pollForToken(apiBaseUrl, pairingSessionId, code, expiresAt) {
2353
3932
  const deadline = Math.min(Date.parse(expiresAt) || Date.now() + 3e5, Date.now() + 3e5);
2354
3933
  let announced = false;
2355
3934
  while (Date.now() < deadline) {
2356
- const status = await (0, import_tool_kit7.getPairingStatus)(apiBaseUrl, pairingSessionId);
3935
+ const status = await (0, import_tool_kit8.getPairingStatus)(apiBaseUrl, pairingSessionId);
2357
3936
  if (status.status === "paired" && status.eventWriteToken) return status.eventWriteToken;
2358
3937
  if (status.status === "expired" || status.status === "cancelled") {
2359
3938
  console.error(`
@@ -2375,11 +3954,11 @@ function installBinary(dryRun) {
2375
3954
  const target = hookBinPath();
2376
3955
  if (dryRun) return target;
2377
3956
  const source = process.argv[1];
2378
- fs2.mkdirSync(path2.dirname(target), { recursive: true });
3957
+ fs.mkdirSync(path2.dirname(target), { recursive: true });
2379
3958
  if (path2.resolve(source) !== path2.resolve(target)) {
2380
- fs2.copyFileSync(source, target);
3959
+ fs.copyFileSync(source, target);
2381
3960
  }
2382
- if (process.platform !== "win32") fs2.chmodSync(target, 493);
3961
+ if (process.platform !== "win32") fs.chmodSync(target, 493);
2383
3962
  return target;
2384
3963
  }
2385
3964
  function settingsPath(options) {
@@ -2387,9 +3966,9 @@ function settingsPath(options) {
2387
3966
  }
2388
3967
  function writeSettings(settingsFile, binary, dryRun) {
2389
3968
  let settings = {};
2390
- const exists = fs2.existsSync(settingsFile);
3969
+ const exists = fs.existsSync(settingsFile);
2391
3970
  if (exists) {
2392
- const raw = fs2.readFileSync(settingsFile, "utf8").trim();
3971
+ const raw = fs.readFileSync(settingsFile, "utf8").trim();
2393
3972
  if (raw) {
2394
3973
  try {
2395
3974
  settings = JSON.parse(raw);
@@ -2409,16 +3988,16 @@ ${settingsFile} is not valid JSON. Fix or move it, then run setup again.`);
2409
3988
  const updated = { ...settings, hooks };
2410
3989
  const serialised = `${JSON.stringify(updated, null, 2)}
2411
3990
  `;
2412
- if (exists && fs2.readFileSync(settingsFile, "utf8") === serialised) return false;
3991
+ if (exists && fs.readFileSync(settingsFile, "utf8") === serialised) return false;
2413
3992
  if (dryRun) {
2414
3993
  console.log(`
2415
3994
  --- ${settingsFile} (dry run) ---
2416
3995
  ${serialised}`);
2417
3996
  return true;
2418
3997
  }
2419
- if (exists) fs2.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
2420
- fs2.mkdirSync(path2.dirname(settingsFile), { recursive: true });
2421
- fs2.writeFileSync(settingsFile, serialised, "utf8");
3998
+ if (exists) fs.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
3999
+ fs.mkdirSync(path2.dirname(settingsFile), { recursive: true });
4000
+ fs.writeFileSync(settingsFile, serialised, "utf8");
2422
4001
  return true;
2423
4002
  }
2424
4003
  function hookCommand(binary) {
@@ -2445,10 +4024,10 @@ function printStatus(options) {
2445
4024
  const credentials = readCredentials();
2446
4025
  const settingsFile = settingsPath(options);
2447
4026
  const binary = hookBinPath();
2448
- const tokenFile = credentials?.toolInstallationId ? (0, import_tool_kit7.defaultTokenFilePath)(credentials.toolInstallationId) : void 0;
4027
+ const tokenFile = credentials?.toolInstallationId ? (0, import_tool_kit8.defaultTokenFilePath)(credentials.toolInstallationId) : void 0;
2449
4028
  const settings = (() => {
2450
4029
  try {
2451
- return JSON.parse(fs2.readFileSync(settingsFile, "utf8"));
4030
+ return JSON.parse(fs.readFileSync(settingsFile, "utf8"));
2452
4031
  } catch {
2453
4032
  return {};
2454
4033
  }
@@ -2457,22 +4036,22 @@ function printStatus(options) {
2457
4036
  const stale = findStaleHookCommands(settings, binary);
2458
4037
  console.log(`api base url ${credentials?.apiBaseUrl ?? "\u2014 not configured"}`);
2459
4038
  console.log(`pairing ${credentials?.toolInstallationId ?? "\u2014 not paired"}`);
2460
- console.log(`token ${tokenFile && (0, import_tool_kit7.readTokenFile)(tokenFile) ? "present" : "\u2014 missing"}`);
2461
- console.log(`hook binary ${fs2.existsSync(binary) ? binary : "\u2014 not installed"}`);
4039
+ console.log(`token ${tokenFile && (0, import_tool_kit8.readTokenFile)(tokenFile) ? "present" : "\u2014 missing"}`);
4040
+ console.log(`hook binary ${fs.existsSync(binary) ? binary : "\u2014 not installed"}`);
2462
4041
  console.log(`hooks ${registered}/${HOOK_EVENTS.length} registered in ${settingsFile}`);
2463
4042
  if (stale.length) {
2464
4043
  console.log(`stale hooks ${stale.length} not pointing at the installed binary \u2014 each one fails silently per event:`);
2465
4044
  for (const command of stale) console.log(` ${command}`);
2466
4045
  console.log(` Remove them from ${settingsFile} by hand; setup cannot tell them from a hook you wrote.`);
2467
4046
  }
2468
- const healthy = credentials?.toolInstallationId && registered === HOOK_EVENTS.length && fs2.existsSync(binary) && !stale.length;
4047
+ const healthy = credentials?.toolInstallationId && registered === HOOK_EVENTS.length && fs.existsSync(binary) && !stale.length;
2469
4048
  return healthy ? 0 : 1;
2470
4049
  }
2471
4050
  function uninstall(options) {
2472
4051
  const settingsFile = settingsPath(options);
2473
- if (fs2.existsSync(settingsFile)) {
4052
+ if (fs.existsSync(settingsFile)) {
2474
4053
  try {
2475
- const settings = JSON.parse(fs2.readFileSync(settingsFile, "utf8"));
4054
+ const settings = JSON.parse(fs.readFileSync(settingsFile, "utf8"));
2476
4055
  const hooks = { ...settings.hooks ?? {} };
2477
4056
  for (const event of Object.keys(hooks)) {
2478
4057
  const kept = hooks[event].filter((group) => !isOurs(group));
@@ -2481,8 +4060,8 @@ function uninstall(options) {
2481
4060
  }
2482
4061
  const updated = { ...settings, hooks };
2483
4062
  if (!Object.keys(hooks).length) delete updated.hooks;
2484
- fs2.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
2485
- fs2.writeFileSync(settingsFile, `${JSON.stringify(updated, null, 2)}
4063
+ fs.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
4064
+ fs.writeFileSync(settingsFile, `${JSON.stringify(updated, null, 2)}
2486
4065
  `, "utf8");
2487
4066
  console.log(`hooks removed from ${settingsFile}`);
2488
4067
  } catch {
@@ -2491,23 +4070,23 @@ function uninstall(options) {
2491
4070
  }
2492
4071
  }
2493
4072
  const binary = hookBinPath();
2494
- if (fs2.existsSync(binary)) {
2495
- fs2.rmSync(binary);
4073
+ if (fs.existsSync(binary)) {
4074
+ fs.rmSync(binary);
2496
4075
  console.log(`removed ${binary}`);
2497
4076
  }
2498
- const credentials = credentialsFilePath();
2499
- if (fs2.existsSync(credentials)) {
2500
- fs2.rmSync(credentials);
4077
+ const credentials = (0, import_tool_kit4.credentialsFilePath)();
4078
+ if (fs.existsSync(credentials)) {
4079
+ fs.rmSync(credentials);
2501
4080
  console.log(`removed ${credentials}`);
2502
4081
  }
2503
- console.log(`tokens left in ${path2.join((0, import_tool_kit7.ascendaHome)(), "tokens")} \u2014 revoke in the Ascenda app to invalidate them`);
4082
+ console.log(`tokens left in ${path2.join((0, import_tool_kit8.ascendaHome)(), "tokens")} \u2014 revoke in the Ascenda app to invalidate them`);
2504
4083
  return 0;
2505
4084
  }
2506
- var import_tool_kit7, HOOK_EVENTS, HOOK_TIMEOUT_SECONDS, HOOK_MARKER, USAGE;
4085
+ var import_tool_kit8, HOOK_EVENTS, HOOK_TIMEOUT_SECONDS, HOOK_MARKER, USAGE;
2507
4086
  var init_setup = __esm({
2508
4087
  "src/setup.ts"() {
2509
4088
  "use strict";
2510
- import_tool_kit7 = __toESM(require_out2(), 1);
4089
+ import_tool_kit8 = __toESM(require_out2(), 1);
2511
4090
  init_config();
2512
4091
  init_paths();
2513
4092
  init_types();
@@ -2534,9 +4113,9 @@ Options
2534
4113
  });
2535
4114
 
2536
4115
  // src/cli.ts
2537
- var import_tool_kit8 = __toESM(require_out2(), 1);
4116
+ var import_tool_kit9 = __toESM(require_out2(), 1);
2538
4117
  import { randomUUID as randomUUID2 } from "node:crypto";
2539
- import * as fs3 from "node:fs";
4118
+ import * as fs2 from "node:fs";
2540
4119
 
2541
4120
  // src/ascendaClient.ts
2542
4121
  var import_tool_kit = __toESM(require_out2(), 1);
@@ -2551,6 +4130,7 @@ var AscendaClient = class {
2551
4130
  eventWriteToken: config.eventWriteToken,
2552
4131
  tokenFilePath: config.tokenFilePath,
2553
4132
  stateFilePath: config.stateFilePath,
4133
+ outboxFilePath: config.outboxFilePath,
2554
4134
  sessionId: config.sessionId,
2555
4135
  workspaceHash: config.workspaceHash,
2556
4136
  projectHash: config.projectHash
@@ -2572,17 +4152,20 @@ var AscendaClient = class {
2572
4152
  init_config();
2573
4153
 
2574
4154
  // src/mapClaudeEvent.ts
2575
- var import_tool_kit6 = __toESM(require_out2(), 1);
4155
+ var import_tool_kit7 = __toESM(require_out2(), 1);
2576
4156
  init_types();
2577
4157
 
2578
4158
  // src/safeExtract.ts
2579
- var import_tool_kit5 = __toESM(require_out2(), 1);
4159
+ var import_tool_kit6 = __toESM(require_out2(), 1);
2580
4160
 
2581
4161
  // src/mapClaudeEvent.ts
2582
4162
  function mapClaudeEvent(hookName, input) {
2583
- return mapEvent(hookName, input).map((event) => ({
4163
+ const events = mapEvent(hookName, input);
4164
+ if (events.length === 0) return events;
4165
+ const branchHash = (0, import_tool_kit7.deriveBranchHashForCwd)((0, import_tool_kit6.getString)(input, ["cwd"]) ?? process.cwd());
4166
+ return events.map((event) => ({
2584
4167
  ...event,
2585
- metadata: { host: CLAUDE_HOST, ...event.metadata }
4168
+ metadata: { host: CLAUDE_HOST, ...branchHash ? { branchHash } : {}, ...event.metadata }
2586
4169
  }));
2587
4170
  }
2588
4171
  function mapEvent(hookName, input) {
@@ -2614,23 +4197,35 @@ function mapEvent(hookName, input) {
2614
4197
  }
2615
4198
  }
2616
4199
  function isNewSessionStart(input) {
2617
- const source = (0, import_tool_kit5.getString)(input, ["source"]);
4200
+ const source = (0, import_tool_kit6.getString)(input, ["source"]);
2618
4201
  return !source || source === "startup" || source === "resume";
2619
4202
  }
2620
4203
  function milestoneInviting(input) {
2621
- if ((0, import_tool_kit5.outcomeForHook)("PostToolUse", input) !== "success") return false;
2622
- const command = (0, import_tool_kit5.getString)(input, ["command"]) ?? (0, import_tool_kit5.getNestedString)(input, [["tool_input", "command"], ["input", "command"], ["parameters", "command"]]);
2623
- return (0, import_tool_kit6.invitesDebrief)((0, import_tool_kit6.classifyWorkMilestone)(command));
4204
+ if ((0, import_tool_kit6.outcomeForHook)("PostToolUse", input) !== "success") return false;
4205
+ const command = (0, import_tool_kit6.getString)(input, ["command"]) ?? (0, import_tool_kit6.getNestedString)(input, [["tool_input", "command"], ["input", "command"], ["parameters", "command"]]);
4206
+ return (0, import_tool_kit7.invitesDebrief)((0, import_tool_kit7.classifyWorkMilestone)(command));
2624
4207
  }
2625
4208
  function mapSessionStart(input) {
2626
4209
  if (!isNewSessionStart(input)) return [];
2627
- return [{ eventType: "create_focus_session", severity: "low", metadata: { activity: "session_started" } }];
4210
+ const modelId = readModelIdentifier(input)?.trim();
4211
+ const modelClass = (0, import_tool_kit7.classifyModelClass)(modelId);
4212
+ return [{
4213
+ eventType: "create_focus_session",
4214
+ severity: "low",
4215
+ metadata: {
4216
+ activity: "session_started",
4217
+ // `classifyModelClass` returns undefined exactly when nothing was
4218
+ // reported (absent, empty, whitespace), so this one guard governs both.
4219
+ ...modelClass !== void 0 && modelId ? { modelClass, modelId } : {}
4220
+ }
4221
+ }];
2628
4222
  }
2629
4223
  function mapUserPromptSubmit(input) {
2630
- const prompt = (0, import_tool_kit5.getString)(input, ["prompt", "userPrompt", "message"]) ?? (0, import_tool_kit5.getNestedString)(input, [["payload", "prompt"], ["payload", "message"]]);
2631
- const events = [{ eventType: "ai_prompt_submitted", severity: "low", metadata: { promptClass: "unknown" } }];
2632
- if ((0, import_tool_kit5.looksLikeCorrection)(prompt)) {
2633
- events.push({ eventType: "ai_correction_prompt", severity: "medium", metadata: { reason: "repeated_reprompting", trigger: "inferred" } });
4224
+ const prompt = (0, import_tool_kit6.getString)(input, ["prompt", "userPrompt", "message"]) ?? (0, import_tool_kit6.getNestedString)(input, [["payload", "prompt"], ["payload", "message"]]);
4225
+ const autonomy = autonomyModeMetadata(input);
4226
+ const events = [{ eventType: "ai_prompt_submitted", severity: "low", metadata: { promptClass: "unknown", ...autonomy } }];
4227
+ if ((0, import_tool_kit6.looksLikeCorrection)(prompt)) {
4228
+ events.push({ eventType: "ai_correction_prompt", severity: "medium", metadata: { reason: "repeated_reprompting", trigger: "inferred", ...autonomy } });
2634
4229
  }
2635
4230
  return events;
2636
4231
  }
@@ -2640,41 +4235,50 @@ function mapPreToolUse(input) {
2640
4235
  function mapPostToolUse(hookName, input) {
2641
4236
  const toolName = getToolName(input);
2642
4237
  const safeToolName = sanitiseToolName(toolName);
2643
- const outcome = (0, import_tool_kit5.outcomeForHook)(hookName, input);
2644
- const durationMs = (0, import_tool_kit5.getNumber)(input, ["duration_ms", "durationMs", "elapsedMs"]) ?? (0, import_tool_kit5.getNestedNumber)(input, [["tool_response", "durationMs"], ["result", "durationMs"]]);
2645
- const command = (0, import_tool_kit5.getString)(input, ["command"]) ?? (0, import_tool_kit5.getNestedString)(input, [["tool_input", "command"], ["input", "command"], ["parameters", "command"]]);
2646
- const commandClass = (0, import_tool_kit6.classifyCommand)(command);
2647
- const gitAction = outcome === "success" ? (0, import_tool_kit6.classifyGitAction)(command) : void 0;
2648
- const milestoneKind = outcome === "success" ? (0, import_tool_kit6.classifyWorkMilestone)(command) : void 0;
4238
+ const outcome = (0, import_tool_kit6.outcomeForHook)(hookName, input);
4239
+ const durationMs = (0, import_tool_kit6.getNumber)(input, ["duration_ms", "durationMs", "elapsedMs"]) ?? (0, import_tool_kit6.getNestedNumber)(input, [["tool_response", "durationMs"], ["result", "durationMs"]]);
4240
+ const command = (0, import_tool_kit6.getString)(input, ["command"]) ?? (0, import_tool_kit6.getNestedString)(input, [["tool_input", "command"], ["input", "command"], ["parameters", "command"]]);
4241
+ const commandClass = (0, import_tool_kit7.classifyCommand)(command);
4242
+ const gitAction = outcome === "success" ? (0, import_tool_kit7.classifyGitAction)(command) : void 0;
4243
+ const milestoneKind = outcome === "success" ? (0, import_tool_kit7.classifyWorkMilestone)(command) : void 0;
4244
+ const autonomy = autonomyModeMetadata(input);
2649
4245
  if (outcome === "cancelled") {
2650
- return [{ eventType: "ai_tool_call_failed", severity: "low", metadata: { toolName: safeToolName, commandClass, outcome, durationBucket: (0, import_tool_kit5.bucketDurationMs)(durationMs), reason: "manual_interrupt" } }];
4246
+ return [{ eventType: "ai_tool_call_failed", severity: "low", metadata: { toolName: safeToolName, commandClass, outcome, durationBucket: (0, import_tool_kit6.bucketDurationMs)(durationMs), reason: "manual_interrupt", ...autonomy } }];
2651
4247
  }
2652
4248
  if (outcome === "failure") {
2653
- if (toolName?.toLowerCase() === "bash" && (0, import_tool_kit6.isVerificationCommand)(commandClass)) {
2654
- return [{ eventType: "compile_error", severity: "medium", metadata: { toolName: safeToolName, commandClass, outcome, durationBucket: (0, import_tool_kit5.bucketDurationMs)(durationMs), reason: "test_failure" } }];
4249
+ if (toolName?.toLowerCase() === "bash" && (0, import_tool_kit7.isVerificationCommand)(commandClass)) {
4250
+ return [{ eventType: "compile_error", severity: "medium", metadata: { toolName: safeToolName, commandClass, outcome, durationBucket: (0, import_tool_kit6.bucketDurationMs)(durationMs), reason: "test_failure", ...autonomy } }];
2655
4251
  }
2656
- return [{ eventType: "ai_tool_call_failed", severity: "medium", metadata: { toolName: safeToolName, commandClass, outcome, durationBucket: (0, import_tool_kit5.bucketDurationMs)(durationMs), reason: "tool_failure" } }];
4252
+ return [{ eventType: "ai_tool_call_failed", severity: "medium", metadata: { toolName: safeToolName, commandClass, outcome, durationBucket: (0, import_tool_kit6.bucketDurationMs)(durationMs), reason: "tool_failure", ...autonomy } }];
2657
4253
  }
2658
4254
  if (isWriteTool(toolName)) {
2659
4255
  const linesChanged = computeLinesChanged(toolName, input);
4256
+ const userModified = (0, import_tool_kit6.getNested)(input, ["tool_response", "userModified"]);
2660
4257
  return [{
2661
4258
  eventType: toolName?.toLowerCase() === "write" ? "ai_file_write" : "ai_file_edit",
2662
4259
  severity: "low",
2663
4260
  metadata: {
2664
4261
  toolName: safeToolName,
2665
4262
  outcome,
2666
- durationBucket: (0, import_tool_kit5.bucketDurationMs)(durationMs),
4263
+ durationBucket: (0, import_tool_kit6.bucketDurationMs)(durationMs),
4264
+ ...autonomy,
4265
+ // `false` is kept, not suppressed: without the negatives there is a
4266
+ // numerator and no denominator, and no correction *rate* can be
4267
+ // computed. Absence still means the payload said nothing — a
4268
+ // non-boolean value is treated as saying nothing rather than guessed
4269
+ // at, so payload drift degrades to "not collected".
4270
+ ...typeof userModified === "boolean" ? { userModified } : {},
2667
4271
  // The boundary C2/the macOS work-self-report card triggers on: at
2668
4272
  // "200+" this is the "substantial accepted change" moment. No
2669
4273
  // second event type exists for this — the bucket on the existing
2670
4274
  // creation event *is* the boundary, deliberately, since the write
2671
4275
  // already happened; there is nothing else to mark.
2672
- ...linesChanged !== void 0 ? { linesChangedBucket: (0, import_tool_kit5.bucketLinesChanged)(linesChanged) } : {}
4276
+ ...linesChanged !== void 0 ? { linesChangedBucket: (0, import_tool_kit6.bucketLinesChanged)(linesChanged) } : {}
2673
4277
  }
2674
4278
  }];
2675
4279
  }
2676
- if (toolName?.toLowerCase() === "bash" && (0, import_tool_kit6.isVerificationCommand)(commandClass)) {
2677
- return [{ eventType: "editor_verification_activity", severity: "low", metadata: { toolName: safeToolName, commandClass, outcome, durationBucket: (0, import_tool_kit5.bucketDurationMs)(durationMs), activity: "ai_test_or_build_run" } }];
4280
+ if (toolName?.toLowerCase() === "bash" && (0, import_tool_kit7.isVerificationCommand)(commandClass)) {
4281
+ return [{ eventType: "editor_verification_activity", severity: "low", metadata: { toolName: safeToolName, commandClass, outcome, durationBucket: (0, import_tool_kit6.bucketDurationMs)(durationMs), activity: "ai_test_or_build_run", ...autonomy } }];
2678
4282
  }
2679
4283
  return [{
2680
4284
  eventType: "ai_tool_call_completed",
@@ -2683,13 +4287,14 @@ function mapPostToolUse(hookName, input) {
2683
4287
  toolName: safeToolName,
2684
4288
  commandClass,
2685
4289
  outcome,
2686
- durationBucket: (0, import_tool_kit5.bucketDurationMs)(durationMs),
4290
+ durationBucket: (0, import_tool_kit6.bucketDurationMs)(durationMs),
4291
+ ...autonomy,
2687
4292
  // The boundary and rework signal both ride this existing event rather
2688
4293
  // than minting a type: the backend already reads `gitAction` off any
2689
4294
  // event, and a commit is not a different *kind* of thing happening, it
2690
4295
  // is a fact about the tool call that just happened.
2691
4296
  ...gitAction !== void 0 ? { gitAction } : {},
2692
- ...(0, import_tool_kit6.isReworkGitAction)(gitAction) ? { activity: "rework_reversion" } : {},
4297
+ ...(0, import_tool_kit7.isReworkGitAction)(gitAction) ? { activity: "rework_reversion" } : {},
2693
4298
  // Same reasoning as `gitAction` above, one grain coarser: a milestone is
2694
4299
  // a fact about the tool call that just happened, not a different kind of
2695
4300
  // event. It rides here so the record carries the work's own rhythm —
@@ -2699,23 +4304,53 @@ function mapPostToolUse(hookName, input) {
2699
4304
  }];
2700
4305
  }
2701
4306
  function mapPreCompact(input) {
2702
- const trigger = (0, import_tool_kit5.getString)(input, ["trigger", "reason", "compactType", "type"]) ?? (0, import_tool_kit5.getNestedString)(input, [["payload", "trigger"], ["payload", "reason"]]);
4307
+ const trigger = (0, import_tool_kit6.getString)(input, ["trigger", "reason", "compactType", "type"]) ?? (0, import_tool_kit6.getNestedString)(input, [["payload", "trigger"], ["payload", "reason"]]);
2703
4308
  const isManual = trigger?.toLowerCase().includes("manual") ?? false;
2704
4309
  return [{ eventType: isManual ? "context_compression_manual" : "context_compression_auto", severity: isManual ? "medium" : "high", metadata: { trigger: isManual ? "manual" : "auto", reason: "context_limit" } }];
2705
4310
  }
2706
4311
  function mapStop(input) {
2707
- const durationMs = (0, import_tool_kit5.getNumber)(input, ["durationMs", "duration_ms", "elapsedMs"]) ?? (0, import_tool_kit5.getNestedNumber)(input, [["session", "durationMs"], ["payload", "durationMs"]]);
2708
- const durationBucket = (0, import_tool_kit5.bucketDurationMs)(durationMs);
4312
+ const durationMs = (0, import_tool_kit6.getNumber)(input, ["durationMs", "duration_ms", "elapsedMs"]) ?? (0, import_tool_kit6.getNestedNumber)(input, [["session", "durationMs"], ["payload", "durationMs"]]);
4313
+ const durationBucket = (0, import_tool_kit6.bucketDurationMs)(durationMs);
2709
4314
  if (durationBucket === "30-60m" || durationBucket === "60m+") {
2710
- return [{ eventType: "agent_loop_long", severity: durationBucket === "60m+" ? "high" : "medium", metadata: { durationBucket, reason: "long_session", trigger: "inferred" } }];
4315
+ return [{ eventType: "agent_loop_long", severity: durationBucket === "60m+" ? "high" : "medium", metadata: { durationBucket, reason: "long_session", trigger: "inferred", ...autonomyModeMetadata(input) } }];
2711
4316
  }
2712
4317
  return [];
2713
4318
  }
4319
+ function autonomyModeMetadata(input) {
4320
+ const raw = readPermissionMode(input);
4321
+ return raw === void 0 ? {} : { autonomyMode: classifyAutonomyMode(raw) };
4322
+ }
4323
+ function readPermissionMode(input) {
4324
+ const candidates = [
4325
+ input["permission_mode"],
4326
+ input["permissionMode"],
4327
+ (0, import_tool_kit6.getNested)(input, ["payload", "permission_mode"])
4328
+ ];
4329
+ for (const value of candidates) {
4330
+ if (value !== void 0 && value !== null) return value;
4331
+ }
4332
+ return void 0;
4333
+ }
4334
+ function classifyAutonomyMode(raw) {
4335
+ if (typeof raw !== "string") return "unknown";
4336
+ return AUTONOMY_BY_PERMISSION_MODE[raw.trim().toLowerCase()] ?? "unknown";
4337
+ }
4338
+ var AUTONOMY_BY_PERMISSION_MODE = {
4339
+ default: "default",
4340
+ plan: "plan",
4341
+ acceptedits: "accept_edits",
4342
+ auto: "auto",
4343
+ dontask: "dont_ask",
4344
+ bypasspermissions: "bypass_permissions"
4345
+ };
4346
+ function readModelIdentifier(input) {
4347
+ return (0, import_tool_kit6.getString)(input, ["model", "model_id", "modelId"]) ?? (0, import_tool_kit6.getNestedString)(input, [["model", "id"], ["model", "display_name"], ["model", "name"], ["payload", "model"]]);
4348
+ }
2714
4349
  function getToolName(input) {
2715
- return (0, import_tool_kit5.getString)(input, ["toolName", "tool_name", "name"]) ?? (0, import_tool_kit5.getNestedString)(input, [["tool", "name"], ["tool_use", "name"], ["payload", "toolName"]]);
4350
+ return (0, import_tool_kit6.getString)(input, ["toolName", "tool_name", "name"]) ?? (0, import_tool_kit6.getNestedString)(input, [["tool", "name"], ["tool_use", "name"], ["payload", "toolName"]]);
2716
4351
  }
2717
4352
  function computeLinesChanged(toolName, input) {
2718
- const toolInput = (0, import_tool_kit5.getNested)(input, ["tool_input"]) ?? (0, import_tool_kit5.getNested)(input, ["input"]) ?? (0, import_tool_kit5.getNested)(input, ["parameters"]);
4353
+ const toolInput = (0, import_tool_kit6.getNested)(input, ["tool_input"]) ?? (0, import_tool_kit6.getNested)(input, ["input"]) ?? (0, import_tool_kit6.getNested)(input, ["parameters"]);
2719
4354
  if (!toolInput || typeof toolInput !== "object") return void 0;
2720
4355
  const record = toolInput;
2721
4356
  switch (toolName?.toLowerCase()) {
@@ -2770,7 +4405,7 @@ async function runPair() {
2770
4405
  const toolType = flagIndex !== -1 ? (process.argv[flagIndex + 1] ?? "").trim() || ASCENDA_TOOL_TYPE : ASCENDA_TOOL_TYPE;
2771
4406
  const existing = process.env.ASCENDA_TOOL_INSTALLATION_ID?.trim();
2772
4407
  const toolInstallationId = existing && existing.includes(":") ? existing : `${toolType}:${randomUUID2()}`;
2773
- const session = await (0, import_tool_kit8.createPairingSession)(apiBaseUrl, toolInstallationId, toolType, toolType === ASCENDA_TOOL_TYPE ? "Claude Code" : toolType);
4408
+ const session = await (0, import_tool_kit9.createPairingSession)(apiBaseUrl, toolInstallationId, toolType, toolType === ASCENDA_TOOL_TYPE ? "Claude Code" : toolType);
2774
4409
  const code = session.deviceCode ?? session.code;
2775
4410
  await writeStdout(
2776
4411
  `
@@ -2784,7 +4419,7 @@ Waiting for confirmation (expires ${session.expiresAt})...
2784
4419
  const deadline = Date.now() + 11 * 60 * 1e3;
2785
4420
  while (Date.now() < deadline) {
2786
4421
  await new Promise((resolve2) => setTimeout(resolve2, 3e3));
2787
- const status = await (0, import_tool_kit8.getPairingStatus)(apiBaseUrl, session.pairingSessionId);
4422
+ const status = await (0, import_tool_kit9.getPairingStatus)(apiBaseUrl, session.pairingSessionId);
2788
4423
  if (status.status === "pending") continue;
2789
4424
  if (status.status !== "paired") {
2790
4425
  process.stderr.write(`Pairing ${status.status}. Run the command again for a fresh code.
@@ -2800,8 +4435,8 @@ Waiting for confirmation (expires ${session.expiresAt})...
2800
4435
  process.exitCode = 1;
2801
4436
  return;
2802
4437
  }
2803
- const tokenFilePath = (0, import_tool_kit8.defaultTokenFilePath)(pairedId);
2804
- (0, import_tool_kit8.persistEventWriteToken)(tokenFilePath, status.eventWriteToken);
4438
+ const tokenFilePath = (0, import_tool_kit9.defaultTokenFilePath)(pairedId);
4439
+ (0, import_tool_kit9.persistEventWriteToken)(tokenFilePath, status.eventWriteToken);
2805
4440
  await writeStdout(
2806
4441
  `Paired. Write token saved to ${tokenFilePath}
2807
4442
 
@@ -2857,24 +4492,31 @@ async function main() {
2857
4492
  await writeStdout(JSON.stringify({
2858
4493
  hookSpecificOutput: { hookEventName: hookName, additionalContext: contextParts.join("\n\n") }
2859
4494
  }));
2860
- if (pending) (0, import_tool_kit8.markFailureNotified)(pending.stateFilePath, pending.state);
4495
+ if (pending) (0, import_tool_kit9.markFailureNotified)(pending.stateFilePath, pending.state);
2861
4496
  }
2862
4497
  await emitLive(hookName, input);
2863
4498
  const mappedEvents = mapClaudeEvent(hookName, input);
2864
4499
  if (!mappedEvents.length) return;
2865
- const workContext = (0, import_tool_kit8.deriveWorkContext)((0, import_tool_kit8.getString)(input, ["cwd"]) ?? process.cwd());
2866
- if (workContext) (0, import_tool_kit8.recordWorkContext)(workContext);
4500
+ const workContext = (0, import_tool_kit9.deriveWorkContext)((0, import_tool_kit9.getString)(input, ["cwd"]) ?? process.cwd());
4501
+ if (workContext) {
4502
+ (0, import_tool_kit9.recordWorkContext)(workContext);
4503
+ (0, import_tool_kit9.recordForgeProjectAlias)(workContext);
4504
+ }
2867
4505
  let config;
2868
4506
  try {
2869
4507
  config = loadConfigFromEnv();
2870
4508
  } catch (error) {
2871
- const logFile = (0, import_tool_kit8.resolveEventLogPath)();
4509
+ if (error instanceof MissingInstallationIdError) journalSkippedSend(error);
4510
+ const logFile = (0, import_tool_kit9.resolveEventLogPath)();
2872
4511
  if (!logFile) throw error;
2873
- for (const event of mappedEvents) logUnsent(logFile, event, workContext);
4512
+ for (const event of mappedEvents) {
4513
+ logUnsent(logFile, event, workContext, (0, import_tool_kit9.getString)(input, ["session_id", "sessionId"]) ?? null);
4514
+ }
2874
4515
  return;
2875
4516
  }
2876
4517
  config.workspaceHash ??= workContext?.workspaceHash ?? null;
2877
4518
  config.projectHash ??= workContext?.projectHash ?? null;
4519
+ config.sessionId ??= (0, import_tool_kit9.getString)(input, ["session_id", "sessionId"]) ?? null;
2878
4520
  const client = new AscendaClient(config);
2879
4521
  for (const event of mappedEvents) {
2880
4522
  const result = await client.send(event);
@@ -2883,28 +4525,33 @@ async function main() {
2883
4525
  return;
2884
4526
  }
2885
4527
  }
4528
+ function journalSkippedSend(error) {
4529
+ (0, import_tool_kit9.recordSendOutcome)(resolveStateFilePath(), (0, import_tool_kit9.unresolvedToolInstallationId)(ASCENDA_TOOL_TYPE), "skipped_no_installation_id", {
4530
+ detail: error.candidates.length === 0 ? "no ASCENDA_TOOL_INSTALLATION_ID, no credentials.json pairing, no claude_code token file" : `no ASCENDA_TOOL_INSTALLATION_ID, no credentials.json pairing, ${error.candidates.length} claude_code token files (${error.candidates.join(", ")})`
4531
+ });
4532
+ }
2886
4533
  function explainRejection(result) {
2887
4534
  if (result === "consent_missing") return "Ascenda telemetry rejected: renew IDE telemetry consent in the Ascenda app.";
2888
4535
  if (result === "auth_failed") return "Ascenda telemetry rejected: event write token invalid or revoked. Re-pair with `npx @ascenda-one/claude-code-hooks pair`.";
2889
- if (result === "transport_error") return "Ascenda telemetry not delivered: the ingest endpoint could not be reached.";
4536
+ if (result === "transport_error") return "Ascenda telemetry not delivered: the ingest endpoint could not be reached; the event is kept in the outbox.";
2890
4537
  return `Ascenda telemetry rejected: ${result}`;
2891
4538
  }
2892
4539
  async function emitLive(hookName, input) {
2893
4540
  const event = hookName === "UserPromptSubmit" ? "prompt_submitted" : hookName === "PreToolUse" ? "tool_call" : hookName === "PreCompact" ? "compaction" : hookName === "PostToolUseFailure" ? "tool_failure" : hookName === "Stop" ? "stop" : void 0;
2894
4541
  if (!event) return;
2895
4542
  try {
2896
- const prompt = event === "prompt_submitted" ? (0, import_tool_kit8.getString)(input, ["prompt", "userPrompt", "message"]) ?? (0, import_tool_kit8.getNestedString)(input, [["payload", "prompt"], ["payload", "message"]]) : void 0;
2897
- const promptSource = event === "prompt_submitted" ? (0, import_tool_kit8.getString)(input, ["promptSource", "prompt_source"]) : void 0;
4543
+ const prompt = event === "prompt_submitted" ? (0, import_tool_kit9.getString)(input, ["prompt", "userPrompt", "message"]) ?? (0, import_tool_kit9.getNestedString)(input, [["payload", "prompt"], ["payload", "message"]]) : void 0;
4544
+ const promptSource = event === "prompt_submitted" ? (0, import_tool_kit9.getString)(input, ["promptSource", "prompt_source"]) : void 0;
2898
4545
  const queued = promptSource === void 0 ? void 0 : promptSource === "queued";
2899
- await (0, import_tool_kit8.emitLiveSignal)({
4546
+ await (0, import_tool_kit9.emitLiveSignal)({
2900
4547
  tool: process.env.ASCENDA_TOOL_TYPE ?? "claude_code",
2901
4548
  // Concurrent sessions must count as separate streams for the X gauge.
2902
4549
  // Without a session id every window collapses into one, so fall back to
2903
4550
  // this process's parent — still per-session in practice, since Claude
2904
4551
  // Code spawns hooks from the session process.
2905
- session: (0, import_tool_kit8.getString)(input, ["session_id", "sessionId"]) ?? process.env.ASCENDA_SESSION_ID ?? `ppid-${process.ppid}`,
4552
+ session: (0, import_tool_kit9.getString)(input, ["session_id", "sessionId"]) ?? process.env.ASCENDA_SESSION_ID ?? `ppid-${process.ppid}`,
2906
4553
  event,
2907
- ...prompt !== void 0 ? { sizeBucket: (0, import_tool_kit8.bucketPromptSize)(prompt) } : {},
4554
+ ...prompt !== void 0 ? { sizeBucket: (0, import_tool_kit9.bucketPromptSize)(prompt) } : {},
2908
4555
  ...queued !== void 0 ? { queued } : {}
2909
4556
  });
2910
4557
  } catch {
@@ -2913,11 +4560,15 @@ async function emitLive(hookName, input) {
2913
4560
  function pendingFailureNotice(hookName) {
2914
4561
  if (hookName !== "SessionStart" && hookName !== "PostToolUse") return void 0;
2915
4562
  if (process.env.ASCENDA_DISABLE_FAILURE_NOTICE === "true") return void 0;
2916
- const rawId = process.env.ASCENDA_TOOL_INSTALLATION_ID?.trim();
2917
- if (!rawId) return void 0;
2918
- const stateFilePath = resolveStateFilePath(normalizeToolInstallationId(rawId));
2919
- const state = (0, import_tool_kit8.readCollectorState)(stateFilePath);
2920
- if (!(0, import_tool_kit8.shouldAnnounceFailure)(state) || !state) return void 0;
4563
+ let toolInstallationId;
4564
+ try {
4565
+ toolInstallationId = resolveToolInstallationId().toolInstallationId;
4566
+ } catch {
4567
+ return void 0;
4568
+ }
4569
+ const stateFilePath = resolveStateFilePath(toolInstallationId);
4570
+ const state = (0, import_tool_kit9.readCollectorState)(stateFilePath);
4571
+ if (!(0, import_tool_kit9.shouldAnnounceFailure)(state) || !state) return void 0;
2921
4572
  const since = state.lastSuccessAt ? `since ${state.lastSuccessAt}` : "and has never succeeded on this machine";
2922
4573
  return {
2923
4574
  text: `Ascenda note: work telemetry has not been reaching Ascenda ${since} (${describeOutcome(state)}). Your work is unaffected and nothing was lost from this session. Run \`npx @ascenda-one/claude-code-hooks doctor\` for details, or \`npx @ascenda-one/claude-code-hooks pair\` to reconnect. This note appears once.`,
@@ -2936,6 +4587,8 @@ function describeOutcome(state) {
2936
4587
  return `the events were refused as invalid${status}`;
2937
4588
  case "transport_error":
2938
4589
  return `the ingest endpoint could not be reached${status}`;
4590
+ case "outbox_discarded":
4591
+ return `the outbox overflowed and ${state.outboxDiscarded?.lastCount ?? "some"} queued events were discarded`;
2939
4592
  default:
2940
4593
  return `last outcome ${state.lastOutcome}${status}`;
2941
4594
  }
@@ -2947,23 +4600,28 @@ function writeStdout(text) {
2947
4600
  }
2948
4601
  async function runDoctor() {
2949
4602
  const lines = ["Ascenda collector doctor", ""];
2950
- const rawId = process.env.ASCENDA_TOOL_INSTALLATION_ID?.trim();
2951
4603
  const apiBaseUrl = (process.env.ASCENDA_API_BASE_URL ?? "https://api.ascenda.one").replace(/\/$/, "");
2952
4604
  lines.push(` API base URL ${apiBaseUrl}`);
2953
- lines.push(` Installation id ${rawId || "(unset \u2014 ASCENDA_TOOL_INSTALLATION_ID is empty)"}`);
2954
- if (!rawId) {
4605
+ let resolved;
4606
+ try {
4607
+ resolved = resolveToolInstallationId();
4608
+ } catch (error) {
4609
+ lines.push(` Installation id (unresolved \u2014 ${error instanceof Error ? error.message : String(error)})`);
4610
+ lines.push(...skippedSendLines(void 0));
2955
4611
  lines.push("", " Not paired on this machine. Run:", " npx @ascenda-one/claude-code-hooks pair");
2956
4612
  await writeStdout(`${lines.join("\n")}
2957
4613
  `);
2958
4614
  return;
2959
4615
  }
2960
- const toolInstallationId = normalizeToolInstallationId(rawId);
2961
- const tokenFilePath = process.env.ASCENDA_EVENT_WRITE_TOKEN_FILE ?? (0, import_tool_kit8.defaultTokenFilePath)(toolInstallationId);
4616
+ const { toolInstallationId } = resolved;
4617
+ lines.push(` Installation id ${toolInstallationId}`);
4618
+ lines.push(` Id source ${describeIdSource(resolved)}`);
4619
+ const tokenFilePath = process.env.ASCENDA_EVENT_WRITE_TOKEN_FILE ?? (0, import_tool_kit9.defaultTokenFilePath)(toolInstallationId);
2962
4620
  lines.push(` Token file ${tokenFilePath}`);
2963
4621
  lines.push(` Token ${describeToken(tokenFilePath)}`);
2964
4622
  const stateFilePath = resolveStateFilePath(toolInstallationId);
2965
4623
  lines.push(` Journal ${stateFilePath}`);
2966
- const state = (0, import_tool_kit8.readCollectorState)(stateFilePath);
4624
+ const state = (0, import_tool_kit9.readCollectorState)(stateFilePath);
2967
4625
  if (!state) {
2968
4626
  lines.push(" Last outcome (no journal yet \u2014 no send attempted since this version was installed)");
2969
4627
  } else {
@@ -2975,6 +4633,8 @@ async function runDoctor() {
2975
4633
  lines.push(` Consecutive failures ${state.consecutiveFailures}`);
2976
4634
  if (state.failingSince) lines.push(` Failing since ${state.failingSince}`);
2977
4635
  }
4636
+ lines.push(...skippedSendLines(stateFilePath));
4637
+ lines.push(...outboxLines(toolInstallationId, state));
2978
4638
  lines.push("", " Live round trip...");
2979
4639
  lines.push(` ${await liveRoundTrip()}`);
2980
4640
  await writeStdout(`${lines.join("\n")}
@@ -2991,27 +4651,84 @@ async function liveRoundTrip() {
2991
4651
  if (result === "accepted") return "OK \u2014 event accepted by the ingest endpoint.";
2992
4652
  return `FAILED \u2014 ${explainRejection(result)}`;
2993
4653
  }
4654
+ function describeIdSource(resolved) {
4655
+ switch (resolved.source) {
4656
+ case "env":
4657
+ return "env (ASCENDA_TOOL_INSTALLATION_ID)";
4658
+ case "credentials":
4659
+ return "credentials file (~/.ascenda/credentials.json)";
4660
+ case "disk":
4661
+ return `disk (token file ${(0, import_tool_kit9.defaultTokenFilePath)(resolved.toolInstallationId)})`;
4662
+ }
4663
+ }
4664
+ function skippedSendLines(alreadyShown) {
4665
+ const stateFilePath = resolveStateFilePath();
4666
+ if (stateFilePath === alreadyShown) return [];
4667
+ const state = (0, import_tool_kit9.readCollectorState)(stateFilePath);
4668
+ if (!state) return [];
4669
+ const since = state.failingSince ? ` since ${state.failingSince}` : "";
4670
+ return [
4671
+ ` Skipped sends ${state.consecutiveFailures}${since} \u2014 no installation id could be resolved (last ${state.lastAttemptAt})`,
4672
+ ...state.detail ? [` Skipped because ${state.detail}`] : [],
4673
+ ` Skipped-send journal ${stateFilePath}`
4674
+ ];
4675
+ }
4676
+ function outboxLines(toolInstallationId, state) {
4677
+ const outboxFilePath = resolveOutboxFilePath(toolInstallationId);
4678
+ const lines = [` Outbox ${outboxFilePath}`];
4679
+ const summary = (0, import_tool_kit9.readOutboxSummary)(outboxFilePath);
4680
+ if (!summary || summary.depth === 0) {
4681
+ lines.push(" Outbox depth 0 (nothing waiting)");
4682
+ } else {
4683
+ const oldest = summary.oldestQueuedAt ? ` \u2014 oldest queued ${summary.oldestQueuedAt} (${describeAge(summary.oldestQueuedAt)} ago)` : "";
4684
+ lines.push(` Outbox depth ${summary.depth} waiting${oldest}`);
4685
+ }
4686
+ if (summary && summary.unreadableLines > 0) {
4687
+ lines.push(` Outbox unreadable ${summary.unreadableLines} line(s) did not parse \u2014 discarded and journaled on the next hook`);
4688
+ }
4689
+ lines.push(` Outbox drain ${(0, import_tool_kit9.outboxDrainEnabled)() ? "on" : "off (queued events are kept and bounded, not sent)"} \u2014 ${import_tool_kit9.OUTBOX_DRAIN_ENV_VAR}`);
4690
+ const discarded = state?.outboxDiscarded;
4691
+ if (discarded) {
4692
+ const reasons = Object.entries(discarded.lastReasons).map(([reason, count]) => `${count} ${reason}`).join(", ");
4693
+ const reach = discarded.lastOldestQueuedAt ? `, reaching back to ${discarded.lastOldestQueuedAt}` : "";
4694
+ lines.push(` Outbox discarded ${discarded.total} total; last ${discarded.lastCount} at ${discarded.lastAt} (${reasons}${reach})`);
4695
+ }
4696
+ return lines;
4697
+ }
4698
+ function describeAge(isoTimestamp) {
4699
+ const ms = Date.now() - Date.parse(isoTimestamp);
4700
+ if (!Number.isFinite(ms) || ms < 0) return "0m";
4701
+ const minutes = Math.floor(ms / 6e4);
4702
+ if (minutes < 60) return `${minutes}m`;
4703
+ const hours = Math.floor(minutes / 60);
4704
+ if (hours < 48) return `${hours}h ${minutes % 60}m`;
4705
+ return `${Math.floor(hours / 24)}d ${hours % 24}h`;
4706
+ }
2994
4707
  function describeToken(tokenFilePath) {
2995
4708
  try {
2996
- if (!fs3.existsSync(tokenFilePath)) {
4709
+ if (!fs2.existsSync(tokenFilePath)) {
2997
4710
  return process.env.ASCENDA_EVENT_WRITE_TOKEN ? "from ASCENDA_EVENT_WRITE_TOKEN (no file)" : "MISSING \u2014 run `pair`";
2998
4711
  }
2999
- const stat = fs3.statSync(tokenFilePath);
4712
+ const stat = fs2.statSync(tokenFilePath);
3000
4713
  const ageDays = Math.floor((Date.now() - stat.mtimeMs) / 864e5);
3001
4714
  return `present, last written ${stat.mtime.toISOString()} (${ageDays}d ago)`;
3002
4715
  } catch (error) {
3003
4716
  return `unreadable \u2014 ${error instanceof Error ? error.message : String(error)}`;
3004
4717
  }
3005
4718
  }
3006
- function logUnsent(logFile, event, workContext) {
3007
- const payload = (0, import_tool_kit8.buildEventPayload)({
4719
+ function logUnsent(logFile, event, workContext, sessionId) {
4720
+ const payload = (0, import_tool_kit9.buildEventPayload)({
3008
4721
  toolInstallationId: `${ASCENDA_TOOL_TYPE}:unpaired`,
3009
4722
  source: "claude_code",
3010
- sessionId: process.env.ASCENDA_SESSION_ID ?? null,
3011
- workspaceHash: envHashOverride("ASCENDA_WORKSPACE_HASH") ?? workContext?.workspaceHash ?? null,
3012
- projectHash: envHashOverride("ASCENDA_PROJECT_HASH") ?? workContext?.projectHash ?? null
4723
+ // The payload's session, same as a delivered row — this log exists so
4724
+ // someone unpaired can see exactly what would be transmitted, and a field
4725
+ // that reads null here but not on the wire would misinform the one person
4726
+ // using it for that.
4727
+ sessionId: envOverride("ASCENDA_SESSION_ID") ?? sessionId,
4728
+ workspaceHash: envOverride("ASCENDA_WORKSPACE_HASH") ?? workContext?.workspaceHash ?? null,
4729
+ projectHash: envOverride("ASCENDA_PROJECT_HASH") ?? workContext?.projectHash ?? null
3013
4730
  }, event);
3014
- (0, import_tool_kit8.appendEventLog)(logFile, { loggedAt: (/* @__PURE__ */ new Date()).toISOString(), delivery: "not_sent", payload });
4731
+ (0, import_tool_kit9.appendEventLog)(logFile, { loggedAt: (/* @__PURE__ */ new Date()).toISOString(), delivery: "not_sent", payload });
3015
4732
  }
3016
4733
  async function readJsonFromStdin() {
3017
4734
  const chunks = [];