@ascenda-one/claude-code-hooks 0.1.27 → 0.1.33

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
@@ -414,39 +414,44 @@ var require_metricKeys = __commonJS({
414
414
  exports.METRIC_KEYS = {
415
415
  // ── Read by a backend reader ────────────────────────────────────────────
416
416
  contextWindowPeakPct: {
417
+ family: "context",
417
418
  readBy: ["backend", "handoff"],
418
419
  backendAliases: CONTEXT_WINDOW_CANONICAL_ALIASES,
419
420
  unit: "fraction of the context window (0\u20131; uncapped for >200k contexts)",
420
421
  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
  },
422
423
  contextUsagePercent: {
424
+ family: "context",
423
425
  readBy: ["backend", "handoff"],
424
426
  backendAliases: CONTEXT_WINDOW_CURSOR_PERCENT_ALIASES,
425
427
  unit: "percent (0\u2013100)",
426
428
  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
429
  },
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"] },
430
+ promptCount: { family: "counts", readBy: ["backend", "handoff"], backendAliases: ["promptCount", "prompt_count"] },
431
+ sessionMinutes: { family: "session", readBy: ["backend"], backendAliases: ["sessionMinutes", "session_minutes"], unit: "minutes" },
432
+ durationBucket: { family: "session", readBy: ["backend", "handoff"], backendAliases: ["durationBucket", "duration_bucket"] },
433
+ afterHoursPrompts: { family: "clock", readBy: ["backend", "handoff"], backendAliases: ["afterHoursPrompts", "after_hours_prompts"] },
434
+ inputTokens: { family: "context", readBy: ["backend"], backendAliases: ["inputTokens", "input_tokens"], unit: "tokens" },
435
+ outputTokens: { family: "context", readBy: ["backend"], backendAliases: ["outputTokens", "output_tokens"], unit: "tokens" },
436
+ cacheReadTokens: { family: "context", readBy: ["backend"], backendAliases: ["cacheReadTokens", "cache_read_tokens"], unit: "tokens" },
437
+ queuedPrompts: { family: "counts", readBy: ["backend"], backendAliases: ["queuedPrompts", "queued_prompts"] },
438
+ linesChangedBucket: { family: "edits", readBy: ["backend"], backendAliases: ["linesChangedBucket", "lines_changed_bucket"] },
437
439
  // ── Read by the local handoff only ──────────────────────────────────────
438
- activeMinutes: { readBy: ["handoff"], unit: "minutes" },
440
+ activeMinutes: { family: "session", readBy: ["handoff"], unit: "minutes" },
439
441
  syntheticPromptLines: {
442
+ family: "reading",
440
443
  readBy: ["handoff"],
441
444
  unit: "lines",
442
445
  note: "Main-thread user lines the runtime wrote on the person's behalf (notifications, its own bookkeeping, slash-command wrappers, interrupt markers) and promptCount left out. Claude Code only; the receipt for the handoff's promptBasis. Counted per transcript, so a resumed transcript's copies count again."
443
446
  },
444
447
  dispatchedPromptLines: {
448
+ family: "reading",
445
449
  readBy: ["handoff"],
446
450
  unit: "lines",
447
451
  note: "Main-thread user lines that read as typed but are the prompt of a chip that launched the session, so promptCount left them out. Counted once per line across the store, as prompts are. Claude Code only; written beside promptBasis: typed_once."
448
452
  },
449
453
  interruptedRuns: {
454
+ family: "waiting",
450
455
  readBy: ["handoff"],
451
456
  unit: "runs",
452
457
  note: "Agent turns the person cut short with an interrupt while the turn was still going. A count per session, never a rate. Claude Code only; a handoff that counted them says so with interruptedRunsCounted, and absent means not counted, never zero."
@@ -462,11 +467,13 @@ var require_metricKeys = __commonJS({
462
467
  * they are.
463
468
  */
464
469
  handsOnMinutes: {
470
+ family: "session",
465
471
  readBy: ["handoff"],
466
472
  unit: "minutes",
467
473
  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."
468
474
  },
469
475
  agentSupervisingMinutes: {
476
+ family: "session",
470
477
  readBy: ["handoff"],
471
478
  unit: "minutes",
472
479
  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."
@@ -476,127 +483,147 @@ var require_metricKeys = __commonJS({
476
483
  // a complete one, and a reader that ignores them is choosing to, rather than
477
484
  // being unable to.
478
485
  activeSplitInstants: {
486
+ family: "session",
479
487
  readBy: ["diagnostic"],
480
488
  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."
481
489
  },
482
490
  activeSplitUndatedLines: {
491
+ family: "session",
483
492
  readBy: ["diagnostic"],
484
493
  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."
485
494
  },
486
495
  activeSplitUnposturedInstants: {
496
+ family: "posture",
487
497
  readBy: ["diagnostic"],
488
498
  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."
489
499
  },
490
- afterHoursRequests: { readBy: ["handoff"] },
491
- approximateLintErrorsCount: { readBy: ["handoff"] },
492
- canceledCount: { readBy: ["handoff"] },
493
- chatEditCount: { readBy: ["handoff"] },
500
+ afterHoursRequests: { family: "clock", readBy: ["handoff"] },
501
+ approximateLintErrorsCount: { family: "outcome", readBy: ["handoff"] },
502
+ canceledCount: { family: "outcome", readBy: ["handoff"] },
503
+ chatEditCount: { family: "edits", readBy: ["handoff"] },
494
504
  compactionCount: {
505
+ family: "context",
495
506
  readBy: ["handoff"],
496
507
  note: "The backend counts context_compression_* event rows, not this key. Both are emitted; this one is for the handoff."
497
508
  },
498
509
  contextWindowPeakTokens: {
510
+ family: "context",
499
511
  readBy: ["handoff"],
500
512
  unit: "tokens",
501
513
  note: "The measured quantity, with no assumed denominator. Prefer this to the ratio for any within-person baseline."
502
514
  },
503
515
  contextWindowTokens: {
516
+ family: "context",
504
517
  readBy: ["handoff"],
505
518
  unit: "tokens",
506
519
  note: "Codex only: the model_context_window the rollout itself recorded \u2014 the real denominator its contextWindowPeakPct was computed against. Claude Code records no window and its ratio assumes 200k; absent here means the store never said."
507
520
  },
508
- date: { readBy: ["handoff"] },
509
- errorCount: { readBy: ["handoff"] },
510
- filesChangedCount: { readBy: ["handoff"] },
511
- humanChangesCount: { readBy: ["handoff"] },
512
- linesAdded: { readBy: ["handoff"] },
513
- linesRemoved: { readBy: ["handoff"] },
514
- primaryModel: { readBy: ["handoff"] },
515
- requestCount: { readBy: ["handoff"] },
516
- sessionStartedAt: { readBy: ["handoff"] },
517
- subagentComposers: { readBy: ["handoff"] },
521
+ date: { family: "clock", readBy: ["handoff"] },
522
+ errorCount: { family: "outcome", readBy: ["handoff"] },
523
+ filesChangedCount: { family: "edits", readBy: ["handoff"] },
524
+ humanChangesCount: { family: "edits", readBy: ["handoff"] },
525
+ linesAdded: { family: "edits", readBy: ["handoff"] },
526
+ linesRemoved: { family: "edits", readBy: ["handoff"] },
527
+ primaryModel: {
528
+ family: "model",
529
+ readBy: ["backend", "handoff"],
530
+ backendAliases: ["primaryModel", "primary_model"],
531
+ note: "Read twice: the desktop's local handoff folds it, and a server-side reader resolves it to group a bucket's sessions by the model that served them. Declared handoff-only until 23 Sep 2026 \u2014 see toolName for why that direction of mistake has no symptom."
532
+ },
533
+ requestCount: { family: "counts", readBy: ["handoff"] },
534
+ sessionStartedAt: { family: "session", readBy: ["handoff"] },
535
+ subagentComposers: { family: "counts", readBy: ["handoff"] },
518
536
  subagentToolCallCount: {
537
+ family: "tools",
519
538
  readBy: ["handoff"],
520
539
  note: "Claude Code only: calls made inside subagent transcripts, kept out of toolCallCount so the main-loop count matches what the wire events carry."
521
540
  },
522
- subagentTranscripts: { readBy: ["handoff"] },
541
+ subagentTranscripts: { family: "counts", readBy: ["handoff"] },
523
542
  toolCallCount: {
543
+ family: "tools",
524
544
  readBy: ["handoff"],
525
545
  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."
526
546
  },
527
547
  toolCallsUndated: {
548
+ family: "tools",
528
549
  readBy: ["handoff"],
529
550
  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."
530
551
  },
531
- toolFailureCount: { readBy: ["handoff"] },
532
- totalEntryCount: { readBy: ["handoff"] },
552
+ toolFailureCount: { family: "outcome", readBy: ["handoff"] },
553
+ totalEntryCount: { family: "counts", readBy: ["handoff"] },
533
554
  userModifiedEditCount: {
555
+ family: "edits",
534
556
  readBy: ["handoff"],
535
557
  note: "Null, never 0 \u2014 Claude Code never sets userModified true, so 0 would assert 'no AI edit was ever corrected by hand'."
536
558
  },
537
559
  // ── Diagnostic: read by nobody, on purpose ──────────────────────────────
538
- abandonedPromptCount: { readBy: ["diagnostic"] },
560
+ abandonedPromptCount: { family: "counts", readBy: ["diagnostic"] },
539
561
  // Epoch-marker metrics. The marker is local-only and never reaches the wire
540
562
  // (see EXTRACTION_EPOCH_KIND), but it travels as a NormalizedHistoricalEvent
541
563
  // and so is keyed by the same vocabulary.
542
- windowOldest: { readBy: ["handoff"], note: "Oldest event the extraction saw \u2014 the marker's left edge." },
543
- windowNewest: { readBy: ["handoff"], note: "Newest event the extraction saw \u2014 the marker's right edge." },
544
- projectsWithNoReadableTranscript: { readBy: ["diagnostic"] },
545
- unparsedComposerHeaders: { readBy: ["diagnostic"] },
546
- unknownComposerHeaderTypes: { readBy: ["diagnostic"] },
547
- orphanedBubbles: { readBy: ["diagnostic"] },
548
- orphanedSubagentBubbles: { readBy: ["diagnostic"] },
549
- sessionsWithoutTimeline: { readBy: ["diagnostic"] },
564
+ windowOldest: { family: "session", readBy: ["handoff"], note: "Oldest event the extraction saw \u2014 the marker's left edge." },
565
+ windowNewest: { family: "session", readBy: ["handoff"], note: "Newest event the extraction saw \u2014 the marker's right edge." },
566
+ projectsWithNoReadableTranscript: { family: "reading", readBy: ["diagnostic"] },
567
+ unparsedComposerHeaders: { family: "reading", readBy: ["diagnostic"] },
568
+ unknownComposerHeaderTypes: { family: "reading", readBy: ["diagnostic"] },
569
+ orphanedBubbles: { family: "reading", readBy: ["diagnostic"] },
570
+ orphanedSubagentBubbles: { family: "reading", readBy: ["diagnostic"] },
571
+ sessionsWithoutTimeline: { family: "reading", readBy: ["diagnostic"] },
550
572
  sessionsWithOnlyInheritedLines: {
573
+ family: "reading",
551
574
  readBy: ["diagnostic"],
552
575
  note: "Claude Code transcripts holding nothing but a copy of an ancestor's history, so no line's instant is theirs and no session is emitted for them. Excluded by rule, not a read failure: the work is in the transcript that owns it."
553
576
  },
554
- emptyComposers: { readBy: ["diagnostic"] },
555
- apiErrorCount: { readBy: ["diagnostic"] },
556
- assistantTurns: { readBy: ["diagnostic"] },
557
- compactionAutoCount: { readBy: ["diagnostic"] },
558
- compactionManualCount: { readBy: ["diagnostic"] },
559
- editDayCount: { readBy: ["diagnostic"] },
560
- emptyChatSessions: { readBy: ["diagnostic"] },
561
- gitBranch: { readBy: ["diagnostic"] },
562
- linesChanged: { readBy: ["diagnostic"] },
563
- malformedChatSessionLines: { readBy: ["diagnostic"] },
564
- malformedHistoryEntries: { readBy: ["diagnostic"] },
565
- mode: { readBy: ["diagnostic"] },
566
- modelCount: { readBy: ["diagnostic"] },
567
- modelSwitchCount: { readBy: ["diagnostic"] },
568
- rapidRepromptCount: { readBy: ["diagnostic"] },
569
- schemaUnreadable: { readBy: ["diagnostic"] },
570
- sessionCount: { readBy: ["diagnostic"] },
571
- sessionsFromBubbleTimeline: { readBy: ["diagnostic"] },
572
- sessionsFromCheckpointTimeline: { readBy: ["diagnostic"] },
573
- sessionsFromRecencyTimeline: { readBy: ["diagnostic"] },
574
- subagentAssistantTurns: { readBy: ["diagnostic"] },
575
- subagentPrompts: { readBy: ["diagnostic"] },
576
- subagentTokensTotal: { readBy: ["diagnostic"] },
577
+ emptyComposers: { family: "reading", readBy: ["diagnostic"] },
578
+ apiErrorCount: { family: "outcome", readBy: ["diagnostic"] },
579
+ assistantTurns: { family: "counts", readBy: ["diagnostic"] },
580
+ compactionAutoCount: { family: "context", readBy: ["diagnostic"] },
581
+ compactionManualCount: { family: "context", readBy: ["diagnostic"] },
582
+ editDayCount: { family: "clock", readBy: ["diagnostic"] },
583
+ emptyChatSessions: { family: "reading", readBy: ["diagnostic"] },
584
+ gitBranch: { family: "repo", readBy: ["diagnostic"] },
585
+ linesChanged: { family: "edits", readBy: ["diagnostic"] },
586
+ malformedChatSessionLines: { family: "reading", readBy: ["diagnostic"] },
587
+ malformedHistoryEntries: { family: "reading", readBy: ["diagnostic"] },
588
+ mode: { family: "posture", readBy: ["diagnostic"] },
589
+ modelCount: { family: "model", readBy: ["diagnostic"] },
590
+ modelSwitchCount: { family: "model", readBy: ["diagnostic"] },
591
+ rapidRepromptCount: { family: "counts", readBy: ["diagnostic"] },
592
+ schemaUnreadable: { family: "reading", readBy: ["diagnostic"] },
593
+ sessionCount: { family: "session", readBy: ["diagnostic"] },
594
+ sessionsFromBubbleTimeline: { family: "reading", readBy: ["diagnostic"] },
595
+ sessionsFromCheckpointTimeline: { family: "reading", readBy: ["diagnostic"] },
596
+ sessionsFromRecencyTimeline: { family: "reading", readBy: ["diagnostic"] },
597
+ subagentAssistantTurns: { family: "counts", readBy: ["diagnostic"] },
598
+ subagentPrompts: { family: "counts", readBy: ["diagnostic"] },
599
+ subagentTokensTotal: { family: "context", readBy: ["diagnostic"] },
577
600
  toolName: {
578
- readBy: ["diagnostic"],
579
- 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."
601
+ family: "tools",
602
+ readBy: ["backend"],
603
+ backendAliases: ["toolName", "tool_name"],
604
+ note: "Set per ai_tool_call_started event by #43's extractors. Declared diagnostic until 23 Sep 2026 on the belief that nothing resolved it server-side; two backend readers do \u2014 one to see a sub-agent dispatch, one composing per-tool metrics. This is the inverse of the mismatch this module was written for: contextUsagePercent was a key nobody read, and a key a reader resolves without being declared drops nothing, so it has no symptom at all. What it costs is that readBy stops being a true census of what the server sees, which is what you consult when deciding what a collector should stop sending. Registered after the fact in the first place: #38 and #43 merged past each other, and the union caught it on the next compile \u2014 metaLines all over again."
580
605
  },
581
- toolResultCount: { readBy: ["diagnostic"] },
582
- toolResultErrorCount: { readBy: ["diagnostic"] },
583
- unknownBubbles: { readBy: ["diagnostic"] },
584
- unknownLines: { readBy: ["diagnostic"] },
606
+ toolResultCount: { family: "tools", readBy: ["diagnostic"] },
607
+ toolResultErrorCount: { family: "outcome", readBy: ["diagnostic"] },
608
+ unknownBubbles: { family: "reading", readBy: ["diagnostic"] },
609
+ unknownLines: { family: "reading", readBy: ["diagnostic"] },
585
610
  metaLines: {
611
+ family: "reading",
586
612
  readBy: ["diagnostic"],
587
613
  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.'
588
614
  },
589
- unparsedBubbles: { readBy: ["diagnostic"] },
590
- unparsedChatSessionFiles: { readBy: ["diagnostic"] },
591
- unparsedHistoryFiles: { readBy: ["diagnostic"] },
592
- unparsedLines: { readBy: ["diagnostic"] },
593
- unreadableChatSessionFiles: { readBy: ["diagnostic"] },
594
- unreadableHistoryFiles: { readBy: ["diagnostic"] },
615
+ unparsedBubbles: { family: "reading", readBy: ["diagnostic"] },
616
+ unparsedChatSessionFiles: { family: "reading", readBy: ["diagnostic"] },
617
+ unparsedHistoryFiles: { family: "reading", readBy: ["diagnostic"] },
618
+ unparsedLines: { family: "reading", readBy: ["diagnostic"] },
619
+ unreadableChatSessionFiles: { family: "reading", readBy: ["diagnostic"] },
620
+ unreadableHistoryFiles: { family: "reading", readBy: ["diagnostic"] },
595
621
  unreadableRolloutFiles: {
622
+ family: "reading",
596
623
  readBy: ["diagnostic"],
597
624
  note: "Codex only: rollout files the extractor meant to read and could not open. Summed into the import's read-failure warning, so a store that is partly unreadable says so rather than reporting a short window as the whole."
598
625
  },
599
- unrecognisedChatSessionFiles: { readBy: ["diagnostic"] }
626
+ unrecognisedChatSessionFiles: { family: "reading", readBy: ["diagnostic"] }
600
627
  };
601
628
  function backendMetricKeys() {
602
629
  return Object.entries(exports.METRIC_KEYS).filter(([, spec]) => spec.readBy.includes("backend")).map(([key, spec]) => [key, spec.backendAliases ?? [key]]);
@@ -609,7 +636,7 @@ var require_out = __commonJS({
609
636
  "../packages/tool-contract/out/index.js"(exports) {
610
637
  "use strict";
611
638
  Object.defineProperty(exports, "__esModule", { value: true });
612
- 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 = exports.ASCENDA_ELAPSED_QUANTITIES = exports.ASCENDA_ACTIVE_TIME_QUANTITIES = exports.ASCENDA_TOOL_TYPES = exports.ASCENDA_TELEMETRY_SOURCES = void 0;
639
+ 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.EVENT_METADATA_DISCLOSURE = exports.COLLABORATION_EVENT_TYPES = exports.SEMANTIC_WORK_SIGNAL_EVENT_TYPES = exports.ASCENDA_ELAPSED_QUANTITIES = exports.ASCENDA_ACTIVE_TIME_QUANTITIES = exports.ASCENDA_TOOL_TYPES = exports.ASCENDA_TELEMETRY_SOURCES = void 0;
613
640
  exports.combineDisjointHalves = combineDisjointHalves;
614
641
  exports.requireComparableQuantities = requireComparableQuantities;
615
642
  exports.ASCENDA_TELEMETRY_SOURCES = [
@@ -677,6 +704,55 @@ var require_out = __commonJS({
677
704
  "review_given",
678
705
  "pull_request_opened"
679
706
  ];
707
+ exports.EVENT_METADATA_DISCLOSURE = {
708
+ language: "edits",
709
+ fileType: "edits",
710
+ durationBucket: "session",
711
+ tokenPressureBucket: "context",
712
+ linesChangedBucket: "edits",
713
+ commandClass: "counts",
714
+ gitAction: "git",
715
+ milestoneKind: "git",
716
+ branchHash: "repo",
717
+ autonomyMode: "posture",
718
+ modelClass: "model",
719
+ modelId: "model",
720
+ userModified: "edits",
721
+ outcome: "outcome",
722
+ trigger: "outcome",
723
+ promptClass: "counts",
724
+ reason: "outcome",
725
+ afterHours: "clock",
726
+ activity: "counts",
727
+ // One constant word, from the agent itself. The session sentence names it.
728
+ sessionEndReason: "session",
729
+ interruptionKind: "waiting",
730
+ // Claude Code's own opaque id for one subagent, and the class it belongs
731
+ // to. Never the agent's name or anything it was asked.
732
+ subagentId: "subagents",
733
+ subagentClass: "subagents",
734
+ // Free text by type, and written by no hook mapper — the IDE extension's
735
+ // test signal is the only producer. The setup disclosure's third refusal
736
+ // line says as much, and tool-kit's guard test fails if a mapper starts.
737
+ message: "counts",
738
+ host: "session",
739
+ // One constant word from the host's own environment: this machine, or a
740
+ // hosted session. The session sentence names it.
741
+ runtime: "session",
742
+ toolName: "tools",
743
+ simulated: "transport",
744
+ relatedEventType: "transport",
745
+ skillVersion: "transport",
746
+ // A hash computed before it reaches any collector; the task itself is never
747
+ // seen by this code, so there is nothing about the work here to disclose.
748
+ taskFingerprint: "transport",
749
+ importKey: "transport",
750
+ extractionId: "transport",
751
+ importSchema: "transport",
752
+ // The version of the Ascenda collector that sent this event. Names the
753
+ // build, and nothing about the work it observed.
754
+ collectorVersion: "transport"
755
+ };
680
756
  exports.EVENT_METADATA_FIELDS = [
681
757
  "language",
682
758
  "fileType",
@@ -700,13 +776,19 @@ var require_out = __commonJS({
700
776
  "message",
701
777
  "host",
702
778
  "toolName",
779
+ "runtime",
780
+ "sessionEndReason",
781
+ "interruptionKind",
782
+ "subagentId",
783
+ "subagentClass",
703
784
  "simulated",
704
785
  "relatedEventType",
705
786
  "skillVersion",
706
787
  "taskFingerprint",
707
788
  "importKey",
708
789
  "extractionId",
709
- "importSchema"
790
+ "importSchema",
791
+ "collectorVersion"
710
792
  ];
711
793
  exports.IDEMPOTENCY_KEY_MAX_LENGTH = 128;
712
794
  exports.TOOL_EVENT_DELIVERED_STATUSES = ["accepted", "duplicate"];
@@ -746,6 +828,12 @@ var require_out = __commonJS({
746
828
  // `ai_prompt_submitted` closes. Neutral so a marker sent once per turn
747
829
  // doesn't weigh on any workload leg.
748
830
  ai_turn_completed: "neutral",
831
+ // A subagent began or finished under a session. Boundaries, not work: the
832
+ // subagent's own tool calls and edits arrive as their own events and carry
833
+ // their own categories. A reader pairs these on `subagentId` to count how
834
+ // many agents ran at once; neutral so that count weighs on no workload leg.
835
+ subagent_started: "neutral",
836
+ subagent_stopped: "neutral",
749
837
  // The agent stopped and is waiting on the person: Claude Code's
750
838
  // `Notification`, Codex's `PermissionRequest`. Supervision, beside the other
751
839
  // oversight overhead, because that is what it is — time the person spends
@@ -818,9 +906,9 @@ var require_payload = __commonJS({
818
906
  }
819
907
  return void 0;
820
908
  }
821
- function getNested2(input, path3) {
909
+ function getNested2(input, path4) {
822
910
  let current = input;
823
- for (const segment of path3) {
911
+ for (const segment of path4) {
824
912
  if (!current || typeof current !== "object")
825
913
  return void 0;
826
914
  current = current[segment];
@@ -828,16 +916,16 @@ var require_payload = __commonJS({
828
916
  return current;
829
917
  }
830
918
  function getNestedString3(input, paths) {
831
- for (const path3 of paths) {
832
- const value = getNested2(input, path3);
919
+ for (const path4 of paths) {
920
+ const value = getNested2(input, path4);
833
921
  if (typeof value === "string" && value.trim())
834
922
  return value;
835
923
  }
836
924
  return void 0;
837
925
  }
838
926
  function getNestedNumber2(input, paths) {
839
- for (const path3 of paths) {
840
- const value = getNested2(input, path3);
927
+ for (const path4 of paths) {
928
+ const value = getNested2(input, path4);
841
929
  if (typeof value === "number" && Number.isFinite(value))
842
930
  return value;
843
931
  }
@@ -872,6 +960,21 @@ var require_payload = __commonJS({
872
960
  }
873
961
  });
874
962
 
963
+ // ../packages/tool-kit/out/collectorVersion.js
964
+ var require_collectorVersion = __commonJS({
965
+ "../packages/tool-kit/out/collectorVersion.js"(exports) {
966
+ "use strict";
967
+ Object.defineProperty(exports, "__esModule", { value: true });
968
+ exports.COLLECTOR_VERSION = exports.UNRELEASED_COLLECTOR_VERSION = void 0;
969
+ exports.describeCollectorVersion = describeCollectorVersion2;
970
+ exports.UNRELEASED_COLLECTOR_VERSION = "unreleased";
971
+ exports.COLLECTOR_VERSION = "0.1.33" ? "0.1.33" : exports.UNRELEASED_COLLECTOR_VERSION;
972
+ function describeCollectorVersion2(version = exports.COLLECTOR_VERSION) {
973
+ return version === exports.UNRELEASED_COLLECTOR_VERSION ? `${version} (built from a checkout, not a release)` : version;
974
+ }
975
+ }
976
+ });
977
+
875
978
  // ../packages/tool-kit/out/eventLog.js
876
979
  var require_eventLog = __commonJS({
877
980
  "../packages/tool-kit/out/eventLog.js"(exports) {
@@ -918,9 +1021,9 @@ var require_eventLog = __commonJS({
918
1021
  exports.expandUserPath = expandUserPath;
919
1022
  exports.resolveEventLogPath = resolveEventLogPath2;
920
1023
  exports.appendEventLog = appendEventLog2;
921
- var fs3 = __importStar(__require("fs"));
922
- var os2 = __importStar(__require("os"));
923
- var path3 = __importStar(__require("path"));
1024
+ var fs5 = __importStar(__require("fs"));
1025
+ var os3 = __importStar(__require("os"));
1026
+ var path4 = __importStar(__require("path"));
924
1027
  exports.EVENT_LOG_ENV_VAR = "ASCENDA_EVENT_LOG_FILE";
925
1028
  var MAX_BYTES = 5 * 1024 * 1024;
926
1029
  function expandUserPath(configured) {
@@ -928,10 +1031,10 @@ var require_eventLog = __commonJS({
928
1031
  if (!value)
929
1032
  return void 0;
930
1033
  if (value === "~")
931
- return os2.homedir();
1034
+ return os3.homedir();
932
1035
  if (value.startsWith("~/"))
933
- return path3.join(os2.homedir(), value.slice(2));
934
- return path3.resolve(value);
1036
+ return path4.join(os3.homedir(), value.slice(2));
1037
+ return path4.resolve(value);
935
1038
  }
936
1039
  function resolveEventLogPath2() {
937
1040
  return expandUserPath(process.env[exports.EVENT_LOG_ENV_VAR]);
@@ -939,20 +1042,20 @@ var require_eventLog = __commonJS({
939
1042
  function appendEventLog2(logFilePath, entry) {
940
1043
  try {
941
1044
  rotateIfLarge(logFilePath);
942
- const dir = path3.dirname(logFilePath);
943
- fs3.mkdirSync(dir, { recursive: true, mode: 448 });
944
- fs3.appendFileSync(logFilePath, `${JSON.stringify(entry)}
1045
+ const dir = path4.dirname(logFilePath);
1046
+ fs5.mkdirSync(dir, { recursive: true, mode: 448 });
1047
+ fs5.appendFileSync(logFilePath, `${JSON.stringify(entry)}
945
1048
  `, { encoding: "utf8", mode: 384 });
946
1049
  if (process.platform !== "win32")
947
- fs3.chmodSync(logFilePath, 384);
1050
+ fs5.chmodSync(logFilePath, 384);
948
1051
  } catch {
949
1052
  }
950
1053
  }
951
1054
  function rotateIfLarge(logFilePath) {
952
1055
  try {
953
- if (fs3.statSync(logFilePath).size < MAX_BYTES)
1056
+ if (fs5.statSync(logFilePath).size < MAX_BYTES)
954
1057
  return;
955
- fs3.renameSync(logFilePath, `${logFilePath}.1`);
1058
+ fs5.renameSync(logFilePath, `${logFilePath}.1`);
956
1059
  } catch {
957
1060
  }
958
1061
  }
@@ -967,6 +1070,12 @@ var require_http = __commonJS({
967
1070
  exports.AscendaApiError = void 0;
968
1071
  exports.createPairingSession = createPairingSession3;
969
1072
  exports.getPairingStatus = getPairingStatus3;
1073
+ exports.startStudyJoin = startStudyJoin;
1074
+ exports.getStudyJoinStatus = getStudyJoinStatus;
1075
+ exports.readInitiatives = readInitiatives;
1076
+ exports.readStudyNotices = readStudyNotices;
1077
+ exports.setStudyObjection = setStudyObjection;
1078
+ exports.markStudyNoticeShown = markStudyNoticeShown;
970
1079
  exports.renewToolToken = renewToolToken;
971
1080
  exports.isRetryableStatus = isRetryableStatus;
972
1081
  exports.postToolEvent = postToolEvent;
@@ -1003,6 +1112,108 @@ var require_http = __commonJS({
1003
1112
  throw new AscendaApiError2(response.status, void 0, await response.text());
1004
1113
  return await response.json();
1005
1114
  }
1115
+ async function startStudyJoin(apiBaseUrl, eventWriteToken, joinCode, mode) {
1116
+ const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions`, {
1117
+ method: "POST",
1118
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
1119
+ body: JSON.stringify({ joinCode, mode })
1120
+ });
1121
+ if (!response.ok)
1122
+ throw await apiError(response);
1123
+ return await response.json();
1124
+ }
1125
+ async function getStudyJoinStatus(apiBaseUrl, eventWriteToken, joinSessionId) {
1126
+ const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions/${encodeURIComponent(joinSessionId)}/status`, {
1127
+ method: "GET",
1128
+ headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` }
1129
+ });
1130
+ if (!response.ok)
1131
+ throw await apiError(response);
1132
+ return await response.json();
1133
+ }
1134
+ async function readInitiatives(apiBaseUrl, eventWriteToken, signal) {
1135
+ let response;
1136
+ try {
1137
+ response = await fetch(`${apiBaseUrl}/v1/tool-installations/initiatives`, {
1138
+ method: "GET",
1139
+ headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` },
1140
+ signal
1141
+ });
1142
+ } catch (error) {
1143
+ return { kind: "failed", reason: error instanceof Error && error.name === "TimeoutError" ? "the request timed out" : "the server could not be reached" };
1144
+ }
1145
+ if (response.status === 401)
1146
+ return { kind: "rejected", httpStatus: 401 };
1147
+ if (!response.ok)
1148
+ return { kind: "failed", reason: `the server answered HTTP ${response.status}` };
1149
+ let body;
1150
+ try {
1151
+ body = await response.json();
1152
+ } catch {
1153
+ return { kind: "failed", reason: "the reply was not readable" };
1154
+ }
1155
+ if (!Array.isArray(body))
1156
+ return { kind: "failed", reason: "the reply was not a list" };
1157
+ return { kind: "ok", initiatives: body };
1158
+ }
1159
+ async function readStudyNotices(apiBaseUrl, eventWriteToken, signal) {
1160
+ let response;
1161
+ try {
1162
+ response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices`, {
1163
+ method: "GET",
1164
+ headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` },
1165
+ signal
1166
+ });
1167
+ } catch (error) {
1168
+ return { kind: "failed", reason: error instanceof Error && error.name === "TimeoutError" ? "the request timed out" : "the server could not be reached" };
1169
+ }
1170
+ if (response.status === 404)
1171
+ return { kind: "absent" };
1172
+ if (response.status === 401)
1173
+ return { kind: "rejected", httpStatus: 401 };
1174
+ if (!response.ok)
1175
+ return { kind: "failed", reason: `the server answered HTTP ${response.status}` };
1176
+ let body;
1177
+ try {
1178
+ body = await response.json();
1179
+ } catch {
1180
+ return { kind: "absent" };
1181
+ }
1182
+ if (!Array.isArray(body))
1183
+ return { kind: "absent" };
1184
+ return { kind: "ok", notices: body };
1185
+ }
1186
+ async function setStudyObjection(apiBaseUrl, eventWriteToken, code, objected) {
1187
+ const response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices/${encodeURIComponent(String(code))}/objection`, {
1188
+ method: objected ? "POST" : "DELETE",
1189
+ headers: { Authorization: `Bearer ${eventWriteToken}` }
1190
+ });
1191
+ if (!response.ok)
1192
+ throw await apiError(response);
1193
+ }
1194
+ async function markStudyNoticeShown(apiBaseUrl, eventWriteToken, organisationId, code, signal) {
1195
+ try {
1196
+ const response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices/${encodeURIComponent(organisationId)}/${encodeURIComponent(String(code))}/shown`, {
1197
+ method: "POST",
1198
+ headers: { Authorization: `Bearer ${eventWriteToken}` },
1199
+ signal
1200
+ });
1201
+ return response.ok;
1202
+ } catch {
1203
+ return false;
1204
+ }
1205
+ }
1206
+ async function apiError(response) {
1207
+ const body = await response.text();
1208
+ let errorCode;
1209
+ try {
1210
+ const parsed = JSON.parse(body);
1211
+ errorCode = parsed.code ?? parsed.error;
1212
+ } catch {
1213
+ errorCode = void 0;
1214
+ }
1215
+ return new AscendaApiError2(response.status, errorCode, body);
1216
+ }
1006
1217
  async function renewToolToken(apiBaseUrl, eventWriteToken, signal) {
1007
1218
  const response = await fetch(`${apiBaseUrl}/v1/tool-events/renew-token`, {
1008
1219
  method: "POST",
@@ -1145,36 +1356,66 @@ var require_tokenStore = __commonJS({
1145
1356
  };
1146
1357
  }();
1147
1358
  Object.defineProperty(exports, "__esModule", { value: true });
1359
+ exports.EVENT_TOKEN_TTL_MS = void 0;
1148
1360
  exports.ascendaHome = ascendaHome3;
1149
1361
  exports.defaultTokenFilePath = defaultTokenFilePath4;
1362
+ exports.tokenExpiryFilePath = tokenExpiryFilePath;
1150
1363
  exports.persistEventWriteToken = persistEventWriteToken4;
1364
+ exports.readTokenExpiry = readTokenExpiry;
1151
1365
  exports.listPersistedToolInstallationIds = listPersistedToolInstallationIds2;
1152
1366
  exports.readTokenFile = readTokenFile3;
1153
1367
  exports.sanitizeFilePart = sanitizeFilePart;
1154
- var fs3 = __importStar(__require("fs"));
1155
- var os2 = __importStar(__require("os"));
1156
- var path3 = __importStar(__require("path"));
1157
- function ascendaHome3(home = os2.homedir()) {
1158
- return process.env.ASCENDA_HOME ?? path3.join(home, ".ascenda");
1368
+ var fs5 = __importStar(__require("fs"));
1369
+ var os3 = __importStar(__require("os"));
1370
+ var path4 = __importStar(__require("path"));
1371
+ function ascendaHome3(home = os3.homedir()) {
1372
+ return process.env.ASCENDA_HOME ?? path4.join(home, ".ascenda");
1159
1373
  }
1160
1374
  function defaultTokenFilePath4(toolInstallationId) {
1161
- return path3.join(ascendaHome3(), "tokens", sanitizeFilePart(toolInstallationId));
1375
+ return path4.join(ascendaHome3(), "tokens", sanitizeFilePart(toolInstallationId));
1162
1376
  }
1163
- function persistEventWriteToken4(tokenFilePath, token) {
1164
- const dir = path3.dirname(tokenFilePath);
1165
- fs3.mkdirSync(dir, { recursive: true, mode: 448 });
1166
- fs3.writeFileSync(tokenFilePath, token, { encoding: "utf8", mode: 384 });
1377
+ function tokenExpiryFilePath(tokenFilePath) {
1378
+ return path4.join(path4.dirname(tokenFilePath), "expiry", path4.basename(tokenFilePath));
1379
+ }
1380
+ function persistEventWriteToken4(tokenFilePath, token, expiresAt) {
1381
+ const dir = path4.dirname(tokenFilePath);
1382
+ fs5.mkdirSync(dir, { recursive: true, mode: 448 });
1383
+ fs5.writeFileSync(tokenFilePath, token, { encoding: "utf8", mode: 384 });
1167
1384
  if (process.platform !== "win32") {
1168
- fs3.chmodSync(dir, 448);
1169
- fs3.chmodSync(tokenFilePath, 384);
1385
+ fs5.chmodSync(dir, 448);
1386
+ fs5.chmodSync(tokenFilePath, 384);
1387
+ }
1388
+ const expiryFile = tokenExpiryFilePath(tokenFilePath);
1389
+ try {
1390
+ if (expiresAt && Number.isFinite(Date.parse(expiresAt))) {
1391
+ fs5.mkdirSync(path4.dirname(expiryFile), { recursive: true, mode: 448 });
1392
+ fs5.writeFileSync(expiryFile, expiresAt, { encoding: "utf8", mode: 384 });
1393
+ } else {
1394
+ fs5.rmSync(expiryFile, { force: true });
1395
+ }
1396
+ } catch {
1397
+ }
1398
+ }
1399
+ exports.EVENT_TOKEN_TTL_MS = 30 * 24 * 60 * 60 * 1e3;
1400
+ function readTokenExpiry(tokenFilePath) {
1401
+ try {
1402
+ const recorded = Date.parse(fs5.readFileSync(tokenExpiryFilePath(tokenFilePath), "utf8").trim());
1403
+ if (Number.isFinite(recorded))
1404
+ return recorded;
1405
+ } catch {
1406
+ }
1407
+ try {
1408
+ return fs5.statSync(tokenFilePath).mtimeMs + exports.EVENT_TOKEN_TTL_MS;
1409
+ } catch {
1410
+ return void 0;
1170
1411
  }
1171
1412
  }
1172
1413
  function listPersistedToolInstallationIds2(toolType) {
1173
1414
  const prefix = `${sanitizeFilePart(toolType)}_`;
1174
- const dir = path3.join(ascendaHome3(), "tokens");
1415
+ const dir = path4.join(ascendaHome3(), "tokens");
1175
1416
  let names;
1176
1417
  try {
1177
- names = fs3.readdirSync(dir);
1418
+ names = fs5.readdirSync(dir);
1178
1419
  } catch {
1179
1420
  return [];
1180
1421
  }
@@ -1182,9 +1423,9 @@ var require_tokenStore = __commonJS({
1182
1423
  for (const name of names.sort()) {
1183
1424
  if (!name.startsWith(prefix) || name.length === prefix.length)
1184
1425
  continue;
1185
- const file = path3.join(dir, name);
1426
+ const file = path4.join(dir, name);
1186
1427
  try {
1187
- if (!fs3.statSync(file).isFile())
1428
+ if (!fs5.statSync(file).isFile())
1188
1429
  continue;
1189
1430
  } catch {
1190
1431
  continue;
@@ -1197,9 +1438,9 @@ var require_tokenStore = __commonJS({
1197
1438
  }
1198
1439
  function readTokenFile3(tokenFilePath) {
1199
1440
  try {
1200
- if (!fs3.existsSync(tokenFilePath))
1441
+ if (!fs5.existsSync(tokenFilePath))
1201
1442
  return void 0;
1202
- const value = fs3.readFileSync(tokenFilePath, "utf8").trim();
1443
+ const value = fs5.readFileSync(tokenFilePath, "utf8").trim();
1203
1444
  return value || void 0;
1204
1445
  } catch {
1205
1446
  return void 0;
@@ -1261,13 +1502,13 @@ var require_stateStore = __commonJS({
1261
1502
  exports.recordOutboxDiscard = recordOutboxDiscard;
1262
1503
  exports.shouldAnnounceFailure = shouldAnnounceFailure2;
1263
1504
  exports.markFailureNotified = markFailureNotified2;
1264
- var fs3 = __importStar(__require("fs"));
1265
- var path3 = __importStar(__require("path"));
1505
+ var fs5 = __importStar(__require("fs"));
1506
+ var path4 = __importStar(__require("path"));
1266
1507
  var tokenStore_1 = require_tokenStore();
1267
1508
  function defaultStateFilePath2(toolInstallationId) {
1268
1509
  const dir = process.env.ASCENDA_STATE_DIR?.trim();
1269
- const base = dir ? dir : path3.join((0, tokenStore_1.ascendaHome)(), "state");
1270
- return path3.join(base, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.json`);
1510
+ const base = dir ? dir : path4.join((0, tokenStore_1.ascendaHome)(), "state");
1511
+ return path4.join(base, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.json`);
1271
1512
  }
1272
1513
  function unresolvedToolInstallationId2(toolType) {
1273
1514
  return `${toolType}:unresolved`;
@@ -1277,9 +1518,9 @@ var require_stateStore = __commonJS({
1277
1518
  }
1278
1519
  function readCollectorState2(stateFilePath) {
1279
1520
  try {
1280
- if (!fs3.existsSync(stateFilePath))
1521
+ if (!fs5.existsSync(stateFilePath))
1281
1522
  return void 0;
1282
- const raw = fs3.readFileSync(stateFilePath, "utf8").trim();
1523
+ const raw = fs5.readFileSync(stateFilePath, "utf8").trim();
1283
1524
  if (!raw)
1284
1525
  return void 0;
1285
1526
  const parsed = JSON.parse(raw);
@@ -1346,17 +1587,17 @@ var require_stateStore = __commonJS({
1346
1587
  function writeStateFile(stateFilePath, state) {
1347
1588
  const temporaryPath = `${stateFilePath}.${process.pid}.tmp`;
1348
1589
  try {
1349
- const dir = path3.dirname(stateFilePath);
1350
- fs3.mkdirSync(dir, { recursive: true, mode: 448 });
1351
- fs3.writeFileSync(temporaryPath, `${JSON.stringify(state, null, 2)}
1590
+ const dir = path4.dirname(stateFilePath);
1591
+ fs5.mkdirSync(dir, { recursive: true, mode: 448 });
1592
+ fs5.writeFileSync(temporaryPath, `${JSON.stringify(state, null, 2)}
1352
1593
  `, { encoding: "utf8", mode: 384 });
1353
- fs3.renameSync(temporaryPath, stateFilePath);
1594
+ fs5.renameSync(temporaryPath, stateFilePath);
1354
1595
  if (process.platform !== "win32")
1355
- fs3.chmodSync(stateFilePath, 384);
1596
+ fs5.chmodSync(stateFilePath, 384);
1356
1597
  } catch {
1357
1598
  try {
1358
- if (fs3.existsSync(temporaryPath))
1359
- fs3.unlinkSync(temporaryPath);
1599
+ if (fs5.existsSync(temporaryPath))
1600
+ fs5.unlinkSync(temporaryPath);
1360
1601
  } catch {
1361
1602
  }
1362
1603
  }
@@ -1417,8 +1658,8 @@ var require_outbox = __commonJS({
1417
1658
  exports.readOutboxSummary = readOutboxSummary2;
1418
1659
  exports.claimOutbox = claimOutbox;
1419
1660
  exports.enforceOutboxBounds = enforceOutboxBounds;
1420
- var fs3 = __importStar(__require("fs"));
1421
- var path3 = __importStar(__require("path"));
1661
+ var fs5 = __importStar(__require("fs"));
1662
+ var path4 = __importStar(__require("path"));
1422
1663
  var stateStore_1 = require_stateStore();
1423
1664
  var tokenStore_1 = require_tokenStore();
1424
1665
  exports.OUTBOX_DRAIN_ENV_VAR = "ASCENDA_OUTBOX_DRAIN";
@@ -1434,25 +1675,25 @@ var require_outbox = __commonJS({
1434
1675
  return !(value === "0" || value === "false" || value === "no" || value === "off");
1435
1676
  }
1436
1677
  function defaultOutboxFilePath2(toolInstallationId) {
1437
- const dir = path3.dirname((0, stateStore_1.defaultStateFilePath)(toolInstallationId));
1438
- return path3.join(dir, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.outbox.jsonl`);
1678
+ const dir = path4.dirname((0, stateStore_1.defaultStateFilePath)(toolInstallationId));
1679
+ return path4.join(dir, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.outbox.jsonl`);
1439
1680
  }
1440
1681
  function appendToOutbox(outboxFilePath, payload, now = /* @__PURE__ */ new Date()) {
1441
1682
  try {
1442
- const dir = path3.dirname(outboxFilePath);
1443
- fs3.mkdirSync(dir, { recursive: true, mode: 448 });
1683
+ const dir = path4.dirname(outboxFilePath);
1684
+ fs5.mkdirSync(dir, { recursive: true, mode: 448 });
1444
1685
  const entry = { queuedAt: now.toISOString(), payload };
1445
- fs3.appendFileSync(outboxFilePath, `${JSON.stringify(entry)}
1686
+ fs5.appendFileSync(outboxFilePath, `${JSON.stringify(entry)}
1446
1687
  `, { encoding: "utf8", mode: 384 });
1447
1688
  if (process.platform !== "win32")
1448
- fs3.chmodSync(outboxFilePath, 384);
1689
+ fs5.chmodSync(outboxFilePath, 384);
1449
1690
  return true;
1450
1691
  } catch {
1451
1692
  return false;
1452
1693
  }
1453
1694
  }
1454
1695
  function readOutboxSummary2(outboxFilePath) {
1455
- const files = [outboxFilePath, ...listClaimFiles(outboxFilePath)].filter((file) => fs3.existsSync(file));
1696
+ const files = [outboxFilePath, ...listClaimFiles(outboxFilePath)].filter((file) => fs5.existsSync(file));
1456
1697
  if (files.length === 0)
1457
1698
  return void 0;
1458
1699
  let depth = 0;
@@ -1473,7 +1714,7 @@ var require_outbox = __commonJS({
1473
1714
  const claimPath = `${outboxFilePath}.${process.pid}${CLAIM_SUFFIX}`;
1474
1715
  const claimed = [];
1475
1716
  try {
1476
- fs3.renameSync(outboxFilePath, claimPath);
1717
+ fs5.renameSync(outboxFilePath, claimPath);
1477
1718
  claimed.push(claimPath);
1478
1719
  } catch {
1479
1720
  }
@@ -1482,10 +1723,10 @@ var require_outbox = __commonJS({
1482
1723
  if (claimed.includes(orphan))
1483
1724
  continue;
1484
1725
  try {
1485
- if (now - fs3.statSync(orphan).mtimeMs < ORPHANED_CLAIM_AGE_MS)
1726
+ if (now - fs5.statSync(orphan).mtimeMs < ORPHANED_CLAIM_AGE_MS)
1486
1727
  continue;
1487
1728
  const mine = `${claimPath}.${orphanIndex++}`;
1488
- fs3.renameSync(orphan, mine);
1729
+ fs5.renameSync(orphan, mine);
1489
1730
  claimed.push(mine);
1490
1731
  } catch {
1491
1732
  }
@@ -1510,18 +1751,18 @@ var require_outbox = __commonJS({
1510
1751
  released = true;
1511
1752
  if (remainder.length > 0) {
1512
1753
  try {
1513
- fs3.mkdirSync(path3.dirname(outboxFilePath), { recursive: true, mode: 448 });
1514
- fs3.appendFileSync(outboxFilePath, remainder.map((entry) => `${JSON.stringify(entry)}
1754
+ fs5.mkdirSync(path4.dirname(outboxFilePath), { recursive: true, mode: 448 });
1755
+ fs5.appendFileSync(outboxFilePath, remainder.map((entry) => `${JSON.stringify(entry)}
1515
1756
  `).join(""), { encoding: "utf8", mode: 384 });
1516
1757
  if (process.platform !== "win32")
1517
- fs3.chmodSync(outboxFilePath, 384);
1758
+ fs5.chmodSync(outboxFilePath, 384);
1518
1759
  } catch {
1519
1760
  return;
1520
1761
  }
1521
1762
  }
1522
1763
  for (const file of claimed) {
1523
1764
  try {
1524
- fs3.unlinkSync(file);
1765
+ fs5.unlinkSync(file);
1525
1766
  } catch {
1526
1767
  }
1527
1768
  }
@@ -1554,10 +1795,10 @@ var require_outbox = __commonJS({
1554
1795
  return { kept, discarded: { count, reasons, ...oldestQueuedAt !== void 0 ? { oldestQueuedAt } : {} } };
1555
1796
  }
1556
1797
  function listClaimFiles(outboxFilePath) {
1557
- const dir = path3.dirname(outboxFilePath);
1558
- const prefix = `${path3.basename(outboxFilePath)}.`;
1798
+ const dir = path4.dirname(outboxFilePath);
1799
+ const prefix = `${path4.basename(outboxFilePath)}.`;
1559
1800
  try {
1560
- return fs3.readdirSync(dir).filter((name) => name.startsWith(prefix) && name.includes(CLAIM_SUFFIX)).map((name) => path3.join(dir, name)).sort();
1801
+ return fs5.readdirSync(dir).filter((name) => name.startsWith(prefix) && name.includes(CLAIM_SUFFIX)).map((name) => path4.join(dir, name)).sort();
1561
1802
  } catch {
1562
1803
  return [];
1563
1804
  }
@@ -1565,7 +1806,7 @@ var require_outbox = __commonJS({
1565
1806
  function readEntries(file) {
1566
1807
  let raw;
1567
1808
  try {
1568
- raw = fs3.readFileSync(file, "utf8");
1809
+ raw = fs5.readFileSync(file, "utf8");
1569
1810
  } catch {
1570
1811
  return { entries: [], unreadable: 0 };
1571
1812
  }
@@ -1614,7 +1855,7 @@ var require_eventSender = __commonJS({
1614
1855
  "../packages/tool-kit/out/eventSender.js"(exports) {
1615
1856
  "use strict";
1616
1857
  Object.defineProperty(exports, "__esModule", { value: true });
1617
- exports.AscendaEventSender = exports.AscendaSemanticEventError = void 0;
1858
+ exports.AscendaEventSender = exports.TOKEN_RENEW_LEAD_MS = exports.AscendaSemanticEventError = void 0;
1618
1859
  exports.buildEventPayload = buildEventPayload2;
1619
1860
  var afterHours_1 = require_afterHours();
1620
1861
  var tool_contract_1 = require_out();
@@ -1625,6 +1866,7 @@ var require_eventSender = __commonJS({
1625
1866
  var tokenStore_1 = require_tokenStore();
1626
1867
  var stateStore_1 = require_stateStore();
1627
1868
  var payload_1 = require_payload();
1869
+ var collectorVersion_1 = require_collectorVersion();
1628
1870
  var AscendaSemanticEventError = class extends Error {
1629
1871
  constructor(message) {
1630
1872
  super(message);
@@ -1646,11 +1888,15 @@ var require_eventSender = __commonJS({
1646
1888
  provenance: tool_contract_1.ASCENDA_PROVENANCE,
1647
1889
  privacyMode: "metadata_only",
1648
1890
  ...mapped,
1649
- metadata: mapped.metadata ?? {}
1891
+ metadata: withCollectorVersion(mapped.metadata)
1650
1892
  };
1651
1893
  }
1894
+ function withCollectorVersion(metadata) {
1895
+ return { ...metadata, collectorVersion: collectorVersion_1.COLLECTOR_VERSION };
1896
+ }
1652
1897
  var DEFAULT_TIMEOUT_MS = 5e3;
1653
1898
  var RETRY_DELAY_MS = 250;
1899
+ exports.TOKEN_RENEW_LEAD_MS = 21 * 24 * 60 * 60 * 1e3;
1654
1900
  var AscendaEventSender2 = class {
1655
1901
  config;
1656
1902
  eventWriteToken;
@@ -1658,6 +1904,8 @@ var require_eventSender = __commonJS({
1658
1904
  lastDrain;
1659
1905
  /** One outbox pass per sender, i.e. per hook process. The hook is on the user's critical path. */
1660
1906
  outboxServiced = false;
1907
+ /** One look at the token's expiry per sender, for the same reason. */
1908
+ expiryChecked = false;
1661
1909
  /** Resolved once, so every clock read in one pass sees the same instant. */
1662
1910
  time;
1663
1911
  constructor(config) {
@@ -1668,6 +1916,30 @@ var require_eventSender = __commonJS({
1668
1916
  async send(mapped) {
1669
1917
  return this.post(buildEventPayload2(this.config, mapped));
1670
1918
  }
1919
+ /**
1920
+ * Writes the event to the outbox and returns without touching the network.
1921
+ * The next outbox pass delivers it, from whichever hook of this
1922
+ * installation sends next.
1923
+ *
1924
+ * For a hook whose host is exiting. A process the host may kill at any
1925
+ * moment can't wait on a send, and one killed mid-send dies before
1926
+ * {@link post} gets to queue the payload, so the event goes with it. Here
1927
+ * the payload is on disk before anything can go wrong.
1928
+ *
1929
+ * Returns whether it is. When the write fails the journal says the event
1930
+ * was lost; nothing else could have kept it.
1931
+ */
1932
+ queue(mapped) {
1933
+ const payload = buildEventPayload2(this.config, mapped);
1934
+ const queued = this.enqueue(payload);
1935
+ if (!queued) {
1936
+ this.lastState = (0, stateStore_1.recordSendOutcome)(this.stateFilePath(), this.config.toolInstallationId, "other", {
1937
+ detail: `${payload.eventType}: outbox write failed, event lost`
1938
+ });
1939
+ }
1940
+ this.log(payload, "not_sent", queued ? "queued" : void 0);
1941
+ return queued;
1942
+ }
1671
1943
  /**
1672
1944
  * Sends one of the six agent-observed types (dark-flow-gap-analysis §2.1).
1673
1945
  * Distinct from {@link send} rather than an option on it, because the
@@ -1708,7 +1980,7 @@ var require_eventSender = __commonJS({
1708
1980
  consentScope: tool_contract_1.ASCENDA_SEMANTIC_CONSENT_SCOPE,
1709
1981
  provenance: tool_contract_1.ASCENDA_SEMANTIC_PROVENANCE,
1710
1982
  privacyMode: "metadata_only",
1711
- metadata: mapped.metadata
1983
+ metadata: withCollectorVersion(mapped.metadata)
1712
1984
  };
1713
1985
  return this.post(payload);
1714
1986
  }
@@ -1739,7 +2011,7 @@ var require_eventSender = __commonJS({
1739
2011
  consentScope: tool_contract_1.ASCENDA_COLLABORATION_CONSENT_SCOPE,
1740
2012
  provenance: tool_contract_1.ASCENDA_PROVENANCE,
1741
2013
  privacyMode: "metadata_only",
1742
- metadata: mapped.metadata ?? {}
2014
+ metadata: withCollectorVersion(mapped.metadata)
1743
2015
  };
1744
2016
  return this.post(payload);
1745
2017
  }
@@ -1757,6 +2029,7 @@ var require_eventSender = __commonJS({
1757
2029
  * hook during an outage to one bounded round trip instead of three.
1758
2030
  */
1759
2031
  async post(payload) {
2032
+ await this.renewIfExpiring();
1760
2033
  const halted = await this.serviceOutbox();
1761
2034
  let outcome;
1762
2035
  let queued = false;
@@ -1962,19 +2235,49 @@ var require_eventSender = __commonJS({
1962
2235
  return;
1963
2236
  (0, eventLog_1.appendEventLog)(logFile, { loggedAt: (/* @__PURE__ */ new Date()).toISOString(), delivery, payload, ...outbox ? { outbox } : {} });
1964
2237
  }
1965
- /** Never throws: a renewal that errors is a failed renewal, not a failed turn. */
2238
+ /**
2239
+ * Renews ahead of expiry, at most once per sender. Waiting for the 401
2240
+ * doesn't work: by then the token has expired, and the server won't renew
2241
+ * an expired token.
2242
+ */
2243
+ async renewIfExpiring() {
2244
+ if (this.expiryChecked || this.config.renewToken === false)
2245
+ return;
2246
+ this.expiryChecked = true;
2247
+ const expiresAt = (0, tokenStore_1.readTokenExpiry)(this.config.tokenFilePath);
2248
+ if (expiresAt === void 0 || this.time.now() < expiresAt - exports.TOKEN_RENEW_LEAD_MS)
2249
+ return;
2250
+ await this.renewEventToken();
2251
+ }
2252
+ /**
2253
+ * Never throws: a renewal that errors is a failed renewal, not a failed turn.
2254
+ *
2255
+ * A refused renewal usually means another process got there first. Hooks
2256
+ * and the MCP server share one token file, and renewing revokes the token
2257
+ * it replaces, so the loser holds a revoked token while the winner's
2258
+ * replacement is already on disk. Adopting that counts as a renewal.
2259
+ */
1966
2260
  async renewEventToken() {
2261
+ if (this.config.renewToken === false)
2262
+ return false;
1967
2263
  try {
1968
2264
  const renewed = await (0, http_1.renewToolToken)(this.config.apiBaseUrl, this.eventWriteToken, this.signal());
1969
2265
  if (!renewed)
1970
- return false;
2266
+ return this.adoptPersistedToken();
1971
2267
  this.eventWriteToken = renewed.eventWriteToken;
1972
- (0, tokenStore_1.persistEventWriteToken)(this.config.tokenFilePath, renewed.eventWriteToken);
2268
+ (0, tokenStore_1.persistEventWriteToken)(this.config.tokenFilePath, renewed.eventWriteToken, renewed.expiresAt);
1973
2269
  return true;
1974
2270
  } catch {
1975
2271
  return false;
1976
2272
  }
1977
2273
  }
2274
+ adoptPersistedToken() {
2275
+ const persisted = (0, tokenStore_1.readTokenFile)(this.config.tokenFilePath);
2276
+ if (!persisted || persisted === this.eventWriteToken)
2277
+ return false;
2278
+ this.eventWriteToken = persisted;
2279
+ return true;
2280
+ }
1978
2281
  signal() {
1979
2282
  return AbortSignal.timeout(this.config.timeoutMs ?? DEFAULT_TIMEOUT_MS);
1980
2283
  }
@@ -2032,16 +2335,16 @@ var require_contextRegistry = __commonJS({
2032
2335
  exports.readWorkContextRegistry = readWorkContextRegistry;
2033
2336
  exports.recordWorkContext = recordWorkContext2;
2034
2337
  exports.recordWorkContextAlias = recordWorkContextAlias;
2035
- var fs3 = __importStar(__require("fs"));
2036
- var os2 = __importStar(__require("os"));
2037
- var path3 = __importStar(__require("path"));
2338
+ var fs5 = __importStar(__require("fs"));
2339
+ var os3 = __importStar(__require("os"));
2340
+ var path4 = __importStar(__require("path"));
2038
2341
  var MAX_PATHS_PER_ENTRY = 8;
2039
2342
  function workContextRegistryFilePath() {
2040
- return path3.join(os2.homedir(), ".ascenda", "work-contexts.json");
2343
+ return path4.join(os3.homedir(), ".ascenda", "work-contexts.json");
2041
2344
  }
2042
2345
  function readWorkContextRegistry(registryFilePath = workContextRegistryFilePath()) {
2043
2346
  try {
2044
- const parsed = JSON.parse(fs3.readFileSync(registryFilePath, "utf8"));
2347
+ const parsed = JSON.parse(fs5.readFileSync(registryFilePath, "utf8"));
2045
2348
  if (parsed && parsed.version === 1 && parsed.contexts && typeof parsed.contexts === "object") {
2046
2349
  return parsed;
2047
2350
  }
@@ -2117,14 +2420,14 @@ var require_contextRegistry = __commonJS({
2117
2420
  return iso.slice(0, 10);
2118
2421
  }
2119
2422
  function writeRegistry(registryFilePath, registry) {
2120
- const dir = path3.dirname(registryFilePath);
2121
- fs3.mkdirSync(dir, { recursive: true, mode: 448 });
2423
+ const dir = path4.dirname(registryFilePath);
2424
+ fs5.mkdirSync(dir, { recursive: true, mode: 448 });
2122
2425
  const tmp = `${registryFilePath}.${process.pid}.tmp`;
2123
- fs3.writeFileSync(tmp, `${JSON.stringify(registry, null, 2)}
2426
+ fs5.writeFileSync(tmp, `${JSON.stringify(registry, null, 2)}
2124
2427
  `, { encoding: "utf8", mode: 384 });
2125
- fs3.renameSync(tmp, registryFilePath);
2428
+ fs5.renameSync(tmp, registryFilePath);
2126
2429
  if (process.platform !== "win32") {
2127
- fs3.chmodSync(registryFilePath, 384);
2430
+ fs5.chmodSync(registryFilePath, 384);
2128
2431
  }
2129
2432
  }
2130
2433
  }
@@ -2174,20 +2477,21 @@ var require_credentials = __commonJS({
2174
2477
  Object.defineProperty(exports, "__esModule", { value: true });
2175
2478
  exports.credentialsFilePath = credentialsFilePath2;
2176
2479
  exports.readMachineCredentials = readMachineCredentials2;
2177
- exports.writeMachineCredentials = writeMachineCredentials;
2480
+ exports.writeMachineCredentials = writeMachineCredentials2;
2178
2481
  exports.writeTopLevelCredentials = writeTopLevelCredentials2;
2482
+ exports.isLocalOnlyHostInstall = isLocalOnlyHostInstall;
2179
2483
  exports.readHostCredentials = readHostCredentials;
2180
2484
  exports.writeHostCredentials = writeHostCredentials;
2181
2485
  exports.removeHostCredentials = removeHostCredentials;
2182
- var fs3 = __importStar(__require("fs"));
2183
- var path3 = __importStar(__require("path"));
2486
+ var fs5 = __importStar(__require("fs"));
2487
+ var path4 = __importStar(__require("path"));
2184
2488
  var tokenStore_1 = require_tokenStore();
2185
2489
  function credentialsFilePath2() {
2186
- return path3.join((0, tokenStore_1.ascendaHome)(), "credentials.json");
2490
+ return path4.join((0, tokenStore_1.ascendaHome)(), "credentials.json");
2187
2491
  }
2188
2492
  function readMachineCredentials2() {
2189
2493
  try {
2190
- const raw = fs3.readFileSync(credentialsFilePath2(), "utf8").trim();
2494
+ const raw = fs5.readFileSync(credentialsFilePath2(), "utf8").trim();
2191
2495
  if (!raw)
2192
2496
  return void 0;
2193
2497
  const parsed = JSON.parse(raw);
@@ -2198,19 +2502,27 @@ var require_credentials = __commonJS({
2198
2502
  return void 0;
2199
2503
  }
2200
2504
  }
2201
- function writeMachineCredentials(credentials) {
2505
+ function writeMachineCredentials2(credentials) {
2202
2506
  const file = credentialsFilePath2();
2203
- fs3.mkdirSync(path3.dirname(file), { recursive: true, mode: 448 });
2204
- fs3.writeFileSync(file, `${JSON.stringify(credentials, null, 2)}
2507
+ fs5.mkdirSync(path4.dirname(file), { recursive: true, mode: 448 });
2508
+ fs5.writeFileSync(file, `${JSON.stringify(credentials, null, 2)}
2205
2509
  `, { encoding: "utf8", mode: 384 });
2206
2510
  if (process.platform !== "win32") {
2207
- fs3.chmodSync(path3.dirname(file), 448);
2208
- fs3.chmodSync(file, 384);
2511
+ fs5.chmodSync(path4.dirname(file), 448);
2512
+ fs5.chmodSync(file, 384);
2209
2513
  }
2210
2514
  }
2211
2515
  function writeTopLevelCredentials2(credentials) {
2212
2516
  const existing = readMachineCredentials2();
2213
- writeMachineCredentials({ ...credentials, ...existing?.tools ? { tools: existing.tools } : {} });
2517
+ writeMachineCredentials2({ ...credentials, ...existing?.tools ? { tools: existing.tools } : {} });
2518
+ }
2519
+ function isLocalOnlyHostInstall(host, hasToken) {
2520
+ const credentials = readHostCredentials(host);
2521
+ if (!credentials?.localOnly)
2522
+ return false;
2523
+ if (process.env.ASCENDA_EVENT_WRITE_TOKEN)
2524
+ return false;
2525
+ return !(credentials.toolInstallationId && hasToken(credentials.toolInstallationId));
2214
2526
  }
2215
2527
  function readHostCredentials(host) {
2216
2528
  const entry = readMachineCredentials2()?.tools?.[host];
@@ -2220,7 +2532,7 @@ var require_credentials = __commonJS({
2220
2532
  }
2221
2533
  function writeHostCredentials(host, credentials) {
2222
2534
  const existing = readMachineCredentials2() ?? {};
2223
- writeMachineCredentials({ ...existing, tools: { ...existing.tools ?? {}, [host]: credentials } });
2535
+ writeMachineCredentials2({ ...existing, tools: { ...existing.tools ?? {}, [host]: credentials } });
2224
2536
  }
2225
2537
  function removeHostCredentials(host) {
2226
2538
  const existing = readMachineCredentials2();
@@ -2233,7 +2545,7 @@ var require_credentials = __commonJS({
2233
2545
  next.tools = tools;
2234
2546
  else
2235
2547
  delete next.tools;
2236
- writeMachineCredentials(next);
2548
+ writeMachineCredentials2(next);
2237
2549
  }
2238
2550
  }
2239
2551
  });
@@ -2285,8 +2597,8 @@ var require_forgeProject = __commonJS({
2285
2597
  exports.readForgeFullName = readForgeFullName;
2286
2598
  exports.forgeFullNameFromConfig = forgeFullNameFromConfig;
2287
2599
  exports.recordForgeProjectAlias = recordForgeProjectAlias2;
2288
- var fs3 = __importStar(__require("fs"));
2289
- var path3 = __importStar(__require("path"));
2600
+ var fs5 = __importStar(__require("fs"));
2601
+ var path4 = __importStar(__require("path"));
2290
2602
  var contextRegistry_1 = require_contextRegistry();
2291
2603
  function forgeProjectHash(value) {
2292
2604
  let h = 2166136261;
@@ -2332,7 +2644,7 @@ var require_forgeProject = __commonJS({
2332
2644
  return null;
2333
2645
  let config;
2334
2646
  try {
2335
- config = fs3.readFileSync(path3.join(repositoryRoot, ".git", "config"), "utf8");
2647
+ config = fs5.readFileSync(path4.join(repositoryRoot, ".git", "config"), "utf8");
2336
2648
  } catch {
2337
2649
  return null;
2338
2650
  }
@@ -2439,31 +2751,31 @@ var require_salt = __commonJS({
2439
2751
  exports.readOrCreateMachineSalt = readOrCreateMachineSalt;
2440
2752
  exports.hashWithMachineSalt = hashWithMachineSalt;
2441
2753
  var crypto2 = __importStar(__require("crypto"));
2442
- var fs3 = __importStar(__require("fs"));
2443
- var path3 = __importStar(__require("path"));
2754
+ var fs5 = __importStar(__require("fs"));
2755
+ var path4 = __importStar(__require("path"));
2444
2756
  var tokenStore_1 = require_tokenStore();
2445
2757
  function machineSaltFilePath() {
2446
- return path3.join((0, tokenStore_1.ascendaHome)(), "salt");
2758
+ return path4.join((0, tokenStore_1.ascendaHome)(), "salt");
2447
2759
  }
2448
2760
  var cache = /* @__PURE__ */ new Map();
2449
2761
  function readOrCreateMachineSalt(saltFilePath = machineSaltFilePath()) {
2450
2762
  const hit = cache.get(saltFilePath);
2451
2763
  if (hit)
2452
2764
  return hit;
2453
- const dir = path3.dirname(saltFilePath);
2454
- fs3.mkdirSync(dir, { recursive: true, mode: 448 });
2765
+ const dir = path4.dirname(saltFilePath);
2766
+ fs5.mkdirSync(dir, { recursive: true, mode: 448 });
2455
2767
  let salt;
2456
2768
  try {
2457
2769
  salt = crypto2.randomBytes(32).toString("hex");
2458
- fs3.writeFileSync(saltFilePath, salt, { encoding: "utf8", mode: 384, flag: "wx" });
2770
+ fs5.writeFileSync(saltFilePath, salt, { encoding: "utf8", mode: 384, flag: "wx" });
2459
2771
  } catch (error) {
2460
2772
  if (error.code !== "EEXIST")
2461
2773
  throw error;
2462
- salt = fs3.readFileSync(saltFilePath, "utf8").trim();
2774
+ salt = fs5.readFileSync(saltFilePath, "utf8").trim();
2463
2775
  }
2464
2776
  if (process.platform !== "win32") {
2465
- fs3.chmodSync(dir, 448);
2466
- fs3.chmodSync(saltFilePath, 384);
2777
+ fs5.chmodSync(dir, 448);
2778
+ fs5.chmodSync(saltFilePath, 384);
2467
2779
  }
2468
2780
  cache.set(saltFilePath, salt);
2469
2781
  return salt;
@@ -2523,8 +2835,8 @@ var require_workContext = __commonJS({
2523
2835
  exports.deriveBranchHash = deriveBranchHash;
2524
2836
  exports.readBranchName = readBranchName;
2525
2837
  exports.deriveBranchHashForCwd = deriveBranchHashForCwd2;
2526
- var fs3 = __importStar(__require("fs"));
2527
- var path3 = __importStar(__require("path"));
2838
+ var fs5 = __importStar(__require("fs"));
2839
+ var path4 = __importStar(__require("path"));
2528
2840
  var salt_1 = require_salt();
2529
2841
  var MAX_WALK_DEPTH = 64;
2530
2842
  function deriveWorkContext2(cwd, saltFilePath) {
@@ -2555,14 +2867,14 @@ var require_workContext = __commonJS({
2555
2867
  };
2556
2868
  }
2557
2869
  function resolveRepositoryRoots(startDir) {
2558
- if (!fs3.existsSync(startDir))
2870
+ if (!fs5.existsSync(startDir))
2559
2871
  return null;
2560
2872
  let dir = startDir;
2561
2873
  for (let depth = 0; depth < MAX_WALK_DEPTH; depth++) {
2562
- const dotGit = path3.join(dir, ".git");
2874
+ const dotGit = path4.join(dir, ".git");
2563
2875
  let stat = null;
2564
2876
  try {
2565
- stat = fs3.statSync(dotGit);
2877
+ stat = fs5.statSync(dotGit);
2566
2878
  } catch {
2567
2879
  stat = null;
2568
2880
  }
@@ -2573,7 +2885,7 @@ var require_workContext = __commonJS({
2573
2885
  const canonicalRoot = (gitDir ? worktreeParentRoot(gitDir) : null) ?? dir;
2574
2886
  return { checkoutRoot: dir, canonicalRoot, gitDir };
2575
2887
  }
2576
- const parent = path3.dirname(dir);
2888
+ const parent = path4.dirname(dir);
2577
2889
  if (parent === dir)
2578
2890
  return null;
2579
2891
  dir = parent;
@@ -2582,16 +2894,16 @@ var require_workContext = __commonJS({
2582
2894
  }
2583
2895
  function readGitdirPointer(dotGitFile, containingDir) {
2584
2896
  try {
2585
- const match = /^gitdir:\s*(.+)\s*$/m.exec(fs3.readFileSync(dotGitFile, "utf8"));
2897
+ const match = /^gitdir:\s*(.+)\s*$/m.exec(fs5.readFileSync(dotGitFile, "utf8"));
2586
2898
  if (!match)
2587
2899
  return null;
2588
- return path3.resolve(containingDir, match[1].trim());
2900
+ return path4.resolve(containingDir, match[1].trim());
2589
2901
  } catch {
2590
2902
  return null;
2591
2903
  }
2592
2904
  }
2593
2905
  function worktreeParentRoot(resolvedGitDir) {
2594
- const marker = `${path3.sep}.git${path3.sep}worktrees${path3.sep}`;
2906
+ const marker = `${path4.sep}.git${path4.sep}worktrees${path4.sep}`;
2595
2907
  const idx = resolvedGitDir.indexOf(marker);
2596
2908
  if (idx === -1)
2597
2909
  return null;
@@ -2601,12 +2913,12 @@ var require_workContext = __commonJS({
2601
2913
  const sep = startPath.includes("\\") && !startPath.includes("/") ? "\\" : "/";
2602
2914
  const leading = /^[\\/]/.test(startPath) ? sep : "";
2603
2915
  const segments = startPath.split(/[\\/]/).filter(Boolean);
2604
- const join3 = (count) => leading + segments.slice(0, count).join(sep);
2916
+ const join4 = (count) => leading + segments.slice(0, count).join(sep);
2605
2917
  for (let i = 0; i + 2 < segments.length; i++) {
2606
2918
  if (segments[i] === ".claude" && segments[i + 1] === "worktrees") {
2607
2919
  if (i === 0)
2608
2920
  return null;
2609
- return { checkoutRoot: join3(i + 3), canonicalRoot: join3(i), gitDir: null };
2921
+ return { checkoutRoot: join4(i + 3), canonicalRoot: join4(i), gitDir: null };
2610
2922
  }
2611
2923
  }
2612
2924
  for (let i = 0; i + 1 < segments.length; i++) {
@@ -2616,7 +2928,7 @@ var require_workContext = __commonJS({
2616
2928
  continue;
2617
2929
  const repoName = folder.slice(0, -suffix.length);
2618
2930
  const canonicalRoot = leading + [...segments.slice(0, i), repoName].join(sep);
2619
- return { checkoutRoot: join3(i + 2), canonicalRoot, gitDir: null };
2931
+ return { checkoutRoot: join4(i + 2), canonicalRoot, gitDir: null };
2620
2932
  }
2621
2933
  return null;
2622
2934
  }
@@ -2664,7 +2976,7 @@ var require_workContext = __commonJS({
2664
2976
  return null;
2665
2977
  let head;
2666
2978
  try {
2667
- head = fs3.readFileSync(path3.join(gitDir, "HEAD"), "utf8").trim();
2979
+ head = fs5.readFileSync(path4.join(gitDir, "HEAD"), "utf8").trim();
2668
2980
  } catch {
2669
2981
  return null;
2670
2982
  }
@@ -2780,6 +3092,9 @@ var require_hookAdapter = __commonJS({
2780
3092
  if (events.length === 0)
2781
3093
  return;
2782
3094
  const notice = options.onNotice ?? ((message) => console.error(message));
3095
+ const hasToken = (id) => (0, tokenStore_1.readTokenFile)(process.env.ASCENDA_EVENT_WRITE_TOKEN_FILE ?? (0, tokenStore_1.defaultTokenFilePath)(id)) !== void 0;
3096
+ if (options.host && (0, credentials_1.isLocalOnlyHostInstall)(options.host, hasToken))
3097
+ return;
2783
3098
  let config;
2784
3099
  try {
2785
3100
  config = loadCliAgentConfig(options.toolType, options.sessionId, options.cwd, options);
@@ -2845,9 +3160,65 @@ var require_hookAdapter = __commonJS({
2845
3160
  }
2846
3161
  });
2847
3162
 
2848
- // ../packages/tool-kit/out/cliAgentSetup.js
2849
- var require_cliAgentSetup = __commonJS({
2850
- "../packages/tool-kit/out/cliAgentSetup.js"(exports) {
3163
+ // ../packages/tool-kit/out/hookSet.js
3164
+ var require_hookSet = __commonJS({
3165
+ "../packages/tool-kit/out/hookSet.js"(exports) {
3166
+ "use strict";
3167
+ Object.defineProperty(exports, "__esModule", { value: true });
3168
+ exports.UNVERSIONED_HOOK_SET = exports.HOOK_SET_FLAG = void 0;
3169
+ exports.hookSetArgument = hookSetArgument2;
3170
+ exports.readHookSet = readHookSet2;
3171
+ exports.isHookSet = isHookSet;
3172
+ exports.readViaPlugin = readViaPlugin2;
3173
+ exports.hookSetOfCommand = hookSetOfCommand2;
3174
+ exports.hookSetChanges = hookSetChanges2;
3175
+ exports.describeHookSetChanges = describeHookSetChanges2;
3176
+ exports.HOOK_SET_FLAG = "--hook-set";
3177
+ exports.UNVERSIONED_HOOK_SET = 1;
3178
+ function hookSetArgument2(hookSet) {
3179
+ return hookSet === void 0 ? "" : ` ${exports.HOOK_SET_FLAG} ${hookSet}`;
3180
+ }
3181
+ function readHookSet2(argv) {
3182
+ const index = argv.indexOf(exports.HOOK_SET_FLAG);
3183
+ if (index === -1)
3184
+ return void 0;
3185
+ const raw = argv[index + 1];
3186
+ if (raw === void 0 || !/^[1-9]\d*$/.test(raw))
3187
+ return void 0;
3188
+ const value = Number(raw);
3189
+ return isHookSet(value) ? value : void 0;
3190
+ }
3191
+ function isHookSet(value) {
3192
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 1;
3193
+ }
3194
+ function readViaPlugin2(env) {
3195
+ return env.CLAUDE_PLUGIN_ROOT ? true : void 0;
3196
+ }
3197
+ function hookSetOfCommand2(command) {
3198
+ const match = command.match(/--hook-set\s+(\d+)/);
3199
+ return match ? Number(match[1]) : exports.UNVERSIONED_HOOK_SET;
3200
+ }
3201
+ function hookSetChanges2(before, events) {
3202
+ const added = events.filter((event) => !before.has(event));
3203
+ const sets = [...before.values()];
3204
+ return sets.length ? { added, previousSet: Math.min(...sets) } : { added };
3205
+ }
3206
+ function describeHookSetChanges2(changes, hookSet) {
3207
+ if (changes.previousSet === void 0)
3208
+ return void 0;
3209
+ const parts = [];
3210
+ if (changes.added.length)
3211
+ parts.push(`added ${changes.added.join(", ")}`);
3212
+ if (changes.previousSet < hookSet)
3213
+ parts.push(`hook set ${changes.previousSet} \u2192 ${hookSet}`);
3214
+ return parts.length ? `upgraded: ${parts.join("; ")}` : void 0;
3215
+ }
3216
+ }
3217
+ });
3218
+
3219
+ // ../packages/tool-kit/out/studyJoin.js
3220
+ var require_studyJoin = __commonJS({
3221
+ "../packages/tool-kit/out/studyJoin.js"(exports) {
2851
3222
  "use strict";
2852
3223
  var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
2853
3224
  if (k2 === void 0) k2 = k;
@@ -2887,151 +3258,908 @@ var require_cliAgentSetup = __commonJS({
2887
3258
  };
2888
3259
  }();
2889
3260
  Object.defineProperty(exports, "__esModule", { value: true });
2890
- exports.isCliAgentManagementCommand = isCliAgentManagementCommand;
2891
- exports.cliAgentHookBinPath = cliAgentHookBinPath;
2892
- exports.runCliAgentSetup = runCliAgentSetup;
2893
- exports.writeHookSettings = writeHookSettings;
2894
- exports.findStaleHookCommands = findStaleHookCommands2;
2895
- var crypto2 = __importStar(__require("crypto"));
2896
- var fs3 = __importStar(__require("fs"));
2897
- var os2 = __importStar(__require("os"));
2898
- var path3 = __importStar(__require("path"));
2899
- var credentials_1 = require_credentials();
2900
- var hookAdapter_1 = require_hookAdapter();
3261
+ exports.runStudyJoin = runStudyJoin2;
3262
+ exports.formatWindow = formatWindow;
3263
+ var readline = __importStar(__require("node:readline"));
2901
3264
  var http_1 = require_http();
2902
- var tokenStore_1 = require_tokenStore();
2903
- var MANAGEMENT_COMMANDS2 = /* @__PURE__ */ new Set(["setup", "install", "status", "uninstall", "-h", "--help"]);
2904
- function isCliAgentManagementCommand(argument) {
2905
- return argument !== void 0 && MANAGEMENT_COMMANDS2.has(argument);
2906
- }
2907
- function cliAgentHookBinPath(binaryName) {
2908
- return path3.join((0, tokenStore_1.ascendaHome)(), "bin", binaryName);
2909
- }
2910
- function usage(spec) {
2911
- return `${spec.binaryName} setup \u2014 wire ${spec.displayName} to Ascenda telemetry
2912
-
2913
- npx ${spec.packageName} setup [options]
2914
- npx ${spec.packageName} status
2915
- npx ${spec.packageName} uninstall
2916
-
2917
- Options
2918
- --api-base-url <url> ingest host (default ${hookAdapter_1.DEFAULT_API_BASE_URL})
2919
- --local [port] shorthand for the local dev server (default port 4477)
2920
- --tool-installation-id <id> reuse an existing pairing instead of creating one
2921
- --token <eventWriteToken> reuse an existing token (stored 0600, never printed)
2922
- --scope project|user where hooks are registered (default project)
2923
- --project-dir <path> project root for --scope project (default cwd)
2924
- --dry-run print what would change, write nothing
2925
- -h, --help
2926
- `;
2927
- }
2928
- async function runCliAgentSetup(argv, spec) {
2929
- let options;
2930
- try {
2931
- options = parseArgs2(argv, spec);
2932
- } catch (error) {
2933
- console.error(error instanceof Error ? error.message : String(error));
2934
- return 1;
2935
- }
2936
- if (options.action === "help") {
2937
- console.log(usage(spec));
3265
+ var STUDY_JOIN_MODE = "report";
3266
+ var POLL_INTERVAL_MS = 3e3;
3267
+ var POLL_TIMEOUT_MS = 11 * 60 * 1e3;
3268
+ async function runStudyJoin2(ctx) {
3269
+ const stdin = ctx.stdin ?? process.stdin;
3270
+ const stdout = ctx.stdout ?? process.stdout;
3271
+ const stderr = ctx.stderr ?? process.stderr;
3272
+ const print = (line) => stdout.write(`${line}
3273
+ `);
3274
+ if (!stdin.isTTY || !stdout.isTTY) {
3275
+ stderr.write("join needs an interactive terminal (stdin and stdout). Run it directly, not from a script or a pipe.\n");
2938
3276
  return 0;
2939
3277
  }
2940
- if (options.action === "status")
2941
- return printStatus2(options, spec);
2942
- if (options.action === "uninstall")
2943
- return uninstall2(options, spec);
2944
- const apiBaseUrl = (options.apiBaseUrl ?? (0, credentials_1.readHostCredentials)(spec.host)?.apiBaseUrl ?? hookAdapter_1.DEFAULT_API_BASE_URL).replace(/\/$/, "");
2945
- console.log(`Ascenda setup for ${spec.displayName} \u2014 ${apiBaseUrl}`);
2946
- const identity = await resolveIdentity2(apiBaseUrl, options, spec);
2947
- if (!identity)
3278
+ if (!ctx.joinCode) {
3279
+ stderr.write("Usage: join <code>\n");
2948
3280
  return 1;
2949
- console.log(` pairing ${identity.toolInstallationId}${identity.paired ? " (new)" : " (existing)"}`);
2950
- const binary = installBinary2(spec, options.dryRun);
2951
- console.log(` hook binary ${binary}`);
2952
- if (!options.dryRun) {
2953
- (0, credentials_1.writeHostCredentials)(spec.host, { apiBaseUrl, toolInstallationId: identity.toolInstallationId, pairedAt: (/* @__PURE__ */ new Date()).toISOString() });
2954
3281
  }
2955
- console.log(` credentials ${(0, credentials_1.credentialsFilePath)()} (tools.${spec.host})`);
2956
- const settingsFile = spec.settings.settingsPath(options.scope, options.projectDir);
2957
- const written = writeHookSettings(settingsFile, binary, spec, options.dryRun);
2958
- if (written === null)
3282
+ let start;
3283
+ try {
3284
+ start = await (0, http_1.startStudyJoin)(ctx.apiBaseUrl, ctx.eventWriteToken, ctx.joinCode, STUDY_JOIN_MODE);
3285
+ } catch (error) {
3286
+ stderr.write(`${describeStartError(error)}
3287
+ `);
2959
3288
  return 1;
2960
- console.log(` hooks ${settingsFile} (${spec.hookEvents.length} events${written ? "" : ", already current"})`);
2961
- if (options.dryRun) {
2962
- console.log("\nDry run \u2014 nothing was written.");
3289
+ }
3290
+ print("");
3291
+ print(`${start.organisationName}: ${describeStudyKind(start.studyKind)}`);
3292
+ print(formatWindow(start.windowStartUtc, start.windowEndUtc));
3293
+ print("");
3294
+ print("Report (30 days) grants:");
3295
+ for (const grant of start.grants)
3296
+ print(` ${describeGrant(grant)}`);
3297
+ print("");
3298
+ print("Study mode needs the Ascenda app. Open the app to join that way instead.");
3299
+ print("");
3300
+ print("Join in:");
3301
+ print(" 1) Report (30 days)");
3302
+ print(" 2) Not now");
3303
+ print("");
3304
+ const answer = await askChoice(stdin, stdout);
3305
+ if (!/^(1|report)$/i.test(answer)) {
3306
+ print("Not now.");
2963
3307
  return 0;
2964
3308
  }
2965
- console.log(`
2966
- Done. ${spec.restartHint}`);
2967
- console.log(`Check anytime: npx ${spec.packageName} status`);
2968
- return 0;
2969
- }
2970
- function parseArgs2(argv, spec) {
2971
- const options = {
2972
- scope: "project",
2973
- projectDir: process.cwd(),
2974
- dryRun: false,
2975
- action: "install"
2976
- };
2977
- for (let i = 0; i < argv.length; i++) {
2978
- const arg = argv[i];
2979
- const next = () => {
2980
- const value = argv[++i];
2981
- if (value === void 0)
2982
- throw new Error(`${arg} needs a value`);
2983
- return value;
2984
- };
2985
- switch (arg) {
2986
- case "setup":
2987
- case "install":
2988
- options.action = "install";
2989
- break;
2990
- case "status":
2991
- options.action = "status";
2992
- break;
2993
- case "uninstall":
2994
- options.action = "uninstall";
2995
- break;
2996
- case "--api-base-url":
2997
- options.apiBaseUrl = next();
2998
- break;
2999
- case "--local": {
3000
- const peek = argv[i + 1];
3001
- const port = peek && /^\d+$/.test(peek) ? argv[++i] : "4477";
3002
- options.apiBaseUrl = `http://localhost:${port}`;
3003
- break;
3309
+ print("");
3310
+ print(`Confirm in the Ascenda app with code ${start.deviceCode}`);
3311
+ print(`Waiting for confirmation (expires ${formatLocalTime(start.expiresAt)})...`);
3312
+ const pollIntervalMs = ctx.pollIntervalMs ?? POLL_INTERVAL_MS;
3313
+ const deadline = Math.min(Date.parse(start.expiresAt) || Date.now() + POLL_TIMEOUT_MS, Date.now() + POLL_TIMEOUT_MS);
3314
+ while (Date.now() < deadline) {
3315
+ await new Promise((resolve2) => setTimeout(resolve2, pollIntervalMs));
3316
+ let poll;
3317
+ try {
3318
+ poll = await (0, http_1.getStudyJoinStatus)(ctx.apiBaseUrl, ctx.eventWriteToken, start.joinSessionId);
3319
+ } catch (error) {
3320
+ if (isRetryablePollError(error))
3321
+ continue;
3322
+ stderr.write(`${describeStartError(error)}
3323
+ `);
3324
+ return 1;
3325
+ }
3326
+ if (poll.status === "pending")
3327
+ continue;
3328
+ if (poll.status === "confirmed") {
3329
+ const granted = poll.granted ?? [];
3330
+ if (granted.length === 0) {
3331
+ print("");
3332
+ print("Nothing was granted. Run join again, or check with your organisation.");
3333
+ return 1;
3004
3334
  }
3005
- case "--tool-installation-id":
3006
- options.toolInstallationId = next();
3007
- break;
3008
- case "--token":
3009
- options.token = next();
3010
- break;
3011
- case "--scope": {
3012
- const value = next();
3013
- if (value !== "project" && value !== "user")
3014
- throw new Error(`--scope must be project or user, got ${value}`);
3015
- options.scope = value;
3016
- break;
3335
+ print("");
3336
+ print("Joined. Granted:");
3337
+ for (const grant of granted)
3338
+ print(` ${describeGrant(grant)}`);
3339
+ print("");
3340
+ print("Each of these can be turned off separately, in the app's consent settings.");
3341
+ print("The organisation sees group counts, never who joined.");
3342
+ return 0;
3343
+ }
3344
+ if (poll.status === "expired") {
3345
+ print("");
3346
+ print("This code expired before it was confirmed. Run join again for a fresh code.");
3347
+ return 1;
3348
+ }
3349
+ if (poll.refusedReason === "grant_failed") {
3350
+ print("");
3351
+ print("Join failed partway through. Some grants may not have gone through.");
3352
+ const granted = poll.granted ?? [];
3353
+ if (granted.length > 0) {
3354
+ print("");
3355
+ print("Granted before the failure:");
3356
+ for (const grant of granted)
3357
+ print(` ${describeGrant(grant)}`);
3358
+ print("");
3359
+ print("Each of these can be turned off separately, in the app's consent settings.");
3017
3360
  }
3018
- case "--project-dir":
3019
- options.projectDir = path3.resolve(next());
3020
- break;
3021
- case "--dry-run":
3022
- options.dryRun = true;
3023
- break;
3024
- case "-h":
3025
- case "--help":
3026
- options.action = "help";
3027
- break;
3028
- default:
3029
- throw new Error(`unknown argument: ${arg}
3030
-
3031
- ${usage(spec)}`);
3361
+ print("Run join again, or check with your organisation.");
3362
+ return 1;
3032
3363
  }
3364
+ print("");
3365
+ print(describeRefusal(poll.refusedReason));
3366
+ return 1;
3033
3367
  }
3034
- return options;
3368
+ print("");
3369
+ print("Timed out waiting for confirmation. Run join again for a fresh code.");
3370
+ return 1;
3371
+ }
3372
+ function isRetryablePollError(error) {
3373
+ if (error instanceof http_1.AscendaApiError)
3374
+ return error.status >= 500 && error.status <= 599;
3375
+ return true;
3376
+ }
3377
+ function askChoice(stdin, stdout) {
3378
+ return new Promise((resolve2) => {
3379
+ const rl = readline.createInterface({ input: stdin, output: stdout });
3380
+ let settled = false;
3381
+ const finish = (value) => {
3382
+ if (settled)
3383
+ return;
3384
+ settled = true;
3385
+ rl.close();
3386
+ resolve2(value.trim());
3387
+ };
3388
+ rl.question("Choice [Not now]: ", finish);
3389
+ rl.once("close", () => finish(""));
3390
+ });
3391
+ }
3392
+ function formatLocalTime(iso) {
3393
+ const date = new Date(iso);
3394
+ if (Number.isNaN(date.getTime()))
3395
+ return iso;
3396
+ return new Intl.DateTimeFormat(void 0, { day: "numeric", month: "short", hour: "numeric", minute: "2-digit" }).format(date);
3397
+ }
3398
+ function formatWindow(startUtc, endUtc) {
3399
+ const start = new Date(startUtc);
3400
+ const end = new Date(endUtc);
3401
+ const sameYear = start.getUTCFullYear() === end.getUTCFullYear();
3402
+ const dayMonth = { day: "numeric", month: "short", timeZone: "UTC" };
3403
+ const withYear = { ...dayMonth, year: "numeric" };
3404
+ const startFmt = new Intl.DateTimeFormat("en-GB", sameYear ? dayMonth : withYear);
3405
+ const endFmt = new Intl.DateTimeFormat("en-GB", withYear);
3406
+ return `${startFmt.format(start)} \u2013 ${endFmt.format(end)}`;
3407
+ }
3408
+ var GRANT_SENTENCES = {
3409
+ 501: "AI assistant data processing consent",
3410
+ 507: "Import of the AI-work history already on your machine"
3411
+ };
3412
+ function describeGrant(grant) {
3413
+ return GRANT_SENTENCES[grant.code] ?? humanise(grant.name);
3414
+ }
3415
+ var STUDY_KIND_SENTENCES = {
3416
+ Report30: "a 30-day report",
3417
+ Study90: "a 90-day study"
3418
+ };
3419
+ function describeStudyKind(studyKind) {
3420
+ return STUDY_KIND_SENTENCES[studyKind] ?? humanise(studyKind);
3421
+ }
3422
+ function humanise(name) {
3423
+ return name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").trim() || name;
3424
+ }
3425
+ var REFUSED_REASON_MESSAGES = {
3426
+ study_no_longer_live: "That study is no longer open to join.",
3427
+ withdrawn: "You're no longer an active participant in that study.",
3428
+ // Handled as its own branch above, with its granted list, before this
3429
+ // table is ever consulted — present so the type stays exhaustive, and as
3430
+ // a plain fallback should something call this function with it directly.
3431
+ grant_failed: "Join failed partway through. Some grants may not have gone through.",
3432
+ declined: "You declined in the app. Nothing was granted.",
3433
+ not_enrolled: "That study couldn't enrol you, so nothing was granted."
3434
+ };
3435
+ function describeRefusal(refusedReason) {
3436
+ if (refusedReason && REFUSED_REASON_MESSAGES[refusedReason])
3437
+ return REFUSED_REASON_MESSAGES[refusedReason];
3438
+ return "The join didn't go through. Nothing new was granted.";
3439
+ }
3440
+ var START_ERROR_MESSAGES = {
3441
+ join_code_not_found: "That code is not a study anyone can join. Check it and try again.",
3442
+ unknown_mode: "This tool only offers Report mode from the command line.",
3443
+ no_live_study: "There's nothing open to join with that code right now.",
3444
+ too_many_open_sessions: "This tool has too many joins waiting to be confirmed. Confirm one, or let one expire, then try again.",
3445
+ unknown_session: "That join can no longer be found. Run join again for a fresh code."
3446
+ };
3447
+ function describeStartError(error) {
3448
+ if (error instanceof http_1.AscendaApiError) {
3449
+ if (error.errorCode && START_ERROR_MESSAGES[error.errorCode])
3450
+ return START_ERROR_MESSAGES[error.errorCode];
3451
+ if (error.status === 401)
3452
+ return "This tool's pairing was rejected. Re-pair it, then try again.";
3453
+ return `Could not reach the join code (HTTP ${error.status}).`;
3454
+ }
3455
+ return error instanceof Error ? error.message : String(error);
3456
+ }
3457
+ }
3458
+ });
3459
+
3460
+ // ../packages/tool-kit/out/initiatives.js
3461
+ var require_initiatives = __commonJS({
3462
+ "../packages/tool-kit/out/initiatives.js"(exports) {
3463
+ "use strict";
3464
+ Object.defineProperty(exports, "__esModule", { value: true });
3465
+ exports.INITIATIVE_COPY = void 0;
3466
+ exports.initiativesStatusLines = initiativesStatusLines2;
3467
+ exports.renderInitiatives = renderInitiatives;
3468
+ var http_1 = require_http();
3469
+ var studyJoin_1 = require_studyJoin();
3470
+ var READ_TIMEOUT_MS = 5e3;
3471
+ exports.INITIATIVE_COPY = {
3472
+ outcomes: {
3473
+ moved_as_declared: "Moved the way declared, beyond the cohort's own variation",
3474
+ moved_against_declared: "Moved the other way, beyond the cohort's own variation",
3475
+ moved_no_direction_declared: "Moved beyond the cohort's own variation; no direction was declared",
3476
+ within_own_variation: "No further from the baseline than the cohort's own week-to-week variation",
3477
+ withheld: "Withheld"
3478
+ },
3479
+ withheldReasons: {
3480
+ cohort_below_minimum: "the cohort was too small to report on when the scoring window closed",
3481
+ below_minimum_cohort: "the cohort was too small to report on when the scoring window closed",
3482
+ below_minimum_cohort_size: "the cohort was too small to report on when the scoring window closed",
3483
+ baseline_withheld: "the baseline was withheld"
3484
+ }
3485
+ };
3486
+ var OUTCOME_EMPTY = "Not stated";
3487
+ var OUTCOME_UNKNOWN = "An outcome this app does not recognise";
3488
+ var WITHHELD_UNKNOWN = "Withheld, for a reason this version of the app doesn't name yet.";
3489
+ var DIRECTION_WORDS = {
3490
+ up: "Expected to rise",
3491
+ down: "Expected to fall",
3492
+ none_declared: "No direction declared"
3493
+ };
3494
+ var DIRECTION_UNKNOWN = "A direction this app does not recognise";
3495
+ async function initiativesStatusLines2(ctx) {
3496
+ const heading = "Changes your organisation has published to you";
3497
+ if (!ctx.eventWriteToken) {
3498
+ return [heading, " Not checked: this install holds no token, so nothing was fetched."];
3499
+ }
3500
+ const read = await (0, http_1.readInitiatives)(ctx.apiBaseUrl, ctx.eventWriteToken, AbortSignal.timeout(ctx.fetchTimeoutMs ?? READ_TIMEOUT_MS));
3501
+ if (read.kind === "rejected") {
3502
+ return [
3503
+ heading,
3504
+ ` Couldn't check: the server turned this install's request down. If that keeps happening, pair again with \`${ctx.pairCommand}\`.`
3505
+ ];
3506
+ }
3507
+ if (read.kind === "failed") {
3508
+ return [heading, ` Couldn't check: ${read.reason}. Run status again to retry.`];
3509
+ }
3510
+ return [heading, ...renderInitiatives(read.initiatives)];
3511
+ }
3512
+ function renderInitiatives(entries, copy = exports.INITIATIVE_COPY) {
3513
+ if (entries.length === 0)
3514
+ return [" None published to you."];
3515
+ const lines = [];
3516
+ let unreadable = 0;
3517
+ for (const entry of entries) {
3518
+ const initiative = asInitiative(entry);
3519
+ if (!initiative) {
3520
+ unreadable += 1;
3521
+ continue;
3522
+ }
3523
+ lines.push(...renderOne(initiative, copy));
3524
+ }
3525
+ if (unreadable > 0) {
3526
+ lines.push(` ${unreadable === 1 ? "1 entry" : `${unreadable} entries`} in the list couldn't be read by this version of the tool.`);
3527
+ }
3528
+ return lines;
3529
+ }
3530
+ function renderOne(initiative, copy) {
3531
+ const lines = [` ${initiative.organisationName}: ${initiative.title}`];
3532
+ lines.push(` ${describeStatus(initiative)}`);
3533
+ if (initiative.summaryForCohort) {
3534
+ for (const line of initiative.summaryForCohort.split(/\r?\n/))
3535
+ lines.push(` ${line}`);
3536
+ }
3537
+ if (initiative.direction)
3538
+ lines.push(` ${DIRECTION_WORDS[initiative.direction] ?? DIRECTION_UNKNOWN}`);
3539
+ lines.push(` Scoring window: ${formatWindowOrRaw(initiative.scoringStartUtc, initiative.scoringEndUtc)}`);
3540
+ if (initiative.result)
3541
+ lines.push(...renderResult(initiative.result, initiative.measureUnit, copy));
3542
+ lines.push("");
3543
+ return lines;
3544
+ }
3545
+ function describeStatus(initiative) {
3546
+ switch (initiative.status) {
3547
+ case "published":
3548
+ return "Published, not scored yet.";
3549
+ case "scored":
3550
+ return "Scored.";
3551
+ case "withdrawn":
3552
+ return initiative.withdrawnUtc ? `Withdrawn on ${formatDay(initiative.withdrawnUtc)}. It won't be scored.` : "Withdrawn. It won't be scored.";
3553
+ default:
3554
+ return "Status not recognised.";
3555
+ }
3556
+ }
3557
+ function renderResult(result, unit, copy) {
3558
+ const lines = [];
3559
+ const show = (n) => unit ? `${figure(n)} ${unit}` : figure(n);
3560
+ if (result.value === null) {
3561
+ const why = copy.withheldReasons[result.withheldReason ?? ""];
3562
+ lines.push(` ${why ? `Withheld: ${why}.` : WITHHELD_UNKNOWN}`);
3563
+ return lines;
3564
+ }
3565
+ lines.push(` Result: ${show(result.value)}`);
3566
+ lines.push(` ${movementLine(result)}`);
3567
+ lines.push(` ${result.outcome ? copy.outcomes[result.outcome] ?? OUTCOME_UNKNOWN : OUTCOME_EMPTY}`);
3568
+ return lines;
3569
+ }
3570
+ function movementLine(result) {
3571
+ if (result.outcome === "within_own_variation")
3572
+ return "No material change against frozen baseline";
3573
+ if (result.delta === null)
3574
+ return "No reading";
3575
+ if (result.delta > 0)
3576
+ return `Up ${figure(result.delta)} against frozen baseline`;
3577
+ if (result.delta < 0)
3578
+ return `Down ${figure(Math.abs(result.delta))} against frozen baseline`;
3579
+ return "No change against frozen baseline";
3580
+ }
3581
+ function figure(n) {
3582
+ return String(Number(n.toPrecision(12)));
3583
+ }
3584
+ function asInitiative(value) {
3585
+ if (!value || typeof value !== "object")
3586
+ return void 0;
3587
+ const o = value;
3588
+ if (typeof o.title !== "string" || typeof o.status !== "string")
3589
+ return void 0;
3590
+ return {
3591
+ id: typeof o.id === "string" ? o.id : "",
3592
+ organisationName: typeof o.organisationName === "string" ? o.organisationName : "Your organisation",
3593
+ title: o.title,
3594
+ summaryForCohort: typeof o.summaryForCohort === "string" ? o.summaryForCohort : "",
3595
+ measureUnit: typeof o.measureUnit === "string" ? o.measureUnit : null,
3596
+ scoringStartUtc: typeof o.scoringStartUtc === "string" ? o.scoringStartUtc : "",
3597
+ scoringEndUtc: typeof o.scoringEndUtc === "string" ? o.scoringEndUtc : "",
3598
+ withdrawnUtc: typeof o.withdrawnUtc === "string" ? o.withdrawnUtc : null,
3599
+ status: o.status,
3600
+ direction: typeof o.direction === "string" ? o.direction : null,
3601
+ result: asResult(o.result)
3602
+ };
3603
+ }
3604
+ function asResult(value) {
3605
+ if (!value || typeof value !== "object")
3606
+ return null;
3607
+ const r = value;
3608
+ const num = (x) => typeof x === "number" && Number.isFinite(x) ? x : null;
3609
+ return {
3610
+ scoredAtUtc: typeof r.scoredAtUtc === "string" ? r.scoredAtUtc : "",
3611
+ value: num(r.value),
3612
+ baselineValue: num(r.baselineValue),
3613
+ delta: num(r.delta),
3614
+ movement: typeof r.movement === "string" ? r.movement : null,
3615
+ outcome: typeof r.outcome === "string" ? r.outcome : "",
3616
+ withheldReason: typeof r.withheldReason === "string" ? r.withheldReason : null,
3617
+ basis: typeof r.basis === "string" ? r.basis : null
3618
+ };
3619
+ }
3620
+ function formatWindowOrRaw(startUtc, endUtc) {
3621
+ if (Number.isNaN(Date.parse(startUtc)) || Number.isNaN(Date.parse(endUtc)))
3622
+ return "not given";
3623
+ return (0, studyJoin_1.formatWindow)(startUtc, endUtc);
3624
+ }
3625
+ function formatDay(iso) {
3626
+ const date = new Date(iso);
3627
+ if (Number.isNaN(date.getTime()))
3628
+ return iso;
3629
+ return new Intl.DateTimeFormat("en-GB", { day: "numeric", month: "short", year: "numeric", timeZone: "UTC" }).format(date);
3630
+ }
3631
+ }
3632
+ });
3633
+
3634
+ // ../packages/tool-kit/out/setupDisclosure.js
3635
+ var require_setupDisclosure = __commonJS({
3636
+ "../packages/tool-kit/out/setupDisclosure.js"(exports) {
3637
+ "use strict";
3638
+ Object.defineProperty(exports, "__esModule", { value: true });
3639
+ exports.FREE_TEXT_KEYS = exports.REFUSALS = exports.ALWAYS_SENT = exports.FAMILY_SENTENCES = void 0;
3640
+ exports.renderSetupDisclosure = renderSetupDisclosure3;
3641
+ exports.FAMILY_SENTENCES = {
3642
+ session: "when a session starts and ends, the one-word reason for the end if your agent gives one, how long each turn took, and whether it ran on this machine or in a hosted cloud session",
3643
+ counts: "how many prompts you sent, how many replies came back, and what class of command ran in a terminal \u2014 test, lint, build, git and so on",
3644
+ tools: "the name of each tool your agent calls",
3645
+ outcome: "whether a call succeeded, failed, or was interrupted",
3646
+ clock: "your machine's offset from UTC, so an evening is read as an evening",
3647
+ repo: "your project and branch as digests computed on this machine \u2014 never the names themselves",
3648
+ model: "which model served the session, by name and by tier",
3649
+ posture: "the permission posture your agent was working under \u2014 asking each time, accepting edits, and so on",
3650
+ git: "that a commit, push or revert happened, and when a pull request opened or merged",
3651
+ edits: "roughly how much a file changed, as a bucket, and whether you edited it after the agent wrote it",
3652
+ context: "how full the context window got",
3653
+ waiting: "that your agent stopped and waited for you, as one word: permission_request, idle_prompt, or other",
3654
+ subagents: "when a subagent starts and stops, the id your agent gives it, and whether it was built in, from a plugin or one you defined \u2014 never its name or what it was asked",
3655
+ reading: "what the reader could not make sense of \u2014 lines it failed to parse, files it could not open, and prompts it judged machine-written rather than typed"
3656
+ };
3657
+ exports.ALWAYS_SENT = ["session", "counts", "tools", "outcome", "repo", "clock"];
3658
+ exports.REFUSALS = [
3659
+ "Never your prompts, your agent's replies, or anything inside a file.",
3660
+ "Never a file path, a command line, or a repository or branch name.",
3661
+ "Content is read here only to choose one of a fixed set of labels, then discarded. No mapper writes it to an event, and a test fails the build if one starts."
3662
+ ];
3663
+ exports.FREE_TEXT_KEYS = ["message"];
3664
+ function renderSetupDisclosure3({ sends, displayName }) {
3665
+ const declared = /* @__PURE__ */ new Set([...exports.ALWAYS_SENT, ...sends]);
3666
+ const ordered = Object.keys(exports.FAMILY_SENTENCES).filter((family) => declared.has(family));
3667
+ const lines = [
3668
+ `What this sends from ${displayName}, once paired:`,
3669
+ ...ordered.map((family) => ` \xB7 ${exports.FAMILY_SENTENCES[family]}`),
3670
+ "",
3671
+ ...exports.REFUSALS.map((line) => ` ${line}`),
3672
+ "",
3673
+ " Turn it off by revoking this tool in the Ascenda app."
3674
+ ];
3675
+ return lines.join("\n");
3676
+ }
3677
+ }
3678
+ });
3679
+
3680
+ // ../packages/tool-kit/out/studyNotices.js
3681
+ var require_studyNotices = __commonJS({
3682
+ "../packages/tool-kit/out/studyNotices.js"(exports) {
3683
+ "use strict";
3684
+ Object.defineProperty(exports, "__esModule", { value: true });
3685
+ exports.NOTICED_PURPOSES = void 0;
3686
+ exports.studyNoticeStatus = studyNoticeStatus2;
3687
+ exports.renderStudyNotices = renderStudyNotices;
3688
+ exports.runStudyObjection = runStudyObjection2;
3689
+ var http_1 = require_http();
3690
+ var READ_TIMEOUT_MS = 5e3;
3691
+ var NOTICE_LABEL = "Counted unless you object";
3692
+ var PROCESSOR = "Ascenda";
3693
+ exports.NOTICED_PURPOSES = [
3694
+ { code: 501, slug: "telemetry", title: "Live tool telemetry" },
3695
+ { code: 507, slug: "import", title: "One-time import of past AI work" },
3696
+ { code: 11, slug: "work-patterns", title: "Work-pattern axes in the group figures" }
3697
+ ];
3698
+ var BASIS_WORDS = {
3699
+ legitimate_interests: "legitimate interests",
3700
+ collective_agreement: "a collective agreement"
3701
+ };
3702
+ async function studyNoticeStatus2(ctx) {
3703
+ const nothing = { lines: [], markShown: async () => {
3704
+ } };
3705
+ const token = ctx.eventWriteToken;
3706
+ if (!token)
3707
+ return nothing;
3708
+ const read = await (0, http_1.readStudyNotices)(ctx.apiBaseUrl, token, AbortSignal.timeout(ctx.fetchTimeoutMs ?? READ_TIMEOUT_MS));
3709
+ if (read.kind !== "ok")
3710
+ return nothing;
3711
+ const lines = renderStudyNotices(read.notices, ctx.commandPrefix, ctx.now);
3712
+ if (lines.length === 0)
3713
+ return nothing;
3714
+ const unshown = shownPurposes(read.notices).filter((n) => !n.noticeFromUtc && n.organisationId);
3715
+ return {
3716
+ lines,
3717
+ markShown: async () => {
3718
+ const signal = AbortSignal.timeout(ctx.fetchTimeoutMs ?? READ_TIMEOUT_MS);
3719
+ await Promise.all(unshown.map((n) => (0, http_1.markStudyNoticeShown)(ctx.apiBaseUrl, token, n.organisationId, n.code, signal)));
3720
+ }
3721
+ };
3722
+ }
3723
+ function shownPurposes(entries) {
3724
+ return entries.map(asNotice).filter((n) => n !== void 0 && exports.NOTICED_PURPOSES.some((p) => p.code === n.code));
3725
+ }
3726
+ function renderStudyNotices(entries, commandPrefix, now = /* @__PURE__ */ new Date()) {
3727
+ const body = [];
3728
+ let unreadable = 0;
3729
+ for (const entry of entries) {
3730
+ const notice = asNotice(entry);
3731
+ const purpose = notice && exports.NOTICED_PURPOSES.find((p) => p.code === notice.code);
3732
+ if (!notice || !purpose) {
3733
+ unreadable += 1;
3734
+ continue;
3735
+ }
3736
+ body.push(...renderOne(notice, purpose, commandPrefix, now));
3737
+ }
3738
+ if (body.length === 0)
3739
+ return [];
3740
+ if (unreadable > 0) {
3741
+ body.push(` ${unreadable === 1 ? "1 entry" : `${unreadable} entries`} in the list couldn't be read by this version of the tool.`);
3742
+ }
3743
+ return ["", "Your organisation's study", ...body];
3744
+ }
3745
+ function renderOne(notice, purpose, commandPrefix, now) {
3746
+ const org = notice.organisationName;
3747
+ const command = `${commandPrefix} object ${purpose.slug}`;
3748
+ const lines = [` ${org}: ${purpose.title}`];
3749
+ lines.push(` ${notice.label || NOTICE_LABEL}`);
3750
+ lines.push(` ${basisLine(notice)}`);
3751
+ if (notice.signatoryName)
3752
+ lines.push(` Recorded by ${notice.signatoryName}.`);
3753
+ lines.push(` ${notice.processor || PROCESSOR} processes this for ${org}.`);
3754
+ if (notice.objected === true) {
3755
+ lines.push(" You objected. You are left out from the next report on.");
3756
+ lines.push(` To undo: ${command} --undo`);
3757
+ } else if (notice.objected === false) {
3758
+ lines.push(" You haven't objected.");
3759
+ if (notice.noticeFromUtc && isDate(notice.noticeFromUtc)) {
3760
+ const starts = notice.countingFromUtc && isDate(notice.countingFromUtc) ? notice.countingFromUtc : new Date(Date.parse(notice.noticeFromUtc) + NOTICE_PERIOD_MS).toISOString();
3761
+ if (Date.parse(starts) > now.getTime()) {
3762
+ lines.push(` Notice given ${formatDay(notice.noticeFromUtc)}. Counting starts ${formatDay(starts)}.`);
3763
+ }
3764
+ }
3765
+ lines.push(` To object: ${command}. No reason is asked. You are left out from the next report on, and earlier reports stay as they were.`);
3766
+ } else {
3767
+ lines.push(" This version of the tool couldn't read whether you've objected. Run status again.");
3768
+ lines.push(` To object: ${command}`);
3769
+ lines.push(` To undo: ${command} --undo`);
3770
+ }
3771
+ lines.push("");
3772
+ return lines;
3773
+ }
3774
+ function basisLine(notice) {
3775
+ const words = notice.basisLabel ?? BASIS_WORDS[notice.basis];
3776
+ const head = words ? `${notice.organisationName}'s basis is ${words}.` : `${notice.organisationName}'s basis is one this version of the tool can't name.`;
3777
+ const dated = notice.documentDate && isDate(notice.documentDate) ? formatDay(notice.documentDate) : null;
3778
+ const ref = notice.documentReference ? `ref ${notice.documentReference}` : null;
3779
+ const title = notice.documentTitle ? dated ? `${notice.documentTitle} (${dated})` : notice.documentTitle : null;
3780
+ const document = [title, ref].filter((part) => Boolean(part)).join(", ");
3781
+ return document ? `${head} Document: ${document}.` : head;
3782
+ }
3783
+ var NOTICE_PERIOD_MS = 14 * 24 * 60 * 60 * 1e3;
3784
+ function asNotice(value) {
3785
+ if (!value || typeof value !== "object")
3786
+ return void 0;
3787
+ const o = value;
3788
+ if (typeof o.code !== "number")
3789
+ return void 0;
3790
+ if (typeof o.mode === "string" && o.mode.trim().toLowerCase() !== "notice")
3791
+ return void 0;
3792
+ const str = (x) => typeof x === "string" && x.trim() ? x : null;
3793
+ return {
3794
+ organisationId: str(o.organisationId),
3795
+ organisationName: str(o.organisationName) ?? "Your organisation",
3796
+ code: o.code,
3797
+ name: str(o.name),
3798
+ label: str(o.label),
3799
+ processor: str(o.processor),
3800
+ basis: typeof o.basis === "string" ? o.basis : "",
3801
+ basisLabel: str(o.basisLabel),
3802
+ documentTitle: str(o.documentTitle),
3803
+ documentDate: str(o.documentDate),
3804
+ documentReference: str(o.documentReference),
3805
+ signatoryName: str(o.signatoryName),
3806
+ objected: typeof o.objected === "boolean" ? o.objected : null,
3807
+ objectedAtUtc: str(o.objectedAtUtc),
3808
+ noticeFromUtc: str(o.noticeFromUtc),
3809
+ countingFromUtc: str(o.countingFromUtc)
3810
+ };
3811
+ }
3812
+ async function runStudyObjection2(ctx) {
3813
+ const stdin = ctx.stdin ?? process.stdin;
3814
+ const stdout = ctx.stdout ?? process.stdout;
3815
+ const stderr = ctx.stderr ?? process.stderr;
3816
+ const print = (line) => stdout.write(`${line}
3817
+ `);
3818
+ if (!stdin.isTTY || !stdout.isTTY) {
3819
+ stderr.write("object needs an interactive terminal (stdin and stdout). Run it directly, not from a script or a pipe.\n");
3820
+ return 1;
3821
+ }
3822
+ const undo = ctx.argv.includes("--undo");
3823
+ const rest = ctx.argv.filter((a) => a !== "--undo");
3824
+ const purpose = rest.length === 1 ? exports.NOTICED_PURPOSES.find((p) => p.slug === rest[0]) : void 0;
3825
+ if (!purpose) {
3826
+ stderr.write(objectionUsage(ctx.commandPrefix));
3827
+ return 1;
3828
+ }
3829
+ if (!ctx.eventWriteToken) {
3830
+ stderr.write(`This install isn't paired, so there's nothing to object to. Pair with \`${ctx.pairCommand}\`.
3831
+ `);
3832
+ return 1;
3833
+ }
3834
+ const command = `${ctx.commandPrefix} object ${purpose.slug}`;
3835
+ try {
3836
+ await (0, http_1.setStudyObjection)(ctx.apiBaseUrl, ctx.eventWriteToken, purpose.code, !undo);
3837
+ } catch (error) {
3838
+ stderr.write(`${describeObjectionError(error, purpose, undo, ctx.pairCommand)}
3839
+ `);
3840
+ return 1;
3841
+ }
3842
+ if (undo) {
3843
+ print(`Objection withdrawn: ${purpose.title}.`);
3844
+ print("You're counted again from the next report.");
3845
+ print(`To object again: ${command}`);
3846
+ } else {
3847
+ print(`Objected: ${purpose.title}.`);
3848
+ print("You objected. You are left out from the next report on, and earlier reports stay as they were.");
3849
+ print(`To undo: ${command} --undo`);
3850
+ }
3851
+ return 0;
3852
+ }
3853
+ function objectionUsage(commandPrefix) {
3854
+ const lines = [`Usage: ${commandPrefix} object <purpose> [--undo]`, "", "Purposes:"];
3855
+ for (const p of exports.NOTICED_PURPOSES)
3856
+ lines.push(` ${p.slug.padEnd(14)}${p.title}`);
3857
+ lines.push("", "status shows which of these your organisation counts unless you object.");
3858
+ return `${lines.join("\n")}
3859
+ `;
3860
+ }
3861
+ function describeObjectionError(error, purpose, undo, pairCommand) {
3862
+ if (error instanceof http_1.AscendaApiError) {
3863
+ if (error.status === 404 && error.errorCode === "not_noticed") {
3864
+ return undo ? `Your organisation doesn't count you for ${purpose.title} unless you object, so there's no objection to undo.` : `Your organisation doesn't count you for ${purpose.title} unless you object, so there's nothing to object to.`;
3865
+ }
3866
+ if (error.status === 401)
3867
+ return `The server turned this install's request down. If that keeps happening, pair again with \`${pairCommand}\`.`;
3868
+ if (error.status === 404)
3869
+ return "This server doesn't take objections yet. Nothing changed.";
3870
+ return `Couldn't record that (HTTP ${error.status}). Nothing changed. Run it again to retry.`;
3871
+ }
3872
+ return "Couldn't reach the server. Nothing changed. Run it again to retry.";
3873
+ }
3874
+ function isDate(iso) {
3875
+ return !Number.isNaN(Date.parse(iso));
3876
+ }
3877
+ var MONTHS2 = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
3878
+ function formatDay(iso) {
3879
+ const date = new Date(iso);
3880
+ return `${date.getUTCDate()} ${MONTHS2[date.getUTCMonth()]} ${date.getUTCFullYear()}`;
3881
+ }
3882
+ }
3883
+ });
3884
+
3885
+ // ../packages/tool-kit/out/cliAgentSetup.js
3886
+ var require_cliAgentSetup = __commonJS({
3887
+ "../packages/tool-kit/out/cliAgentSetup.js"(exports) {
3888
+ "use strict";
3889
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
3890
+ if (k2 === void 0) k2 = k;
3891
+ var desc = Object.getOwnPropertyDescriptor(m, k);
3892
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
3893
+ desc = { enumerable: true, get: function() {
3894
+ return m[k];
3895
+ } };
3896
+ }
3897
+ Object.defineProperty(o, k2, desc);
3898
+ } : function(o, m, k, k2) {
3899
+ if (k2 === void 0) k2 = k;
3900
+ o[k2] = m[k];
3901
+ });
3902
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
3903
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
3904
+ } : function(o, v) {
3905
+ o["default"] = v;
3906
+ });
3907
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
3908
+ var ownKeys = function(o) {
3909
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
3910
+ var ar = [];
3911
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
3912
+ return ar;
3913
+ };
3914
+ return ownKeys(o);
3915
+ };
3916
+ return function(mod) {
3917
+ if (mod && mod.__esModule) return mod;
3918
+ var result = {};
3919
+ if (mod != null) {
3920
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
3921
+ }
3922
+ __setModuleDefault(result, mod);
3923
+ return result;
3924
+ };
3925
+ }();
3926
+ Object.defineProperty(exports, "__esModule", { value: true });
3927
+ exports.isCliAgentManagementCommand = isCliAgentManagementCommand;
3928
+ exports.cliAgentHookBinPath = cliAgentHookBinPath;
3929
+ exports.runCliAgentSetup = runCliAgentSetup;
3930
+ exports.writeHookSettings = writeHookSettings;
3931
+ exports.registeredHookSets = registeredHookSets;
3932
+ exports.findStaleHookCommands = findStaleHookCommands2;
3933
+ var crypto2 = __importStar(__require("crypto"));
3934
+ var fs5 = __importStar(__require("fs"));
3935
+ var os3 = __importStar(__require("os"));
3936
+ var path4 = __importStar(__require("path"));
3937
+ var collectorVersion_1 = require_collectorVersion();
3938
+ var credentials_1 = require_credentials();
3939
+ var hookAdapter_1 = require_hookAdapter();
3940
+ var http_1 = require_http();
3941
+ var hookSet_1 = require_hookSet();
3942
+ var initiatives_1 = require_initiatives();
3943
+ var setupDisclosure_1 = require_setupDisclosure();
3944
+ var stateStore_1 = require_stateStore();
3945
+ var studyJoin_1 = require_studyJoin();
3946
+ var studyNotices_1 = require_studyNotices();
3947
+ var tokenStore_1 = require_tokenStore();
3948
+ var MANAGEMENT_COMMANDS2 = /* @__PURE__ */ new Set(["setup", "install", "status", "uninstall", "join", "object", "-h", "--help"]);
3949
+ function isCliAgentManagementCommand(argument) {
3950
+ return argument !== void 0 && MANAGEMENT_COMMANDS2.has(argument);
3951
+ }
3952
+ function cliAgentHookBinPath(binaryName) {
3953
+ return path4.join((0, tokenStore_1.ascendaHome)(), "bin", binaryName);
3954
+ }
3955
+ function usage(spec) {
3956
+ return `${spec.binaryName} setup \u2014 wire ${spec.displayName} to Ascenda telemetry
3957
+
3958
+ npx ${spec.packageName} setup [options]
3959
+ npx ${spec.packageName} status
3960
+ npx ${spec.packageName} uninstall
3961
+ npx ${spec.packageName} join <code>
3962
+ npx ${spec.packageName} object <purpose> [--undo]
3963
+
3964
+ Options
3965
+ --api-base-url <url> ingest host (default ${hookAdapter_1.DEFAULT_API_BASE_URL})
3966
+ --local [port] shorthand for the local dev server (default port 4477)
3967
+ --tool-installation-id <id> reuse an existing pairing instead of creating one
3968
+ --token <eventWriteToken> reuse an existing token (stored 0600, never printed)
3969
+ --no-pair install without pairing: local features on, nothing sent
3970
+ --scope project|user where hooks are registered (default project)
3971
+ --project-dir <path> project root for --scope project (default cwd)
3972
+ --dry-run print what would change, write nothing
3973
+ -h, --help
3974
+ `;
3975
+ }
3976
+ async function runCliAgentSetup(argv, spec) {
3977
+ if (argv[0] === "join")
3978
+ return runCliAgentStudyJoin(argv.slice(1), spec);
3979
+ if (argv[0] === "object")
3980
+ return runCliAgentStudyObjection(argv.slice(1), spec);
3981
+ let options;
3982
+ try {
3983
+ options = parseArgs2(argv, spec);
3984
+ } catch (error) {
3985
+ console.error(error instanceof Error ? error.message : String(error));
3986
+ return 1;
3987
+ }
3988
+ if (options.action === "help") {
3989
+ console.log(usage(spec));
3990
+ return 0;
3991
+ }
3992
+ if (options.action === "status")
3993
+ return await printStatus2(options, spec);
3994
+ if (options.action === "uninstall")
3995
+ return uninstall2(options, spec);
3996
+ const apiBaseUrl = (options.apiBaseUrl ?? (0, credentials_1.readHostCredentials)(spec.host)?.apiBaseUrl ?? hookAdapter_1.DEFAULT_API_BASE_URL).replace(/\/$/, "");
3997
+ console.log(`Ascenda setup for ${spec.displayName} \u2014 ${apiBaseUrl}`);
3998
+ console.log(`
3999
+ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName: spec.displayName })}
4000
+ `);
4001
+ let identity;
4002
+ let unpairedReason;
4003
+ if (options.skipPairing) {
4004
+ unpairedReason = "asked not to pair (--no-pair)";
4005
+ } else {
4006
+ identity = await resolveIdentity2(apiBaseUrl, options, spec);
4007
+ if (identity) {
4008
+ console.log(` pairing ${identity.toolInstallationId}${identity.paired ? " (new)" : " (existing)"}`);
4009
+ } else {
4010
+ unpairedReason = "pairing did not finish \u2014 installing the local half anyway";
4011
+ }
4012
+ }
4013
+ if (unpairedReason) {
4014
+ console.log(` pairing none: ${unpairedReason}`);
4015
+ console.log(" local features on, nothing is sent");
4016
+ }
4017
+ const binary = installBinary2(spec, options.dryRun);
4018
+ console.log(` hook binary ${binary}`);
4019
+ if (!options.dryRun) {
4020
+ const now = (/* @__PURE__ */ new Date()).toISOString();
4021
+ const toolInstallationId = identity?.toolInstallationId ?? options.toolInstallationId ?? (0, credentials_1.readHostCredentials)(spec.host)?.toolInstallationId ?? `${spec.toolType}:${crypto2.randomUUID()}`;
4022
+ (0, credentials_1.writeHostCredentials)(spec.host, {
4023
+ apiBaseUrl,
4024
+ toolInstallationId,
4025
+ ...identity ? { pairedAt: now } : { localOnly: true, installedAt: now }
4026
+ });
4027
+ }
4028
+ console.log(` credentials ${(0, credentials_1.credentialsFilePath)()} (tools.${spec.host})`);
4029
+ const settingsFile = spec.settings.settingsPath(options.scope, options.projectDir);
4030
+ const before = registeredHookSets(readSettings(settingsFile), spec);
4031
+ const written = writeHookSettings(settingsFile, binary, spec, options.dryRun);
4032
+ if (written === null)
4033
+ return 1;
4034
+ console.log(` hooks ${settingsFile} (${spec.hookEvents.length} events${written ? "" : ", already current"})`);
4035
+ const changes = spec.hookSet === void 0 ? void 0 : (0, hookSet_1.describeHookSetChanges)((0, hookSet_1.hookSetChanges)(before, spec.hookEvents), spec.hookSet);
4036
+ if (changes)
4037
+ console.log(` ${changes}`);
4038
+ if (options.dryRun) {
4039
+ console.log("\nDry run \u2014 nothing was written.");
4040
+ return 0;
4041
+ }
4042
+ console.log(`
4043
+ Done. ${spec.restartHint}`);
4044
+ if (!identity) {
4045
+ console.log(`Pair later: npx ${spec.packageName} setup`);
4046
+ }
4047
+ console.log(`Check anytime: npx ${spec.packageName} status`);
4048
+ return 0;
4049
+ }
4050
+ function parseArgs2(argv, spec) {
4051
+ const options = {
4052
+ scope: "project",
4053
+ projectDir: process.cwd(),
4054
+ dryRun: false,
4055
+ skipPairing: false,
4056
+ action: "install"
4057
+ };
4058
+ for (let i = 0; i < argv.length; i++) {
4059
+ const arg = argv[i];
4060
+ const next = () => {
4061
+ const value = argv[++i];
4062
+ if (value === void 0)
4063
+ throw new Error(`${arg} needs a value`);
4064
+ return value;
4065
+ };
4066
+ switch (arg) {
4067
+ case "setup":
4068
+ case "install":
4069
+ options.action = "install";
4070
+ break;
4071
+ case "status":
4072
+ options.action = "status";
4073
+ break;
4074
+ case "uninstall":
4075
+ options.action = "uninstall";
4076
+ break;
4077
+ case "--api-base-url":
4078
+ options.apiBaseUrl = next();
4079
+ break;
4080
+ case "--local": {
4081
+ const peek = argv[i + 1];
4082
+ const port = peek && /^\d+$/.test(peek) ? argv[++i] : "4477";
4083
+ options.apiBaseUrl = `http://localhost:${port}`;
4084
+ break;
4085
+ }
4086
+ case "--tool-installation-id":
4087
+ options.toolInstallationId = next();
4088
+ break;
4089
+ case "--token":
4090
+ options.token = next();
4091
+ break;
4092
+ case "--scope": {
4093
+ const value = next();
4094
+ if (value !== "project" && value !== "user")
4095
+ throw new Error(`--scope must be project or user, got ${value}`);
4096
+ options.scope = value;
4097
+ break;
4098
+ }
4099
+ case "--project-dir":
4100
+ options.projectDir = path4.resolve(next());
4101
+ break;
4102
+ case "--dry-run":
4103
+ options.dryRun = true;
4104
+ break;
4105
+ case "--no-pair":
4106
+ // `--no-pairing` is the spelling this landed under first. Both appeared
4107
+ // only in an unreleased changelog, so this alias exists to spare anyone
4108
+ // reading that draft, and `--no-pair` — the Claude Code adapter's own
4109
+ // spelling — is the documented one.
4110
+ case "--no-pairing":
4111
+ options.skipPairing = true;
4112
+ break;
4113
+ case "-h":
4114
+ case "--help":
4115
+ options.action = "help";
4116
+ break;
4117
+ default:
4118
+ throw new Error(`unknown argument: ${arg}
4119
+
4120
+ ${usage(spec)}`);
4121
+ }
4122
+ }
4123
+ return options;
4124
+ }
4125
+ async function runCliAgentStudyJoin(argv, spec) {
4126
+ const joinCode = argv[0];
4127
+ if (!joinCode || joinCode.startsWith("-")) {
4128
+ console.error(`Usage: npx ${spec.packageName} join <code>`);
4129
+ return 1;
4130
+ }
4131
+ const pairing = resolvePairedToken(spec);
4132
+ if (!pairing)
4133
+ return 1;
4134
+ return (0, studyJoin_1.runStudyJoin)({ ...pairing, displayName: spec.displayName, joinCode });
4135
+ }
4136
+ async function runCliAgentStudyObjection(argv, spec) {
4137
+ const pairing = resolvePairedToken(spec);
4138
+ if (!pairing)
4139
+ return 1;
4140
+ return (0, studyNotices_1.runStudyObjection)({
4141
+ ...pairing,
4142
+ commandPrefix: `npx ${spec.packageName}`,
4143
+ pairCommand: `npx ${spec.packageName} setup`,
4144
+ argv
4145
+ });
4146
+ }
4147
+ function resolvePairedToken(spec) {
4148
+ const setupCommand = `npx ${spec.packageName} setup`;
4149
+ let toolInstallationId;
4150
+ try {
4151
+ ({ toolInstallationId } = (0, hookAdapter_1.resolveCliAgentInstallationId)(spec.toolType, { host: spec.host, setupCommand }));
4152
+ } catch (error) {
4153
+ console.error(error instanceof hookAdapter_1.MissingInstallationIdError ? error.message : error instanceof Error ? error.message : String(error));
4154
+ return void 0;
4155
+ }
4156
+ const eventWriteToken = (0, tokenStore_1.readTokenFile)(process.env.ASCENDA_EVENT_WRITE_TOKEN_FILE ?? (0, tokenStore_1.defaultTokenFilePath)(toolInstallationId)) ?? process.env.ASCENDA_EVENT_WRITE_TOKEN;
4157
+ if (!eventWriteToken) {
4158
+ console.error(`Not paired: no write token for ${toolInstallationId}. Run: ${setupCommand}`);
4159
+ return void 0;
4160
+ }
4161
+ const apiBaseUrl = (process.env.ASCENDA_API_BASE_URL ?? (0, credentials_1.readHostCredentials)(spec.host)?.apiBaseUrl ?? hookAdapter_1.DEFAULT_API_BASE_URL).replace(/\/$/, "");
4162
+ return { apiBaseUrl, eventWriteToken };
3035
4163
  }
3036
4164
  async function resolveIdentity2(apiBaseUrl, options, spec) {
3037
4165
  const existingId = options.toolInstallationId ?? (0, credentials_1.readHostCredentials)(spec.host)?.toolInstallationId;
@@ -3040,8 +4168,13 @@ ${usage(spec)}`);
3040
4168
  (0, tokenStore_1.persistEventWriteToken)((0, tokenStore_1.defaultTokenFilePath)(existingId), options.token);
3041
4169
  return { toolInstallationId: existingId, paired: false };
3042
4170
  }
3043
- if (existingId && (0, tokenStore_1.readTokenFile)((0, tokenStore_1.defaultTokenFilePath)(existingId))) {
3044
- return { toolInstallationId: existingId, paired: false };
4171
+ const existingToken = existingId ? (0, tokenStore_1.readTokenFile)((0, tokenStore_1.defaultTokenFilePath)(existingId)) : void 0;
4172
+ if (existingId && existingToken) {
4173
+ const check = await checkSavedToken(apiBaseUrl, existingId, existingToken);
4174
+ if (check === "keep")
4175
+ return { toolInstallationId: existingId, paired: false };
4176
+ console.log(`
4177
+ The saved token for ${existingId} isn't accepted any more. Pairing again.`);
3045
4178
  }
3046
4179
  if (options.dryRun) {
3047
4180
  return { toolInstallationId: existingId ?? `${spec.toolType}:<paired at run time>`, paired: false };
@@ -3049,7 +4182,7 @@ ${usage(spec)}`);
3049
4182
  const toolInstallationId = existingId ?? `${spec.toolType}:${crypto2.randomUUID()}`;
3050
4183
  let session;
3051
4184
  try {
3052
- session = await (0, http_1.createPairingSession)(apiBaseUrl, toolInstallationId, spec.toolType, `${spec.displayName} on ${os2.hostname()}`);
4185
+ session = await (0, http_1.createPairingSession)(apiBaseUrl, toolInstallationId, spec.toolType, `${spec.displayName} on ${os3.hostname()}`);
3053
4186
  } catch (error) {
3054
4187
  console.error(`
3055
4188
  Could not reach ${apiBaseUrl} to pair: ${error instanceof Error ? error.message : String(error)}`);
@@ -3062,6 +4195,18 @@ Could not reach ${apiBaseUrl} to pair: ${error instanceof Error ? error.message
3062
4195
  (0, tokenStore_1.persistEventWriteToken)((0, tokenStore_1.defaultTokenFilePath)(toolInstallationId), token);
3063
4196
  return { toolInstallationId, paired: true };
3064
4197
  }
4198
+ var TOKEN_CHECK_TIMEOUT_MS = 5e3;
4199
+ async function checkSavedToken(apiBaseUrl, toolInstallationId, token) {
4200
+ const read = await (0, http_1.readInitiatives)(apiBaseUrl, token, AbortSignal.timeout(TOKEN_CHECK_TIMEOUT_MS));
4201
+ if (read.kind === "rejected")
4202
+ return "repair";
4203
+ if (read.kind === "failed" && (0, stateStore_1.readCollectorState)((0, stateStore_1.defaultStateFilePath)(toolInstallationId))?.lastOutcome === "auth_failed") {
4204
+ console.log(`
4205
+ Couldn't check the saved token (${read.reason}), and the last send was refused.`);
4206
+ console.log(" Keeping it for now. Run setup again once the server is reachable.");
4207
+ }
4208
+ return "keep";
4209
+ }
3065
4210
  async function pollForToken2(apiBaseUrl, pairingSessionId, code, expiresAt) {
3066
4211
  const deadline = Math.min(Date.parse(expiresAt) || Date.now() + 3e5, Date.now() + 3e5);
3067
4212
  let announced = false;
@@ -3090,19 +4235,19 @@ Pairing ${status.status}. Run setup again.`);
3090
4235
  if (dryRun)
3091
4236
  return target;
3092
4237
  const source = process.argv[1];
3093
- fs3.mkdirSync(path3.dirname(target), { recursive: true });
3094
- if (path3.resolve(source) !== path3.resolve(target)) {
3095
- fs3.copyFileSync(source, target);
4238
+ fs5.mkdirSync(path4.dirname(target), { recursive: true });
4239
+ if (path4.resolve(source) !== path4.resolve(target)) {
4240
+ fs5.copyFileSync(source, target);
3096
4241
  }
3097
4242
  if (process.platform !== "win32")
3098
- fs3.chmodSync(target, 493);
4243
+ fs5.chmodSync(target, 493);
3099
4244
  return target;
3100
4245
  }
3101
4246
  function writeHookSettings(settingsFile, binary, spec, dryRun) {
3102
4247
  let settings = { ...spec.settings.scaffold ?? {} };
3103
- const exists = fs3.existsSync(settingsFile);
4248
+ const exists = fs5.existsSync(settingsFile);
3104
4249
  if (exists) {
3105
- const raw = fs3.readFileSync(settingsFile, "utf8").trim();
4250
+ const raw = fs5.readFileSync(settingsFile, "utf8").trim();
3106
4251
  if (raw) {
3107
4252
  try {
3108
4253
  settings = JSON.parse(raw);
@@ -3113,7 +4258,7 @@ ${settingsFile} is not valid JSON. Fix or move it, then run setup again.`);
3113
4258
  }
3114
4259
  }
3115
4260
  }
3116
- const command = hookCommand2(binary);
4261
+ const command = hookCommand2(binary, spec);
3117
4262
  const hooks = { ...settings.hooks ?? {} };
3118
4263
  for (const event of spec.hookEvents) {
3119
4264
  const kept = (hooks[event] ?? []).filter((entry) => !isOurs2(entry, spec));
@@ -3122,7 +4267,7 @@ ${settingsFile} is not valid JSON. Fix or move it, then run setup again.`);
3122
4267
  const updated = { ...settings, hooks };
3123
4268
  const serialised = `${JSON.stringify(updated, null, 2)}
3124
4269
  `;
3125
- if (exists && fs3.readFileSync(settingsFile, "utf8") === serialised)
4270
+ if (exists && fs5.readFileSync(settingsFile, "utf8") === serialised)
3126
4271
  return false;
3127
4272
  if (dryRun) {
3128
4273
  console.log(`
@@ -3131,13 +4276,25 @@ ${serialised}`);
3131
4276
  return true;
3132
4277
  }
3133
4278
  if (exists)
3134
- fs3.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
3135
- fs3.mkdirSync(path3.dirname(settingsFile), { recursive: true });
3136
- fs3.writeFileSync(settingsFile, serialised, "utf8");
4279
+ fs5.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
4280
+ fs5.mkdirSync(path4.dirname(settingsFile), { recursive: true });
4281
+ fs5.writeFileSync(settingsFile, serialised, "utf8");
3137
4282
  return true;
3138
4283
  }
3139
- function hookCommand2(binary) {
3140
- return `"${process.execPath}" "${binary}"`;
4284
+ function hookCommand2(binary, spec) {
4285
+ return `"${process.execPath}" "${binary}"${(0, hookSet_1.hookSetArgument)(spec.hookSet)}`;
4286
+ }
4287
+ function registeredHookSets(settings, spec) {
4288
+ const sets = /* @__PURE__ */ new Map();
4289
+ for (const [event, entries] of Object.entries(settings.hooks ?? {})) {
4290
+ for (const entry of entries ?? []) {
4291
+ if (!isOurs2(entry, spec))
4292
+ continue;
4293
+ const set = (0, hookSet_1.hookSetOfCommand)(spec.settings.commandOf(entry));
4294
+ sets.set(event, Math.min(set, sets.get(event) ?? set));
4295
+ }
4296
+ }
4297
+ return sets;
3141
4298
  }
3142
4299
  function isOurs2(entry, spec) {
3143
4300
  const command = spec.settings.commandOf(entry);
@@ -3159,12 +4316,12 @@ ${serialised}`);
3159
4316
  }
3160
4317
  function readSettings(settingsFile) {
3161
4318
  try {
3162
- return JSON.parse(fs3.readFileSync(settingsFile, "utf8"));
4319
+ return JSON.parse(fs5.readFileSync(settingsFile, "utf8"));
3163
4320
  } catch {
3164
4321
  return {};
3165
4322
  }
3166
4323
  }
3167
- function printStatus2(options, spec) {
4324
+ async function printStatus2(options, spec) {
3168
4325
  const credentials = (0, credentials_1.readHostCredentials)(spec.host);
3169
4326
  const settingsFile = spec.settings.settingsPath(options.scope, options.projectDir);
3170
4327
  const binary = cliAgentHookBinPath(spec.binaryName);
@@ -3172,25 +4329,46 @@ ${serialised}`);
3172
4329
  const settings = readSettings(settingsFile);
3173
4330
  const registered = spec.hookEvents.filter((event) => (settings.hooks?.[event] ?? []).some((entry) => isOurs2(entry, spec))).length;
3174
4331
  const stale = findStaleHookCommands2(settings, binary, spec);
4332
+ const localOnly = (0, credentials_1.isLocalOnlyHostInstall)(spec.host, (id) => (0, tokenStore_1.readTokenFile)((0, tokenStore_1.defaultTokenFilePath)(id)) !== void 0);
4333
+ console.log(`version ${(0, collectorVersion_1.describeCollectorVersion)()}`);
3175
4334
  console.log(`api base url ${credentials?.apiBaseUrl ?? "\u2014 not configured"}`);
3176
- console.log(`pairing ${credentials?.toolInstallationId ?? "\u2014 not paired"}`);
3177
- console.log(`token ${tokenFile && (0, tokenStore_1.readTokenFile)(tokenFile) ? "present" : "\u2014 missing"}`);
3178
- console.log(`hook binary ${fs3.existsSync(binary) ? binary : "\u2014 not installed"}`);
4335
+ console.log(`pairing ${credentials?.toolInstallationId ?? "\u2014 not paired"}${localOnly ? " (installed, not paired \u2014 local features active, telemetry inactive)" : ""}`);
4336
+ console.log(`token ${localOnly ? "\u2014 none needed until this install is paired" : tokenFile && (0, tokenStore_1.readTokenFile)(tokenFile) ? "present" : "\u2014 missing"}`);
4337
+ console.log(`hook binary ${fs5.existsSync(binary) ? binary : "\u2014 not installed"}`);
3179
4338
  console.log(`hooks ${registered}/${spec.hookEvents.length} registered in ${settingsFile}`);
4339
+ if (spec.hookSet !== void 0 && registered > 0) {
4340
+ const sets = [...registeredHookSets(settings, spec).values()];
4341
+ const oldest = Math.min(...sets);
4342
+ console.log(oldest < spec.hookSet ? `hook set ${oldest}, this version registers ${spec.hookSet}. Upgrade: npx ${spec.packageName} setup${options.scope === "user" ? " --scope user" : ""}` : `hook set ${spec.hookSet} (current)`);
4343
+ }
3180
4344
  if (stale.length) {
3181
4345
  console.log(`stale hooks ${stale.length} not pointing at the installed binary \u2014 each one fails silently per event:`);
3182
4346
  for (const command of stale)
3183
4347
  console.log(` ${command}`);
3184
4348
  console.log(` Remove them from ${settingsFile} by hand; setup cannot tell them from a hook you wrote.`);
3185
4349
  }
3186
- const healthy = credentials?.toolInstallationId && registered === spec.hookEvents.length && fs3.existsSync(binary) && !stale.length;
4350
+ const tokenValue = localOnly ? void 0 : (tokenFile ? (0, tokenStore_1.readTokenFile)(tokenFile) : void 0) ?? (process.env.ASCENDA_EVENT_WRITE_TOKEN?.trim() || void 0);
4351
+ const apiBaseUrl = (process.env.ASCENDA_API_BASE_URL ?? credentials?.apiBaseUrl ?? hookAdapter_1.DEFAULT_API_BASE_URL).replace(/\/$/, "");
4352
+ const [initiativeLines, notices] = await Promise.all([
4353
+ (0, initiatives_1.initiativesStatusLines)({ apiBaseUrl, eventWriteToken: tokenValue, pairCommand: `npx ${spec.packageName} setup` }),
4354
+ (0, studyNotices_1.studyNoticeStatus)({ apiBaseUrl, eventWriteToken: tokenValue, commandPrefix: `npx ${spec.packageName}` })
4355
+ ]);
4356
+ console.log("");
4357
+ for (const line of initiativeLines)
4358
+ console.log(line);
4359
+ for (const line of notices.lines)
4360
+ console.log(line);
4361
+ if (process.stdout.isTTY)
4362
+ await notices.markShown();
4363
+ const paired = localOnly || credentials?.toolInstallationId !== void 0;
4364
+ const healthy = paired && registered === spec.hookEvents.length && fs5.existsSync(binary) && !stale.length;
3187
4365
  return healthy ? 0 : 1;
3188
4366
  }
3189
4367
  function uninstall2(options, spec) {
3190
4368
  const settingsFile = spec.settings.settingsPath(options.scope, options.projectDir);
3191
- if (fs3.existsSync(settingsFile)) {
4369
+ if (fs5.existsSync(settingsFile)) {
3192
4370
  try {
3193
- const settings = JSON.parse(fs3.readFileSync(settingsFile, "utf8"));
4371
+ const settings = JSON.parse(fs5.readFileSync(settingsFile, "utf8"));
3194
4372
  const hooks = { ...settings.hooks ?? {} };
3195
4373
  for (const event of Object.keys(hooks)) {
3196
4374
  const kept = hooks[event].filter((entry) => !isOurs2(entry, spec));
@@ -3202,8 +4380,8 @@ ${serialised}`);
3202
4380
  const updated = { ...settings, hooks };
3203
4381
  if (!Object.keys(hooks).length)
3204
4382
  delete updated.hooks;
3205
- fs3.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
3206
- fs3.writeFileSync(settingsFile, `${JSON.stringify(updated, null, 2)}
4383
+ fs5.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
4384
+ fs5.writeFileSync(settingsFile, `${JSON.stringify(updated, null, 2)}
3207
4385
  `, "utf8");
3208
4386
  console.log(`hooks removed from ${settingsFile}`);
3209
4387
  } catch {
@@ -3212,15 +4390,15 @@ ${serialised}`);
3212
4390
  }
3213
4391
  }
3214
4392
  const binary = cliAgentHookBinPath(spec.binaryName);
3215
- if (fs3.existsSync(binary)) {
3216
- fs3.rmSync(binary);
4393
+ if (fs5.existsSync(binary)) {
4394
+ fs5.rmSync(binary);
3217
4395
  console.log(`removed ${binary}`);
3218
4396
  }
3219
4397
  if ((0, credentials_1.readHostCredentials)(spec.host)) {
3220
4398
  (0, credentials_1.removeHostCredentials)(spec.host);
3221
4399
  console.log(`removed tools.${spec.host} from ${(0, credentials_1.credentialsFilePath)()}`);
3222
4400
  }
3223
- console.log(`tokens left in ${path3.join((0, tokenStore_1.ascendaHome)(), "tokens")} \u2014 revoke in the Ascenda app to invalidate them`);
4401
+ console.log(`tokens left in ${path4.join((0, tokenStore_1.ascendaHome)(), "tokens")} \u2014 revoke in the Ascenda app to invalidate them`);
3224
4402
  return 0;
3225
4403
  }
3226
4404
  }
@@ -3270,12 +4448,12 @@ var require_turnState = __commonJS({
3270
4448
  Object.defineProperty(exports, "__esModule", { value: true });
3271
4449
  exports.recordTurnStart = recordTurnStart;
3272
4450
  exports.consumeTurnDurationMs = consumeTurnDurationMs;
3273
- var fs3 = __importStar(__require("fs"));
3274
- var path3 = __importStar(__require("path"));
4451
+ var fs5 = __importStar(__require("fs"));
4452
+ var path4 = __importStar(__require("path"));
3275
4453
  var tokenStore_1 = require_tokenStore();
3276
- var stateDir = () => process.env.ASCENDA_STATE_DIR ?? path3.join((0, tokenStore_1.ascendaHome)(), "state");
4454
+ var stateDir = () => process.env.ASCENDA_STATE_DIR ?? path4.join((0, tokenStore_1.ascendaHome)(), "state");
3277
4455
  function turnFile(agent, sessionId) {
3278
- return path3.join(stateDir(), `${sanitize(agent)}-turn-${sanitize(sessionId)}`);
4456
+ return path4.join(stateDir(), `${sanitize(agent)}-turn-${sanitize(sessionId)}`);
3279
4457
  }
3280
4458
  function sanitize(value) {
3281
4459
  return value.replace(/[^a-zA-Z0-9._-]/g, "_");
@@ -3284,8 +4462,8 @@ var require_turnState = __commonJS({
3284
4462
  if (!sessionId)
3285
4463
  return;
3286
4464
  try {
3287
- fs3.mkdirSync(stateDir(), { recursive: true });
3288
- fs3.writeFileSync(turnFile(agent, sessionId), String(now), { encoding: "utf8", mode: 384 });
4465
+ fs5.mkdirSync(stateDir(), { recursive: true });
4466
+ fs5.writeFileSync(turnFile(agent, sessionId), String(now), { encoding: "utf8", mode: 384 });
3289
4467
  } catch {
3290
4468
  }
3291
4469
  }
@@ -3294,8 +4472,8 @@ var require_turnState = __commonJS({
3294
4472
  return void 0;
3295
4473
  const file = turnFile(agent, sessionId);
3296
4474
  try {
3297
- const started = Number(fs3.readFileSync(file, "utf8").trim());
3298
- fs3.rmSync(file, { force: true });
4475
+ const started = Number(fs5.readFileSync(file, "utf8").trim());
4476
+ fs5.rmSync(file, { force: true });
3299
4477
  if (!Number.isFinite(started) || started <= 0 || started > now)
3300
4478
  return void 0;
3301
4479
  return now - started;
@@ -3348,26 +4526,29 @@ var require_liveBus = __commonJS({
3348
4526
  };
3349
4527
  }();
3350
4528
  Object.defineProperty(exports, "__esModule", { value: true });
4529
+ exports.LIVE_BUS_BACKGROUND_TRUST_MS = void 0;
3351
4530
  exports.liveBusSocketCandidates = liveBusSocketCandidates;
3352
4531
  exports.liveBusSocketPath = liveBusSocketPath;
3353
4532
  exports.bucketPromptSize = bucketPromptSize2;
3354
4533
  exports.emitLiveSignal = emitLiveSignal2;
3355
- var fs3 = __importStar(__require("fs"));
4534
+ var fs5 = __importStar(__require("fs"));
3356
4535
  var net = __importStar(__require("net"));
3357
- var os2 = __importStar(__require("os"));
3358
- var path3 = __importStar(__require("path"));
4536
+ var os3 = __importStar(__require("os"));
4537
+ var path4 = __importStar(__require("path"));
4538
+ var hookSet_1 = require_hookSet();
3359
4539
  var WRITE_TIMEOUT_MS = 50;
4540
+ exports.LIVE_BUS_BACKGROUND_TRUST_MS = 60 * 60 * 1e3;
3360
4541
  var APP_BUNDLE_ID = "one.ascenda.ascendaMissionControl";
3361
4542
  var SAVER_HOST_BUNDLE_ID = "com.apple.ScreenSaver.Engine.legacyScreenSaver";
3362
4543
  function liveBusSocketCandidates() {
3363
4544
  const override = process.env.ASCENDA_LIVE_BUS_SOCKET;
3364
4545
  if (override)
3365
4546
  return [override];
3366
- const home = os2.homedir();
4547
+ const home = os3.homedir();
3367
4548
  return [
3368
- path3.join(home, ".ascenda", "live.sock"),
3369
- path3.join(home, "Library", "Containers", APP_BUNDLE_ID, "Data", ".ascenda", "live.sock"),
3370
- path3.join(home, "Library", "Containers", SAVER_HOST_BUNDLE_ID, "Data", "l.sock")
4549
+ path4.join(home, ".ascenda", "live.sock"),
4550
+ path4.join(home, "Library", "Containers", APP_BUNDLE_ID, "Data", ".ascenda", "live.sock"),
4551
+ path4.join(home, "Library", "Containers", SAVER_HOST_BUNDLE_ID, "Data", "l.sock")
3371
4552
  ];
3372
4553
  }
3373
4554
  function existingSocketCandidates() {
@@ -3376,7 +4557,7 @@ var require_liveBus = __commonJS({
3376
4557
  return candidates;
3377
4558
  return candidates.filter((candidate) => {
3378
4559
  try {
3379
- return fs3.statSync(candidate).isSocket();
4560
+ return fs5.statSync(candidate).isSocket();
3380
4561
  } catch {
3381
4562
  return false;
3382
4563
  }
@@ -3396,6 +4577,14 @@ var require_liveBus = __commonJS({
3396
4577
  return "xl";
3397
4578
  }
3398
4579
  var NOBODY_LISTENING = /* @__PURE__ */ new Set(["ECONNREFUSED", "ENOENT"]);
4580
+ function onTheWire(signal) {
4581
+ const out = { ...signal };
4582
+ if ("hookSet" in out && !(0, hookSet_1.isHookSet)(out.hookSet))
4583
+ delete out.hookSet;
4584
+ if ("viaPlugin" in out && out.viaPlugin !== true)
4585
+ delete out.viaPlugin;
4586
+ return out;
4587
+ }
3399
4588
  function emitLiveSignal2(signal) {
3400
4589
  return new Promise((resolve2) => {
3401
4590
  const candidates = existingSocketCandidates();
@@ -3456,15 +4645,154 @@ var require_liveBus = __commonJS({
3456
4645
  return;
3457
4646
  connected = true;
3458
4647
  try {
3459
- attempt.write(`${JSON.stringify(signal)}
4648
+ attempt.write(`${JSON.stringify(onTheWire(signal))}
3460
4649
  `, done);
3461
4650
  } catch {
3462
4651
  done();
3463
4652
  }
3464
- });
3465
- };
3466
- tryFrom(0);
3467
- });
4653
+ });
4654
+ };
4655
+ tryFrom(0);
4656
+ });
4657
+ }
4658
+ }
4659
+ });
4660
+
4661
+ // ../packages/tool-kit/out/agentProcess.js
4662
+ var require_agentProcess = __commonJS({
4663
+ "../packages/tool-kit/out/agentProcess.js"(exports) {
4664
+ "use strict";
4665
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
4666
+ if (k2 === void 0) k2 = k;
4667
+ var desc = Object.getOwnPropertyDescriptor(m, k);
4668
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
4669
+ desc = { enumerable: true, get: function() {
4670
+ return m[k];
4671
+ } };
4672
+ }
4673
+ Object.defineProperty(o, k2, desc);
4674
+ } : function(o, m, k, k2) {
4675
+ if (k2 === void 0) k2 = k;
4676
+ o[k2] = m[k];
4677
+ });
4678
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
4679
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
4680
+ } : function(o, v) {
4681
+ o["default"] = v;
4682
+ });
4683
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
4684
+ var ownKeys = function(o) {
4685
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
4686
+ var ar = [];
4687
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
4688
+ return ar;
4689
+ };
4690
+ return ownKeys(o);
4691
+ };
4692
+ return function(mod) {
4693
+ if (mod && mod.__esModule) return mod;
4694
+ var result = {};
4695
+ if (mod != null) {
4696
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
4697
+ }
4698
+ __setModuleDefault(result, mod);
4699
+ return result;
4700
+ };
4701
+ }();
4702
+ Object.defineProperty(exports, "__esModule", { value: true });
4703
+ exports.psArgsLookup = exports.psLookup = exports.AGENT_PROCESS = void 0;
4704
+ exports.scriptMarkerIn = scriptMarkerIn;
4705
+ exports.findAgentProcess = findAgentProcess2;
4706
+ exports.findAgentPid = findAgentPid;
4707
+ exports.livePidFields = livePidFields2;
4708
+ var child_process_1 = __require("child_process");
4709
+ var path4 = __importStar(__require("path"));
4710
+ exports.AGENT_PROCESS = {
4711
+ claude_code: {
4712
+ executable: (command) => path4.basename(command) === "claude" || /\/claude\/versions\/[^/]+$/.test(command) || /\/@anthropic-ai\/claude-code\/bin\/claude\.exe$/.test(command),
4713
+ scriptMarkers: ["@anthropic-ai/claude-code"]
4714
+ },
4715
+ codex: {
4716
+ executable: (command) => /^codex(-(aarch64|x86_64)-apple-darwin)?$/.test(path4.basename(command)),
4717
+ args: (args) => !/\s(app-server|mcp-server)(\s|$)/.test(args)
4718
+ },
4719
+ gemini_cli: {
4720
+ executable: () => false,
4721
+ args: (args) => !/\s--(experimental-)?acp(\s|=|$)/.test(args),
4722
+ scriptMarkers: ["@google/gemini-cli"]
4723
+ }
4724
+ };
4725
+ var SCRIPT_RUNTIME = /^(node|bun|deno)$/;
4726
+ function scriptMarkerIn(args, markers) {
4727
+ return markers.find((marker) => args.includes(`/${marker}/`));
4728
+ }
4729
+ var MAX_DEPTH = 6;
4730
+ var PS_TIMEOUT_MS = 100;
4731
+ function ps(columns, pid) {
4732
+ try {
4733
+ const result = (0, child_process_1.spawnSync)("/bin/ps", ["-o", columns, "-p", String(pid)], {
4734
+ encoding: "utf8",
4735
+ timeout: PS_TIMEOUT_MS
4736
+ });
4737
+ if (result.status !== 0 || typeof result.stdout !== "string")
4738
+ return void 0;
4739
+ const line = result.stdout.trim();
4740
+ return line === "" ? void 0 : line;
4741
+ } catch {
4742
+ return void 0;
4743
+ }
4744
+ }
4745
+ var psLookup = (pid) => {
4746
+ const line = ps("ppid=,comm=", pid);
4747
+ const match = line ? /^(\d+)\s+(.+)$/.exec(line) : null;
4748
+ return match ? { ppid: Number(match[1]), command: match[2] } : void 0;
4749
+ };
4750
+ exports.psLookup = psLookup;
4751
+ var psArgsLookup = (pid) => ps("args=", pid);
4752
+ exports.psArgsLookup = psArgsLookup;
4753
+ function findAgentProcess2(rule, options = {}) {
4754
+ if (!rule)
4755
+ return void 0;
4756
+ if ((options.platform ?? process.platform) !== "darwin")
4757
+ return void 0;
4758
+ const lookup = options.lookup ?? exports.psLookup;
4759
+ const argsLookup = options.argsLookup ?? exports.psArgsLookup;
4760
+ const markers = rule.scriptMarkers ?? [];
4761
+ let pid = options.startPid ?? process.ppid;
4762
+ for (let depth = 0; depth < MAX_DEPTH && pid > 1; depth++) {
4763
+ const info = lookup(pid);
4764
+ if (!info)
4765
+ return void 0;
4766
+ if (pid !== process.pid) {
4767
+ if (rule.executable(info.command)) {
4768
+ return accepts(rule, rule.args ? argsLookup(pid) : "") ? { pid, match: "executable" } : void 0;
4769
+ }
4770
+ if (markers.length > 0 && SCRIPT_RUNTIME.test(path4.basename(info.command))) {
4771
+ const args = argsLookup(pid);
4772
+ const marker = args === void 0 ? void 0 : scriptMarkerIn(args, markers);
4773
+ if (marker !== void 0) {
4774
+ return accepts(rule, args) ? { pid, match: "path", marker } : void 0;
4775
+ }
4776
+ }
4777
+ }
4778
+ pid = info.ppid;
4779
+ }
4780
+ return void 0;
4781
+ }
4782
+ function accepts(rule, args) {
4783
+ if (!rule.args)
4784
+ return true;
4785
+ return args !== void 0 && rule.args(args);
4786
+ }
4787
+ function findAgentPid(rule, options = {}) {
4788
+ return findAgentProcess2(rule, options)?.pid;
4789
+ }
4790
+ function livePidFields2(match) {
4791
+ if (!match)
4792
+ return {};
4793
+ if (match.match === "executable")
4794
+ return { pid: match.pid };
4795
+ return { pid: match.pid, pidMatch: "path", pidMarker: match.marker };
3468
4796
  }
3469
4797
  }
3470
4798
  });
@@ -3474,9 +4802,9 @@ var require_out2 = __commonJS({
3474
4802
  "../packages/tool-kit/out/index.js"(exports) {
3475
4803
  "use strict";
3476
4804
  Object.defineProperty(exports, "__esModule", { value: true });
3477
- 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;
3478
- 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.fixedTimeProvider = exports.systemTimeProvider = 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;
3479
- exports.isRetryableStatus = exports.parseIngestResponse = exports.postToolEventsBatch = exports.postToolEvent = exports.renewToolToken = void 0;
4805
+ exports.FREE_TEXT_KEYS = exports.FAMILY_SENTENCES = exports.ALWAYS_SENT = exports.writeHookSettings = exports.runCliAgentSetup = exports.registeredHookSets = 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.TOKEN_RENEW_LEAD_MS = exports.AscendaSemanticEventError = exports.AscendaEventSender = exports.describeCollectorVersion = exports.UNRELEASED_COLLECTOR_VERSION = exports.COLLECTOR_VERSION = 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;
4806
+ exports.recordWorkContextAlias = exports.recordWorkContext = exports.readBranchName = exports.normalizeBranchName = exports.deriveBranchHashForCwd = exports.deriveBranchHash = exports.deriveWorkContext = exports.hashWithMachineSalt = exports.readOrCreateMachineSalt = exports.machineSaltFilePath = exports.fixedTimeProvider = exports.systemTimeProvider = 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.tokenExpiryFilePath = exports.readTokenFile = exports.readTokenExpiry = exports.persistEventWriteToken = exports.listPersistedToolInstallationIds = exports.defaultTokenFilePath = exports.ascendaHome = exports.EVENT_TOKEN_TTL_MS = exports.recordTurnStart = exports.consumeTurnDurationMs = exports.writeTopLevelCredentials = exports.writeMachineCredentials = exports.writeHostCredentials = exports.removeHostCredentials = exports.readMachineCredentials = exports.readHostCredentials = exports.isLocalOnlyHostInstall = exports.credentialsFilePath = exports.renderSetupDisclosure = exports.REFUSALS = void 0;
4807
+ exports.runStudyJoin = exports.studyNoticeStatus = exports.runStudyObjection = exports.renderStudyNotices = exports.NOTICED_PURPOSES = exports.renderInitiatives = exports.initiativesStatusLines = exports.INITIATIVE_COPY = exports.startStudyJoin = exports.setStudyObjection = exports.markStudyNoticeShown = exports.readStudyNotices = exports.readInitiatives = exports.isRetryableStatus = exports.parseIngestResponse = exports.postToolEventsBatch = exports.postToolEvent = exports.renewToolToken = exports.getStudyJoinStatus = exports.getPairingStatus = exports.createPairingSession = exports.AscendaApiError = exports.scriptMarkerIn = exports.psLookup = exports.psArgsLookup = exports.livePidFields = exports.findAgentProcess = exports.findAgentPid = exports.AGENT_PROCESS = exports.readViaPlugin = exports.readHookSet = exports.isHookSet = exports.hookSetOfCommand = exports.hookSetChanges = exports.hookSetArgument = exports.describeHookSetChanges = exports.UNVERSIONED_HOOK_SET = exports.HOOK_SET_FLAG = exports.LIVE_BUS_BACKGROUND_TRUST_MS = exports.liveBusSocketCandidates = exports.liveBusSocketPath = exports.bucketPromptSize = exports.emitLiveSignal = exports.recordForgeProjectAlias = exports.forgeFullNameFromConfig = exports.readForgeFullName = exports.parseForgeFullName = exports.forgeProjectHash = exports.workContextRegistryFilePath = exports.readWorkContextRegistry = void 0;
3480
4808
  var commandClassifier_1 = require_commandClassifier();
3481
4809
  Object.defineProperty(exports, "classifyCommand", { enumerable: true, get: function() {
3482
4810
  return commandClassifier_1.classifyCommand;
@@ -3557,6 +4885,16 @@ var require_out2 = __commonJS({
3557
4885
  Object.defineProperty(exports, "mintIdempotencyKey", { enumerable: true, get: function() {
3558
4886
  return payload_1.mintIdempotencyKey;
3559
4887
  } });
4888
+ var collectorVersion_1 = require_collectorVersion();
4889
+ Object.defineProperty(exports, "COLLECTOR_VERSION", { enumerable: true, get: function() {
4890
+ return collectorVersion_1.COLLECTOR_VERSION;
4891
+ } });
4892
+ Object.defineProperty(exports, "UNRELEASED_COLLECTOR_VERSION", { enumerable: true, get: function() {
4893
+ return collectorVersion_1.UNRELEASED_COLLECTOR_VERSION;
4894
+ } });
4895
+ Object.defineProperty(exports, "describeCollectorVersion", { enumerable: true, get: function() {
4896
+ return collectorVersion_1.describeCollectorVersion;
4897
+ } });
3560
4898
  var eventSender_1 = require_eventSender();
3561
4899
  Object.defineProperty(exports, "AscendaEventSender", { enumerable: true, get: function() {
3562
4900
  return eventSender_1.AscendaEventSender;
@@ -3564,6 +4902,9 @@ var require_out2 = __commonJS({
3564
4902
  Object.defineProperty(exports, "AscendaSemanticEventError", { enumerable: true, get: function() {
3565
4903
  return eventSender_1.AscendaSemanticEventError;
3566
4904
  } });
4905
+ Object.defineProperty(exports, "TOKEN_RENEW_LEAD_MS", { enumerable: true, get: function() {
4906
+ return eventSender_1.TOKEN_RENEW_LEAD_MS;
4907
+ } });
3567
4908
  Object.defineProperty(exports, "buildEventPayload", { enumerable: true, get: function() {
3568
4909
  return eventSender_1.buildEventPayload;
3569
4910
  } });
@@ -3609,16 +4950,38 @@ var require_out2 = __commonJS({
3609
4950
  Object.defineProperty(exports, "isCliAgentManagementCommand", { enumerable: true, get: function() {
3610
4951
  return cliAgentSetup_1.isCliAgentManagementCommand;
3611
4952
  } });
4953
+ Object.defineProperty(exports, "registeredHookSets", { enumerable: true, get: function() {
4954
+ return cliAgentSetup_1.registeredHookSets;
4955
+ } });
3612
4956
  Object.defineProperty(exports, "runCliAgentSetup", { enumerable: true, get: function() {
3613
4957
  return cliAgentSetup_1.runCliAgentSetup;
3614
4958
  } });
3615
4959
  Object.defineProperty(exports, "writeHookSettings", { enumerable: true, get: function() {
3616
4960
  return cliAgentSetup_1.writeHookSettings;
3617
4961
  } });
4962
+ var setupDisclosure_1 = require_setupDisclosure();
4963
+ Object.defineProperty(exports, "ALWAYS_SENT", { enumerable: true, get: function() {
4964
+ return setupDisclosure_1.ALWAYS_SENT;
4965
+ } });
4966
+ Object.defineProperty(exports, "FAMILY_SENTENCES", { enumerable: true, get: function() {
4967
+ return setupDisclosure_1.FAMILY_SENTENCES;
4968
+ } });
4969
+ Object.defineProperty(exports, "FREE_TEXT_KEYS", { enumerable: true, get: function() {
4970
+ return setupDisclosure_1.FREE_TEXT_KEYS;
4971
+ } });
4972
+ Object.defineProperty(exports, "REFUSALS", { enumerable: true, get: function() {
4973
+ return setupDisclosure_1.REFUSALS;
4974
+ } });
4975
+ Object.defineProperty(exports, "renderSetupDisclosure", { enumerable: true, get: function() {
4976
+ return setupDisclosure_1.renderSetupDisclosure;
4977
+ } });
3618
4978
  var credentials_1 = require_credentials();
3619
4979
  Object.defineProperty(exports, "credentialsFilePath", { enumerable: true, get: function() {
3620
4980
  return credentials_1.credentialsFilePath;
3621
4981
  } });
4982
+ Object.defineProperty(exports, "isLocalOnlyHostInstall", { enumerable: true, get: function() {
4983
+ return credentials_1.isLocalOnlyHostInstall;
4984
+ } });
3622
4985
  Object.defineProperty(exports, "readHostCredentials", { enumerable: true, get: function() {
3623
4986
  return credentials_1.readHostCredentials;
3624
4987
  } });
@@ -3645,6 +5008,9 @@ var require_out2 = __commonJS({
3645
5008
  return turnState_1.recordTurnStart;
3646
5009
  } });
3647
5010
  var tokenStore_1 = require_tokenStore();
5011
+ Object.defineProperty(exports, "EVENT_TOKEN_TTL_MS", { enumerable: true, get: function() {
5012
+ return tokenStore_1.EVENT_TOKEN_TTL_MS;
5013
+ } });
3648
5014
  Object.defineProperty(exports, "ascendaHome", { enumerable: true, get: function() {
3649
5015
  return tokenStore_1.ascendaHome;
3650
5016
  } });
@@ -3657,9 +5023,15 @@ var require_out2 = __commonJS({
3657
5023
  Object.defineProperty(exports, "persistEventWriteToken", { enumerable: true, get: function() {
3658
5024
  return tokenStore_1.persistEventWriteToken;
3659
5025
  } });
5026
+ Object.defineProperty(exports, "readTokenExpiry", { enumerable: true, get: function() {
5027
+ return tokenStore_1.readTokenExpiry;
5028
+ } });
3660
5029
  Object.defineProperty(exports, "readTokenFile", { enumerable: true, get: function() {
3661
5030
  return tokenStore_1.readTokenFile;
3662
5031
  } });
5032
+ Object.defineProperty(exports, "tokenExpiryFilePath", { enumerable: true, get: function() {
5033
+ return tokenStore_1.tokenExpiryFilePath;
5034
+ } });
3663
5035
  var stateStore_1 = require_stateStore();
3664
5036
  Object.defineProperty(exports, "defaultStateFilePath", { enumerable: true, get: function() {
3665
5037
  return stateStore_1.defaultStateFilePath;
@@ -3791,6 +5163,59 @@ var require_out2 = __commonJS({
3791
5163
  Object.defineProperty(exports, "liveBusSocketCandidates", { enumerable: true, get: function() {
3792
5164
  return liveBus_1.liveBusSocketCandidates;
3793
5165
  } });
5166
+ Object.defineProperty(exports, "LIVE_BUS_BACKGROUND_TRUST_MS", { enumerable: true, get: function() {
5167
+ return liveBus_1.LIVE_BUS_BACKGROUND_TRUST_MS;
5168
+ } });
5169
+ var hookSet_1 = require_hookSet();
5170
+ Object.defineProperty(exports, "HOOK_SET_FLAG", { enumerable: true, get: function() {
5171
+ return hookSet_1.HOOK_SET_FLAG;
5172
+ } });
5173
+ Object.defineProperty(exports, "UNVERSIONED_HOOK_SET", { enumerable: true, get: function() {
5174
+ return hookSet_1.UNVERSIONED_HOOK_SET;
5175
+ } });
5176
+ Object.defineProperty(exports, "describeHookSetChanges", { enumerable: true, get: function() {
5177
+ return hookSet_1.describeHookSetChanges;
5178
+ } });
5179
+ Object.defineProperty(exports, "hookSetArgument", { enumerable: true, get: function() {
5180
+ return hookSet_1.hookSetArgument;
5181
+ } });
5182
+ Object.defineProperty(exports, "hookSetChanges", { enumerable: true, get: function() {
5183
+ return hookSet_1.hookSetChanges;
5184
+ } });
5185
+ Object.defineProperty(exports, "hookSetOfCommand", { enumerable: true, get: function() {
5186
+ return hookSet_1.hookSetOfCommand;
5187
+ } });
5188
+ Object.defineProperty(exports, "isHookSet", { enumerable: true, get: function() {
5189
+ return hookSet_1.isHookSet;
5190
+ } });
5191
+ Object.defineProperty(exports, "readHookSet", { enumerable: true, get: function() {
5192
+ return hookSet_1.readHookSet;
5193
+ } });
5194
+ Object.defineProperty(exports, "readViaPlugin", { enumerable: true, get: function() {
5195
+ return hookSet_1.readViaPlugin;
5196
+ } });
5197
+ var agentProcess_1 = require_agentProcess();
5198
+ Object.defineProperty(exports, "AGENT_PROCESS", { enumerable: true, get: function() {
5199
+ return agentProcess_1.AGENT_PROCESS;
5200
+ } });
5201
+ Object.defineProperty(exports, "findAgentPid", { enumerable: true, get: function() {
5202
+ return agentProcess_1.findAgentPid;
5203
+ } });
5204
+ Object.defineProperty(exports, "findAgentProcess", { enumerable: true, get: function() {
5205
+ return agentProcess_1.findAgentProcess;
5206
+ } });
5207
+ Object.defineProperty(exports, "livePidFields", { enumerable: true, get: function() {
5208
+ return agentProcess_1.livePidFields;
5209
+ } });
5210
+ Object.defineProperty(exports, "psArgsLookup", { enumerable: true, get: function() {
5211
+ return agentProcess_1.psArgsLookup;
5212
+ } });
5213
+ Object.defineProperty(exports, "psLookup", { enumerable: true, get: function() {
5214
+ return agentProcess_1.psLookup;
5215
+ } });
5216
+ Object.defineProperty(exports, "scriptMarkerIn", { enumerable: true, get: function() {
5217
+ return agentProcess_1.scriptMarkerIn;
5218
+ } });
3794
5219
  var http_1 = require_http();
3795
5220
  Object.defineProperty(exports, "AscendaApiError", { enumerable: true, get: function() {
3796
5221
  return http_1.AscendaApiError;
@@ -3801,6 +5226,9 @@ var require_out2 = __commonJS({
3801
5226
  Object.defineProperty(exports, "getPairingStatus", { enumerable: true, get: function() {
3802
5227
  return http_1.getPairingStatus;
3803
5228
  } });
5229
+ Object.defineProperty(exports, "getStudyJoinStatus", { enumerable: true, get: function() {
5230
+ return http_1.getStudyJoinStatus;
5231
+ } });
3804
5232
  Object.defineProperty(exports, "renewToolToken", { enumerable: true, get: function() {
3805
5233
  return http_1.renewToolToken;
3806
5234
  } });
@@ -3816,29 +5244,48 @@ var require_out2 = __commonJS({
3816
5244
  Object.defineProperty(exports, "isRetryableStatus", { enumerable: true, get: function() {
3817
5245
  return http_1.isRetryableStatus;
3818
5246
  } });
3819
- }
3820
- });
3821
-
3822
- // src/paths.ts
3823
- import * as path from "path";
3824
- function hookBinPath() {
3825
- return path.join((0, import_tool_kit3.ascendaHome)(), "bin", "ascenda-claude-hook");
3826
- }
3827
- function readCredentials() {
3828
- const credentials = (0, import_tool_kit3.readMachineCredentials)();
3829
- if (!credentials) return void 0;
3830
- const { tools: _tools, ...topLevel } = credentials;
3831
- return topLevel;
3832
- }
3833
- function writeCredentials(credentials) {
3834
- (0, import_tool_kit3.writeTopLevelCredentials)(credentials);
3835
- }
3836
- var import_tool_kit3, import_tool_kit4;
3837
- var init_paths = __esm({
3838
- "src/paths.ts"() {
3839
- "use strict";
3840
- import_tool_kit3 = __toESM(require_out2(), 1);
3841
- import_tool_kit4 = __toESM(require_out2(), 1);
5247
+ Object.defineProperty(exports, "readInitiatives", { enumerable: true, get: function() {
5248
+ return http_1.readInitiatives;
5249
+ } });
5250
+ Object.defineProperty(exports, "readStudyNotices", { enumerable: true, get: function() {
5251
+ return http_1.readStudyNotices;
5252
+ } });
5253
+ Object.defineProperty(exports, "markStudyNoticeShown", { enumerable: true, get: function() {
5254
+ return http_1.markStudyNoticeShown;
5255
+ } });
5256
+ Object.defineProperty(exports, "setStudyObjection", { enumerable: true, get: function() {
5257
+ return http_1.setStudyObjection;
5258
+ } });
5259
+ Object.defineProperty(exports, "startStudyJoin", { enumerable: true, get: function() {
5260
+ return http_1.startStudyJoin;
5261
+ } });
5262
+ var initiatives_1 = require_initiatives();
5263
+ Object.defineProperty(exports, "INITIATIVE_COPY", { enumerable: true, get: function() {
5264
+ return initiatives_1.INITIATIVE_COPY;
5265
+ } });
5266
+ Object.defineProperty(exports, "initiativesStatusLines", { enumerable: true, get: function() {
5267
+ return initiatives_1.initiativesStatusLines;
5268
+ } });
5269
+ Object.defineProperty(exports, "renderInitiatives", { enumerable: true, get: function() {
5270
+ return initiatives_1.renderInitiatives;
5271
+ } });
5272
+ var studyNotices_1 = require_studyNotices();
5273
+ Object.defineProperty(exports, "NOTICED_PURPOSES", { enumerable: true, get: function() {
5274
+ return studyNotices_1.NOTICED_PURPOSES;
5275
+ } });
5276
+ Object.defineProperty(exports, "renderStudyNotices", { enumerable: true, get: function() {
5277
+ return studyNotices_1.renderStudyNotices;
5278
+ } });
5279
+ Object.defineProperty(exports, "runStudyObjection", { enumerable: true, get: function() {
5280
+ return studyNotices_1.runStudyObjection;
5281
+ } });
5282
+ Object.defineProperty(exports, "studyNoticeStatus", { enumerable: true, get: function() {
5283
+ return studyNotices_1.studyNoticeStatus;
5284
+ } });
5285
+ var studyJoin_1 = require_studyJoin();
5286
+ Object.defineProperty(exports, "runStudyJoin", { enumerable: true, get: function() {
5287
+ return studyJoin_1.runStudyJoin;
5288
+ } });
3842
5289
  }
3843
5290
  });
3844
5291
 
@@ -3846,6 +5293,10 @@ var init_paths = __esm({
3846
5293
  function isClaudeHookEventName(value) {
3847
5294
  return CLAUDE_HOOK_EVENT_NAMES.includes(value);
3848
5295
  }
5296
+ function claudeRuntime(env = process.env) {
5297
+ const flag = env.CLAUDE_CODE_REMOTE?.trim().toLowerCase();
5298
+ return flag === "true" || flag === "1" ? "cloud" : "local";
5299
+ }
3849
5300
  var import_tool_contract, CLAUDE_HOOK_EVENT_NAMES, ASCENDA_TOOL_TYPE, CLAUDE_HOST;
3850
5301
  var init_types = __esm({
3851
5302
  "src/types.ts"() {
@@ -3860,26 +5311,69 @@ var init_types = __esm({
3860
5311
  "PreCompact",
3861
5312
  "PostCompact",
3862
5313
  "Stop",
3863
- "Notification"
5314
+ "StopFailure",
5315
+ "Notification",
5316
+ "SessionEnd",
5317
+ "SubagentStart",
5318
+ "SubagentStop"
3864
5319
  ];
3865
5320
  ASCENDA_TOOL_TYPE = "claude_code";
3866
5321
  CLAUDE_HOST = "claude_code";
3867
5322
  }
3868
5323
  });
3869
5324
 
5325
+ // src/paths.ts
5326
+ import * as fs2 from "fs";
5327
+ import * as path2 from "path";
5328
+ function hookBinPath() {
5329
+ return path2.join((0, import_tool_kit5.ascendaHome)(), "bin", "ascenda-claude-hook");
5330
+ }
5331
+ function readCredentials() {
5332
+ const credentials = (0, import_tool_kit5.readMachineCredentials)();
5333
+ if (!credentials) return void 0;
5334
+ const { tools: _tools, ...topLevel } = credentials;
5335
+ return topLevel;
5336
+ }
5337
+ function writeCredentials(credentials) {
5338
+ (0, import_tool_kit5.writeTopLevelCredentials)(credentials);
5339
+ }
5340
+ function removeCredentials() {
5341
+ const credentials = (0, import_tool_kit5.readMachineCredentials)();
5342
+ if (!credentials) return;
5343
+ if (credentials.tools && Object.keys(credentials.tools).length > 0) {
5344
+ (0, import_tool_kit5.writeMachineCredentials)({ tools: credentials.tools });
5345
+ return;
5346
+ }
5347
+ fs2.rmSync((0, import_tool_kit5.credentialsFilePath)(), { force: true });
5348
+ }
5349
+ var import_tool_kit5, import_tool_kit6;
5350
+ var init_paths = __esm({
5351
+ "src/paths.ts"() {
5352
+ "use strict";
5353
+ import_tool_kit5 = __toESM(require_out2(), 1);
5354
+ import_tool_kit6 = __toESM(require_out2(), 1);
5355
+ }
5356
+ });
5357
+
3870
5358
  // src/config.ts
3871
5359
  function resolveOutboxFilePath(toolInstallationId) {
3872
- return process.env.ASCENDA_OUTBOX_FILE ?? (0, import_tool_kit5.defaultOutboxFilePath)(toolInstallationId);
5360
+ return process.env.ASCENDA_OUTBOX_FILE ?? (0, import_tool_kit7.defaultOutboxFilePath)(toolInstallationId);
3873
5361
  }
3874
5362
  function resolveStateFilePath(toolInstallationId) {
3875
- return process.env.ASCENDA_STATE_FILE ?? (toolInstallationId ? (0, import_tool_kit5.defaultStateFilePath)(toolInstallationId) : (0, import_tool_kit5.unresolvedStateFilePath)(ASCENDA_TOOL_TYPE));
5363
+ return process.env.ASCENDA_STATE_FILE ?? (toolInstallationId ? (0, import_tool_kit7.defaultStateFilePath)(toolInstallationId) : (0, import_tool_kit7.unresolvedStateFilePath)(ASCENDA_TOOL_TYPE));
5364
+ }
5365
+ function localOnlyInstall(credentials = readCredentials()) {
5366
+ if (!credentials?.localOnly) return false;
5367
+ if (envOverride("ASCENDA_EVENT_WRITE_TOKEN")) return false;
5368
+ const tokenFilePath = process.env.ASCENDA_EVENT_WRITE_TOKEN_FILE ?? (credentials.toolInstallationId ? (0, import_tool_kit7.defaultTokenFilePath)(credentials.toolInstallationId) : void 0);
5369
+ return !(tokenFilePath && (0, import_tool_kit7.readTokenFile)(tokenFilePath));
3876
5370
  }
3877
5371
  function resolveToolInstallationId(credentials = readCredentials()) {
3878
5372
  const fromEnv = process.env.ASCENDA_TOOL_INSTALLATION_ID?.trim();
3879
5373
  if (fromEnv) return { toolInstallationId: normalizeToolInstallationId(fromEnv), source: "env" };
3880
5374
  const fromCredentials = credentials?.toolInstallationId?.trim();
3881
5375
  if (fromCredentials) return { toolInstallationId: normalizeToolInstallationId(fromCredentials), source: "credentials" };
3882
- const candidates = (0, import_tool_kit5.listPersistedToolInstallationIds)(ASCENDA_TOOL_TYPE);
5376
+ const candidates = (0, import_tool_kit7.listPersistedToolInstallationIds)(ASCENDA_TOOL_TYPE);
3883
5377
  if (candidates.length === 1) return { toolInstallationId: candidates[0], source: "disk" };
3884
5378
  throw new MissingInstallationIdError(candidates);
3885
5379
  }
@@ -3887,11 +5381,11 @@ function loadConfigFromEnv() {
3887
5381
  const credentials = readCredentials();
3888
5382
  const apiBaseUrl = (process.env.ASCENDA_API_BASE_URL ?? credentials?.apiBaseUrl ?? DEFAULT_API_BASE_URL).replace(/\/$/, "");
3889
5383
  const { toolInstallationId } = resolveToolInstallationId(credentials);
3890
- const tokenFilePath = process.env.ASCENDA_EVENT_WRITE_TOKEN_FILE ?? (0, import_tool_kit5.defaultTokenFilePath)(toolInstallationId);
3891
- const fileToken = (0, import_tool_kit5.readTokenFile)(tokenFilePath);
5384
+ const tokenFilePath = process.env.ASCENDA_EVENT_WRITE_TOKEN_FILE ?? (0, import_tool_kit7.defaultTokenFilePath)(toolInstallationId);
5385
+ const fileToken = (0, import_tool_kit7.readTokenFile)(tokenFilePath);
3892
5386
  const eventWriteToken = fileToken ?? process.env.ASCENDA_EVENT_WRITE_TOKEN;
3893
5387
  if (!eventWriteToken) throw new Error("Missing ASCENDA_EVENT_WRITE_TOKEN (or token file)");
3894
- if (!fileToken) (0, import_tool_kit5.persistEventWriteToken)(tokenFilePath, eventWriteToken);
5388
+ if (!fileToken) (0, import_tool_kit7.persistEventWriteToken)(tokenFilePath, eventWriteToken);
3895
5389
  return {
3896
5390
  apiBaseUrl,
3897
5391
  toolInstallationId,
@@ -3899,6 +5393,11 @@ function loadConfigFromEnv() {
3899
5393
  tokenFilePath,
3900
5394
  stateFilePath: resolveStateFilePath(toolInstallationId),
3901
5395
  outboxFilePath: resolveOutboxFilePath(toolInstallationId),
5396
+ // A hosted session is a fresh container on every start, with its token
5397
+ // supplied by the environment. A rotation there would be written to a
5398
+ // file that dies with the container while revoking the environment's
5399
+ // copy, so there it never rotates.
5400
+ renewToken: claudeRuntime() !== "cloud",
3902
5401
  // Override only. When unset, main() fills it from the hook payload's own
3903
5402
  // `session_id`, exactly as it does the context hashes below — see there.
3904
5403
  //
@@ -3924,11 +5423,11 @@ function normalizeToolInstallationId(value) {
3924
5423
  if (trimmed.startsWith("claude_tool_")) return `${ASCENDA_TOOL_TYPE}:${trimmed.slice("claude_tool_".length)}`;
3925
5424
  return `${ASCENDA_TOOL_TYPE}:${trimmed}`;
3926
5425
  }
3927
- var import_tool_kit5, DEFAULT_API_BASE_URL, MissingInstallationIdError;
5426
+ var import_tool_kit7, DEFAULT_API_BASE_URL, MissingInstallationIdError;
3928
5427
  var init_config = __esm({
3929
5428
  "src/config.ts"() {
3930
5429
  "use strict";
3931
- import_tool_kit5 = __toESM(require_out2(), 1);
5430
+ import_tool_kit7 = __toESM(require_out2(), 1);
3932
5431
  init_paths();
3933
5432
  init_types();
3934
5433
  DEFAULT_API_BASE_URL = "https://api.ascenda.one";
@@ -3949,14 +5448,17 @@ var init_config = __esm({
3949
5448
  // src/setup.ts
3950
5449
  var setup_exports = {};
3951
5450
  __export(setup_exports, {
5451
+ HOOK_SET: () => HOOK_SET,
5452
+ SENDS: () => SENDS,
3952
5453
  findStaleHookCommands: () => findStaleHookCommands,
5454
+ ourHookSets: () => ourHookSets,
3953
5455
  runSetup: () => runSetup,
3954
5456
  writeSettings: () => writeSettings
3955
5457
  });
3956
5458
  import * as crypto from "crypto";
3957
- import * as fs from "fs";
3958
- import * as os from "os";
3959
- import * as path2 from "path";
5459
+ import * as fs3 from "fs";
5460
+ import * as os2 from "os";
5461
+ import * as path3 from "path";
3960
5462
  async function runSetup(argv) {
3961
5463
  let options;
3962
5464
  try {
@@ -3969,28 +5471,58 @@ async function runSetup(argv) {
3969
5471
  console.log(USAGE);
3970
5472
  return 0;
3971
5473
  }
3972
- if (options.action === "status") return printStatus(options);
5474
+ if (options.action === "status") return await printStatus(options);
3973
5475
  if (options.action === "uninstall") return uninstall(options);
3974
5476
  const apiBaseUrl = (options.apiBaseUrl ?? readCredentials()?.apiBaseUrl ?? DEFAULT_API_BASE_URL).replace(/\/$/, "");
3975
5477
  console.log(`Ascenda setup \u2014 ${apiBaseUrl}`);
5478
+ if (!options.pair) console.log("\n Nothing is sent from an install with no pairing. What pairing would start sending:");
5479
+ console.log(`
5480
+ ${(0, import_tool_kit8.renderSetupDisclosure)({ sends: SENDS, displayName: "Claude Code" })}
5481
+ `);
3976
5482
  const identity = await resolveIdentity(apiBaseUrl, options);
3977
- if (!identity) return 1;
3978
- console.log(` pairing ${identity.toolInstallationId}${identity.paired ? " (new)" : " (existing)"}`);
5483
+ const unpaired = identity.pairing === "local-only";
5484
+ console.log(` pairing ${unpaired ? `none \u2014 ${identity.reason}` : `${identity.toolInstallationId}${identity.pairing === "new" ? " (new)" : " (existing)"}`}`);
5485
+ if (unpaired) console.log(` installation ${identity.toolInstallationId} (recorded, so a later pair attaches to it)`);
3979
5486
  const binary = installBinary(options.dryRun);
3980
5487
  console.log(` hook binary ${binary}`);
3981
5488
  if (!options.dryRun) {
3982
- writeCredentials({ apiBaseUrl, toolInstallationId: identity.toolInstallationId, pairedAt: (/* @__PURE__ */ new Date()).toISOString() });
5489
+ const now = (/* @__PURE__ */ new Date()).toISOString();
5490
+ writeCredentials({
5491
+ apiBaseUrl,
5492
+ toolInstallationId: identity.toolInstallationId,
5493
+ // No fabricated `pairedAt` on an install that has no pairing, and no
5494
+ // token file either. The id is the whole record, and it is what `pair`
5495
+ // picks up.
5496
+ ...unpaired ? { localOnly: true, installedAt: now } : { pairedAt: now }
5497
+ });
3983
5498
  }
3984
- console.log(` credentials ${(0, import_tool_kit4.credentialsFilePath)()}`);
5499
+ console.log(` credentials ${(0, import_tool_kit6.credentialsFilePath)()}`);
3985
5500
  const settingsFile = settingsPath(options);
5501
+ const before = ourHookSets(readSettingsFile(settingsFile));
3986
5502
  const written = writeSettings(settingsFile, binary, options.dryRun);
3987
5503
  if (written === null) return 1;
3988
5504
  console.log(` hooks ${settingsFile} (${HOOK_EVENTS.length} events${written ? "" : ", already current"})`);
5505
+ const changes = (0, import_tool_kit8.describeHookSetChanges)((0, import_tool_kit8.hookSetChanges)(before, HOOK_EVENTS), HOOK_SET);
5506
+ if (changes) console.log(` ${changes}`);
5507
+ const otherFile = settingsPath({ ...options, scope: options.scope === "user" ? "project" : "user" });
5508
+ if (otherFile !== settingsFile && ourHookSets(readSettingsFile(otherFile)).size > 0) {
5509
+ console.log(` note ${otherFile} registers these hooks too, so each event runs twice.`);
5510
+ console.log(" Remove the ascenda-claude-hook entries from one of the two files.");
5511
+ }
3989
5512
  if (options.dryRun) {
3990
5513
  console.log("\nDry run \u2014 nothing was written.");
3991
5514
  return 0;
3992
5515
  }
3993
- console.log("\nDone. Restart Claude Code in this project to load the hooks.");
5516
+ if (unpaired) {
5517
+ console.log("\nInstalled, not paired.");
5518
+ console.log(" active the session prompts, and the live signal to a socket on this machine");
5519
+ console.log(` inactive delivery to ${apiBaseUrl}. Nothing is sent, and nothing is queued for later.`);
5520
+ if (identity.hint) console.log(` note ${identity.hint}`);
5521
+ console.log(" pair later npx @ascenda-one/claude-code-hooks pair");
5522
+ console.log("\nRestart Claude Code in this project to load the hooks.");
5523
+ } else {
5524
+ console.log("\nDone. Restart Claude Code in this project to load the hooks.");
5525
+ }
3994
5526
  console.log(`Check anytime: npx @ascenda-one/claude-code-hooks status`);
3995
5527
  return 0;
3996
5528
  }
@@ -3999,6 +5531,7 @@ function parseArgs(argv) {
3999
5531
  scope: "project",
4000
5532
  projectDir: process.env.CLAUDE_PROJECT_DIR ?? process.cwd(),
4001
5533
  dryRun: false,
5534
+ pair: true,
4002
5535
  action: "install"
4003
5536
  };
4004
5537
  for (let i = 0; i < argv.length; i++) {
@@ -4041,7 +5574,15 @@ function parseArgs(argv) {
4041
5574
  break;
4042
5575
  }
4043
5576
  case "--project-dir":
4044
- options.projectDir = path2.resolve(next());
5577
+ options.projectDir = path3.resolve(next());
5578
+ break;
5579
+ case "--no-pair":
5580
+ // `--no-pairing` is the spelling the CLI agents' setup landed under
5581
+ // first, and the one their README still showed for a day. Both parse
5582
+ // everywhere, so a person who read either page gets the install rather
5583
+ // than "unknown argument".
5584
+ case "--no-pairing":
5585
+ options.pair = false;
4045
5586
  break;
4046
5587
  case "--dry-run":
4047
5588
  options.dryRun = true;
@@ -4062,40 +5603,52 @@ async function resolveIdentity(apiBaseUrl, options) {
4062
5603
  const existingId = options.toolInstallationId ?? readCredentials()?.toolInstallationId;
4063
5604
  if (existingId && options.token) {
4064
5605
  if (!options.dryRun) (0, import_tool_kit8.persistEventWriteToken)((0, import_tool_kit8.defaultTokenFilePath)(existingId), options.token);
4065
- return { toolInstallationId: existingId, paired: false };
5606
+ return { toolInstallationId: existingId, pairing: "existing" };
4066
5607
  }
4067
5608
  if (existingId && (0, import_tool_kit8.readTokenFile)((0, import_tool_kit8.defaultTokenFilePath)(existingId))) {
4068
- return { toolInstallationId: existingId, paired: false };
5609
+ return { toolInstallationId: existingId, pairing: "existing" };
5610
+ }
5611
+ const toolInstallationId = existingId ?? (options.dryRun ? `${ASCENDA_TOOL_TYPE}:<minted at run time>` : `${ASCENDA_TOOL_TYPE}:${crypto.randomUUID()}`);
5612
+ if (!options.pair) {
5613
+ return { toolInstallationId, pairing: "local-only", reason: "asked not to pair (--no-pair)" };
4069
5614
  }
4070
5615
  if (options.dryRun) {
4071
- return { toolInstallationId: existingId ?? `${ASCENDA_TOOL_TYPE}:<paired at run time>`, paired: false };
5616
+ return { toolInstallationId, pairing: "existing" };
4072
5617
  }
4073
- const toolInstallationId = existingId ?? `${ASCENDA_TOOL_TYPE}:${crypto.randomUUID()}`;
4074
5618
  let session;
4075
5619
  try {
4076
- session = await (0, import_tool_kit8.createPairingSession)(apiBaseUrl, toolInstallationId, ASCENDA_TOOL_TYPE, `Claude Code on ${os.hostname()}`);
5620
+ session = await (0, import_tool_kit8.createPairingSession)(apiBaseUrl, toolInstallationId, ASCENDA_TOOL_TYPE, `Claude Code on ${os2.hostname()}`);
4077
5621
  } catch (error) {
4078
- console.error(`
4079
- Could not reach ${apiBaseUrl} to pair: ${error instanceof Error ? error.message : String(error)}`);
4080
- console.error("Start the local dev server and use --local, or pass --api-base-url for your backend.");
4081
- return void 0;
5622
+ return {
5623
+ toolInstallationId,
5624
+ pairing: "local-only",
5625
+ reason: `could not reach ${apiBaseUrl} (${error instanceof Error ? error.message : String(error)})`,
5626
+ hint: "for a local dev server use --local, or name your backend with --api-base-url"
5627
+ };
4082
5628
  }
4083
- const token = await pollForToken(apiBaseUrl, session.pairingSessionId, session.code, session.expiresAt);
4084
- if (!token) return void 0;
4085
- (0, import_tool_kit8.persistEventWriteToken)((0, import_tool_kit8.defaultTokenFilePath)(toolInstallationId), token);
4086
- return { toolInstallationId, paired: true };
5629
+ const outcome = await pollForToken(apiBaseUrl, session.pairingSessionId, session.code, session.expiresAt);
5630
+ if ("reason" in outcome) return { toolInstallationId, pairing: "local-only", reason: outcome.reason };
5631
+ (0, import_tool_kit8.persistEventWriteToken)((0, import_tool_kit8.defaultTokenFilePath)(toolInstallationId), outcome.token);
5632
+ return { toolInstallationId, pairing: "new" };
4087
5633
  }
4088
5634
  async function pollForToken(apiBaseUrl, pairingSessionId, code, expiresAt) {
4089
5635
  const deadline = Math.min(Date.parse(expiresAt) || Date.now() + 3e5, Date.now() + 3e5);
4090
5636
  let announced = false;
5637
+ let failures = 0;
4091
5638
  while (Date.now() < deadline) {
4092
- const status = await (0, import_tool_kit8.getPairingStatus)(apiBaseUrl, pairingSessionId);
4093
- if (status.status === "paired" && status.eventWriteToken) return status.eventWriteToken;
4094
- if (status.status === "expired" || status.status === "cancelled") {
4095
- console.error(`
4096
- Pairing ${status.status}. Run setup again.`);
4097
- return void 0;
5639
+ let status;
5640
+ try {
5641
+ status = await (0, import_tool_kit8.getPairingStatus)(apiBaseUrl, pairingSessionId);
5642
+ failures = 0;
5643
+ } catch (error) {
5644
+ if (++failures >= POLL_ERROR_TOLERANCE) {
5645
+ return { reason: `lost contact while waiting (${error instanceof Error ? error.message : String(error)})` };
5646
+ }
5647
+ await new Promise((resolve2) => setTimeout(resolve2, 2e3));
5648
+ continue;
4098
5649
  }
5650
+ if (status.status === "paired" && status.eventWriteToken) return { token: status.eventWriteToken };
5651
+ if (status.status === "expired" || status.status === "cancelled") return { reason: `pairing ${status.status}` };
4099
5652
  if (!announced) {
4100
5653
  console.log(`
4101
5654
  Confirm in the Ascenda app \u2014 code ${code}`);
@@ -4104,28 +5657,27 @@ Pairing ${status.status}. Run setup again.`);
4104
5657
  }
4105
5658
  await new Promise((resolve2) => setTimeout(resolve2, 2e3));
4106
5659
  }
4107
- console.error("\nPairing timed out. Run setup again.");
4108
- return void 0;
5660
+ return { reason: "no confirmation within 5 minutes" };
4109
5661
  }
4110
5662
  function installBinary(dryRun) {
4111
5663
  const target = hookBinPath();
4112
5664
  if (dryRun) return target;
4113
5665
  const source = process.argv[1];
4114
- fs.mkdirSync(path2.dirname(target), { recursive: true });
4115
- if (path2.resolve(source) !== path2.resolve(target)) {
4116
- fs.copyFileSync(source, target);
5666
+ fs3.mkdirSync(path3.dirname(target), { recursive: true });
5667
+ if (path3.resolve(source) !== path3.resolve(target)) {
5668
+ fs3.copyFileSync(source, target);
4117
5669
  }
4118
- if (process.platform !== "win32") fs.chmodSync(target, 493);
5670
+ if (process.platform !== "win32") fs3.chmodSync(target, 493);
4119
5671
  return target;
4120
5672
  }
4121
5673
  function settingsPath(options) {
4122
- return options.scope === "user" ? path2.join(os.homedir(), ".claude", "settings.json") : path2.join(options.projectDir, ".claude", "settings.local.json");
5674
+ return options.scope === "user" ? path3.join(os2.homedir(), ".claude", "settings.json") : path3.join(options.projectDir, ".claude", "settings.local.json");
4123
5675
  }
4124
5676
  function writeSettings(settingsFile, binary, dryRun) {
4125
5677
  let settings = {};
4126
- const exists = fs.existsSync(settingsFile);
5678
+ const exists = fs3.existsSync(settingsFile);
4127
5679
  if (exists) {
4128
- const raw = fs.readFileSync(settingsFile, "utf8").trim();
5680
+ const raw = fs3.readFileSync(settingsFile, "utf8").trim();
4129
5681
  if (raw) {
4130
5682
  try {
4131
5683
  settings = JSON.parse(raw);
@@ -4140,21 +5692,21 @@ ${settingsFile} is not valid JSON. Fix or move it, then run setup again.`);
4140
5692
  const hooks = { ...settings.hooks ?? {} };
4141
5693
  for (const event of HOOK_EVENTS) {
4142
5694
  const kept = (hooks[event] ?? []).filter((group) => !isOurs(group));
4143
- hooks[event] = [...kept, { hooks: [{ type: "command", command: `${command} ${event}`, timeout: HOOK_TIMEOUT_SECONDS }] }];
5695
+ hooks[event] = [...kept, { hooks: [{ type: "command", command: `${command} ${event}${(0, import_tool_kit8.hookSetArgument)(HOOK_SET)}`, timeout: HOOK_TIMEOUT_SECONDS }] }];
4144
5696
  }
4145
5697
  const updated = { ...settings, hooks };
4146
5698
  const serialised = `${JSON.stringify(updated, null, 2)}
4147
5699
  `;
4148
- if (exists && fs.readFileSync(settingsFile, "utf8") === serialised) return false;
5700
+ if (exists && fs3.readFileSync(settingsFile, "utf8") === serialised) return false;
4149
5701
  if (dryRun) {
4150
5702
  console.log(`
4151
5703
  --- ${settingsFile} (dry run) ---
4152
5704
  ${serialised}`);
4153
5705
  return true;
4154
5706
  }
4155
- if (exists) fs.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
4156
- fs.mkdirSync(path2.dirname(settingsFile), { recursive: true });
4157
- fs.writeFileSync(settingsFile, serialised, "utf8");
5707
+ if (exists) fs3.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
5708
+ fs3.mkdirSync(path3.dirname(settingsFile), { recursive: true });
5709
+ fs3.writeFileSync(settingsFile, serialised, "utf8");
4158
5710
  return true;
4159
5711
  }
4160
5712
  function hookCommand(binary) {
@@ -4177,21 +5729,37 @@ function findStaleHookCommands(settings, binary) {
4177
5729
  }
4178
5730
  return [...stale];
4179
5731
  }
4180
- function countRegistered(settingsFile, binary) {
4181
- const settings = (() => {
4182
- try {
4183
- return JSON.parse(fs.readFileSync(settingsFile, "utf8"));
4184
- } catch {
4185
- return {};
5732
+ function readSettingsFile(settingsFile) {
5733
+ try {
5734
+ return JSON.parse(fs3.readFileSync(settingsFile, "utf8"));
5735
+ } catch {
5736
+ return {};
5737
+ }
5738
+ }
5739
+ function ourHookSets(settings) {
5740
+ const sets = /* @__PURE__ */ new Map();
5741
+ for (const [event, groups] of Object.entries(settings.hooks ?? {})) {
5742
+ for (const group of groups ?? []) {
5743
+ if (!isOurs(group)) continue;
5744
+ for (const entry of group.hooks ?? []) {
5745
+ if (typeof entry?.command !== "string") continue;
5746
+ const set = (0, import_tool_kit8.hookSetOfCommand)(entry.command);
5747
+ sets.set(event, Math.min(set, sets.get(event) ?? set));
5748
+ }
4186
5749
  }
4187
- })();
5750
+ }
5751
+ return sets;
5752
+ }
5753
+ function countRegistered(settingsFile, binary) {
5754
+ const settings = readSettingsFile(settingsFile);
4188
5755
  return { settings, registered: HOOK_EVENTS.filter((event) => (settings.hooks?.[event] ?? []).some(isOurs)).length };
4189
5756
  }
4190
- function printStatus(options) {
5757
+ async function printStatus(options) {
4191
5758
  const credentials = readCredentials();
4192
5759
  const settingsFile = settingsPath(options);
4193
5760
  const binary = hookBinPath();
4194
5761
  const tokenFile = credentials?.toolInstallationId ? (0, import_tool_kit8.defaultTokenFilePath)(credentials.toolInstallationId) : void 0;
5762
+ const unpaired = localOnlyInstall(credentials);
4195
5763
  const here = countRegistered(settingsFile, binary);
4196
5764
  const settings = here.settings;
4197
5765
  const registered = here.registered;
@@ -4199,27 +5767,59 @@ function printStatus(options) {
4199
5767
  const otherFile = settingsPath(otherScope);
4200
5768
  const elsewhere = registered === 0 && otherFile !== settingsFile ? countRegistered(otherFile, binary) : void 0;
4201
5769
  const stale = findStaleHookCommands(settings, binary);
5770
+ console.log(`version ${(0, import_tool_kit8.describeCollectorVersion)()}`);
4202
5771
  console.log(`api base url ${credentials?.apiBaseUrl ?? "\u2014 not configured"}`);
4203
- console.log(`pairing ${credentials?.toolInstallationId ?? "\u2014 not paired"}`);
4204
- console.log(`token ${tokenFile && (0, import_tool_kit8.readTokenFile)(tokenFile) ? "present" : "\u2014 missing"}`);
4205
- console.log(`hook binary ${fs.existsSync(binary) ? binary : "\u2014 not installed"}`);
5772
+ console.log(`pairing ${describePairing(credentials, unpaired)}`);
5773
+ const fileToken = Boolean(tokenFile && (0, import_tool_kit8.readTokenFile)(tokenFile));
5774
+ const token = fileToken || Boolean(envOverride("ASCENDA_EVENT_WRITE_TOKEN"));
5775
+ console.log(`token ${fileToken ? "present" : token ? "from ASCENDA_EVENT_WRITE_TOKEN (no file)" : unpaired ? "\u2014 none until this install is paired" : "\u2014 missing"}`);
5776
+ console.log(`delivery ${token ? "active" : unpaired ? "inactive \u2014 nothing is sent, and nothing is queued for later" : "\u2014 no token for this pairing, so nothing can be sent"}`);
5777
+ console.log("local features active \u2014 the session prompts and the live socket signal need no pairing");
5778
+ console.log(`hook binary ${fs3.existsSync(binary) ? binary : "\u2014 not installed"}`);
4206
5779
  console.log(`hooks ${registered}/${HOOK_EVENTS.length} registered in ${settingsFile}`);
4207
5780
  if (elsewhere && elsewhere.registered > 0) {
4208
5781
  console.log(` ${elsewhere.registered}/${HOOK_EVENTS.length} found in ${otherFile} (--scope ${otherScope.scope})`);
4209
5782
  }
5783
+ const where = registered > 0 ? { settings, scope: options.scope } : elsewhere && elsewhere.registered > 0 ? { settings: elsewhere.settings, scope: otherScope.scope } : void 0;
5784
+ if (where) {
5785
+ const oldest = Math.min(...ourHookSets(where.settings).values());
5786
+ console.log(oldest < HOOK_SET ? `hook set ${oldest}, this version registers ${HOOK_SET}. Upgrade: npx @ascenda-one/claude-code-hooks setup${where.scope === "user" ? " --scope user" : ""}` : `hook set ${HOOK_SET} (current)`);
5787
+ }
4210
5788
  if (stale.length) {
4211
5789
  console.log(`stale hooks ${stale.length} not pointing at the installed binary \u2014 each one fails silently per event:`);
4212
5790
  for (const command of stale) console.log(` ${command}`);
4213
5791
  console.log(` Remove them from ${settingsFile} by hand; setup cannot tell them from a hook you wrote.`);
4214
5792
  }
4215
- const healthy = credentials?.toolInstallationId && registered === HOOK_EVENTS.length && fs.existsSync(binary) && !stale.length;
5793
+ const tokenValue = unpaired ? void 0 : (tokenFile ? (0, import_tool_kit8.readTokenFile)(tokenFile) : void 0) ?? envOverride("ASCENDA_EVENT_WRITE_TOKEN") ?? void 0;
5794
+ const apiBaseUrl = (process.env.ASCENDA_API_BASE_URL ?? credentials?.apiBaseUrl ?? DEFAULT_API_BASE_URL).replace(/\/$/, "");
5795
+ const [initiativeLines, notices] = await Promise.all([
5796
+ (0, import_tool_kit8.initiativesStatusLines)({ apiBaseUrl, eventWriteToken: tokenValue, pairCommand: "npx @ascenda-one/claude-code-hooks pair" }),
5797
+ (0, import_tool_kit8.studyNoticeStatus)({ apiBaseUrl, eventWriteToken: tokenValue, commandPrefix: "npx @ascenda-one/claude-code-hooks" })
5798
+ ]);
5799
+ console.log("");
5800
+ for (const line of initiativeLines) console.log(line);
5801
+ for (const line of notices.lines) console.log(line);
5802
+ if (process.stdout.isTTY) await notices.markShown();
5803
+ if (unpaired) {
5804
+ console.log("\nInstalled, not paired. Pair when you want the telemetry half:");
5805
+ console.log(" npx @ascenda-one/claude-code-hooks pair");
5806
+ }
5807
+ const wired = registered === HOOK_EVENTS.length || options.scope === "project" && elsewhere?.registered === HOOK_EVENTS.length;
5808
+ const healthy = credentials?.toolInstallationId && wired && fs3.existsSync(binary) && !stale.length;
4216
5809
  return healthy ? 0 : 1;
4217
5810
  }
5811
+ function describePairing(credentials, unpaired) {
5812
+ if (!credentials?.toolInstallationId) return "\u2014 not paired";
5813
+ if (!unpaired) return credentials.toolInstallationId;
5814
+ const when = credentials.installedAt ? `, installed ${credentials.installedAt}` : "";
5815
+ return `${credentials.toolInstallationId} (not paired${when})`;
5816
+ }
4218
5817
  function uninstall(options) {
5818
+ const unpaired = localOnlyInstall();
4219
5819
  const settingsFile = settingsPath(options);
4220
- if (fs.existsSync(settingsFile)) {
5820
+ if (fs3.existsSync(settingsFile)) {
4221
5821
  try {
4222
- const settings = JSON.parse(fs.readFileSync(settingsFile, "utf8"));
5822
+ const settings = JSON.parse(fs3.readFileSync(settingsFile, "utf8"));
4223
5823
  const hooks = { ...settings.hooks ?? {} };
4224
5824
  for (const event of Object.keys(hooks)) {
4225
5825
  const kept = hooks[event].filter((group) => !isOurs(group));
@@ -4228,8 +5828,8 @@ function uninstall(options) {
4228
5828
  }
4229
5829
  const updated = { ...settings, hooks };
4230
5830
  if (!Object.keys(hooks).length) delete updated.hooks;
4231
- fs.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
4232
- fs.writeFileSync(settingsFile, `${JSON.stringify(updated, null, 2)}
5831
+ fs3.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
5832
+ fs3.writeFileSync(settingsFile, `${JSON.stringify(updated, null, 2)}
4233
5833
  `, "utf8");
4234
5834
  console.log(`hooks removed from ${settingsFile}`);
4235
5835
  } catch {
@@ -4238,19 +5838,19 @@ function uninstall(options) {
4238
5838
  }
4239
5839
  }
4240
5840
  const binary = hookBinPath();
4241
- if (fs.existsSync(binary)) {
4242
- fs.rmSync(binary);
5841
+ if (fs3.existsSync(binary)) {
5842
+ fs3.rmSync(binary);
4243
5843
  console.log(`removed ${binary}`);
4244
5844
  }
4245
- const credentials = (0, import_tool_kit4.credentialsFilePath)();
4246
- if (fs.existsSync(credentials)) {
4247
- fs.rmSync(credentials);
4248
- console.log(`removed ${credentials}`);
5845
+ const credentialsFile2 = (0, import_tool_kit6.credentialsFilePath)();
5846
+ if (fs3.existsSync(credentialsFile2)) {
5847
+ removeCredentials();
5848
+ console.log(fs3.existsSync(credentialsFile2) ? `cleared the Claude Code pairing from ${credentialsFile2} (other tools' pairings kept)` : `removed ${credentialsFile2}`);
4249
5849
  }
4250
- console.log(`tokens left in ${path2.join((0, import_tool_kit8.ascendaHome)(), "tokens")} \u2014 revoke in the Ascenda app to invalidate them`);
5850
+ console.log(unpaired ? "this install was never paired, so there is no token here and nothing to revoke" : `tokens left in ${path3.join((0, import_tool_kit8.ascendaHome)(), "tokens")} \u2014 revoke in the Ascenda app to invalidate them`);
4251
5851
  return 0;
4252
5852
  }
4253
- var import_tool_kit8, HOOK_EVENTS, HOOK_TIMEOUT_SECONDS, HOOK_MARKER, USAGE;
5853
+ var import_tool_kit8, HOOK_EVENTS, HOOK_SET, HOOK_TIMEOUT_SECONDS, HOOK_MARKER, SENDS, USAGE, POLL_ERROR_TOLERANCE;
4254
5854
  var init_setup = __esm({
4255
5855
  "src/setup.ts"() {
4256
5856
  "use strict";
@@ -4258,9 +5858,11 @@ var init_setup = __esm({
4258
5858
  init_config();
4259
5859
  init_paths();
4260
5860
  init_types();
4261
- HOOK_EVENTS = ["SessionStart", "UserPromptSubmit", "PreToolUse", "PostToolUse", "PostToolUseFailure", "PreCompact", "PostCompact", "Stop", "Notification"];
5861
+ HOOK_EVENTS = ["SessionStart", "UserPromptSubmit", "PreToolUse", "PostToolUse", "PostToolUseFailure", "PreCompact", "PostCompact", "Stop", "StopFailure", "Notification", "SessionEnd", "SubagentStart", "SubagentStop"];
5862
+ HOOK_SET = 3;
4262
5863
  HOOK_TIMEOUT_SECONDS = 5;
4263
5864
  HOOK_MARKER = "ascenda-claude-hook";
5865
+ SENDS = ["model", "posture", "git", "edits", "waiting", "subagents"];
4264
5866
  USAGE = `ascenda-claude-hook setup \u2014 wire Claude Code to Ascenda telemetry
4265
5867
 
4266
5868
  npx @ascenda-one/claude-code-hooks setup [options]
@@ -4268,27 +5870,33 @@ var init_setup = __esm({
4268
5870
  npx @ascenda-one/claude-code-hooks doctor
4269
5871
  npx @ascenda-one/claude-code-hooks pair [--tool-type <type>]
4270
5872
  npx @ascenda-one/claude-code-hooks uninstall
5873
+ npx @ascenda-one/claude-code-hooks object <purpose> [--undo]
4271
5874
 
4272
5875
  doctor prints the send journal, outbox and one live round trip
4273
5876
  pair prints a code to paste into the app, then waits for confirmation
5877
+ object stop being counted for a purpose your organisation counts unless
5878
+ you object, from the next report; --undo reverses it
4274
5879
 
4275
5880
  Options
4276
5881
  --api-base-url <url> ingest host (default ${DEFAULT_API_BASE_URL})
4277
5882
  --local [port] shorthand for the local dev server (default port 4477)
4278
5883
  --tool-installation-id <id> reuse an existing pairing instead of creating one
4279
5884
  --token <eventWriteToken> reuse an existing token (stored 0600, never printed)
5885
+ --no-pair install without pairing: local features on, nothing sent
5886
+ (--no-pairing is accepted too)
4280
5887
  --scope project|user where hooks are registered (default project)
4281
5888
  --project-dir <path> project root for --scope project (default cwd)
4282
5889
  --dry-run print what would change, write nothing
4283
5890
  -h, --help
4284
5891
  `;
5892
+ POLL_ERROR_TOLERANCE = 3;
4285
5893
  }
4286
5894
  });
4287
5895
 
4288
5896
  // src/cli.ts
4289
5897
  var import_tool_kit9 = __toESM(require_out2(), 1);
4290
5898
  import { randomUUID as randomUUID2 } from "node:crypto";
4291
- import * as fs2 from "node:fs";
5899
+ import * as fs4 from "node:fs";
4292
5900
 
4293
5901
  // src/ascendaClient.ts
4294
5902
  var import_tool_kit = __toESM(require_out2(), 1);
@@ -4304,6 +5912,7 @@ var AscendaClient = class {
4304
5912
  tokenFilePath: config.tokenFilePath,
4305
5913
  stateFilePath: config.stateFilePath,
4306
5914
  outboxFilePath: config.outboxFilePath,
5915
+ renewToken: config.renewToken,
4307
5916
  sessionId: config.sessionId,
4308
5917
  workspaceHash: config.workspaceHash,
4309
5918
  projectHash: config.projectHash
@@ -4316,29 +5925,32 @@ var AscendaClient = class {
4316
5925
  async send(mapped) {
4317
5926
  return this.sender.send(mapped);
4318
5927
  }
5928
+ /** Outbox only, no network. See {@link AscendaEventSender.queue}. */
5929
+ queue(mapped) {
5930
+ return this.sender.queue(mapped);
5931
+ }
4319
5932
  async renewEventToken() {
4320
5933
  return this.sender.renewEventToken();
4321
5934
  }
4322
5935
  };
4323
5936
 
4324
- // src/cli.ts
4325
- init_config();
4326
-
4327
5937
  // src/mapClaudeEvent.ts
4328
- var import_tool_kit7 = __toESM(require_out2(), 1);
5938
+ var import_tool_kit4 = __toESM(require_out2(), 1);
4329
5939
  init_types();
4330
5940
 
4331
5941
  // src/safeExtract.ts
4332
- var import_tool_kit6 = __toESM(require_out2(), 1);
5942
+ var import_tool_kit3 = __toESM(require_out2(), 1);
4333
5943
 
4334
5944
  // src/mapClaudeEvent.ts
4335
5945
  function mapClaudeEvent(hookName, input) {
4336
5946
  const events = mapEvent(hookName, input);
4337
5947
  if (events.length === 0) return events;
4338
- const branchHash = (0, import_tool_kit7.deriveBranchHashForCwd)((0, import_tool_kit6.getString)(input, ["cwd"]) ?? process.cwd());
5948
+ const branchHash = (0, import_tool_kit4.deriveBranchHashForCwd)((0, import_tool_kit3.getString)(input, ["cwd"]) ?? process.cwd());
5949
+ const runtime = claudeRuntime();
5950
+ const subagentId = readSubagentId(input);
4339
5951
  return events.map((event) => ({
4340
5952
  ...event,
4341
- metadata: { host: CLAUDE_HOST, ...branchHash ? { branchHash } : {}, ...event.metadata }
5953
+ metadata: { host: CLAUDE_HOST, runtime, ...branchHash ? { branchHash } : {}, ...subagentId ? { subagentId } : {}, ...event.metadata }
4342
5954
  }));
4343
5955
  }
4344
5956
  function mapEvent(hookName, input) {
@@ -4362,25 +5974,35 @@ function mapEvent(hookName, input) {
4362
5974
  return [{ eventType: "context_pressure_high", severity: "medium", metadata: { trigger: "inferred", reason: "context_limit" } }];
4363
5975
  case "Stop":
4364
5976
  return mapStop(input);
5977
+ // Live signal only (see `emitLive` in cli.ts). The payload carries the
5978
+ // last assistant message, and nothing here reads it.
5979
+ case "StopFailure":
5980
+ return [];
4365
5981
  case "Notification":
4366
5982
  return mapNotification(input);
5983
+ case "SessionEnd":
5984
+ return mapSessionEnd(input);
5985
+ case "SubagentStart":
5986
+ return mapSubagent("subagent_started", input);
5987
+ case "SubagentStop":
5988
+ return mapSubagent("subagent_stopped", input);
4367
5989
  default:
4368
5990
  return [];
4369
5991
  }
4370
5992
  }
4371
5993
  function isNewSessionStart(input) {
4372
- const source = (0, import_tool_kit6.getString)(input, ["source"]);
5994
+ const source = (0, import_tool_kit3.getString)(input, ["source"]);
4373
5995
  return !source || source === "startup" || source === "resume";
4374
5996
  }
4375
5997
  function milestoneInviting(input) {
4376
- if ((0, import_tool_kit6.outcomeForHook)("PostToolUse", input) !== "success") return false;
4377
- const command = (0, import_tool_kit6.getString)(input, ["command"]) ?? (0, import_tool_kit6.getNestedString)(input, [["tool_input", "command"], ["input", "command"], ["parameters", "command"]]);
4378
- return (0, import_tool_kit7.invitesDebrief)((0, import_tool_kit7.classifyWorkMilestone)(command));
5998
+ if ((0, import_tool_kit3.outcomeForHook)("PostToolUse", input) !== "success") return false;
5999
+ const command = (0, import_tool_kit3.getString)(input, ["command"]) ?? (0, import_tool_kit3.getNestedString)(input, [["tool_input", "command"], ["input", "command"], ["parameters", "command"]]);
6000
+ return (0, import_tool_kit4.invitesDebrief)((0, import_tool_kit4.classifyWorkMilestone)(command));
4379
6001
  }
4380
6002
  function mapSessionStart(input) {
4381
6003
  if (!isNewSessionStart(input)) return [];
4382
6004
  const modelId = readModelIdentifier(input)?.trim();
4383
- const modelClass = (0, import_tool_kit7.classifyModelClass)(modelId);
6005
+ const modelClass = (0, import_tool_kit4.classifyModelClass)(modelId);
4384
6006
  return [{
4385
6007
  eventType: "create_focus_session",
4386
6008
  severity: "low",
@@ -4392,11 +6014,56 @@ function mapSessionStart(input) {
4392
6014
  }
4393
6015
  }];
4394
6016
  }
6017
+ function mapSessionEnd(input) {
6018
+ const raw = input["reason"];
6019
+ return [{
6020
+ eventType: "recovery_offline_period",
6021
+ severity: "low",
6022
+ metadata: {
6023
+ activity: "session_ended",
6024
+ ...raw === void 0 || raw === null ? {} : { sessionEndReason: classifySessionEndReason(raw) }
6025
+ }
6026
+ }];
6027
+ }
6028
+ function classifySessionEndReason(raw) {
6029
+ if (typeof raw !== "string") return "unknown";
6030
+ const value = raw.trim().toLowerCase();
6031
+ return SESSION_END_REASONS.includes(value) ? value : "unknown";
6032
+ }
6033
+ var SESSION_END_REASONS = ["clear", "resume", "logout", "prompt_input_exit", "other"];
6034
+ function mapSubagent(eventType, input) {
6035
+ const raw = input["agent_type"];
6036
+ return [{
6037
+ eventType,
6038
+ severity: "low",
6039
+ metadata: raw === void 0 || raw === null ? {} : { subagentClass: classifySubagentType(raw) }
6040
+ }];
6041
+ }
6042
+ function classifySubagentType(raw) {
6043
+ if (typeof raw !== "string") return "unknown";
6044
+ const value = raw.trim().toLowerCase();
6045
+ if (value === "") return "none";
6046
+ if (value.includes(":")) return "plugin";
6047
+ return BUILT_IN_SUBAGENTS[value] ?? "custom";
6048
+ }
6049
+ var BUILT_IN_SUBAGENTS = {
6050
+ "general-purpose": "general_purpose",
6051
+ explore: "explore",
6052
+ plan: "plan",
6053
+ "statusline-setup": "statusline_setup",
6054
+ "claude-code-guide": "claude_code_guide"
6055
+ };
6056
+ function readSubagentId(input) {
6057
+ const raw = input["agent_id"];
6058
+ if (typeof raw !== "string") return void 0;
6059
+ const value = raw.trim();
6060
+ return /^[A-Za-z0-9_-]{1,128}$/.test(value) ? value : void 0;
6061
+ }
4395
6062
  function mapUserPromptSubmit(input) {
4396
- const prompt = (0, import_tool_kit6.getString)(input, ["prompt", "userPrompt", "message"]) ?? (0, import_tool_kit6.getNestedString)(input, [["payload", "prompt"], ["payload", "message"]]);
6063
+ const prompt = (0, import_tool_kit3.getString)(input, ["prompt", "userPrompt", "message"]) ?? (0, import_tool_kit3.getNestedString)(input, [["payload", "prompt"], ["payload", "message"]]);
4397
6064
  const autonomy = autonomyModeMetadata(input);
4398
6065
  const events = [{ eventType: "ai_prompt_submitted", severity: "low", metadata: { promptClass: "unknown", ...autonomy } }];
4399
- if ((0, import_tool_kit6.looksLikeCorrection)(prompt)) {
6066
+ if ((0, import_tool_kit3.looksLikeCorrection)(prompt)) {
4400
6067
  events.push({ eventType: "ai_correction_prompt", severity: "medium", metadata: { reason: "repeated_reprompting", trigger: "inferred", ...autonomy } });
4401
6068
  }
4402
6069
  return events;
@@ -4410,7 +6077,7 @@ function mapNotification(input) {
4410
6077
  // Low, always. Being asked is overhead to be counted, not a failure to be
4411
6078
  // flagged, and a severity that climbed would make this the input to a score.
4412
6079
  severity: "low",
4413
- metadata: { interruptionKind: notificationKind((0, import_tool_kit6.getString)(input, ["message"])) }
6080
+ metadata: { interruptionKind: notificationKind((0, import_tool_kit3.getString)(input, ["message"])) }
4414
6081
  }];
4415
6082
  }
4416
6083
  function notificationKind(message) {
@@ -4422,32 +6089,32 @@ function notificationKind(message) {
4422
6089
  function mapPostToolUse(hookName, input) {
4423
6090
  const toolName = getToolName(input);
4424
6091
  const safeToolName = sanitiseToolName(toolName);
4425
- const outcome = (0, import_tool_kit6.outcomeForHook)(hookName, input);
4426
- const durationMs = (0, import_tool_kit6.getNumber)(input, ["duration_ms", "durationMs", "elapsedMs"]) ?? (0, import_tool_kit6.getNestedNumber)(input, [["tool_response", "durationMs"], ["result", "durationMs"]]);
4427
- const command = (0, import_tool_kit6.getString)(input, ["command"]) ?? (0, import_tool_kit6.getNestedString)(input, [["tool_input", "command"], ["input", "command"], ["parameters", "command"]]);
4428
- const commandClass = (0, import_tool_kit7.classifyCommand)(command);
4429
- const gitAction = outcome === "success" ? (0, import_tool_kit7.classifyGitAction)(command) : void 0;
4430
- const milestoneKind = outcome === "success" ? (0, import_tool_kit7.classifyWorkMilestone)(command) : void 0;
6092
+ const outcome = (0, import_tool_kit3.outcomeForHook)(hookName, input);
6093
+ const durationMs = (0, import_tool_kit3.getNumber)(input, ["duration_ms", "durationMs", "elapsedMs"]) ?? (0, import_tool_kit3.getNestedNumber)(input, [["tool_response", "durationMs"], ["result", "durationMs"]]);
6094
+ const command = (0, import_tool_kit3.getString)(input, ["command"]) ?? (0, import_tool_kit3.getNestedString)(input, [["tool_input", "command"], ["input", "command"], ["parameters", "command"]]);
6095
+ const commandClass = (0, import_tool_kit4.classifyCommand)(command);
6096
+ const gitAction = outcome === "success" ? (0, import_tool_kit4.classifyGitAction)(command) : void 0;
6097
+ const milestoneKind = outcome === "success" ? (0, import_tool_kit4.classifyWorkMilestone)(command) : void 0;
4431
6098
  const autonomy = autonomyModeMetadata(input);
4432
6099
  if (outcome === "cancelled") {
4433
- return [{ eventType: "ai_tool_call_failed", severity: "low", metadata: { toolName: safeToolName, commandClass, outcome, durationBucket: (0, import_tool_kit6.bucketDurationMs)(durationMs), reason: "manual_interrupt", ...autonomy } }];
6100
+ return [{ eventType: "ai_tool_call_failed", severity: "low", metadata: { toolName: safeToolName, commandClass, outcome, durationBucket: (0, import_tool_kit3.bucketDurationMs)(durationMs), reason: "manual_interrupt", ...autonomy } }];
4434
6101
  }
4435
6102
  if (outcome === "failure") {
4436
- if (toolName?.toLowerCase() === "bash" && (0, import_tool_kit7.isVerificationCommand)(commandClass)) {
4437
- return [{ eventType: "compile_error", severity: "medium", metadata: { toolName: safeToolName, commandClass, outcome, durationBucket: (0, import_tool_kit6.bucketDurationMs)(durationMs), reason: "test_failure", ...autonomy } }];
6103
+ if (toolName?.toLowerCase() === "bash" && (0, import_tool_kit4.isVerificationCommand)(commandClass)) {
6104
+ return [{ eventType: "compile_error", severity: "medium", metadata: { toolName: safeToolName, commandClass, outcome, durationBucket: (0, import_tool_kit3.bucketDurationMs)(durationMs), reason: "test_failure", ...autonomy } }];
4438
6105
  }
4439
- return [{ eventType: "ai_tool_call_failed", severity: "medium", metadata: { toolName: safeToolName, commandClass, outcome, durationBucket: (0, import_tool_kit6.bucketDurationMs)(durationMs), reason: "tool_failure", ...autonomy } }];
6106
+ return [{ eventType: "ai_tool_call_failed", severity: "medium", metadata: { toolName: safeToolName, commandClass, outcome, durationBucket: (0, import_tool_kit3.bucketDurationMs)(durationMs), reason: "tool_failure", ...autonomy } }];
4440
6107
  }
4441
6108
  if (isWriteTool(toolName)) {
4442
6109
  const linesChanged = computeLinesChanged(toolName, input);
4443
- const userModified = (0, import_tool_kit6.getNested)(input, ["tool_response", "userModified"]);
6110
+ const userModified = (0, import_tool_kit3.getNested)(input, ["tool_response", "userModified"]);
4444
6111
  return [{
4445
6112
  eventType: toolName?.toLowerCase() === "write" ? "ai_file_write" : "ai_file_edit",
4446
6113
  severity: "low",
4447
6114
  metadata: {
4448
6115
  toolName: safeToolName,
4449
6116
  outcome,
4450
- durationBucket: (0, import_tool_kit6.bucketDurationMs)(durationMs),
6117
+ durationBucket: (0, import_tool_kit3.bucketDurationMs)(durationMs),
4451
6118
  ...autonomy,
4452
6119
  // `false` is kept, not suppressed: without the negatives there is a
4453
6120
  // numerator and no denominator, and no correction *rate* can be
@@ -4460,12 +6127,12 @@ function mapPostToolUse(hookName, input) {
4460
6127
  // second event type exists for this — the bucket on the existing
4461
6128
  // creation event *is* the boundary, deliberately, since the write
4462
6129
  // already happened; there is nothing else to mark.
4463
- ...linesChanged !== void 0 ? { linesChangedBucket: (0, import_tool_kit6.bucketLinesChanged)(linesChanged) } : {}
6130
+ ...linesChanged !== void 0 ? { linesChangedBucket: (0, import_tool_kit3.bucketLinesChanged)(linesChanged) } : {}
4464
6131
  }
4465
6132
  }];
4466
6133
  }
4467
- if (toolName?.toLowerCase() === "bash" && (0, import_tool_kit7.isVerificationCommand)(commandClass)) {
4468
- 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 } }];
6134
+ if (toolName?.toLowerCase() === "bash" && (0, import_tool_kit4.isVerificationCommand)(commandClass)) {
6135
+ return [{ eventType: "editor_verification_activity", severity: "low", metadata: { toolName: safeToolName, commandClass, outcome, durationBucket: (0, import_tool_kit3.bucketDurationMs)(durationMs), activity: "ai_test_or_build_run", ...autonomy } }];
4469
6136
  }
4470
6137
  return [{
4471
6138
  eventType: "ai_tool_call_completed",
@@ -4474,14 +6141,14 @@ function mapPostToolUse(hookName, input) {
4474
6141
  toolName: safeToolName,
4475
6142
  commandClass,
4476
6143
  outcome,
4477
- durationBucket: (0, import_tool_kit6.bucketDurationMs)(durationMs),
6144
+ durationBucket: (0, import_tool_kit3.bucketDurationMs)(durationMs),
4478
6145
  ...autonomy,
4479
6146
  // The boundary and rework signal both ride this existing event rather
4480
6147
  // than minting a type: the backend already reads `gitAction` off any
4481
6148
  // event, and a commit is not a different *kind* of thing happening, it
4482
6149
  // is a fact about the tool call that just happened.
4483
6150
  ...gitAction !== void 0 ? { gitAction } : {},
4484
- ...(0, import_tool_kit7.isReworkGitAction)(gitAction) ? { activity: "rework_reversion" } : {},
6151
+ ...(0, import_tool_kit4.isReworkGitAction)(gitAction) ? { activity: "rework_reversion" } : {},
4485
6152
  // Same reasoning as `gitAction` above, one grain coarser: a milestone is
4486
6153
  // a fact about the tool call that just happened, not a different kind of
4487
6154
  // event. It rides here so the record carries the work's own rhythm —
@@ -4491,13 +6158,13 @@ function mapPostToolUse(hookName, input) {
4491
6158
  }];
4492
6159
  }
4493
6160
  function mapPreCompact(input) {
4494
- const trigger = (0, import_tool_kit6.getString)(input, ["trigger", "reason", "compactType", "type"]) ?? (0, import_tool_kit6.getNestedString)(input, [["payload", "trigger"], ["payload", "reason"]]);
6161
+ const trigger = (0, import_tool_kit3.getString)(input, ["trigger", "reason", "compactType", "type"]) ?? (0, import_tool_kit3.getNestedString)(input, [["payload", "trigger"], ["payload", "reason"]]);
4495
6162
  const isManual = trigger?.toLowerCase().includes("manual") ?? false;
4496
6163
  return [{ eventType: isManual ? "context_compression_manual" : "context_compression_auto", severity: isManual ? "medium" : "high", metadata: { trigger: isManual ? "manual" : "auto", reason: "context_limit" } }];
4497
6164
  }
4498
6165
  function mapStop(input) {
4499
- const durationMs = (0, import_tool_kit6.getNumber)(input, ["durationMs", "duration_ms", "elapsedMs"]) ?? (0, import_tool_kit6.getNestedNumber)(input, [["session", "durationMs"], ["payload", "durationMs"]]);
4500
- const durationBucket = (0, import_tool_kit6.bucketDurationMs)(durationMs);
6166
+ const durationMs = (0, import_tool_kit3.getNumber)(input, ["durationMs", "duration_ms", "elapsedMs"]) ?? (0, import_tool_kit3.getNestedNumber)(input, [["session", "durationMs"], ["payload", "durationMs"]]);
6167
+ const durationBucket = (0, import_tool_kit3.bucketDurationMs)(durationMs);
4501
6168
  const autonomy = autonomyModeMetadata(input);
4502
6169
  const events = [];
4503
6170
  if (durationBucket === "30-60m" || durationBucket === "60m+") {
@@ -4514,7 +6181,7 @@ function readPermissionMode(input) {
4514
6181
  const candidates = [
4515
6182
  input["permission_mode"],
4516
6183
  input["permissionMode"],
4517
- (0, import_tool_kit6.getNested)(input, ["payload", "permission_mode"])
6184
+ (0, import_tool_kit3.getNested)(input, ["payload", "permission_mode"])
4518
6185
  ];
4519
6186
  for (const value of candidates) {
4520
6187
  if (value !== void 0 && value !== null) return value;
@@ -4534,13 +6201,13 @@ var AUTONOMY_BY_PERMISSION_MODE = {
4534
6201
  bypasspermissions: "bypass_permissions"
4535
6202
  };
4536
6203
  function readModelIdentifier(input) {
4537
- 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"]]);
6204
+ return (0, import_tool_kit3.getString)(input, ["model", "model_id", "modelId"]) ?? (0, import_tool_kit3.getNestedString)(input, [["model", "id"], ["model", "display_name"], ["model", "name"], ["payload", "model"]]);
4538
6205
  }
4539
6206
  function getToolName(input) {
4540
- return (0, import_tool_kit6.getString)(input, ["toolName", "tool_name", "name"]) ?? (0, import_tool_kit6.getNestedString)(input, [["tool", "name"], ["tool_use", "name"], ["payload", "toolName"]]);
6207
+ return (0, import_tool_kit3.getString)(input, ["toolName", "tool_name", "name"]) ?? (0, import_tool_kit3.getNestedString)(input, [["tool", "name"], ["tool_use", "name"], ["payload", "toolName"]]);
4541
6208
  }
4542
6209
  function computeLinesChanged(toolName, input) {
4543
- const toolInput = (0, import_tool_kit6.getNested)(input, ["tool_input"]) ?? (0, import_tool_kit6.getNested)(input, ["input"]) ?? (0, import_tool_kit6.getNested)(input, ["parameters"]);
6210
+ const toolInput = (0, import_tool_kit3.getNested)(input, ["tool_input"]) ?? (0, import_tool_kit3.getNested)(input, ["input"]) ?? (0, import_tool_kit3.getNested)(input, ["parameters"]);
4544
6211
  if (!toolInput || typeof toolInput !== "object") return void 0;
4545
6212
  const record = toolInput;
4546
6213
  switch (toolName?.toLowerCase()) {
@@ -4585,19 +6252,198 @@ function sanitiseToolName(toolName) {
4585
6252
  return toolName.replace(/[^a-zA-Z0-9_-]/g, "").slice(0, 40) || "unknown";
4586
6253
  }
4587
6254
 
6255
+ // src/liveEvent.ts
6256
+ function liveEventFor(hookName, input) {
6257
+ switch (hookName) {
6258
+ case "UserPromptSubmit":
6259
+ return "prompt_submitted";
6260
+ case "PreToolUse":
6261
+ return getToolName(input) === ASK_USER_QUESTION ? "awaiting" : "tool_call";
6262
+ case "PreCompact":
6263
+ return "compaction";
6264
+ case "PostToolUseFailure":
6265
+ return "tool_failure";
6266
+ case "Stop":
6267
+ return "stop";
6268
+ case "StopFailure":
6269
+ return "halted";
6270
+ case "Notification":
6271
+ return notificationLiveEvent(input);
6272
+ default:
6273
+ return void 0;
6274
+ }
6275
+ }
6276
+ var ASK_USER_QUESTION = "AskUserQuestion";
6277
+ var NOTIFICATION_EVENTS = {
6278
+ permission_prompt: "awaiting",
6279
+ elicitation_dialog: "awaiting",
6280
+ idle_prompt: "halted"
6281
+ };
6282
+ var NOTIFICATION_KIND_EVENTS = {
6283
+ permission_request: "awaiting",
6284
+ idle_prompt: "halted"
6285
+ };
6286
+ function notificationLiveEvent(input) {
6287
+ const kind = (0, import_tool_kit3.getString)(input, ["notification_type", "notificationType"]);
6288
+ if (kind !== void 0) return Object.hasOwn(NOTIFICATION_EVENTS, kind) ? NOTIFICATION_EVENTS[kind] : void 0;
6289
+ const label = notificationKind((0, import_tool_kit3.getString)(input, ["message"]));
6290
+ return Object.hasOwn(NOTIFICATION_KIND_EVENTS, label) ? NOTIFICATION_KIND_EVENTS[label] : void 0;
6291
+ }
6292
+
6293
+ // src/usageLimitReset.ts
6294
+ import * as fs from "node:fs";
6295
+ import * as os from "node:os";
6296
+ import * as path from "node:path";
6297
+ var MAX_RESUME_AHEAD_MS = 6 * 60 * 60 * 1e3;
6298
+ var MONTHS = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
6299
+ var RESET_CLAUSE = new RegExp(
6300
+ "\\bresets?(?:\\s+at)?\\s+(?:([a-z]{3,9})\\.?\\s+(\\d{1,2})(?:st|nd|rd|th)?,?\\s+(?:at\\s+)?)?(\\d{1,2})(?::(\\d{2}))?\\s*(am|pm|a\\.m\\.|p\\.m\\.)?(?:\\s*\\(([^)]+)\\))?",
6301
+ "i"
6302
+ );
6303
+ var PIPE_EPOCH = /usage limit reached\|(\d{10,13})\b/i;
6304
+ function parseUsageLimitReset(text, now, localZone) {
6305
+ const piped = PIPE_EPOCH.exec(text);
6306
+ if (piped) {
6307
+ const raw = Number(piped[1]);
6308
+ return piped[1].length > 10 ? raw : raw * 1e3;
6309
+ }
6310
+ const match = RESET_CLAUSE.exec(text);
6311
+ if (!match) return void 0;
6312
+ const [, monthWord, dayText, hourText, minuteText, meridiem, zoneText] = match;
6313
+ const hour = to24Hour(Number(hourText), meridiem, minuteText !== void 0);
6314
+ if (hour === void 0) return void 0;
6315
+ const minute = minuteText === void 0 ? 0 : Number(minuteText);
6316
+ if (minute > 59) return void 0;
6317
+ const zone = zoneText?.trim() || localZone || Intl.DateTimeFormat().resolvedOptions().timeZone;
6318
+ const today = wallDate(now, zone);
6319
+ if (!today) return void 0;
6320
+ if (monthWord !== void 0) {
6321
+ const month = MONTHS.indexOf(monthWord.slice(0, 3).toLowerCase());
6322
+ if (month < 0 || !matchesMonthName(monthWord, month)) return void 0;
6323
+ const day = Number(dayText);
6324
+ if (day < 1 || day > 31) return void 0;
6325
+ let at = zonedToEpoch({ year: today.year, month: month + 1, day, hour, minute }, zone);
6326
+ if (at !== void 0 && at <= now.getTime()) {
6327
+ at = zonedToEpoch({ year: today.year + 1, month: month + 1, day, hour, minute }, zone);
6328
+ }
6329
+ return at;
6330
+ }
6331
+ const sameDay = zonedToEpoch({ ...today, hour, minute }, zone);
6332
+ if (sameDay === void 0) return void 0;
6333
+ if (sameDay > now.getTime()) return sameDay;
6334
+ return zonedToEpoch({ ...nextDay(today), hour, minute }, zone);
6335
+ }
6336
+ function resumesAtFor(text, now, localZone) {
6337
+ if (!text) return void 0;
6338
+ const at = parseUsageLimitReset(text, now, localZone);
6339
+ if (at === void 0) return void 0;
6340
+ const ahead = at - now.getTime();
6341
+ if (ahead <= 0 || ahead > MAX_RESUME_AHEAD_MS) return void 0;
6342
+ return Math.round(at / 6e4) * 60;
6343
+ }
6344
+ function to24Hour(hour, meridiem, hasMinutes) {
6345
+ if (meridiem === void 0) {
6346
+ if (!hasMinutes || hour > 23) return void 0;
6347
+ return hour;
6348
+ }
6349
+ if (hour < 1 || hour > 12) return void 0;
6350
+ const pm = meridiem.toLowerCase().startsWith("p");
6351
+ if (hour === 12) return pm ? 12 : 0;
6352
+ return pm ? hour + 12 : hour;
6353
+ }
6354
+ function matchesMonthName(word, month) {
6355
+ const full = new Date(Date.UTC(2e3, month, 1)).toLocaleString("en-US", { month: "long", timeZone: "UTC" }).toLowerCase();
6356
+ return full.startsWith(word.toLowerCase());
6357
+ }
6358
+ function wallDate(instant, zone) {
6359
+ const parts = wallParts(instant.getTime(), zone);
6360
+ return parts && { year: parts.year, month: parts.month, day: parts.day };
6361
+ }
6362
+ function nextDay(date) {
6363
+ const next = new Date(Date.UTC(date.year, date.month - 1, date.day + 1));
6364
+ return { year: next.getUTCFullYear(), month: next.getUTCMonth() + 1, day: next.getUTCDate() };
6365
+ }
6366
+ function wallParts(epochMs, zone) {
6367
+ let format;
6368
+ try {
6369
+ format = new Intl.DateTimeFormat("en-US", {
6370
+ timeZone: zone,
6371
+ hourCycle: "h23",
6372
+ year: "numeric",
6373
+ month: "numeric",
6374
+ day: "numeric",
6375
+ hour: "numeric",
6376
+ minute: "numeric"
6377
+ });
6378
+ } catch {
6379
+ return void 0;
6380
+ }
6381
+ const value = (type) => Number(format.formatToParts(epochMs).find((part) => part.type === type)?.value);
6382
+ return { year: value("year"), month: value("month"), day: value("day"), hour: value("hour"), minute: value("minute") };
6383
+ }
6384
+ function zonedToEpoch(time, zone) {
6385
+ const asUtc = Date.UTC(time.year, time.month - 1, time.day, time.hour, time.minute);
6386
+ const check = new Date(asUtc);
6387
+ if (check.getUTCDate() !== time.day) return void 0;
6388
+ let guess = asUtc;
6389
+ for (let pass = 0; pass < 2; pass += 1) {
6390
+ const seen = wallParts(guess, zone);
6391
+ if (!seen) return void 0;
6392
+ const seenUtc = Date.UTC(seen.year, seen.month - 1, seen.day, seen.hour, seen.minute);
6393
+ guess += asUtc - seenUtc;
6394
+ }
6395
+ return guess;
6396
+ }
6397
+ function managedSettingsPath() {
6398
+ if (process.env.ASCENDA_CLAUDE_MANAGED_SETTINGS) return process.env.ASCENDA_CLAUDE_MANAGED_SETTINGS;
6399
+ if (process.platform === "darwin") return "/Library/Application Support/ClaudeCode/managed-settings.json";
6400
+ if (process.platform === "win32") return "C:\\Program Files\\ClaudeCode\\managed-settings.json";
6401
+ return "/etc/claude-code/managed-settings.json";
6402
+ }
6403
+ function autoContinueEnabled(sources = {}) {
6404
+ const home = sources.home ?? os.homedir();
6405
+ const files = [
6406
+ sources.managedPath ?? managedSettingsPath(),
6407
+ ...sources.projectDir ? [path.join(sources.projectDir, ".claude", "settings.local.json"), path.join(sources.projectDir, ".claude", "settings.json")] : [],
6408
+ path.join(home, ".claude", "settings.json")
6409
+ ];
6410
+ for (const file of files) {
6411
+ const value = readSetting(file, "autoContinueAtUsageLimit");
6412
+ if (value !== void 0) return value === true;
6413
+ }
6414
+ return false;
6415
+ }
6416
+ function readSetting(file, key) {
6417
+ try {
6418
+ const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
6419
+ if (parsed && typeof parsed === "object" && key in parsed) return parsed[key];
6420
+ } catch {
6421
+ }
6422
+ return void 0;
6423
+ }
6424
+
4588
6425
  // src/cli.ts
6426
+ init_config();
4589
6427
  init_paths();
4590
6428
  init_types();
4591
6429
  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.";
4592
6430
  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.";
4593
6431
  async function runPair() {
4594
- const apiBaseUrl = (process.env.ASCENDA_API_BASE_URL ?? "https://api.ascenda.one").replace(/\/$/, "");
6432
+ const credentials = readCredentials();
6433
+ const apiBaseUrl = (process.env.ASCENDA_API_BASE_URL ?? credentials?.apiBaseUrl ?? "https://api.ascenda.one").replace(/\/$/, "");
4595
6434
  const flagIndex = process.argv.indexOf("--tool-type");
4596
6435
  const requestedType = flagIndex !== -1 ? (process.argv[flagIndex + 1] ?? "").trim() : "";
4597
6436
  const toolType = requestedType || ASCENDA_TOOL_TYPE;
4598
- const existing = process.env.ASCENDA_TOOL_INSTALLATION_ID?.trim();
6437
+ const existing = process.env.ASCENDA_TOOL_INSTALLATION_ID?.trim() || credentials?.toolInstallationId?.trim();
4599
6438
  const reusable = existing && existing.includes(":") && (!requestedType || existing.startsWith(`${requestedType}:`));
4600
6439
  const toolInstallationId = reusable ? existing : `${toolType}:${randomUUID2()}`;
6440
+ const isClaudeCode = toolType === ASCENDA_TOOL_TYPE;
6441
+ const { SENDS: SENDS2 } = isClaudeCode ? await Promise.resolve().then(() => (init_setup(), setup_exports)) : { SENDS: [] };
6442
+ await writeStdout(
6443
+ `
6444
+ ${(0, import_tool_kit9.renderSetupDisclosure)({ sends: SENDS2, displayName: isClaudeCode ? "Claude Code" : toolType })}
6445
+ `
6446
+ );
4601
6447
  const session = await (0, import_tool_kit9.createPairingSession)(apiBaseUrl, toolInstallationId, toolType, toolType === ASCENDA_TOOL_TYPE ? "Claude Code" : toolType);
4602
6448
  const code = session.deviceCode ?? session.code;
4603
6449
  await writeStdout(
@@ -4633,7 +6479,7 @@ Waiting for confirmation (expires ${session.expiresAt})...
4633
6479
  writeCredentials({ apiBaseUrl, toolInstallationId: pairedId, pairedAt: (/* @__PURE__ */ new Date()).toISOString() });
4634
6480
  await writeStdout(
4635
6481
  `Paired. Write token saved to ${tokenFilePath}
4636
- Pairing saved to ${(0, import_tool_kit4.credentialsFilePath)()}
6482
+ Pairing saved to ${(0, import_tool_kit6.credentialsFilePath)()}
4637
6483
 
4638
6484
  Restart Claude Code and events flow. Nothing to add to your shell profile.
4639
6485
 
@@ -4644,18 +6490,61 @@ Restart Claude Code and events flow. Nothing to add to your shell profile.
4644
6490
  process.stderr.write("Timed out waiting for confirmation. Run the command again for a fresh code.\n");
4645
6491
  process.exitCode = 1;
4646
6492
  }
6493
+ async function runJoin(argv) {
6494
+ const joinCode = argv[0];
6495
+ if (!joinCode || joinCode.startsWith("-")) {
6496
+ process.stderr.write("Usage: ascenda-claude-hook join <code>\n");
6497
+ return 1;
6498
+ }
6499
+ let apiBaseUrl;
6500
+ let eventWriteToken;
6501
+ try {
6502
+ ({ apiBaseUrl, eventWriteToken } = loadConfigFromEnv());
6503
+ } catch (error) {
6504
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}
6505
+ `);
6506
+ return 1;
6507
+ }
6508
+ return (0, import_tool_kit9.runStudyJoin)({ apiBaseUrl, eventWriteToken, displayName: "Claude Code", joinCode });
6509
+ }
6510
+ async function runObject(argv) {
6511
+ let apiBaseUrl;
6512
+ let eventWriteToken;
6513
+ try {
6514
+ ({ apiBaseUrl, eventWriteToken } = loadConfigFromEnv());
6515
+ } catch (error) {
6516
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}
6517
+ `);
6518
+ return 1;
6519
+ }
6520
+ return (0, import_tool_kit9.runStudyObjection)({
6521
+ apiBaseUrl,
6522
+ eventWriteToken,
6523
+ commandPrefix: "npx @ascenda-one/claude-code-hooks",
6524
+ pairCommand: "npx @ascenda-one/claude-code-hooks pair",
6525
+ argv
6526
+ });
6527
+ }
4647
6528
  var MANAGEMENT_COMMANDS = /* @__PURE__ */ new Set(["setup", "install", "status", "uninstall", "-h", "--help"]);
4648
6529
  async function main() {
4649
6530
  const command = process.argv[2];
4650
6531
  if (!command) {
4651
6532
  throw new Error(
4652
- "Usage: ascenda-claude-hook <ClaudeHookEventName> | pair | doctor | setup | status | uninstall"
6533
+ "Usage: ascenda-claude-hook <ClaudeHookEventName> | pair | join | object | doctor | setup | status | uninstall"
4653
6534
  );
4654
6535
  }
4655
6536
  if (command === "pair") {
4656
6537
  await runPair();
4657
6538
  return;
4658
6539
  }
6540
+ if (command === "join") {
6541
+ setupExitCode = await runJoin(process.argv.slice(3));
6542
+ return;
6543
+ }
6544
+ if (command === "object") {
6545
+ setupExitCode = await runObject(process.argv.slice(3));
6546
+ return;
6547
+ }
4659
6548
  if (command === "doctor") {
4660
6549
  await runDoctor();
4661
6550
  return;
@@ -4667,7 +6556,7 @@ async function main() {
4667
6556
  }
4668
6557
  if (!isClaudeHookEventName(command)) {
4669
6558
  throw new Error(
4670
- `Unknown command "${command}". Expected a Claude Code hook name, "pair", "doctor", "setup", "status" or "uninstall".`
6559
+ `Unknown command "${command}". Expected a Claude Code hook name, "pair", "join", "object", "doctor", "setup", "status" or "uninstall".`
4671
6560
  );
4672
6561
  }
4673
6562
  const hookName = command;
@@ -4699,9 +6588,13 @@ async function main() {
4699
6588
  try {
4700
6589
  config = loadConfigFromEnv();
4701
6590
  } catch (error) {
4702
- if (error instanceof MissingInstallationIdError) journalSkippedSend(error);
6591
+ const unpaired = localOnlyInstall();
6592
+ if (!unpaired && error instanceof MissingInstallationIdError) journalSkippedSend(error);
4703
6593
  const logFile = (0, import_tool_kit9.resolveEventLogPath)();
4704
- if (!logFile) throw error;
6594
+ if (!logFile) {
6595
+ if (unpaired) return;
6596
+ throw error;
6597
+ }
4705
6598
  for (const event of mappedEvents) {
4706
6599
  logUnsent(logFile, event, workContext, (0, import_tool_kit9.getString)(input, ["session_id", "sessionId"]) ?? null);
4707
6600
  }
@@ -4711,6 +6604,12 @@ async function main() {
4711
6604
  config.projectHash ??= workContext?.projectHash ?? null;
4712
6605
  config.sessionId ??= (0, import_tool_kit9.getString)(input, ["session_id", "sessionId"]) ?? null;
4713
6606
  const client = new AscendaClient(config);
6607
+ if (hookName === "SessionEnd") {
6608
+ for (const event of mappedEvents) {
6609
+ if (!client.queue(event)) console.error("Ascenda telemetry not kept: the session end could not be written to the outbox.");
6610
+ }
6611
+ return;
6612
+ }
4714
6613
  for (const event of mappedEvents) {
4715
6614
  const result = await client.send(event);
4716
6615
  if (result === "accepted") continue;
@@ -4730,12 +6629,23 @@ function explainRejection(result) {
4730
6629
  return `Ascenda telemetry rejected: ${result}`;
4731
6630
  }
4732
6631
  async function emitLive(hookName, input) {
4733
- const event = hookName === "UserPromptSubmit" ? "prompt_submitted" : hookName === "PreToolUse" ? "tool_call" : hookName === "PreCompact" ? "compaction" : hookName === "PostToolUseFailure" ? "tool_failure" : hookName === "Stop" ? "stop" : void 0;
6632
+ let event;
6633
+ try {
6634
+ event = liveEventFor(hookName, input);
6635
+ } catch {
6636
+ return;
6637
+ }
4734
6638
  if (!event) return;
4735
6639
  try {
4736
6640
  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;
4737
6641
  const promptSource = event === "prompt_submitted" ? (0, import_tool_kit9.getString)(input, ["promptSource", "prompt_source"]) : void 0;
4738
6642
  const queued = promptSource === void 0 ? void 0 : promptSource === "queued";
6643
+ const backgroundTasks = event === "stop" ? countBackgroundTasks(input) : void 0;
6644
+ const errorKind = hookName === "StopFailure" && event === "halted" ? (0, import_tool_kit9.getString)(input, ["error"]) === "rate_limit" ? "rate_limit" : "error" : void 0;
6645
+ const resumesAt = errorKind === "rate_limit" ? usageLimitResumesAt(input) : void 0;
6646
+ const agent = (0, import_tool_kit9.findAgentProcess)(import_tool_kit9.AGENT_PROCESS.claude_code);
6647
+ const hookSet = (0, import_tool_kit9.readHookSet)(process.argv);
6648
+ const viaPlugin = (0, import_tool_kit9.readViaPlugin)(process.env);
4739
6649
  await (0, import_tool_kit9.emitLiveSignal)({
4740
6650
  tool: process.env.ASCENDA_TOOL_TYPE ?? "claude_code",
4741
6651
  // Concurrent sessions must count as separate streams for the X gauge.
@@ -4743,13 +6653,43 @@ async function emitLive(hookName, input) {
4743
6653
  // this process's parent — still per-session in practice, since Claude
4744
6654
  // Code spawns hooks from the session process.
4745
6655
  session: (0, import_tool_kit9.getString)(input, ["session_id", "sessionId"]) ?? process.env.ASCENDA_SESSION_ID ?? `ppid-${process.ppid}`,
6656
+ ...(0, import_tool_kit9.livePidFields)(agent),
4746
6657
  event,
4747
6658
  ...prompt !== void 0 ? { sizeBucket: (0, import_tool_kit9.bucketPromptSize)(prompt) } : {},
4748
- ...queued !== void 0 ? { queued } : {}
6659
+ ...queued !== void 0 ? { queued } : {},
6660
+ ...backgroundTasks !== void 0 ? { backgroundTasks } : {},
6661
+ ...hookSet !== void 0 ? { hookSet } : {},
6662
+ ...viaPlugin === true ? { viaPlugin } : {},
6663
+ ...errorKind !== void 0 ? { errorKind } : {},
6664
+ ...resumesAt !== void 0 ? { resumesAt } : {}
4749
6665
  });
4750
6666
  } catch {
4751
6667
  }
4752
6668
  }
6669
+ function usageLimitResumesAt(input) {
6670
+ const projectDir = process.env.CLAUDE_PROJECT_DIR ?? (0, import_tool_kit9.getString)(input, ["cwd"]);
6671
+ if (!autoContinueEnabled({ projectDir })) return void 0;
6672
+ const now = /* @__PURE__ */ new Date();
6673
+ const texts = [
6674
+ (0, import_tool_kit9.getString)(input, ["error_details"]),
6675
+ (0, import_tool_kit9.getNestedString)(input, [["error_details", "message"]]),
6676
+ (0, import_tool_kit9.getString)(input, ["last_assistant_message"])
6677
+ ];
6678
+ for (const text of texts) {
6679
+ const at = resumesAtFor(text, now);
6680
+ if (at !== void 0) return at;
6681
+ }
6682
+ return void 0;
6683
+ }
6684
+ function countBackgroundTasks(input) {
6685
+ const tasks = input.background_tasks;
6686
+ if (!Array.isArray(tasks)) return void 0;
6687
+ return tasks.filter((task) => {
6688
+ const status = task && typeof task === "object" ? task.status : void 0;
6689
+ return typeof status !== "string" || !ENDED_TASK_STATUSES.has(status);
6690
+ }).length;
6691
+ }
6692
+ var ENDED_TASK_STATUSES = /* @__PURE__ */ new Set(["completed", "failed", "killed", "stopped", "cancelled"]);
4753
6693
  function pendingFailureNotice(hookName) {
4754
6694
  if (hookName !== "SessionStart" && hookName !== "PostToolUse") return void 0;
4755
6695
  if (process.env.ASCENDA_DISABLE_FAILURE_NOTICE === "true") return void 0;
@@ -4794,6 +6734,7 @@ function writeStdout(text) {
4794
6734
  async function runDoctor() {
4795
6735
  const lines = ["Ascenda collector doctor", ""];
4796
6736
  const apiBaseUrl = (process.env.ASCENDA_API_BASE_URL ?? "https://api.ascenda.one").replace(/\/$/, "");
6737
+ const unpaired = localOnlyInstall();
4797
6738
  lines.push(` API base URL ${apiBaseUrl}`);
4798
6739
  let resolved;
4799
6740
  try {
@@ -4811,12 +6752,14 @@ async function runDoctor() {
4811
6752
  lines.push(` Id source ${describeIdSource(resolved)}`);
4812
6753
  const tokenFilePath = process.env.ASCENDA_EVENT_WRITE_TOKEN_FILE ?? (0, import_tool_kit9.defaultTokenFilePath)(toolInstallationId);
4813
6754
  lines.push(` Token file ${tokenFilePath}`);
4814
- lines.push(` Token ${describeToken(tokenFilePath)}`);
6755
+ lines.push(` Token ${describeToken(tokenFilePath, unpaired)}`);
6756
+ const hasToken = fs4.existsSync(tokenFilePath) || Boolean(process.env.ASCENDA_EVENT_WRITE_TOKEN);
6757
+ lines.push(` Mode ${unpaired ? "installed, not paired \u2014 local features active, telemetry inactive" : hasToken ? "paired \u2014 local features and telemetry active" : "paired, but no token on this machine \u2014 local features active, nothing can be sent"}`);
4815
6758
  const stateFilePath = resolveStateFilePath(toolInstallationId);
4816
6759
  lines.push(` Journal ${stateFilePath}`);
4817
6760
  const state = (0, import_tool_kit9.readCollectorState)(stateFilePath);
4818
6761
  if (!state) {
4819
- lines.push(" Last outcome (no journal yet \u2014 no send attempted since this version was installed)");
6762
+ lines.push(unpaired ? " Last outcome (none \u2014 nothing is sent from an install with no pairing)" : " Last outcome (no journal yet \u2014 no send attempted since this version was installed)");
4820
6763
  } else {
4821
6764
  lines.push(` Last attempt ${state.lastAttemptAt}`);
4822
6765
  lines.push(` Last success ${state.lastSuccessAt ?? "never"}`);
@@ -4828,6 +6771,18 @@ async function runDoctor() {
4828
6771
  }
4829
6772
  lines.push(...skippedSendLines(stateFilePath));
4830
6773
  lines.push(...outboxLines(toolInstallationId, state));
6774
+ if (unpaired) {
6775
+ lines.push(
6776
+ "",
6777
+ " Nothing is sent from this install, and nothing is queued for later. The",
6778
+ " session prompts and the live signal to a socket on this machine run",
6779
+ " without a pairing. To turn delivery on:",
6780
+ " npx @ascenda-one/claude-code-hooks pair"
6781
+ );
6782
+ await writeStdout(`${lines.join("\n")}
6783
+ `);
6784
+ return;
6785
+ }
4831
6786
  lines.push("", " Live round trip...");
4832
6787
  lines.push(` ${await liveRoundTrip()}`);
4833
6788
  await writeStdout(`${lines.join("\n")}
@@ -4897,12 +6852,13 @@ function describeAge(isoTimestamp) {
4897
6852
  if (hours < 48) return `${hours}h ${minutes % 60}m`;
4898
6853
  return `${Math.floor(hours / 24)}d ${hours % 24}h`;
4899
6854
  }
4900
- function describeToken(tokenFilePath) {
6855
+ function describeToken(tokenFilePath, unpaired) {
4901
6856
  try {
4902
- if (!fs2.existsSync(tokenFilePath)) {
4903
- return process.env.ASCENDA_EVENT_WRITE_TOKEN ? "from ASCENDA_EVENT_WRITE_TOKEN (no file)" : "MISSING \u2014 run `pair`";
6857
+ if (!fs4.existsSync(tokenFilePath)) {
6858
+ if (process.env.ASCENDA_EVENT_WRITE_TOKEN) return "from ASCENDA_EVENT_WRITE_TOKEN (no file)";
6859
+ return unpaired ? "none \u2014 this install has no pairing" : "MISSING \u2014 run `pair`";
4904
6860
  }
4905
- const stat = fs2.statSync(tokenFilePath);
6861
+ const stat = fs4.statSync(tokenFilePath);
4906
6862
  const ageDays = Math.floor((Date.now() - stat.mtimeMs) / 864e5);
4907
6863
  return `present, last written ${stat.mtime.toISOString()} (${ageDays}d ago)`;
4908
6864
  } catch (error) {