@ascenda-one/claude-code-hooks 0.1.14 → 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
@@ -12,9 +12,16 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
12
12
  if (typeof require !== "undefined") return require.apply(this, arguments);
13
13
  throw Error('Dynamic require of "' + x + '" is not supported');
14
14
  });
15
+ var __esm = (fn, res) => function __init() {
16
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
17
+ };
15
18
  var __commonJS = (cb, mod) => function __require2() {
16
19
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
17
20
  };
21
+ var __export = (target, all) => {
22
+ for (var name in all)
23
+ __defProp(target, name, { get: all[name], enumerable: true });
24
+ };
18
25
  var __copyProps = (to, from, except, desc) => {
19
26
  if (from && typeof from === "object" || typeof from === "function") {
20
27
  for (let key of __getOwnPropNames(from))
@@ -200,6 +207,102 @@ var require_workMilestoneClassifier = __commonJS({
200
207
  }
201
208
  });
202
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
+
203
306
  // ../packages/tool-kit/out/buckets.js
204
307
  var require_buckets = __commonJS({
205
308
  "../packages/tool-kit/out/buckets.js"(exports) {
@@ -294,11 +397,298 @@ var require_afterHours = __commonJS({
294
397
  }
295
398
  });
296
399
 
400
+ // ../packages/tool-contract/out/metricKeys.js
401
+ var require_metricKeys = __commonJS({
402
+ "../packages/tool-contract/out/metricKeys.js"(exports) {
403
+ "use strict";
404
+ Object.defineProperty(exports, "__esModule", { value: true });
405
+ exports.METRIC_KEYS = void 0;
406
+ exports.backendMetricKeys = backendMetricKeys;
407
+ var CONTEXT_WINDOW_CANONICAL_ALIASES = [
408
+ "contextWindowPeakPct",
409
+ "context_window_peak_pct",
410
+ "contextWindowPct",
411
+ "context_window_pct"
412
+ ];
413
+ var CONTEXT_WINDOW_CURSOR_PERCENT_ALIASES = ["contextUsagePercent"];
414
+ exports.METRIC_KEYS = {
415
+ // ── Read by a backend reader ────────────────────────────────────────────
416
+ contextWindowPeakPct: {
417
+ readBy: ["backend", "handoff"],
418
+ backendAliases: CONTEXT_WINDOW_CANONICAL_ALIASES,
419
+ unit: "fraction of the context window (0\u20131; uncapped for >200k contexts)",
420
+ note: "Claude Code reports a true per-session peak. Cursor reports its composer's last known occupancy under the same key \u2014 the closest its store can answer, and not the same measurement."
421
+ },
422
+ contextUsagePercent: {
423
+ readBy: ["backend", "handoff"],
424
+ backendAliases: CONTEXT_WINDOW_CURSOR_PERCENT_ALIASES,
425
+ unit: "percent (0\u2013100)",
426
+ note: "Cursor's own column name. Superseded by contextWindowPeakPct on the wire; kept because the handoff reads it and imported rows carry it. Unit-explicit on the backend: always divided by 100, never put through the fraction-or-percent heuristic."
427
+ },
428
+ promptCount: { readBy: ["backend", "handoff"], backendAliases: ["promptCount", "prompt_count"] },
429
+ sessionMinutes: { readBy: ["backend"], backendAliases: ["sessionMinutes", "session_minutes"], unit: "minutes" },
430
+ durationBucket: { readBy: ["backend", "handoff"], backendAliases: ["durationBucket", "duration_bucket"] },
431
+ afterHoursPrompts: { readBy: ["backend", "handoff"], backendAliases: ["afterHoursPrompts", "after_hours_prompts"] },
432
+ inputTokens: { readBy: ["backend"], backendAliases: ["inputTokens", "input_tokens"], unit: "tokens" },
433
+ outputTokens: { readBy: ["backend"], backendAliases: ["outputTokens", "output_tokens"], unit: "tokens" },
434
+ cacheReadTokens: { readBy: ["backend"], backendAliases: ["cacheReadTokens", "cache_read_tokens"], unit: "tokens" },
435
+ queuedPrompts: { readBy: ["backend"], backendAliases: ["queuedPrompts", "queued_prompts"] },
436
+ linesChangedBucket: { readBy: ["backend"], backendAliases: ["linesChangedBucket", "lines_changed_bucket"] },
437
+ // ── Read by the local handoff only ──────────────────────────────────────
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
+ },
475
+ afterHoursRequests: { readBy: ["handoff"] },
476
+ approximateLintErrorsCount: { readBy: ["handoff"] },
477
+ canceledCount: { readBy: ["handoff"] },
478
+ chatEditCount: { readBy: ["handoff"] },
479
+ compactionCount: {
480
+ readBy: ["handoff"],
481
+ note: "The backend counts context_compression_* event rows, not this key. Both are emitted; this one is for the handoff."
482
+ },
483
+ contextWindowPeakTokens: {
484
+ readBy: ["handoff"],
485
+ unit: "tokens",
486
+ note: "The measured quantity, with no assumed denominator. Prefer this to the ratio for any within-person baseline."
487
+ },
488
+ date: { readBy: ["handoff"] },
489
+ errorCount: { readBy: ["handoff"] },
490
+ filesChangedCount: { readBy: ["handoff"] },
491
+ humanChangesCount: { readBy: ["handoff"] },
492
+ linesAdded: { readBy: ["handoff"] },
493
+ linesRemoved: { readBy: ["handoff"] },
494
+ primaryModel: { readBy: ["handoff"] },
495
+ requestCount: { readBy: ["handoff"] },
496
+ sessionStartedAt: { readBy: ["handoff"] },
497
+ subagentComposers: { readBy: ["handoff"] },
498
+ subagentToolCallCount: {
499
+ readBy: ["handoff"],
500
+ note: "Claude Code only: calls made inside subagent transcripts, kept out of toolCallCount so the main-loop count matches what the wire events carry."
501
+ },
502
+ subagentTranscripts: { readBy: ["handoff"] },
503
+ toolCallCount: {
504
+ readBy: ["handoff"],
505
+ note: "The backend counts ai_tool_call_started event rows, not this key \u2014 same split as compactionCount. Deduplicated on the tool-call id; see each extractor for what one call means in its store."
506
+ },
507
+ toolCallsUndated: {
508
+ readBy: ["handoff"],
509
+ note: "Cursor only: calls whose every record carries an empty createdAt. Counted in toolCallCount, but no event exists for them \u2014 the wire total is smaller than this session count by exactly this number."
510
+ },
511
+ toolFailureCount: { readBy: ["handoff"] },
512
+ totalEntryCount: { readBy: ["handoff"] },
513
+ userModifiedEditCount: {
514
+ readBy: ["handoff"],
515
+ note: "Null, never 0 \u2014 Claude Code never sets userModified true, so 0 would assert 'no AI edit was ever corrected by hand'."
516
+ },
517
+ // ── Diagnostic: read by nobody, on purpose ──────────────────────────────
518
+ abandonedPromptCount: { readBy: ["diagnostic"] },
519
+ // Epoch-marker metrics. The marker is local-only and never reaches the wire
520
+ // (see EXTRACTION_EPOCH_KIND), but it travels as a NormalizedHistoricalEvent
521
+ // and so is keyed by the same vocabulary.
522
+ windowOldest: { readBy: ["handoff"], note: "Oldest event the extraction saw \u2014 the marker's left edge." },
523
+ windowNewest: { readBy: ["handoff"], note: "Newest event the extraction saw \u2014 the marker's right edge." },
524
+ projectsWithNoReadableTranscript: { readBy: ["diagnostic"] },
525
+ unparsedComposerHeaders: { readBy: ["diagnostic"] },
526
+ unknownComposerHeaderTypes: { readBy: ["diagnostic"] },
527
+ orphanedBubbles: { readBy: ["diagnostic"] },
528
+ orphanedSubagentBubbles: { readBy: ["diagnostic"] },
529
+ sessionsWithoutTimeline: { readBy: ["diagnostic"] },
530
+ emptyComposers: { readBy: ["diagnostic"] },
531
+ apiErrorCount: { readBy: ["diagnostic"] },
532
+ assistantTurns: { readBy: ["diagnostic"] },
533
+ compactionAutoCount: { readBy: ["diagnostic"] },
534
+ compactionManualCount: { readBy: ["diagnostic"] },
535
+ editDayCount: { readBy: ["diagnostic"] },
536
+ emptyChatSessions: { readBy: ["diagnostic"] },
537
+ gitBranch: { readBy: ["diagnostic"] },
538
+ linesChanged: { readBy: ["diagnostic"] },
539
+ malformedChatSessionLines: { readBy: ["diagnostic"] },
540
+ malformedHistoryEntries: { readBy: ["diagnostic"] },
541
+ mode: { readBy: ["diagnostic"] },
542
+ modelCount: { readBy: ["diagnostic"] },
543
+ modelSwitchCount: { readBy: ["diagnostic"] },
544
+ rapidRepromptCount: { readBy: ["diagnostic"] },
545
+ schemaUnreadable: { readBy: ["diagnostic"] },
546
+ sessionCount: { readBy: ["diagnostic"] },
547
+ sessionsFromBubbleTimeline: { readBy: ["diagnostic"] },
548
+ sessionsFromCheckpointTimeline: { readBy: ["diagnostic"] },
549
+ sessionsFromRecencyTimeline: { readBy: ["diagnostic"] },
550
+ subagentAssistantTurns: { readBy: ["diagnostic"] },
551
+ subagentPrompts: { readBy: ["diagnostic"] },
552
+ subagentTokensTotal: { readBy: ["diagnostic"] },
553
+ toolName: {
554
+ readBy: ["diagnostic"],
555
+ note: "Set per ai_tool_call_started event by #43's extractors and shipped in wire metadata, but no reader resolves it server-side yet (the backend's ToolName column is MCP audit, not telemetry). Registered after the fact: #38 and #43 merged past each other, and the union caught it on the next compile \u2014 metaLines all over again."
556
+ },
557
+ toolResultCount: { readBy: ["diagnostic"] },
558
+ toolResultErrorCount: { readBy: ["diagnostic"] },
559
+ unknownBubbles: { readBy: ["diagnostic"] },
560
+ unknownLines: { readBy: ["diagnostic"] },
561
+ metaLines: {
562
+ readBy: ["diagnostic"],
563
+ note: 'Recognised-but-skipped transcript machinery (file-history-snapshot, queued-command, \u2026). Split out of unknownLines by #43 so that number keeps meaning "a type nobody has looked at". Registered here after the fact: #41 and #43 merged past each other, and the union caught it on the next compile \u2014 which is this module doing its job.'
564
+ },
565
+ unparsedBubbles: { readBy: ["diagnostic"] },
566
+ unparsedChatSessionFiles: { readBy: ["diagnostic"] },
567
+ unparsedHistoryFiles: { readBy: ["diagnostic"] },
568
+ unparsedLines: { readBy: ["diagnostic"] },
569
+ unreadableChatSessionFiles: { readBy: ["diagnostic"] },
570
+ unreadableHistoryFiles: { readBy: ["diagnostic"] },
571
+ unrecognisedChatSessionFiles: { readBy: ["diagnostic"] }
572
+ };
573
+ function backendMetricKeys() {
574
+ return Object.entries(exports.METRIC_KEYS).filter(([, spec]) => spec.readBy.includes("backend")).map(([key, spec]) => [key, spec.backendAliases ?? [key]]);
575
+ }
576
+ }
577
+ });
578
+
579
+ // ../packages/tool-contract/out/index.js
580
+ var require_out = __commonJS({
581
+ "../packages/tool-contract/out/index.js"(exports) {
582
+ "use strict";
583
+ Object.defineProperty(exports, "__esModule", { value: true });
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;
585
+ exports.SEMANTIC_WORK_SIGNAL_EVENT_TYPES = [
586
+ "approach_churn_detected",
587
+ "goal_drift_detected",
588
+ "progress_stalled",
589
+ "progress_recovered",
590
+ "session_intention_declared",
591
+ "scope_change_declared"
592
+ ];
593
+ exports.COLLABORATION_EVENT_TYPES = [
594
+ "review_requested_of_me",
595
+ "review_given",
596
+ "pull_request_opened"
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"];
631
+ exports.EVENT_WORKLOAD_CATEGORY = {
632
+ create_focus_session: "creation",
633
+ ai_prompt_submitted: "creation",
634
+ ai_generation_completed: "creation",
635
+ ai_file_write: "creation",
636
+ ai_file_edit: "creation",
637
+ editor_verification_activity: "verification",
638
+ compile_diagnostic: "verification",
639
+ editor_correction_activity: "supervision",
640
+ ai_correction_prompt: "supervision",
641
+ supervis_meeting_load: "supervision",
642
+ ai_tool_call_started: "supervision",
643
+ ai_tool_call_completed: "supervision",
644
+ ai_tool_call_failed: "supervision",
645
+ // Collaboration (the report's §4.2 collaboration family). Both review
646
+ // events are supervision: being asked to check work, and checking it, are
647
+ // the load the report's "verification overload" concern is about — the one
648
+ // that concentrates on senior engineers as a team adopts AI. Opening a pull
649
+ // request is creation: it is the point your own work leaves your hands.
650
+ review_requested_of_me: "supervision",
651
+ review_given: "supervision",
652
+ pull_request_opened: "creation",
653
+ context_pressure_high: "risk",
654
+ agent_loop_long: "risk",
655
+ after_hours_ai_session: "risk",
656
+ compile_error: "risk",
657
+ tool_failure: "risk",
658
+ recovery_offline_period: "neutral",
659
+ context_compression_manual: "neutral",
660
+ context_compression_auto: "neutral",
661
+ editor_activity: "neutral",
662
+ // Semantic (agent-observed) — see SEMANTIC_WORK_SIGNAL_EVENT_TYPES.
663
+ approach_churn_detected: "risk",
664
+ goal_drift_detected: "risk",
665
+ progress_stalled: "risk",
666
+ progress_recovered: "neutral",
667
+ session_intention_declared: "neutral",
668
+ scope_change_declared: "neutral"
669
+ };
670
+ exports.ASCENDA_CONSENT_SCOPE = "ide_telemetry";
671
+ exports.ASCENDA_PROVENANCE = "ai_work_telemetry";
672
+ exports.ASCENDA_SEMANTIC_CONSENT_SCOPE = "semantic_work_signals";
673
+ exports.ASCENDA_COLLABORATION_CONSENT_SCOPE = "workflow_telemetry";
674
+ exports.ASCENDA_HISTORICAL_CONSENT_SCOPE = "historical_import";
675
+ exports.ASCENDA_SEMANTIC_PROVENANCE = "semantic_work_signals";
676
+ var metricKeys_1 = require_metricKeys();
677
+ Object.defineProperty(exports, "METRIC_KEYS", { enumerable: true, get: function() {
678
+ return metricKeys_1.METRIC_KEYS;
679
+ } });
680
+ Object.defineProperty(exports, "backendMetricKeys", { enumerable: true, get: function() {
681
+ return metricKeys_1.backendMetricKeys;
682
+ } });
683
+ }
684
+ });
685
+
297
686
  // ../packages/tool-kit/out/payload.js
298
687
  var require_payload = __commonJS({
299
688
  "../packages/tool-kit/out/payload.js"(exports) {
300
689
  "use strict";
301
690
  Object.defineProperty(exports, "__esModule", { value: true });
691
+ exports.mintIdempotencyKey = mintIdempotencyKey;
302
692
  exports.getString = getString3;
303
693
  exports.getNumber = getNumber2;
304
694
  exports.getNested = getNested2;
@@ -307,6 +697,14 @@ var require_payload = __commonJS({
307
697
  exports.inferOutcome = inferOutcome2;
308
698
  exports.outcomeForHook = outcomeForHook2;
309
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
+ }
310
708
  function getString3(input, keys) {
311
709
  for (const key of keys) {
312
710
  const value = input[key];
@@ -323,9 +721,9 @@ var require_payload = __commonJS({
323
721
  }
324
722
  return void 0;
325
723
  }
326
- function getNested2(input, path) {
724
+ function getNested2(input, path3) {
327
725
  let current = input;
328
- for (const segment of path) {
726
+ for (const segment of path3) {
329
727
  if (!current || typeof current !== "object")
330
728
  return void 0;
331
729
  current = current[segment];
@@ -333,16 +731,16 @@ var require_payload = __commonJS({
333
731
  return current;
334
732
  }
335
733
  function getNestedString3(input, paths) {
336
- for (const path of paths) {
337
- const value = getNested2(input, path);
734
+ for (const path3 of paths) {
735
+ const value = getNested2(input, path3);
338
736
  if (typeof value === "string" && value.trim())
339
737
  return value;
340
738
  }
341
739
  return void 0;
342
740
  }
343
741
  function getNestedNumber2(input, paths) {
344
- for (const path of paths) {
345
- const value = getNested2(input, path);
742
+ for (const path3 of paths) {
743
+ const value = getNested2(input, path3);
346
744
  if (typeof value === "number" && Number.isFinite(value))
347
745
  return value;
348
746
  }
@@ -377,73 +775,6 @@ var require_payload = __commonJS({
377
775
  }
378
776
  });
379
777
 
380
- // ../packages/tool-contract/out/index.js
381
- var require_out = __commonJS({
382
- "../packages/tool-contract/out/index.js"(exports) {
383
- "use strict";
384
- Object.defineProperty(exports, "__esModule", { value: true });
385
- 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;
386
- exports.SEMANTIC_WORK_SIGNAL_EVENT_TYPES = [
387
- "approach_churn_detected",
388
- "goal_drift_detected",
389
- "progress_stalled",
390
- "progress_recovered",
391
- "session_intention_declared",
392
- "scope_change_declared"
393
- ];
394
- exports.COLLABORATION_EVENT_TYPES = [
395
- "review_requested_of_me",
396
- "review_given",
397
- "pull_request_opened"
398
- ];
399
- exports.EVENT_WORKLOAD_CATEGORY = {
400
- create_focus_session: "creation",
401
- ai_prompt_submitted: "creation",
402
- ai_generation_completed: "creation",
403
- ai_file_write: "creation",
404
- ai_file_edit: "creation",
405
- editor_verification_activity: "verification",
406
- compile_diagnostic: "verification",
407
- editor_correction_activity: "supervision",
408
- ai_correction_prompt: "supervision",
409
- supervis_meeting_load: "supervision",
410
- ai_tool_call_started: "supervision",
411
- ai_tool_call_completed: "supervision",
412
- ai_tool_call_failed: "supervision",
413
- // Collaboration (the report's §4.2 collaboration family). Both review
414
- // events are supervision: being asked to check work, and checking it, are
415
- // the load the report's "verification overload" concern is about — the one
416
- // that concentrates on senior engineers as a team adopts AI. Opening a pull
417
- // request is creation: it is the point your own work leaves your hands.
418
- review_requested_of_me: "supervision",
419
- review_given: "supervision",
420
- pull_request_opened: "creation",
421
- context_pressure_high: "risk",
422
- agent_loop_long: "risk",
423
- after_hours_ai_session: "risk",
424
- compile_error: "risk",
425
- tool_failure: "risk",
426
- recovery_offline_period: "neutral",
427
- context_compression_manual: "neutral",
428
- context_compression_auto: "neutral",
429
- editor_activity: "neutral",
430
- // Semantic (agent-observed) — see SEMANTIC_WORK_SIGNAL_EVENT_TYPES.
431
- approach_churn_detected: "risk",
432
- goal_drift_detected: "risk",
433
- progress_stalled: "risk",
434
- progress_recovered: "neutral",
435
- session_intention_declared: "neutral",
436
- scope_change_declared: "neutral"
437
- };
438
- exports.ASCENDA_CONSENT_SCOPE = "ide_telemetry";
439
- exports.ASCENDA_PROVENANCE = "ai_work_telemetry";
440
- exports.ASCENDA_SEMANTIC_CONSENT_SCOPE = "semantic_work_signals";
441
- exports.ASCENDA_COLLABORATION_CONSENT_SCOPE = "workflow_telemetry";
442
- exports.ASCENDA_HISTORICAL_CONSENT_SCOPE = "historical_import";
443
- exports.ASCENDA_SEMANTIC_PROVENANCE = "semantic_work_signals";
444
- }
445
- });
446
-
447
778
  // ../packages/tool-kit/out/eventLog.js
448
779
  var require_eventLog = __commonJS({
449
780
  "../packages/tool-kit/out/eventLog.js"(exports) {
@@ -490,9 +821,9 @@ var require_eventLog = __commonJS({
490
821
  exports.expandUserPath = expandUserPath;
491
822
  exports.resolveEventLogPath = resolveEventLogPath2;
492
823
  exports.appendEventLog = appendEventLog2;
493
- var fs2 = __importStar(__require("fs"));
494
- var os = __importStar(__require("os"));
495
- var path = __importStar(__require("path"));
824
+ var fs3 = __importStar(__require("fs"));
825
+ var os2 = __importStar(__require("os"));
826
+ var path3 = __importStar(__require("path"));
496
827
  exports.EVENT_LOG_ENV_VAR = "ASCENDA_EVENT_LOG_FILE";
497
828
  var MAX_BYTES = 5 * 1024 * 1024;
498
829
  function expandUserPath(configured) {
@@ -500,10 +831,10 @@ var require_eventLog = __commonJS({
500
831
  if (!value)
501
832
  return void 0;
502
833
  if (value === "~")
503
- return os.homedir();
834
+ return os2.homedir();
504
835
  if (value.startsWith("~/"))
505
- return path.join(os.homedir(), value.slice(2));
506
- return path.resolve(value);
836
+ return path3.join(os2.homedir(), value.slice(2));
837
+ return path3.resolve(value);
507
838
  }
508
839
  function resolveEventLogPath2() {
509
840
  return expandUserPath(process.env[exports.EVENT_LOG_ENV_VAR]);
@@ -511,20 +842,20 @@ var require_eventLog = __commonJS({
511
842
  function appendEventLog2(logFilePath, entry) {
512
843
  try {
513
844
  rotateIfLarge(logFilePath);
514
- const dir = path.dirname(logFilePath);
515
- fs2.mkdirSync(dir, { recursive: true, mode: 448 });
516
- fs2.appendFileSync(logFilePath, `${JSON.stringify(entry)}
845
+ const dir = path3.dirname(logFilePath);
846
+ fs3.mkdirSync(dir, { recursive: true, mode: 448 });
847
+ fs3.appendFileSync(logFilePath, `${JSON.stringify(entry)}
517
848
  `, { encoding: "utf8", mode: 384 });
518
849
  if (process.platform !== "win32")
519
- fs2.chmodSync(logFilePath, 384);
850
+ fs3.chmodSync(logFilePath, 384);
520
851
  } catch {
521
852
  }
522
853
  }
523
854
  function rotateIfLarge(logFilePath) {
524
855
  try {
525
- if (fs2.statSync(logFilePath).size < MAX_BYTES)
856
+ if (fs3.statSync(logFilePath).size < MAX_BYTES)
526
857
  return;
527
- fs2.renameSync(logFilePath, `${logFilePath}.1`);
858
+ fs3.renameSync(logFilePath, `${logFilePath}.1`);
528
859
  } catch {
529
860
  }
530
861
  }
@@ -537,13 +868,14 @@ var require_http = __commonJS({
537
868
  "use strict";
538
869
  Object.defineProperty(exports, "__esModule", { value: true });
539
870
  exports.AscendaApiError = void 0;
540
- exports.createPairingSession = createPairingSession2;
541
- exports.getPairingStatus = getPairingStatus2;
871
+ exports.createPairingSession = createPairingSession3;
872
+ exports.getPairingStatus = getPairingStatus3;
542
873
  exports.renewToolToken = renewToolToken;
543
874
  exports.isRetryableStatus = isRetryableStatus;
544
875
  exports.postToolEvent = postToolEvent;
545
876
  exports.postToolEventsBatch = postToolEventsBatch;
546
877
  exports.parseIngestResponse = parseIngestResponse;
878
+ var tool_contract_1 = require_out();
547
879
  var AscendaApiError2 = class extends Error {
548
880
  status;
549
881
  errorCode;
@@ -555,7 +887,7 @@ var require_http = __commonJS({
555
887
  }
556
888
  };
557
889
  exports.AscendaApiError = AscendaApiError2;
558
- async function createPairingSession2(apiBaseUrl, toolInstallationId, toolType, displayName) {
890
+ async function createPairingSession3(apiBaseUrl, toolInstallationId, toolType, displayName) {
559
891
  const response = await fetch(`${apiBaseUrl}/v1/tool-pairing-sessions`, {
560
892
  method: "POST",
561
893
  headers: { "Content-Type": "application/json" },
@@ -565,7 +897,7 @@ var require_http = __commonJS({
565
897
  throw new AscendaApiError2(response.status, void 0, await response.text());
566
898
  return await response.json();
567
899
  }
568
- async function getPairingStatus2(apiBaseUrl, pairingSessionId) {
900
+ async function getPairingStatus3(apiBaseUrl, pairingSessionId) {
569
901
  const response = await fetch(`${apiBaseUrl}/v1/tool-pairing-sessions/${encodeURIComponent(pairingSessionId)}/status`, {
570
902
  method: "GET",
571
903
  headers: { Accept: "application/json" }
@@ -586,6 +918,35 @@ var require_http = __commonJS({
586
918
  throw new AscendaApiError2(response.status, void 0, await response.text());
587
919
  return await response.json();
588
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
+ }
589
950
  function isRetryableStatus(status) {
590
951
  return status === 408 || status === 429 || status !== void 0 && status >= 500 && status <= 599;
591
952
  }
@@ -612,8 +973,20 @@ var require_http = __commonJS({
612
973
  }
613
974
  }
614
975
  async function parseIngestResponse(response) {
615
- if (response.ok)
616
- 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
+ }
617
990
  const body = await response.text();
618
991
  let errorCode;
619
992
  try {
@@ -675,30 +1048,61 @@ var require_tokenStore = __commonJS({
675
1048
  };
676
1049
  }();
677
1050
  Object.defineProperty(exports, "__esModule", { value: true });
678
- exports.defaultTokenFilePath = defaultTokenFilePath3;
679
- exports.persistEventWriteToken = persistEventWriteToken3;
680
- exports.readTokenFile = readTokenFile2;
1051
+ exports.ascendaHome = ascendaHome3;
1052
+ exports.defaultTokenFilePath = defaultTokenFilePath4;
1053
+ exports.persistEventWriteToken = persistEventWriteToken4;
1054
+ exports.listPersistedToolInstallationIds = listPersistedToolInstallationIds2;
1055
+ exports.readTokenFile = readTokenFile3;
681
1056
  exports.sanitizeFilePart = sanitizeFilePart;
682
- var fs2 = __importStar(__require("fs"));
683
- var os = __importStar(__require("os"));
684
- var path = __importStar(__require("path"));
685
- function defaultTokenFilePath3(toolInstallationId) {
686
- return path.join(os.homedir(), ".ascenda", "tokens", sanitizeFilePart(toolInstallationId));
687
- }
688
- function persistEventWriteToken3(tokenFilePath, token) {
689
- const dir = path.dirname(tokenFilePath);
690
- fs2.mkdirSync(dir, { recursive: true, mode: 448 });
691
- fs2.writeFileSync(tokenFilePath, token, { encoding: "utf8", mode: 384 });
1057
+ var fs3 = __importStar(__require("fs"));
1058
+ var os2 = __importStar(__require("os"));
1059
+ var path3 = __importStar(__require("path"));
1060
+ function ascendaHome3() {
1061
+ return process.env.ASCENDA_HOME ?? path3.join(os2.homedir(), ".ascenda");
1062
+ }
1063
+ function defaultTokenFilePath4(toolInstallationId) {
1064
+ return path3.join(ascendaHome3(), "tokens", sanitizeFilePart(toolInstallationId));
1065
+ }
1066
+ function persistEventWriteToken4(tokenFilePath, token) {
1067
+ const dir = path3.dirname(tokenFilePath);
1068
+ fs3.mkdirSync(dir, { recursive: true, mode: 448 });
1069
+ fs3.writeFileSync(tokenFilePath, token, { encoding: "utf8", mode: 384 });
692
1070
  if (process.platform !== "win32") {
693
- fs2.chmodSync(dir, 448);
694
- fs2.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)}`);
695
1098
  }
1099
+ return ids;
696
1100
  }
697
- function readTokenFile2(tokenFilePath) {
1101
+ function readTokenFile3(tokenFilePath) {
698
1102
  try {
699
- if (!fs2.existsSync(tokenFilePath))
1103
+ if (!fs3.existsSync(tokenFilePath))
700
1104
  return void 0;
701
- const value = fs2.readFileSync(tokenFilePath, "utf8").trim();
1105
+ const value = fs3.readFileSync(tokenFilePath, "utf8").trim();
702
1106
  return value || void 0;
703
1107
  } catch {
704
1108
  return void 0;
@@ -753,24 +1157,33 @@ var require_stateStore = __commonJS({
753
1157
  }();
754
1158
  Object.defineProperty(exports, "__esModule", { value: true });
755
1159
  exports.defaultStateFilePath = defaultStateFilePath2;
1160
+ exports.unresolvedToolInstallationId = unresolvedToolInstallationId2;
1161
+ exports.unresolvedStateFilePath = unresolvedStateFilePath2;
756
1162
  exports.readCollectorState = readCollectorState2;
757
- exports.recordSendOutcome = recordSendOutcome;
1163
+ exports.recordSendOutcome = recordSendOutcome2;
1164
+ exports.recordOutboxDiscard = recordOutboxDiscard;
758
1165
  exports.shouldAnnounceFailure = shouldAnnounceFailure2;
759
1166
  exports.markFailureNotified = markFailureNotified2;
760
- var fs2 = __importStar(__require("fs"));
761
- var os = __importStar(__require("os"));
762
- var path = __importStar(__require("path"));
1167
+ var fs3 = __importStar(__require("fs"));
1168
+ var os2 = __importStar(__require("os"));
1169
+ var path3 = __importStar(__require("path"));
763
1170
  var tokenStore_1 = require_tokenStore();
764
1171
  function defaultStateFilePath2(toolInstallationId) {
765
1172
  const dir = process.env.ASCENDA_STATE_DIR?.trim();
766
- const base = dir ? dir : path.join(os.homedir(), ".ascenda", "state");
767
- return path.join(base, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.json`);
1173
+ const base = dir ? dir : path3.join(os2.homedir(), ".ascenda", "state");
1174
+ return path3.join(base, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.json`);
1175
+ }
1176
+ function unresolvedToolInstallationId2(toolType) {
1177
+ return `${toolType}:unresolved`;
1178
+ }
1179
+ function unresolvedStateFilePath2(toolType) {
1180
+ return defaultStateFilePath2(unresolvedToolInstallationId2(toolType));
768
1181
  }
769
1182
  function readCollectorState2(stateFilePath) {
770
1183
  try {
771
- if (!fs2.existsSync(stateFilePath))
1184
+ if (!fs3.existsSync(stateFilePath))
772
1185
  return void 0;
773
- const raw = fs2.readFileSync(stateFilePath, "utf8").trim();
1186
+ const raw = fs3.readFileSync(stateFilePath, "utf8").trim();
774
1187
  if (!raw)
775
1188
  return void 0;
776
1189
  const parsed = JSON.parse(raw);
@@ -781,7 +1194,7 @@ var require_stateStore = __commonJS({
781
1194
  return void 0;
782
1195
  }
783
1196
  }
784
- function recordSendOutcome(stateFilePath, toolInstallationId, outcome, detail = {}) {
1197
+ function recordSendOutcome2(stateFilePath, toolInstallationId, outcome, detail = {}) {
785
1198
  const now = (/* @__PURE__ */ new Date()).toISOString();
786
1199
  const previous = readCollectorState2(stateFilePath);
787
1200
  const accepted = outcome === "accepted";
@@ -798,7 +1211,28 @@ var require_stateStore = __commonJS({
798
1211
  // the one already open. Carrying `notifiedFailingSince` across a
799
1212
  // continuing episode is what keeps the notice to once per outage.
800
1213
  ...accepted ? {} : { failingSince: previous?.failingSince ?? now },
801
- ...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
+ }
802
1236
  };
803
1237
  writeStateFile(stateFilePath, next);
804
1238
  return next;
@@ -816,17 +1250,17 @@ var require_stateStore = __commonJS({
816
1250
  function writeStateFile(stateFilePath, state) {
817
1251
  const temporaryPath = `${stateFilePath}.${process.pid}.tmp`;
818
1252
  try {
819
- const dir = path.dirname(stateFilePath);
820
- fs2.mkdirSync(dir, { recursive: true, mode: 448 });
821
- fs2.writeFileSync(temporaryPath, `${JSON.stringify(state, null, 2)}
1253
+ const dir = path3.dirname(stateFilePath);
1254
+ fs3.mkdirSync(dir, { recursive: true, mode: 448 });
1255
+ fs3.writeFileSync(temporaryPath, `${JSON.stringify(state, null, 2)}
822
1256
  `, { encoding: "utf8", mode: 384 });
823
- fs2.renameSync(temporaryPath, stateFilePath);
1257
+ fs3.renameSync(temporaryPath, stateFilePath);
824
1258
  if (process.platform !== "win32")
825
- fs2.chmodSync(stateFilePath, 384);
1259
+ fs3.chmodSync(stateFilePath, 384);
826
1260
  } catch {
827
1261
  try {
828
- if (fs2.existsSync(temporaryPath))
829
- fs2.unlinkSync(temporaryPath);
1262
+ if (fs3.existsSync(temporaryPath))
1263
+ fs3.unlinkSync(temporaryPath);
830
1264
  } catch {
831
1265
  }
832
1266
  }
@@ -838,41 +1272,264 @@ var require_stateStore = __commonJS({
838
1272
  }
839
1273
  });
840
1274
 
841
- // ../packages/tool-kit/out/eventSender.js
842
- var require_eventSender = __commonJS({
843
- "../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) {
844
1278
  "use strict";
845
- Object.defineProperty(exports, "__esModule", { value: true });
846
- exports.AscendaEventSender = exports.AscendaSemanticEventError = void 0;
847
- exports.buildEventPayload = buildEventPayload2;
848
- var afterHours_1 = require_afterHours();
849
- var tool_contract_1 = require_out();
850
- var eventLog_1 = require_eventLog();
851
- var http_1 = require_http();
852
- var tokenStore_1 = require_tokenStore();
853
- var stateStore_1 = require_stateStore();
854
- var AscendaSemanticEventError = class extends Error {
855
- constructor(message) {
856
- super(message);
857
- this.name = "AscendaSemanticEventError";
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
+ } };
858
1286
  }
859
- };
860
- exports.AscendaSemanticEventError = AscendaSemanticEventError;
861
- function buildEventPayload2(identity, mapped) {
862
- return {
863
- toolInstallationId: identity.toolInstallationId,
864
- source: identity.source,
865
- occurredAt: (/* @__PURE__ */ new Date()).toISOString(),
866
- utcOffsetMinutes: (0, afterHours_1.utcOffsetMinutesAt)(/* @__PURE__ */ new Date()),
867
- sessionId: identity.sessionId ?? void 0,
868
- workspaceHash: identity.workspaceHash ?? void 0,
869
- projectHash: identity.projectHash ?? void 0,
870
- consentScope: tool_contract_1.ASCENDA_CONSENT_SCOPE,
871
- provenance: tool_contract_1.ASCENDA_PROVENANCE,
872
- privacyMode: "metadata_only",
873
- ...mapped,
874
- metadata: mapped.metadata ?? {}
875
- };
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();
1507
+ var tokenStore_1 = require_tokenStore();
1508
+ var stateStore_1 = require_stateStore();
1509
+ var payload_1 = require_payload();
1510
+ var AscendaSemanticEventError = class extends Error {
1511
+ constructor(message) {
1512
+ super(message);
1513
+ this.name = "AscendaSemanticEventError";
1514
+ }
1515
+ };
1516
+ exports.AscendaSemanticEventError = AscendaSemanticEventError;
1517
+ function buildEventPayload2(identity, mapped) {
1518
+ return {
1519
+ toolInstallationId: identity.toolInstallationId,
1520
+ source: identity.source,
1521
+ occurredAt: (/* @__PURE__ */ new Date()).toISOString(),
1522
+ idempotencyKey: (0, payload_1.mintIdempotencyKey)(),
1523
+ utcOffsetMinutes: (0, afterHours_1.utcOffsetMinutesAt)(/* @__PURE__ */ new Date()),
1524
+ sessionId: identity.sessionId ?? void 0,
1525
+ workspaceHash: identity.workspaceHash ?? void 0,
1526
+ projectHash: identity.projectHash ?? void 0,
1527
+ consentScope: tool_contract_1.ASCENDA_CONSENT_SCOPE,
1528
+ provenance: tool_contract_1.ASCENDA_PROVENANCE,
1529
+ privacyMode: "metadata_only",
1530
+ ...mapped,
1531
+ metadata: mapped.metadata ?? {}
1532
+ };
876
1533
  }
877
1534
  var DEFAULT_TIMEOUT_MS = 5e3;
878
1535
  var RETRY_DELAY_MS = 250;
@@ -880,6 +1537,9 @@ var require_eventSender = __commonJS({
880
1537
  config;
881
1538
  eventWriteToken;
882
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;
883
1543
  constructor(config) {
884
1544
  this.config = config;
885
1545
  this.eventWriteToken = config.eventWriteToken;
@@ -918,6 +1578,7 @@ var require_eventSender = __commonJS({
918
1578
  source: this.config.source,
919
1579
  eventType: mapped.eventType,
920
1580
  occurredAt: (/* @__PURE__ */ new Date()).toISOString(),
1581
+ idempotencyKey: (0, payload_1.mintIdempotencyKey)(),
921
1582
  utcOffsetMinutes: (0, afterHours_1.utcOffsetMinutesAt)(/* @__PURE__ */ new Date()),
922
1583
  severity: "low",
923
1584
  sessionId: this.config.sessionId ?? void 0,
@@ -948,6 +1609,7 @@ var require_eventSender = __commonJS({
948
1609
  source: this.config.source,
949
1610
  eventType: mapped.eventType,
950
1611
  occurredAt: (/* @__PURE__ */ new Date()).toISOString(),
1612
+ idempotencyKey: (0, payload_1.mintIdempotencyKey)(),
951
1613
  utcOffsetMinutes: (0, afterHours_1.utcOffsetMinutesAt)(/* @__PURE__ */ new Date()),
952
1614
  severity: "low",
953
1615
  sessionId: this.config.sessionId ?? void 0,
@@ -966,15 +1628,30 @@ var require_eventSender = __commonJS({
966
1628
  * deliberate: Claude Code, Codex, the GitHub collector and the MCP server all
967
1629
  * send through this method, and the defect being fixed showed up in three
968
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.
969
1637
  */
970
1638
  async post(payload) {
971
- 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
+ }
972
1649
  this.lastState = (0, stateStore_1.recordSendOutcome)(this.stateFilePath(), this.config.toolInstallationId, outcome.result, {
973
1650
  httpStatus: outcome.httpStatus,
974
1651
  errorCode: outcome.errorCode,
975
- detail: outcome.detail
1652
+ detail: queued ? withNote(outcome.detail, "queued in outbox") : outcome.detail
976
1653
  });
977
- this.log(payload, outcome.result);
1654
+ this.log(payload, outcome.result, queued ? "queued" : void 0);
978
1655
  return outcome.result;
979
1656
  }
980
1657
  /**
@@ -983,6 +1660,15 @@ var require_eventSender = __commonJS({
983
1660
  * error gets one retry, because the common cases (a restarting instance, a
984
1661
  * proxy blip, a 429) clear in well under a second and the alternative is
985
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.
986
1672
  */
987
1673
  async attempt(payload) {
988
1674
  const outcome = await (0, http_1.postToolEvent)(this.config.apiBaseUrl, this.eventWriteToken, payload, this.signal());
@@ -991,12 +1677,138 @@ var require_eventSender = __commonJS({
991
1677
  return outcome;
992
1678
  return (0, http_1.postToolEvent)(this.config.apiBaseUrl, this.eventWriteToken, payload, this.signal());
993
1679
  }
994
- if (outcome.result === "transport_error" && (outcome.httpStatus === void 0 || (0, http_1.isRetryableStatus)(outcome.httpStatus))) {
995
- await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY_MS));
1680
+ if (this.isRetryable(outcome)) {
1681
+ await new Promise((resolve2) => setTimeout(resolve2, RETRY_DELAY_MS));
996
1682
  return (0, http_1.postToolEvent)(this.config.apiBaseUrl, this.eventWriteToken, payload, this.signal());
997
1683
  }
998
1684
  return outcome;
999
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
+ }
1000
1812
  /**
1001
1813
  * The state written by the most recent send, so a caller can decide whether
1002
1814
  * to surface a one-time notice without re-reading the journal it just wrote.
@@ -1004,10 +1816,16 @@ var require_eventSender = __commonJS({
1004
1816
  get state() {
1005
1817
  return this.lastState;
1006
1818
  }
1819
+ /** What this sender's one outbox pass did; undefined before the first send. */
1820
+ get drain() {
1821
+ return this.lastDrain;
1822
+ }
1007
1823
  stateFilePath() {
1008
1824
  return this.config.stateFilePath ?? (0, stateStore_1.defaultStateFilePath)(this.config.toolInstallationId);
1009
1825
  }
1010
- /** 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
+ }
1011
1829
  /**
1012
1830
  * Every send path funnels through {@link post}, so semantic and
1013
1831
  * collaboration signals are logged on the same terms as host events — the
@@ -1017,12 +1835,13 @@ var require_eventSender = __commonJS({
1017
1835
  * It is now `transport_error` through the ordinary path, because the
1018
1836
  * transport returns that outcome instead of throwing.
1019
1837
  */
1020
- log(payload, delivery) {
1838
+ log(payload, delivery, outbox) {
1021
1839
  const logFile = this.config.eventLogFile === void 0 ? (0, eventLog_1.resolveEventLogPath)() : this.config.eventLogFile;
1022
1840
  if (!logFile)
1023
1841
  return;
1024
- (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 } : {} });
1025
1843
  }
1844
+ /** Never throws: a renewal that errors is a failed renewal, not a failed turn. */
1026
1845
  async renewEventToken() {
1027
1846
  try {
1028
1847
  const renewed = await (0, http_1.renewToolToken)(this.config.apiBaseUrl, this.eventWriteToken, this.signal());
@@ -1040,6 +1859,9 @@ var require_eventSender = __commonJS({
1040
1859
  }
1041
1860
  };
1042
1861
  exports.AscendaEventSender = AscendaEventSender2;
1862
+ function withNote(detail, note) {
1863
+ return detail ? `${detail} (${note})` : note;
1864
+ }
1043
1865
  }
1044
1866
  });
1045
1867
 
@@ -1089,16 +1911,16 @@ var require_contextRegistry = __commonJS({
1089
1911
  exports.readWorkContextRegistry = readWorkContextRegistry;
1090
1912
  exports.recordWorkContext = recordWorkContext2;
1091
1913
  exports.recordWorkContextAlias = recordWorkContextAlias;
1092
- var fs2 = __importStar(__require("fs"));
1093
- var os = __importStar(__require("os"));
1094
- var path = __importStar(__require("path"));
1914
+ var fs3 = __importStar(__require("fs"));
1915
+ var os2 = __importStar(__require("os"));
1916
+ var path3 = __importStar(__require("path"));
1095
1917
  var MAX_PATHS_PER_ENTRY = 8;
1096
1918
  function workContextRegistryFilePath() {
1097
- return path.join(os.homedir(), ".ascenda", "work-contexts.json");
1919
+ return path3.join(os2.homedir(), ".ascenda", "work-contexts.json");
1098
1920
  }
1099
1921
  function readWorkContextRegistry(registryFilePath = workContextRegistryFilePath()) {
1100
1922
  try {
1101
- const parsed = JSON.parse(fs2.readFileSync(registryFilePath, "utf8"));
1923
+ const parsed = JSON.parse(fs3.readFileSync(registryFilePath, "utf8"));
1102
1924
  if (parsed && parsed.version === 1 && parsed.contexts && typeof parsed.contexts === "object") {
1103
1925
  return parsed;
1104
1926
  }
@@ -1174,14 +1996,277 @@ var require_contextRegistry = __commonJS({
1174
1996
  return iso.slice(0, 10);
1175
1997
  }
1176
1998
  function writeRegistry(registryFilePath, registry) {
1177
- const dir = path.dirname(registryFilePath);
1178
- fs2.mkdirSync(dir, { recursive: true, mode: 448 });
1999
+ const dir = path3.dirname(registryFilePath);
2000
+ fs3.mkdirSync(dir, { recursive: true, mode: 448 });
1179
2001
  const tmp = `${registryFilePath}.${process.pid}.tmp`;
1180
- fs2.writeFileSync(tmp, `${JSON.stringify(registry, null, 2)}
2002
+ fs3.writeFileSync(tmp, `${JSON.stringify(registry, null, 2)}
1181
2003
  `, { encoding: "utf8", mode: 384 });
1182
- fs2.renameSync(tmp, registryFilePath);
2004
+ fs3.renameSync(tmp, registryFilePath);
1183
2005
  if (process.platform !== "win32") {
1184
- fs2.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;
1185
2270
  }
1186
2271
  }
1187
2272
  }
@@ -1232,32 +2317,32 @@ var require_salt = __commonJS({
1232
2317
  exports.machineSaltFilePath = machineSaltFilePath;
1233
2318
  exports.readOrCreateMachineSalt = readOrCreateMachineSalt;
1234
2319
  exports.hashWithMachineSalt = hashWithMachineSalt;
1235
- var crypto = __importStar(__require("crypto"));
1236
- var fs2 = __importStar(__require("fs"));
1237
- var os = __importStar(__require("os"));
1238
- var path = __importStar(__require("path"));
2320
+ var crypto2 = __importStar(__require("crypto"));
2321
+ var fs3 = __importStar(__require("fs"));
2322
+ var os2 = __importStar(__require("os"));
2323
+ var path3 = __importStar(__require("path"));
1239
2324
  function machineSaltFilePath() {
1240
- return path.join(os.homedir(), ".ascenda", "salt");
2325
+ return path3.join(os2.homedir(), ".ascenda", "salt");
1241
2326
  }
1242
2327
  var cache = /* @__PURE__ */ new Map();
1243
2328
  function readOrCreateMachineSalt(saltFilePath = machineSaltFilePath()) {
1244
2329
  const hit = cache.get(saltFilePath);
1245
2330
  if (hit)
1246
2331
  return hit;
1247
- const dir = path.dirname(saltFilePath);
1248
- fs2.mkdirSync(dir, { recursive: true, mode: 448 });
2332
+ const dir = path3.dirname(saltFilePath);
2333
+ fs3.mkdirSync(dir, { recursive: true, mode: 448 });
1249
2334
  let salt;
1250
2335
  try {
1251
- salt = crypto.randomBytes(32).toString("hex");
1252
- fs2.writeFileSync(saltFilePath, salt, { encoding: "utf8", mode: 384, flag: "wx" });
2336
+ salt = crypto2.randomBytes(32).toString("hex");
2337
+ fs3.writeFileSync(saltFilePath, salt, { encoding: "utf8", mode: 384, flag: "wx" });
1253
2338
  } catch (error) {
1254
2339
  if (error.code !== "EEXIST")
1255
2340
  throw error;
1256
- salt = fs2.readFileSync(saltFilePath, "utf8").trim();
2341
+ salt = fs3.readFileSync(saltFilePath, "utf8").trim();
1257
2342
  }
1258
2343
  if (process.platform !== "win32") {
1259
- fs2.chmodSync(dir, 448);
1260
- fs2.chmodSync(saltFilePath, 384);
2344
+ fs3.chmodSync(dir, 448);
2345
+ fs3.chmodSync(saltFilePath, 384);
1261
2346
  }
1262
2347
  cache.set(saltFilePath, salt);
1263
2348
  return salt;
@@ -1265,7 +2350,7 @@ var require_salt = __commonJS({
1265
2350
  function hashWithMachineSalt(value, saltFilePath) {
1266
2351
  if (!value)
1267
2352
  return null;
1268
- return crypto.createHash("sha256").update(readOrCreateMachineSalt(saltFilePath)).update("\0").update(value).digest("hex").slice(0, 16);
2353
+ return crypto2.createHash("sha256").update(readOrCreateMachineSalt(saltFilePath)).update("\0").update(value).digest("hex").slice(0, 16);
1269
2354
  }
1270
2355
  }
1271
2356
  });
@@ -1313,8 +2398,12 @@ var require_workContext = __commonJS({
1313
2398
  }();
1314
2399
  Object.defineProperty(exports, "__esModule", { value: true });
1315
2400
  exports.deriveWorkContext = deriveWorkContext2;
1316
- var fs2 = __importStar(__require("fs"));
1317
- var path = __importStar(__require("path"));
2401
+ exports.normalizeBranchName = normalizeBranchName;
2402
+ exports.deriveBranchHash = deriveBranchHash;
2403
+ exports.readBranchName = readBranchName;
2404
+ exports.deriveBranchHashForCwd = deriveBranchHashForCwd2;
2405
+ var fs3 = __importStar(__require("fs"));
2406
+ var path3 = __importStar(__require("path"));
1318
2407
  var salt_1 = require_salt();
1319
2408
  var MAX_WALK_DEPTH = 64;
1320
2409
  function deriveWorkContext2(cwd, saltFilePath) {
@@ -1327,6 +2416,8 @@ var require_workContext = __commonJS({
1327
2416
  } catch {
1328
2417
  roots = null;
1329
2418
  }
2419
+ if (!roots)
2420
+ roots = inferRootsFromPath(startPath);
1330
2421
  const workspacePath = roots?.checkoutRoot ?? startPath;
1331
2422
  const workspaceLabel = basenameOf(workspacePath);
1332
2423
  if (!workspaceLabel)
@@ -1343,44 +2434,70 @@ var require_workContext = __commonJS({
1343
2434
  };
1344
2435
  }
1345
2436
  function resolveRepositoryRoots(startDir) {
1346
- if (!fs2.existsSync(startDir))
2437
+ if (!fs3.existsSync(startDir))
1347
2438
  return null;
1348
2439
  let dir = startDir;
1349
2440
  for (let depth = 0; depth < MAX_WALK_DEPTH; depth++) {
1350
- const dotGit = path.join(dir, ".git");
2441
+ const dotGit = path3.join(dir, ".git");
1351
2442
  let stat = null;
1352
2443
  try {
1353
- stat = fs2.statSync(dotGit);
2444
+ stat = fs3.statSync(dotGit);
1354
2445
  } catch {
1355
2446
  stat = null;
1356
2447
  }
1357
2448
  if (stat?.isDirectory())
1358
- return { checkoutRoot: dir, canonicalRoot: dir };
1359
- if (stat?.isFile())
1360
- return { checkoutRoot: dir, canonicalRoot: worktreeParentRoot(dotGit, dir) ?? dir };
1361
- const parent = path.dirname(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
+ }
2455
+ const parent = path3.dirname(dir);
1362
2456
  if (parent === dir)
1363
2457
  return null;
1364
2458
  dir = parent;
1365
2459
  }
1366
2460
  return null;
1367
2461
  }
1368
- function worktreeParentRoot(dotGitFile, containingDir) {
1369
- let gitdir;
2462
+ function readGitdirPointer(dotGitFile, containingDir) {
1370
2463
  try {
1371
- const match = /^gitdir:\s*(.+)\s*$/m.exec(fs2.readFileSync(dotGitFile, "utf8"));
2464
+ const match = /^gitdir:\s*(.+)\s*$/m.exec(fs3.readFileSync(dotGitFile, "utf8"));
1372
2465
  if (!match)
1373
2466
  return null;
1374
- gitdir = match[1].trim();
2467
+ return path3.resolve(containingDir, match[1].trim());
1375
2468
  } catch {
1376
2469
  return null;
1377
2470
  }
1378
- const resolved = path.resolve(containingDir, gitdir);
1379
- const marker = `${path.sep}.git${path.sep}worktrees${path.sep}`;
1380
- const idx = resolved.indexOf(marker);
2471
+ }
2472
+ function worktreeParentRoot(resolvedGitDir) {
2473
+ const marker = `${path3.sep}.git${path3.sep}worktrees${path3.sep}`;
2474
+ const idx = resolvedGitDir.indexOf(marker);
1381
2475
  if (idx === -1)
1382
2476
  return null;
1383
- 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;
1384
2501
  }
1385
2502
  function stripTrailingSeparators(value) {
1386
2503
  let end = value.length;
@@ -1392,6 +2509,55 @@ var require_workContext = __commonJS({
1392
2509
  const segment = value.split(/[\\/]/).filter(Boolean).pop() ?? null;
1393
2510
  return segment && segment.length > 0 ? segment : null;
1394
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);
2557
+ }
2558
+ function deriveBranchHashForCwd2(cwd, saltFilePath) {
2559
+ return deriveBranchHash(readBranchName(cwd), saltFilePath);
2560
+ }
1395
2561
  }
1396
2562
  });
1397
2563
 
@@ -1400,35 +2566,69 @@ var require_hookAdapter = __commonJS({
1400
2566
  "../packages/tool-kit/out/hookAdapter.js"(exports) {
1401
2567
  "use strict";
1402
2568
  Object.defineProperty(exports, "__esModule", { value: true });
1403
- exports.DEFAULT_API_BASE_URL = void 0;
2569
+ exports.MissingInstallationIdError = exports.DEFAULT_API_BASE_URL = void 0;
2570
+ exports.resolveCliAgentInstallationId = resolveCliAgentInstallationId;
1404
2571
  exports.resolveContextHashes = resolveContextHashes;
1405
2572
  exports.loadCliAgentConfig = loadCliAgentConfig;
1406
2573
  exports.deliverHookEvents = deliverHookEvents;
1407
2574
  var contextRegistry_1 = require_contextRegistry();
2575
+ var credentials_1 = require_credentials();
2576
+ var forgeProject_1 = require_forgeProject();
1408
2577
  var eventLog_1 = require_eventLog();
1409
2578
  var eventSender_1 = require_eventSender();
2579
+ var stateStore_1 = require_stateStore();
1410
2580
  var tokenStore_1 = require_tokenStore();
1411
2581
  var workContext_1 = require_workContext();
1412
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
+ }
1413
2613
  function resolveContextHashes(cwd) {
1414
2614
  const workspaceOverride = process.env.ASCENDA_WORKSPACE_HASH?.trim() || null;
1415
2615
  const projectOverride = process.env.ASCENDA_PROJECT_HASH?.trim() || null;
1416
2616
  if (workspaceOverride && projectOverride)
1417
2617
  return { workspaceHash: workspaceOverride, projectHash: projectOverride };
1418
2618
  const context = (0, workContext_1.deriveWorkContext)(cwd ?? process.cwd());
1419
- if (context)
2619
+ if (context) {
1420
2620
  (0, contextRegistry_1.recordWorkContext)(context);
2621
+ (0, forgeProject_1.recordForgeProjectAlias)(context);
2622
+ }
1421
2623
  return {
1422
2624
  workspaceHash: workspaceOverride ?? context?.workspaceHash ?? null,
1423
2625
  projectHash: projectOverride ?? context?.projectHash ?? null
1424
2626
  };
1425
2627
  }
1426
- function loadCliAgentConfig(toolType, sessionIdFromHook, cwd) {
1427
- const apiBaseUrl = (process.env.ASCENDA_API_BASE_URL ?? exports.DEFAULT_API_BASE_URL).replace(/\/$/, "");
1428
- const toolInstallationIdRaw = process.env.ASCENDA_TOOL_INSTALLATION_ID;
1429
- if (!toolInstallationIdRaw)
1430
- throw new Error("Missing ASCENDA_TOOL_INSTALLATION_ID");
1431
- 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);
1432
2632
  const tokenFilePath = process.env.ASCENDA_EVENT_WRITE_TOKEN_FILE ?? (0, tokenStore_1.defaultTokenFilePath)(toolInstallationId);
1433
2633
  const fileToken = (0, tokenStore_1.readTokenFile)(tokenFilePath);
1434
2634
  const eventWriteToken = fileToken ?? process.env.ASCENDA_EVENT_WRITE_TOKEN;
@@ -1455,8 +2655,10 @@ var require_hookAdapter = __commonJS({
1455
2655
  const notice = options.onNotice ?? ((message) => console.error(message));
1456
2656
  let config;
1457
2657
  try {
1458
- config = loadCliAgentConfig(options.toolType, options.sessionId, options.cwd);
2658
+ config = loadCliAgentConfig(options.toolType, options.sessionId, options.cwd, options);
1459
2659
  } catch (error) {
2660
+ if (error instanceof MissingInstallationIdError2)
2661
+ journalSkippedSend2(options.host, error);
1460
2662
  const logFile = (0, eventLog_1.resolveEventLogPath)();
1461
2663
  if (!logFile)
1462
2664
  throw error;
@@ -1496,16 +2698,403 @@ var require_hookAdapter = __commonJS({
1496
2698
  } else if (result === "auth_failed") {
1497
2699
  notice("Ascenda telemetry paused: connection revoked or expired. Re-pair via an Ascenda IDE extension or pairing-sim.");
1498
2700
  } else if (result === "transport_error") {
1499
- 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.");
1500
2702
  } else {
1501
2703
  notice(`Ascenda telemetry rejected: ${result}`);
1502
2704
  }
1503
- return;
2705
+ return;
2706
+ }
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
+ }
2714
+ function parsePositiveInt(value) {
2715
+ const n = Number(value);
2716
+ return Number.isInteger(n) && n > 0 ? n : void 0;
2717
+ }
2718
+ }
2719
+ });
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)];
1504
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;
1505
3011
  }
1506
- function parsePositiveInt(value) {
1507
- const n = Number(value);
1508
- return Number.isInteger(n) && n > 0 ? n : void 0;
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;
1509
3098
  }
1510
3099
  }
1511
3100
  });
@@ -1554,12 +3143,12 @@ var require_turnState = __commonJS({
1554
3143
  Object.defineProperty(exports, "__esModule", { value: true });
1555
3144
  exports.recordTurnStart = recordTurnStart;
1556
3145
  exports.consumeTurnDurationMs = consumeTurnDurationMs;
1557
- var fs2 = __importStar(__require("fs"));
1558
- var os = __importStar(__require("os"));
1559
- var path = __importStar(__require("path"));
1560
- var stateDir = () => process.env.ASCENDA_STATE_DIR ?? path.join(os.homedir(), ".ascenda", "state");
3146
+ var fs3 = __importStar(__require("fs"));
3147
+ var os2 = __importStar(__require("os"));
3148
+ var path3 = __importStar(__require("path"));
3149
+ var stateDir = () => process.env.ASCENDA_STATE_DIR ?? path3.join(os2.homedir(), ".ascenda", "state");
1561
3150
  function turnFile(agent, sessionId) {
1562
- return path.join(stateDir(), `${sanitize(agent)}-turn-${sanitize(sessionId)}`);
3151
+ return path3.join(stateDir(), `${sanitize(agent)}-turn-${sanitize(sessionId)}`);
1563
3152
  }
1564
3153
  function sanitize(value) {
1565
3154
  return value.replace(/[^a-zA-Z0-9._-]/g, "_");
@@ -1568,8 +3157,8 @@ var require_turnState = __commonJS({
1568
3157
  if (!sessionId)
1569
3158
  return;
1570
3159
  try {
1571
- fs2.mkdirSync(stateDir(), { recursive: true });
1572
- fs2.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 });
1573
3162
  } catch {
1574
3163
  }
1575
3164
  }
@@ -1578,8 +3167,8 @@ var require_turnState = __commonJS({
1578
3167
  return void 0;
1579
3168
  const file = turnFile(agent, sessionId);
1580
3169
  try {
1581
- const started = Number(fs2.readFileSync(file, "utf8").trim());
1582
- fs2.rmSync(file, { force: true });
3170
+ const started = Number(fs3.readFileSync(file, "utf8").trim());
3171
+ fs3.rmSync(file, { force: true });
1583
3172
  if (!Number.isFinite(started) || started <= 0 || started > now)
1584
3173
  return void 0;
1585
3174
  return now - started;
@@ -1636,10 +3225,10 @@ var require_liveBus = __commonJS({
1636
3225
  exports.liveBusSocketPath = liveBusSocketPath;
1637
3226
  exports.bucketPromptSize = bucketPromptSize2;
1638
3227
  exports.emitLiveSignal = emitLiveSignal2;
1639
- var fs2 = __importStar(__require("fs"));
3228
+ var fs3 = __importStar(__require("fs"));
1640
3229
  var net = __importStar(__require("net"));
1641
- var os = __importStar(__require("os"));
1642
- var path = __importStar(__require("path"));
3230
+ var os2 = __importStar(__require("os"));
3231
+ var path3 = __importStar(__require("path"));
1643
3232
  var WRITE_TIMEOUT_MS = 50;
1644
3233
  var APP_BUNDLE_ID = "one.ascenda.ascendaMissionControl";
1645
3234
  var SAVER_HOST_BUNDLE_ID = "com.apple.ScreenSaver.Engine.legacyScreenSaver";
@@ -1647,18 +3236,18 @@ var require_liveBus = __commonJS({
1647
3236
  const override = process.env.ASCENDA_LIVE_BUS_SOCKET;
1648
3237
  if (override)
1649
3238
  return [override];
1650
- const home = os.homedir();
3239
+ const home = os2.homedir();
1651
3240
  return [
1652
- path.join(home, ".ascenda", "live.sock"),
1653
- path.join(home, "Library", "Containers", APP_BUNDLE_ID, "Data", ".ascenda", "live.sock"),
1654
- path.join(home, "Library", "Containers", SAVER_HOST_BUNDLE_ID, "Data", "l.sock")
3241
+ path3.join(home, ".ascenda", "live.sock"),
3242
+ path3.join(home, "Library", "Containers", APP_BUNDLE_ID, "Data", ".ascenda", "live.sock"),
3243
+ path3.join(home, "Library", "Containers", SAVER_HOST_BUNDLE_ID, "Data", "l.sock")
1655
3244
  ];
1656
3245
  }
1657
3246
  function liveBusSocketPath() {
1658
3247
  const candidates = liveBusSocketCandidates();
1659
3248
  for (const candidate of candidates) {
1660
3249
  try {
1661
- if (fs2.statSync(candidate).isSocket())
3250
+ if (fs3.statSync(candidate).isSocket())
1662
3251
  return candidate;
1663
3252
  } catch {
1664
3253
  }
@@ -1676,7 +3265,7 @@ var require_liveBus = __commonJS({
1676
3265
  return "xl";
1677
3266
  }
1678
3267
  function emitLiveSignal2(signal) {
1679
- return new Promise((resolve) => {
3268
+ return new Promise((resolve2) => {
1680
3269
  let settled = false;
1681
3270
  const done = () => {
1682
3271
  if (settled)
@@ -1686,13 +3275,13 @@ var require_liveBus = __commonJS({
1686
3275
  socket.destroy();
1687
3276
  } catch {
1688
3277
  }
1689
- resolve();
3278
+ resolve2();
1690
3279
  };
1691
3280
  let socket;
1692
3281
  try {
1693
3282
  socket = net.createConnection(liveBusSocketPath());
1694
3283
  } catch {
1695
- resolve();
3284
+ resolve2();
1696
3285
  return;
1697
3286
  }
1698
3287
  const timer = setTimeout(done, WRITE_TIMEOUT_MS);
@@ -1723,8 +3312,9 @@ var require_out2 = __commonJS({
1723
3312
  "../packages/tool-kit/out/index.js"(exports) {
1724
3313
  "use strict";
1725
3314
  Object.defineProperty(exports, "__esModule", { value: true });
1726
- exports.workContextRegistryFilePath = 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.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;
1727
- exports.isRetryableStatus = exports.parseIngestResponse = exports.postToolEventsBatch = exports.postToolEvent = exports.renewToolToken = exports.getPairingStatus = exports.createPairingSession = exports.AscendaApiError = exports.liveBusSocketCandidates = exports.liveBusSocketPath = exports.bucketPromptSize = exports.emitLiveSignal = 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;
1728
3318
  var commandClassifier_1 = require_commandClassifier();
1729
3319
  Object.defineProperty(exports, "classifyCommand", { enumerable: true, get: function() {
1730
3320
  return commandClassifier_1.classifyCommand;
@@ -1746,6 +3336,14 @@ var require_out2 = __commonJS({
1746
3336
  Object.defineProperty(exports, "invitesDebrief", { enumerable: true, get: function() {
1747
3337
  return workMilestoneClassifier_1.invitesDebrief;
1748
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
+ } });
1749
3347
  var buckets_1 = require_buckets();
1750
3348
  Object.defineProperty(exports, "bucketLinesChanged", { enumerable: true, get: function() {
1751
3349
  return buckets_1.bucketLinesChanged;
@@ -1794,6 +3392,9 @@ var require_out2 = __commonJS({
1794
3392
  Object.defineProperty(exports, "looksLikeCorrection", { enumerable: true, get: function() {
1795
3393
  return payload_1.looksLikeCorrection;
1796
3394
  } });
3395
+ Object.defineProperty(exports, "mintIdempotencyKey", { enumerable: true, get: function() {
3396
+ return payload_1.mintIdempotencyKey;
3397
+ } });
1797
3398
  var eventSender_1 = require_eventSender();
1798
3399
  Object.defineProperty(exports, "AscendaEventSender", { enumerable: true, get: function() {
1799
3400
  return eventSender_1.AscendaEventSender;
@@ -1821,15 +3422,59 @@ var require_out2 = __commonJS({
1821
3422
  Object.defineProperty(exports, "DEFAULT_API_BASE_URL", { enumerable: true, get: function() {
1822
3423
  return hookAdapter_1.DEFAULT_API_BASE_URL;
1823
3424
  } });
3425
+ Object.defineProperty(exports, "MissingInstallationIdError", { enumerable: true, get: function() {
3426
+ return hookAdapter_1.MissingInstallationIdError;
3427
+ } });
1824
3428
  Object.defineProperty(exports, "deliverHookEvents", { enumerable: true, get: function() {
1825
3429
  return hookAdapter_1.deliverHookEvents;
1826
3430
  } });
1827
3431
  Object.defineProperty(exports, "loadCliAgentConfig", { enumerable: true, get: function() {
1828
3432
  return hookAdapter_1.loadCliAgentConfig;
1829
3433
  } });
3434
+ Object.defineProperty(exports, "resolveCliAgentInstallationId", { enumerable: true, get: function() {
3435
+ return hookAdapter_1.resolveCliAgentInstallationId;
3436
+ } });
1830
3437
  Object.defineProperty(exports, "resolveContextHashes", { enumerable: true, get: function() {
1831
3438
  return hookAdapter_1.resolveContextHashes;
1832
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
+ } });
1833
3478
  var turnState_1 = require_turnState();
1834
3479
  Object.defineProperty(exports, "consumeTurnDurationMs", { enumerable: true, get: function() {
1835
3480
  return turnState_1.consumeTurnDurationMs;
@@ -1838,9 +3483,15 @@ var require_out2 = __commonJS({
1838
3483
  return turnState_1.recordTurnStart;
1839
3484
  } });
1840
3485
  var tokenStore_1 = require_tokenStore();
3486
+ Object.defineProperty(exports, "ascendaHome", { enumerable: true, get: function() {
3487
+ return tokenStore_1.ascendaHome;
3488
+ } });
1841
3489
  Object.defineProperty(exports, "defaultTokenFilePath", { enumerable: true, get: function() {
1842
3490
  return tokenStore_1.defaultTokenFilePath;
1843
3491
  } });
3492
+ Object.defineProperty(exports, "listPersistedToolInstallationIds", { enumerable: true, get: function() {
3493
+ return tokenStore_1.listPersistedToolInstallationIds;
3494
+ } });
1844
3495
  Object.defineProperty(exports, "persistEventWriteToken", { enumerable: true, get: function() {
1845
3496
  return tokenStore_1.persistEventWriteToken;
1846
3497
  } });
@@ -1863,6 +3514,46 @@ var require_out2 = __commonJS({
1863
3514
  Object.defineProperty(exports, "markFailureNotified", { enumerable: true, get: function() {
1864
3515
  return stateStore_1.markFailureNotified;
1865
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
+ } });
1866
3557
  var salt_1 = require_salt();
1867
3558
  Object.defineProperty(exports, "machineSaltFilePath", { enumerable: true, get: function() {
1868
3559
  return salt_1.machineSaltFilePath;
@@ -1877,6 +3568,18 @@ var require_out2 = __commonJS({
1877
3568
  Object.defineProperty(exports, "deriveWorkContext", { enumerable: true, get: function() {
1878
3569
  return workContext_1.deriveWorkContext;
1879
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
+ } });
1880
3583
  var contextRegistry_1 = require_contextRegistry();
1881
3584
  Object.defineProperty(exports, "recordWorkContext", { enumerable: true, get: function() {
1882
3585
  return contextRegistry_1.recordWorkContext;
@@ -1890,6 +3593,22 @@ var require_out2 = __commonJS({
1890
3593
  Object.defineProperty(exports, "workContextRegistryFilePath", { enumerable: true, get: function() {
1891
3594
  return contextRegistry_1.workContextRegistryFilePath;
1892
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
+ } });
1893
3612
  var liveBus_1 = require_liveBus();
1894
3613
  Object.defineProperty(exports, "emitLiveSignal", { enumerable: true, get: function() {
1895
3614
  return liveBus_1.emitLiveSignal;
@@ -1931,83 +3650,86 @@ var require_out2 = __commonJS({
1931
3650
  }
1932
3651
  });
1933
3652
 
1934
- // src/cli.ts
1935
- var import_tool_kit6 = __toESM(require_out2(), 1);
1936
- import { randomUUID } from "node:crypto";
1937
- import * as fs from "node:fs";
1938
-
1939
- // src/ascendaClient.ts
1940
- var import_tool_kit = __toESM(require_out2(), 1);
1941
- var import_tool_kit2 = __toESM(require_out2(), 1);
1942
- var AscendaClient = class {
1943
- sender;
1944
- constructor(config) {
1945
- this.sender = new import_tool_kit.AscendaEventSender({
1946
- apiBaseUrl: config.apiBaseUrl,
1947
- toolInstallationId: config.toolInstallationId,
1948
- source: "claude_code",
1949
- eventWriteToken: config.eventWriteToken,
1950
- tokenFilePath: config.tokenFilePath,
1951
- stateFilePath: config.stateFilePath,
1952
- sessionId: config.sessionId,
1953
- workspaceHash: config.workspaceHash,
1954
- projectHash: config.projectHash
1955
- });
1956
- }
1957
- /** The journal entry written by the most recent {@link send}. */
1958
- get state() {
1959
- return this.sender.state;
1960
- }
1961
- async send(mapped) {
1962
- return this.sender.send(mapped);
1963
- }
1964
- async renewEventToken() {
1965
- return this.sender.renewEventToken();
3653
+ // src/paths.ts
3654
+ import * as path from "path";
3655
+ function hookBinPath() {
3656
+ return path.join((0, import_tool_kit3.ascendaHome)(), "bin", "ascenda-claude-hook");
3657
+ }
3658
+ function readCredentials() {
3659
+ const credentials = (0, import_tool_kit3.readMachineCredentials)();
3660
+ if (!credentials) return void 0;
3661
+ const { tools: _tools, ...topLevel } = credentials;
3662
+ return topLevel;
3663
+ }
3664
+ function writeCredentials(credentials) {
3665
+ (0, import_tool_kit3.writeTopLevelCredentials)(credentials);
3666
+ }
3667
+ var import_tool_kit3, import_tool_kit4;
3668
+ var init_paths = __esm({
3669
+ "src/paths.ts"() {
3670
+ "use strict";
3671
+ import_tool_kit3 = __toESM(require_out2(), 1);
3672
+ import_tool_kit4 = __toESM(require_out2(), 1);
1966
3673
  }
1967
- };
1968
-
1969
- // src/config.ts
1970
- var import_tool_kit3 = __toESM(require_out2(), 1);
3674
+ });
1971
3675
 
1972
3676
  // src/types.ts
1973
- var import_tool_contract = __toESM(require_out(), 1);
1974
- var CLAUDE_HOOK_EVENT_NAMES = [
1975
- "SessionStart",
1976
- "UserPromptSubmit",
1977
- "PreToolUse",
1978
- "PostToolUse",
1979
- "PostToolUseFailure",
1980
- "PreCompact",
1981
- "PostCompact",
1982
- "Stop",
1983
- "Notification"
1984
- ];
1985
3677
  function isClaudeHookEventName(value) {
1986
3678
  return CLAUDE_HOOK_EVENT_NAMES.includes(value);
1987
3679
  }
1988
- var ASCENDA_TOOL_TYPE = "claude_code";
1989
- var CLAUDE_HOST = "claude_code";
3680
+ var import_tool_contract, CLAUDE_HOOK_EVENT_NAMES, ASCENDA_TOOL_TYPE, CLAUDE_HOST;
3681
+ var init_types = __esm({
3682
+ "src/types.ts"() {
3683
+ "use strict";
3684
+ import_tool_contract = __toESM(require_out(), 1);
3685
+ CLAUDE_HOOK_EVENT_NAMES = [
3686
+ "SessionStart",
3687
+ "UserPromptSubmit",
3688
+ "PreToolUse",
3689
+ "PostToolUse",
3690
+ "PostToolUseFailure",
3691
+ "PreCompact",
3692
+ "PostCompact",
3693
+ "Stop",
3694
+ "Notification"
3695
+ ];
3696
+ ASCENDA_TOOL_TYPE = "claude_code";
3697
+ CLAUDE_HOST = "claude_code";
3698
+ }
3699
+ });
1990
3700
 
1991
3701
  // src/config.ts
3702
+ function resolveOutboxFilePath(toolInstallationId) {
3703
+ return process.env.ASCENDA_OUTBOX_FILE ?? (0, import_tool_kit5.defaultOutboxFilePath)(toolInstallationId);
3704
+ }
1992
3705
  function resolveStateFilePath(toolInstallationId) {
1993
- return process.env.ASCENDA_STATE_FILE ?? (0, import_tool_kit3.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);
1994
3716
  }
1995
3717
  function loadConfigFromEnv() {
1996
- const apiBaseUrl = (process.env.ASCENDA_API_BASE_URL ?? "https://api.ascenda.one").replace(/\/$/, "");
1997
- const toolInstallationIdRaw = process.env.ASCENDA_TOOL_INSTALLATION_ID;
1998
- if (!toolInstallationIdRaw) throw new Error("Missing ASCENDA_TOOL_INSTALLATION_ID");
1999
- const toolInstallationId = normalizeToolInstallationId(toolInstallationIdRaw);
2000
- const tokenFilePath = process.env.ASCENDA_EVENT_WRITE_TOKEN_FILE ?? (0, import_tool_kit3.defaultTokenFilePath)(toolInstallationId);
2001
- const fileToken = (0, import_tool_kit3.readTokenFile)(tokenFilePath);
3718
+ const credentials = readCredentials();
3719
+ const apiBaseUrl = (process.env.ASCENDA_API_BASE_URL ?? credentials?.apiBaseUrl ?? DEFAULT_API_BASE_URL).replace(/\/$/, "");
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);
2002
3723
  const eventWriteToken = fileToken ?? process.env.ASCENDA_EVENT_WRITE_TOKEN;
2003
3724
  if (!eventWriteToken) throw new Error("Missing ASCENDA_EVENT_WRITE_TOKEN (or token file)");
2004
- if (!fileToken) (0, import_tool_kit3.persistEventWriteToken)(tokenFilePath, eventWriteToken);
3725
+ if (!fileToken) (0, import_tool_kit5.persistEventWriteToken)(tokenFilePath, eventWriteToken);
2005
3726
  return {
2006
3727
  apiBaseUrl,
2007
3728
  toolInstallationId,
2008
3729
  eventWriteToken,
2009
3730
  tokenFilePath,
2010
3731
  stateFilePath: resolveStateFilePath(toolInstallationId),
3732
+ outboxFilePath: resolveOutboxFilePath(toolInstallationId),
2011
3733
  sessionId: process.env.ASCENDA_SESSION_ID ?? null,
2012
3734
  // Overrides only. When unset, main() fills these from the hook payload's
2013
3735
  // own cwd — the payload knows where the work happened; the environment
@@ -2026,18 +3748,405 @@ function normalizeToolInstallationId(value) {
2026
3748
  if (trimmed.startsWith("claude_tool_")) return `${ASCENDA_TOOL_TYPE}:${trimmed.slice("claude_tool_".length)}`;
2027
3749
  return `${ASCENDA_TOOL_TYPE}:${trimmed}`;
2028
3750
  }
3751
+ var import_tool_kit5, DEFAULT_API_BASE_URL, MissingInstallationIdError;
3752
+ var init_config = __esm({
3753
+ "src/config.ts"() {
3754
+ "use strict";
3755
+ import_tool_kit5 = __toESM(require_out2(), 1);
3756
+ init_paths();
3757
+ init_types();
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
+ };
3770
+ }
3771
+ });
3772
+
3773
+ // src/setup.ts
3774
+ var setup_exports = {};
3775
+ __export(setup_exports, {
3776
+ findStaleHookCommands: () => findStaleHookCommands,
3777
+ runSetup: () => runSetup,
3778
+ writeSettings: () => writeSettings
3779
+ });
3780
+ import * as crypto from "crypto";
3781
+ import * as fs from "fs";
3782
+ import * as os from "os";
3783
+ import * as path2 from "path";
3784
+ async function runSetup(argv) {
3785
+ let options;
3786
+ try {
3787
+ options = parseArgs(argv);
3788
+ } catch (error) {
3789
+ console.error(error instanceof Error ? error.message : String(error));
3790
+ return 1;
3791
+ }
3792
+ if (options.action === "help") {
3793
+ console.log(USAGE);
3794
+ return 0;
3795
+ }
3796
+ if (options.action === "status") return printStatus(options);
3797
+ if (options.action === "uninstall") return uninstall(options);
3798
+ const apiBaseUrl = (options.apiBaseUrl ?? readCredentials()?.apiBaseUrl ?? DEFAULT_API_BASE_URL).replace(/\/$/, "");
3799
+ console.log(`Ascenda setup \u2014 ${apiBaseUrl}`);
3800
+ const identity = await resolveIdentity(apiBaseUrl, options);
3801
+ if (!identity) return 1;
3802
+ console.log(` pairing ${identity.toolInstallationId}${identity.paired ? " (new)" : " (existing)"}`);
3803
+ const binary = installBinary(options.dryRun);
3804
+ console.log(` hook binary ${binary}`);
3805
+ if (!options.dryRun) {
3806
+ writeCredentials({ apiBaseUrl, toolInstallationId: identity.toolInstallationId, pairedAt: (/* @__PURE__ */ new Date()).toISOString() });
3807
+ }
3808
+ console.log(` credentials ${(0, import_tool_kit4.credentialsFilePath)()}`);
3809
+ const settingsFile = settingsPath(options);
3810
+ const written = writeSettings(settingsFile, binary, options.dryRun);
3811
+ if (written === null) return 1;
3812
+ console.log(` hooks ${settingsFile} (${HOOK_EVENTS.length} events${written ? "" : ", already current"})`);
3813
+ if (options.dryRun) {
3814
+ console.log("\nDry run \u2014 nothing was written.");
3815
+ return 0;
3816
+ }
3817
+ console.log("\nDone. Restart Claude Code in this project to load the hooks.");
3818
+ console.log(`Check anytime: npx @ascenda-one/claude-code-hooks status`);
3819
+ return 0;
3820
+ }
3821
+ function parseArgs(argv) {
3822
+ const options = {
3823
+ scope: "project",
3824
+ projectDir: process.env.CLAUDE_PROJECT_DIR ?? process.cwd(),
3825
+ dryRun: false,
3826
+ action: "install"
3827
+ };
3828
+ for (let i = 0; i < argv.length; i++) {
3829
+ const arg = argv[i];
3830
+ const next = () => {
3831
+ const value = argv[++i];
3832
+ if (value === void 0) throw new Error(`${arg} needs a value`);
3833
+ return value;
3834
+ };
3835
+ switch (arg) {
3836
+ case "setup":
3837
+ case "install":
3838
+ options.action = "install";
3839
+ break;
3840
+ case "status":
3841
+ options.action = "status";
3842
+ break;
3843
+ case "uninstall":
3844
+ options.action = "uninstall";
3845
+ break;
3846
+ case "--api-base-url":
3847
+ options.apiBaseUrl = next();
3848
+ break;
3849
+ case "--local": {
3850
+ const peek = argv[i + 1];
3851
+ const port = peek && /^\d+$/.test(peek) ? argv[++i] : "4477";
3852
+ options.apiBaseUrl = `http://localhost:${port}`;
3853
+ break;
3854
+ }
3855
+ case "--tool-installation-id":
3856
+ options.toolInstallationId = next();
3857
+ break;
3858
+ case "--token":
3859
+ options.token = next();
3860
+ break;
3861
+ case "--scope": {
3862
+ const value = next();
3863
+ if (value !== "project" && value !== "user") throw new Error(`--scope must be project or user, got ${value}`);
3864
+ options.scope = value;
3865
+ break;
3866
+ }
3867
+ case "--project-dir":
3868
+ options.projectDir = path2.resolve(next());
3869
+ break;
3870
+ case "--dry-run":
3871
+ options.dryRun = true;
3872
+ break;
3873
+ case "-h":
3874
+ case "--help":
3875
+ options.action = "help";
3876
+ break;
3877
+ default:
3878
+ throw new Error(`unknown argument: ${arg}
3879
+
3880
+ ${USAGE}`);
3881
+ }
3882
+ }
3883
+ return options;
3884
+ }
3885
+ async function resolveIdentity(apiBaseUrl, options) {
3886
+ const existingId = options.toolInstallationId ?? readCredentials()?.toolInstallationId;
3887
+ if (existingId && options.token) {
3888
+ if (!options.dryRun) (0, import_tool_kit8.persistEventWriteToken)((0, import_tool_kit8.defaultTokenFilePath)(existingId), options.token);
3889
+ return { toolInstallationId: existingId, paired: false };
3890
+ }
3891
+ if (existingId && (0, import_tool_kit8.readTokenFile)((0, import_tool_kit8.defaultTokenFilePath)(existingId))) {
3892
+ return { toolInstallationId: existingId, paired: false };
3893
+ }
3894
+ if (options.dryRun) {
3895
+ return { toolInstallationId: existingId ?? `${ASCENDA_TOOL_TYPE}:<paired at run time>`, paired: false };
3896
+ }
3897
+ const toolInstallationId = existingId ?? `${ASCENDA_TOOL_TYPE}:${crypto.randomUUID()}`;
3898
+ let session;
3899
+ try {
3900
+ session = await (0, import_tool_kit8.createPairingSession)(apiBaseUrl, toolInstallationId, ASCENDA_TOOL_TYPE, `Claude Code on ${os.hostname()}`);
3901
+ } catch (error) {
3902
+ console.error(`
3903
+ Could not reach ${apiBaseUrl} to pair: ${error instanceof Error ? error.message : String(error)}`);
3904
+ console.error("Start the local dev server and use --local, or pass --api-base-url for your backend.");
3905
+ return void 0;
3906
+ }
3907
+ const token = await pollForToken(apiBaseUrl, session.pairingSessionId, session.code, session.expiresAt);
3908
+ if (!token) return void 0;
3909
+ (0, import_tool_kit8.persistEventWriteToken)((0, import_tool_kit8.defaultTokenFilePath)(toolInstallationId), token);
3910
+ return { toolInstallationId, paired: true };
3911
+ }
3912
+ async function pollForToken(apiBaseUrl, pairingSessionId, code, expiresAt) {
3913
+ const deadline = Math.min(Date.parse(expiresAt) || Date.now() + 3e5, Date.now() + 3e5);
3914
+ let announced = false;
3915
+ while (Date.now() < deadline) {
3916
+ const status = await (0, import_tool_kit8.getPairingStatus)(apiBaseUrl, pairingSessionId);
3917
+ if (status.status === "paired" && status.eventWriteToken) return status.eventWriteToken;
3918
+ if (status.status === "expired" || status.status === "cancelled") {
3919
+ console.error(`
3920
+ Pairing ${status.status}. Run setup again.`);
3921
+ return void 0;
3922
+ }
3923
+ if (!announced) {
3924
+ console.log(`
3925
+ Confirm in the Ascenda app \u2014 code ${code}`);
3926
+ console.log(" Waiting...");
3927
+ announced = true;
3928
+ }
3929
+ await new Promise((resolve2) => setTimeout(resolve2, 2e3));
3930
+ }
3931
+ console.error("\nPairing timed out. Run setup again.");
3932
+ return void 0;
3933
+ }
3934
+ function installBinary(dryRun) {
3935
+ const target = hookBinPath();
3936
+ if (dryRun) return target;
3937
+ const source = process.argv[1];
3938
+ fs.mkdirSync(path2.dirname(target), { recursive: true });
3939
+ if (path2.resolve(source) !== path2.resolve(target)) {
3940
+ fs.copyFileSync(source, target);
3941
+ }
3942
+ if (process.platform !== "win32") fs.chmodSync(target, 493);
3943
+ return target;
3944
+ }
3945
+ function settingsPath(options) {
3946
+ return options.scope === "user" ? path2.join(os.homedir(), ".claude", "settings.json") : path2.join(options.projectDir, ".claude", "settings.local.json");
3947
+ }
3948
+ function writeSettings(settingsFile, binary, dryRun) {
3949
+ let settings = {};
3950
+ const exists = fs.existsSync(settingsFile);
3951
+ if (exists) {
3952
+ const raw = fs.readFileSync(settingsFile, "utf8").trim();
3953
+ if (raw) {
3954
+ try {
3955
+ settings = JSON.parse(raw);
3956
+ } catch {
3957
+ console.error(`
3958
+ ${settingsFile} is not valid JSON. Fix or move it, then run setup again.`);
3959
+ return null;
3960
+ }
3961
+ }
3962
+ }
3963
+ const command = hookCommand(binary);
3964
+ const hooks = { ...settings.hooks ?? {} };
3965
+ for (const event of HOOK_EVENTS) {
3966
+ const kept = (hooks[event] ?? []).filter((group) => !isOurs(group));
3967
+ hooks[event] = [...kept, { hooks: [{ type: "command", command: `${command} ${event}`, timeout: HOOK_TIMEOUT_SECONDS }] }];
3968
+ }
3969
+ const updated = { ...settings, hooks };
3970
+ const serialised = `${JSON.stringify(updated, null, 2)}
3971
+ `;
3972
+ if (exists && fs.readFileSync(settingsFile, "utf8") === serialised) return false;
3973
+ if (dryRun) {
3974
+ console.log(`
3975
+ --- ${settingsFile} (dry run) ---
3976
+ ${serialised}`);
3977
+ return true;
3978
+ }
3979
+ if (exists) fs.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
3980
+ fs.mkdirSync(path2.dirname(settingsFile), { recursive: true });
3981
+ fs.writeFileSync(settingsFile, serialised, "utf8");
3982
+ return true;
3983
+ }
3984
+ function hookCommand(binary) {
3985
+ return `"${process.execPath}" "${binary}"`;
3986
+ }
3987
+ function isOurs(group) {
3988
+ return (group.hooks ?? []).some((entry) => typeof entry.command === "string" && entry.command.includes(HOOK_MARKER));
3989
+ }
3990
+ function findStaleHookCommands(settings, binary) {
3991
+ const stale = /* @__PURE__ */ new Set();
3992
+ for (const groups of Object.values(settings.hooks ?? {})) {
3993
+ for (const group of groups ?? []) {
3994
+ for (const entry of group.hooks ?? []) {
3995
+ const command = entry?.command;
3996
+ if (typeof command !== "string") continue;
3997
+ if (!/ascenda/i.test(command) || command.includes(binary)) continue;
3998
+ stale.add(command);
3999
+ }
4000
+ }
4001
+ }
4002
+ return [...stale];
4003
+ }
4004
+ function printStatus(options) {
4005
+ const credentials = readCredentials();
4006
+ const settingsFile = settingsPath(options);
4007
+ const binary = hookBinPath();
4008
+ const tokenFile = credentials?.toolInstallationId ? (0, import_tool_kit8.defaultTokenFilePath)(credentials.toolInstallationId) : void 0;
4009
+ const settings = (() => {
4010
+ try {
4011
+ return JSON.parse(fs.readFileSync(settingsFile, "utf8"));
4012
+ } catch {
4013
+ return {};
4014
+ }
4015
+ })();
4016
+ const registered = HOOK_EVENTS.filter((event) => (settings.hooks?.[event] ?? []).some(isOurs)).length;
4017
+ const stale = findStaleHookCommands(settings, binary);
4018
+ console.log(`api base url ${credentials?.apiBaseUrl ?? "\u2014 not configured"}`);
4019
+ console.log(`pairing ${credentials?.toolInstallationId ?? "\u2014 not paired"}`);
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"}`);
4022
+ console.log(`hooks ${registered}/${HOOK_EVENTS.length} registered in ${settingsFile}`);
4023
+ if (stale.length) {
4024
+ console.log(`stale hooks ${stale.length} not pointing at the installed binary \u2014 each one fails silently per event:`);
4025
+ for (const command of stale) console.log(` ${command}`);
4026
+ console.log(` Remove them from ${settingsFile} by hand; setup cannot tell them from a hook you wrote.`);
4027
+ }
4028
+ const healthy = credentials?.toolInstallationId && registered === HOOK_EVENTS.length && fs.existsSync(binary) && !stale.length;
4029
+ return healthy ? 0 : 1;
4030
+ }
4031
+ function uninstall(options) {
4032
+ const settingsFile = settingsPath(options);
4033
+ if (fs.existsSync(settingsFile)) {
4034
+ try {
4035
+ const settings = JSON.parse(fs.readFileSync(settingsFile, "utf8"));
4036
+ const hooks = { ...settings.hooks ?? {} };
4037
+ for (const event of Object.keys(hooks)) {
4038
+ const kept = hooks[event].filter((group) => !isOurs(group));
4039
+ if (kept.length) hooks[event] = kept;
4040
+ else delete hooks[event];
4041
+ }
4042
+ const updated = { ...settings, hooks };
4043
+ if (!Object.keys(hooks).length) delete updated.hooks;
4044
+ fs.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
4045
+ fs.writeFileSync(settingsFile, `${JSON.stringify(updated, null, 2)}
4046
+ `, "utf8");
4047
+ console.log(`hooks removed from ${settingsFile}`);
4048
+ } catch {
4049
+ console.error(`could not parse ${settingsFile} \u2014 remove the ascenda hook entries by hand`);
4050
+ return 1;
4051
+ }
4052
+ }
4053
+ const binary = hookBinPath();
4054
+ if (fs.existsSync(binary)) {
4055
+ fs.rmSync(binary);
4056
+ console.log(`removed ${binary}`);
4057
+ }
4058
+ const credentials = (0, import_tool_kit4.credentialsFilePath)();
4059
+ if (fs.existsSync(credentials)) {
4060
+ fs.rmSync(credentials);
4061
+ console.log(`removed ${credentials}`);
4062
+ }
4063
+ console.log(`tokens left in ${path2.join((0, import_tool_kit8.ascendaHome)(), "tokens")} \u2014 revoke in the Ascenda app to invalidate them`);
4064
+ return 0;
4065
+ }
4066
+ var import_tool_kit8, HOOK_EVENTS, HOOK_TIMEOUT_SECONDS, HOOK_MARKER, USAGE;
4067
+ var init_setup = __esm({
4068
+ "src/setup.ts"() {
4069
+ "use strict";
4070
+ import_tool_kit8 = __toESM(require_out2(), 1);
4071
+ init_config();
4072
+ init_paths();
4073
+ init_types();
4074
+ HOOK_EVENTS = ["SessionStart", "UserPromptSubmit", "PreToolUse", "PostToolUse", "PreCompact", "PostCompact", "Stop"];
4075
+ HOOK_TIMEOUT_SECONDS = 5;
4076
+ HOOK_MARKER = "ascenda-claude-hook";
4077
+ USAGE = `ascenda-claude-hook setup \u2014 wire Claude Code to Ascenda telemetry
4078
+
4079
+ npx @ascenda-one/claude-code-hooks setup [options]
4080
+ npx @ascenda-one/claude-code-hooks status
4081
+ npx @ascenda-one/claude-code-hooks uninstall
4082
+
4083
+ Options
4084
+ --api-base-url <url> ingest host (default ${DEFAULT_API_BASE_URL})
4085
+ --local [port] shorthand for the local dev server (default port 4477)
4086
+ --tool-installation-id <id> reuse an existing pairing instead of creating one
4087
+ --token <eventWriteToken> reuse an existing token (stored 0600, never printed)
4088
+ --scope project|user where hooks are registered (default project)
4089
+ --project-dir <path> project root for --scope project (default cwd)
4090
+ --dry-run print what would change, write nothing
4091
+ -h, --help
4092
+ `;
4093
+ }
4094
+ });
4095
+
4096
+ // src/cli.ts
4097
+ var import_tool_kit9 = __toESM(require_out2(), 1);
4098
+ import { randomUUID as randomUUID2 } from "node:crypto";
4099
+ import * as fs2 from "node:fs";
4100
+
4101
+ // src/ascendaClient.ts
4102
+ var import_tool_kit = __toESM(require_out2(), 1);
4103
+ var import_tool_kit2 = __toESM(require_out2(), 1);
4104
+ var AscendaClient = class {
4105
+ sender;
4106
+ constructor(config) {
4107
+ this.sender = new import_tool_kit.AscendaEventSender({
4108
+ apiBaseUrl: config.apiBaseUrl,
4109
+ toolInstallationId: config.toolInstallationId,
4110
+ source: "claude_code",
4111
+ eventWriteToken: config.eventWriteToken,
4112
+ tokenFilePath: config.tokenFilePath,
4113
+ stateFilePath: config.stateFilePath,
4114
+ outboxFilePath: config.outboxFilePath,
4115
+ sessionId: config.sessionId,
4116
+ workspaceHash: config.workspaceHash,
4117
+ projectHash: config.projectHash
4118
+ });
4119
+ }
4120
+ /** The journal entry written by the most recent {@link send}. */
4121
+ get state() {
4122
+ return this.sender.state;
4123
+ }
4124
+ async send(mapped) {
4125
+ return this.sender.send(mapped);
4126
+ }
4127
+ async renewEventToken() {
4128
+ return this.sender.renewEventToken();
4129
+ }
4130
+ };
4131
+
4132
+ // src/cli.ts
4133
+ init_config();
2029
4134
 
2030
4135
  // src/mapClaudeEvent.ts
2031
- var import_tool_kit5 = __toESM(require_out2(), 1);
4136
+ var import_tool_kit7 = __toESM(require_out2(), 1);
4137
+ init_types();
2032
4138
 
2033
4139
  // src/safeExtract.ts
2034
- var import_tool_kit4 = __toESM(require_out2(), 1);
4140
+ var import_tool_kit6 = __toESM(require_out2(), 1);
2035
4141
 
2036
4142
  // src/mapClaudeEvent.ts
2037
4143
  function mapClaudeEvent(hookName, input) {
2038
- 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) => ({
2039
4148
  ...event,
2040
- metadata: { host: CLAUDE_HOST, ...event.metadata }
4149
+ metadata: { host: CLAUDE_HOST, ...branchHash ? { branchHash } : {}, ...event.metadata }
2041
4150
  }));
2042
4151
  }
2043
4152
  function mapEvent(hookName, input) {
@@ -2069,23 +4178,35 @@ function mapEvent(hookName, input) {
2069
4178
  }
2070
4179
  }
2071
4180
  function isNewSessionStart(input) {
2072
- const source = (0, import_tool_kit4.getString)(input, ["source"]);
4181
+ const source = (0, import_tool_kit6.getString)(input, ["source"]);
2073
4182
  return !source || source === "startup" || source === "resume";
2074
4183
  }
2075
4184
  function milestoneInviting(input) {
2076
- if ((0, import_tool_kit4.outcomeForHook)("PostToolUse", input) !== "success") return false;
2077
- const command = (0, import_tool_kit4.getString)(input, ["command"]) ?? (0, import_tool_kit4.getNestedString)(input, [["tool_input", "command"], ["input", "command"], ["parameters", "command"]]);
2078
- return (0, import_tool_kit5.invitesDebrief)((0, import_tool_kit5.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));
2079
4188
  }
2080
4189
  function mapSessionStart(input) {
2081
4190
  if (!isNewSessionStart(input)) return [];
2082
- 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
+ }];
2083
4203
  }
2084
4204
  function mapUserPromptSubmit(input) {
2085
- const prompt = (0, import_tool_kit4.getString)(input, ["prompt", "userPrompt", "message"]) ?? (0, import_tool_kit4.getNestedString)(input, [["payload", "prompt"], ["payload", "message"]]);
2086
- const events = [{ eventType: "ai_prompt_submitted", severity: "low", metadata: { promptClass: "unknown" } }];
2087
- if ((0, import_tool_kit4.looksLikeCorrection)(prompt)) {
2088
- 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 } });
2089
4210
  }
2090
4211
  return events;
2091
4212
  }
@@ -2095,41 +4216,50 @@ function mapPreToolUse(input) {
2095
4216
  function mapPostToolUse(hookName, input) {
2096
4217
  const toolName = getToolName(input);
2097
4218
  const safeToolName = sanitiseToolName(toolName);
2098
- const outcome = (0, import_tool_kit4.outcomeForHook)(hookName, input);
2099
- const durationMs = (0, import_tool_kit4.getNumber)(input, ["duration_ms", "durationMs", "elapsedMs"]) ?? (0, import_tool_kit4.getNestedNumber)(input, [["tool_response", "durationMs"], ["result", "durationMs"]]);
2100
- const command = (0, import_tool_kit4.getString)(input, ["command"]) ?? (0, import_tool_kit4.getNestedString)(input, [["tool_input", "command"], ["input", "command"], ["parameters", "command"]]);
2101
- const commandClass = (0, import_tool_kit5.classifyCommand)(command);
2102
- const gitAction = outcome === "success" ? (0, import_tool_kit5.classifyGitAction)(command) : void 0;
2103
- const milestoneKind = outcome === "success" ? (0, import_tool_kit5.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);
2104
4226
  if (outcome === "cancelled") {
2105
- return [{ eventType: "ai_tool_call_failed", severity: "low", metadata: { toolName: safeToolName, commandClass, outcome, durationBucket: (0, import_tool_kit4.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 } }];
2106
4228
  }
2107
4229
  if (outcome === "failure") {
2108
- if (toolName?.toLowerCase() === "bash" && (0, import_tool_kit5.isVerificationCommand)(commandClass)) {
2109
- return [{ eventType: "compile_error", severity: "medium", metadata: { toolName: safeToolName, commandClass, outcome, durationBucket: (0, import_tool_kit4.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 } }];
2110
4232
  }
2111
- return [{ eventType: "ai_tool_call_failed", severity: "medium", metadata: { toolName: safeToolName, commandClass, outcome, durationBucket: (0, import_tool_kit4.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 } }];
2112
4234
  }
2113
4235
  if (isWriteTool(toolName)) {
2114
4236
  const linesChanged = computeLinesChanged(toolName, input);
4237
+ const userModified = (0, import_tool_kit6.getNested)(input, ["tool_response", "userModified"]);
2115
4238
  return [{
2116
4239
  eventType: toolName?.toLowerCase() === "write" ? "ai_file_write" : "ai_file_edit",
2117
4240
  severity: "low",
2118
4241
  metadata: {
2119
4242
  toolName: safeToolName,
2120
4243
  outcome,
2121
- durationBucket: (0, import_tool_kit4.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 } : {},
2122
4252
  // The boundary C2/the macOS work-self-report card triggers on: at
2123
4253
  // "200+" this is the "substantial accepted change" moment. No
2124
4254
  // second event type exists for this — the bucket on the existing
2125
4255
  // creation event *is* the boundary, deliberately, since the write
2126
4256
  // already happened; there is nothing else to mark.
2127
- ...linesChanged !== void 0 ? { linesChangedBucket: (0, import_tool_kit4.bucketLinesChanged)(linesChanged) } : {}
4257
+ ...linesChanged !== void 0 ? { linesChangedBucket: (0, import_tool_kit6.bucketLinesChanged)(linesChanged) } : {}
2128
4258
  }
2129
4259
  }];
2130
4260
  }
2131
- if (toolName?.toLowerCase() === "bash" && (0, import_tool_kit5.isVerificationCommand)(commandClass)) {
2132
- return [{ eventType: "editor_verification_activity", severity: "low", metadata: { toolName: safeToolName, commandClass, outcome, durationBucket: (0, import_tool_kit4.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 } }];
2133
4263
  }
2134
4264
  return [{
2135
4265
  eventType: "ai_tool_call_completed",
@@ -2138,13 +4268,14 @@ function mapPostToolUse(hookName, input) {
2138
4268
  toolName: safeToolName,
2139
4269
  commandClass,
2140
4270
  outcome,
2141
- durationBucket: (0, import_tool_kit4.bucketDurationMs)(durationMs),
4271
+ durationBucket: (0, import_tool_kit6.bucketDurationMs)(durationMs),
4272
+ ...autonomy,
2142
4273
  // The boundary and rework signal both ride this existing event rather
2143
4274
  // than minting a type: the backend already reads `gitAction` off any
2144
4275
  // event, and a commit is not a different *kind* of thing happening, it
2145
4276
  // is a fact about the tool call that just happened.
2146
4277
  ...gitAction !== void 0 ? { gitAction } : {},
2147
- ...(0, import_tool_kit5.isReworkGitAction)(gitAction) ? { activity: "rework_reversion" } : {},
4278
+ ...(0, import_tool_kit7.isReworkGitAction)(gitAction) ? { activity: "rework_reversion" } : {},
2148
4279
  // Same reasoning as `gitAction` above, one grain coarser: a milestone is
2149
4280
  // a fact about the tool call that just happened, not a different kind of
2150
4281
  // event. It rides here so the record carries the work's own rhythm —
@@ -2154,23 +4285,53 @@ function mapPostToolUse(hookName, input) {
2154
4285
  }];
2155
4286
  }
2156
4287
  function mapPreCompact(input) {
2157
- const trigger = (0, import_tool_kit4.getString)(input, ["trigger", "reason", "compactType", "type"]) ?? (0, import_tool_kit4.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"]]);
2158
4289
  const isManual = trigger?.toLowerCase().includes("manual") ?? false;
2159
4290
  return [{ eventType: isManual ? "context_compression_manual" : "context_compression_auto", severity: isManual ? "medium" : "high", metadata: { trigger: isManual ? "manual" : "auto", reason: "context_limit" } }];
2160
4291
  }
2161
4292
  function mapStop(input) {
2162
- const durationMs = (0, import_tool_kit4.getNumber)(input, ["durationMs", "duration_ms", "elapsedMs"]) ?? (0, import_tool_kit4.getNestedNumber)(input, [["session", "durationMs"], ["payload", "durationMs"]]);
2163
- const durationBucket = (0, import_tool_kit4.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);
2164
4295
  if (durationBucket === "30-60m" || durationBucket === "60m+") {
2165
- 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) } }];
2166
4297
  }
2167
4298
  return [];
2168
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
+ }
2169
4330
  function getToolName(input) {
2170
- return (0, import_tool_kit4.getString)(input, ["toolName", "tool_name", "name"]) ?? (0, import_tool_kit4.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"]]);
2171
4332
  }
2172
4333
  function computeLinesChanged(toolName, input) {
2173
- const toolInput = (0, import_tool_kit4.getNested)(input, ["tool_input"]) ?? (0, import_tool_kit4.getNested)(input, ["input"]) ?? (0, import_tool_kit4.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"]);
2174
4335
  if (!toolInput || typeof toolInput !== "object") return void 0;
2175
4336
  const record = toolInput;
2176
4337
  switch (toolName?.toLowerCase()) {
@@ -2216,6 +4377,7 @@ function sanitiseToolName(toolName) {
2216
4377
  }
2217
4378
 
2218
4379
  // src/cli.ts
4380
+ init_types();
2219
4381
  var INTENTION_INVITE = "Ascenda tip: if it's natural, you can ask what would make this session count before diving in \u2014 one line is enough. Not a required step, and skip it entirely if the user is already mid-task.";
2220
4382
  var MILESTONE_DEBRIEF_INVITE = "Ascenda tip: that finished a piece of work. If the moment suits, it's worth a short debrief \u2014 what moved, what's still unresolved, and what you'd do differently next time. One or two lines. Skip it if they're already onto the next thing.";
2221
4383
  async function runPair() {
@@ -2223,8 +4385,8 @@ async function runPair() {
2223
4385
  const flagIndex = process.argv.indexOf("--tool-type");
2224
4386
  const toolType = flagIndex !== -1 ? (process.argv[flagIndex + 1] ?? "").trim() || ASCENDA_TOOL_TYPE : ASCENDA_TOOL_TYPE;
2225
4387
  const existing = process.env.ASCENDA_TOOL_INSTALLATION_ID?.trim();
2226
- const toolInstallationId = existing && existing.includes(":") ? existing : `${toolType}:${randomUUID()}`;
2227
- const session = await (0, import_tool_kit6.createPairingSession)(apiBaseUrl, toolInstallationId, toolType, toolType === ASCENDA_TOOL_TYPE ? "Claude Code" : toolType);
4388
+ const toolInstallationId = existing && existing.includes(":") ? existing : `${toolType}:${randomUUID2()}`;
4389
+ const session = await (0, import_tool_kit9.createPairingSession)(apiBaseUrl, toolInstallationId, toolType, toolType === ASCENDA_TOOL_TYPE ? "Claude Code" : toolType);
2228
4390
  const code = session.deviceCode ?? session.code;
2229
4391
  await writeStdout(
2230
4392
  `
@@ -2237,8 +4399,8 @@ Waiting for confirmation (expires ${session.expiresAt})...
2237
4399
  );
2238
4400
  const deadline = Date.now() + 11 * 60 * 1e3;
2239
4401
  while (Date.now() < deadline) {
2240
- await new Promise((resolve) => setTimeout(resolve, 3e3));
2241
- const status = await (0, import_tool_kit6.getPairingStatus)(apiBaseUrl, session.pairingSessionId);
4402
+ await new Promise((resolve2) => setTimeout(resolve2, 3e3));
4403
+ const status = await (0, import_tool_kit9.getPairingStatus)(apiBaseUrl, session.pairingSessionId);
2242
4404
  if (status.status === "pending") continue;
2243
4405
  if (status.status !== "paired") {
2244
4406
  process.stderr.write(`Pairing ${status.status}. Run the command again for a fresh code.
@@ -2254,8 +4416,8 @@ Waiting for confirmation (expires ${session.expiresAt})...
2254
4416
  process.exitCode = 1;
2255
4417
  return;
2256
4418
  }
2257
- const tokenFilePath = (0, import_tool_kit6.defaultTokenFilePath)(pairedId);
2258
- (0, import_tool_kit6.persistEventWriteToken)(tokenFilePath, status.eventWriteToken);
4419
+ const tokenFilePath = (0, import_tool_kit9.defaultTokenFilePath)(pairedId);
4420
+ (0, import_tool_kit9.persistEventWriteToken)(tokenFilePath, status.eventWriteToken);
2259
4421
  await writeStdout(
2260
4422
  `Paired. Write token saved to ${tokenFilePath}
2261
4423
 
@@ -2270,9 +4432,14 @@ One step left \u2014 add this to your shell profile (~/.zshrc), then restart Cla
2270
4432
  process.stderr.write("Timed out waiting for confirmation. Run the command again for a fresh code.\n");
2271
4433
  process.exitCode = 1;
2272
4434
  }
4435
+ var MANAGEMENT_COMMANDS = /* @__PURE__ */ new Set(["setup", "install", "status", "uninstall", "-h", "--help"]);
2273
4436
  async function main() {
2274
4437
  const command = process.argv[2];
2275
- if (!command) throw new Error("Usage: ascenda-claude-hook <ClaudeHookEventName> | pair | doctor");
4438
+ if (!command) {
4439
+ throw new Error(
4440
+ "Usage: ascenda-claude-hook <ClaudeHookEventName> | pair | doctor | setup | status | uninstall"
4441
+ );
4442
+ }
2276
4443
  if (command === "pair") {
2277
4444
  await runPair();
2278
4445
  return;
@@ -2281,8 +4448,15 @@ async function main() {
2281
4448
  await runDoctor();
2282
4449
  return;
2283
4450
  }
4451
+ if (MANAGEMENT_COMMANDS.has(command)) {
4452
+ const { runSetup: runSetup2 } = await Promise.resolve().then(() => (init_setup(), setup_exports));
4453
+ setupExitCode = await runSetup2(process.argv.slice(2));
4454
+ return;
4455
+ }
2284
4456
  if (!isClaudeHookEventName(command)) {
2285
- throw new Error(`Unknown command "${command}". Expected a Claude Code hook name, "pair" or "doctor".`);
4457
+ throw new Error(
4458
+ `Unknown command "${command}". Expected a Claude Code hook name, "pair", "doctor", "setup", "status" or "uninstall".`
4459
+ );
2286
4460
  }
2287
4461
  const hookName = command;
2288
4462
  const input = await readJsonFromStdin();
@@ -2299,18 +4473,22 @@ async function main() {
2299
4473
  await writeStdout(JSON.stringify({
2300
4474
  hookSpecificOutput: { hookEventName: hookName, additionalContext: contextParts.join("\n\n") }
2301
4475
  }));
2302
- if (pending) (0, import_tool_kit6.markFailureNotified)(pending.stateFilePath, pending.state);
4476
+ if (pending) (0, import_tool_kit9.markFailureNotified)(pending.stateFilePath, pending.state);
2303
4477
  }
2304
4478
  await emitLive(hookName, input);
2305
4479
  const mappedEvents = mapClaudeEvent(hookName, input);
2306
4480
  if (!mappedEvents.length) return;
2307
- const workContext = (0, import_tool_kit6.deriveWorkContext)((0, import_tool_kit6.getString)(input, ["cwd"]) ?? process.cwd());
2308
- if (workContext) (0, import_tool_kit6.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
+ }
2309
4486
  let config;
2310
4487
  try {
2311
4488
  config = loadConfigFromEnv();
2312
4489
  } catch (error) {
2313
- const logFile = (0, import_tool_kit6.resolveEventLogPath)();
4490
+ if (error instanceof MissingInstallationIdError) journalSkippedSend(error);
4491
+ const logFile = (0, import_tool_kit9.resolveEventLogPath)();
2314
4492
  if (!logFile) throw error;
2315
4493
  for (const event of mappedEvents) logUnsent(logFile, event, workContext);
2316
4494
  return;
@@ -2325,28 +4503,33 @@ async function main() {
2325
4503
  return;
2326
4504
  }
2327
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
+ }
2328
4511
  function explainRejection(result) {
2329
4512
  if (result === "consent_missing") return "Ascenda telemetry rejected: renew IDE telemetry consent in the Ascenda app.";
2330
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`.";
2331
- 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.";
2332
4515
  return `Ascenda telemetry rejected: ${result}`;
2333
4516
  }
2334
4517
  async function emitLive(hookName, input) {
2335
4518
  const event = hookName === "UserPromptSubmit" ? "prompt_submitted" : hookName === "PreToolUse" ? "tool_call" : hookName === "PreCompact" ? "compaction" : hookName === "PostToolUseFailure" ? "tool_failure" : hookName === "Stop" ? "stop" : void 0;
2336
4519
  if (!event) return;
2337
4520
  try {
2338
- const prompt = event === "prompt_submitted" ? (0, import_tool_kit6.getString)(input, ["prompt", "userPrompt", "message"]) ?? (0, import_tool_kit6.getNestedString)(input, [["payload", "prompt"], ["payload", "message"]]) : void 0;
2339
- const promptSource = event === "prompt_submitted" ? (0, import_tool_kit6.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;
2340
4523
  const queued = promptSource === void 0 ? void 0 : promptSource === "queued";
2341
- await (0, import_tool_kit6.emitLiveSignal)({
4524
+ await (0, import_tool_kit9.emitLiveSignal)({
2342
4525
  tool: process.env.ASCENDA_TOOL_TYPE ?? "claude_code",
2343
4526
  // Concurrent sessions must count as separate streams for the X gauge.
2344
4527
  // Without a session id every window collapses into one, so fall back to
2345
4528
  // this process's parent — still per-session in practice, since Claude
2346
4529
  // Code spawns hooks from the session process.
2347
- session: (0, import_tool_kit6.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}`,
2348
4531
  event,
2349
- ...prompt !== void 0 ? { sizeBucket: (0, import_tool_kit6.bucketPromptSize)(prompt) } : {},
4532
+ ...prompt !== void 0 ? { sizeBucket: (0, import_tool_kit9.bucketPromptSize)(prompt) } : {},
2350
4533
  ...queued !== void 0 ? { queued } : {}
2351
4534
  });
2352
4535
  } catch {
@@ -2355,11 +4538,15 @@ async function emitLive(hookName, input) {
2355
4538
  function pendingFailureNotice(hookName) {
2356
4539
  if (hookName !== "SessionStart" && hookName !== "PostToolUse") return void 0;
2357
4540
  if (process.env.ASCENDA_DISABLE_FAILURE_NOTICE === "true") return void 0;
2358
- const rawId = process.env.ASCENDA_TOOL_INSTALLATION_ID?.trim();
2359
- if (!rawId) return void 0;
2360
- const stateFilePath = resolveStateFilePath(normalizeToolInstallationId(rawId));
2361
- const state = (0, import_tool_kit6.readCollectorState)(stateFilePath);
2362
- if (!(0, import_tool_kit6.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;
2363
4550
  const since = state.lastSuccessAt ? `since ${state.lastSuccessAt}` : "and has never succeeded on this machine";
2364
4551
  return {
2365
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.`,
@@ -2378,34 +4565,41 @@ function describeOutcome(state) {
2378
4565
  return `the events were refused as invalid${status}`;
2379
4566
  case "transport_error":
2380
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`;
2381
4570
  default:
2382
4571
  return `last outcome ${state.lastOutcome}${status}`;
2383
4572
  }
2384
4573
  }
2385
4574
  function writeStdout(text) {
2386
- return new Promise((resolve) => {
2387
- process.stdout.write(text, () => resolve());
4575
+ return new Promise((resolve2) => {
4576
+ process.stdout.write(text, () => resolve2());
2388
4577
  });
2389
4578
  }
2390
4579
  async function runDoctor() {
2391
4580
  const lines = ["Ascenda collector doctor", ""];
2392
- const rawId = process.env.ASCENDA_TOOL_INSTALLATION_ID?.trim();
2393
4581
  const apiBaseUrl = (process.env.ASCENDA_API_BASE_URL ?? "https://api.ascenda.one").replace(/\/$/, "");
2394
4582
  lines.push(` API base URL ${apiBaseUrl}`);
2395
- lines.push(` Installation id ${rawId || "(unset \u2014 ASCENDA_TOOL_INSTALLATION_ID is empty)"}`);
2396
- 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));
2397
4589
  lines.push("", " Not paired on this machine. Run:", " npx @ascenda-one/claude-code-hooks pair");
2398
4590
  await writeStdout(`${lines.join("\n")}
2399
4591
  `);
2400
4592
  return;
2401
4593
  }
2402
- const toolInstallationId = normalizeToolInstallationId(rawId);
2403
- const tokenFilePath = process.env.ASCENDA_EVENT_WRITE_TOKEN_FILE ?? (0, import_tool_kit6.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);
2404
4598
  lines.push(` Token file ${tokenFilePath}`);
2405
4599
  lines.push(` Token ${describeToken(tokenFilePath)}`);
2406
4600
  const stateFilePath = resolveStateFilePath(toolInstallationId);
2407
4601
  lines.push(` Journal ${stateFilePath}`);
2408
- const state = (0, import_tool_kit6.readCollectorState)(stateFilePath);
4602
+ const state = (0, import_tool_kit9.readCollectorState)(stateFilePath);
2409
4603
  if (!state) {
2410
4604
  lines.push(" Last outcome (no journal yet \u2014 no send attempted since this version was installed)");
2411
4605
  } else {
@@ -2417,6 +4611,8 @@ async function runDoctor() {
2417
4611
  lines.push(` Consecutive failures ${state.consecutiveFailures}`);
2418
4612
  if (state.failingSince) lines.push(` Failing since ${state.failingSince}`);
2419
4613
  }
4614
+ lines.push(...skippedSendLines(stateFilePath));
4615
+ lines.push(...outboxLines(toolInstallationId, state));
2420
4616
  lines.push("", " Live round trip...");
2421
4617
  lines.push(` ${await liveRoundTrip()}`);
2422
4618
  await writeStdout(`${lines.join("\n")}
@@ -2433,12 +4629,65 @@ async function liveRoundTrip() {
2433
4629
  if (result === "accepted") return "OK \u2014 event accepted by the ingest endpoint.";
2434
4630
  return `FAILED \u2014 ${explainRejection(result)}`;
2435
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
+ }
2436
4685
  function describeToken(tokenFilePath) {
2437
4686
  try {
2438
- if (!fs.existsSync(tokenFilePath)) {
4687
+ if (!fs2.existsSync(tokenFilePath)) {
2439
4688
  return process.env.ASCENDA_EVENT_WRITE_TOKEN ? "from ASCENDA_EVENT_WRITE_TOKEN (no file)" : "MISSING \u2014 run `pair`";
2440
4689
  }
2441
- const stat = fs.statSync(tokenFilePath);
4690
+ const stat = fs2.statSync(tokenFilePath);
2442
4691
  const ageDays = Math.floor((Date.now() - stat.mtimeMs) / 864e5);
2443
4692
  return `present, last written ${stat.mtime.toISOString()} (${ageDays}d ago)`;
2444
4693
  } catch (error) {
@@ -2446,14 +4695,14 @@ function describeToken(tokenFilePath) {
2446
4695
  }
2447
4696
  }
2448
4697
  function logUnsent(logFile, event, workContext) {
2449
- const payload = (0, import_tool_kit6.buildEventPayload)({
4698
+ const payload = (0, import_tool_kit9.buildEventPayload)({
2450
4699
  toolInstallationId: `${ASCENDA_TOOL_TYPE}:unpaired`,
2451
4700
  source: "claude_code",
2452
4701
  sessionId: process.env.ASCENDA_SESSION_ID ?? null,
2453
4702
  workspaceHash: envHashOverride("ASCENDA_WORKSPACE_HASH") ?? workContext?.workspaceHash ?? null,
2454
4703
  projectHash: envHashOverride("ASCENDA_PROJECT_HASH") ?? workContext?.projectHash ?? null
2455
4704
  }, event);
2456
- (0, import_tool_kit6.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 });
2457
4706
  }
2458
4707
  async function readJsonFromStdin() {
2459
4708
  const chunks = [];
@@ -2466,6 +4715,7 @@ async function readJsonFromStdin() {
2466
4715
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
2467
4716
  return parsed;
2468
4717
  }
4718
+ var setupExitCode;
2469
4719
  main().catch((error) => {
2470
4720
  console.error(error instanceof Error ? error.message : String(error));
2471
- }).finally(() => process.exit(process.exitCode ?? 0));
4721
+ }).finally(() => process.exit(setupExitCode ?? process.exitCode ?? 0));