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

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"] },
@@ -532,7 +581,7 @@ var require_out = __commonJS({
532
581
  "../packages/tool-contract/out/index.js"(exports) {
533
582
  "use strict";
534
583
  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;
584
+ 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
585
  exports.SEMANTIC_WORK_SIGNAL_EVENT_TYPES = [
537
586
  "approach_churn_detected",
538
587
  "goal_drift_detected",
@@ -546,6 +595,39 @@ var require_out = __commonJS({
546
595
  "review_given",
547
596
  "pull_request_opened"
548
597
  ];
598
+ exports.EVENT_METADATA_FIELDS = [
599
+ "language",
600
+ "fileType",
601
+ "durationBucket",
602
+ "tokenPressureBucket",
603
+ "linesChangedBucket",
604
+ "commandClass",
605
+ "gitAction",
606
+ "milestoneKind",
607
+ "branchHash",
608
+ "autonomyMode",
609
+ "modelClass",
610
+ "modelId",
611
+ "userModified",
612
+ "outcome",
613
+ "trigger",
614
+ "promptClass",
615
+ "reason",
616
+ "afterHours",
617
+ "activity",
618
+ "message",
619
+ "host",
620
+ "toolName",
621
+ "simulated",
622
+ "relatedEventType",
623
+ "skillVersion",
624
+ "taskFingerprint",
625
+ "importKey",
626
+ "extractionId",
627
+ "importSchema"
628
+ ];
629
+ exports.IDEMPOTENCY_KEY_MAX_LENGTH = 128;
630
+ exports.TOOL_EVENT_DELIVERED_STATUSES = ["accepted", "duplicate"];
549
631
  exports.EVENT_WORKLOAD_CATEGORY = {
550
632
  create_focus_session: "creation",
551
633
  ai_prompt_submitted: "creation",
@@ -601,6 +683,98 @@ var require_out = __commonJS({
601
683
  }
602
684
  });
603
685
 
686
+ // ../packages/tool-kit/out/payload.js
687
+ var require_payload = __commonJS({
688
+ "../packages/tool-kit/out/payload.js"(exports) {
689
+ "use strict";
690
+ Object.defineProperty(exports, "__esModule", { value: true });
691
+ exports.mintIdempotencyKey = mintIdempotencyKey;
692
+ exports.getString = getString3;
693
+ exports.getNumber = getNumber2;
694
+ exports.getNested = getNested2;
695
+ exports.getNestedString = getNestedString3;
696
+ exports.getNestedNumber = getNestedNumber2;
697
+ exports.inferOutcome = inferOutcome2;
698
+ exports.outcomeForHook = outcomeForHook2;
699
+ exports.looksLikeCorrection = looksLikeCorrection2;
700
+ var node_crypto_1 = __require("node:crypto");
701
+ var tool_contract_1 = require_out();
702
+ function mintIdempotencyKey() {
703
+ const key = (0, node_crypto_1.randomUUID)();
704
+ if (key.length > tool_contract_1.IDEMPOTENCY_KEY_MAX_LENGTH)
705
+ throw new Error("idempotency key exceeds the wire limit");
706
+ return key;
707
+ }
708
+ function getString3(input, keys) {
709
+ for (const key of keys) {
710
+ const value = input[key];
711
+ if (typeof value === "string" && value.trim())
712
+ return value;
713
+ }
714
+ return void 0;
715
+ }
716
+ function getNumber2(input, keys) {
717
+ for (const key of keys) {
718
+ const value = input[key];
719
+ if (typeof value === "number" && Number.isFinite(value))
720
+ return value;
721
+ }
722
+ return void 0;
723
+ }
724
+ function getNested2(input, path3) {
725
+ let current = input;
726
+ for (const segment of path3) {
727
+ if (!current || typeof current !== "object")
728
+ return void 0;
729
+ current = current[segment];
730
+ }
731
+ return current;
732
+ }
733
+ function getNestedString3(input, paths) {
734
+ for (const path3 of paths) {
735
+ const value = getNested2(input, path3);
736
+ if (typeof value === "string" && value.trim())
737
+ return value;
738
+ }
739
+ return void 0;
740
+ }
741
+ function getNestedNumber2(input, paths) {
742
+ for (const path3 of paths) {
743
+ const value = getNested2(input, path3);
744
+ if (typeof value === "number" && Number.isFinite(value))
745
+ return value;
746
+ }
747
+ return void 0;
748
+ }
749
+ function inferOutcome2(input) {
750
+ const exitCode = getNumber2(input, ["exitCode", "exit_code", "status"]) ?? getNestedNumber2(input, [["tool_response", "exitCode"], ["tool_response", "exit_code"], ["result", "exitCode"], ["result", "exit_code"]]);
751
+ if (typeof exitCode === "number")
752
+ return exitCode === 0 ? "success" : "failure";
753
+ const error = getString3(input, ["error", "errorMessage"]) ?? getNestedString3(input, [["tool_response", "error"], ["result", "error"]]);
754
+ if (error)
755
+ return "failure";
756
+ return "unknown";
757
+ }
758
+ function outcomeForHook2(hookName, input) {
759
+ if (hookName === "PostToolUseFailure") {
760
+ const interrupted = input["is_interrupt"] === true || getNested2(input, ["tool_response", "interrupted"]) === true;
761
+ return interrupted ? "cancelled" : "failure";
762
+ }
763
+ if (hookName === "PostToolUse") {
764
+ if (getNested2(input, ["tool_response", "interrupted"]) === true)
765
+ return "cancelled";
766
+ return "success";
767
+ }
768
+ return "unknown";
769
+ }
770
+ function looksLikeCorrection2(text) {
771
+ if (!text)
772
+ return false;
773
+ 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);
774
+ }
775
+ }
776
+ });
777
+
604
778
  // ../packages/tool-kit/out/eventLog.js
605
779
  var require_eventLog = __commonJS({
606
780
  "../packages/tool-kit/out/eventLog.js"(exports) {
@@ -647,7 +821,7 @@ var require_eventLog = __commonJS({
647
821
  exports.expandUserPath = expandUserPath;
648
822
  exports.resolveEventLogPath = resolveEventLogPath2;
649
823
  exports.appendEventLog = appendEventLog2;
650
- var fs4 = __importStar(__require("fs"));
824
+ var fs3 = __importStar(__require("fs"));
651
825
  var os2 = __importStar(__require("os"));
652
826
  var path3 = __importStar(__require("path"));
653
827
  exports.EVENT_LOG_ENV_VAR = "ASCENDA_EVENT_LOG_FILE";
@@ -669,19 +843,19 @@ var require_eventLog = __commonJS({
669
843
  try {
670
844
  rotateIfLarge(logFilePath);
671
845
  const dir = path3.dirname(logFilePath);
672
- fs4.mkdirSync(dir, { recursive: true, mode: 448 });
673
- fs4.appendFileSync(logFilePath, `${JSON.stringify(entry)}
846
+ fs3.mkdirSync(dir, { recursive: true, mode: 448 });
847
+ fs3.appendFileSync(logFilePath, `${JSON.stringify(entry)}
674
848
  `, { encoding: "utf8", mode: 384 });
675
849
  if (process.platform !== "win32")
676
- fs4.chmodSync(logFilePath, 384);
850
+ fs3.chmodSync(logFilePath, 384);
677
851
  } catch {
678
852
  }
679
853
  }
680
854
  function rotateIfLarge(logFilePath) {
681
855
  try {
682
- if (fs4.statSync(logFilePath).size < MAX_BYTES)
856
+ if (fs3.statSync(logFilePath).size < MAX_BYTES)
683
857
  return;
684
- fs4.renameSync(logFilePath, `${logFilePath}.1`);
858
+ fs3.renameSync(logFilePath, `${logFilePath}.1`);
685
859
  } catch {
686
860
  }
687
861
  }
@@ -701,6 +875,7 @@ var require_http = __commonJS({
701
875
  exports.postToolEvent = postToolEvent;
702
876
  exports.postToolEventsBatch = postToolEventsBatch;
703
877
  exports.parseIngestResponse = parseIngestResponse;
878
+ var tool_contract_1 = require_out();
704
879
  var AscendaApiError2 = class extends Error {
705
880
  status;
706
881
  errorCode;
@@ -743,6 +918,35 @@ var require_http = __commonJS({
743
918
  throw new AscendaApiError2(response.status, void 0, await response.text());
744
919
  return await response.json();
745
920
  }
921
+ function isDeliveredStatus(value) {
922
+ return typeof value === "string" && tool_contract_1.TOOL_EVENT_DELIVERED_STATUSES.includes(value);
923
+ }
924
+ function readSuccessBody(body) {
925
+ let parsed;
926
+ try {
927
+ parsed = JSON.parse(body);
928
+ } catch {
929
+ return { duplicates: 0 };
930
+ }
931
+ if (!parsed || typeof parsed !== "object")
932
+ return { duplicates: 0 };
933
+ const single = parsed.status;
934
+ if (isDeliveredStatus(single))
935
+ return { duplicates: single === "duplicate" ? 1 : 0 };
936
+ const raw = parsed.results;
937
+ if (!Array.isArray(raw))
938
+ return { duplicates: 0 };
939
+ const results = [];
940
+ for (const item of raw) {
941
+ if (!item || typeof item !== "object")
942
+ continue;
943
+ const { index, status, reason } = item;
944
+ if (typeof index !== "number" || typeof status !== "string")
945
+ continue;
946
+ results.push({ index, status, ...typeof reason === "string" ? { reason } : {} });
947
+ }
948
+ return { duplicates: results.filter((item) => item.status === "duplicate").length, results };
949
+ }
746
950
  function isRetryableStatus(status) {
747
951
  return status === 408 || status === 429 || status !== void 0 && status >= 500 && status <= 599;
748
952
  }
@@ -769,8 +973,20 @@ var require_http = __commonJS({
769
973
  }
770
974
  }
771
975
  async function parseIngestResponse(response) {
772
- if (response.ok)
773
- return { result: "accepted", httpStatus: response.status };
976
+ if (response.ok) {
977
+ const outcome = { result: "accepted", httpStatus: response.status };
978
+ let read = { duplicates: 0 };
979
+ try {
980
+ read = readSuccessBody(await response.text());
981
+ } catch {
982
+ read = { duplicates: 0 };
983
+ }
984
+ return {
985
+ ...outcome,
986
+ ...read.duplicates > 0 ? { duplicates: read.duplicates } : {},
987
+ ...read.results !== void 0 ? { results: read.results } : {}
988
+ };
989
+ }
774
990
  const body = await response.text();
775
991
  let errorCode;
776
992
  try {
@@ -835,9 +1051,10 @@ var require_tokenStore = __commonJS({
835
1051
  exports.ascendaHome = ascendaHome3;
836
1052
  exports.defaultTokenFilePath = defaultTokenFilePath4;
837
1053
  exports.persistEventWriteToken = persistEventWriteToken4;
1054
+ exports.listPersistedToolInstallationIds = listPersistedToolInstallationIds2;
838
1055
  exports.readTokenFile = readTokenFile3;
839
1056
  exports.sanitizeFilePart = sanitizeFilePart;
840
- var fs4 = __importStar(__require("fs"));
1057
+ var fs3 = __importStar(__require("fs"));
841
1058
  var os2 = __importStar(__require("os"));
842
1059
  var path3 = __importStar(__require("path"));
843
1060
  function ascendaHome3() {
@@ -848,18 +1065,44 @@ var require_tokenStore = __commonJS({
848
1065
  }
849
1066
  function persistEventWriteToken4(tokenFilePath, token) {
850
1067
  const dir = path3.dirname(tokenFilePath);
851
- fs4.mkdirSync(dir, { recursive: true, mode: 448 });
852
- fs4.writeFileSync(tokenFilePath, token, { encoding: "utf8", mode: 384 });
1068
+ fs3.mkdirSync(dir, { recursive: true, mode: 448 });
1069
+ fs3.writeFileSync(tokenFilePath, token, { encoding: "utf8", mode: 384 });
853
1070
  if (process.platform !== "win32") {
854
- fs4.chmodSync(dir, 448);
855
- fs4.chmodSync(tokenFilePath, 384);
1071
+ fs3.chmodSync(dir, 448);
1072
+ fs3.chmodSync(tokenFilePath, 384);
1073
+ }
1074
+ }
1075
+ function listPersistedToolInstallationIds2(toolType) {
1076
+ const prefix = `${sanitizeFilePart(toolType)}_`;
1077
+ const dir = path3.join(ascendaHome3(), "tokens");
1078
+ let names;
1079
+ try {
1080
+ names = fs3.readdirSync(dir);
1081
+ } catch {
1082
+ return [];
1083
+ }
1084
+ const ids = [];
1085
+ for (const name of names.sort()) {
1086
+ if (!name.startsWith(prefix) || name.length === prefix.length)
1087
+ continue;
1088
+ const file = path3.join(dir, name);
1089
+ try {
1090
+ if (!fs3.statSync(file).isFile())
1091
+ continue;
1092
+ } catch {
1093
+ continue;
1094
+ }
1095
+ if (readTokenFile3(file) === void 0)
1096
+ continue;
1097
+ ids.push(`${toolType}:${name.slice(prefix.length)}`);
856
1098
  }
1099
+ return ids;
857
1100
  }
858
1101
  function readTokenFile3(tokenFilePath) {
859
1102
  try {
860
- if (!fs4.existsSync(tokenFilePath))
1103
+ if (!fs3.existsSync(tokenFilePath))
861
1104
  return void 0;
862
- const value = fs4.readFileSync(tokenFilePath, "utf8").trim();
1105
+ const value = fs3.readFileSync(tokenFilePath, "utf8").trim();
863
1106
  return value || void 0;
864
1107
  } catch {
865
1108
  return void 0;
@@ -914,11 +1157,14 @@ var require_stateStore = __commonJS({
914
1157
  }();
915
1158
  Object.defineProperty(exports, "__esModule", { value: true });
916
1159
  exports.defaultStateFilePath = defaultStateFilePath2;
1160
+ exports.unresolvedToolInstallationId = unresolvedToolInstallationId2;
1161
+ exports.unresolvedStateFilePath = unresolvedStateFilePath2;
917
1162
  exports.readCollectorState = readCollectorState2;
918
- exports.recordSendOutcome = recordSendOutcome;
1163
+ exports.recordSendOutcome = recordSendOutcome2;
1164
+ exports.recordOutboxDiscard = recordOutboxDiscard;
919
1165
  exports.shouldAnnounceFailure = shouldAnnounceFailure2;
920
1166
  exports.markFailureNotified = markFailureNotified2;
921
- var fs4 = __importStar(__require("fs"));
1167
+ var fs3 = __importStar(__require("fs"));
922
1168
  var os2 = __importStar(__require("os"));
923
1169
  var path3 = __importStar(__require("path"));
924
1170
  var tokenStore_1 = require_tokenStore();
@@ -927,11 +1173,17 @@ var require_stateStore = __commonJS({
927
1173
  const base = dir ? dir : path3.join(os2.homedir(), ".ascenda", "state");
928
1174
  return path3.join(base, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.json`);
929
1175
  }
1176
+ function unresolvedToolInstallationId2(toolType) {
1177
+ return `${toolType}:unresolved`;
1178
+ }
1179
+ function unresolvedStateFilePath2(toolType) {
1180
+ return defaultStateFilePath2(unresolvedToolInstallationId2(toolType));
1181
+ }
930
1182
  function readCollectorState2(stateFilePath) {
931
1183
  try {
932
- if (!fs4.existsSync(stateFilePath))
1184
+ if (!fs3.existsSync(stateFilePath))
933
1185
  return void 0;
934
- const raw = fs4.readFileSync(stateFilePath, "utf8").trim();
1186
+ const raw = fs3.readFileSync(stateFilePath, "utf8").trim();
935
1187
  if (!raw)
936
1188
  return void 0;
937
1189
  const parsed = JSON.parse(raw);
@@ -942,7 +1194,7 @@ var require_stateStore = __commonJS({
942
1194
  return void 0;
943
1195
  }
944
1196
  }
945
- function recordSendOutcome(stateFilePath, toolInstallationId, outcome, detail = {}) {
1197
+ function recordSendOutcome2(stateFilePath, toolInstallationId, outcome, detail = {}) {
946
1198
  const now = (/* @__PURE__ */ new Date()).toISOString();
947
1199
  const previous = readCollectorState2(stateFilePath);
948
1200
  const accepted = outcome === "accepted";
@@ -959,7 +1211,28 @@ var require_stateStore = __commonJS({
959
1211
  // the one already open. Carrying `notifiedFailingSince` across a
960
1212
  // continuing episode is what keeps the notice to once per outage.
961
1213
  ...accepted ? {} : { failingSince: previous?.failingSince ?? now },
962
- ...accepted ? {} : previous?.notifiedFailingSince !== void 0 ? { notifiedFailingSince: previous.notifiedFailingSince } : {}
1214
+ ...accepted ? {} : previous?.notifiedFailingSince !== void 0 ? { notifiedFailingSince: previous.notifiedFailingSince } : {},
1215
+ // Cumulative by design: a send outcome, success included, never erases
1216
+ // the record of what the outbox had to throw away.
1217
+ ...previous?.outboxDiscarded !== void 0 ? { outboxDiscarded: previous.outboxDiscarded } : {}
1218
+ };
1219
+ writeStateFile(stateFilePath, next);
1220
+ return next;
1221
+ }
1222
+ function recordOutboxDiscard(stateFilePath, toolInstallationId, discard) {
1223
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1224
+ const previous = readCollectorState2(stateFilePath);
1225
+ const next = {
1226
+ ...previous ?? { lastAttemptAt: now, consecutiveFailures: 0 },
1227
+ toolInstallationId,
1228
+ lastOutcome: "outbox_discarded",
1229
+ outboxDiscarded: {
1230
+ total: (previous?.outboxDiscarded?.total ?? 0) + discard.count,
1231
+ lastAt: now,
1232
+ lastCount: discard.count,
1233
+ lastReasons: discard.reasons,
1234
+ ...discard.oldestQueuedAt !== void 0 ? { lastOldestQueuedAt: discard.oldestQueuedAt } : {}
1235
+ }
963
1236
  };
964
1237
  writeStateFile(stateFilePath, next);
965
1238
  return next;
@@ -978,16 +1251,16 @@ var require_stateStore = __commonJS({
978
1251
  const temporaryPath = `${stateFilePath}.${process.pid}.tmp`;
979
1252
  try {
980
1253
  const dir = path3.dirname(stateFilePath);
981
- fs4.mkdirSync(dir, { recursive: true, mode: 448 });
982
- fs4.writeFileSync(temporaryPath, `${JSON.stringify(state, null, 2)}
1254
+ fs3.mkdirSync(dir, { recursive: true, mode: 448 });
1255
+ fs3.writeFileSync(temporaryPath, `${JSON.stringify(state, null, 2)}
983
1256
  `, { encoding: "utf8", mode: 384 });
984
- fs4.renameSync(temporaryPath, stateFilePath);
1257
+ fs3.renameSync(temporaryPath, stateFilePath);
985
1258
  if (process.platform !== "win32")
986
- fs4.chmodSync(stateFilePath, 384);
1259
+ fs3.chmodSync(stateFilePath, 384);
987
1260
  } catch {
988
1261
  try {
989
- if (fs4.existsSync(temporaryPath))
990
- fs4.unlinkSync(temporaryPath);
1262
+ if (fs3.existsSync(temporaryPath))
1263
+ fs3.unlinkSync(temporaryPath);
991
1264
  } catch {
992
1265
  }
993
1266
  }
@@ -999,19 +1272,241 @@ var require_stateStore = __commonJS({
999
1272
  }
1000
1273
  });
1001
1274
 
1002
- // ../packages/tool-kit/out/eventSender.js
1003
- var require_eventSender = __commonJS({
1004
- "../packages/tool-kit/out/eventSender.js"(exports) {
1275
+ // ../packages/tool-kit/out/outbox.js
1276
+ var require_outbox = __commonJS({
1277
+ "../packages/tool-kit/out/outbox.js"(exports) {
1005
1278
  "use strict";
1006
- Object.defineProperty(exports, "__esModule", { value: true });
1007
- exports.AscendaEventSender = exports.AscendaSemanticEventError = void 0;
1008
- exports.buildEventPayload = buildEventPayload2;
1009
- var afterHours_1 = require_afterHours();
1010
- var tool_contract_1 = require_out();
1011
- var eventLog_1 = require_eventLog();
1012
- var http_1 = require_http();
1279
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
1280
+ if (k2 === void 0) k2 = k;
1281
+ var desc = Object.getOwnPropertyDescriptor(m, k);
1282
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
1283
+ desc = { enumerable: true, get: function() {
1284
+ return m[k];
1285
+ } };
1286
+ }
1287
+ Object.defineProperty(o, k2, desc);
1288
+ } : function(o, m, k, k2) {
1289
+ if (k2 === void 0) k2 = k;
1290
+ o[k2] = m[k];
1291
+ });
1292
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
1293
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
1294
+ } : function(o, v) {
1295
+ o["default"] = v;
1296
+ });
1297
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
1298
+ var ownKeys = function(o) {
1299
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
1300
+ var ar = [];
1301
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
1302
+ return ar;
1303
+ };
1304
+ return ownKeys(o);
1305
+ };
1306
+ return function(mod) {
1307
+ if (mod && mod.__esModule) return mod;
1308
+ var result = {};
1309
+ if (mod != null) {
1310
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
1311
+ }
1312
+ __setModuleDefault(result, mod);
1313
+ return result;
1314
+ };
1315
+ }();
1316
+ Object.defineProperty(exports, "__esModule", { value: true });
1317
+ exports.DEFAULT_OUTBOX_DRAIN_BATCH_SIZE = exports.DEFAULT_OUTBOX_MAX_AGE_MS = exports.DEFAULT_OUTBOX_MAX_ENTRIES = exports.OUTBOX_DRAIN_ENV_VAR = void 0;
1318
+ exports.outboxDrainEnabled = outboxDrainEnabled2;
1319
+ exports.defaultOutboxFilePath = defaultOutboxFilePath2;
1320
+ exports.appendToOutbox = appendToOutbox;
1321
+ exports.readOutboxSummary = readOutboxSummary2;
1322
+ exports.claimOutbox = claimOutbox;
1323
+ exports.enforceOutboxBounds = enforceOutboxBounds;
1324
+ var fs3 = __importStar(__require("fs"));
1325
+ var path3 = __importStar(__require("path"));
1326
+ var stateStore_1 = require_stateStore();
1327
+ var tokenStore_1 = require_tokenStore();
1328
+ exports.OUTBOX_DRAIN_ENV_VAR = "ASCENDA_OUTBOX_DRAIN";
1329
+ exports.DEFAULT_OUTBOX_MAX_ENTRIES = 1e4;
1330
+ exports.DEFAULT_OUTBOX_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1e3;
1331
+ exports.DEFAULT_OUTBOX_DRAIN_BATCH_SIZE = 100;
1332
+ var ORPHANED_CLAIM_AGE_MS = 6e4;
1333
+ var CLAIM_SUFFIX = ".draining";
1334
+ function outboxDrainEnabled2(env = process.env) {
1335
+ const value = env[exports.OUTBOX_DRAIN_ENV_VAR]?.trim().toLowerCase();
1336
+ return value === "1" || value === "true" || value === "yes" || value === "on";
1337
+ }
1338
+ function defaultOutboxFilePath2(toolInstallationId) {
1339
+ const dir = path3.dirname((0, stateStore_1.defaultStateFilePath)(toolInstallationId));
1340
+ return path3.join(dir, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.outbox.jsonl`);
1341
+ }
1342
+ function appendToOutbox(outboxFilePath, payload, now = /* @__PURE__ */ new Date()) {
1343
+ try {
1344
+ const dir = path3.dirname(outboxFilePath);
1345
+ fs3.mkdirSync(dir, { recursive: true, mode: 448 });
1346
+ const entry = { queuedAt: now.toISOString(), payload };
1347
+ fs3.appendFileSync(outboxFilePath, `${JSON.stringify(entry)}
1348
+ `, { encoding: "utf8", mode: 384 });
1349
+ if (process.platform !== "win32")
1350
+ fs3.chmodSync(outboxFilePath, 384);
1351
+ return true;
1352
+ } catch {
1353
+ return false;
1354
+ }
1355
+ }
1356
+ function readOutboxSummary2(outboxFilePath) {
1357
+ const files = [outboxFilePath, ...listClaimFiles(outboxFilePath)].filter((file) => fs3.existsSync(file));
1358
+ if (files.length === 0)
1359
+ return void 0;
1360
+ let depth = 0;
1361
+ let unreadableLines = 0;
1362
+ let oldestQueuedAt;
1363
+ for (const file of files) {
1364
+ const { entries, unreadable } = readEntries(file);
1365
+ depth += entries.length;
1366
+ unreadableLines += unreadable;
1367
+ for (const entry of entries) {
1368
+ if (oldestQueuedAt === void 0 || entry.queuedAt < oldestQueuedAt)
1369
+ oldestQueuedAt = entry.queuedAt;
1370
+ }
1371
+ }
1372
+ return { depth, unreadableLines, ...oldestQueuedAt !== void 0 ? { oldestQueuedAt } : {} };
1373
+ }
1374
+ function claimOutbox(outboxFilePath, now = Date.now()) {
1375
+ const claimPath = `${outboxFilePath}.${process.pid}${CLAIM_SUFFIX}`;
1376
+ const claimed = [];
1377
+ try {
1378
+ fs3.renameSync(outboxFilePath, claimPath);
1379
+ claimed.push(claimPath);
1380
+ } catch {
1381
+ }
1382
+ let orphanIndex = 0;
1383
+ for (const orphan of listClaimFiles(outboxFilePath)) {
1384
+ if (claimed.includes(orphan))
1385
+ continue;
1386
+ try {
1387
+ if (now - fs3.statSync(orphan).mtimeMs < ORPHANED_CLAIM_AGE_MS)
1388
+ continue;
1389
+ const mine = `${claimPath}.${orphanIndex++}`;
1390
+ fs3.renameSync(orphan, mine);
1391
+ claimed.push(mine);
1392
+ } catch {
1393
+ }
1394
+ }
1395
+ if (claimed.length === 0)
1396
+ return void 0;
1397
+ const entries = [];
1398
+ let unreadable = 0;
1399
+ for (const file of claimed) {
1400
+ const read = readEntries(file);
1401
+ entries.push(...read.entries);
1402
+ unreadable += read.unreadable;
1403
+ }
1404
+ entries.sort((a, b) => a.queuedAt < b.queuedAt ? -1 : a.queuedAt > b.queuedAt ? 1 : 0);
1405
+ let released = false;
1406
+ return {
1407
+ entries,
1408
+ unreadable,
1409
+ release(remainder) {
1410
+ if (released)
1411
+ return;
1412
+ released = true;
1413
+ if (remainder.length > 0) {
1414
+ try {
1415
+ fs3.mkdirSync(path3.dirname(outboxFilePath), { recursive: true, mode: 448 });
1416
+ fs3.appendFileSync(outboxFilePath, remainder.map((entry) => `${JSON.stringify(entry)}
1417
+ `).join(""), { encoding: "utf8", mode: 384 });
1418
+ if (process.platform !== "win32")
1419
+ fs3.chmodSync(outboxFilePath, 384);
1420
+ } catch {
1421
+ return;
1422
+ }
1423
+ }
1424
+ for (const file of claimed) {
1425
+ try {
1426
+ fs3.unlinkSync(file);
1427
+ } catch {
1428
+ }
1429
+ }
1430
+ }
1431
+ };
1432
+ }
1433
+ function enforceOutboxBounds(entries, bounds, now = Date.now()) {
1434
+ const reasons = {};
1435
+ let oldestQueuedAt;
1436
+ const cutoff = new Date(now - bounds.maxAgeMs).toISOString();
1437
+ const fresh = [];
1438
+ for (const entry of entries) {
1439
+ if (entry.queuedAt < cutoff) {
1440
+ reasons.age = (reasons.age ?? 0) + 1;
1441
+ if (oldestQueuedAt === void 0 || entry.queuedAt < oldestQueuedAt)
1442
+ oldestQueuedAt = entry.queuedAt;
1443
+ } else {
1444
+ fresh.push(entry);
1445
+ }
1446
+ }
1447
+ const excess = Math.max(0, fresh.length - bounds.maxEntries);
1448
+ if (excess > 0) {
1449
+ reasons.count = excess;
1450
+ const first = fresh[0]?.queuedAt;
1451
+ if (first !== void 0 && (oldestQueuedAt === void 0 || first < oldestQueuedAt))
1452
+ oldestQueuedAt = first;
1453
+ }
1454
+ const kept = excess > 0 ? fresh.slice(excess) : fresh;
1455
+ const count = Object.values(reasons).reduce((sum, n) => sum + (n ?? 0), 0);
1456
+ return { kept, discarded: { count, reasons, ...oldestQueuedAt !== void 0 ? { oldestQueuedAt } : {} } };
1457
+ }
1458
+ function listClaimFiles(outboxFilePath) {
1459
+ const dir = path3.dirname(outboxFilePath);
1460
+ const prefix = `${path3.basename(outboxFilePath)}.`;
1461
+ try {
1462
+ return fs3.readdirSync(dir).filter((name) => name.startsWith(prefix) && name.includes(CLAIM_SUFFIX)).map((name) => path3.join(dir, name)).sort();
1463
+ } catch {
1464
+ return [];
1465
+ }
1466
+ }
1467
+ function readEntries(file) {
1468
+ let raw;
1469
+ try {
1470
+ raw = fs3.readFileSync(file, "utf8");
1471
+ } catch {
1472
+ return { entries: [], unreadable: 0 };
1473
+ }
1474
+ const entries = [];
1475
+ let unreadable = 0;
1476
+ for (const line of raw.split("\n")) {
1477
+ if (!line.trim())
1478
+ continue;
1479
+ try {
1480
+ const parsed = JSON.parse(line);
1481
+ if (!parsed || typeof parsed !== "object" || typeof parsed.queuedAt !== "string" || !parsed.payload || typeof parsed.payload !== "object") {
1482
+ unreadable += 1;
1483
+ continue;
1484
+ }
1485
+ entries.push({ queuedAt: parsed.queuedAt, payload: parsed.payload });
1486
+ } catch {
1487
+ unreadable += 1;
1488
+ }
1489
+ }
1490
+ return { entries, unreadable };
1491
+ }
1492
+ }
1493
+ });
1494
+
1495
+ // ../packages/tool-kit/out/eventSender.js
1496
+ var require_eventSender = __commonJS({
1497
+ "../packages/tool-kit/out/eventSender.js"(exports) {
1498
+ "use strict";
1499
+ Object.defineProperty(exports, "__esModule", { value: true });
1500
+ exports.AscendaEventSender = exports.AscendaSemanticEventError = void 0;
1501
+ exports.buildEventPayload = buildEventPayload2;
1502
+ var afterHours_1 = require_afterHours();
1503
+ var tool_contract_1 = require_out();
1504
+ var eventLog_1 = require_eventLog();
1505
+ var http_1 = require_http();
1506
+ var outbox_1 = require_outbox();
1013
1507
  var tokenStore_1 = require_tokenStore();
1014
1508
  var stateStore_1 = require_stateStore();
1509
+ var payload_1 = require_payload();
1015
1510
  var AscendaSemanticEventError = class extends Error {
1016
1511
  constructor(message) {
1017
1512
  super(message);
@@ -1024,6 +1519,7 @@ var require_eventSender = __commonJS({
1024
1519
  toolInstallationId: identity.toolInstallationId,
1025
1520
  source: identity.source,
1026
1521
  occurredAt: (/* @__PURE__ */ new Date()).toISOString(),
1522
+ idempotencyKey: (0, payload_1.mintIdempotencyKey)(),
1027
1523
  utcOffsetMinutes: (0, afterHours_1.utcOffsetMinutesAt)(/* @__PURE__ */ new Date()),
1028
1524
  sessionId: identity.sessionId ?? void 0,
1029
1525
  workspaceHash: identity.workspaceHash ?? void 0,
@@ -1041,6 +1537,9 @@ var require_eventSender = __commonJS({
1041
1537
  config;
1042
1538
  eventWriteToken;
1043
1539
  lastState;
1540
+ lastDrain;
1541
+ /** One outbox pass per sender, i.e. per hook process. The hook is on the user's critical path. */
1542
+ outboxServiced = false;
1044
1543
  constructor(config) {
1045
1544
  this.config = config;
1046
1545
  this.eventWriteToken = config.eventWriteToken;
@@ -1079,6 +1578,7 @@ var require_eventSender = __commonJS({
1079
1578
  source: this.config.source,
1080
1579
  eventType: mapped.eventType,
1081
1580
  occurredAt: (/* @__PURE__ */ new Date()).toISOString(),
1581
+ idempotencyKey: (0, payload_1.mintIdempotencyKey)(),
1082
1582
  utcOffsetMinutes: (0, afterHours_1.utcOffsetMinutesAt)(/* @__PURE__ */ new Date()),
1083
1583
  severity: "low",
1084
1584
  sessionId: this.config.sessionId ?? void 0,
@@ -1109,6 +1609,7 @@ var require_eventSender = __commonJS({
1109
1609
  source: this.config.source,
1110
1610
  eventType: mapped.eventType,
1111
1611
  occurredAt: (/* @__PURE__ */ new Date()).toISOString(),
1612
+ idempotencyKey: (0, payload_1.mintIdempotencyKey)(),
1112
1613
  utcOffsetMinutes: (0, afterHours_1.utcOffsetMinutesAt)(/* @__PURE__ */ new Date()),
1113
1614
  severity: "low",
1114
1615
  sessionId: this.config.sessionId ?? void 0,
@@ -1127,15 +1628,30 @@ var require_eventSender = __commonJS({
1127
1628
  * deliberate: Claude Code, Codex, the GitHub collector and the MCP server all
1128
1629
  * send through this method, and the defect being fixed showed up in three
1129
1630
  * separate components because each was left to notice its own failures.
1631
+ *
1632
+ * The outbox is serviced first, once per process. If that pass just watched
1633
+ * the ingest door refuse a batch, the live event is not offered to the same
1634
+ * door a second time in the same instant: it inherits the pass's outcome,
1635
+ * and a retryable one puts it straight in the queue. That is what keeps a
1636
+ * hook during an outage to one bounded round trip instead of three.
1130
1637
  */
1131
1638
  async post(payload) {
1132
- const outcome = await this.attempt(payload);
1639
+ const halted = await this.serviceOutbox();
1640
+ let outcome;
1641
+ let queued = false;
1642
+ if (halted) {
1643
+ outcome = halted;
1644
+ queued = this.isRetryable(outcome) && this.enqueue(payload);
1645
+ } else {
1646
+ outcome = await this.attempt(payload);
1647
+ queued = this.isRetryable(outcome) && this.enqueue(payload);
1648
+ }
1133
1649
  this.lastState = (0, stateStore_1.recordSendOutcome)(this.stateFilePath(), this.config.toolInstallationId, outcome.result, {
1134
1650
  httpStatus: outcome.httpStatus,
1135
1651
  errorCode: outcome.errorCode,
1136
- detail: outcome.detail
1652
+ detail: queued ? withNote(outcome.detail, "queued in outbox") : outcome.detail
1137
1653
  });
1138
- this.log(payload, outcome.result);
1654
+ this.log(payload, outcome.result, queued ? "queued" : void 0);
1139
1655
  return outcome.result;
1140
1656
  }
1141
1657
  /**
@@ -1144,6 +1660,15 @@ var require_eventSender = __commonJS({
1144
1660
  * error gets one retry, because the common cases (a restarting instance, a
1145
1661
  * proxy blip, a 429) clear in well under a second and the alternative is
1146
1662
  * losing the event outright.
1663
+ *
1664
+ * Both recoveries resend the same `payload` object, so the `idempotencyKey`
1665
+ * minted at construction is what the server sees on every attempt. That is
1666
+ * what lets a retry of a request the server actually processed (a timeout
1667
+ * after the write, a 502 from a proxy in front of a 200) come back
1668
+ * `duplicate` instead of landing twice. Never rebuild the payload here.
1669
+ *
1670
+ * When the retry fails too, the caller queues the payload: anything longer
1671
+ * than the pause here is the outbox's job, not another in-process wait.
1147
1672
  */
1148
1673
  async attempt(payload) {
1149
1674
  const outcome = await (0, http_1.postToolEvent)(this.config.apiBaseUrl, this.eventWriteToken, payload, this.signal());
@@ -1152,12 +1677,138 @@ var require_eventSender = __commonJS({
1152
1677
  return outcome;
1153
1678
  return (0, http_1.postToolEvent)(this.config.apiBaseUrl, this.eventWriteToken, payload, this.signal());
1154
1679
  }
1155
- if (outcome.result === "transport_error" && (outcome.httpStatus === void 0 || (0, http_1.isRetryableStatus)(outcome.httpStatus))) {
1680
+ if (this.isRetryable(outcome)) {
1156
1681
  await new Promise((resolve2) => setTimeout(resolve2, RETRY_DELAY_MS));
1157
1682
  return (0, http_1.postToolEvent)(this.config.apiBaseUrl, this.eventWriteToken, payload, this.signal());
1158
1683
  }
1159
1684
  return outcome;
1160
1685
  }
1686
+ /** A failure that never reached a verdict. Replaying can change the answer. */
1687
+ isRetryable(outcome) {
1688
+ return outcome.result === "transport_error" && (outcome.httpStatus === void 0 || (0, http_1.isRetryableStatus)(outcome.httpStatus));
1689
+ }
1690
+ /**
1691
+ * Keeps a refused payload for a later drain. Returns whether it is now on
1692
+ * disk; when it is not (read-only home, full disk) the event is lost and the
1693
+ * journal's detail says so instead of implying it was kept.
1694
+ */
1695
+ enqueue(payload) {
1696
+ return (0, outbox_1.appendToOutbox)(this.outboxFilePath(), payload);
1697
+ }
1698
+ /**
1699
+ * One pass over the outbox: claim it, apply the bounds, and — when sending
1700
+ * is enabled — offer one batch, oldest first, to the batch door.
1701
+ *
1702
+ * Entries are deleted on `accepted` or `duplicate`, decided on `status`
1703
+ * alone; `reason` is for a person reading their logs. A per-item `rejected`
1704
+ * is a verdict, and replaying a verdict cannot change it, so those are
1705
+ * discarded and journaled rather than kept forever. A whole-batch
1706
+ * `validation_failed` is the same verdict for every item. Anything else
1707
+ * stops the pass with everything still on disk, and is returned so the live
1708
+ * send can skip a door that just refused.
1709
+ *
1710
+ * Never loops, never backs off, never sends more than one batch: the next
1711
+ * hook invocation is usually seconds away, and a hook sitting in a retry
1712
+ * loop delays the tool call the user is waiting on.
1713
+ */
1714
+ async serviceOutbox() {
1715
+ if (this.outboxServiced)
1716
+ return void 0;
1717
+ this.outboxServiced = true;
1718
+ const sendEnabled = this.config.outboxDrain ?? (0, outbox_1.outboxDrainEnabled)();
1719
+ const claimed = (0, outbox_1.claimOutbox)(this.outboxFilePath());
1720
+ if (!claimed) {
1721
+ this.lastDrain = { found: 0, discarded: 0, delivered: 0, remaining: 0, sendEnabled };
1722
+ return void 0;
1723
+ }
1724
+ const found = claimed.entries.length + claimed.unreadable;
1725
+ const { kept, discarded } = (0, outbox_1.enforceOutboxBounds)(claimed.entries, {
1726
+ maxEntries: this.config.outboxMaxEntries ?? outbox_1.DEFAULT_OUTBOX_MAX_ENTRIES,
1727
+ maxAgeMs: this.config.outboxMaxAgeMs ?? outbox_1.DEFAULT_OUTBOX_MAX_AGE_MS
1728
+ });
1729
+ if (claimed.unreadable > 0) {
1730
+ discarded.count += claimed.unreadable;
1731
+ discarded.reasons.unreadable = claimed.unreadable;
1732
+ }
1733
+ let discardedTotal = this.journalDiscard(discarded);
1734
+ if (!sendEnabled || kept.length === 0) {
1735
+ claimed.release(kept);
1736
+ this.lastDrain = { found, discarded: discardedTotal, delivered: 0, remaining: kept.length, sendEnabled };
1737
+ return void 0;
1738
+ }
1739
+ const batchSize = this.config.outboxDrainBatchSize ?? outbox_1.DEFAULT_OUTBOX_DRAIN_BATCH_SIZE;
1740
+ const batch = kept.slice(0, batchSize);
1741
+ const rest = kept.slice(batchSize);
1742
+ const outcome = await this.attemptBatch(batch.map((entry) => entry.payload));
1743
+ let delivered = [];
1744
+ let rejected = [];
1745
+ let undecided = [];
1746
+ let halted;
1747
+ if (outcome.result === "accepted") {
1748
+ if (outcome.results === void 0) {
1749
+ delivered = batch;
1750
+ } else {
1751
+ const byIndex = new Map(outcome.results.map((item) => [item.index, item.status]));
1752
+ for (const [index, entry] of batch.entries()) {
1753
+ const status = byIndex.get(index);
1754
+ if (status !== void 0 && tool_contract_1.TOOL_EVENT_DELIVERED_STATUSES.includes(status))
1755
+ delivered.push(entry);
1756
+ else if (status === "rejected")
1757
+ rejected.push(entry);
1758
+ else
1759
+ undecided.push(entry);
1760
+ }
1761
+ }
1762
+ } else if (outcome.result === "validation_failed") {
1763
+ rejected = batch;
1764
+ } else {
1765
+ undecided = batch;
1766
+ halted = outcome;
1767
+ }
1768
+ if (rejected.length > 0) {
1769
+ discardedTotal += this.journalDiscard({ count: rejected.length, reasons: { rejected: rejected.length }, oldestQueuedAt: rejected[0]?.queuedAt });
1770
+ }
1771
+ if (!halted) {
1772
+ this.lastState = (0, stateStore_1.recordSendOutcome)(this.stateFilePath(), this.config.toolInstallationId, outcome.result, {
1773
+ httpStatus: outcome.httpStatus,
1774
+ errorCode: outcome.errorCode,
1775
+ detail: withNote(outcome.detail, `outbox drain: ${delivered.length} delivered`)
1776
+ });
1777
+ }
1778
+ for (const entry of delivered)
1779
+ this.log(entry.payload, "accepted", "drained");
1780
+ const remainder = [...undecided, ...rest];
1781
+ claimed.release(remainder);
1782
+ this.lastDrain = {
1783
+ found,
1784
+ discarded: discardedTotal,
1785
+ delivered: delivered.length,
1786
+ remaining: remainder.length,
1787
+ sendEnabled,
1788
+ ...halted ? { halted: halted.result } : {}
1789
+ };
1790
+ return halted;
1791
+ }
1792
+ /** The batch door, with the same single token renewal as the live path and no in-process retry. */
1793
+ async attemptBatch(payloads) {
1794
+ const outcome = await (0, http_1.postToolEventsBatch)(this.config.apiBaseUrl, this.eventWriteToken, payloads, this.signal());
1795
+ if (outcome.result !== "auth_failed")
1796
+ return outcome;
1797
+ if (!await this.renewEventToken())
1798
+ return outcome;
1799
+ return (0, http_1.postToolEventsBatch)(this.config.apiBaseUrl, this.eventWriteToken, payloads, this.signal());
1800
+ }
1801
+ journalDiscard(discard) {
1802
+ if (discard.count === 0)
1803
+ return 0;
1804
+ const reasons = discard.reasons;
1805
+ this.lastState = (0, stateStore_1.recordOutboxDiscard)(this.stateFilePath(), this.config.toolInstallationId, {
1806
+ count: discard.count,
1807
+ reasons,
1808
+ oldestQueuedAt: discard.oldestQueuedAt
1809
+ });
1810
+ return discard.count;
1811
+ }
1161
1812
  /**
1162
1813
  * The state written by the most recent send, so a caller can decide whether
1163
1814
  * to surface a one-time notice without re-reading the journal it just wrote.
@@ -1165,10 +1816,16 @@ var require_eventSender = __commonJS({
1165
1816
  get state() {
1166
1817
  return this.lastState;
1167
1818
  }
1819
+ /** What this sender's one outbox pass did; undefined before the first send. */
1820
+ get drain() {
1821
+ return this.lastDrain;
1822
+ }
1168
1823
  stateFilePath() {
1169
1824
  return this.config.stateFilePath ?? (0, stateStore_1.defaultStateFilePath)(this.config.toolInstallationId);
1170
1825
  }
1171
- /** Never throws: a renewal that errors is a failed renewal, not a failed turn. */
1826
+ outboxFilePath() {
1827
+ return this.config.outboxFilePath ?? (0, outbox_1.defaultOutboxFilePath)(this.config.toolInstallationId);
1828
+ }
1172
1829
  /**
1173
1830
  * Every send path funnels through {@link post}, so semantic and
1174
1831
  * collaboration signals are logged on the same terms as host events — the
@@ -1178,12 +1835,13 @@ var require_eventSender = __commonJS({
1178
1835
  * It is now `transport_error` through the ordinary path, because the
1179
1836
  * transport returns that outcome instead of throwing.
1180
1837
  */
1181
- log(payload, delivery) {
1838
+ log(payload, delivery, outbox) {
1182
1839
  const logFile = this.config.eventLogFile === void 0 ? (0, eventLog_1.resolveEventLogPath)() : this.config.eventLogFile;
1183
1840
  if (!logFile)
1184
1841
  return;
1185
- (0, eventLog_1.appendEventLog)(logFile, { loggedAt: (/* @__PURE__ */ new Date()).toISOString(), delivery, payload });
1842
+ (0, eventLog_1.appendEventLog)(logFile, { loggedAt: (/* @__PURE__ */ new Date()).toISOString(), delivery, payload, ...outbox ? { outbox } : {} });
1186
1843
  }
1844
+ /** Never throws: a renewal that errors is a failed renewal, not a failed turn. */
1187
1845
  async renewEventToken() {
1188
1846
  try {
1189
1847
  const renewed = await (0, http_1.renewToolToken)(this.config.apiBaseUrl, this.eventWriteToken, this.signal());
@@ -1201,6 +1859,9 @@ var require_eventSender = __commonJS({
1201
1859
  }
1202
1860
  };
1203
1861
  exports.AscendaEventSender = AscendaEventSender2;
1862
+ function withNote(detail, note) {
1863
+ return detail ? `${detail} (${note})` : note;
1864
+ }
1204
1865
  }
1205
1866
  });
1206
1867
 
@@ -1250,7 +1911,7 @@ var require_contextRegistry = __commonJS({
1250
1911
  exports.readWorkContextRegistry = readWorkContextRegistry;
1251
1912
  exports.recordWorkContext = recordWorkContext2;
1252
1913
  exports.recordWorkContextAlias = recordWorkContextAlias;
1253
- var fs4 = __importStar(__require("fs"));
1914
+ var fs3 = __importStar(__require("fs"));
1254
1915
  var os2 = __importStar(__require("os"));
1255
1916
  var path3 = __importStar(__require("path"));
1256
1917
  var MAX_PATHS_PER_ENTRY = 8;
@@ -1259,7 +1920,7 @@ var require_contextRegistry = __commonJS({
1259
1920
  }
1260
1921
  function readWorkContextRegistry(registryFilePath = workContextRegistryFilePath()) {
1261
1922
  try {
1262
- const parsed = JSON.parse(fs4.readFileSync(registryFilePath, "utf8"));
1923
+ const parsed = JSON.parse(fs3.readFileSync(registryFilePath, "utf8"));
1263
1924
  if (parsed && parsed.version === 1 && parsed.contexts && typeof parsed.contexts === "object") {
1264
1925
  return parsed;
1265
1926
  }
@@ -1336,13 +1997,276 @@ var require_contextRegistry = __commonJS({
1336
1997
  }
1337
1998
  function writeRegistry(registryFilePath, registry) {
1338
1999
  const dir = path3.dirname(registryFilePath);
1339
- fs4.mkdirSync(dir, { recursive: true, mode: 448 });
2000
+ fs3.mkdirSync(dir, { recursive: true, mode: 448 });
1340
2001
  const tmp = `${registryFilePath}.${process.pid}.tmp`;
1341
- fs4.writeFileSync(tmp, `${JSON.stringify(registry, null, 2)}
2002
+ fs3.writeFileSync(tmp, `${JSON.stringify(registry, null, 2)}
1342
2003
  `, { encoding: "utf8", mode: 384 });
1343
- fs4.renameSync(tmp, registryFilePath);
2004
+ fs3.renameSync(tmp, registryFilePath);
1344
2005
  if (process.platform !== "win32") {
1345
- fs4.chmodSync(registryFilePath, 384);
2006
+ fs3.chmodSync(registryFilePath, 384);
2007
+ }
2008
+ }
2009
+ }
2010
+ });
2011
+
2012
+ // ../packages/tool-kit/out/credentials.js
2013
+ var require_credentials = __commonJS({
2014
+ "../packages/tool-kit/out/credentials.js"(exports) {
2015
+ "use strict";
2016
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
2017
+ if (k2 === void 0) k2 = k;
2018
+ var desc = Object.getOwnPropertyDescriptor(m, k);
2019
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
2020
+ desc = { enumerable: true, get: function() {
2021
+ return m[k];
2022
+ } };
2023
+ }
2024
+ Object.defineProperty(o, k2, desc);
2025
+ } : function(o, m, k, k2) {
2026
+ if (k2 === void 0) k2 = k;
2027
+ o[k2] = m[k];
2028
+ });
2029
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
2030
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
2031
+ } : function(o, v) {
2032
+ o["default"] = v;
2033
+ });
2034
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
2035
+ var ownKeys = function(o) {
2036
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
2037
+ var ar = [];
2038
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
2039
+ return ar;
2040
+ };
2041
+ return ownKeys(o);
2042
+ };
2043
+ return function(mod) {
2044
+ if (mod && mod.__esModule) return mod;
2045
+ var result = {};
2046
+ if (mod != null) {
2047
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
2048
+ }
2049
+ __setModuleDefault(result, mod);
2050
+ return result;
2051
+ };
2052
+ }();
2053
+ Object.defineProperty(exports, "__esModule", { value: true });
2054
+ exports.credentialsFilePath = credentialsFilePath2;
2055
+ exports.readMachineCredentials = readMachineCredentials2;
2056
+ exports.writeMachineCredentials = writeMachineCredentials;
2057
+ exports.writeTopLevelCredentials = writeTopLevelCredentials2;
2058
+ exports.readHostCredentials = readHostCredentials;
2059
+ exports.writeHostCredentials = writeHostCredentials;
2060
+ exports.removeHostCredentials = removeHostCredentials;
2061
+ var fs3 = __importStar(__require("fs"));
2062
+ var path3 = __importStar(__require("path"));
2063
+ var tokenStore_1 = require_tokenStore();
2064
+ function credentialsFilePath2() {
2065
+ return path3.join((0, tokenStore_1.ascendaHome)(), "credentials.json");
2066
+ }
2067
+ function readMachineCredentials2() {
2068
+ try {
2069
+ const raw = fs3.readFileSync(credentialsFilePath2(), "utf8").trim();
2070
+ if (!raw)
2071
+ return void 0;
2072
+ const parsed = JSON.parse(raw);
2073
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
2074
+ return void 0;
2075
+ return parsed;
2076
+ } catch {
2077
+ return void 0;
2078
+ }
2079
+ }
2080
+ function writeMachineCredentials(credentials) {
2081
+ const file = credentialsFilePath2();
2082
+ fs3.mkdirSync(path3.dirname(file), { recursive: true, mode: 448 });
2083
+ fs3.writeFileSync(file, `${JSON.stringify(credentials, null, 2)}
2084
+ `, { encoding: "utf8", mode: 384 });
2085
+ if (process.platform !== "win32") {
2086
+ fs3.chmodSync(path3.dirname(file), 448);
2087
+ fs3.chmodSync(file, 384);
2088
+ }
2089
+ }
2090
+ function writeTopLevelCredentials2(credentials) {
2091
+ const existing = readMachineCredentials2();
2092
+ writeMachineCredentials({ ...credentials, ...existing?.tools ? { tools: existing.tools } : {} });
2093
+ }
2094
+ function readHostCredentials(host) {
2095
+ const entry = readMachineCredentials2()?.tools?.[host];
2096
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
2097
+ return void 0;
2098
+ return entry;
2099
+ }
2100
+ function writeHostCredentials(host, credentials) {
2101
+ const existing = readMachineCredentials2() ?? {};
2102
+ writeMachineCredentials({ ...existing, tools: { ...existing.tools ?? {}, [host]: credentials } });
2103
+ }
2104
+ function removeHostCredentials(host) {
2105
+ const existing = readMachineCredentials2();
2106
+ if (!existing?.tools || !(host in existing.tools))
2107
+ return;
2108
+ const tools = { ...existing.tools };
2109
+ delete tools[host];
2110
+ const next = { ...existing };
2111
+ if (Object.keys(tools).length)
2112
+ next.tools = tools;
2113
+ else
2114
+ delete next.tools;
2115
+ writeMachineCredentials(next);
2116
+ }
2117
+ }
2118
+ });
2119
+
2120
+ // ../packages/tool-kit/out/forgeProject.js
2121
+ var require_forgeProject = __commonJS({
2122
+ "../packages/tool-kit/out/forgeProject.js"(exports) {
2123
+ "use strict";
2124
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
2125
+ if (k2 === void 0) k2 = k;
2126
+ var desc = Object.getOwnPropertyDescriptor(m, k);
2127
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
2128
+ desc = { enumerable: true, get: function() {
2129
+ return m[k];
2130
+ } };
2131
+ }
2132
+ Object.defineProperty(o, k2, desc);
2133
+ } : function(o, m, k, k2) {
2134
+ if (k2 === void 0) k2 = k;
2135
+ o[k2] = m[k];
2136
+ });
2137
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
2138
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
2139
+ } : function(o, v) {
2140
+ o["default"] = v;
2141
+ });
2142
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
2143
+ var ownKeys = function(o) {
2144
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
2145
+ var ar = [];
2146
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
2147
+ return ar;
2148
+ };
2149
+ return ownKeys(o);
2150
+ };
2151
+ return function(mod) {
2152
+ if (mod && mod.__esModule) return mod;
2153
+ var result = {};
2154
+ if (mod != null) {
2155
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
2156
+ }
2157
+ __setModuleDefault(result, mod);
2158
+ return result;
2159
+ };
2160
+ }();
2161
+ Object.defineProperty(exports, "__esModule", { value: true });
2162
+ exports.forgeProjectHash = forgeProjectHash;
2163
+ exports.parseForgeFullName = parseForgeFullName;
2164
+ exports.readForgeFullName = readForgeFullName;
2165
+ exports.forgeFullNameFromConfig = forgeFullNameFromConfig;
2166
+ exports.recordForgeProjectAlias = recordForgeProjectAlias2;
2167
+ var fs3 = __importStar(__require("fs"));
2168
+ var path3 = __importStar(__require("path"));
2169
+ var contextRegistry_1 = require_contextRegistry();
2170
+ function forgeProjectHash(value) {
2171
+ let h = 2166136261;
2172
+ for (let i = 0; i < value.length; i++) {
2173
+ h ^= value.charCodeAt(i);
2174
+ h = Math.imul(h, 16777619) >>> 0;
2175
+ }
2176
+ return h.toString(16).padStart(8, "0");
2177
+ }
2178
+ function parseForgeFullName(remoteUrl) {
2179
+ if (!remoteUrl)
2180
+ return null;
2181
+ const trimmed = remoteUrl.trim();
2182
+ if (!trimmed)
2183
+ return null;
2184
+ const scp = /^(?:[^@/]+@)?([^/:]+):(.+)$/.exec(trimmed);
2185
+ const scheme = /^([a-z][a-z0-9+.-]*):\/\/(?:[^@/]*@)?([^/:]+)(?::\d+)?\/(.+)$/i.exec(trimmed);
2186
+ let host;
2187
+ let repoPath;
2188
+ if (scheme) {
2189
+ host = scheme[2];
2190
+ repoPath = scheme[3];
2191
+ } else if (scp && !/^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed)) {
2192
+ host = scp[1];
2193
+ repoPath = scp[2];
2194
+ } else {
2195
+ return null;
2196
+ }
2197
+ const normalizedHost = host.toLowerCase().replace(/^www\./, "");
2198
+ if (normalizedHost !== "github.com")
2199
+ return null;
2200
+ const segments = repoPath.split("/").filter((segment) => segment.length > 0);
2201
+ if (segments.length < 2)
2202
+ return null;
2203
+ const owner = segments[0];
2204
+ const repo = segments[1].replace(/\.git$/, "");
2205
+ if (!owner || !repo)
2206
+ return null;
2207
+ return `${owner}/${repo}`;
2208
+ }
2209
+ function readForgeFullName(repositoryRoot) {
2210
+ if (!repositoryRoot)
2211
+ return null;
2212
+ let config;
2213
+ try {
2214
+ config = fs3.readFileSync(path3.join(repositoryRoot, ".git", "config"), "utf8");
2215
+ } catch {
2216
+ return null;
2217
+ }
2218
+ return forgeFullNameFromConfig(config);
2219
+ }
2220
+ function forgeFullNameFromConfig(config) {
2221
+ const remotes = /* @__PURE__ */ new Map();
2222
+ let currentRemote = null;
2223
+ for (const rawLine of config.split(/\r?\n/)) {
2224
+ const line = rawLine.trim();
2225
+ if (!line || line.startsWith("#") || line.startsWith(";"))
2226
+ continue;
2227
+ const section = /^\[([^\]]*)\]$/.exec(line);
2228
+ if (section) {
2229
+ const remote = /^remote\s+"(.*)"$/.exec(section[1].trim());
2230
+ currentRemote = remote ? remote[1] : null;
2231
+ continue;
2232
+ }
2233
+ if (!currentRemote)
2234
+ continue;
2235
+ const entry = /^url\s*=\s*(.*)$/.exec(line);
2236
+ if (entry && !remotes.has(currentRemote))
2237
+ remotes.set(currentRemote, entry[1].trim());
2238
+ }
2239
+ const ordered = [
2240
+ ...remotes.has("origin") ? ["origin"] : [],
2241
+ ...remotes.has("upstream") ? ["upstream"] : [],
2242
+ ...[...remotes.keys()].filter((name) => name !== "origin" && name !== "upstream")
2243
+ ];
2244
+ for (const name of ordered) {
2245
+ const fullName = parseForgeFullName(remotes.get(name));
2246
+ if (fullName)
2247
+ return fullName;
2248
+ }
2249
+ return null;
2250
+ }
2251
+ function recordForgeProjectAlias2(context, options) {
2252
+ try {
2253
+ if (!context?.projectHash || !context.projectLabel || !context.projectPath)
2254
+ return false;
2255
+ const fullName = readForgeFullName(context.projectPath);
2256
+ if (!fullName)
2257
+ return false;
2258
+ const variants = [fullName, fullName.toLowerCase()].filter((value, index, all) => all.indexOf(value) === index);
2259
+ let wrote = false;
2260
+ for (const variant of variants) {
2261
+ const hash = forgeProjectHash(variant);
2262
+ if (hash === context.projectHash || hash === context.workspaceHash)
2263
+ continue;
2264
+ if ((0, contextRegistry_1.recordWorkContextAlias)(hash, context.projectLabel, context.projectPath, options))
2265
+ wrote = true;
2266
+ }
2267
+ return wrote;
2268
+ } catch {
2269
+ return false;
1346
2270
  }
1347
2271
  }
1348
2272
  }
@@ -1394,7 +2318,7 @@ var require_salt = __commonJS({
1394
2318
  exports.readOrCreateMachineSalt = readOrCreateMachineSalt;
1395
2319
  exports.hashWithMachineSalt = hashWithMachineSalt;
1396
2320
  var crypto2 = __importStar(__require("crypto"));
1397
- var fs4 = __importStar(__require("fs"));
2321
+ var fs3 = __importStar(__require("fs"));
1398
2322
  var os2 = __importStar(__require("os"));
1399
2323
  var path3 = __importStar(__require("path"));
1400
2324
  function machineSaltFilePath() {
@@ -1406,19 +2330,19 @@ var require_salt = __commonJS({
1406
2330
  if (hit)
1407
2331
  return hit;
1408
2332
  const dir = path3.dirname(saltFilePath);
1409
- fs4.mkdirSync(dir, { recursive: true, mode: 448 });
2333
+ fs3.mkdirSync(dir, { recursive: true, mode: 448 });
1410
2334
  let salt;
1411
2335
  try {
1412
2336
  salt = crypto2.randomBytes(32).toString("hex");
1413
- fs4.writeFileSync(saltFilePath, salt, { encoding: "utf8", mode: 384, flag: "wx" });
2337
+ fs3.writeFileSync(saltFilePath, salt, { encoding: "utf8", mode: 384, flag: "wx" });
1414
2338
  } catch (error) {
1415
2339
  if (error.code !== "EEXIST")
1416
2340
  throw error;
1417
- salt = fs4.readFileSync(saltFilePath, "utf8").trim();
2341
+ salt = fs3.readFileSync(saltFilePath, "utf8").trim();
1418
2342
  }
1419
2343
  if (process.platform !== "win32") {
1420
- fs4.chmodSync(dir, 448);
1421
- fs4.chmodSync(saltFilePath, 384);
2344
+ fs3.chmodSync(dir, 448);
2345
+ fs3.chmodSync(saltFilePath, 384);
1422
2346
  }
1423
2347
  cache.set(saltFilePath, salt);
1424
2348
  return salt;
@@ -1474,7 +2398,11 @@ var require_workContext = __commonJS({
1474
2398
  }();
1475
2399
  Object.defineProperty(exports, "__esModule", { value: true });
1476
2400
  exports.deriveWorkContext = deriveWorkContext2;
1477
- var fs4 = __importStar(__require("fs"));
2401
+ exports.normalizeBranchName = normalizeBranchName;
2402
+ exports.deriveBranchHash = deriveBranchHash;
2403
+ exports.readBranchName = readBranchName;
2404
+ exports.deriveBranchHashForCwd = deriveBranchHashForCwd2;
2405
+ var fs3 = __importStar(__require("fs"));
1478
2406
  var path3 = __importStar(__require("path"));
1479
2407
  var salt_1 = require_salt();
1480
2408
  var MAX_WALK_DEPTH = 64;
@@ -1488,6 +2416,8 @@ var require_workContext = __commonJS({
1488
2416
  } catch {
1489
2417
  roots = null;
1490
2418
  }
2419
+ if (!roots)
2420
+ roots = inferRootsFromPath(startPath);
1491
2421
  const workspacePath = roots?.checkoutRoot ?? startPath;
1492
2422
  const workspaceLabel = basenameOf(workspacePath);
1493
2423
  if (!workspaceLabel)
@@ -1504,21 +2434,24 @@ var require_workContext = __commonJS({
1504
2434
  };
1505
2435
  }
1506
2436
  function resolveRepositoryRoots(startDir) {
1507
- if (!fs4.existsSync(startDir))
2437
+ if (!fs3.existsSync(startDir))
1508
2438
  return null;
1509
2439
  let dir = startDir;
1510
2440
  for (let depth = 0; depth < MAX_WALK_DEPTH; depth++) {
1511
2441
  const dotGit = path3.join(dir, ".git");
1512
2442
  let stat = null;
1513
2443
  try {
1514
- stat = fs4.statSync(dotGit);
2444
+ stat = fs3.statSync(dotGit);
1515
2445
  } catch {
1516
2446
  stat = null;
1517
2447
  }
1518
2448
  if (stat?.isDirectory())
1519
- return { checkoutRoot: dir, canonicalRoot: dir };
1520
- if (stat?.isFile())
1521
- return { checkoutRoot: dir, canonicalRoot: worktreeParentRoot(dotGit, dir) ?? dir };
2449
+ return { checkoutRoot: dir, canonicalRoot: dir, gitDir: dotGit };
2450
+ if (stat?.isFile()) {
2451
+ const gitDir = readGitdirPointer(dotGit, dir);
2452
+ const canonicalRoot = (gitDir ? worktreeParentRoot(gitDir) : null) ?? dir;
2453
+ return { checkoutRoot: dir, canonicalRoot, gitDir };
2454
+ }
1522
2455
  const parent = path3.dirname(dir);
1523
2456
  if (parent === dir)
1524
2457
  return null;
@@ -1526,32 +2459,104 @@ var require_workContext = __commonJS({
1526
2459
  }
1527
2460
  return null;
1528
2461
  }
1529
- function worktreeParentRoot(dotGitFile, containingDir) {
1530
- let gitdir;
2462
+ function readGitdirPointer(dotGitFile, containingDir) {
1531
2463
  try {
1532
- const match = /^gitdir:\s*(.+)\s*$/m.exec(fs4.readFileSync(dotGitFile, "utf8"));
2464
+ const match = /^gitdir:\s*(.+)\s*$/m.exec(fs3.readFileSync(dotGitFile, "utf8"));
1533
2465
  if (!match)
1534
2466
  return null;
1535
- gitdir = match[1].trim();
2467
+ return path3.resolve(containingDir, match[1].trim());
1536
2468
  } catch {
1537
2469
  return null;
1538
2470
  }
1539
- const resolved = path3.resolve(containingDir, gitdir);
2471
+ }
2472
+ function worktreeParentRoot(resolvedGitDir) {
1540
2473
  const marker = `${path3.sep}.git${path3.sep}worktrees${path3.sep}`;
1541
- const idx = resolved.indexOf(marker);
2474
+ const idx = resolvedGitDir.indexOf(marker);
1542
2475
  if (idx === -1)
1543
2476
  return null;
1544
- return resolved.slice(0, idx);
2477
+ return resolvedGitDir.slice(0, idx);
2478
+ }
2479
+ function inferRootsFromPath(startPath) {
2480
+ const sep = startPath.includes("\\") && !startPath.includes("/") ? "\\" : "/";
2481
+ const leading = /^[\\/]/.test(startPath) ? sep : "";
2482
+ const segments = startPath.split(/[\\/]/).filter(Boolean);
2483
+ const join3 = (count) => leading + segments.slice(0, count).join(sep);
2484
+ for (let i = 0; i + 2 < segments.length; i++) {
2485
+ if (segments[i] === ".claude" && segments[i + 1] === "worktrees") {
2486
+ if (i === 0)
2487
+ return null;
2488
+ return { checkoutRoot: join3(i + 3), canonicalRoot: join3(i), gitDir: null };
2489
+ }
2490
+ }
2491
+ for (let i = 0; i + 1 < segments.length; i++) {
2492
+ const folder = segments[i];
2493
+ const suffix = ["-worktrees", "-wt"].find((s) => folder.endsWith(s) && folder.length > s.length);
2494
+ if (!suffix)
2495
+ continue;
2496
+ const repoName = folder.slice(0, -suffix.length);
2497
+ const canonicalRoot = leading + [...segments.slice(0, i), repoName].join(sep);
2498
+ return { checkoutRoot: join3(i + 2), canonicalRoot, gitDir: null };
2499
+ }
2500
+ return null;
2501
+ }
2502
+ function stripTrailingSeparators(value) {
2503
+ let end = value.length;
2504
+ while (end > 1 && (value[end - 1] === "/" || value[end - 1] === "\\"))
2505
+ end--;
2506
+ return value.slice(0, end);
2507
+ }
2508
+ function basenameOf(value) {
2509
+ const segment = value.split(/[\\/]/).filter(Boolean).pop() ?? null;
2510
+ return segment && segment.length > 0 ? segment : null;
2511
+ }
2512
+ var REFS_HEADS_PREFIX = "refs/heads/";
2513
+ function normalizeBranchName(branch) {
2514
+ if (!branch)
2515
+ return null;
2516
+ let name = branch.trim();
2517
+ if (name.startsWith(REFS_HEADS_PREFIX))
2518
+ name = name.slice(REFS_HEADS_PREFIX.length).trim();
2519
+ if (!name || name === "HEAD")
2520
+ return null;
2521
+ return name;
2522
+ }
2523
+ function deriveBranchHash(branch, saltFilePath) {
2524
+ const name = normalizeBranchName(branch);
2525
+ if (!name)
2526
+ return null;
2527
+ try {
2528
+ return (0, salt_1.hashWithMachineSalt)(name, saltFilePath);
2529
+ } catch {
2530
+ return null;
2531
+ }
2532
+ }
2533
+ function readBranchName(cwd) {
2534
+ if (!cwd || !cwd.trim())
2535
+ return null;
2536
+ let gitDir = null;
2537
+ try {
2538
+ gitDir = resolveRepositoryRoots(stripTrailingSeparators(cwd.trim()))?.gitDir ?? null;
2539
+ } catch {
2540
+ gitDir = null;
2541
+ }
2542
+ if (!gitDir)
2543
+ return null;
2544
+ let head;
2545
+ try {
2546
+ head = fs3.readFileSync(path3.join(gitDir, "HEAD"), "utf8").trim();
2547
+ } catch {
2548
+ return null;
2549
+ }
2550
+ const match = /^ref:\s*(.+)$/.exec(head);
2551
+ if (!match)
2552
+ return null;
2553
+ const ref = match[1].trim();
2554
+ if (!ref.startsWith(REFS_HEADS_PREFIX))
2555
+ return null;
2556
+ return normalizeBranchName(ref);
1545
2557
  }
1546
- function stripTrailingSeparators(value) {
1547
- let end = value.length;
1548
- while (end > 1 && (value[end - 1] === "/" || value[end - 1] === "\\"))
1549
- end--;
1550
- return value.slice(0, end);
1551
- }
1552
- function basenameOf(value) {
1553
- const segment = value.split(/[\\/]/).filter(Boolean).pop() ?? null;
1554
- return segment && segment.length > 0 ? segment : null;
2558
+ function deriveBranchHashForCwd2(cwd, saltFilePath) {
2559
+ return deriveBranchHash(readBranchName(cwd), saltFilePath);
1555
2560
  }
1556
2561
  }
1557
2562
  });
@@ -1561,35 +2566,69 @@ var require_hookAdapter = __commonJS({
1561
2566
  "../packages/tool-kit/out/hookAdapter.js"(exports) {
1562
2567
  "use strict";
1563
2568
  Object.defineProperty(exports, "__esModule", { value: true });
1564
- exports.DEFAULT_API_BASE_URL = void 0;
2569
+ exports.MissingInstallationIdError = exports.DEFAULT_API_BASE_URL = void 0;
2570
+ exports.resolveCliAgentInstallationId = resolveCliAgentInstallationId;
1565
2571
  exports.resolveContextHashes = resolveContextHashes;
1566
2572
  exports.loadCliAgentConfig = loadCliAgentConfig;
1567
2573
  exports.deliverHookEvents = deliverHookEvents;
1568
2574
  var contextRegistry_1 = require_contextRegistry();
2575
+ var credentials_1 = require_credentials();
2576
+ var forgeProject_1 = require_forgeProject();
1569
2577
  var eventLog_1 = require_eventLog();
1570
2578
  var eventSender_1 = require_eventSender();
2579
+ var stateStore_1 = require_stateStore();
1571
2580
  var tokenStore_1 = require_tokenStore();
1572
2581
  var workContext_1 = require_workContext();
1573
2582
  exports.DEFAULT_API_BASE_URL = "https://api.ascenda.one";
2583
+ var MissingInstallationIdError2 = class extends Error {
2584
+ /** The token files that were considered — none, or too many to pick from. */
2585
+ candidates;
2586
+ toolType;
2587
+ constructor(toolType, candidates, setupCommand) {
2588
+ 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}`);
2589
+ this.name = "MissingInstallationIdError";
2590
+ this.toolType = toolType;
2591
+ this.candidates = candidates;
2592
+ }
2593
+ };
2594
+ exports.MissingInstallationIdError = MissingInstallationIdError2;
2595
+ function resolveCliAgentInstallationId(toolType, identity = {}) {
2596
+ const fromEnv = process.env.ASCENDA_TOOL_INSTALLATION_ID?.trim();
2597
+ if (fromEnv)
2598
+ return { toolInstallationId: qualify(toolType, fromEnv), source: "env" };
2599
+ const fromCredentials = identity.host ? (0, credentials_1.readHostCredentials)(identity.host)?.toolInstallationId?.trim() : void 0;
2600
+ if (fromCredentials)
2601
+ return { toolInstallationId: qualify(toolType, fromCredentials), source: "credentials" };
2602
+ const candidates = (0, tokenStore_1.listPersistedToolInstallationIds)(toolType);
2603
+ if (candidates.length === 1)
2604
+ return { toolInstallationId: candidates[0], source: "disk" };
2605
+ throw new MissingInstallationIdError2(toolType, candidates, identity.setupCommand ?? defaultSetupCommand(identity.host));
2606
+ }
2607
+ function defaultSetupCommand(host) {
2608
+ return host ? `npx @ascenda-one/${host.replace(/_cli$/, "")}-hooks setup` : "the agent's setup command";
2609
+ }
2610
+ function qualify(toolType, value) {
2611
+ return value.includes(":") ? value : `${toolType}:${value}`;
2612
+ }
1574
2613
  function resolveContextHashes(cwd) {
1575
2614
  const workspaceOverride = process.env.ASCENDA_WORKSPACE_HASH?.trim() || null;
1576
2615
  const projectOverride = process.env.ASCENDA_PROJECT_HASH?.trim() || null;
1577
2616
  if (workspaceOverride && projectOverride)
1578
2617
  return { workspaceHash: workspaceOverride, projectHash: projectOverride };
1579
2618
  const context = (0, workContext_1.deriveWorkContext)(cwd ?? process.cwd());
1580
- if (context)
2619
+ if (context) {
1581
2620
  (0, contextRegistry_1.recordWorkContext)(context);
2621
+ (0, forgeProject_1.recordForgeProjectAlias)(context);
2622
+ }
1582
2623
  return {
1583
2624
  workspaceHash: workspaceOverride ?? context?.workspaceHash ?? null,
1584
2625
  projectHash: projectOverride ?? context?.projectHash ?? null
1585
2626
  };
1586
2627
  }
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()}`;
2628
+ function loadCliAgentConfig(toolType, sessionIdFromHook, cwd, identity = {}) {
2629
+ const credentials = identity.host ? (0, credentials_1.readHostCredentials)(identity.host) : void 0;
2630
+ const apiBaseUrl = (process.env.ASCENDA_API_BASE_URL ?? credentials?.apiBaseUrl ?? exports.DEFAULT_API_BASE_URL).replace(/\/$/, "");
2631
+ const { toolInstallationId } = resolveCliAgentInstallationId(toolType, identity);
1593
2632
  const tokenFilePath = process.env.ASCENDA_EVENT_WRITE_TOKEN_FILE ?? (0, tokenStore_1.defaultTokenFilePath)(toolInstallationId);
1594
2633
  const fileToken = (0, tokenStore_1.readTokenFile)(tokenFilePath);
1595
2634
  const eventWriteToken = fileToken ?? process.env.ASCENDA_EVENT_WRITE_TOKEN;
@@ -1616,8 +2655,10 @@ var require_hookAdapter = __commonJS({
1616
2655
  const notice = options.onNotice ?? ((message) => console.error(message));
1617
2656
  let config;
1618
2657
  try {
1619
- config = loadCliAgentConfig(options.toolType, options.sessionId, options.cwd);
2658
+ config = loadCliAgentConfig(options.toolType, options.sessionId, options.cwd, options);
1620
2659
  } catch (error) {
2660
+ if (error instanceof MissingInstallationIdError2)
2661
+ journalSkippedSend2(options.host, error);
1621
2662
  const logFile = (0, eventLog_1.resolveEventLogPath)();
1622
2663
  if (!logFile)
1623
2664
  throw error;
@@ -1657,13 +2698,19 @@ var require_hookAdapter = __commonJS({
1657
2698
  } else if (result === "auth_failed") {
1658
2699
  notice("Ascenda telemetry paused: connection revoked or expired. Re-pair via an Ascenda IDE extension or pairing-sim.");
1659
2700
  } else if (result === "transport_error") {
1660
- notice("Ascenda telemetry paused: the ingest endpoint could not be reached. Your work is unaffected.");
2701
+ notice("Ascenda telemetry paused: the ingest endpoint could not be reached; the event is kept in the outbox. Your work is unaffected.");
1661
2702
  } else {
1662
2703
  notice(`Ascenda telemetry rejected: ${result}`);
1663
2704
  }
1664
2705
  return;
1665
2706
  }
1666
2707
  }
2708
+ function journalSkippedSend2(host, error) {
2709
+ const who = host ? `${host}: ` : "";
2710
+ (0, stateStore_1.recordSendOutcome)((0, stateStore_1.unresolvedStateFilePath)(error.toolType), (0, stateStore_1.unresolvedToolInstallationId)(error.toolType), "skipped_no_installation_id", {
2711
+ 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(", ")})`
2712
+ });
2713
+ }
1667
2714
  function parsePositiveInt(value) {
1668
2715
  const n = Number(value);
1669
2716
  return Number.isInteger(n) && n > 0 ? n : void 0;
@@ -1671,6 +2718,387 @@ var require_hookAdapter = __commonJS({
1671
2718
  }
1672
2719
  });
1673
2720
 
2721
+ // ../packages/tool-kit/out/cliAgentSetup.js
2722
+ var require_cliAgentSetup = __commonJS({
2723
+ "../packages/tool-kit/out/cliAgentSetup.js"(exports) {
2724
+ "use strict";
2725
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
2726
+ if (k2 === void 0) k2 = k;
2727
+ var desc = Object.getOwnPropertyDescriptor(m, k);
2728
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
2729
+ desc = { enumerable: true, get: function() {
2730
+ return m[k];
2731
+ } };
2732
+ }
2733
+ Object.defineProperty(o, k2, desc);
2734
+ } : function(o, m, k, k2) {
2735
+ if (k2 === void 0) k2 = k;
2736
+ o[k2] = m[k];
2737
+ });
2738
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
2739
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
2740
+ } : function(o, v) {
2741
+ o["default"] = v;
2742
+ });
2743
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
2744
+ var ownKeys = function(o) {
2745
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
2746
+ var ar = [];
2747
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
2748
+ return ar;
2749
+ };
2750
+ return ownKeys(o);
2751
+ };
2752
+ return function(mod) {
2753
+ if (mod && mod.__esModule) return mod;
2754
+ var result = {};
2755
+ if (mod != null) {
2756
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
2757
+ }
2758
+ __setModuleDefault(result, mod);
2759
+ return result;
2760
+ };
2761
+ }();
2762
+ Object.defineProperty(exports, "__esModule", { value: true });
2763
+ exports.isCliAgentManagementCommand = isCliAgentManagementCommand;
2764
+ exports.cliAgentHookBinPath = cliAgentHookBinPath;
2765
+ exports.runCliAgentSetup = runCliAgentSetup;
2766
+ exports.writeHookSettings = writeHookSettings;
2767
+ exports.findStaleHookCommands = findStaleHookCommands2;
2768
+ var crypto2 = __importStar(__require("crypto"));
2769
+ var fs3 = __importStar(__require("fs"));
2770
+ var os2 = __importStar(__require("os"));
2771
+ var path3 = __importStar(__require("path"));
2772
+ var credentials_1 = require_credentials();
2773
+ var hookAdapter_1 = require_hookAdapter();
2774
+ var http_1 = require_http();
2775
+ var tokenStore_1 = require_tokenStore();
2776
+ var MANAGEMENT_COMMANDS2 = /* @__PURE__ */ new Set(["setup", "install", "status", "uninstall", "-h", "--help"]);
2777
+ function isCliAgentManagementCommand(argument) {
2778
+ return argument !== void 0 && MANAGEMENT_COMMANDS2.has(argument);
2779
+ }
2780
+ function cliAgentHookBinPath(binaryName) {
2781
+ return path3.join((0, tokenStore_1.ascendaHome)(), "bin", binaryName);
2782
+ }
2783
+ function usage(spec) {
2784
+ return `${spec.binaryName} setup \u2014 wire ${spec.displayName} to Ascenda telemetry
2785
+
2786
+ npx ${spec.packageName} setup [options]
2787
+ npx ${spec.packageName} status
2788
+ npx ${spec.packageName} uninstall
2789
+
2790
+ Options
2791
+ --api-base-url <url> ingest host (default ${hookAdapter_1.DEFAULT_API_BASE_URL})
2792
+ --local [port] shorthand for the local dev server (default port 4477)
2793
+ --tool-installation-id <id> reuse an existing pairing instead of creating one
2794
+ --token <eventWriteToken> reuse an existing token (stored 0600, never printed)
2795
+ --scope project|user where hooks are registered (default project)
2796
+ --project-dir <path> project root for --scope project (default cwd)
2797
+ --dry-run print what would change, write nothing
2798
+ -h, --help
2799
+ `;
2800
+ }
2801
+ async function runCliAgentSetup(argv, spec) {
2802
+ let options;
2803
+ try {
2804
+ options = parseArgs2(argv, spec);
2805
+ } catch (error) {
2806
+ console.error(error instanceof Error ? error.message : String(error));
2807
+ return 1;
2808
+ }
2809
+ if (options.action === "help") {
2810
+ console.log(usage(spec));
2811
+ return 0;
2812
+ }
2813
+ if (options.action === "status")
2814
+ return printStatus2(options, spec);
2815
+ if (options.action === "uninstall")
2816
+ return uninstall2(options, spec);
2817
+ const apiBaseUrl = (options.apiBaseUrl ?? (0, credentials_1.readHostCredentials)(spec.host)?.apiBaseUrl ?? hookAdapter_1.DEFAULT_API_BASE_URL).replace(/\/$/, "");
2818
+ console.log(`Ascenda setup for ${spec.displayName} \u2014 ${apiBaseUrl}`);
2819
+ const identity = await resolveIdentity2(apiBaseUrl, options, spec);
2820
+ if (!identity)
2821
+ return 1;
2822
+ console.log(` pairing ${identity.toolInstallationId}${identity.paired ? " (new)" : " (existing)"}`);
2823
+ const binary = installBinary2(spec, options.dryRun);
2824
+ console.log(` hook binary ${binary}`);
2825
+ if (!options.dryRun) {
2826
+ (0, credentials_1.writeHostCredentials)(spec.host, { apiBaseUrl, toolInstallationId: identity.toolInstallationId, pairedAt: (/* @__PURE__ */ new Date()).toISOString() });
2827
+ }
2828
+ console.log(` credentials ${(0, credentials_1.credentialsFilePath)()} (tools.${spec.host})`);
2829
+ const settingsFile = spec.settings.settingsPath(options.scope, options.projectDir);
2830
+ const written = writeHookSettings(settingsFile, binary, spec, options.dryRun);
2831
+ if (written === null)
2832
+ return 1;
2833
+ console.log(` hooks ${settingsFile} (${spec.hookEvents.length} events${written ? "" : ", already current"})`);
2834
+ if (options.dryRun) {
2835
+ console.log("\nDry run \u2014 nothing was written.");
2836
+ return 0;
2837
+ }
2838
+ console.log(`
2839
+ Done. ${spec.restartHint}`);
2840
+ console.log(`Check anytime: npx ${spec.packageName} status`);
2841
+ return 0;
2842
+ }
2843
+ function parseArgs2(argv, spec) {
2844
+ const options = {
2845
+ scope: "project",
2846
+ projectDir: process.cwd(),
2847
+ dryRun: false,
2848
+ action: "install"
2849
+ };
2850
+ for (let i = 0; i < argv.length; i++) {
2851
+ const arg = argv[i];
2852
+ const next = () => {
2853
+ const value = argv[++i];
2854
+ if (value === void 0)
2855
+ throw new Error(`${arg} needs a value`);
2856
+ return value;
2857
+ };
2858
+ switch (arg) {
2859
+ case "setup":
2860
+ case "install":
2861
+ options.action = "install";
2862
+ break;
2863
+ case "status":
2864
+ options.action = "status";
2865
+ break;
2866
+ case "uninstall":
2867
+ options.action = "uninstall";
2868
+ break;
2869
+ case "--api-base-url":
2870
+ options.apiBaseUrl = next();
2871
+ break;
2872
+ case "--local": {
2873
+ const peek = argv[i + 1];
2874
+ const port = peek && /^\d+$/.test(peek) ? argv[++i] : "4477";
2875
+ options.apiBaseUrl = `http://localhost:${port}`;
2876
+ break;
2877
+ }
2878
+ case "--tool-installation-id":
2879
+ options.toolInstallationId = next();
2880
+ break;
2881
+ case "--token":
2882
+ options.token = next();
2883
+ break;
2884
+ case "--scope": {
2885
+ const value = next();
2886
+ if (value !== "project" && value !== "user")
2887
+ throw new Error(`--scope must be project or user, got ${value}`);
2888
+ options.scope = value;
2889
+ break;
2890
+ }
2891
+ case "--project-dir":
2892
+ options.projectDir = path3.resolve(next());
2893
+ break;
2894
+ case "--dry-run":
2895
+ options.dryRun = true;
2896
+ break;
2897
+ case "-h":
2898
+ case "--help":
2899
+ options.action = "help";
2900
+ break;
2901
+ default:
2902
+ throw new Error(`unknown argument: ${arg}
2903
+
2904
+ ${usage(spec)}`);
2905
+ }
2906
+ }
2907
+ return options;
2908
+ }
2909
+ async function resolveIdentity2(apiBaseUrl, options, spec) {
2910
+ const existingId = options.toolInstallationId ?? (0, credentials_1.readHostCredentials)(spec.host)?.toolInstallationId;
2911
+ if (existingId && options.token) {
2912
+ if (!options.dryRun)
2913
+ (0, tokenStore_1.persistEventWriteToken)((0, tokenStore_1.defaultTokenFilePath)(existingId), options.token);
2914
+ return { toolInstallationId: existingId, paired: false };
2915
+ }
2916
+ if (existingId && (0, tokenStore_1.readTokenFile)((0, tokenStore_1.defaultTokenFilePath)(existingId))) {
2917
+ return { toolInstallationId: existingId, paired: false };
2918
+ }
2919
+ if (options.dryRun) {
2920
+ return { toolInstallationId: existingId ?? `${spec.toolType}:<paired at run time>`, paired: false };
2921
+ }
2922
+ const toolInstallationId = existingId ?? `${spec.toolType}:${crypto2.randomUUID()}`;
2923
+ let session;
2924
+ try {
2925
+ session = await (0, http_1.createPairingSession)(apiBaseUrl, toolInstallationId, spec.toolType, `${spec.displayName} on ${os2.hostname()}`);
2926
+ } catch (error) {
2927
+ console.error(`
2928
+ Could not reach ${apiBaseUrl} to pair: ${error instanceof Error ? error.message : String(error)}`);
2929
+ console.error("Start the local dev server and use --local, or pass --api-base-url for your backend.");
2930
+ return void 0;
2931
+ }
2932
+ const token = await pollForToken2(apiBaseUrl, session.pairingSessionId, session.code, session.expiresAt);
2933
+ if (!token)
2934
+ return void 0;
2935
+ (0, tokenStore_1.persistEventWriteToken)((0, tokenStore_1.defaultTokenFilePath)(toolInstallationId), token);
2936
+ return { toolInstallationId, paired: true };
2937
+ }
2938
+ async function pollForToken2(apiBaseUrl, pairingSessionId, code, expiresAt) {
2939
+ const deadline = Math.min(Date.parse(expiresAt) || Date.now() + 3e5, Date.now() + 3e5);
2940
+ let announced = false;
2941
+ while (Date.now() < deadline) {
2942
+ const status = await (0, http_1.getPairingStatus)(apiBaseUrl, pairingSessionId);
2943
+ if (status.status === "paired" && status.eventWriteToken)
2944
+ return status.eventWriteToken;
2945
+ if (status.status === "expired" || status.status === "cancelled") {
2946
+ console.error(`
2947
+ Pairing ${status.status}. Run setup again.`);
2948
+ return void 0;
2949
+ }
2950
+ if (!announced) {
2951
+ console.log(`
2952
+ Confirm in the Ascenda app \u2014 code ${code}`);
2953
+ console.log(" Waiting...");
2954
+ announced = true;
2955
+ }
2956
+ await new Promise((resolve2) => setTimeout(resolve2, 2e3));
2957
+ }
2958
+ console.error("\nPairing timed out. Run setup again.");
2959
+ return void 0;
2960
+ }
2961
+ function installBinary2(spec, dryRun) {
2962
+ const target = cliAgentHookBinPath(spec.binaryName);
2963
+ if (dryRun)
2964
+ return target;
2965
+ const source = process.argv[1];
2966
+ fs3.mkdirSync(path3.dirname(target), { recursive: true });
2967
+ if (path3.resolve(source) !== path3.resolve(target)) {
2968
+ fs3.copyFileSync(source, target);
2969
+ }
2970
+ if (process.platform !== "win32")
2971
+ fs3.chmodSync(target, 493);
2972
+ return target;
2973
+ }
2974
+ function writeHookSettings(settingsFile, binary, spec, dryRun) {
2975
+ let settings = { ...spec.settings.scaffold ?? {} };
2976
+ const exists = fs3.existsSync(settingsFile);
2977
+ if (exists) {
2978
+ const raw = fs3.readFileSync(settingsFile, "utf8").trim();
2979
+ if (raw) {
2980
+ try {
2981
+ settings = JSON.parse(raw);
2982
+ } catch {
2983
+ console.error(`
2984
+ ${settingsFile} is not valid JSON. Fix or move it, then run setup again.`);
2985
+ return null;
2986
+ }
2987
+ }
2988
+ }
2989
+ const command = hookCommand2(binary);
2990
+ const hooks = { ...settings.hooks ?? {} };
2991
+ for (const event of spec.hookEvents) {
2992
+ const kept = (hooks[event] ?? []).filter((entry) => !isOurs2(entry, spec));
2993
+ hooks[event] = [...kept, spec.settings.entry(command, event)];
2994
+ }
2995
+ const updated = { ...settings, hooks };
2996
+ const serialised = `${JSON.stringify(updated, null, 2)}
2997
+ `;
2998
+ if (exists && fs3.readFileSync(settingsFile, "utf8") === serialised)
2999
+ return false;
3000
+ if (dryRun) {
3001
+ console.log(`
3002
+ --- ${settingsFile} (dry run) ---
3003
+ ${serialised}`);
3004
+ return true;
3005
+ }
3006
+ if (exists)
3007
+ fs3.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
3008
+ fs3.mkdirSync(path3.dirname(settingsFile), { recursive: true });
3009
+ fs3.writeFileSync(settingsFile, serialised, "utf8");
3010
+ return true;
3011
+ }
3012
+ function hookCommand2(binary) {
3013
+ return `"${process.execPath}" "${binary}"`;
3014
+ }
3015
+ function isOurs2(entry, spec) {
3016
+ const command = spec.settings.commandOf(entry);
3017
+ return typeof command === "string" && command.includes(spec.binaryName);
3018
+ }
3019
+ function findStaleHookCommands2(settings, binary, spec) {
3020
+ const stale = /* @__PURE__ */ new Set();
3021
+ for (const entries of Object.values(settings.hooks ?? {})) {
3022
+ for (const entry of entries ?? []) {
3023
+ const command = spec.settings.commandOf(entry);
3024
+ if (typeof command !== "string")
3025
+ continue;
3026
+ if (!/ascenda/i.test(command) || command.includes(binary))
3027
+ continue;
3028
+ stale.add(command);
3029
+ }
3030
+ }
3031
+ return [...stale];
3032
+ }
3033
+ function readSettings(settingsFile) {
3034
+ try {
3035
+ return JSON.parse(fs3.readFileSync(settingsFile, "utf8"));
3036
+ } catch {
3037
+ return {};
3038
+ }
3039
+ }
3040
+ function printStatus2(options, spec) {
3041
+ const credentials = (0, credentials_1.readHostCredentials)(spec.host);
3042
+ const settingsFile = spec.settings.settingsPath(options.scope, options.projectDir);
3043
+ const binary = cliAgentHookBinPath(spec.binaryName);
3044
+ const tokenFile = credentials?.toolInstallationId ? (0, tokenStore_1.defaultTokenFilePath)(credentials.toolInstallationId) : void 0;
3045
+ const settings = readSettings(settingsFile);
3046
+ const registered = spec.hookEvents.filter((event) => (settings.hooks?.[event] ?? []).some((entry) => isOurs2(entry, spec))).length;
3047
+ const stale = findStaleHookCommands2(settings, binary, spec);
3048
+ console.log(`api base url ${credentials?.apiBaseUrl ?? "\u2014 not configured"}`);
3049
+ console.log(`pairing ${credentials?.toolInstallationId ?? "\u2014 not paired"}`);
3050
+ console.log(`token ${tokenFile && (0, tokenStore_1.readTokenFile)(tokenFile) ? "present" : "\u2014 missing"}`);
3051
+ console.log(`hook binary ${fs3.existsSync(binary) ? binary : "\u2014 not installed"}`);
3052
+ console.log(`hooks ${registered}/${spec.hookEvents.length} registered in ${settingsFile}`);
3053
+ if (stale.length) {
3054
+ console.log(`stale hooks ${stale.length} not pointing at the installed binary \u2014 each one fails silently per event:`);
3055
+ for (const command of stale)
3056
+ console.log(` ${command}`);
3057
+ console.log(` Remove them from ${settingsFile} by hand; setup cannot tell them from a hook you wrote.`);
3058
+ }
3059
+ const healthy = credentials?.toolInstallationId && registered === spec.hookEvents.length && fs3.existsSync(binary) && !stale.length;
3060
+ return healthy ? 0 : 1;
3061
+ }
3062
+ function uninstall2(options, spec) {
3063
+ const settingsFile = spec.settings.settingsPath(options.scope, options.projectDir);
3064
+ if (fs3.existsSync(settingsFile)) {
3065
+ try {
3066
+ const settings = JSON.parse(fs3.readFileSync(settingsFile, "utf8"));
3067
+ const hooks = { ...settings.hooks ?? {} };
3068
+ for (const event of Object.keys(hooks)) {
3069
+ const kept = hooks[event].filter((entry) => !isOurs2(entry, spec));
3070
+ if (kept.length)
3071
+ hooks[event] = kept;
3072
+ else
3073
+ delete hooks[event];
3074
+ }
3075
+ const updated = { ...settings, hooks };
3076
+ if (!Object.keys(hooks).length)
3077
+ delete updated.hooks;
3078
+ fs3.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
3079
+ fs3.writeFileSync(settingsFile, `${JSON.stringify(updated, null, 2)}
3080
+ `, "utf8");
3081
+ console.log(`hooks removed from ${settingsFile}`);
3082
+ } catch {
3083
+ console.error(`could not parse ${settingsFile} \u2014 remove the ascenda hook entries by hand`);
3084
+ return 1;
3085
+ }
3086
+ }
3087
+ const binary = cliAgentHookBinPath(spec.binaryName);
3088
+ if (fs3.existsSync(binary)) {
3089
+ fs3.rmSync(binary);
3090
+ console.log(`removed ${binary}`);
3091
+ }
3092
+ if ((0, credentials_1.readHostCredentials)(spec.host)) {
3093
+ (0, credentials_1.removeHostCredentials)(spec.host);
3094
+ console.log(`removed tools.${spec.host} from ${(0, credentials_1.credentialsFilePath)()}`);
3095
+ }
3096
+ console.log(`tokens left in ${path3.join((0, tokenStore_1.ascendaHome)(), "tokens")} \u2014 revoke in the Ascenda app to invalidate them`);
3097
+ return 0;
3098
+ }
3099
+ }
3100
+ });
3101
+
1674
3102
  // ../packages/tool-kit/out/turnState.js
1675
3103
  var require_turnState = __commonJS({
1676
3104
  "../packages/tool-kit/out/turnState.js"(exports) {
@@ -1715,7 +3143,7 @@ var require_turnState = __commonJS({
1715
3143
  Object.defineProperty(exports, "__esModule", { value: true });
1716
3144
  exports.recordTurnStart = recordTurnStart;
1717
3145
  exports.consumeTurnDurationMs = consumeTurnDurationMs;
1718
- var fs4 = __importStar(__require("fs"));
3146
+ var fs3 = __importStar(__require("fs"));
1719
3147
  var os2 = __importStar(__require("os"));
1720
3148
  var path3 = __importStar(__require("path"));
1721
3149
  var stateDir = () => process.env.ASCENDA_STATE_DIR ?? path3.join(os2.homedir(), ".ascenda", "state");
@@ -1729,8 +3157,8 @@ var require_turnState = __commonJS({
1729
3157
  if (!sessionId)
1730
3158
  return;
1731
3159
  try {
1732
- fs4.mkdirSync(stateDir(), { recursive: true });
1733
- fs4.writeFileSync(turnFile(agent, sessionId), String(now), { encoding: "utf8", mode: 384 });
3160
+ fs3.mkdirSync(stateDir(), { recursive: true });
3161
+ fs3.writeFileSync(turnFile(agent, sessionId), String(now), { encoding: "utf8", mode: 384 });
1734
3162
  } catch {
1735
3163
  }
1736
3164
  }
@@ -1739,8 +3167,8 @@ var require_turnState = __commonJS({
1739
3167
  return void 0;
1740
3168
  const file = turnFile(agent, sessionId);
1741
3169
  try {
1742
- const started = Number(fs4.readFileSync(file, "utf8").trim());
1743
- fs4.rmSync(file, { force: true });
3170
+ const started = Number(fs3.readFileSync(file, "utf8").trim());
3171
+ fs3.rmSync(file, { force: true });
1744
3172
  if (!Number.isFinite(started) || started <= 0 || started > now)
1745
3173
  return void 0;
1746
3174
  return now - started;
@@ -1797,7 +3225,7 @@ var require_liveBus = __commonJS({
1797
3225
  exports.liveBusSocketPath = liveBusSocketPath;
1798
3226
  exports.bucketPromptSize = bucketPromptSize2;
1799
3227
  exports.emitLiveSignal = emitLiveSignal2;
1800
- var fs4 = __importStar(__require("fs"));
3228
+ var fs3 = __importStar(__require("fs"));
1801
3229
  var net = __importStar(__require("net"));
1802
3230
  var os2 = __importStar(__require("os"));
1803
3231
  var path3 = __importStar(__require("path"));
@@ -1819,7 +3247,7 @@ var require_liveBus = __commonJS({
1819
3247
  const candidates = liveBusSocketCandidates();
1820
3248
  for (const candidate of candidates) {
1821
3249
  try {
1822
- if (fs4.statSync(candidate).isSocket())
3250
+ if (fs3.statSync(candidate).isSocket())
1823
3251
  return candidate;
1824
3252
  } catch {
1825
3253
  }
@@ -1884,8 +3312,9 @@ var require_out2 = __commonJS({
1884
3312
  "../packages/tool-kit/out/index.js"(exports) {
1885
3313
  "use strict";
1886
3314
  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;
3315
+ 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;
3316
+ 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;
3317
+ exports.isRetryableStatus = exports.parseIngestResponse = exports.postToolEventsBatch = void 0;
1889
3318
  var commandClassifier_1 = require_commandClassifier();
1890
3319
  Object.defineProperty(exports, "classifyCommand", { enumerable: true, get: function() {
1891
3320
  return commandClassifier_1.classifyCommand;
@@ -1907,6 +3336,14 @@ var require_out2 = __commonJS({
1907
3336
  Object.defineProperty(exports, "invitesDebrief", { enumerable: true, get: function() {
1908
3337
  return workMilestoneClassifier_1.invitesDebrief;
1909
3338
  } });
3339
+ var autonomyBand_1 = require_autonomyBand();
3340
+ Object.defineProperty(exports, "autonomyBand", { enumerable: true, get: function() {
3341
+ return autonomyBand_1.autonomyBand;
3342
+ } });
3343
+ var modelClassifier_1 = require_modelClassifier();
3344
+ Object.defineProperty(exports, "classifyModelClass", { enumerable: true, get: function() {
3345
+ return modelClassifier_1.classifyModelClass;
3346
+ } });
1910
3347
  var buckets_1 = require_buckets();
1911
3348
  Object.defineProperty(exports, "bucketLinesChanged", { enumerable: true, get: function() {
1912
3349
  return buckets_1.bucketLinesChanged;
@@ -1955,6 +3392,9 @@ var require_out2 = __commonJS({
1955
3392
  Object.defineProperty(exports, "looksLikeCorrection", { enumerable: true, get: function() {
1956
3393
  return payload_1.looksLikeCorrection;
1957
3394
  } });
3395
+ Object.defineProperty(exports, "mintIdempotencyKey", { enumerable: true, get: function() {
3396
+ return payload_1.mintIdempotencyKey;
3397
+ } });
1958
3398
  var eventSender_1 = require_eventSender();
1959
3399
  Object.defineProperty(exports, "AscendaEventSender", { enumerable: true, get: function() {
1960
3400
  return eventSender_1.AscendaEventSender;
@@ -1982,15 +3422,59 @@ var require_out2 = __commonJS({
1982
3422
  Object.defineProperty(exports, "DEFAULT_API_BASE_URL", { enumerable: true, get: function() {
1983
3423
  return hookAdapter_1.DEFAULT_API_BASE_URL;
1984
3424
  } });
3425
+ Object.defineProperty(exports, "MissingInstallationIdError", { enumerable: true, get: function() {
3426
+ return hookAdapter_1.MissingInstallationIdError;
3427
+ } });
1985
3428
  Object.defineProperty(exports, "deliverHookEvents", { enumerable: true, get: function() {
1986
3429
  return hookAdapter_1.deliverHookEvents;
1987
3430
  } });
1988
3431
  Object.defineProperty(exports, "loadCliAgentConfig", { enumerable: true, get: function() {
1989
3432
  return hookAdapter_1.loadCliAgentConfig;
1990
3433
  } });
3434
+ Object.defineProperty(exports, "resolveCliAgentInstallationId", { enumerable: true, get: function() {
3435
+ return hookAdapter_1.resolveCliAgentInstallationId;
3436
+ } });
1991
3437
  Object.defineProperty(exports, "resolveContextHashes", { enumerable: true, get: function() {
1992
3438
  return hookAdapter_1.resolveContextHashes;
1993
3439
  } });
3440
+ var cliAgentSetup_1 = require_cliAgentSetup();
3441
+ Object.defineProperty(exports, "cliAgentHookBinPath", { enumerable: true, get: function() {
3442
+ return cliAgentSetup_1.cliAgentHookBinPath;
3443
+ } });
3444
+ Object.defineProperty(exports, "findStaleHookCommands", { enumerable: true, get: function() {
3445
+ return cliAgentSetup_1.findStaleHookCommands;
3446
+ } });
3447
+ Object.defineProperty(exports, "isCliAgentManagementCommand", { enumerable: true, get: function() {
3448
+ return cliAgentSetup_1.isCliAgentManagementCommand;
3449
+ } });
3450
+ Object.defineProperty(exports, "runCliAgentSetup", { enumerable: true, get: function() {
3451
+ return cliAgentSetup_1.runCliAgentSetup;
3452
+ } });
3453
+ Object.defineProperty(exports, "writeHookSettings", { enumerable: true, get: function() {
3454
+ return cliAgentSetup_1.writeHookSettings;
3455
+ } });
3456
+ var credentials_1 = require_credentials();
3457
+ Object.defineProperty(exports, "credentialsFilePath", { enumerable: true, get: function() {
3458
+ return credentials_1.credentialsFilePath;
3459
+ } });
3460
+ Object.defineProperty(exports, "readHostCredentials", { enumerable: true, get: function() {
3461
+ return credentials_1.readHostCredentials;
3462
+ } });
3463
+ Object.defineProperty(exports, "readMachineCredentials", { enumerable: true, get: function() {
3464
+ return credentials_1.readMachineCredentials;
3465
+ } });
3466
+ Object.defineProperty(exports, "removeHostCredentials", { enumerable: true, get: function() {
3467
+ return credentials_1.removeHostCredentials;
3468
+ } });
3469
+ Object.defineProperty(exports, "writeHostCredentials", { enumerable: true, get: function() {
3470
+ return credentials_1.writeHostCredentials;
3471
+ } });
3472
+ Object.defineProperty(exports, "writeMachineCredentials", { enumerable: true, get: function() {
3473
+ return credentials_1.writeMachineCredentials;
3474
+ } });
3475
+ Object.defineProperty(exports, "writeTopLevelCredentials", { enumerable: true, get: function() {
3476
+ return credentials_1.writeTopLevelCredentials;
3477
+ } });
1994
3478
  var turnState_1 = require_turnState();
1995
3479
  Object.defineProperty(exports, "consumeTurnDurationMs", { enumerable: true, get: function() {
1996
3480
  return turnState_1.consumeTurnDurationMs;
@@ -2005,6 +3489,9 @@ var require_out2 = __commonJS({
2005
3489
  Object.defineProperty(exports, "defaultTokenFilePath", { enumerable: true, get: function() {
2006
3490
  return tokenStore_1.defaultTokenFilePath;
2007
3491
  } });
3492
+ Object.defineProperty(exports, "listPersistedToolInstallationIds", { enumerable: true, get: function() {
3493
+ return tokenStore_1.listPersistedToolInstallationIds;
3494
+ } });
2008
3495
  Object.defineProperty(exports, "persistEventWriteToken", { enumerable: true, get: function() {
2009
3496
  return tokenStore_1.persistEventWriteToken;
2010
3497
  } });
@@ -2027,6 +3514,46 @@ var require_out2 = __commonJS({
2027
3514
  Object.defineProperty(exports, "markFailureNotified", { enumerable: true, get: function() {
2028
3515
  return stateStore_1.markFailureNotified;
2029
3516
  } });
3517
+ Object.defineProperty(exports, "unresolvedStateFilePath", { enumerable: true, get: function() {
3518
+ return stateStore_1.unresolvedStateFilePath;
3519
+ } });
3520
+ Object.defineProperty(exports, "unresolvedToolInstallationId", { enumerable: true, get: function() {
3521
+ return stateStore_1.unresolvedToolInstallationId;
3522
+ } });
3523
+ Object.defineProperty(exports, "recordOutboxDiscard", { enumerable: true, get: function() {
3524
+ return stateStore_1.recordOutboxDiscard;
3525
+ } });
3526
+ var outbox_1 = require_outbox();
3527
+ Object.defineProperty(exports, "OUTBOX_DRAIN_ENV_VAR", { enumerable: true, get: function() {
3528
+ return outbox_1.OUTBOX_DRAIN_ENV_VAR;
3529
+ } });
3530
+ Object.defineProperty(exports, "DEFAULT_OUTBOX_MAX_ENTRIES", { enumerable: true, get: function() {
3531
+ return outbox_1.DEFAULT_OUTBOX_MAX_ENTRIES;
3532
+ } });
3533
+ Object.defineProperty(exports, "DEFAULT_OUTBOX_MAX_AGE_MS", { enumerable: true, get: function() {
3534
+ return outbox_1.DEFAULT_OUTBOX_MAX_AGE_MS;
3535
+ } });
3536
+ Object.defineProperty(exports, "DEFAULT_OUTBOX_DRAIN_BATCH_SIZE", { enumerable: true, get: function() {
3537
+ return outbox_1.DEFAULT_OUTBOX_DRAIN_BATCH_SIZE;
3538
+ } });
3539
+ Object.defineProperty(exports, "outboxDrainEnabled", { enumerable: true, get: function() {
3540
+ return outbox_1.outboxDrainEnabled;
3541
+ } });
3542
+ Object.defineProperty(exports, "defaultOutboxFilePath", { enumerable: true, get: function() {
3543
+ return outbox_1.defaultOutboxFilePath;
3544
+ } });
3545
+ Object.defineProperty(exports, "appendToOutbox", { enumerable: true, get: function() {
3546
+ return outbox_1.appendToOutbox;
3547
+ } });
3548
+ Object.defineProperty(exports, "readOutboxSummary", { enumerable: true, get: function() {
3549
+ return outbox_1.readOutboxSummary;
3550
+ } });
3551
+ Object.defineProperty(exports, "claimOutbox", { enumerable: true, get: function() {
3552
+ return outbox_1.claimOutbox;
3553
+ } });
3554
+ Object.defineProperty(exports, "enforceOutboxBounds", { enumerable: true, get: function() {
3555
+ return outbox_1.enforceOutboxBounds;
3556
+ } });
2030
3557
  var salt_1 = require_salt();
2031
3558
  Object.defineProperty(exports, "machineSaltFilePath", { enumerable: true, get: function() {
2032
3559
  return salt_1.machineSaltFilePath;
@@ -2041,6 +3568,18 @@ var require_out2 = __commonJS({
2041
3568
  Object.defineProperty(exports, "deriveWorkContext", { enumerable: true, get: function() {
2042
3569
  return workContext_1.deriveWorkContext;
2043
3570
  } });
3571
+ Object.defineProperty(exports, "deriveBranchHash", { enumerable: true, get: function() {
3572
+ return workContext_1.deriveBranchHash;
3573
+ } });
3574
+ Object.defineProperty(exports, "deriveBranchHashForCwd", { enumerable: true, get: function() {
3575
+ return workContext_1.deriveBranchHashForCwd;
3576
+ } });
3577
+ Object.defineProperty(exports, "normalizeBranchName", { enumerable: true, get: function() {
3578
+ return workContext_1.normalizeBranchName;
3579
+ } });
3580
+ Object.defineProperty(exports, "readBranchName", { enumerable: true, get: function() {
3581
+ return workContext_1.readBranchName;
3582
+ } });
2044
3583
  var contextRegistry_1 = require_contextRegistry();
2045
3584
  Object.defineProperty(exports, "recordWorkContext", { enumerable: true, get: function() {
2046
3585
  return contextRegistry_1.recordWorkContext;
@@ -2054,6 +3593,22 @@ var require_out2 = __commonJS({
2054
3593
  Object.defineProperty(exports, "workContextRegistryFilePath", { enumerable: true, get: function() {
2055
3594
  return contextRegistry_1.workContextRegistryFilePath;
2056
3595
  } });
3596
+ var forgeProject_1 = require_forgeProject();
3597
+ Object.defineProperty(exports, "forgeProjectHash", { enumerable: true, get: function() {
3598
+ return forgeProject_1.forgeProjectHash;
3599
+ } });
3600
+ Object.defineProperty(exports, "parseForgeFullName", { enumerable: true, get: function() {
3601
+ return forgeProject_1.parseForgeFullName;
3602
+ } });
3603
+ Object.defineProperty(exports, "readForgeFullName", { enumerable: true, get: function() {
3604
+ return forgeProject_1.readForgeFullName;
3605
+ } });
3606
+ Object.defineProperty(exports, "forgeFullNameFromConfig", { enumerable: true, get: function() {
3607
+ return forgeProject_1.forgeFullNameFromConfig;
3608
+ } });
3609
+ Object.defineProperty(exports, "recordForgeProjectAlias", { enumerable: true, get: function() {
3610
+ return forgeProject_1.recordForgeProjectAlias;
3611
+ } });
2057
3612
  var liveBus_1 = require_liveBus();
2058
3613
  Object.defineProperty(exports, "emitLiveSignal", { enumerable: true, get: function() {
2059
3614
  return liveBus_1.emitLiveSignal;
@@ -2096,40 +3651,25 @@ var require_out2 = __commonJS({
2096
3651
  });
2097
3652
 
2098
3653
  // src/paths.ts
2099
- import * as fs from "fs";
2100
3654
  import * as path from "path";
2101
3655
  function hookBinPath() {
2102
3656
  return path.join((0, import_tool_kit3.ascendaHome)(), "bin", "ascenda-claude-hook");
2103
3657
  }
2104
- function credentialsFilePath() {
2105
- return path.join((0, import_tool_kit3.ascendaHome)(), "credentials.json");
2106
- }
2107
3658
  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
- }
3659
+ const credentials = (0, import_tool_kit3.readMachineCredentials)();
3660
+ if (!credentials) return void 0;
3661
+ const { tools: _tools, ...topLevel } = credentials;
3662
+ return topLevel;
2117
3663
  }
2118
3664
  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
- }
3665
+ (0, import_tool_kit3.writeTopLevelCredentials)(credentials);
2127
3666
  }
2128
- var import_tool_kit3;
3667
+ var import_tool_kit3, import_tool_kit4;
2129
3668
  var init_paths = __esm({
2130
3669
  "src/paths.ts"() {
2131
3670
  "use strict";
2132
3671
  import_tool_kit3 = __toESM(require_out2(), 1);
3672
+ import_tool_kit4 = __toESM(require_out2(), 1);
2133
3673
  }
2134
3674
  });
2135
3675
 
@@ -2159,28 +3699,37 @@ var init_types = __esm({
2159
3699
  });
2160
3700
 
2161
3701
  // src/config.ts
3702
+ function resolveOutboxFilePath(toolInstallationId) {
3703
+ return process.env.ASCENDA_OUTBOX_FILE ?? (0, import_tool_kit5.defaultOutboxFilePath)(toolInstallationId);
3704
+ }
2162
3705
  function resolveStateFilePath(toolInstallationId) {
2163
- return process.env.ASCENDA_STATE_FILE ?? (0, import_tool_kit4.defaultStateFilePath)(toolInstallationId);
3706
+ return process.env.ASCENDA_STATE_FILE ?? (toolInstallationId ? (0, import_tool_kit5.defaultStateFilePath)(toolInstallationId) : (0, import_tool_kit5.unresolvedStateFilePath)(ASCENDA_TOOL_TYPE));
3707
+ }
3708
+ function resolveToolInstallationId(credentials = readCredentials()) {
3709
+ const fromEnv = process.env.ASCENDA_TOOL_INSTALLATION_ID?.trim();
3710
+ if (fromEnv) return { toolInstallationId: normalizeToolInstallationId(fromEnv), source: "env" };
3711
+ const fromCredentials = credentials?.toolInstallationId?.trim();
3712
+ if (fromCredentials) return { toolInstallationId: normalizeToolInstallationId(fromCredentials), source: "credentials" };
3713
+ const candidates = (0, import_tool_kit5.listPersistedToolInstallationIds)(ASCENDA_TOOL_TYPE);
3714
+ if (candidates.length === 1) return { toolInstallationId: candidates[0], source: "disk" };
3715
+ throw new MissingInstallationIdError(candidates);
2164
3716
  }
2165
3717
  function loadConfigFromEnv() {
2166
3718
  const credentials = readCredentials();
2167
3719
  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);
3720
+ const { toolInstallationId } = resolveToolInstallationId(credentials);
3721
+ const tokenFilePath = process.env.ASCENDA_EVENT_WRITE_TOKEN_FILE ?? (0, import_tool_kit5.defaultTokenFilePath)(toolInstallationId);
3722
+ const fileToken = (0, import_tool_kit5.readTokenFile)(tokenFilePath);
2175
3723
  const eventWriteToken = fileToken ?? process.env.ASCENDA_EVENT_WRITE_TOKEN;
2176
3724
  if (!eventWriteToken) throw new Error("Missing ASCENDA_EVENT_WRITE_TOKEN (or token file)");
2177
- if (!fileToken) (0, import_tool_kit4.persistEventWriteToken)(tokenFilePath, eventWriteToken);
3725
+ if (!fileToken) (0, import_tool_kit5.persistEventWriteToken)(tokenFilePath, eventWriteToken);
2178
3726
  return {
2179
3727
  apiBaseUrl,
2180
3728
  toolInstallationId,
2181
3729
  eventWriteToken,
2182
3730
  tokenFilePath,
2183
3731
  stateFilePath: resolveStateFilePath(toolInstallationId),
3732
+ outboxFilePath: resolveOutboxFilePath(toolInstallationId),
2184
3733
  sessionId: process.env.ASCENDA_SESSION_ID ?? null,
2185
3734
  // Overrides only. When unset, main() fills these from the hook payload's
2186
3735
  // own cwd — the payload knows where the work happened; the environment
@@ -2199,14 +3748,25 @@ function normalizeToolInstallationId(value) {
2199
3748
  if (trimmed.startsWith("claude_tool_")) return `${ASCENDA_TOOL_TYPE}:${trimmed.slice("claude_tool_".length)}`;
2200
3749
  return `${ASCENDA_TOOL_TYPE}:${trimmed}`;
2201
3750
  }
2202
- var import_tool_kit4, DEFAULT_API_BASE_URL;
3751
+ var import_tool_kit5, DEFAULT_API_BASE_URL, MissingInstallationIdError;
2203
3752
  var init_config = __esm({
2204
3753
  "src/config.ts"() {
2205
3754
  "use strict";
2206
- import_tool_kit4 = __toESM(require_out2(), 1);
3755
+ import_tool_kit5 = __toESM(require_out2(), 1);
2207
3756
  init_paths();
2208
3757
  init_types();
2209
3758
  DEFAULT_API_BASE_URL = "https://api.ascenda.one";
3759
+ MissingInstallationIdError = class extends Error {
3760
+ /** The token files that were considered — none, or too many to pick from. */
3761
+ candidates;
3762
+ constructor(candidates) {
3763
+ super(
3764
+ 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`
3765
+ );
3766
+ this.name = "MissingInstallationIdError";
3767
+ this.candidates = candidates;
3768
+ }
3769
+ };
2210
3770
  }
2211
3771
  });
2212
3772
 
@@ -2218,7 +3778,7 @@ __export(setup_exports, {
2218
3778
  writeSettings: () => writeSettings
2219
3779
  });
2220
3780
  import * as crypto from "crypto";
2221
- import * as fs2 from "fs";
3781
+ import * as fs from "fs";
2222
3782
  import * as os from "os";
2223
3783
  import * as path2 from "path";
2224
3784
  async function runSetup(argv) {
@@ -2245,7 +3805,7 @@ async function runSetup(argv) {
2245
3805
  if (!options.dryRun) {
2246
3806
  writeCredentials({ apiBaseUrl, toolInstallationId: identity.toolInstallationId, pairedAt: (/* @__PURE__ */ new Date()).toISOString() });
2247
3807
  }
2248
- console.log(` credentials ${credentialsFilePath()}`);
3808
+ console.log(` credentials ${(0, import_tool_kit4.credentialsFilePath)()}`);
2249
3809
  const settingsFile = settingsPath(options);
2250
3810
  const written = writeSettings(settingsFile, binary, options.dryRun);
2251
3811
  if (written === null) return 1;
@@ -2325,10 +3885,10 @@ ${USAGE}`);
2325
3885
  async function resolveIdentity(apiBaseUrl, options) {
2326
3886
  const existingId = options.toolInstallationId ?? readCredentials()?.toolInstallationId;
2327
3887
  if (existingId && options.token) {
2328
- if (!options.dryRun) (0, import_tool_kit7.persistEventWriteToken)((0, import_tool_kit7.defaultTokenFilePath)(existingId), options.token);
3888
+ if (!options.dryRun) (0, import_tool_kit8.persistEventWriteToken)((0, import_tool_kit8.defaultTokenFilePath)(existingId), options.token);
2329
3889
  return { toolInstallationId: existingId, paired: false };
2330
3890
  }
2331
- if (existingId && (0, import_tool_kit7.readTokenFile)((0, import_tool_kit7.defaultTokenFilePath)(existingId))) {
3891
+ if (existingId && (0, import_tool_kit8.readTokenFile)((0, import_tool_kit8.defaultTokenFilePath)(existingId))) {
2332
3892
  return { toolInstallationId: existingId, paired: false };
2333
3893
  }
2334
3894
  if (options.dryRun) {
@@ -2337,7 +3897,7 @@ async function resolveIdentity(apiBaseUrl, options) {
2337
3897
  const toolInstallationId = existingId ?? `${ASCENDA_TOOL_TYPE}:${crypto.randomUUID()}`;
2338
3898
  let session;
2339
3899
  try {
2340
- session = await (0, import_tool_kit7.createPairingSession)(apiBaseUrl, toolInstallationId, ASCENDA_TOOL_TYPE, `Claude Code on ${os.hostname()}`);
3900
+ session = await (0, import_tool_kit8.createPairingSession)(apiBaseUrl, toolInstallationId, ASCENDA_TOOL_TYPE, `Claude Code on ${os.hostname()}`);
2341
3901
  } catch (error) {
2342
3902
  console.error(`
2343
3903
  Could not reach ${apiBaseUrl} to pair: ${error instanceof Error ? error.message : String(error)}`);
@@ -2346,14 +3906,14 @@ Could not reach ${apiBaseUrl} to pair: ${error instanceof Error ? error.message
2346
3906
  }
2347
3907
  const token = await pollForToken(apiBaseUrl, session.pairingSessionId, session.code, session.expiresAt);
2348
3908
  if (!token) return void 0;
2349
- (0, import_tool_kit7.persistEventWriteToken)((0, import_tool_kit7.defaultTokenFilePath)(toolInstallationId), token);
3909
+ (0, import_tool_kit8.persistEventWriteToken)((0, import_tool_kit8.defaultTokenFilePath)(toolInstallationId), token);
2350
3910
  return { toolInstallationId, paired: true };
2351
3911
  }
2352
3912
  async function pollForToken(apiBaseUrl, pairingSessionId, code, expiresAt) {
2353
3913
  const deadline = Math.min(Date.parse(expiresAt) || Date.now() + 3e5, Date.now() + 3e5);
2354
3914
  let announced = false;
2355
3915
  while (Date.now() < deadline) {
2356
- const status = await (0, import_tool_kit7.getPairingStatus)(apiBaseUrl, pairingSessionId);
3916
+ const status = await (0, import_tool_kit8.getPairingStatus)(apiBaseUrl, pairingSessionId);
2357
3917
  if (status.status === "paired" && status.eventWriteToken) return status.eventWriteToken;
2358
3918
  if (status.status === "expired" || status.status === "cancelled") {
2359
3919
  console.error(`
@@ -2375,11 +3935,11 @@ function installBinary(dryRun) {
2375
3935
  const target = hookBinPath();
2376
3936
  if (dryRun) return target;
2377
3937
  const source = process.argv[1];
2378
- fs2.mkdirSync(path2.dirname(target), { recursive: true });
3938
+ fs.mkdirSync(path2.dirname(target), { recursive: true });
2379
3939
  if (path2.resolve(source) !== path2.resolve(target)) {
2380
- fs2.copyFileSync(source, target);
3940
+ fs.copyFileSync(source, target);
2381
3941
  }
2382
- if (process.platform !== "win32") fs2.chmodSync(target, 493);
3942
+ if (process.platform !== "win32") fs.chmodSync(target, 493);
2383
3943
  return target;
2384
3944
  }
2385
3945
  function settingsPath(options) {
@@ -2387,9 +3947,9 @@ function settingsPath(options) {
2387
3947
  }
2388
3948
  function writeSettings(settingsFile, binary, dryRun) {
2389
3949
  let settings = {};
2390
- const exists = fs2.existsSync(settingsFile);
3950
+ const exists = fs.existsSync(settingsFile);
2391
3951
  if (exists) {
2392
- const raw = fs2.readFileSync(settingsFile, "utf8").trim();
3952
+ const raw = fs.readFileSync(settingsFile, "utf8").trim();
2393
3953
  if (raw) {
2394
3954
  try {
2395
3955
  settings = JSON.parse(raw);
@@ -2409,16 +3969,16 @@ ${settingsFile} is not valid JSON. Fix or move it, then run setup again.`);
2409
3969
  const updated = { ...settings, hooks };
2410
3970
  const serialised = `${JSON.stringify(updated, null, 2)}
2411
3971
  `;
2412
- if (exists && fs2.readFileSync(settingsFile, "utf8") === serialised) return false;
3972
+ if (exists && fs.readFileSync(settingsFile, "utf8") === serialised) return false;
2413
3973
  if (dryRun) {
2414
3974
  console.log(`
2415
3975
  --- ${settingsFile} (dry run) ---
2416
3976
  ${serialised}`);
2417
3977
  return true;
2418
3978
  }
2419
- if (exists) fs2.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
2420
- fs2.mkdirSync(path2.dirname(settingsFile), { recursive: true });
2421
- fs2.writeFileSync(settingsFile, serialised, "utf8");
3979
+ if (exists) fs.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
3980
+ fs.mkdirSync(path2.dirname(settingsFile), { recursive: true });
3981
+ fs.writeFileSync(settingsFile, serialised, "utf8");
2422
3982
  return true;
2423
3983
  }
2424
3984
  function hookCommand(binary) {
@@ -2445,10 +4005,10 @@ function printStatus(options) {
2445
4005
  const credentials = readCredentials();
2446
4006
  const settingsFile = settingsPath(options);
2447
4007
  const binary = hookBinPath();
2448
- const tokenFile = credentials?.toolInstallationId ? (0, import_tool_kit7.defaultTokenFilePath)(credentials.toolInstallationId) : void 0;
4008
+ const tokenFile = credentials?.toolInstallationId ? (0, import_tool_kit8.defaultTokenFilePath)(credentials.toolInstallationId) : void 0;
2449
4009
  const settings = (() => {
2450
4010
  try {
2451
- return JSON.parse(fs2.readFileSync(settingsFile, "utf8"));
4011
+ return JSON.parse(fs.readFileSync(settingsFile, "utf8"));
2452
4012
  } catch {
2453
4013
  return {};
2454
4014
  }
@@ -2457,22 +4017,22 @@ function printStatus(options) {
2457
4017
  const stale = findStaleHookCommands(settings, binary);
2458
4018
  console.log(`api base url ${credentials?.apiBaseUrl ?? "\u2014 not configured"}`);
2459
4019
  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"}`);
4020
+ console.log(`token ${tokenFile && (0, import_tool_kit8.readTokenFile)(tokenFile) ? "present" : "\u2014 missing"}`);
4021
+ console.log(`hook binary ${fs.existsSync(binary) ? binary : "\u2014 not installed"}`);
2462
4022
  console.log(`hooks ${registered}/${HOOK_EVENTS.length} registered in ${settingsFile}`);
2463
4023
  if (stale.length) {
2464
4024
  console.log(`stale hooks ${stale.length} not pointing at the installed binary \u2014 each one fails silently per event:`);
2465
4025
  for (const command of stale) console.log(` ${command}`);
2466
4026
  console.log(` Remove them from ${settingsFile} by hand; setup cannot tell them from a hook you wrote.`);
2467
4027
  }
2468
- const healthy = credentials?.toolInstallationId && registered === HOOK_EVENTS.length && fs2.existsSync(binary) && !stale.length;
4028
+ const healthy = credentials?.toolInstallationId && registered === HOOK_EVENTS.length && fs.existsSync(binary) && !stale.length;
2469
4029
  return healthy ? 0 : 1;
2470
4030
  }
2471
4031
  function uninstall(options) {
2472
4032
  const settingsFile = settingsPath(options);
2473
- if (fs2.existsSync(settingsFile)) {
4033
+ if (fs.existsSync(settingsFile)) {
2474
4034
  try {
2475
- const settings = JSON.parse(fs2.readFileSync(settingsFile, "utf8"));
4035
+ const settings = JSON.parse(fs.readFileSync(settingsFile, "utf8"));
2476
4036
  const hooks = { ...settings.hooks ?? {} };
2477
4037
  for (const event of Object.keys(hooks)) {
2478
4038
  const kept = hooks[event].filter((group) => !isOurs(group));
@@ -2481,8 +4041,8 @@ function uninstall(options) {
2481
4041
  }
2482
4042
  const updated = { ...settings, hooks };
2483
4043
  if (!Object.keys(hooks).length) delete updated.hooks;
2484
- fs2.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
2485
- fs2.writeFileSync(settingsFile, `${JSON.stringify(updated, null, 2)}
4044
+ fs.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
4045
+ fs.writeFileSync(settingsFile, `${JSON.stringify(updated, null, 2)}
2486
4046
  `, "utf8");
2487
4047
  console.log(`hooks removed from ${settingsFile}`);
2488
4048
  } catch {
@@ -2491,23 +4051,23 @@ function uninstall(options) {
2491
4051
  }
2492
4052
  }
2493
4053
  const binary = hookBinPath();
2494
- if (fs2.existsSync(binary)) {
2495
- fs2.rmSync(binary);
4054
+ if (fs.existsSync(binary)) {
4055
+ fs.rmSync(binary);
2496
4056
  console.log(`removed ${binary}`);
2497
4057
  }
2498
- const credentials = credentialsFilePath();
2499
- if (fs2.existsSync(credentials)) {
2500
- fs2.rmSync(credentials);
4058
+ const credentials = (0, import_tool_kit4.credentialsFilePath)();
4059
+ if (fs.existsSync(credentials)) {
4060
+ fs.rmSync(credentials);
2501
4061
  console.log(`removed ${credentials}`);
2502
4062
  }
2503
- console.log(`tokens left in ${path2.join((0, import_tool_kit7.ascendaHome)(), "tokens")} \u2014 revoke in the Ascenda app to invalidate them`);
4063
+ console.log(`tokens left in ${path2.join((0, import_tool_kit8.ascendaHome)(), "tokens")} \u2014 revoke in the Ascenda app to invalidate them`);
2504
4064
  return 0;
2505
4065
  }
2506
- var import_tool_kit7, HOOK_EVENTS, HOOK_TIMEOUT_SECONDS, HOOK_MARKER, USAGE;
4066
+ var import_tool_kit8, HOOK_EVENTS, HOOK_TIMEOUT_SECONDS, HOOK_MARKER, USAGE;
2507
4067
  var init_setup = __esm({
2508
4068
  "src/setup.ts"() {
2509
4069
  "use strict";
2510
- import_tool_kit7 = __toESM(require_out2(), 1);
4070
+ import_tool_kit8 = __toESM(require_out2(), 1);
2511
4071
  init_config();
2512
4072
  init_paths();
2513
4073
  init_types();
@@ -2534,9 +4094,9 @@ Options
2534
4094
  });
2535
4095
 
2536
4096
  // src/cli.ts
2537
- var import_tool_kit8 = __toESM(require_out2(), 1);
4097
+ var import_tool_kit9 = __toESM(require_out2(), 1);
2538
4098
  import { randomUUID as randomUUID2 } from "node:crypto";
2539
- import * as fs3 from "node:fs";
4099
+ import * as fs2 from "node:fs";
2540
4100
 
2541
4101
  // src/ascendaClient.ts
2542
4102
  var import_tool_kit = __toESM(require_out2(), 1);
@@ -2551,6 +4111,7 @@ var AscendaClient = class {
2551
4111
  eventWriteToken: config.eventWriteToken,
2552
4112
  tokenFilePath: config.tokenFilePath,
2553
4113
  stateFilePath: config.stateFilePath,
4114
+ outboxFilePath: config.outboxFilePath,
2554
4115
  sessionId: config.sessionId,
2555
4116
  workspaceHash: config.workspaceHash,
2556
4117
  projectHash: config.projectHash
@@ -2572,17 +4133,20 @@ var AscendaClient = class {
2572
4133
  init_config();
2573
4134
 
2574
4135
  // src/mapClaudeEvent.ts
2575
- var import_tool_kit6 = __toESM(require_out2(), 1);
4136
+ var import_tool_kit7 = __toESM(require_out2(), 1);
2576
4137
  init_types();
2577
4138
 
2578
4139
  // src/safeExtract.ts
2579
- var import_tool_kit5 = __toESM(require_out2(), 1);
4140
+ var import_tool_kit6 = __toESM(require_out2(), 1);
2580
4141
 
2581
4142
  // src/mapClaudeEvent.ts
2582
4143
  function mapClaudeEvent(hookName, input) {
2583
- return mapEvent(hookName, input).map((event) => ({
4144
+ const events = mapEvent(hookName, input);
4145
+ if (events.length === 0) return events;
4146
+ const branchHash = (0, import_tool_kit7.deriveBranchHashForCwd)((0, import_tool_kit6.getString)(input, ["cwd"]) ?? process.cwd());
4147
+ return events.map((event) => ({
2584
4148
  ...event,
2585
- metadata: { host: CLAUDE_HOST, ...event.metadata }
4149
+ metadata: { host: CLAUDE_HOST, ...branchHash ? { branchHash } : {}, ...event.metadata }
2586
4150
  }));
2587
4151
  }
2588
4152
  function mapEvent(hookName, input) {
@@ -2614,23 +4178,35 @@ function mapEvent(hookName, input) {
2614
4178
  }
2615
4179
  }
2616
4180
  function isNewSessionStart(input) {
2617
- const source = (0, import_tool_kit5.getString)(input, ["source"]);
4181
+ const source = (0, import_tool_kit6.getString)(input, ["source"]);
2618
4182
  return !source || source === "startup" || source === "resume";
2619
4183
  }
2620
4184
  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));
4185
+ if ((0, import_tool_kit6.outcomeForHook)("PostToolUse", input) !== "success") return false;
4186
+ const command = (0, import_tool_kit6.getString)(input, ["command"]) ?? (0, import_tool_kit6.getNestedString)(input, [["tool_input", "command"], ["input", "command"], ["parameters", "command"]]);
4187
+ return (0, import_tool_kit7.invitesDebrief)((0, import_tool_kit7.classifyWorkMilestone)(command));
2624
4188
  }
2625
4189
  function mapSessionStart(input) {
2626
4190
  if (!isNewSessionStart(input)) return [];
2627
- return [{ eventType: "create_focus_session", severity: "low", metadata: { activity: "session_started" } }];
4191
+ const modelId = readModelIdentifier(input)?.trim();
4192
+ const modelClass = (0, import_tool_kit7.classifyModelClass)(modelId);
4193
+ return [{
4194
+ eventType: "create_focus_session",
4195
+ severity: "low",
4196
+ metadata: {
4197
+ activity: "session_started",
4198
+ // `classifyModelClass` returns undefined exactly when nothing was
4199
+ // reported (absent, empty, whitespace), so this one guard governs both.
4200
+ ...modelClass !== void 0 && modelId ? { modelClass, modelId } : {}
4201
+ }
4202
+ }];
2628
4203
  }
2629
4204
  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" } });
4205
+ const prompt = (0, import_tool_kit6.getString)(input, ["prompt", "userPrompt", "message"]) ?? (0, import_tool_kit6.getNestedString)(input, [["payload", "prompt"], ["payload", "message"]]);
4206
+ const autonomy = autonomyModeMetadata(input);
4207
+ const events = [{ eventType: "ai_prompt_submitted", severity: "low", metadata: { promptClass: "unknown", ...autonomy } }];
4208
+ if ((0, import_tool_kit6.looksLikeCorrection)(prompt)) {
4209
+ events.push({ eventType: "ai_correction_prompt", severity: "medium", metadata: { reason: "repeated_reprompting", trigger: "inferred", ...autonomy } });
2634
4210
  }
2635
4211
  return events;
2636
4212
  }
@@ -2640,41 +4216,50 @@ function mapPreToolUse(input) {
2640
4216
  function mapPostToolUse(hookName, input) {
2641
4217
  const toolName = getToolName(input);
2642
4218
  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;
4219
+ const outcome = (0, import_tool_kit6.outcomeForHook)(hookName, input);
4220
+ const durationMs = (0, import_tool_kit6.getNumber)(input, ["duration_ms", "durationMs", "elapsedMs"]) ?? (0, import_tool_kit6.getNestedNumber)(input, [["tool_response", "durationMs"], ["result", "durationMs"]]);
4221
+ const command = (0, import_tool_kit6.getString)(input, ["command"]) ?? (0, import_tool_kit6.getNestedString)(input, [["tool_input", "command"], ["input", "command"], ["parameters", "command"]]);
4222
+ const commandClass = (0, import_tool_kit7.classifyCommand)(command);
4223
+ const gitAction = outcome === "success" ? (0, import_tool_kit7.classifyGitAction)(command) : void 0;
4224
+ const milestoneKind = outcome === "success" ? (0, import_tool_kit7.classifyWorkMilestone)(command) : void 0;
4225
+ const autonomy = autonomyModeMetadata(input);
2649
4226
  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" } }];
4227
+ 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
4228
  }
2652
4229
  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" } }];
4230
+ if (toolName?.toLowerCase() === "bash" && (0, import_tool_kit7.isVerificationCommand)(commandClass)) {
4231
+ return [{ eventType: "compile_error", severity: "medium", metadata: { toolName: safeToolName, commandClass, outcome, durationBucket: (0, import_tool_kit6.bucketDurationMs)(durationMs), reason: "test_failure", ...autonomy } }];
2655
4232
  }
2656
- return [{ eventType: "ai_tool_call_failed", severity: "medium", metadata: { toolName: safeToolName, commandClass, outcome, durationBucket: (0, import_tool_kit5.bucketDurationMs)(durationMs), reason: "tool_failure" } }];
4233
+ 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
4234
  }
2658
4235
  if (isWriteTool(toolName)) {
2659
4236
  const linesChanged = computeLinesChanged(toolName, input);
4237
+ const userModified = (0, import_tool_kit6.getNested)(input, ["tool_response", "userModified"]);
2660
4238
  return [{
2661
4239
  eventType: toolName?.toLowerCase() === "write" ? "ai_file_write" : "ai_file_edit",
2662
4240
  severity: "low",
2663
4241
  metadata: {
2664
4242
  toolName: safeToolName,
2665
4243
  outcome,
2666
- durationBucket: (0, import_tool_kit5.bucketDurationMs)(durationMs),
4244
+ durationBucket: (0, import_tool_kit6.bucketDurationMs)(durationMs),
4245
+ ...autonomy,
4246
+ // `false` is kept, not suppressed: without the negatives there is a
4247
+ // numerator and no denominator, and no correction *rate* can be
4248
+ // computed. Absence still means the payload said nothing — a
4249
+ // non-boolean value is treated as saying nothing rather than guessed
4250
+ // at, so payload drift degrades to "not collected".
4251
+ ...typeof userModified === "boolean" ? { userModified } : {},
2667
4252
  // The boundary C2/the macOS work-self-report card triggers on: at
2668
4253
  // "200+" this is the "substantial accepted change" moment. No
2669
4254
  // second event type exists for this — the bucket on the existing
2670
4255
  // creation event *is* the boundary, deliberately, since the write
2671
4256
  // already happened; there is nothing else to mark.
2672
- ...linesChanged !== void 0 ? { linesChangedBucket: (0, import_tool_kit5.bucketLinesChanged)(linesChanged) } : {}
4257
+ ...linesChanged !== void 0 ? { linesChangedBucket: (0, import_tool_kit6.bucketLinesChanged)(linesChanged) } : {}
2673
4258
  }
2674
4259
  }];
2675
4260
  }
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" } }];
4261
+ if (toolName?.toLowerCase() === "bash" && (0, import_tool_kit7.isVerificationCommand)(commandClass)) {
4262
+ 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
4263
  }
2679
4264
  return [{
2680
4265
  eventType: "ai_tool_call_completed",
@@ -2683,13 +4268,14 @@ function mapPostToolUse(hookName, input) {
2683
4268
  toolName: safeToolName,
2684
4269
  commandClass,
2685
4270
  outcome,
2686
- durationBucket: (0, import_tool_kit5.bucketDurationMs)(durationMs),
4271
+ durationBucket: (0, import_tool_kit6.bucketDurationMs)(durationMs),
4272
+ ...autonomy,
2687
4273
  // The boundary and rework signal both ride this existing event rather
2688
4274
  // than minting a type: the backend already reads `gitAction` off any
2689
4275
  // event, and a commit is not a different *kind* of thing happening, it
2690
4276
  // is a fact about the tool call that just happened.
2691
4277
  ...gitAction !== void 0 ? { gitAction } : {},
2692
- ...(0, import_tool_kit6.isReworkGitAction)(gitAction) ? { activity: "rework_reversion" } : {},
4278
+ ...(0, import_tool_kit7.isReworkGitAction)(gitAction) ? { activity: "rework_reversion" } : {},
2693
4279
  // Same reasoning as `gitAction` above, one grain coarser: a milestone is
2694
4280
  // a fact about the tool call that just happened, not a different kind of
2695
4281
  // event. It rides here so the record carries the work's own rhythm —
@@ -2699,23 +4285,53 @@ function mapPostToolUse(hookName, input) {
2699
4285
  }];
2700
4286
  }
2701
4287
  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"]]);
4288
+ const trigger = (0, import_tool_kit6.getString)(input, ["trigger", "reason", "compactType", "type"]) ?? (0, import_tool_kit6.getNestedString)(input, [["payload", "trigger"], ["payload", "reason"]]);
2703
4289
  const isManual = trigger?.toLowerCase().includes("manual") ?? false;
2704
4290
  return [{ eventType: isManual ? "context_compression_manual" : "context_compression_auto", severity: isManual ? "medium" : "high", metadata: { trigger: isManual ? "manual" : "auto", reason: "context_limit" } }];
2705
4291
  }
2706
4292
  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);
4293
+ const durationMs = (0, import_tool_kit6.getNumber)(input, ["durationMs", "duration_ms", "elapsedMs"]) ?? (0, import_tool_kit6.getNestedNumber)(input, [["session", "durationMs"], ["payload", "durationMs"]]);
4294
+ const durationBucket = (0, import_tool_kit6.bucketDurationMs)(durationMs);
2709
4295
  if (durationBucket === "30-60m" || durationBucket === "60m+") {
2710
- return [{ eventType: "agent_loop_long", severity: durationBucket === "60m+" ? "high" : "medium", metadata: { durationBucket, reason: "long_session", trigger: "inferred" } }];
4296
+ return [{ eventType: "agent_loop_long", severity: durationBucket === "60m+" ? "high" : "medium", metadata: { durationBucket, reason: "long_session", trigger: "inferred", ...autonomyModeMetadata(input) } }];
2711
4297
  }
2712
4298
  return [];
2713
4299
  }
4300
+ function autonomyModeMetadata(input) {
4301
+ const raw = readPermissionMode(input);
4302
+ return raw === void 0 ? {} : { autonomyMode: classifyAutonomyMode(raw) };
4303
+ }
4304
+ function readPermissionMode(input) {
4305
+ const candidates = [
4306
+ input["permission_mode"],
4307
+ input["permissionMode"],
4308
+ (0, import_tool_kit6.getNested)(input, ["payload", "permission_mode"])
4309
+ ];
4310
+ for (const value of candidates) {
4311
+ if (value !== void 0 && value !== null) return value;
4312
+ }
4313
+ return void 0;
4314
+ }
4315
+ function classifyAutonomyMode(raw) {
4316
+ if (typeof raw !== "string") return "unknown";
4317
+ return AUTONOMY_BY_PERMISSION_MODE[raw.trim().toLowerCase()] ?? "unknown";
4318
+ }
4319
+ var AUTONOMY_BY_PERMISSION_MODE = {
4320
+ default: "default",
4321
+ plan: "plan",
4322
+ acceptedits: "accept_edits",
4323
+ auto: "auto",
4324
+ dontask: "dont_ask",
4325
+ bypasspermissions: "bypass_permissions"
4326
+ };
4327
+ function readModelIdentifier(input) {
4328
+ 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"]]);
4329
+ }
2714
4330
  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"]]);
4331
+ 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
4332
  }
2717
4333
  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"]);
4334
+ 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
4335
  if (!toolInput || typeof toolInput !== "object") return void 0;
2720
4336
  const record = toolInput;
2721
4337
  switch (toolName?.toLowerCase()) {
@@ -2770,7 +4386,7 @@ async function runPair() {
2770
4386
  const toolType = flagIndex !== -1 ? (process.argv[flagIndex + 1] ?? "").trim() || ASCENDA_TOOL_TYPE : ASCENDA_TOOL_TYPE;
2771
4387
  const existing = process.env.ASCENDA_TOOL_INSTALLATION_ID?.trim();
2772
4388
  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);
4389
+ const session = await (0, import_tool_kit9.createPairingSession)(apiBaseUrl, toolInstallationId, toolType, toolType === ASCENDA_TOOL_TYPE ? "Claude Code" : toolType);
2774
4390
  const code = session.deviceCode ?? session.code;
2775
4391
  await writeStdout(
2776
4392
  `
@@ -2784,7 +4400,7 @@ Waiting for confirmation (expires ${session.expiresAt})...
2784
4400
  const deadline = Date.now() + 11 * 60 * 1e3;
2785
4401
  while (Date.now() < deadline) {
2786
4402
  await new Promise((resolve2) => setTimeout(resolve2, 3e3));
2787
- const status = await (0, import_tool_kit8.getPairingStatus)(apiBaseUrl, session.pairingSessionId);
4403
+ const status = await (0, import_tool_kit9.getPairingStatus)(apiBaseUrl, session.pairingSessionId);
2788
4404
  if (status.status === "pending") continue;
2789
4405
  if (status.status !== "paired") {
2790
4406
  process.stderr.write(`Pairing ${status.status}. Run the command again for a fresh code.
@@ -2800,8 +4416,8 @@ Waiting for confirmation (expires ${session.expiresAt})...
2800
4416
  process.exitCode = 1;
2801
4417
  return;
2802
4418
  }
2803
- const tokenFilePath = (0, import_tool_kit8.defaultTokenFilePath)(pairedId);
2804
- (0, import_tool_kit8.persistEventWriteToken)(tokenFilePath, status.eventWriteToken);
4419
+ const tokenFilePath = (0, import_tool_kit9.defaultTokenFilePath)(pairedId);
4420
+ (0, import_tool_kit9.persistEventWriteToken)(tokenFilePath, status.eventWriteToken);
2805
4421
  await writeStdout(
2806
4422
  `Paired. Write token saved to ${tokenFilePath}
2807
4423
 
@@ -2857,18 +4473,22 @@ async function main() {
2857
4473
  await writeStdout(JSON.stringify({
2858
4474
  hookSpecificOutput: { hookEventName: hookName, additionalContext: contextParts.join("\n\n") }
2859
4475
  }));
2860
- if (pending) (0, import_tool_kit8.markFailureNotified)(pending.stateFilePath, pending.state);
4476
+ if (pending) (0, import_tool_kit9.markFailureNotified)(pending.stateFilePath, pending.state);
2861
4477
  }
2862
4478
  await emitLive(hookName, input);
2863
4479
  const mappedEvents = mapClaudeEvent(hookName, input);
2864
4480
  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);
4481
+ const workContext = (0, import_tool_kit9.deriveWorkContext)((0, import_tool_kit9.getString)(input, ["cwd"]) ?? process.cwd());
4482
+ if (workContext) {
4483
+ (0, import_tool_kit9.recordWorkContext)(workContext);
4484
+ (0, import_tool_kit9.recordForgeProjectAlias)(workContext);
4485
+ }
2867
4486
  let config;
2868
4487
  try {
2869
4488
  config = loadConfigFromEnv();
2870
4489
  } catch (error) {
2871
- const logFile = (0, import_tool_kit8.resolveEventLogPath)();
4490
+ if (error instanceof MissingInstallationIdError) journalSkippedSend(error);
4491
+ const logFile = (0, import_tool_kit9.resolveEventLogPath)();
2872
4492
  if (!logFile) throw error;
2873
4493
  for (const event of mappedEvents) logUnsent(logFile, event, workContext);
2874
4494
  return;
@@ -2883,28 +4503,33 @@ async function main() {
2883
4503
  return;
2884
4504
  }
2885
4505
  }
4506
+ function journalSkippedSend(error) {
4507
+ (0, import_tool_kit9.recordSendOutcome)(resolveStateFilePath(), (0, import_tool_kit9.unresolvedToolInstallationId)(ASCENDA_TOOL_TYPE), "skipped_no_installation_id", {
4508
+ 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(", ")})`
4509
+ });
4510
+ }
2886
4511
  function explainRejection(result) {
2887
4512
  if (result === "consent_missing") return "Ascenda telemetry rejected: renew IDE telemetry consent in the Ascenda app.";
2888
4513
  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.";
4514
+ if (result === "transport_error") return "Ascenda telemetry not delivered: the ingest endpoint could not be reached; the event is kept in the outbox.";
2890
4515
  return `Ascenda telemetry rejected: ${result}`;
2891
4516
  }
2892
4517
  async function emitLive(hookName, input) {
2893
4518
  const event = hookName === "UserPromptSubmit" ? "prompt_submitted" : hookName === "PreToolUse" ? "tool_call" : hookName === "PreCompact" ? "compaction" : hookName === "PostToolUseFailure" ? "tool_failure" : hookName === "Stop" ? "stop" : void 0;
2894
4519
  if (!event) return;
2895
4520
  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;
4521
+ 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;
4522
+ const promptSource = event === "prompt_submitted" ? (0, import_tool_kit9.getString)(input, ["promptSource", "prompt_source"]) : void 0;
2898
4523
  const queued = promptSource === void 0 ? void 0 : promptSource === "queued";
2899
- await (0, import_tool_kit8.emitLiveSignal)({
4524
+ await (0, import_tool_kit9.emitLiveSignal)({
2900
4525
  tool: process.env.ASCENDA_TOOL_TYPE ?? "claude_code",
2901
4526
  // Concurrent sessions must count as separate streams for the X gauge.
2902
4527
  // Without a session id every window collapses into one, so fall back to
2903
4528
  // this process's parent — still per-session in practice, since Claude
2904
4529
  // 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}`,
4530
+ session: (0, import_tool_kit9.getString)(input, ["session_id", "sessionId"]) ?? process.env.ASCENDA_SESSION_ID ?? `ppid-${process.ppid}`,
2906
4531
  event,
2907
- ...prompt !== void 0 ? { sizeBucket: (0, import_tool_kit8.bucketPromptSize)(prompt) } : {},
4532
+ ...prompt !== void 0 ? { sizeBucket: (0, import_tool_kit9.bucketPromptSize)(prompt) } : {},
2908
4533
  ...queued !== void 0 ? { queued } : {}
2909
4534
  });
2910
4535
  } catch {
@@ -2913,11 +4538,15 @@ async function emitLive(hookName, input) {
2913
4538
  function pendingFailureNotice(hookName) {
2914
4539
  if (hookName !== "SessionStart" && hookName !== "PostToolUse") return void 0;
2915
4540
  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;
4541
+ let toolInstallationId;
4542
+ try {
4543
+ toolInstallationId = resolveToolInstallationId().toolInstallationId;
4544
+ } catch {
4545
+ return void 0;
4546
+ }
4547
+ const stateFilePath = resolveStateFilePath(toolInstallationId);
4548
+ const state = (0, import_tool_kit9.readCollectorState)(stateFilePath);
4549
+ if (!(0, import_tool_kit9.shouldAnnounceFailure)(state) || !state) return void 0;
2921
4550
  const since = state.lastSuccessAt ? `since ${state.lastSuccessAt}` : "and has never succeeded on this machine";
2922
4551
  return {
2923
4552
  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 +4565,8 @@ function describeOutcome(state) {
2936
4565
  return `the events were refused as invalid${status}`;
2937
4566
  case "transport_error":
2938
4567
  return `the ingest endpoint could not be reached${status}`;
4568
+ case "outbox_discarded":
4569
+ return `the outbox overflowed and ${state.outboxDiscarded?.lastCount ?? "some"} queued events were discarded`;
2939
4570
  default:
2940
4571
  return `last outcome ${state.lastOutcome}${status}`;
2941
4572
  }
@@ -2947,23 +4578,28 @@ function writeStdout(text) {
2947
4578
  }
2948
4579
  async function runDoctor() {
2949
4580
  const lines = ["Ascenda collector doctor", ""];
2950
- const rawId = process.env.ASCENDA_TOOL_INSTALLATION_ID?.trim();
2951
4581
  const apiBaseUrl = (process.env.ASCENDA_API_BASE_URL ?? "https://api.ascenda.one").replace(/\/$/, "");
2952
4582
  lines.push(` API base URL ${apiBaseUrl}`);
2953
- lines.push(` Installation id ${rawId || "(unset \u2014 ASCENDA_TOOL_INSTALLATION_ID is empty)"}`);
2954
- if (!rawId) {
4583
+ let resolved;
4584
+ try {
4585
+ resolved = resolveToolInstallationId();
4586
+ } catch (error) {
4587
+ lines.push(` Installation id (unresolved \u2014 ${error instanceof Error ? error.message : String(error)})`);
4588
+ lines.push(...skippedSendLines(void 0));
2955
4589
  lines.push("", " Not paired on this machine. Run:", " npx @ascenda-one/claude-code-hooks pair");
2956
4590
  await writeStdout(`${lines.join("\n")}
2957
4591
  `);
2958
4592
  return;
2959
4593
  }
2960
- const toolInstallationId = normalizeToolInstallationId(rawId);
2961
- const tokenFilePath = process.env.ASCENDA_EVENT_WRITE_TOKEN_FILE ?? (0, import_tool_kit8.defaultTokenFilePath)(toolInstallationId);
4594
+ const { toolInstallationId } = resolved;
4595
+ lines.push(` Installation id ${toolInstallationId}`);
4596
+ lines.push(` Id source ${describeIdSource(resolved)}`);
4597
+ const tokenFilePath = process.env.ASCENDA_EVENT_WRITE_TOKEN_FILE ?? (0, import_tool_kit9.defaultTokenFilePath)(toolInstallationId);
2962
4598
  lines.push(` Token file ${tokenFilePath}`);
2963
4599
  lines.push(` Token ${describeToken(tokenFilePath)}`);
2964
4600
  const stateFilePath = resolveStateFilePath(toolInstallationId);
2965
4601
  lines.push(` Journal ${stateFilePath}`);
2966
- const state = (0, import_tool_kit8.readCollectorState)(stateFilePath);
4602
+ const state = (0, import_tool_kit9.readCollectorState)(stateFilePath);
2967
4603
  if (!state) {
2968
4604
  lines.push(" Last outcome (no journal yet \u2014 no send attempted since this version was installed)");
2969
4605
  } else {
@@ -2975,6 +4611,8 @@ async function runDoctor() {
2975
4611
  lines.push(` Consecutive failures ${state.consecutiveFailures}`);
2976
4612
  if (state.failingSince) lines.push(` Failing since ${state.failingSince}`);
2977
4613
  }
4614
+ lines.push(...skippedSendLines(stateFilePath));
4615
+ lines.push(...outboxLines(toolInstallationId, state));
2978
4616
  lines.push("", " Live round trip...");
2979
4617
  lines.push(` ${await liveRoundTrip()}`);
2980
4618
  await writeStdout(`${lines.join("\n")}
@@ -2991,12 +4629,65 @@ async function liveRoundTrip() {
2991
4629
  if (result === "accepted") return "OK \u2014 event accepted by the ingest endpoint.";
2992
4630
  return `FAILED \u2014 ${explainRejection(result)}`;
2993
4631
  }
4632
+ function describeIdSource(resolved) {
4633
+ switch (resolved.source) {
4634
+ case "env":
4635
+ return "env (ASCENDA_TOOL_INSTALLATION_ID)";
4636
+ case "credentials":
4637
+ return "credentials file (~/.ascenda/credentials.json)";
4638
+ case "disk":
4639
+ return `disk (token file ${(0, import_tool_kit9.defaultTokenFilePath)(resolved.toolInstallationId)})`;
4640
+ }
4641
+ }
4642
+ function skippedSendLines(alreadyShown) {
4643
+ const stateFilePath = resolveStateFilePath();
4644
+ if (stateFilePath === alreadyShown) return [];
4645
+ const state = (0, import_tool_kit9.readCollectorState)(stateFilePath);
4646
+ if (!state) return [];
4647
+ const since = state.failingSince ? ` since ${state.failingSince}` : "";
4648
+ return [
4649
+ ` Skipped sends ${state.consecutiveFailures}${since} \u2014 no installation id could be resolved (last ${state.lastAttemptAt})`,
4650
+ ...state.detail ? [` Skipped because ${state.detail}`] : [],
4651
+ ` Skipped-send journal ${stateFilePath}`
4652
+ ];
4653
+ }
4654
+ function outboxLines(toolInstallationId, state) {
4655
+ const outboxFilePath = resolveOutboxFilePath(toolInstallationId);
4656
+ const lines = [` Outbox ${outboxFilePath}`];
4657
+ const summary = (0, import_tool_kit9.readOutboxSummary)(outboxFilePath);
4658
+ if (!summary || summary.depth === 0) {
4659
+ lines.push(" Outbox depth 0 (nothing waiting)");
4660
+ } else {
4661
+ const oldest = summary.oldestQueuedAt ? ` \u2014 oldest queued ${summary.oldestQueuedAt} (${describeAge(summary.oldestQueuedAt)} ago)` : "";
4662
+ lines.push(` Outbox depth ${summary.depth} waiting${oldest}`);
4663
+ }
4664
+ if (summary && summary.unreadableLines > 0) {
4665
+ lines.push(` Outbox unreadable ${summary.unreadableLines} line(s) did not parse \u2014 discarded and journaled on the next hook`);
4666
+ }
4667
+ 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}`);
4668
+ const discarded = state?.outboxDiscarded;
4669
+ if (discarded) {
4670
+ const reasons = Object.entries(discarded.lastReasons).map(([reason, count]) => `${count} ${reason}`).join(", ");
4671
+ const reach = discarded.lastOldestQueuedAt ? `, reaching back to ${discarded.lastOldestQueuedAt}` : "";
4672
+ lines.push(` Outbox discarded ${discarded.total} total; last ${discarded.lastCount} at ${discarded.lastAt} (${reasons}${reach})`);
4673
+ }
4674
+ return lines;
4675
+ }
4676
+ function describeAge(isoTimestamp) {
4677
+ const ms = Date.now() - Date.parse(isoTimestamp);
4678
+ if (!Number.isFinite(ms) || ms < 0) return "0m";
4679
+ const minutes = Math.floor(ms / 6e4);
4680
+ if (minutes < 60) return `${minutes}m`;
4681
+ const hours = Math.floor(minutes / 60);
4682
+ if (hours < 48) return `${hours}h ${minutes % 60}m`;
4683
+ return `${Math.floor(hours / 24)}d ${hours % 24}h`;
4684
+ }
2994
4685
  function describeToken(tokenFilePath) {
2995
4686
  try {
2996
- if (!fs3.existsSync(tokenFilePath)) {
4687
+ if (!fs2.existsSync(tokenFilePath)) {
2997
4688
  return process.env.ASCENDA_EVENT_WRITE_TOKEN ? "from ASCENDA_EVENT_WRITE_TOKEN (no file)" : "MISSING \u2014 run `pair`";
2998
4689
  }
2999
- const stat = fs3.statSync(tokenFilePath);
4690
+ const stat = fs2.statSync(tokenFilePath);
3000
4691
  const ageDays = Math.floor((Date.now() - stat.mtimeMs) / 864e5);
3001
4692
  return `present, last written ${stat.mtime.toISOString()} (${ageDays}d ago)`;
3002
4693
  } catch (error) {
@@ -3004,14 +4695,14 @@ function describeToken(tokenFilePath) {
3004
4695
  }
3005
4696
  }
3006
4697
  function logUnsent(logFile, event, workContext) {
3007
- const payload = (0, import_tool_kit8.buildEventPayload)({
4698
+ const payload = (0, import_tool_kit9.buildEventPayload)({
3008
4699
  toolInstallationId: `${ASCENDA_TOOL_TYPE}:unpaired`,
3009
4700
  source: "claude_code",
3010
4701
  sessionId: process.env.ASCENDA_SESSION_ID ?? null,
3011
4702
  workspaceHash: envHashOverride("ASCENDA_WORKSPACE_HASH") ?? workContext?.workspaceHash ?? null,
3012
4703
  projectHash: envHashOverride("ASCENDA_PROJECT_HASH") ?? workContext?.projectHash ?? null
3013
4704
  }, event);
3014
- (0, import_tool_kit8.appendEventLog)(logFile, { loggedAt: (/* @__PURE__ */ new Date()).toISOString(), delivery: "not_sent", payload });
4705
+ (0, import_tool_kit9.appendEventLog)(logFile, { loggedAt: (/* @__PURE__ */ new Date()).toISOString(), delivery: "not_sent", payload });
3015
4706
  }
3016
4707
  async function readJsonFromStdin() {
3017
4708
  const chunks = [];