@ascenda-one/github-collector 0.1.35 → 0.1.36

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
@@ -149,25 +149,66 @@ var require_gitActionClassifier = __commonJS({
149
149
  if (!/\bgit\b/.test(value))
150
150
  return void 0;
151
151
  const heads = (0, commandHeads_1.commandHeads)(value);
152
- if (heads.some((h) => /^git\s+commit\b/.test(h) && /\s--amend\b/.test(h)))
152
+ const commands = heads.map(parseGitCommand).filter((c) => c !== void 0);
153
+ if (commands.some((c) => c.verb === "commit" && c.args.includes("--amend")))
153
154
  return "amend";
154
- if (heads.some((h) => /^git\s+revert\b/.test(h)))
155
+ if (commands.some((c) => c.verb === "revert"))
155
156
  return "revert";
156
- if (heads.some((h) => /^git\s+reset\b/.test(h) && /\s--hard\b/.test(h)))
157
+ if (commands.some((c) => c.verb === "reset" && c.args.includes("--hard")))
157
158
  return "reset_hard";
158
- if (heads.some((h) => /^git\s+restore\b/.test(h) && !/\s--staged\b/.test(h)))
159
+ if (commands.some(discardsWork))
159
160
  return "restore";
160
- if (heads.some((h) => /^git\s+checkout\b.*\s--\s/.test(h)))
161
- return "restore";
162
- if (heads.some((h) => /^git\s+push\b/.test(h)))
161
+ if (commands.some((c) => c.verb === "push"))
163
162
  return "push";
164
- if (heads.some((h) => /^git\s+commit\b/.test(h)))
163
+ if (commands.some((c) => c.verb === "commit"))
165
164
  return "commit";
166
165
  return void 0;
167
166
  }
168
167
  function isReworkGitAction(action) {
169
168
  return action === "revert" || action === "reset_hard" || action === "restore";
170
169
  }
170
+ var GLOBAL_OPTIONS_WITH_VALUE = /* @__PURE__ */ new Set(["-c", "--git-dir", "--work-tree", "--namespace", "--super-prefix", "--config-env", "--exec-path"]);
171
+ function parseGitCommand(head) {
172
+ const words = head.split(/\s+/);
173
+ if (words[0] !== "git")
174
+ return void 0;
175
+ let i = 1;
176
+ while (i < words.length && words[i].startsWith("-")) {
177
+ i += GLOBAL_OPTIONS_WITH_VALUE.has(words[i]) ? 2 : 1;
178
+ }
179
+ if (i >= words.length)
180
+ return void 0;
181
+ return { verb: words[i], args: words.slice(i + 1) };
182
+ }
183
+ function discardsWork({ verb, args }) {
184
+ switch (verb) {
185
+ case "restore":
186
+ return !args.includes("--staged");
187
+ case "switch":
188
+ return args.includes("--discard-changes") || args.includes("--force") || args.includes("-f");
189
+ case "clean": {
190
+ const flags = args.filter((a) => /^-[a-z]+$/.test(a)).join("");
191
+ const dryRun = args.includes("--dry-run") || flags.includes("n");
192
+ return !dryRun && (args.includes("--force") || flags.includes("f"));
193
+ }
194
+ case "checkout":
195
+ return checkoutDiscards(args);
196
+ default:
197
+ return false;
198
+ }
199
+ }
200
+ function checkoutDiscards(args) {
201
+ if (args.includes("--"))
202
+ return true;
203
+ if (args.some((a) => ["-b", "--orphan", "--detach", "-d", "-t", "--track", "-B"].includes(a)))
204
+ return false;
205
+ const words = args.filter((a) => !a.startsWith("-"));
206
+ if (words.length >= 2)
207
+ return true;
208
+ if (words.length === 1)
209
+ return /^\.{1,2}(\/|$)|\/$|[*?]|\.[a-z][a-z0-9]*$/.test(words[0]);
210
+ return false;
211
+ }
171
212
  }
172
213
  });
173
214
 
@@ -178,6 +219,7 @@ var require_workMilestoneClassifier = __commonJS({
178
219
  Object.defineProperty(exports, "__esModule", { value: true });
179
220
  exports.classifyWorkMilestone = classifyWorkMilestone;
180
221
  exports.invitesDebrief = invitesDebrief;
222
+ exports.classifyMcpWorkMilestone = classifyMcpWorkMilestone;
181
223
  var commandHeads_1 = require_commandHeads();
182
224
  function classifyWorkMilestone(command) {
183
225
  if (!command)
@@ -197,6 +239,41 @@ var require_workMilestoneClassifier = __commonJS({
197
239
  function invitesDebrief(kind) {
198
240
  return kind === "pr_merged" || kind === "issue_closed";
199
241
  }
242
+ function classifyMcpWorkMilestone(toolName) {
243
+ if (!toolName)
244
+ return void 0;
245
+ const parts = toolName.toLowerCase().split("__");
246
+ if (parts[0] !== "mcp" || parts.length < 3)
247
+ return void 0;
248
+ const tool = parts[parts.length - 1].replace(/[^a-z0-9]/g, "");
249
+ if (/^(merge|accept)(pullrequest|mergerequest)$/.test(tool))
250
+ return "pr_merged";
251
+ if (/^closeissue$/.test(tool))
252
+ return "issue_closed";
253
+ if (/^(create|open)(pullrequest|mergerequest)$/.test(tool))
254
+ return "pr_opened";
255
+ return void 0;
256
+ }
257
+ }
258
+ });
259
+
260
+ // ../packages/tool-kit/out/shellFacts.js
261
+ var require_shellFacts = __commonJS({
262
+ "../packages/tool-kit/out/shellFacts.js"(exports) {
263
+ "use strict";
264
+ Object.defineProperty(exports, "__esModule", { value: true });
265
+ exports.shellCommandFacts = shellCommandFacts;
266
+ var gitActionClassifier_1 = require_gitActionClassifier();
267
+ var workMilestoneClassifier_1 = require_workMilestoneClassifier();
268
+ function shellCommandFacts(command) {
269
+ const gitAction = (0, gitActionClassifier_1.classifyGitAction)(command);
270
+ const milestoneKind = (0, workMilestoneClassifier_1.classifyWorkMilestone)(command);
271
+ return {
272
+ ...gitAction !== void 0 ? { gitAction } : {},
273
+ ...(0, gitActionClassifier_1.isReworkGitAction)(gitAction) ? { activity: "rework_reversion" } : {},
274
+ ...milestoneKind !== void 0 ? { milestoneKind } : {}
275
+ };
276
+ }
200
277
  }
201
278
  });
202
279
 
@@ -590,6 +667,61 @@ var require_metricKeys = __commonJS({
590
667
  subagentAssistantTurns: { family: "counts", readBy: ["diagnostic"] },
591
668
  subagentPrompts: { family: "counts", readBy: ["diagnostic"] },
592
669
  subagentTokensTotal: { family: "context", readBy: ["diagnostic"] },
670
+ advisorMessageCount: {
671
+ family: "counts",
672
+ readBy: ["diagnostic"],
673
+ note: "Claude Code only: advisor calls (a second model consulted inside one API message). Their tokens and models are already folded into the session totals and model mix, and this is the receipt for how much of that they are."
674
+ },
675
+ advisorTokensTotal: {
676
+ family: "context",
677
+ readBy: ["diagnostic"],
678
+ unit: "tokens",
679
+ note: "Claude Code only: input, output and cache tokens spent by advisor calls. A part of the session totals, not an addition to them."
680
+ },
681
+ cacheCreationTokens: {
682
+ family: "context",
683
+ readBy: ["diagnostic"],
684
+ unit: "tokens",
685
+ note: "Prompt-cache writes, summed once per API message. Absent where the store never wrote the figure, which is not the same as none written."
686
+ },
687
+ cacheCreation5mTokens: {
688
+ family: "context",
689
+ readBy: ["diagnostic"],
690
+ unit: "tokens",
691
+ note: "The part of cacheCreationTokens written with the 5-minute lifetime. Absent on transcripts that only record the total."
692
+ },
693
+ cacheCreation1hTokens: {
694
+ family: "context",
695
+ readBy: ["diagnostic"],
696
+ unit: "tokens",
697
+ note: "The part of cacheCreationTokens written with the 1-hour lifetime. Absent on transcripts that only record the total."
698
+ },
699
+ headlessPromptLines: {
700
+ family: "reading",
701
+ readBy: ["diagnostic"],
702
+ unit: "lines",
703
+ note: "Claude Code only: user lines written by the Agent SDK or a headless run (entrypoint sdk-*). Nobody typed them, so promptCount leaves them out. Counted once per line across the store."
704
+ },
705
+ tokensNotCollected: {
706
+ family: "context",
707
+ readBy: ["diagnostic"],
708
+ note: "True when the store recorded no token figures for this session (Cursor builds that write a zero tokenCount, Codex rollouts from before token_count events). The token keys are then left off the event instead of being sent as 0, so absent and zero stay apart. Metrics are flat scalars with no null, so a flag beside the missing keys is the marker the contract allows."
709
+ },
710
+ unattributedSubagentTranscripts: {
711
+ family: "reading",
712
+ readBy: ["diagnostic"],
713
+ note: "Claude Code only: flat subagent transcripts whose lines name no parent session, so they could not be folded anywhere."
714
+ },
715
+ duplicateChatSessions: {
716
+ family: "reading",
717
+ readBy: ["diagnostic"],
718
+ note: "VS Code only: chat sessions seen in more than one place (a transferred session also in a workspace). Counted once."
719
+ },
720
+ sessionsStartedFromBubble: {
721
+ family: "reading",
722
+ readBy: ["diagnostic"],
723
+ note: "Cursor only: sessions whose start is the earliest message rather than the header's createdAt, which can sit months before anyone typed."
724
+ },
593
725
  toolName: {
594
726
  family: "tools",
595
727
  readBy: ["backend"],
@@ -697,7 +829,9 @@ var require_out = __commonJS({
697
829
  exports.COLLABORATION_EVENT_TYPES = [
698
830
  "review_requested_of_me",
699
831
  "review_given",
700
- "pull_request_opened"
832
+ "pull_request_opened",
833
+ "pull_request_closed",
834
+ "pull_request_merged"
701
835
  ];
702
836
  exports.EVENT_METADATA_DISCLOSURE = {
703
837
  language: "edits",
@@ -709,6 +843,13 @@ var require_out = __commonJS({
709
843
  gitAction: "git",
710
844
  milestoneKind: "git",
711
845
  branchHash: "repo",
846
+ repoKey: "forge",
847
+ headRepoKey: "forge",
848
+ prCreatedAt: "git",
849
+ prClosedAt: "git",
850
+ prMergedAt: "git",
851
+ branchKey: "forge",
852
+ promptId: "turns",
712
853
  autonomyMode: "posture",
713
854
  modelClass: "model",
714
855
  modelId: "model",
@@ -758,6 +899,13 @@ var require_out = __commonJS({
758
899
  "gitAction",
759
900
  "milestoneKind",
760
901
  "branchHash",
902
+ "repoKey",
903
+ "headRepoKey",
904
+ "prCreatedAt",
905
+ "prClosedAt",
906
+ "prMergedAt",
907
+ "branchKey",
908
+ "promptId",
761
909
  "autonomyMode",
762
910
  "modelClass",
763
911
  "modelId",
@@ -827,6 +975,10 @@ var require_out = __commonJS({
827
975
  review_requested_of_me: "supervision",
828
976
  review_given: "supervision",
829
977
  pull_request_opened: "creation",
978
+ // Where a pull request of yours ended up. A boundary like a turn ending, not
979
+ // work in itself, so neutral: it must not weigh on any workload leg.
980
+ pull_request_closed: "neutral",
981
+ pull_request_merged: "neutral",
830
982
  context_pressure_high: "risk",
831
983
  agent_loop_long: "risk",
832
984
  after_hours_ai_session: "risk",
@@ -857,6 +1009,16 @@ var require_out = __commonJS({
857
1009
  // step toward an interruption count becoming a score, a streak, or something
858
1010
  // that fires on a miss. It must never become any of those.
859
1011
  supervision_interruption: "supervision",
1012
+ // The agent asked to run a tool, and the auto-mode classifier refused one.
1013
+ // Claude Code's `PermissionRequest` and `PermissionDenied` hooks. Neutral,
1014
+ // because the Notification for the same prompt is already counted above as
1015
+ // `supervision_interruption`, and counting both would weigh one prompt
1016
+ // twice. These rows exist for the public event stream: which tool asked, and
1017
+ // under which posture. `permission_requested` fires before the person
1018
+ // answers and no hook reports their answer, so neither event says whether
1019
+ // the request was granted.
1020
+ permission_requested: "neutral",
1021
+ permission_denied: "neutral",
860
1022
  // Semantic (agent-observed) — see SEMANTIC_WORK_SIGNAL_EVENT_TYPES.
861
1023
  approach_churn_detected: "risk",
862
1024
  goal_drift_detected: "risk",
@@ -981,122 +1143,13 @@ var require_collectorVersion = __commonJS({
981
1143
  exports.COLLECTOR_VERSION = exports.UNRELEASED_COLLECTOR_VERSION = void 0;
982
1144
  exports.describeCollectorVersion = describeCollectorVersion;
983
1145
  exports.UNRELEASED_COLLECTOR_VERSION = "unreleased";
984
- exports.COLLECTOR_VERSION = "0.1.35" ? "0.1.35" : exports.UNRELEASED_COLLECTOR_VERSION;
1146
+ exports.COLLECTOR_VERSION = "0.1.36" ? "0.1.36" : exports.UNRELEASED_COLLECTOR_VERSION;
985
1147
  function describeCollectorVersion(version = exports.COLLECTOR_VERSION) {
986
1148
  return version === exports.UNRELEASED_COLLECTOR_VERSION ? `${version} (built from a checkout, not a release)` : version;
987
1149
  }
988
1150
  }
989
1151
  });
990
1152
 
991
- // ../packages/agent-events/out/index.js
992
- var require_out2 = __commonJS({
993
- "../packages/agent-events/out/index.js"(exports) {
994
- "use strict";
995
- Object.defineProperty(exports, "__esModule", { value: true });
996
- exports.KNOWN_AGENTS = exports.AGENT_EVENT_KINDS = exports.AGENT_EVENT_SCHEMA = void 0;
997
- exports.isAgentEventV0 = isAgentEventV0;
998
- exports.parseEventLogLine = parseEventLogLine;
999
- exports.normaliseKind = normaliseKind;
1000
- exports.AGENT_EVENT_SCHEMA = "agent-event/v0";
1001
- exports.AGENT_EVENT_KINDS = [
1002
- "session.started",
1003
- "session.ended",
1004
- "prompt.submitted",
1005
- "tool.started",
1006
- "tool.completed",
1007
- "tool.failed",
1008
- "turn.completed",
1009
- "agent.waiting",
1010
- "context.compacted",
1011
- "subagent.started",
1012
- "subagent.stopped",
1013
- "other"
1014
- ];
1015
- exports.KNOWN_AGENTS = ["claude_code", "codex", "cursor", "gemini_cli", "windsurf", "vscode"];
1016
- function isAgentEventV0(value) {
1017
- if (!value || typeof value !== "object")
1018
- return false;
1019
- const e = value;
1020
- return e.schema === exports.AGENT_EVENT_SCHEMA && typeof e.id === "string" && e.id.length > 0 && typeof e.time === "string" && !Number.isNaN(Date.parse(e.time)) && typeof e.agent === "string" && e.agent.length > 0 && typeof e.kind === "string";
1021
- }
1022
- function parseEventLogLine(line) {
1023
- if (!line.trim())
1024
- return void 0;
1025
- try {
1026
- const parsed = JSON.parse(line);
1027
- return isAgentEventV0(parsed?.event) ? parsed.event : void 0;
1028
- } catch {
1029
- return void 0;
1030
- }
1031
- }
1032
- function normaliseKind(kind) {
1033
- return exports.AGENT_EVENT_KINDS.includes(kind) ? kind : "other";
1034
- }
1035
- }
1036
- });
1037
-
1038
- // ../packages/tool-kit/out/agentEvent.js
1039
- var require_agentEvent = __commonJS({
1040
- "../packages/tool-kit/out/agentEvent.js"(exports) {
1041
- "use strict";
1042
- Object.defineProperty(exports, "__esModule", { value: true });
1043
- exports.toAgentEvent = toAgentEvent;
1044
- var agent_events_1 = require_out2();
1045
- var KIND_BY_TYPE = {
1046
- create_focus_session: "session.started",
1047
- recovery_offline_period: "session.ended",
1048
- ai_prompt_submitted: "prompt.submitted",
1049
- ai_tool_call_started: "tool.started",
1050
- ai_tool_call_completed: "tool.completed",
1051
- ai_file_write: "tool.completed",
1052
- ai_file_edit: "tool.completed",
1053
- editor_verification_activity: "tool.completed",
1054
- ai_tool_call_failed: "tool.failed",
1055
- compile_error: "tool.failed",
1056
- tool_failure: "tool.failed",
1057
- ai_turn_completed: "turn.completed",
1058
- supervision_interruption: "agent.waiting",
1059
- context_compression_manual: "context.compacted",
1060
- context_compression_auto: "context.compacted",
1061
- subagent_started: "subagent.started",
1062
- subagent_stopped: "subagent.stopped"
1063
- };
1064
- function agentOf(payload) {
1065
- const host = stringField(payload.metadata?.host);
1066
- if (host)
1067
- return host;
1068
- return payload.source === "vscode_extension" ? "vscode" : payload.source;
1069
- }
1070
- function stringField(value) {
1071
- return typeof value === "string" && value.length > 0 ? value : void 0;
1072
- }
1073
- function toAgentEvent(payload) {
1074
- const metadata = payload.metadata ?? {};
1075
- const kind = KIND_BY_TYPE[payload.eventType] ?? "other";
1076
- const tool = kind.startsWith("tool.") ? stringField(metadata.toolName) : void 0;
1077
- const outcome = stringField(metadata.outcome);
1078
- return {
1079
- schema: agent_events_1.AGENT_EVENT_SCHEMA,
1080
- id: payload.idempotencyKey ?? `${payload.toolInstallationId}:${payload.occurredAt}:${payload.eventType}`,
1081
- time: payload.occurredAt,
1082
- // `+ 0` turns the -0 a UTC machine computes into 0, which is what JSON
1083
- // writes anyway; without it the event in memory and the one on disk differ.
1084
- ...typeof payload.utcOffsetMinutes === "number" ? { utcOffsetMinutes: payload.utcOffsetMinutes + 0 } : {},
1085
- agent: agentOf(payload),
1086
- kind,
1087
- ...stringField(payload.sessionId) ? { sessionId: payload.sessionId } : {},
1088
- ...stringField(metadata.subagentId) ? { subagentId: metadata.subagentId } : {},
1089
- ...tool ? { tool } : {},
1090
- ...outcome && outcome !== "unknown" ? { outcome } : {},
1091
- ...stringField(metadata.durationBucket) ? { durationBucket: metadata.durationBucket } : {},
1092
- ...stringField(payload.projectHash) ? { projectHash: payload.projectHash } : {},
1093
- ...stringField(metadata.collectorVersion) ? { collectorVersion: metadata.collectorVersion } : {},
1094
- sourceType: payload.eventType
1095
- };
1096
- }
1097
- }
1098
- });
1099
-
1100
1153
  // ../packages/tool-kit/out/tokenStore.js
1101
1154
  var require_tokenStore = __commonJS({
1102
1155
  "../packages/tool-kit/out/tokenStore.js"(exports) {
@@ -1235,9 +1288,9 @@ var require_tokenStore = __commonJS({
1235
1288
  }
1236
1289
  });
1237
1290
 
1238
- // ../packages/tool-kit/out/credentials.js
1239
- var require_credentials = __commonJS({
1240
- "../packages/tool-kit/out/credentials.js"(exports) {
1291
+ // ../packages/tool-kit/out/stateStore.js
1292
+ var require_stateStore = __commonJS({
1293
+ "../packages/tool-kit/out/stateStore.js"(exports) {
1241
1294
  "use strict";
1242
1295
  var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
1243
1296
  if (k2 === void 0) k2 = k;
@@ -1277,94 +1330,124 @@ var require_credentials = __commonJS({
1277
1330
  };
1278
1331
  }();
1279
1332
  Object.defineProperty(exports, "__esModule", { value: true });
1280
- exports.credentialsFilePath = credentialsFilePath;
1281
- exports.readMachineCredentials = readMachineCredentials;
1282
- exports.writeMachineCredentials = writeMachineCredentials;
1283
- exports.writeTopLevelCredentials = writeTopLevelCredentials;
1284
- exports.writeEventLogSetting = writeEventLogSetting;
1285
- exports.isLocalOnlyHostInstall = isLocalOnlyHostInstall;
1286
- exports.readHostCredentials = readHostCredentials;
1287
- exports.writeHostCredentials = writeHostCredentials;
1288
- exports.removeHostCredentials = removeHostCredentials;
1333
+ exports.defaultStateFilePath = defaultStateFilePath;
1334
+ exports.unresolvedToolInstallationId = unresolvedToolInstallationId;
1335
+ exports.unresolvedStateFilePath = unresolvedStateFilePath;
1336
+ exports.readCollectorState = readCollectorState;
1337
+ exports.recordSendOutcome = recordSendOutcome;
1338
+ exports.recordOutboxDiscard = recordOutboxDiscard;
1339
+ exports.shouldAnnounceFailure = shouldAnnounceFailure;
1340
+ exports.markFailureNotified = markFailureNotified;
1289
1341
  var fs = __importStar(__require("fs"));
1290
1342
  var path = __importStar(__require("path"));
1291
1343
  var tokenStore_1 = require_tokenStore();
1292
- function credentialsFilePath() {
1293
- return path.join((0, tokenStore_1.ascendaHome)(), "credentials.json");
1344
+ function defaultStateFilePath(toolInstallationId) {
1345
+ const dir = process.env.ASCENDA_STATE_DIR?.trim();
1346
+ const base2 = dir ? dir : path.join((0, tokenStore_1.ascendaHome)(), "state");
1347
+ return path.join(base2, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.json`);
1294
1348
  }
1295
- function readMachineCredentials() {
1349
+ function unresolvedToolInstallationId(toolType) {
1350
+ return `${toolType}:unresolved`;
1351
+ }
1352
+ function unresolvedStateFilePath(toolType) {
1353
+ return defaultStateFilePath(unresolvedToolInstallationId(toolType));
1354
+ }
1355
+ function readCollectorState(stateFilePath) {
1296
1356
  try {
1297
- const raw = fs.readFileSync(credentialsFilePath(), "utf8").trim();
1357
+ if (!fs.existsSync(stateFilePath))
1358
+ return void 0;
1359
+ const raw = fs.readFileSync(stateFilePath, "utf8").trim();
1298
1360
  if (!raw)
1299
1361
  return void 0;
1300
1362
  const parsed = JSON.parse(raw);
1301
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
1363
+ if (!parsed || typeof parsed !== "object")
1302
1364
  return void 0;
1303
1365
  return parsed;
1304
1366
  } catch {
1305
1367
  return void 0;
1306
1368
  }
1307
1369
  }
1308
- function writeMachineCredentials(credentials) {
1309
- const file = credentialsFilePath();
1310
- fs.mkdirSync(path.dirname(file), { recursive: true, mode: 448 });
1311
- fs.writeFileSync(file, `${JSON.stringify(credentials, null, 2)}
1312
- `, { encoding: "utf8", mode: 384 });
1313
- if (process.platform !== "win32") {
1314
- fs.chmodSync(path.dirname(file), 448);
1315
- fs.chmodSync(file, 384);
1316
- }
1317
- }
1318
- function writeTopLevelCredentials(credentials) {
1319
- const existing = readMachineCredentials();
1320
- const eventLogPath = credentials.eventLogPath ?? existing?.eventLogPath;
1321
- writeMachineCredentials({
1322
- ...credentials,
1323
- ...eventLogPath ? { eventLogPath } : {},
1324
- ...existing?.tools ? { tools: existing.tools } : {}
1325
- });
1370
+ function recordSendOutcome(stateFilePath, toolInstallationId, outcome, detail = {}) {
1371
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1372
+ const previous = readCollectorState(stateFilePath);
1373
+ const accepted = outcome === "accepted";
1374
+ const next = {
1375
+ toolInstallationId,
1376
+ lastAttemptAt: now,
1377
+ lastSuccessAt: accepted ? now : previous?.lastSuccessAt,
1378
+ lastOutcome: outcome,
1379
+ consecutiveFailures: accepted ? 0 : (previous?.consecutiveFailures ?? 0) + 1,
1380
+ ...detail.httpStatus !== void 0 ? { httpStatus: detail.httpStatus } : {},
1381
+ ...detail.errorCode !== void 0 ? { errorCode: detail.errorCode } : {},
1382
+ ...detail.detail !== void 0 ? { detail: truncate(detail.detail) } : {},
1383
+ // A success closes the episode; a failure either opens one or continues
1384
+ // the one already open. Carrying `notifiedFailingSince` across a
1385
+ // continuing episode is what keeps the notice to once per outage.
1386
+ ...accepted ? {} : { failingSince: previous?.failingSince ?? now },
1387
+ ...accepted ? {} : previous?.notifiedFailingSince !== void 0 ? { notifiedFailingSince: previous.notifiedFailingSince } : {},
1388
+ // Cumulative by design: a send outcome, success included, never erases
1389
+ // the record of what the outbox had to throw away.
1390
+ ...previous?.outboxDiscarded !== void 0 ? { outboxDiscarded: previous.outboxDiscarded } : {}
1391
+ };
1392
+ writeStateFile(stateFilePath, next);
1393
+ return next;
1326
1394
  }
1327
- function writeEventLogSetting(value) {
1328
- const existing = readMachineCredentials() ?? {};
1329
- writeMachineCredentials({ ...existing, eventLogPath: value });
1395
+ function recordOutboxDiscard(stateFilePath, toolInstallationId, discard) {
1396
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1397
+ const previous = readCollectorState(stateFilePath);
1398
+ const next = {
1399
+ ...previous ?? { lastAttemptAt: now, consecutiveFailures: 0 },
1400
+ toolInstallationId,
1401
+ lastOutcome: "outbox_discarded",
1402
+ outboxDiscarded: {
1403
+ total: (previous?.outboxDiscarded?.total ?? 0) + discard.count,
1404
+ lastAt: now,
1405
+ lastCount: discard.count,
1406
+ lastReasons: discard.reasons,
1407
+ ...discard.oldestQueuedAt !== void 0 ? { lastOldestQueuedAt: discard.oldestQueuedAt } : {}
1408
+ }
1409
+ };
1410
+ writeStateFile(stateFilePath, next);
1411
+ return next;
1330
1412
  }
1331
- function isLocalOnlyHostInstall(host, hasToken) {
1332
- const credentials = readHostCredentials(host);
1333
- if (!credentials?.localOnly)
1334
- return false;
1335
- if (process.env.ASCENDA_EVENT_WRITE_TOKEN)
1413
+ function shouldAnnounceFailure(state) {
1414
+ if (!state || state.consecutiveFailures === 0 || !state.failingSince)
1336
1415
  return false;
1337
- return !(credentials.toolInstallationId && hasToken(credentials.toolInstallationId));
1416
+ return state.notifiedFailingSince !== state.failingSince;
1338
1417
  }
1339
- function readHostCredentials(host) {
1340
- const entry = readMachineCredentials()?.tools?.[host];
1341
- if (!entry || typeof entry !== "object" || Array.isArray(entry))
1342
- return void 0;
1343
- return entry;
1418
+ function markFailureNotified(stateFilePath, state) {
1419
+ if (!state.failingSince)
1420
+ return;
1421
+ writeStateFile(stateFilePath, { ...state, notifiedFailingSince: state.failingSince });
1344
1422
  }
1345
- function writeHostCredentials(host, credentials) {
1346
- const existing = readMachineCredentials() ?? {};
1347
- writeMachineCredentials({ ...existing, tools: { ...existing.tools ?? {}, [host]: credentials } });
1423
+ function writeStateFile(stateFilePath, state) {
1424
+ const temporaryPath = `${stateFilePath}.${process.pid}.tmp`;
1425
+ try {
1426
+ const dir = path.dirname(stateFilePath);
1427
+ fs.mkdirSync(dir, { recursive: true, mode: 448 });
1428
+ fs.writeFileSync(temporaryPath, `${JSON.stringify(state, null, 2)}
1429
+ `, { encoding: "utf8", mode: 384 });
1430
+ fs.renameSync(temporaryPath, stateFilePath);
1431
+ if (process.platform !== "win32")
1432
+ fs.chmodSync(stateFilePath, 384);
1433
+ } catch {
1434
+ try {
1435
+ if (fs.existsSync(temporaryPath))
1436
+ fs.unlinkSync(temporaryPath);
1437
+ } catch {
1438
+ }
1439
+ }
1348
1440
  }
1349
- function removeHostCredentials(host) {
1350
- const existing = readMachineCredentials();
1351
- if (!existing?.tools || !(host in existing.tools))
1352
- return;
1353
- const tools = { ...existing.tools };
1354
- delete tools[host];
1355
- const next = { ...existing };
1356
- if (Object.keys(tools).length)
1357
- next.tools = tools;
1358
- else
1359
- delete next.tools;
1360
- writeMachineCredentials(next);
1441
+ function truncate(value) {
1442
+ const collapsed = value.replace(/\s+/g, " ").trim();
1443
+ return collapsed.length > 200 ? `${collapsed.slice(0, 197)}...` : collapsed;
1361
1444
  }
1362
1445
  }
1363
1446
  });
1364
1447
 
1365
- // ../packages/tool-kit/out/eventLog.js
1366
- var require_eventLog = __commonJS({
1367
- "../packages/tool-kit/out/eventLog.js"(exports) {
1448
+ // ../packages/tool-kit/out/outbox.js
1449
+ var require_outbox = __commonJS({
1450
+ "../packages/tool-kit/out/outbox.js"(exports) {
1368
1451
  "use strict";
1369
1452
  var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
1370
1453
  if (k2 === void 0) k2 = k;
@@ -1404,354 +1487,492 @@ var require_eventLog = __commonJS({
1404
1487
  };
1405
1488
  }();
1406
1489
  Object.defineProperty(exports, "__esModule", { value: true });
1407
- exports.EVENT_LOG_OFF = exports.EVENT_LOG_ENV_VAR = void 0;
1408
- exports.expandUserPath = expandUserPath;
1409
- exports.defaultEventLogPath = defaultEventLogPath;
1410
- exports.resolveEventLog = resolveEventLog;
1411
- exports.resolveEventLogPath = resolveEventLogPath;
1412
- exports.describeEventLog = describeEventLog;
1413
- exports.parseEventLogFlag = parseEventLogFlag;
1414
- exports.appendEventLog = appendEventLog;
1490
+ exports.DEFAULT_OUTBOX_DRAIN_BATCH_SIZE = exports.DEFAULT_OUTBOX_MAX_AGE_MS = exports.DEFAULT_OUTBOX_MAX_ENTRIES = exports.OUTBOX_DRAIN_ENV_VAR = void 0;
1491
+ exports.outboxDrainEnabled = outboxDrainEnabled;
1492
+ exports.defaultOutboxFilePath = defaultOutboxFilePath;
1493
+ exports.appendToOutbox = appendToOutbox;
1494
+ exports.readOutboxSummary = readOutboxSummary;
1495
+ exports.claimOutbox = claimOutbox;
1496
+ exports.enforceOutboxBounds = enforceOutboxBounds;
1415
1497
  var fs = __importStar(__require("fs"));
1416
- var os = __importStar(__require("os"));
1417
1498
  var path = __importStar(__require("path"));
1418
- var agentEvent_1 = require_agentEvent();
1419
- var credentials_1 = require_credentials();
1499
+ var stateStore_1 = require_stateStore();
1420
1500
  var tokenStore_1 = require_tokenStore();
1421
- exports.EVENT_LOG_ENV_VAR = "ASCENDA_EVENT_LOG_FILE";
1422
- exports.EVENT_LOG_OFF = "off";
1423
- var MAX_BYTES = 5 * 1024 * 1024;
1424
- function expandUserPath(configured) {
1425
- const value = configured?.trim();
1426
- if (!value)
1427
- return void 0;
1428
- if (value === "~")
1429
- return os.homedir();
1430
- if (value.startsWith("~/"))
1431
- return path.join(os.homedir(), value.slice(2));
1432
- return path.resolve(value);
1433
- }
1434
- function defaultEventLogPath() {
1435
- return path.join((0, tokenStore_1.ascendaHome)(), "events.jsonl");
1436
- }
1437
- function resolveEventLog(options = {}) {
1438
- for (const [source, raw] of [
1439
- ["env", process.env[exports.EVENT_LOG_ENV_VAR]],
1440
- ["credentials", (0, credentials_1.readMachineCredentials)()?.eventLogPath]
1441
- ]) {
1442
- const value = raw?.trim();
1443
- if (!value)
1444
- continue;
1445
- if (value.toLowerCase() === exports.EVENT_LOG_OFF)
1446
- return { path: void 0, source: "disabled" };
1447
- return { path: expandUserPath(value), source };
1448
- }
1449
- if (options.localOnly)
1450
- return { path: defaultEventLogPath(), source: "unpaired-default" };
1451
- return { path: void 0, source: "off" };
1452
- }
1453
- function resolveEventLogPath(options = {}) {
1454
- return resolveEventLog(options).path;
1455
- }
1456
- function describeEventLog(setting, command) {
1457
- switch (setting.source) {
1458
- case "env":
1459
- return `${setting.path} (from ${exports.EVENT_LOG_ENV_VAR})`;
1460
- case "credentials":
1461
- return `${setting.path} (set by ${command} --event-log)`;
1462
- case "unpaired-default":
1463
- return `${setting.path} (on because this install isn't paired; ${command} --event-log off to stop)`;
1464
- case "disabled":
1465
- return `off (turned off; ${command} --event-log to turn it on)`;
1466
- case "off":
1467
- return `off (${command} --event-log to keep a local copy of every event)`;
1468
- }
1501
+ exports.OUTBOX_DRAIN_ENV_VAR = "ASCENDA_OUTBOX_DRAIN";
1502
+ exports.DEFAULT_OUTBOX_MAX_ENTRIES = 1e4;
1503
+ exports.DEFAULT_OUTBOX_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1e3;
1504
+ exports.DEFAULT_OUTBOX_DRAIN_BATCH_SIZE = 100;
1505
+ var ORPHANED_CLAIM_AGE_MS = 6e4;
1506
+ var CLAIM_SUFFIX = ".draining";
1507
+ function outboxDrainEnabled(env = process.env) {
1508
+ const value = env[exports.OUTBOX_DRAIN_ENV_VAR]?.trim().toLowerCase();
1509
+ if (value === void 0 || value === "")
1510
+ return true;
1511
+ return !(value === "0" || value === "false" || value === "no" || value === "off");
1469
1512
  }
1470
- function parseEventLogFlag(argv, index) {
1471
- const peek = argv[index + 1];
1472
- if (peek !== void 0 && !peek.startsWith("-"))
1473
- return { value: peek, consumed: 1 };
1474
- return { value: defaultEventLogPath(), consumed: 0 };
1513
+ function defaultOutboxFilePath(toolInstallationId) {
1514
+ const dir = path.dirname((0, stateStore_1.defaultStateFilePath)(toolInstallationId));
1515
+ return path.join(dir, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.outbox.jsonl`);
1475
1516
  }
1476
- function appendEventLog(logFilePath, entry) {
1517
+ function appendToOutbox(outboxFilePath, payload, now = /* @__PURE__ */ new Date()) {
1477
1518
  try {
1478
- rotateIfLarge(logFilePath);
1479
- const dir = path.dirname(logFilePath);
1519
+ const dir = path.dirname(outboxFilePath);
1480
1520
  fs.mkdirSync(dir, { recursive: true, mode: 448 });
1481
- const line = { ...entry, event: entry.event ?? (0, agentEvent_1.toAgentEvent)(entry.payload) };
1482
- fs.appendFileSync(logFilePath, `${JSON.stringify(line)}
1521
+ const entry = { queuedAt: now.toISOString(), payload };
1522
+ fs.appendFileSync(outboxFilePath, `${JSON.stringify(entry)}
1483
1523
  `, { encoding: "utf8", mode: 384 });
1484
1524
  if (process.platform !== "win32")
1485
- fs.chmodSync(logFilePath, 384);
1525
+ fs.chmodSync(outboxFilePath, 384);
1526
+ return true;
1486
1527
  } catch {
1528
+ return false;
1487
1529
  }
1488
1530
  }
1489
- function rotateIfLarge(logFilePath) {
1531
+ function readOutboxSummary(outboxFilePath) {
1532
+ const files = [outboxFilePath, ...listClaimFiles(outboxFilePath)].filter((file) => fs.existsSync(file));
1533
+ if (files.length === 0)
1534
+ return void 0;
1535
+ let depth = 0;
1536
+ let unreadableLines = 0;
1537
+ let oldestQueuedAt;
1538
+ for (const file of files) {
1539
+ const { entries, unreadable } = readEntries(file);
1540
+ depth += entries.length;
1541
+ unreadableLines += unreadable;
1542
+ for (const entry of entries) {
1543
+ if (oldestQueuedAt === void 0 || entry.queuedAt < oldestQueuedAt)
1544
+ oldestQueuedAt = entry.queuedAt;
1545
+ }
1546
+ }
1547
+ return { depth, unreadableLines, ...oldestQueuedAt !== void 0 ? { oldestQueuedAt } : {} };
1548
+ }
1549
+ function claimOutbox(outboxFilePath, now = Date.now()) {
1550
+ const claimPath = `${outboxFilePath}.${process.pid}${CLAIM_SUFFIX}`;
1551
+ const claimed = [];
1490
1552
  try {
1491
- if (fs.statSync(logFilePath).size < MAX_BYTES)
1492
- return;
1493
- fs.renameSync(logFilePath, `${logFilePath}.1`);
1553
+ fs.renameSync(outboxFilePath, claimPath);
1554
+ claimed.push(claimPath);
1494
1555
  } catch {
1495
1556
  }
1496
- }
1497
- }
1498
- });
1499
-
1500
- // ../packages/tool-kit/out/http.js
1501
- var require_http = __commonJS({
1502
- "../packages/tool-kit/out/http.js"(exports) {
1503
- "use strict";
1504
- Object.defineProperty(exports, "__esModule", { value: true });
1505
- exports.AscendaApiError = void 0;
1506
- exports.createPairingSession = createPairingSession;
1507
- exports.getPairingStatus = getPairingStatus;
1508
- exports.startStudyJoin = startStudyJoin;
1509
- exports.getStudyJoinStatus = getStudyJoinStatus;
1510
- exports.readInitiatives = readInitiatives;
1511
- exports.readStudyNotices = readStudyNotices;
1512
- exports.setStudyObjection = setStudyObjection;
1513
- exports.markStudyNoticeShown = markStudyNoticeShown;
1514
- exports.renewToolToken = renewToolToken;
1515
- exports.isRetryableStatus = isRetryableStatus;
1516
- exports.postToolEvent = postToolEvent;
1517
- exports.postToolEventsBatch = postToolEventsBatch;
1518
- exports.parseIngestResponse = parseIngestResponse;
1519
- var tool_contract_1 = require_out();
1520
- var AscendaApiError = class extends Error {
1521
- status;
1522
- errorCode;
1523
- constructor(status, errorCode, body) {
1524
- super(body ?? `Ascenda API error ${status}`);
1525
- this.status = status;
1526
- this.errorCode = errorCode;
1527
- this.name = "AscendaApiError";
1557
+ let orphanIndex = 0;
1558
+ for (const orphan of listClaimFiles(outboxFilePath)) {
1559
+ if (claimed.includes(orphan))
1560
+ continue;
1561
+ try {
1562
+ if (now - fs.statSync(orphan).mtimeMs < ORPHANED_CLAIM_AGE_MS)
1563
+ continue;
1564
+ const mine = `${claimPath}.${orphanIndex++}`;
1565
+ fs.renameSync(orphan, mine);
1566
+ claimed.push(mine);
1567
+ } catch {
1568
+ }
1528
1569
  }
1529
- };
1530
- exports.AscendaApiError = AscendaApiError;
1531
- async function createPairingSession(apiBaseUrl, toolInstallationId, toolType, displayName) {
1532
- const response = await fetch(`${apiBaseUrl}/v1/tool-pairing-sessions`, {
1533
- method: "POST",
1534
- headers: { "Content-Type": "application/json" },
1535
- body: JSON.stringify({ toolInstallationId, toolType, displayName })
1536
- });
1537
- if (!response.ok)
1538
- throw new AscendaApiError(response.status, void 0, await response.text());
1539
- return await response.json();
1540
- }
1541
- async function getPairingStatus(apiBaseUrl, pairingSessionId) {
1542
- const response = await fetch(`${apiBaseUrl}/v1/tool-pairing-sessions/${encodeURIComponent(pairingSessionId)}/status`, {
1543
- method: "GET",
1544
- headers: { Accept: "application/json" }
1545
- });
1546
- if (!response.ok)
1547
- throw new AscendaApiError(response.status, void 0, await response.text());
1548
- return await response.json();
1570
+ if (claimed.length === 0)
1571
+ return void 0;
1572
+ const entries = [];
1573
+ let unreadable = 0;
1574
+ for (const file of claimed) {
1575
+ const read = readEntries(file);
1576
+ entries.push(...read.entries);
1577
+ unreadable += read.unreadable;
1578
+ }
1579
+ entries.sort((a, b) => a.queuedAt < b.queuedAt ? -1 : a.queuedAt > b.queuedAt ? 1 : 0);
1580
+ let released = false;
1581
+ return {
1582
+ entries,
1583
+ unreadable,
1584
+ release(remainder) {
1585
+ if (released)
1586
+ return;
1587
+ released = true;
1588
+ if (remainder.length > 0) {
1589
+ try {
1590
+ fs.mkdirSync(path.dirname(outboxFilePath), { recursive: true, mode: 448 });
1591
+ fs.appendFileSync(outboxFilePath, remainder.map((entry) => `${JSON.stringify(entry)}
1592
+ `).join(""), { encoding: "utf8", mode: 384 });
1593
+ if (process.platform !== "win32")
1594
+ fs.chmodSync(outboxFilePath, 384);
1595
+ } catch {
1596
+ return;
1597
+ }
1598
+ }
1599
+ for (const file of claimed) {
1600
+ try {
1601
+ fs.unlinkSync(file);
1602
+ } catch {
1603
+ }
1604
+ }
1605
+ }
1606
+ };
1549
1607
  }
1550
- async function startStudyJoin(apiBaseUrl, eventWriteToken, joinCode, mode) {
1551
- const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions`, {
1552
- method: "POST",
1553
- headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
1554
- body: JSON.stringify({ joinCode, mode })
1555
- });
1556
- if (!response.ok)
1557
- throw await apiError(response);
1558
- return await response.json();
1608
+ function enforceOutboxBounds(entries, bounds, now = Date.now()) {
1609
+ const reasons = {};
1610
+ let oldestQueuedAt;
1611
+ const cutoff = new Date(now - bounds.maxAgeMs).toISOString();
1612
+ const fresh = [];
1613
+ for (const entry of entries) {
1614
+ if (entry.queuedAt < cutoff) {
1615
+ reasons.age = (reasons.age ?? 0) + 1;
1616
+ if (oldestQueuedAt === void 0 || entry.queuedAt < oldestQueuedAt)
1617
+ oldestQueuedAt = entry.queuedAt;
1618
+ } else {
1619
+ fresh.push(entry);
1620
+ }
1621
+ }
1622
+ const excess = Math.max(0, fresh.length - bounds.maxEntries);
1623
+ if (excess > 0) {
1624
+ reasons.count = excess;
1625
+ const first = fresh[0]?.queuedAt;
1626
+ if (first !== void 0 && (oldestQueuedAt === void 0 || first < oldestQueuedAt))
1627
+ oldestQueuedAt = first;
1628
+ }
1629
+ const kept = excess > 0 ? fresh.slice(excess) : fresh;
1630
+ const count = Object.values(reasons).reduce((sum, n) => sum + (n ?? 0), 0);
1631
+ return { kept, discarded: { count, reasons, ...oldestQueuedAt !== void 0 ? { oldestQueuedAt } : {} } };
1559
1632
  }
1560
- async function getStudyJoinStatus(apiBaseUrl, eventWriteToken, joinSessionId) {
1561
- const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions/${encodeURIComponent(joinSessionId)}/status`, {
1562
- method: "GET",
1563
- headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` }
1564
- });
1565
- if (!response.ok)
1566
- throw await apiError(response);
1567
- return await response.json();
1633
+ function listClaimFiles(outboxFilePath) {
1634
+ const dir = path.dirname(outboxFilePath);
1635
+ const prefix = `${path.basename(outboxFilePath)}.`;
1636
+ try {
1637
+ return fs.readdirSync(dir).filter((name) => name.startsWith(prefix) && name.includes(CLAIM_SUFFIX)).map((name) => path.join(dir, name)).sort();
1638
+ } catch {
1639
+ return [];
1640
+ }
1568
1641
  }
1569
- async function readInitiatives(apiBaseUrl, eventWriteToken, signal) {
1570
- let response;
1642
+ function readEntries(file) {
1643
+ let raw;
1571
1644
  try {
1572
- response = await fetch(`${apiBaseUrl}/v1/tool-installations/initiatives`, {
1573
- method: "GET",
1574
- headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` },
1575
- signal
1576
- });
1577
- } catch (error) {
1578
- return { kind: "failed", reason: error instanceof Error && error.name === "TimeoutError" ? "the request timed out" : "the server could not be reached" };
1645
+ raw = fs.readFileSync(file, "utf8");
1646
+ } catch {
1647
+ return { entries: [], unreadable: 0 };
1579
1648
  }
1580
- if (response.status === 401)
1581
- return { kind: "rejected", httpStatus: 401 };
1582
- if (!response.ok)
1583
- return { kind: "failed", reason: `the server answered HTTP ${response.status}` };
1584
- let body;
1649
+ const entries = [];
1650
+ let unreadable = 0;
1651
+ for (const line of raw.split("\n")) {
1652
+ if (!line.trim())
1653
+ continue;
1654
+ try {
1655
+ const parsed = JSON.parse(line);
1656
+ if (!parsed || typeof parsed !== "object" || typeof parsed.queuedAt !== "string" || !parsed.payload || typeof parsed.payload !== "object") {
1657
+ unreadable += 1;
1658
+ continue;
1659
+ }
1660
+ entries.push({ queuedAt: parsed.queuedAt, payload: parsed.payload });
1661
+ } catch {
1662
+ unreadable += 1;
1663
+ }
1664
+ }
1665
+ return { entries, unreadable };
1666
+ }
1667
+ }
1668
+ });
1669
+
1670
+ // ../packages/tool-kit/out/backgroundDelivery.js
1671
+ var require_backgroundDelivery = __commonJS({
1672
+ "../packages/tool-kit/out/backgroundDelivery.js"(exports) {
1673
+ "use strict";
1674
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
1675
+ if (k2 === void 0) k2 = k;
1676
+ var desc = Object.getOwnPropertyDescriptor(m, k);
1677
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
1678
+ desc = { enumerable: true, get: function() {
1679
+ return m[k];
1680
+ } };
1681
+ }
1682
+ Object.defineProperty(o, k2, desc);
1683
+ } : function(o, m, k, k2) {
1684
+ if (k2 === void 0) k2 = k;
1685
+ o[k2] = m[k];
1686
+ });
1687
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
1688
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
1689
+ } : function(o, v) {
1690
+ o["default"] = v;
1691
+ });
1692
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
1693
+ var ownKeys = function(o) {
1694
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
1695
+ var ar = [];
1696
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
1697
+ return ar;
1698
+ };
1699
+ return ownKeys(o);
1700
+ };
1701
+ return function(mod) {
1702
+ if (mod && mod.__esModule) return mod;
1703
+ var result = {};
1704
+ if (mod != null) {
1705
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
1706
+ }
1707
+ __setModuleDefault(result, mod);
1708
+ return result;
1709
+ };
1710
+ }();
1711
+ Object.defineProperty(exports, "__esModule", { value: true });
1712
+ exports.FLUSH_LOCK_FRESH_MS = exports.OUTBOX_FLUSH_COMMAND = exports.HOOK_DELIVERY_ENV_VAR = void 0;
1713
+ exports.hookDeliveryInline = hookDeliveryInline;
1714
+ exports.flushLockPath = flushLockPath;
1715
+ exports.startBackgroundFlush = startBackgroundFlush;
1716
+ exports.runOutboxFlush = runOutboxFlush;
1717
+ var fs = __importStar(__require("fs"));
1718
+ var child_process_1 = __require("child_process");
1719
+ var outbox_1 = require_outbox();
1720
+ exports.HOOK_DELIVERY_ENV_VAR = "ASCENDA_HOOK_DELIVERY";
1721
+ exports.OUTBOX_FLUSH_COMMAND = "__flush-outbox";
1722
+ exports.FLUSH_LOCK_FRESH_MS = 2e4;
1723
+ var FLUSH_MAX_PASSES = 20;
1724
+ var FLUSH_MAX_RUN_MS = 6e4;
1725
+ function hookDeliveryInline(env = process.env) {
1726
+ return env[exports.HOOK_DELIVERY_ENV_VAR]?.trim().toLowerCase() === "inline" || !(0, outbox_1.outboxDrainEnabled)(env);
1727
+ }
1728
+ function flushLockPath(outboxFilePath) {
1729
+ return `${outboxFilePath}.flushing`;
1730
+ }
1731
+ function lockIsFresh(lockPath, now) {
1585
1732
  try {
1586
- body = await response.json();
1733
+ return now - fs.statSync(lockPath).mtimeMs < exports.FLUSH_LOCK_FRESH_MS;
1587
1734
  } catch {
1588
- return { kind: "failed", reason: "the reply was not readable" };
1735
+ return false;
1589
1736
  }
1590
- if (!Array.isArray(body))
1591
- return { kind: "failed", reason: "the reply was not a list" };
1592
- return { kind: "ok", initiatives: body };
1593
1737
  }
1594
- async function readStudyNotices(apiBaseUrl, eventWriteToken, signal) {
1595
- let response;
1738
+ function touchLock(lockPath) {
1596
1739
  try {
1597
- response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices`, {
1598
- method: "GET",
1599
- headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` },
1600
- signal
1601
- });
1602
- } catch (error) {
1603
- return { kind: "failed", reason: error instanceof Error && error.name === "TimeoutError" ? "the request timed out" : "the server could not be reached" };
1740
+ fs.writeFileSync(lockPath, `${process.pid}
1741
+ `, { encoding: "utf8", mode: 384 });
1742
+ } catch {
1604
1743
  }
1605
- if (response.status === 404)
1606
- return { kind: "absent" };
1607
- if (response.status === 401)
1608
- return { kind: "rejected", httpStatus: 401 };
1609
- if (!response.ok)
1610
- return { kind: "failed", reason: `the server answered HTTP ${response.status}` };
1611
- let body;
1744
+ }
1745
+ function removeLock(lockPath) {
1612
1746
  try {
1613
- body = await response.json();
1747
+ fs.unlinkSync(lockPath);
1614
1748
  } catch {
1615
- return { kind: "absent" };
1616
1749
  }
1617
- if (!Array.isArray(body))
1618
- return { kind: "absent" };
1619
- return { kind: "ok", notices: body };
1620
1750
  }
1621
- async function setStudyObjection(apiBaseUrl, eventWriteToken, code, objected) {
1622
- const response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices/${encodeURIComponent(String(code))}/objection`, {
1623
- method: objected ? "POST" : "DELETE",
1624
- headers: { Authorization: `Bearer ${eventWriteToken}` }
1625
- });
1626
- if (!response.ok)
1627
- throw await apiError(response);
1751
+ function outboxHasEntries(outboxFilePath) {
1752
+ try {
1753
+ return fs.statSync(outboxFilePath).size > 0;
1754
+ } catch {
1755
+ return false;
1756
+ }
1628
1757
  }
1629
- async function markStudyNoticeShown(apiBaseUrl, eventWriteToken, organisationId, code, signal) {
1758
+ function startBackgroundFlush(options) {
1759
+ const lockPath = flushLockPath(options.outboxFilePath);
1760
+ const now = options.now ?? Date.now();
1761
+ if (lockIsFresh(lockPath, now))
1762
+ return false;
1763
+ const script = options.script ?? process.argv[1];
1764
+ if (!script)
1765
+ return false;
1630
1766
  try {
1631
- const response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices/${encodeURIComponent(organisationId)}/${encodeURIComponent(String(code))}/shown`, {
1632
- method: "POST",
1633
- headers: { Authorization: `Bearer ${eventWriteToken}` },
1634
- signal
1767
+ touchLock(lockPath);
1768
+ const child = (0, child_process_1.spawn)(process.execPath, [script, exports.OUTBOX_FLUSH_COMMAND], {
1769
+ detached: true,
1770
+ stdio: "ignore",
1771
+ windowsHide: true,
1772
+ env: process.env
1635
1773
  });
1636
- return response.ok;
1774
+ child.on("error", () => removeLock(lockPath));
1775
+ child.unref();
1776
+ return true;
1637
1777
  } catch {
1778
+ removeLock(lockPath);
1638
1779
  return false;
1639
1780
  }
1640
1781
  }
1641
- async function apiError(response) {
1642
- const body = await response.text();
1643
- let errorCode;
1782
+ async function runOutboxFlush(sender, now = Date.now) {
1783
+ const outboxFilePath = sender.outboxFilePath();
1784
+ const lockPath = flushLockPath(outboxFilePath);
1785
+ const started = now();
1786
+ let last;
1787
+ let passes = 0;
1788
+ const drain = async () => {
1789
+ while (passes < FLUSH_MAX_PASSES && now() - started < FLUSH_MAX_RUN_MS) {
1790
+ passes += 1;
1791
+ touchLock(lockPath);
1792
+ last = await sender.flushOutbox();
1793
+ if (!last || last.found === 0 || last.halted || !last.sendEnabled)
1794
+ return;
1795
+ if (last.delivered === 0 && last.discarded === 0)
1796
+ return;
1797
+ }
1798
+ };
1644
1799
  try {
1645
- const parsed = JSON.parse(body);
1646
- errorCode = parsed.code ?? parsed.error;
1800
+ await drain();
1801
+ removeLock(lockPath);
1802
+ if (!last?.halted && last?.sendEnabled !== false && outboxHasEntries(outboxFilePath)) {
1803
+ touchLock(lockPath);
1804
+ await drain();
1805
+ removeLock(lockPath);
1806
+ }
1647
1807
  } catch {
1648
- errorCode = void 0;
1808
+ removeLock(lockPath);
1649
1809
  }
1650
- return new AscendaApiError(response.status, errorCode, body);
1651
- }
1652
- async function renewToolToken(apiBaseUrl, eventWriteToken, signal) {
1653
- const response = await fetch(`${apiBaseUrl}/v1/tool-events/renew-token`, {
1654
- method: "POST",
1655
- headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
1656
- signal
1657
- });
1658
- if (response.status === 401)
1659
- return null;
1660
- if (!response.ok)
1661
- throw new AscendaApiError(response.status, void 0, await response.text());
1662
- return await response.json();
1810
+ return last;
1663
1811
  }
1664
- function isDeliveredStatus(value) {
1665
- return typeof value === "string" && tool_contract_1.TOOL_EVENT_DELIVERED_STATUSES.includes(value);
1812
+ }
1813
+ });
1814
+
1815
+ // ../packages/agent-events/out/index.js
1816
+ var require_out2 = __commonJS({
1817
+ "../packages/agent-events/out/index.js"(exports) {
1818
+ "use strict";
1819
+ Object.defineProperty(exports, "__esModule", { value: true });
1820
+ exports.KNOWN_AGENTS = exports.WAIT_REASONS = exports.VCS_ACTIONS = exports.AGENT_EVENT_KINDS = exports.AGENT_EVENT_SCHEMA = void 0;
1821
+ exports.isAgentEventV0 = isAgentEventV0;
1822
+ exports.parseEventLogLine = parseEventLogLine;
1823
+ exports.normaliseKind = normaliseKind;
1824
+ exports.AGENT_EVENT_SCHEMA = "agent-event/v0";
1825
+ exports.AGENT_EVENT_KINDS = [
1826
+ "session.started",
1827
+ "session.ended",
1828
+ "prompt.submitted",
1829
+ "tool.started",
1830
+ "tool.completed",
1831
+ "tool.failed",
1832
+ "turn.completed",
1833
+ "agent.waiting",
1834
+ "permission.requested",
1835
+ "permission.denied",
1836
+ "context.compacted",
1837
+ "subagent.started",
1838
+ "subagent.stopped",
1839
+ "pull_request.opened",
1840
+ "pull_request.closed",
1841
+ "pull_request.merged",
1842
+ "other"
1843
+ ];
1844
+ exports.VCS_ACTIONS = ["commit", "push", "pr_created", "pr_merged"];
1845
+ exports.WAIT_REASONS = ["permission", "idle", "input", "other"];
1846
+ exports.KNOWN_AGENTS = ["claude_code", "codex", "cursor", "gemini_cli", "windsurf", "vscode"];
1847
+ function isAgentEventV0(value) {
1848
+ if (!value || typeof value !== "object")
1849
+ return false;
1850
+ const e = value;
1851
+ return e.schema === exports.AGENT_EVENT_SCHEMA && typeof e.id === "string" && e.id.length > 0 && typeof e.time === "string" && !Number.isNaN(Date.parse(e.time)) && typeof e.agent === "string" && e.agent.length > 0 && typeof e.kind === "string";
1666
1852
  }
1667
- function readSuccessBody(body) {
1668
- let parsed;
1853
+ function parseEventLogLine(line) {
1854
+ if (!line.trim())
1855
+ return void 0;
1669
1856
  try {
1670
- parsed = JSON.parse(body);
1857
+ const parsed = JSON.parse(line);
1858
+ return isAgentEventV0(parsed?.event) ? parsed.event : void 0;
1671
1859
  } catch {
1672
- return { duplicates: 0 };
1673
- }
1674
- if (!parsed || typeof parsed !== "object")
1675
- return { duplicates: 0 };
1676
- const single = parsed.status;
1677
- if (isDeliveredStatus(single))
1678
- return { duplicates: single === "duplicate" ? 1 : 0 };
1679
- const raw = parsed.results;
1680
- if (!Array.isArray(raw))
1681
- return { duplicates: 0 };
1682
- const results = [];
1683
- for (const item of raw) {
1684
- if (!item || typeof item !== "object")
1685
- continue;
1686
- const { index, status, reason } = item;
1687
- if (typeof index !== "number" || typeof status !== "string")
1688
- continue;
1689
- results.push({ index, status, ...typeof reason === "string" ? { reason } : {} });
1860
+ return void 0;
1690
1861
  }
1691
- return { duplicates: results.filter((item) => item.status === "duplicate").length, results };
1692
1862
  }
1693
- function isRetryableStatus(status) {
1694
- return status === 408 || status === 429 || status !== void 0 && status >= 500 && status <= 599;
1695
- }
1696
- async function postToolEvent(apiBaseUrl, eventWriteToken, payload, signal) {
1697
- return sendIngest(`${apiBaseUrl}/v1/tool-events`, eventWriteToken, JSON.stringify(payload), signal);
1863
+ function normaliseKind(kind) {
1864
+ return exports.AGENT_EVENT_KINDS.includes(kind) ? kind : "other";
1698
1865
  }
1699
- async function postToolEventsBatch(apiBaseUrl, eventWriteToken, payloads, signal) {
1700
- return sendIngest(`${apiBaseUrl}/v1/tool-events/batch`, eventWriteToken, JSON.stringify({ events: payloads }), signal);
1866
+ }
1867
+ });
1868
+
1869
+ // ../packages/tool-kit/out/agentEvent.js
1870
+ var require_agentEvent = __commonJS({
1871
+ "../packages/tool-kit/out/agentEvent.js"(exports) {
1872
+ "use strict";
1873
+ Object.defineProperty(exports, "__esModule", { value: true });
1874
+ exports.toAgentEvent = toAgentEvent;
1875
+ var agent_events_1 = require_out2();
1876
+ var KIND_BY_TYPE = {
1877
+ create_focus_session: "session.started",
1878
+ recovery_offline_period: "session.ended",
1879
+ ai_prompt_submitted: "prompt.submitted",
1880
+ ai_tool_call_started: "tool.started",
1881
+ ai_tool_call_completed: "tool.completed",
1882
+ ai_file_write: "tool.completed",
1883
+ ai_file_edit: "tool.completed",
1884
+ editor_verification_activity: "tool.completed",
1885
+ ai_tool_call_failed: "tool.failed",
1886
+ compile_error: "tool.failed",
1887
+ tool_failure: "tool.failed",
1888
+ ai_turn_completed: "turn.completed",
1889
+ supervision_interruption: "agent.waiting",
1890
+ permission_requested: "permission.requested",
1891
+ permission_denied: "permission.denied",
1892
+ context_compression_manual: "context.compacted",
1893
+ context_compression_auto: "context.compacted",
1894
+ subagent_started: "subagent.started",
1895
+ subagent_stopped: "subagent.stopped",
1896
+ pull_request_opened: "pull_request.opened",
1897
+ pull_request_closed: "pull_request.closed",
1898
+ pull_request_merged: "pull_request.merged"
1899
+ };
1900
+ function agentOf(payload) {
1901
+ const host = stringField(payload.metadata?.host);
1902
+ if (host)
1903
+ return host;
1904
+ return payload.source === "vscode_extension" ? "vscode" : payload.source;
1701
1905
  }
1702
- async function sendIngest(url, eventWriteToken, body, signal) {
1703
- try {
1704
- const response = await fetch(url, {
1705
- method: "POST",
1706
- headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
1707
- body,
1708
- signal
1709
- });
1710
- return parseIngestResponse(response);
1711
- } catch (error) {
1712
- return {
1713
- result: "transport_error",
1714
- detail: error instanceof Error ? `${error.name}: ${error.message}` : String(error)
1715
- };
1906
+ function vcsActionOf(metadata) {
1907
+ const milestone = stringField(metadata.milestoneKind);
1908
+ if (milestone === "pr_opened")
1909
+ return "pr_created";
1910
+ if (milestone === "pr_merged")
1911
+ return "pr_merged";
1912
+ const git = stringField(metadata.gitAction);
1913
+ return git === "commit" || git === "push" ? git : void 0;
1914
+ }
1915
+ function waitReasonOf(metadata) {
1916
+ switch (stringField(metadata.interruptionKind)) {
1917
+ case "permission_request":
1918
+ return "permission";
1919
+ case "input_request":
1920
+ return "input";
1921
+ case "idle_prompt":
1922
+ return "idle";
1923
+ case void 0:
1924
+ return void 0;
1925
+ default:
1926
+ return "other";
1716
1927
  }
1717
1928
  }
1718
- async function parseIngestResponse(response) {
1719
- if (response.ok) {
1720
- const outcome = { result: "accepted", httpStatus: response.status };
1721
- let read = { duplicates: 0 };
1722
- try {
1723
- read = readSuccessBody(await response.text());
1724
- } catch {
1725
- read = { duplicates: 0 };
1726
- }
1727
- return {
1728
- ...outcome,
1729
- ...read.duplicates > 0 ? { duplicates: read.duplicates } : {},
1730
- ...read.results !== void 0 ? { results: read.results } : {}
1731
- };
1732
- }
1733
- const body = await response.text();
1734
- let errorCode;
1735
- try {
1736
- errorCode = JSON.parse(body).error;
1737
- } catch {
1738
- errorCode = void 0;
1739
- }
1740
- const base2 = { httpStatus: response.status, errorCode, detail: body || void 0 };
1741
- if (response.status === 401)
1742
- return { ...base2, result: "auth_failed" };
1743
- if (response.status === 403 && errorCode === "consent_missing_or_expired")
1744
- return { ...base2, result: "consent_missing" };
1745
- if (response.status === 400 || response.status === 422)
1746
- return { ...base2, result: "validation_failed" };
1747
- return { ...base2, result: "transport_error" };
1929
+ function stringField(value) {
1930
+ return typeof value === "string" && value.length > 0 ? value : void 0;
1931
+ }
1932
+ function toAgentEvent(payload) {
1933
+ const metadata = payload.metadata ?? {};
1934
+ const kind = KIND_BY_TYPE[payload.eventType] ?? "other";
1935
+ const tool = kind.startsWith("tool.") || kind.startsWith("permission.") ? stringField(metadata.toolName) : void 0;
1936
+ const outcome = stringField(metadata.outcome);
1937
+ const vcsAction = kind === "tool.completed" ? vcsActionOf(metadata) : void 0;
1938
+ const reason = kind === "agent.waiting" ? waitReasonOf(metadata) : void 0;
1939
+ const model = kind === "session.started" ? stringField(metadata.modelId) : void 0;
1940
+ return {
1941
+ schema: agent_events_1.AGENT_EVENT_SCHEMA,
1942
+ id: payload.idempotencyKey ?? `${payload.toolInstallationId}:${payload.occurredAt}:${payload.eventType}`,
1943
+ time: payload.occurredAt,
1944
+ // `+ 0` turns the -0 a UTC machine computes into 0, which is what JSON
1945
+ // writes anyway; without it the event in memory and the one on disk differ.
1946
+ ...typeof payload.utcOffsetMinutes === "number" ? { utcOffsetMinutes: payload.utcOffsetMinutes + 0 } : {},
1947
+ agent: agentOf(payload),
1948
+ kind,
1949
+ ...stringField(payload.sessionId) ? { sessionId: payload.sessionId } : {},
1950
+ ...stringField(metadata.subagentId) ? { subagentId: metadata.subagentId } : {},
1951
+ ...tool ? { tool } : {},
1952
+ ...outcome && outcome !== "unknown" ? { outcome } : {},
1953
+ ...stringField(metadata.durationBucket) ? { durationBucket: metadata.durationBucket } : {},
1954
+ ...stringField(payload.projectHash) ? { projectHash: payload.projectHash } : {},
1955
+ ...stringField(metadata.repoKey) ? { repoKey: metadata.repoKey } : {},
1956
+ ...stringField(metadata.branchKey) ? { branchKey: metadata.branchKey } : {},
1957
+ ...stringField(metadata.autonomyMode) ? { permissionMode: metadata.autonomyMode } : {},
1958
+ ...stringField(metadata.headRepoKey) ? { headRepoKey: metadata.headRepoKey } : {},
1959
+ ...stringField(metadata.prCreatedAt) ? { prCreatedAt: metadata.prCreatedAt } : {},
1960
+ ...stringField(metadata.prClosedAt) ? { prClosedAt: metadata.prClosedAt } : {},
1961
+ ...stringField(metadata.prMergedAt) ? { prMergedAt: metadata.prMergedAt } : {},
1962
+ ...stringField(metadata.promptId) ? { promptId: metadata.promptId } : {},
1963
+ ...vcsAction ? { vcsAction } : {},
1964
+ ...reason ? { reason } : {},
1965
+ ...model ? { model } : {},
1966
+ ...stringField(metadata.collectorVersion) ? { collectorVersion: metadata.collectorVersion } : {},
1967
+ sourceType: payload.eventType
1968
+ };
1748
1969
  }
1749
1970
  }
1750
1971
  });
1751
1972
 
1752
- // ../packages/tool-kit/out/stateStore.js
1753
- var require_stateStore = __commonJS({
1754
- "../packages/tool-kit/out/stateStore.js"(exports) {
1973
+ // ../packages/tool-kit/out/credentials.js
1974
+ var require_credentials = __commonJS({
1975
+ "../packages/tool-kit/out/credentials.js"(exports) {
1755
1976
  "use strict";
1756
1977
  var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
1757
1978
  if (k2 === void 0) k2 = k;
@@ -1791,124 +2012,102 @@ var require_stateStore = __commonJS({
1791
2012
  };
1792
2013
  }();
1793
2014
  Object.defineProperty(exports, "__esModule", { value: true });
1794
- exports.defaultStateFilePath = defaultStateFilePath;
1795
- exports.unresolvedToolInstallationId = unresolvedToolInstallationId;
1796
- exports.unresolvedStateFilePath = unresolvedStateFilePath;
1797
- exports.readCollectorState = readCollectorState;
1798
- exports.recordSendOutcome = recordSendOutcome;
1799
- exports.recordOutboxDiscard = recordOutboxDiscard;
1800
- exports.shouldAnnounceFailure = shouldAnnounceFailure;
1801
- exports.markFailureNotified = markFailureNotified;
2015
+ exports.credentialsFilePath = credentialsFilePath;
2016
+ exports.readMachineCredentials = readMachineCredentials;
2017
+ exports.writeMachineCredentials = writeMachineCredentials;
2018
+ exports.writeTopLevelCredentials = writeTopLevelCredentials;
2019
+ exports.writeRepoKeysSetting = writeRepoKeysSetting;
2020
+ exports.writeEventLogSetting = writeEventLogSetting;
2021
+ exports.isLocalOnlyHostInstall = isLocalOnlyHostInstall;
2022
+ exports.readHostCredentials = readHostCredentials;
2023
+ exports.writeHostCredentials = writeHostCredentials;
2024
+ exports.removeHostCredentials = removeHostCredentials;
1802
2025
  var fs = __importStar(__require("fs"));
1803
2026
  var path = __importStar(__require("path"));
1804
2027
  var tokenStore_1 = require_tokenStore();
1805
- function defaultStateFilePath(toolInstallationId) {
1806
- const dir = process.env.ASCENDA_STATE_DIR?.trim();
1807
- const base2 = dir ? dir : path.join((0, tokenStore_1.ascendaHome)(), "state");
1808
- return path.join(base2, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.json`);
1809
- }
1810
- function unresolvedToolInstallationId(toolType) {
1811
- return `${toolType}:unresolved`;
1812
- }
1813
- function unresolvedStateFilePath(toolType) {
1814
- return defaultStateFilePath(unresolvedToolInstallationId(toolType));
2028
+ function credentialsFilePath() {
2029
+ return path.join((0, tokenStore_1.ascendaHome)(), "credentials.json");
1815
2030
  }
1816
- function readCollectorState(stateFilePath) {
2031
+ function readMachineCredentials() {
1817
2032
  try {
1818
- if (!fs.existsSync(stateFilePath))
1819
- return void 0;
1820
- const raw = fs.readFileSync(stateFilePath, "utf8").trim();
2033
+ const raw = fs.readFileSync(credentialsFilePath(), "utf8").trim();
1821
2034
  if (!raw)
1822
2035
  return void 0;
1823
2036
  const parsed = JSON.parse(raw);
1824
- if (!parsed || typeof parsed !== "object")
2037
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
1825
2038
  return void 0;
1826
2039
  return parsed;
1827
2040
  } catch {
1828
2041
  return void 0;
1829
2042
  }
1830
2043
  }
1831
- function recordSendOutcome(stateFilePath, toolInstallationId, outcome, detail = {}) {
1832
- const now = (/* @__PURE__ */ new Date()).toISOString();
1833
- const previous = readCollectorState(stateFilePath);
1834
- const accepted = outcome === "accepted";
1835
- const next = {
1836
- toolInstallationId,
1837
- lastAttemptAt: now,
1838
- lastSuccessAt: accepted ? now : previous?.lastSuccessAt,
1839
- lastOutcome: outcome,
1840
- consecutiveFailures: accepted ? 0 : (previous?.consecutiveFailures ?? 0) + 1,
1841
- ...detail.httpStatus !== void 0 ? { httpStatus: detail.httpStatus } : {},
1842
- ...detail.errorCode !== void 0 ? { errorCode: detail.errorCode } : {},
1843
- ...detail.detail !== void 0 ? { detail: truncate(detail.detail) } : {},
1844
- // A success closes the episode; a failure either opens one or continues
1845
- // the one already open. Carrying `notifiedFailingSince` across a
1846
- // continuing episode is what keeps the notice to once per outage.
1847
- ...accepted ? {} : { failingSince: previous?.failingSince ?? now },
1848
- ...accepted ? {} : previous?.notifiedFailingSince !== void 0 ? { notifiedFailingSince: previous.notifiedFailingSince } : {},
1849
- // Cumulative by design: a send outcome, success included, never erases
1850
- // the record of what the outbox had to throw away.
1851
- ...previous?.outboxDiscarded !== void 0 ? { outboxDiscarded: previous.outboxDiscarded } : {}
1852
- };
1853
- writeStateFile(stateFilePath, next);
1854
- return next;
2044
+ function writeMachineCredentials(credentials) {
2045
+ const file = credentialsFilePath();
2046
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 448 });
2047
+ fs.writeFileSync(file, `${JSON.stringify(credentials, null, 2)}
2048
+ `, { encoding: "utf8", mode: 384 });
2049
+ if (process.platform !== "win32") {
2050
+ fs.chmodSync(path.dirname(file), 448);
2051
+ fs.chmodSync(file, 384);
2052
+ }
1855
2053
  }
1856
- function recordOutboxDiscard(stateFilePath, toolInstallationId, discard) {
1857
- const now = (/* @__PURE__ */ new Date()).toISOString();
1858
- const previous = readCollectorState(stateFilePath);
1859
- const next = {
1860
- ...previous ?? { lastAttemptAt: now, consecutiveFailures: 0 },
1861
- toolInstallationId,
1862
- lastOutcome: "outbox_discarded",
1863
- outboxDiscarded: {
1864
- total: (previous?.outboxDiscarded?.total ?? 0) + discard.count,
1865
- lastAt: now,
1866
- lastCount: discard.count,
1867
- lastReasons: discard.reasons,
1868
- ...discard.oldestQueuedAt !== void 0 ? { lastOldestQueuedAt: discard.oldestQueuedAt } : {}
1869
- }
1870
- };
1871
- writeStateFile(stateFilePath, next);
1872
- return next;
2054
+ function writeTopLevelCredentials(credentials) {
2055
+ const existing = readMachineCredentials();
2056
+ const eventLogPath = credentials.eventLogPath ?? existing?.eventLogPath;
2057
+ const repoKeys = credentials.repoKeys ?? existing?.repoKeys;
2058
+ writeMachineCredentials({
2059
+ ...credentials,
2060
+ ...eventLogPath ? { eventLogPath } : {},
2061
+ ...repoKeys === false ? { repoKeys } : {},
2062
+ ...existing?.tools ? { tools: existing.tools } : {}
2063
+ });
1873
2064
  }
1874
- function shouldAnnounceFailure(state) {
1875
- if (!state || state.consecutiveFailures === 0 || !state.failingSince)
2065
+ function writeRepoKeysSetting(on) {
2066
+ const existing = readMachineCredentials() ?? {};
2067
+ const { repoKeys: _dropped, ...rest } = existing;
2068
+ writeMachineCredentials(on ? rest : { ...rest, repoKeys: false });
2069
+ }
2070
+ function writeEventLogSetting(value) {
2071
+ const existing = readMachineCredentials() ?? {};
2072
+ writeMachineCredentials({ ...existing, eventLogPath: value });
2073
+ }
2074
+ function isLocalOnlyHostInstall(host, hasToken) {
2075
+ const credentials = readHostCredentials(host);
2076
+ if (!credentials?.localOnly)
1876
2077
  return false;
1877
- return state.notifiedFailingSince !== state.failingSince;
2078
+ if (process.env.ASCENDA_EVENT_WRITE_TOKEN)
2079
+ return false;
2080
+ return !(credentials.toolInstallationId && hasToken(credentials.toolInstallationId));
1878
2081
  }
1879
- function markFailureNotified(stateFilePath, state) {
1880
- if (!state.failingSince)
1881
- return;
1882
- writeStateFile(stateFilePath, { ...state, notifiedFailingSince: state.failingSince });
2082
+ function readHostCredentials(host) {
2083
+ const entry = readMachineCredentials()?.tools?.[host];
2084
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
2085
+ return void 0;
2086
+ return entry;
1883
2087
  }
1884
- function writeStateFile(stateFilePath, state) {
1885
- const temporaryPath = `${stateFilePath}.${process.pid}.tmp`;
1886
- try {
1887
- const dir = path.dirname(stateFilePath);
1888
- fs.mkdirSync(dir, { recursive: true, mode: 448 });
1889
- fs.writeFileSync(temporaryPath, `${JSON.stringify(state, null, 2)}
1890
- `, { encoding: "utf8", mode: 384 });
1891
- fs.renameSync(temporaryPath, stateFilePath);
1892
- if (process.platform !== "win32")
1893
- fs.chmodSync(stateFilePath, 384);
1894
- } catch {
1895
- try {
1896
- if (fs.existsSync(temporaryPath))
1897
- fs.unlinkSync(temporaryPath);
1898
- } catch {
1899
- }
1900
- }
2088
+ function writeHostCredentials(host, credentials) {
2089
+ const existing = readMachineCredentials() ?? {};
2090
+ writeMachineCredentials({ ...existing, tools: { ...existing.tools ?? {}, [host]: credentials } });
1901
2091
  }
1902
- function truncate(value) {
1903
- const collapsed = value.replace(/\s+/g, " ").trim();
1904
- return collapsed.length > 200 ? `${collapsed.slice(0, 197)}...` : collapsed;
2092
+ function removeHostCredentials(host) {
2093
+ const existing = readMachineCredentials();
2094
+ if (!existing?.tools || !(host in existing.tools))
2095
+ return;
2096
+ const tools = { ...existing.tools };
2097
+ delete tools[host];
2098
+ const next = { ...existing };
2099
+ if (Object.keys(tools).length)
2100
+ next.tools = tools;
2101
+ else
2102
+ delete next.tools;
2103
+ writeMachineCredentials(next);
1905
2104
  }
1906
2105
  }
1907
2106
  });
1908
2107
 
1909
- // ../packages/tool-kit/out/outbox.js
1910
- var require_outbox = __commonJS({
1911
- "../packages/tool-kit/out/outbox.js"(exports) {
2108
+ // ../packages/tool-kit/out/eventLog.js
2109
+ var require_eventLog = __commonJS({
2110
+ "../packages/tool-kit/out/eventLog.js"(exports) {
1912
2111
  "use strict";
1913
2112
  var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
1914
2113
  if (k2 === void 0) k2 = k;
@@ -1948,182 +2147,347 @@ var require_outbox = __commonJS({
1948
2147
  };
1949
2148
  }();
1950
2149
  Object.defineProperty(exports, "__esModule", { value: true });
1951
- exports.DEFAULT_OUTBOX_DRAIN_BATCH_SIZE = exports.DEFAULT_OUTBOX_MAX_AGE_MS = exports.DEFAULT_OUTBOX_MAX_ENTRIES = exports.OUTBOX_DRAIN_ENV_VAR = void 0;
1952
- exports.outboxDrainEnabled = outboxDrainEnabled;
1953
- exports.defaultOutboxFilePath = defaultOutboxFilePath;
1954
- exports.appendToOutbox = appendToOutbox;
1955
- exports.readOutboxSummary = readOutboxSummary;
1956
- exports.claimOutbox = claimOutbox;
1957
- exports.enforceOutboxBounds = enforceOutboxBounds;
2150
+ exports.EVENT_LOG_OFF = exports.EVENT_LOG_ENV_VAR = void 0;
2151
+ exports.expandUserPath = expandUserPath;
2152
+ exports.defaultEventLogPath = defaultEventLogPath;
2153
+ exports.resolveEventLog = resolveEventLog;
2154
+ exports.resolveEventLogPath = resolveEventLogPath;
2155
+ exports.describeEventLog = describeEventLog;
2156
+ exports.parseEventLogFlag = parseEventLogFlag;
2157
+ exports.appendEventLog = appendEventLog;
1958
2158
  var fs = __importStar(__require("fs"));
2159
+ var os = __importStar(__require("os"));
1959
2160
  var path = __importStar(__require("path"));
1960
- var stateStore_1 = require_stateStore();
2161
+ var agentEvent_1 = require_agentEvent();
2162
+ var credentials_1 = require_credentials();
1961
2163
  var tokenStore_1 = require_tokenStore();
1962
- exports.OUTBOX_DRAIN_ENV_VAR = "ASCENDA_OUTBOX_DRAIN";
1963
- exports.DEFAULT_OUTBOX_MAX_ENTRIES = 1e4;
1964
- exports.DEFAULT_OUTBOX_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1e3;
1965
- exports.DEFAULT_OUTBOX_DRAIN_BATCH_SIZE = 100;
1966
- var ORPHANED_CLAIM_AGE_MS = 6e4;
1967
- var CLAIM_SUFFIX = ".draining";
1968
- function outboxDrainEnabled(env = process.env) {
1969
- const value = env[exports.OUTBOX_DRAIN_ENV_VAR]?.trim().toLowerCase();
1970
- if (value === void 0 || value === "")
1971
- return true;
1972
- return !(value === "0" || value === "false" || value === "no" || value === "off");
2164
+ exports.EVENT_LOG_ENV_VAR = "ASCENDA_EVENT_LOG_FILE";
2165
+ exports.EVENT_LOG_OFF = "off";
2166
+ var MAX_BYTES = 5 * 1024 * 1024;
2167
+ function expandUserPath(configured) {
2168
+ const value = configured?.trim();
2169
+ if (!value)
2170
+ return void 0;
2171
+ if (value === "~")
2172
+ return os.homedir();
2173
+ if (value.startsWith("~/"))
2174
+ return path.join(os.homedir(), value.slice(2));
2175
+ return path.resolve(value);
1973
2176
  }
1974
- function defaultOutboxFilePath(toolInstallationId) {
1975
- const dir = path.dirname((0, stateStore_1.defaultStateFilePath)(toolInstallationId));
1976
- return path.join(dir, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.outbox.jsonl`);
2177
+ function defaultEventLogPath() {
2178
+ return path.join((0, tokenStore_1.ascendaHome)(), "events.jsonl");
1977
2179
  }
1978
- function appendToOutbox(outboxFilePath, payload, now = /* @__PURE__ */ new Date()) {
2180
+ function resolveEventLog(options = {}) {
2181
+ for (const [source, raw] of [
2182
+ ["env", process.env[exports.EVENT_LOG_ENV_VAR]],
2183
+ ["credentials", (0, credentials_1.readMachineCredentials)()?.eventLogPath]
2184
+ ]) {
2185
+ const value = raw?.trim();
2186
+ if (!value)
2187
+ continue;
2188
+ if (value.toLowerCase() === exports.EVENT_LOG_OFF)
2189
+ return { path: void 0, source: "disabled" };
2190
+ return { path: expandUserPath(value), source };
2191
+ }
2192
+ if (options.localOnly)
2193
+ return { path: defaultEventLogPath(), source: "unpaired-default" };
2194
+ return { path: void 0, source: "off" };
2195
+ }
2196
+ function resolveEventLogPath(options = {}) {
2197
+ return resolveEventLog(options).path;
2198
+ }
2199
+ function describeEventLog(setting, command) {
2200
+ switch (setting.source) {
2201
+ case "env":
2202
+ return `${setting.path} (from ${exports.EVENT_LOG_ENV_VAR})`;
2203
+ case "credentials":
2204
+ return `${setting.path} (set by ${command} --event-log)`;
2205
+ case "unpaired-default":
2206
+ return `${setting.path} (on because this install isn't paired; ${command} --event-log off to stop)`;
2207
+ case "disabled":
2208
+ return `off (turned off; ${command} --event-log to turn it on)`;
2209
+ case "off":
2210
+ return `off (${command} --event-log to keep a local copy of every event)`;
2211
+ }
2212
+ }
2213
+ function parseEventLogFlag(argv, index) {
2214
+ const peek = argv[index + 1];
2215
+ if (peek !== void 0 && !peek.startsWith("-"))
2216
+ return { value: peek, consumed: 1 };
2217
+ return { value: defaultEventLogPath(), consumed: 0 };
2218
+ }
2219
+ function appendEventLog(logFilePath, entry) {
1979
2220
  try {
1980
- const dir = path.dirname(outboxFilePath);
2221
+ rotateIfLarge(logFilePath);
2222
+ const dir = path.dirname(logFilePath);
1981
2223
  fs.mkdirSync(dir, { recursive: true, mode: 448 });
1982
- const entry = { queuedAt: now.toISOString(), payload };
1983
- fs.appendFileSync(outboxFilePath, `${JSON.stringify(entry)}
2224
+ const line = { ...entry, event: entry.event ?? (0, agentEvent_1.toAgentEvent)(entry.payload) };
2225
+ fs.appendFileSync(logFilePath, `${JSON.stringify(line)}
1984
2226
  `, { encoding: "utf8", mode: 384 });
1985
2227
  if (process.platform !== "win32")
1986
- fs.chmodSync(outboxFilePath, 384);
1987
- return true;
2228
+ fs.chmodSync(logFilePath, 384);
1988
2229
  } catch {
1989
- return false;
1990
2230
  }
1991
2231
  }
1992
- function readOutboxSummary(outboxFilePath) {
1993
- const files = [outboxFilePath, ...listClaimFiles(outboxFilePath)].filter((file) => fs.existsSync(file));
1994
- if (files.length === 0)
1995
- return void 0;
1996
- let depth = 0;
1997
- let unreadableLines = 0;
1998
- let oldestQueuedAt;
1999
- for (const file of files) {
2000
- const { entries, unreadable } = readEntries(file);
2001
- depth += entries.length;
2002
- unreadableLines += unreadable;
2003
- for (const entry of entries) {
2004
- if (oldestQueuedAt === void 0 || entry.queuedAt < oldestQueuedAt)
2005
- oldestQueuedAt = entry.queuedAt;
2006
- }
2007
- }
2008
- return { depth, unreadableLines, ...oldestQueuedAt !== void 0 ? { oldestQueuedAt } : {} };
2009
- }
2010
- function claimOutbox(outboxFilePath, now = Date.now()) {
2011
- const claimPath = `${outboxFilePath}.${process.pid}${CLAIM_SUFFIX}`;
2012
- const claimed = [];
2232
+ function rotateIfLarge(logFilePath) {
2013
2233
  try {
2014
- fs.renameSync(outboxFilePath, claimPath);
2015
- claimed.push(claimPath);
2234
+ if (fs.statSync(logFilePath).size < MAX_BYTES)
2235
+ return;
2236
+ fs.renameSync(logFilePath, `${logFilePath}.1`);
2016
2237
  } catch {
2017
2238
  }
2018
- let orphanIndex = 0;
2019
- for (const orphan of listClaimFiles(outboxFilePath)) {
2020
- if (claimed.includes(orphan))
2021
- continue;
2022
- try {
2023
- if (now - fs.statSync(orphan).mtimeMs < ORPHANED_CLAIM_AGE_MS)
2024
- continue;
2025
- const mine = `${claimPath}.${orphanIndex++}`;
2026
- fs.renameSync(orphan, mine);
2027
- claimed.push(mine);
2028
- } catch {
2029
- }
2239
+ }
2240
+ }
2241
+ });
2242
+
2243
+ // ../packages/tool-kit/out/http.js
2244
+ var require_http = __commonJS({
2245
+ "../packages/tool-kit/out/http.js"(exports) {
2246
+ "use strict";
2247
+ Object.defineProperty(exports, "__esModule", { value: true });
2248
+ exports.AscendaApiError = void 0;
2249
+ exports.createPairingSession = createPairingSession;
2250
+ exports.getPairingStatus = getPairingStatus;
2251
+ exports.startStudyJoin = startStudyJoin;
2252
+ exports.getStudyJoinStatus = getStudyJoinStatus;
2253
+ exports.readInitiatives = readInitiatives;
2254
+ exports.readStudyNotices = readStudyNotices;
2255
+ exports.setStudyObjection = setStudyObjection;
2256
+ exports.markStudyNoticeShown = markStudyNoticeShown;
2257
+ exports.renewToolToken = renewToolToken;
2258
+ exports.isRetryableStatus = isRetryableStatus;
2259
+ exports.postToolEvent = postToolEvent;
2260
+ exports.postToolEventsBatch = postToolEventsBatch;
2261
+ exports.parseIngestResponse = parseIngestResponse;
2262
+ var tool_contract_1 = require_out();
2263
+ var AscendaApiError = class extends Error {
2264
+ status;
2265
+ errorCode;
2266
+ constructor(status, errorCode, body) {
2267
+ super(body ?? `Ascenda API error ${status}`);
2268
+ this.status = status;
2269
+ this.errorCode = errorCode;
2270
+ this.name = "AscendaApiError";
2030
2271
  }
2031
- if (claimed.length === 0)
2032
- return void 0;
2033
- const entries = [];
2034
- let unreadable = 0;
2035
- for (const file of claimed) {
2036
- const read = readEntries(file);
2037
- entries.push(...read.entries);
2038
- unreadable += read.unreadable;
2272
+ };
2273
+ exports.AscendaApiError = AscendaApiError;
2274
+ async function createPairingSession(apiBaseUrl, toolInstallationId, toolType, displayName) {
2275
+ const response = await fetch(`${apiBaseUrl}/v1/tool-pairing-sessions`, {
2276
+ method: "POST",
2277
+ headers: { "Content-Type": "application/json" },
2278
+ body: JSON.stringify({ toolInstallationId, toolType, displayName })
2279
+ });
2280
+ if (!response.ok)
2281
+ throw new AscendaApiError(response.status, void 0, await response.text());
2282
+ return await response.json();
2283
+ }
2284
+ async function getPairingStatus(apiBaseUrl, pairingSessionId) {
2285
+ const response = await fetch(`${apiBaseUrl}/v1/tool-pairing-sessions/${encodeURIComponent(pairingSessionId)}/status`, {
2286
+ method: "GET",
2287
+ headers: { Accept: "application/json" }
2288
+ });
2289
+ if (!response.ok)
2290
+ throw new AscendaApiError(response.status, void 0, await response.text());
2291
+ return await response.json();
2292
+ }
2293
+ async function startStudyJoin(apiBaseUrl, eventWriteToken, joinCode, mode) {
2294
+ const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions`, {
2295
+ method: "POST",
2296
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
2297
+ body: JSON.stringify({ joinCode, mode })
2298
+ });
2299
+ if (!response.ok)
2300
+ throw await apiError(response);
2301
+ return await response.json();
2302
+ }
2303
+ async function getStudyJoinStatus(apiBaseUrl, eventWriteToken, joinSessionId) {
2304
+ const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions/${encodeURIComponent(joinSessionId)}/status`, {
2305
+ method: "GET",
2306
+ headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` }
2307
+ });
2308
+ if (!response.ok)
2309
+ throw await apiError(response);
2310
+ return await response.json();
2311
+ }
2312
+ async function readInitiatives(apiBaseUrl, eventWriteToken, signal) {
2313
+ let response;
2314
+ try {
2315
+ response = await fetch(`${apiBaseUrl}/v1/tool-installations/initiatives`, {
2316
+ method: "GET",
2317
+ headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` },
2318
+ signal
2319
+ });
2320
+ } catch (error) {
2321
+ return { kind: "failed", reason: error instanceof Error && error.name === "TimeoutError" ? "the request timed out" : "the server could not be reached" };
2039
2322
  }
2040
- entries.sort((a, b) => a.queuedAt < b.queuedAt ? -1 : a.queuedAt > b.queuedAt ? 1 : 0);
2041
- let released = false;
2042
- return {
2043
- entries,
2044
- unreadable,
2045
- release(remainder) {
2046
- if (released)
2047
- return;
2048
- released = true;
2049
- if (remainder.length > 0) {
2050
- try {
2051
- fs.mkdirSync(path.dirname(outboxFilePath), { recursive: true, mode: 448 });
2052
- fs.appendFileSync(outboxFilePath, remainder.map((entry) => `${JSON.stringify(entry)}
2053
- `).join(""), { encoding: "utf8", mode: 384 });
2054
- if (process.platform !== "win32")
2055
- fs.chmodSync(outboxFilePath, 384);
2056
- } catch {
2057
- return;
2058
- }
2059
- }
2060
- for (const file of claimed) {
2061
- try {
2062
- fs.unlinkSync(file);
2063
- } catch {
2064
- }
2065
- }
2066
- }
2067
- };
2323
+ if (response.status === 401)
2324
+ return { kind: "rejected", httpStatus: 401 };
2325
+ if (!response.ok)
2326
+ return { kind: "failed", reason: `the server answered HTTP ${response.status}` };
2327
+ let body;
2328
+ try {
2329
+ body = await response.json();
2330
+ } catch {
2331
+ return { kind: "failed", reason: "the reply was not readable" };
2332
+ }
2333
+ if (!Array.isArray(body))
2334
+ return { kind: "failed", reason: "the reply was not a list" };
2335
+ return { kind: "ok", initiatives: body };
2068
2336
  }
2069
- function enforceOutboxBounds(entries, bounds, now = Date.now()) {
2070
- const reasons = {};
2071
- let oldestQueuedAt;
2072
- const cutoff = new Date(now - bounds.maxAgeMs).toISOString();
2073
- const fresh = [];
2074
- for (const entry of entries) {
2075
- if (entry.queuedAt < cutoff) {
2076
- reasons.age = (reasons.age ?? 0) + 1;
2077
- if (oldestQueuedAt === void 0 || entry.queuedAt < oldestQueuedAt)
2078
- oldestQueuedAt = entry.queuedAt;
2079
- } else {
2080
- fresh.push(entry);
2081
- }
2337
+ async function readStudyNotices(apiBaseUrl, eventWriteToken, signal) {
2338
+ let response;
2339
+ try {
2340
+ response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices`, {
2341
+ method: "GET",
2342
+ headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` },
2343
+ signal
2344
+ });
2345
+ } catch (error) {
2346
+ return { kind: "failed", reason: error instanceof Error && error.name === "TimeoutError" ? "the request timed out" : "the server could not be reached" };
2082
2347
  }
2083
- const excess = Math.max(0, fresh.length - bounds.maxEntries);
2084
- if (excess > 0) {
2085
- reasons.count = excess;
2086
- const first = fresh[0]?.queuedAt;
2087
- if (first !== void 0 && (oldestQueuedAt === void 0 || first < oldestQueuedAt))
2088
- oldestQueuedAt = first;
2348
+ if (response.status === 404)
2349
+ return { kind: "absent" };
2350
+ if (response.status === 401)
2351
+ return { kind: "rejected", httpStatus: 401 };
2352
+ if (!response.ok)
2353
+ return { kind: "failed", reason: `the server answered HTTP ${response.status}` };
2354
+ let body;
2355
+ try {
2356
+ body = await response.json();
2357
+ } catch {
2358
+ return { kind: "absent" };
2089
2359
  }
2090
- const kept = excess > 0 ? fresh.slice(excess) : fresh;
2091
- const count = Object.values(reasons).reduce((sum, n) => sum + (n ?? 0), 0);
2092
- return { kept, discarded: { count, reasons, ...oldestQueuedAt !== void 0 ? { oldestQueuedAt } : {} } };
2360
+ if (!Array.isArray(body))
2361
+ return { kind: "absent" };
2362
+ return { kind: "ok", notices: body };
2093
2363
  }
2094
- function listClaimFiles(outboxFilePath) {
2095
- const dir = path.dirname(outboxFilePath);
2096
- const prefix = `${path.basename(outboxFilePath)}.`;
2364
+ async function setStudyObjection(apiBaseUrl, eventWriteToken, code, objected) {
2365
+ const response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices/${encodeURIComponent(String(code))}/objection`, {
2366
+ method: objected ? "POST" : "DELETE",
2367
+ headers: { Authorization: `Bearer ${eventWriteToken}` }
2368
+ });
2369
+ if (!response.ok)
2370
+ throw await apiError(response);
2371
+ }
2372
+ async function markStudyNoticeShown(apiBaseUrl, eventWriteToken, organisationId, code, signal) {
2097
2373
  try {
2098
- return fs.readdirSync(dir).filter((name) => name.startsWith(prefix) && name.includes(CLAIM_SUFFIX)).map((name) => path.join(dir, name)).sort();
2374
+ const response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices/${encodeURIComponent(organisationId)}/${encodeURIComponent(String(code))}/shown`, {
2375
+ method: "POST",
2376
+ headers: { Authorization: `Bearer ${eventWriteToken}` },
2377
+ signal
2378
+ });
2379
+ return response.ok;
2099
2380
  } catch {
2100
- return [];
2381
+ return false;
2101
2382
  }
2102
2383
  }
2103
- function readEntries(file) {
2104
- let raw;
2384
+ async function apiError(response) {
2385
+ const body = await response.text();
2386
+ let errorCode;
2105
2387
  try {
2106
- raw = fs.readFileSync(file, "utf8");
2388
+ const parsed = JSON.parse(body);
2389
+ errorCode = parsed.code ?? parsed.error;
2107
2390
  } catch {
2108
- return { entries: [], unreadable: 0 };
2391
+ errorCode = void 0;
2109
2392
  }
2110
- const entries = [];
2111
- let unreadable = 0;
2112
- for (const line of raw.split("\n")) {
2113
- if (!line.trim())
2393
+ return new AscendaApiError(response.status, errorCode, body);
2394
+ }
2395
+ async function renewToolToken(apiBaseUrl, eventWriteToken, signal) {
2396
+ const response = await fetch(`${apiBaseUrl}/v1/tool-events/renew-token`, {
2397
+ method: "POST",
2398
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
2399
+ signal
2400
+ });
2401
+ if (response.status === 401)
2402
+ return null;
2403
+ if (!response.ok)
2404
+ throw new AscendaApiError(response.status, void 0, await response.text());
2405
+ return await response.json();
2406
+ }
2407
+ function isDeliveredStatus(value) {
2408
+ return typeof value === "string" && tool_contract_1.TOOL_EVENT_DELIVERED_STATUSES.includes(value);
2409
+ }
2410
+ function readSuccessBody(body) {
2411
+ let parsed;
2412
+ try {
2413
+ parsed = JSON.parse(body);
2414
+ } catch {
2415
+ return { duplicates: 0 };
2416
+ }
2417
+ if (!parsed || typeof parsed !== "object")
2418
+ return { duplicates: 0 };
2419
+ const single = parsed.status;
2420
+ if (isDeliveredStatus(single))
2421
+ return { duplicates: single === "duplicate" ? 1 : 0 };
2422
+ const raw = parsed.results;
2423
+ if (!Array.isArray(raw))
2424
+ return { duplicates: 0 };
2425
+ const results = [];
2426
+ for (const item of raw) {
2427
+ if (!item || typeof item !== "object")
2428
+ continue;
2429
+ const { index, status, reason } = item;
2430
+ if (typeof index !== "number" || typeof status !== "string")
2114
2431
  continue;
2432
+ results.push({ index, status, ...typeof reason === "string" ? { reason } : {} });
2433
+ }
2434
+ return { duplicates: results.filter((item) => item.status === "duplicate").length, results };
2435
+ }
2436
+ function isRetryableStatus(status) {
2437
+ return status === 408 || status === 429 || status !== void 0 && status >= 500 && status <= 599;
2438
+ }
2439
+ async function postToolEvent(apiBaseUrl, eventWriteToken, payload, signal) {
2440
+ return sendIngest(`${apiBaseUrl}/v1/tool-events`, eventWriteToken, JSON.stringify(payload), signal);
2441
+ }
2442
+ async function postToolEventsBatch(apiBaseUrl, eventWriteToken, payloads, signal) {
2443
+ return sendIngest(`${apiBaseUrl}/v1/tool-events/batch`, eventWriteToken, JSON.stringify({ events: payloads }), signal);
2444
+ }
2445
+ async function sendIngest(url, eventWriteToken, body, signal) {
2446
+ try {
2447
+ const response = await fetch(url, {
2448
+ method: "POST",
2449
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
2450
+ body,
2451
+ signal
2452
+ });
2453
+ return parseIngestResponse(response);
2454
+ } catch (error) {
2455
+ return {
2456
+ result: "transport_error",
2457
+ detail: error instanceof Error ? `${error.name}: ${error.message}` : String(error)
2458
+ };
2459
+ }
2460
+ }
2461
+ async function parseIngestResponse(response) {
2462
+ if (response.ok) {
2463
+ const outcome = { result: "accepted", httpStatus: response.status };
2464
+ let read = { duplicates: 0 };
2115
2465
  try {
2116
- const parsed = JSON.parse(line);
2117
- if (!parsed || typeof parsed !== "object" || typeof parsed.queuedAt !== "string" || !parsed.payload || typeof parsed.payload !== "object") {
2118
- unreadable += 1;
2119
- continue;
2120
- }
2121
- entries.push({ queuedAt: parsed.queuedAt, payload: parsed.payload });
2466
+ read = readSuccessBody(await response.text());
2122
2467
  } catch {
2123
- unreadable += 1;
2468
+ read = { duplicates: 0 };
2124
2469
  }
2470
+ return {
2471
+ ...outcome,
2472
+ ...read.duplicates > 0 ? { duplicates: read.duplicates } : {},
2473
+ ...read.results !== void 0 ? { results: read.results } : {}
2474
+ };
2125
2475
  }
2126
- return { entries, unreadable };
2476
+ const body = await response.text();
2477
+ let errorCode;
2478
+ try {
2479
+ errorCode = JSON.parse(body).error;
2480
+ } catch {
2481
+ errorCode = void 0;
2482
+ }
2483
+ const base2 = { httpStatus: response.status, errorCode, detail: body || void 0 };
2484
+ if (response.status === 401)
2485
+ return { ...base2, result: "auth_failed" };
2486
+ if (response.status === 403 && errorCode === "consent_missing_or_expired")
2487
+ return { ...base2, result: "consent_missing" };
2488
+ if (response.status === 400 || response.status === 422)
2489
+ return { ...base2, result: "validation_failed" };
2490
+ return { ...base2, result: "transport_error" };
2127
2491
  }
2128
2492
  }
2129
2493
  });
@@ -2376,6 +2740,29 @@ var require_eventSender = __commonJS({
2376
2740
  }
2377
2741
  return outcome;
2378
2742
  }
2743
+ /**
2744
+ * One outbox pass with nothing live to send: what a background flusher runs,
2745
+ * once per batch. Unlike the pass {@link post} makes, it may run more than
2746
+ * once per sender, because a flusher isn't on anyone's critical path.
2747
+ *
2748
+ * A halted pass is journaled here. Inside {@link post} the live send that
2749
+ * follows journals it, and a flusher has no live send, so without this an
2750
+ * outage would never reach the journal `doctor` and the notices read.
2751
+ */
2752
+ async flushOutbox() {
2753
+ await this.renewIfExpiring();
2754
+ this.outboxServiced = false;
2755
+ this.lastDrain = void 0;
2756
+ const halted = await this.serviceOutbox();
2757
+ if (halted) {
2758
+ this.lastState = (0, stateStore_1.recordSendOutcome)(this.stateFilePath(), this.config.toolInstallationId, halted.result, {
2759
+ httpStatus: halted.httpStatus,
2760
+ errorCode: halted.errorCode,
2761
+ detail: withNote(halted.detail, "kept in outbox")
2762
+ });
2763
+ }
2764
+ return this.lastDrain;
2765
+ }
2379
2766
  /** A failure that never reached a verdict. Replaying can change the answer. */
2380
2767
  isRetryable(outcome) {
2381
2768
  return outcome.result === "transport_error" && (outcome.httpStatus === void 0 || (0, http_1.isRetryableStatus)(outcome.httpStatus));
@@ -2775,6 +3162,8 @@ var require_forgeProject = __commonJS({
2775
3162
  }();
2776
3163
  Object.defineProperty(exports, "__esModule", { value: true });
2777
3164
  exports.forgeProjectHash = forgeProjectHash2;
3165
+ exports.forgeRepoKey = forgeRepoKey2;
3166
+ exports.forgeBranchKey = forgeBranchKey2;
2778
3167
  exports.parseForgeFullName = parseForgeFullName;
2779
3168
  exports.readForgeFullName = readForgeFullName;
2780
3169
  exports.forgeFullNameFromConfig = forgeFullNameFromConfig;
@@ -2790,6 +3179,19 @@ var require_forgeProject = __commonJS({
2790
3179
  }
2791
3180
  return h.toString(16).padStart(8, "0");
2792
3181
  }
3182
+ function forgeRepoKey2(fullName) {
3183
+ return forgeProjectHash2(fullName.toLowerCase());
3184
+ }
3185
+ function forgeBranchKey2(fullName, branch) {
3186
+ const input = `${fullName.toLowerCase()}
3187
+ ${branch}`;
3188
+ let h = 0xcbf29ce484222325n;
3189
+ for (const byte of Buffer.from(input, "utf8")) {
3190
+ h ^= BigInt(byte);
3191
+ h = BigInt.asUintN(64, h * 0x100000001b3n);
3192
+ }
3193
+ return h.toString(16).padStart(16, "0");
3194
+ }
2793
3195
  function parseForgeFullName(remoteUrl) {
2794
3196
  if (!remoteUrl)
2795
3197
  return null;
@@ -3176,6 +3578,95 @@ var require_workContext = __commonJS({
3176
3578
  }
3177
3579
  });
3178
3580
 
3581
+ // ../packages/tool-kit/out/forgeKeys.js
3582
+ var require_forgeKeys = __commonJS({
3583
+ "../packages/tool-kit/out/forgeKeys.js"(exports) {
3584
+ "use strict";
3585
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
3586
+ if (k2 === void 0) k2 = k;
3587
+ var desc = Object.getOwnPropertyDescriptor(m, k);
3588
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
3589
+ desc = { enumerable: true, get: function() {
3590
+ return m[k];
3591
+ } };
3592
+ }
3593
+ Object.defineProperty(o, k2, desc);
3594
+ } : function(o, m, k, k2) {
3595
+ if (k2 === void 0) k2 = k;
3596
+ o[k2] = m[k];
3597
+ });
3598
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
3599
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
3600
+ } : function(o, v) {
3601
+ o["default"] = v;
3602
+ });
3603
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
3604
+ var ownKeys = function(o) {
3605
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
3606
+ var ar = [];
3607
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
3608
+ return ar;
3609
+ };
3610
+ return ownKeys(o);
3611
+ };
3612
+ return function(mod) {
3613
+ if (mod && mod.__esModule) return mod;
3614
+ var result = {};
3615
+ if (mod != null) {
3616
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
3617
+ }
3618
+ __setModuleDefault(result, mod);
3619
+ return result;
3620
+ };
3621
+ }();
3622
+ Object.defineProperty(exports, "__esModule", { value: true });
3623
+ exports.REPO_KEYS_ENV_VAR = void 0;
3624
+ exports.repoKeysEnabled = repoKeysEnabled2;
3625
+ exports.deriveForgeKeysForCwd = deriveForgeKeysForCwd;
3626
+ var fs = __importStar(__require("fs"));
3627
+ var path = __importStar(__require("path"));
3628
+ var credentials_1 = require_credentials();
3629
+ var forgeProject_1 = require_forgeProject();
3630
+ var workContext_1 = require_workContext();
3631
+ exports.REPO_KEYS_ENV_VAR = "ASCENDA_REPO_KEYS";
3632
+ function repoKeysEnabled2() {
3633
+ const env = process.env[exports.REPO_KEYS_ENV_VAR]?.trim().toLowerCase();
3634
+ if (env === "off" || env === "0" || env === "false")
3635
+ return false;
3636
+ if (env === "on" || env === "1" || env === "true")
3637
+ return true;
3638
+ return (0, credentials_1.readMachineCredentials)()?.repoKeys !== false;
3639
+ }
3640
+ function readDefaultBranch(repositoryRoot) {
3641
+ try {
3642
+ const head = fs.readFileSync(path.join(repositoryRoot, ".git", "refs", "remotes", "origin", "HEAD"), "utf8").trim();
3643
+ const match = /^ref:\s*refs\/remotes\/origin\/(.+)$/.exec(head);
3644
+ return match ? (0, workContext_1.normalizeBranchName)(match[1]) : null;
3645
+ } catch {
3646
+ return null;
3647
+ }
3648
+ }
3649
+ function deriveForgeKeysForCwd(cwd) {
3650
+ try {
3651
+ if (!cwd || !repoKeysEnabled2())
3652
+ return {};
3653
+ const root = (0, workContext_1.deriveWorkContext)(cwd)?.projectPath;
3654
+ const fullName = (0, forgeProject_1.readForgeFullName)(root);
3655
+ if (!root || !fullName)
3656
+ return {};
3657
+ const branch = (0, workContext_1.readBranchName)(cwd);
3658
+ const onDefault = branch !== null && branch === readDefaultBranch(root);
3659
+ return {
3660
+ repoKey: (0, forgeProject_1.forgeRepoKey)(fullName),
3661
+ ...branch && !onDefault ? { branchKey: (0, forgeProject_1.forgeBranchKey)(fullName, branch) } : {}
3662
+ };
3663
+ } catch {
3664
+ return {};
3665
+ }
3666
+ }
3667
+ }
3668
+ });
3669
+
3179
3670
  // ../packages/tool-kit/out/hookAdapter.js
3180
3671
  var require_hookAdapter = __commonJS({
3181
3672
  "../packages/tool-kit/out/hookAdapter.js"(exports) {
@@ -3185,13 +3676,18 @@ var require_hookAdapter = __commonJS({
3185
3676
  exports.resolveCliAgentInstallationId = resolveCliAgentInstallationId;
3186
3677
  exports.resolveContextHashes = resolveContextHashes;
3187
3678
  exports.loadCliAgentConfig = loadCliAgentConfig;
3679
+ exports.withForgeKeys = withForgeKeys;
3680
+ exports.withPromptId = withPromptId;
3188
3681
  exports.deliverHookEvents = deliverHookEvents;
3682
+ exports.flushHookOutbox = flushHookOutbox;
3189
3683
  var contextRegistry_1 = require_contextRegistry();
3190
3684
  var credentials_1 = require_credentials();
3191
3685
  var forgeProject_1 = require_forgeProject();
3192
3686
  var eventLog_1 = require_eventLog();
3687
+ var forgeKeys_1 = require_forgeKeys();
3193
3688
  var eventSender_1 = require_eventSender();
3194
3689
  var stateStore_1 = require_stateStore();
3690
+ var backgroundDelivery_1 = require_backgroundDelivery();
3195
3691
  var tokenStore_1 = require_tokenStore();
3196
3692
  var workContext_1 = require_workContext();
3197
3693
  exports.DEFAULT_API_BASE_URL = "https://api.ascenda.one";
@@ -3244,6 +3740,19 @@ var require_hookAdapter = __commonJS({
3244
3740
  };
3245
3741
  }
3246
3742
  function loadCliAgentConfig(toolType, sessionIdFromHook, cwd, identity = {}) {
3743
+ const pairing = loadCliAgentPairing(toolType, identity);
3744
+ const contextHashes = resolveContextHashes(cwd);
3745
+ return {
3746
+ ...pairing,
3747
+ // An empty ASCENDA_SESSION_ID is "unset", not "override with nothing":
3748
+ // read raw, `ASCENDA_SESSION_ID=""` beat a real hook session and shipped
3749
+ // an empty string, grouping unrelated rows under a value naming no session.
3750
+ sessionId: process.env.ASCENDA_SESSION_ID?.trim() || sessionIdFromHook || null,
3751
+ workspaceHash: contextHashes.workspaceHash,
3752
+ projectHash: contextHashes.projectHash
3753
+ };
3754
+ }
3755
+ function loadCliAgentPairing(toolType, identity) {
3247
3756
  const credentials = identity.host ? (0, credentials_1.readHostCredentials)(identity.host) : void 0;
3248
3757
  const apiBaseUrl = (process.env.ASCENDA_API_BASE_URL ?? credentials?.apiBaseUrl ?? exports.DEFAULT_API_BASE_URL).replace(/\/$/, "");
3249
3758
  const { toolInstallationId } = resolveCliAgentInstallationId(toolType, identity);
@@ -3254,26 +3763,33 @@ var require_hookAdapter = __commonJS({
3254
3763
  throw new Error("Missing ASCENDA_EVENT_WRITE_TOKEN (or token file)");
3255
3764
  if (!fileToken)
3256
3765
  (0, tokenStore_1.persistEventWriteToken)(tokenFilePath, eventWriteToken);
3257
- const contextHashes = resolveContextHashes(cwd);
3258
3766
  return {
3259
3767
  apiBaseUrl,
3260
3768
  toolInstallationId,
3261
3769
  eventWriteToken,
3262
3770
  tokenFilePath,
3263
- // An empty ASCENDA_SESSION_ID is "unset", not "override with nothing":
3264
- // read raw, `ASCENDA_SESSION_ID=""` beat a real hook session and shipped
3265
- // an empty string, grouping unrelated rows under a value naming no session.
3266
- sessionId: process.env.ASCENDA_SESSION_ID?.trim() || sessionIdFromHook || null,
3267
- workspaceHash: contextHashes.workspaceHash,
3268
- projectHash: contextHashes.projectHash,
3269
3771
  // Agents await command hooks; fail fast rather than stall the user's turn.
3270
3772
  timeoutMs: parsePositiveInt(process.env.ASCENDA_HTTP_TIMEOUT_MS) ?? 3e3
3271
3773
  };
3272
3774
  }
3775
+ function withForgeKeys(events, cwd) {
3776
+ const keys = (0, forgeKeys_1.deriveForgeKeysForCwd)(cwd ?? process.cwd());
3777
+ if (!keys.repoKey)
3778
+ return events;
3779
+ return events.map((event) => ({ ...event, metadata: { ...keys, ...event.metadata } }));
3780
+ }
3781
+ function withPromptId(events, promptId) {
3782
+ if (!promptId)
3783
+ return events;
3784
+ return events.map((event) => ({ ...event, metadata: { promptId, ...event.metadata } }));
3785
+ }
3273
3786
  async function deliverHookEvents(events, options) {
3274
3787
  if (events.length === 0)
3275
3788
  return;
3276
- const notice = options.onNotice ?? ((message) => console.error(message));
3789
+ events = withPromptId(events, options.promptId);
3790
+ if (options.forgeKeys)
3791
+ events = withForgeKeys(events, options.cwd);
3792
+ const notice = options.onNotice ?? ((message2) => console.error(message2));
3277
3793
  const hasToken = (id) => (0, tokenStore_1.readTokenFile)(process.env.ASCENDA_EVENT_WRITE_TOKEN_FILE ?? (0, tokenStore_1.defaultTokenFilePath)(id)) !== void 0;
3278
3794
  if (options.host && (0, credentials_1.isLocalOnlyHostInstall)(options.host, hasToken)) {
3279
3795
  const logFile = (0, eventLog_1.resolveEventLogPath)({ localOnly: true });
@@ -3304,21 +3820,55 @@ var require_hookAdapter = __commonJS({
3304
3820
  projectHash: config.projectHash,
3305
3821
  timeoutMs: config.timeoutMs
3306
3822
  });
3307
- for (const event of events) {
3308
- const result = await sender.send(event);
3309
- if (result === "accepted")
3310
- continue;
3311
- if (result === "consent_missing") {
3312
- notice("Ascenda telemetry paused: renew IDE telemetry consent in the Ascenda app.");
3313
- } else if (result === "auth_failed") {
3314
- notice("Ascenda telemetry paused: connection revoked or expired. Re-pair via an Ascenda IDE extension or pairing-sim.");
3315
- } else if (result === "transport_error") {
3316
- notice("Ascenda telemetry paused: the ingest endpoint could not be reached; the event is kept in the outbox. Your work is unaffected.");
3317
- } else {
3318
- notice(`Ascenda telemetry rejected: ${result}`);
3823
+ if ((0, backgroundDelivery_1.hookDeliveryInline)()) {
3824
+ for (const event of events) {
3825
+ const result = await sender.send(event);
3826
+ if (result === "accepted")
3827
+ continue;
3828
+ const message2 = noticeFor(result);
3829
+ if (message2)
3830
+ notice(message2);
3831
+ return;
3319
3832
  }
3320
3833
  return;
3321
3834
  }
3835
+ for (const event of events)
3836
+ sender.queue(event);
3837
+ (0, backgroundDelivery_1.startBackgroundFlush)({ outboxFilePath: sender.outboxFilePath() });
3838
+ const last = (0, stateStore_1.readCollectorState)(sender.stateFilePath())?.lastOutcome;
3839
+ const message = last ? noticeFor(last) : void 0;
3840
+ if (message)
3841
+ notice(message);
3842
+ }
3843
+ function noticeFor(result) {
3844
+ if (result === "accepted" || result === "duplicate")
3845
+ return void 0;
3846
+ if (result === "consent_missing")
3847
+ return "Ascenda telemetry paused: renew IDE telemetry consent in the Ascenda app.";
3848
+ if (result === "auth_failed")
3849
+ return "Ascenda telemetry paused: connection revoked or expired. Re-pair via an Ascenda IDE extension or pairing-sim.";
3850
+ if (result === "transport_error")
3851
+ return "Ascenda telemetry paused: the ingest endpoint could not be reached; the event is kept in the outbox. Your work is unaffected.";
3852
+ if (result === "outbox_discarded")
3853
+ return void 0;
3854
+ return `Ascenda telemetry rejected: ${result}`;
3855
+ }
3856
+ async function flushHookOutbox(options) {
3857
+ let config;
3858
+ try {
3859
+ config = loadCliAgentPairing(options.toolType, options);
3860
+ } catch {
3861
+ return;
3862
+ }
3863
+ const sender = new eventSender_1.AscendaEventSender({
3864
+ apiBaseUrl: config.apiBaseUrl,
3865
+ toolInstallationId: config.toolInstallationId,
3866
+ source: options.source,
3867
+ eventWriteToken: config.eventWriteToken,
3868
+ tokenFilePath: config.tokenFilePath,
3869
+ timeoutMs: config.timeoutMs
3870
+ });
3871
+ await (0, backgroundDelivery_1.runOutboxFlush)(sender);
3322
3872
  }
3323
3873
  function logUnsent(logFile, events, options) {
3324
3874
  const contextHashes = resolveContextHashes(options.cwd);
@@ -3820,52 +4370,6 @@ var require_initiatives = __commonJS({
3820
4370
  }
3821
4371
  });
3822
4372
 
3823
- // ../packages/tool-kit/out/setupDisclosure.js
3824
- var require_setupDisclosure = __commonJS({
3825
- "../packages/tool-kit/out/setupDisclosure.js"(exports) {
3826
- "use strict";
3827
- Object.defineProperty(exports, "__esModule", { value: true });
3828
- exports.FREE_TEXT_KEYS = exports.REFUSALS = exports.ALWAYS_SENT = exports.FAMILY_SENTENCES = void 0;
3829
- exports.renderSetupDisclosure = renderSetupDisclosure;
3830
- exports.FAMILY_SENTENCES = {
3831
- 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",
3832
- 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",
3833
- tools: "the name of each tool your agent calls",
3834
- outcome: "whether a call succeeded, failed, or was interrupted",
3835
- clock: "your machine's offset from UTC, so an evening is read as an evening",
3836
- repo: "your project and branch as digests computed on this machine \u2014 never the names themselves",
3837
- model: "which model served the session, by name and by tier",
3838
- posture: "the permission posture your agent was working under \u2014 asking each time, accepting edits, and so on",
3839
- git: "that a commit, push or revert happened, and when a pull request opened or merged",
3840
- edits: "roughly how much a file changed, as a bucket, and whether you edited it after the agent wrote it",
3841
- context: "how full the context window got",
3842
- waiting: "that your agent stopped and waited for you, as one word: permission_request, idle_prompt, or other",
3843
- 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",
3844
- 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"
3845
- };
3846
- exports.ALWAYS_SENT = ["session", "counts", "tools", "outcome", "repo", "clock"];
3847
- exports.REFUSALS = [
3848
- "Never your prompts, your agent's replies, or anything inside a file.",
3849
- "Never a file path, a command line, or a repository or branch name.",
3850
- "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."
3851
- ];
3852
- exports.FREE_TEXT_KEYS = ["message"];
3853
- function renderSetupDisclosure({ sends, displayName }) {
3854
- const declared = /* @__PURE__ */ new Set([...exports.ALWAYS_SENT, ...sends]);
3855
- const ordered = Object.keys(exports.FAMILY_SENTENCES).filter((family) => declared.has(family));
3856
- const lines = [
3857
- `What this sends from ${displayName}, once paired:`,
3858
- ...ordered.map((family) => ` \xB7 ${exports.FAMILY_SENTENCES[family]}`),
3859
- "",
3860
- ...exports.REFUSALS.map((line) => ` ${line}`),
3861
- "",
3862
- " Turn it off by revoking this tool in the Ascenda app."
3863
- ];
3864
- return lines.join("\n");
3865
- }
3866
- }
3867
- });
3868
-
3869
4373
  // ../packages/tool-kit/out/hookRunner.js
3870
4374
  var require_hookRunner = __commonJS({
3871
4375
  "../packages/tool-kit/out/hookRunner.js"(exports) {
@@ -3910,9 +4414,11 @@ var require_hookRunner = __commonJS({
3910
4414
  Object.defineProperty(exports, "__esModule", { value: true });
3911
4415
  exports.hookRunnerPaths = hookRunnerPaths;
3912
4416
  exports.hookLauncherScript = hookLauncherScript;
4417
+ exports.isDowngrade = isDowngrade;
3913
4418
  exports.installHookRunner = installHookRunner;
3914
4419
  exports.removeHookRunner = removeHookRunner;
3915
4420
  exports.hookRunnerCommand = hookRunnerCommand;
4421
+ exports.writeAtomically = writeAtomically;
3916
4422
  exports.lastHookPath = lastHookPath;
3917
4423
  exports.stampLastHook = stampLastHook;
3918
4424
  exports.readLastHook = readLastHook;
@@ -3922,10 +4428,11 @@ var require_hookRunner = __commonJS({
3922
4428
  var child_process_1 = __require("child_process");
3923
4429
  var fs = __importStar(__require("fs"));
3924
4430
  var path = __importStar(__require("path"));
4431
+ var collectorVersion_1 = require_collectorVersion();
3925
4432
  var tokenStore_1 = require_tokenStore();
3926
4433
  function hookRunnerPaths(binaryName) {
3927
4434
  const launcher = path.join((0, tokenStore_1.ascendaHome)(), "bin", binaryName);
3928
- return { launcher, bundle: `${launcher}.mjs`, record: `${launcher}.node`, noNode: `${launcher}.no-node` };
4435
+ return { launcher, bundle: `${launcher}.mjs`, record: `${launcher}.node`, noNode: `${launcher}.no-node`, version: `${launcher}.version` };
3929
4436
  }
3930
4437
  var LAUNCHER_MANAGEMENT_COMMANDS = ["setup", "install", "status", "uninstall", "doctor", "pair", "join", "object", "-h", "--help"];
3931
4438
  function hookLauncherScript(options) {
@@ -4019,21 +4526,57 @@ var require_hookRunner = __commonJS({
4019
4526
  ""
4020
4527
  ].join("\n");
4021
4528
  }
4529
+ function releaseOf(version) {
4530
+ const match = /^v?(\d+)\.(\d+)\.(\d+)/.exec((version ?? "").trim());
4531
+ return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : void 0;
4532
+ }
4533
+ function isDowngrade(installed, incoming) {
4534
+ const have = releaseOf(installed);
4535
+ const want = releaseOf(incoming);
4536
+ if (!have || !want)
4537
+ return false;
4538
+ for (let i = 0; i < 3; i++) {
4539
+ if (have[i] !== want[i])
4540
+ return have[i] > want[i];
4541
+ }
4542
+ return false;
4543
+ }
4544
+ function readInstalledVersion(file) {
4545
+ try {
4546
+ return fs.readFileSync(file, "utf8").trim() || void 0;
4547
+ } catch {
4548
+ return void 0;
4549
+ }
4550
+ }
4022
4551
  function installHookRunner(options) {
4023
4552
  const paths = hookRunnerPaths(options.binaryName);
4024
4553
  if (options.dryRun)
4025
4554
  return paths.launcher;
4026
4555
  const source = path.resolve(options.source ?? process.argv[1]);
4556
+ const incoming = options.version ?? collectorVersion_1.COLLECTOR_VERSION;
4557
+ const installed = readInstalledVersion(paths.version);
4558
+ const installedFile = process.platform === "win32" ? paths.launcher : paths.bundle;
4559
+ if (installed && fs.existsSync(installedFile) && isDowngrade(installed, incoming)) {
4560
+ options.onKeptNewer?.(installed, incoming);
4561
+ if (process.platform !== "win32" && !fs.existsSync(paths.launcher))
4562
+ writeAtomically(paths.launcher, hookLauncherScript(options), 493);
4563
+ return paths.launcher;
4564
+ }
4027
4565
  fs.mkdirSync(path.dirname(paths.launcher), { recursive: true });
4028
4566
  if (process.platform === "win32") {
4029
4567
  if (source !== path.resolve(paths.launcher))
4030
4568
  fs.copyFileSync(source, paths.launcher);
4569
+ writeAtomically(paths.version, `${incoming}
4570
+ `, 420);
4031
4571
  return paths.launcher;
4032
4572
  }
4033
4573
  if (source !== path.resolve(paths.bundle))
4034
4574
  writeAtomically(paths.bundle, fs.readFileSync(source), 493);
4035
4575
  writeAtomically(paths.launcher, hookLauncherScript(options), 493);
4036
4576
  writeAtomically(paths.record, `${process.execPath}
4577
+ `, 420);
4578
+ if (source !== path.resolve(paths.bundle))
4579
+ writeAtomically(paths.version, `${incoming}
4037
4580
  `, 420);
4038
4581
  fs.rmSync(paths.noNode, { force: true });
4039
4582
  return paths.launcher;
@@ -4048,8 +4591,8 @@ var require_hookRunner = __commonJS({
4048
4591
  }
4049
4592
  return removed;
4050
4593
  }
4051
- function hookRunnerCommand(launcher) {
4052
- return process.platform === "win32" ? `"${process.execPath}" "${launcher}"` : `"${launcher}"`;
4594
+ function hookRunnerCommand(launcher, platform = process.platform) {
4595
+ return platform === "win32" ? `"${process.execPath}" "${launcher}"` : `"${launcher}"`;
4053
4596
  }
4054
4597
  function writeAtomically(target, contents, mode) {
4055
4598
  const tmp = `${target}.${process.pid}.tmp`;
@@ -4119,6 +4662,115 @@ var require_hookRunner = __commonJS({
4119
4662
  }
4120
4663
  });
4121
4664
 
4665
+ // ../packages/tool-kit/out/settingsFile.js
4666
+ var require_settingsFile = __commonJS({
4667
+ "../packages/tool-kit/out/settingsFile.js"(exports) {
4668
+ "use strict";
4669
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
4670
+ if (k2 === void 0) k2 = k;
4671
+ var desc = Object.getOwnPropertyDescriptor(m, k);
4672
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
4673
+ desc = { enumerable: true, get: function() {
4674
+ return m[k];
4675
+ } };
4676
+ }
4677
+ Object.defineProperty(o, k2, desc);
4678
+ } : function(o, m, k, k2) {
4679
+ if (k2 === void 0) k2 = k;
4680
+ o[k2] = m[k];
4681
+ });
4682
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
4683
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
4684
+ } : function(o, v) {
4685
+ o["default"] = v;
4686
+ });
4687
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
4688
+ var ownKeys = function(o) {
4689
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
4690
+ var ar = [];
4691
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
4692
+ return ar;
4693
+ };
4694
+ return ownKeys(o);
4695
+ };
4696
+ return function(mod) {
4697
+ if (mod && mod.__esModule) return mod;
4698
+ var result = {};
4699
+ if (mod != null) {
4700
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
4701
+ }
4702
+ __setModuleDefault(result, mod);
4703
+ return result;
4704
+ };
4705
+ }();
4706
+ Object.defineProperty(exports, "__esModule", { value: true });
4707
+ exports.replaceSettingsFile = replaceSettingsFile;
4708
+ var fs = __importStar(__require("fs"));
4709
+ var path = __importStar(__require("path"));
4710
+ var hookRunner_1 = require_hookRunner();
4711
+ function replaceSettingsFile(settingsFile, contents) {
4712
+ const exists = fs.existsSync(settingsFile);
4713
+ const target = exists ? fs.realpathSync(settingsFile) : settingsFile;
4714
+ if (exists) {
4715
+ const backup = `${settingsFile}.ascenda-backup`;
4716
+ if (!fs.existsSync(backup))
4717
+ fs.copyFileSync(target, backup);
4718
+ }
4719
+ fs.mkdirSync(path.dirname(target), { recursive: true });
4720
+ const mode = exists ? fs.statSync(target).mode & 511 : 420;
4721
+ (0, hookRunner_1.writeAtomically)(target, contents, mode);
4722
+ }
4723
+ }
4724
+ });
4725
+
4726
+ // ../packages/tool-kit/out/setupDisclosure.js
4727
+ var require_setupDisclosure = __commonJS({
4728
+ "../packages/tool-kit/out/setupDisclosure.js"(exports) {
4729
+ "use strict";
4730
+ Object.defineProperty(exports, "__esModule", { value: true });
4731
+ exports.FREE_TEXT_KEYS = exports.REFUSALS = exports.ALWAYS_SENT = exports.FAMILY_SENTENCES = void 0;
4732
+ exports.renderSetupDisclosure = renderSetupDisclosure;
4733
+ exports.FAMILY_SENTENCES = {
4734
+ 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",
4735
+ 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",
4736
+ tools: "the name of each tool your agent calls",
4737
+ outcome: "whether a call succeeded, failed, or was interrupted",
4738
+ clock: "your machine's offset from UTC, so an evening is read as an evening",
4739
+ repo: "your project and branch as digests computed on this machine \u2014 never the names themselves",
4740
+ model: "which model served the session, by name and by tier",
4741
+ posture: "the permission posture your agent was working under \u2014 asking each time, accepting edits, and so on",
4742
+ git: "that a commit, push or revert happened, and when a pull request opened or merged",
4743
+ edits: "roughly how much a file changed, as a bucket, and whether you edited it after the agent wrote it",
4744
+ context: "how full the context window got",
4745
+ waiting: "that your agent stopped and waited for you, as one word: permission_request, input_request, idle_prompt, or other, and that it asked permission for a tool or had one refused in auto mode, with the tool's name",
4746
+ 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",
4747
+ forge: "for a GitHub repository, one digest of owner/repo and one of the branch, which anyone who guesses the names can reproduce, so a pull request can be matched to your session (turn off with setup --no-repo-keys)",
4748
+ turns: "an opaque id your agent gives each prompt, so one turn's events group together",
4749
+ 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"
4750
+ };
4751
+ exports.ALWAYS_SENT = ["session", "counts", "tools", "outcome", "repo", "clock"];
4752
+ exports.REFUSALS = [
4753
+ "Never your prompts, your agent's replies, or anything inside a file.",
4754
+ "Never a file path, a command line, or a repository or branch name.",
4755
+ "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."
4756
+ ];
4757
+ exports.FREE_TEXT_KEYS = ["message"];
4758
+ function renderSetupDisclosure({ sends, displayName }) {
4759
+ const declared = /* @__PURE__ */ new Set([...exports.ALWAYS_SENT, ...sends]);
4760
+ const ordered = Object.keys(exports.FAMILY_SENTENCES).filter((family) => declared.has(family));
4761
+ const lines = [
4762
+ `What this sends from ${displayName}, once paired:`,
4763
+ ...ordered.map((family) => ` \xB7 ${exports.FAMILY_SENTENCES[family]}`),
4764
+ "",
4765
+ ...exports.REFUSALS.map((line) => ` ${line}`),
4766
+ "",
4767
+ " Turn it off by revoking this tool in the Ascenda app."
4768
+ ];
4769
+ return lines.join("\n");
4770
+ }
4771
+ }
4772
+ });
4773
+
4122
4774
  // ../packages/tool-kit/out/saverHandoff.js
4123
4775
  var require_saverHandoff = __commonJS({
4124
4776
  "../packages/tool-kit/out/saverHandoff.js"(exports) {
@@ -4884,6 +5536,8 @@ var require_cliAgentSetup = __commonJS({
4884
5536
  exports.runCliAgentSetup = runCliAgentSetup;
4885
5537
  exports.writeHookSettings = writeHookSettings;
4886
5538
  exports.registeredHookSets = registeredHookSets;
5539
+ exports.ourHookPositions = ourHookPositions;
5540
+ exports.trustProblemLines = trustProblemLines;
4887
5541
  exports.findStaleHookCommands = findStaleHookCommands;
4888
5542
  exports.cliAgentRegistrations = cliAgentRegistrations;
4889
5543
  var crypto = __importStar(__require("crypto"));
@@ -4897,6 +5551,7 @@ var require_cliAgentSetup = __commonJS({
4897
5551
  var http_1 = require_http();
4898
5552
  var hookSet_1 = require_hookSet();
4899
5553
  var initiatives_1 = require_initiatives();
5554
+ var settingsFile_1 = require_settingsFile();
4900
5555
  var setupDisclosure_1 = require_setupDisclosure();
4901
5556
  var hookRunner_1 = require_hookRunner();
4902
5557
  var liveSignalDoctor_1 = require_liveSignalDoctor();
@@ -4933,6 +5588,10 @@ Options
4933
5588
  --no-pair install without pairing: local features on, nothing sent
4934
5589
  --event-log [path|off] keep every event in a local JSONL file (default ~/.ascenda/events.jsonl).
4935
5590
  On by default when not paired; machine-wide, shared by every agent
5591
+ --no-repo-keys leave the repository and branch keys off every event. On by default: a GitHub
5592
+ repository gets a key and, off its default branch, a branch key, so a pull
5593
+ request can be matched to a session. They are digests anyone who guesses the
5594
+ names can reproduce. Machine-wide. --repo-keys turns them back on
4936
5595
  --scope user|project where hooks are registered (default user: every project)
4937
5596
  --project-dir <path> project root for --scope project (default cwd)
4938
5597
  --dry-run print what would change, write nothing
@@ -4989,6 +5648,8 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
4989
5648
  });
4990
5649
  if (options.eventLog !== void 0)
4991
5650
  (0, credentials_1.writeEventLogSetting)(options.eventLog);
5651
+ if (options.repoKeys !== void 0)
5652
+ (0, credentials_1.writeRepoKeysSetting)(options.repoKeys);
4992
5653
  }
4993
5654
  if (isHomeProject(options)) {
4994
5655
  detail("scope", "user (a project install in the home folder only loads when the agent starts there)");
@@ -5128,6 +5789,12 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
5128
5789
  i += consumed;
5129
5790
  break;
5130
5791
  }
5792
+ case "--repo-keys":
5793
+ options.repoKeys = true;
5794
+ break;
5795
+ case "--no-repo-keys":
5796
+ options.repoKeys = false;
5797
+ break;
5131
5798
  case "--no-pair":
5132
5799
  // `--no-pairing` is the spelling this landed under first. Both appeared
5133
5800
  // only in an unreleased changelog, so this alias exists to spare anyone
@@ -5257,7 +5924,12 @@ Pairing ${status.status}. Run setup again.`);
5257
5924
  return void 0;
5258
5925
  }
5259
5926
  function installBinary(spec, dryRun) {
5260
- return (0, hookRunner_1.installHookRunner)({ binaryName: spec.binaryName, setupCommand: `npx ${spec.packageName} setup`, dryRun });
5927
+ return (0, hookRunner_1.installHookRunner)({
5928
+ binaryName: spec.binaryName,
5929
+ setupCommand: `npx ${spec.packageName} setup`,
5930
+ dryRun,
5931
+ onKeptNewer: (installed, incoming) => console.log(` Kept the installed hook bundle (${installed}) rather than replace it with this older ${incoming}. Run setup from the newer version to change it.`)
5932
+ });
5261
5933
  }
5262
5934
  function writeHookSettings(settingsFile, binary, spec, dryRun) {
5263
5935
  let settings = { ...spec.settings.scaffold ?? {} };
@@ -5277,8 +5949,7 @@ ${settingsFile} is not valid JSON. Fix or move it, then run setup again.`);
5277
5949
  const command = hookCommand(binary, spec);
5278
5950
  const hooks = { ...settings.hooks ?? {} };
5279
5951
  for (const event of spec.hookEvents) {
5280
- const kept = (hooks[event] ?? []).filter((entry) => !isOurs(entry, spec));
5281
- hooks[event] = [...kept, spec.settings.entry(command, event)];
5952
+ hooks[event] = placeOurEntry(hooks[event] ?? [], spec.settings.entry(command, event), spec);
5282
5953
  }
5283
5954
  const updated = { ...settings, hooks };
5284
5955
  const serialised = `${JSON.stringify(updated, null, 2)}
@@ -5291,10 +5962,7 @@ ${settingsFile} is not valid JSON. Fix or move it, then run setup again.`);
5291
5962
  ${serialised}`);
5292
5963
  return true;
5293
5964
  }
5294
- if (exists)
5295
- fs.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
5296
- fs.mkdirSync(path.dirname(settingsFile), { recursive: true });
5297
- fs.writeFileSync(settingsFile, serialised, "utf8");
5965
+ (0, settingsFile_1.replaceSettingsFile)(settingsFile, serialised);
5298
5966
  return true;
5299
5967
  }
5300
5968
  function hookCommand(binary, spec) {
@@ -5304,28 +5972,130 @@ ${serialised}`);
5304
5972
  const sets = /* @__PURE__ */ new Map();
5305
5973
  for (const [event, entries] of Object.entries(settings.hooks ?? {})) {
5306
5974
  for (const entry of entries ?? []) {
5307
- if (!isOurs(entry, spec))
5308
- continue;
5309
- const set = (0, hookSet_1.hookSetOfCommand)(spec.settings.commandOf(entry));
5310
- sets.set(event, Math.min(set, sets.get(event) ?? set));
5975
+ for (const command of commandsOf(entry, spec)) {
5976
+ if (!isOurCommand(command, spec))
5977
+ continue;
5978
+ const set = (0, hookSet_1.hookSetOfCommand)(command);
5979
+ sets.set(event, Math.min(set, sets.get(event) ?? set));
5980
+ }
5311
5981
  }
5312
5982
  }
5313
5983
  return sets;
5314
5984
  }
5315
- function isOurs(entry, spec) {
5985
+ function ourHookPositions(settings, spec) {
5986
+ const found = [];
5987
+ for (const [event, groups] of Object.entries(settings.hooks ?? {})) {
5988
+ (groups ?? []).forEach((group, groupIndex) => {
5989
+ const handlers = group?.hooks;
5990
+ if (Array.isArray(handlers)) {
5991
+ handlers.forEach((handler, handlerIndex) => {
5992
+ if (isOurs({ hooks: [handler] }, spec))
5993
+ found.push({ event, group: groupIndex, handler: handlerIndex });
5994
+ });
5995
+ } else if (isOurs(group, spec)) {
5996
+ found.push({ event, group: groupIndex, handler: 0 });
5997
+ }
5998
+ });
5999
+ }
6000
+ return found;
6001
+ }
6002
+ function trustProblemLines(spec, settingsFile, settings, indent) {
6003
+ if (!spec.trust)
6004
+ return [];
6005
+ const ours = ourHookPositions(settings, spec);
6006
+ if (ours.length === 0)
6007
+ return [];
6008
+ const report = spec.trust.check(settingsFile, ours);
6009
+ const where = (0, hookRunner_1.tidyHomePath)(report.approvalsFile, os.homedir());
6010
+ const lines = [];
6011
+ if (report.unreadable) {
6012
+ lines.push(`${spec.displayName}'s approvals in ${where} could not be read, so whether these hooks are trusted is unknown.`);
6013
+ }
6014
+ if (report.untrusted.length) {
6015
+ const names = [...new Set(report.untrusted.map((position) => position.event))].join(", ");
6016
+ lines.push(`${report.untrusted.length} of ${ours.length} hooks are not approved in ${where} (${names}). ${spec.displayName} skips them without a message, so nothing is sent for those events.`);
6017
+ }
6018
+ for (const entry of report.stale)
6019
+ lines.push(entry);
6020
+ if (lines.length)
6021
+ lines.push(spec.trust.fix);
6022
+ return lines.map((line) => `${indent}${line}`);
6023
+ }
6024
+ function commandsOf(entry, spec) {
6025
+ if (spec.settings.grouped) {
6026
+ return innerHooks(entry).map(commandOfHook).filter((command2) => typeof command2 === "string");
6027
+ }
5316
6028
  const command = spec.settings.commandOf(entry);
5317
- return typeof command === "string" && command.includes(spec.binaryName);
6029
+ return typeof command === "string" ? [command] : [];
6030
+ }
6031
+ function innerHooks(entry) {
6032
+ const hooks = entry && typeof entry === "object" ? entry.hooks : void 0;
6033
+ return Array.isArray(hooks) ? hooks : [];
6034
+ }
6035
+ function commandOfHook(hook) {
6036
+ return hook && typeof hook === "object" ? hook.command : void 0;
6037
+ }
6038
+ function isOurCommand(command, spec) {
6039
+ return command.includes(spec.binaryName);
6040
+ }
6041
+ function isOurs(entry, spec) {
6042
+ return commandsOf(entry, spec).some((command) => isOurCommand(command, spec));
6043
+ }
6044
+ function isOurInnerHook(hook, spec) {
6045
+ const command = commandOfHook(hook);
6046
+ return typeof command === "string" && isOurCommand(command, spec);
6047
+ }
6048
+ function withoutOurEntries(entries, spec) {
6049
+ if (!spec.settings.grouped)
6050
+ return entries.filter((entry) => !isOurs(entry, spec));
6051
+ const kept = [];
6052
+ for (const entry of entries) {
6053
+ if (!isOurs(entry, spec)) {
6054
+ kept.push(entry);
6055
+ continue;
6056
+ }
6057
+ const others = innerHooks(entry).filter((hook) => !isOurInnerHook(hook, spec));
6058
+ if (others.length)
6059
+ kept.push({ ...entry, hooks: others });
6060
+ }
6061
+ return kept;
6062
+ }
6063
+ function placeOurEntry(entries, wanted, spec) {
6064
+ if (!spec.settings.grouped)
6065
+ return [...withoutOurEntries(entries, spec), wanted];
6066
+ const replacements = innerHooks(wanted);
6067
+ let placed = false;
6068
+ const result = [];
6069
+ for (const entry of entries) {
6070
+ if (!isOurs(entry, spec)) {
6071
+ result.push(entry);
6072
+ continue;
6073
+ }
6074
+ const matcher = entry.matcher;
6075
+ const matchesAll = matcher === void 0 || matcher === "";
6076
+ const next = [];
6077
+ for (const hook of innerHooks(entry)) {
6078
+ if (!isOurInnerHook(hook, spec))
6079
+ next.push(hook);
6080
+ else if (!placed && matchesAll) {
6081
+ next.push(...replacements);
6082
+ placed = true;
6083
+ }
6084
+ }
6085
+ if (next.length)
6086
+ result.push({ ...entry, hooks: next });
6087
+ }
6088
+ return placed ? result : [...result, wanted];
5318
6089
  }
5319
6090
  function findStaleHookCommands(settings, binary, spec) {
5320
6091
  const stale = /* @__PURE__ */ new Set();
5321
6092
  for (const entries of Object.values(settings.hooks ?? {})) {
5322
6093
  for (const entry of entries ?? []) {
5323
- const command = spec.settings.commandOf(entry);
5324
- if (typeof command !== "string")
5325
- continue;
5326
- if (!/ascenda/i.test(command) || command.includes(binary))
5327
- continue;
5328
- stale.add(command);
6094
+ for (const command of commandsOf(entry, spec)) {
6095
+ if (!/ascenda/i.test(command) || command.includes(binary))
6096
+ continue;
6097
+ stale.add(command);
6098
+ }
5329
6099
  }
5330
6100
  }
5331
6101
  return [...stale];
@@ -5369,6 +6139,14 @@ ${serialised}`);
5369
6139
  const oldest = Math.min(...sets);
5370
6140
  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)`);
5371
6141
  }
6142
+ const trustLines = trustProblemLines(spec, settingsFile, settings, "");
6143
+ if (trustLines.length) {
6144
+ console.log(`not trusted ${trustLines[0]}`);
6145
+ for (const line of trustLines.slice(1))
6146
+ console.log(` ${line}`);
6147
+ } else if (spec.trust && registered > 0) {
6148
+ console.log("trust every registered hook is approved");
6149
+ }
5372
6150
  if (stale.length) {
5373
6151
  console.log(`stale hooks ${stale.length} not pointing at the installed binary \u2014 each one fails silently per event:`);
5374
6152
  for (const command of stale)
@@ -5390,7 +6168,7 @@ ${serialised}`);
5390
6168
  await notices.markShown();
5391
6169
  const paired = localOnly || credentials?.toolInstallationId !== void 0;
5392
6170
  const wired = registered === spec.hookEvents.length || options.scope === "project" && elsewhere === spec.hookEvents.length;
5393
- const healthy = paired && wired && fs.existsSync(binary) && !stale.length && !node?.problem;
6171
+ const healthy = paired && wired && fs.existsSync(binary) && !stale.length && !node?.problem && trustLines.length === 0;
5394
6172
  return healthy ? 0 : 1;
5395
6173
  }
5396
6174
  function countRegistered(settings, spec) {
@@ -5433,12 +6211,37 @@ ${serialised}`);
5433
6211
  } catch (error) {
5434
6212
  lines.push(` Live signal (could not be checked: ${error instanceof Error ? error.message : String(error)})`);
5435
6213
  }
6214
+ if (spec.trust) {
6215
+ const found = trustDoctorLines(spec, options.projectDir, ui);
6216
+ if (found.length)
6217
+ lines.push("", ...found);
6218
+ }
5436
6219
  lines.push("", ...accountLines(ui, spec));
5437
6220
  const localOnly = (0, credentials_1.isLocalOnlyHostInstall)(spec.host, (id) => (0, tokenStore_1.readTokenFile)((0, tokenStore_1.defaultTokenFilePath)(id)) !== void 0);
5438
6221
  lines.push("", ` ${ui.bold("Local events")} ${(0, eventLog_1.describeEventLog)((0, eventLog_1.resolveEventLog)({ localOnly }), `npx ${spec.packageName} setup`)}`);
5439
6222
  console.log(lines.join("\n"));
5440
6223
  return 0;
5441
6224
  }
6225
+ function trustDoctorLines(spec, projectDir, ui) {
6226
+ const userFile = spec.settings.settingsPath("user", projectDir);
6227
+ const projectFile = spec.settings.settingsPath("project", projectDir);
6228
+ const files = userFile === projectFile ? [userFile] : [userFile, projectFile];
6229
+ const out = [];
6230
+ for (const file of files) {
6231
+ const settings = readSettings(file);
6232
+ if (ourHookPositions(settings, spec).length === 0)
6233
+ continue;
6234
+ const problems = trustProblemLines(spec, file, settings, "");
6235
+ if (problems.length === 0) {
6236
+ out.push(` ${ui.mark("ok")} ${"Hook approvals".padEnd(20)} every hook in ${(0, hookRunner_1.tidyHomePath)(file, os.homedir())} is approved`);
6237
+ continue;
6238
+ }
6239
+ out.push(` ${ui.mark("bad")} ${"Hook approvals".padEnd(20)} ${ui.red(problems[0])}`);
6240
+ for (const line of problems.slice(1))
6241
+ out.push(`${" ".repeat(25)}${line}`);
6242
+ }
6243
+ return out;
6244
+ }
5442
6245
  function accountLines(ui, spec) {
5443
6246
  const credentials = (0, credentials_1.readHostCredentials)(spec.host);
5444
6247
  const id = credentials?.toolInstallationId;
@@ -5472,7 +6275,7 @@ ${serialised}`);
5472
6275
  const settings = JSON.parse(fs.readFileSync(settingsFile, "utf8"));
5473
6276
  const hooks = { ...settings.hooks ?? {} };
5474
6277
  for (const event of Object.keys(hooks)) {
5475
- const kept = hooks[event].filter((entry) => !isOurs(entry, spec));
6278
+ const kept = withoutOurEntries(hooks[event], spec);
5476
6279
  if (kept.length)
5477
6280
  hooks[event] = kept;
5478
6281
  else
@@ -5481,9 +6284,8 @@ ${serialised}`);
5481
6284
  const updated = { ...settings, hooks };
5482
6285
  if (!Object.keys(hooks).length)
5483
6286
  delete updated.hooks;
5484
- fs.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
5485
- fs.writeFileSync(settingsFile, `${JSON.stringify(updated, null, 2)}
5486
- `, "utf8");
6287
+ (0, settingsFile_1.replaceSettingsFile)(settingsFile, `${JSON.stringify(updated, null, 2)}
6288
+ `);
5487
6289
  return true;
5488
6290
  } catch {
5489
6291
  return false;
@@ -5555,7 +6357,9 @@ var require_turnState = __commonJS({
5555
6357
  }();
5556
6358
  Object.defineProperty(exports, "__esModule", { value: true });
5557
6359
  exports.recordTurnStart = recordTurnStart;
6360
+ exports.readTurnPromptId = readTurnPromptId;
5558
6361
  exports.consumeTurnDurationMs = consumeTurnDurationMs;
6362
+ var crypto_1 = __require("crypto");
5559
6363
  var fs = __importStar(__require("fs"));
5560
6364
  var path = __importStar(__require("path"));
5561
6365
  var tokenStore_1 = require_tokenStore();
@@ -5568,11 +6372,24 @@ var require_turnState = __commonJS({
5568
6372
  }
5569
6373
  function recordTurnStart(agent, sessionId, now = Date.now()) {
5570
6374
  if (!sessionId)
5571
- return;
6375
+ return void 0;
5572
6376
  try {
6377
+ const promptId = (0, crypto_1.randomUUID)();
5573
6378
  fs.mkdirSync(stateDir(), { recursive: true });
5574
- fs.writeFileSync(turnFile(agent, sessionId), String(now), { encoding: "utf8", mode: 384 });
6379
+ fs.writeFileSync(turnFile(agent, sessionId), `${now} ${promptId}`, { encoding: "utf8", mode: 384 });
6380
+ return promptId;
6381
+ } catch {
6382
+ return void 0;
6383
+ }
6384
+ }
6385
+ function readTurnPromptId(agent, sessionId) {
6386
+ if (!sessionId)
6387
+ return void 0;
6388
+ try {
6389
+ const id = fs.readFileSync(turnFile(agent, sessionId), "utf8").trim().split(/\s+/)[1];
6390
+ return id && /^[A-Za-z0-9_-]{1,128}$/.test(id) ? id : void 0;
5575
6391
  } catch {
6392
+ return void 0;
5576
6393
  }
5577
6394
  }
5578
6395
  function consumeTurnDurationMs(agent, sessionId, now = Date.now()) {
@@ -5580,7 +6397,7 @@ var require_turnState = __commonJS({
5580
6397
  return void 0;
5581
6398
  const file = turnFile(agent, sessionId);
5582
6399
  try {
5583
- const started = Number(fs.readFileSync(file, "utf8").trim());
6400
+ const started = Number(fs.readFileSync(file, "utf8").trim().split(/\s+/)[0]);
5584
6401
  fs.rmSync(file, { force: true });
5585
6402
  if (!Number.isFinite(started) || started <= 0 || started > now)
5586
6403
  return void 0;
@@ -5736,10 +6553,11 @@ var require_out3 = __commonJS({
5736
6553
  "../packages/tool-kit/out/index.js"(exports) {
5737
6554
  "use strict";
5738
6555
  Object.defineProperty(exports, "__esModule", { value: true });
5739
- exports.findStaleHookCommands = exports.cliAgentHookBinPath = exports.resolveContextHashes = exports.resolveCliAgentInstallationId = exports.loadCliAgentConfig = exports.deliverHookEvents = exports.MissingInstallationIdError = exports.DEFAULT_API_BASE_URL = exports.resolveEventLogPath = exports.resolveEventLog = exports.parseEventLogFlag = exports.expandUserPath = exports.describeEventLog = exports.defaultEventLogPath = exports.appendEventLog = exports.EVENT_LOG_OFF = exports.EVENT_LOG_ENV_VAR = exports.toAgentEvent = exports.buildEventPayload = exports.buildEventBody = 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;
5740
- 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.writeEventLogSetting = exports.writeHostCredentials = exports.removeHostCredentials = exports.readMachineCredentials = exports.readHostCredentials = exports.isLocalOnlyHostInstall = exports.credentialsFilePath = exports.renderSetupDisclosure = exports.REFUSALS = exports.FREE_TEXT_KEYS = exports.FAMILY_SENTENCES = exports.ALWAYS_SENT = exports.writeHookSettings = exports.runCliAgentSetup = exports.registeredHookSets = exports.isCliAgentManagementCommand = void 0;
5741
- exports.hookSetArgument = exports.describeHookSetChanges = exports.UNVERSIONED_HOOK_SET = exports.HOOK_SET_FLAG = exports.liveSignalDoctorLines = exports.doctorRow = exports.DOCTOR_VALUE_COLUMN = exports.tidyHomePath = exports.stampLastHook = exports.resolveHookNode = exports.removeHookRunner = exports.readLastHook = exports.lastHookPath = exports.installHookRunner = exports.hookRunnerPaths = exports.hookRunnerCommand = exports.hookLauncherScript = exports.describeAge = exports.terminalStyle = exports.colourEnabled = exports.SAVER_REPLAY_WINDOW_MS = exports.saverSupportDir = exports.saverStatusDir = exports.saverReplayPath = exports.saverContainerDir = exports.readSaverStatuses = exports.probeSocket = exports.heldForSaver = exports.holdForSaver = exports.LIVE_BUS_BACKGROUND_TRUST_MS = exports.liveBusSocketCandidates = exports.liveBusSocketPath = exports.bucketPromptSize = exports.deliverLine = 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 = void 0;
5742
- 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 = void 0;
6556
+ exports.resolveEventLog = exports.parseEventLogFlag = exports.expandUserPath = exports.describeEventLog = exports.defaultEventLogPath = exports.appendEventLog = exports.EVENT_LOG_OFF = exports.EVENT_LOG_ENV_VAR = exports.toAgentEvent = exports.buildEventPayload = exports.buildEventBody = exports.TOKEN_RENEW_LEAD_MS = exports.AscendaSemanticEventError = exports.AscendaEventSender = exports.startBackgroundFlush = exports.runOutboxFlush = exports.hookDeliveryInline = exports.flushLockPath = exports.OUTBOX_FLUSH_COMMAND = exports.HOOK_DELIVERY_ENV_VAR = exports.FLUSH_LOCK_FRESH_MS = 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.shellCommandFacts = exports.invitesDebrief = exports.classifyMcpWorkMilestone = exports.classifyWorkMilestone = exports.isReworkGitAction = exports.classifyGitAction = exports.isVerificationCommand = exports.classifyCommand = void 0;
6557
+ 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.readTurnPromptId = exports.consumeTurnDurationMs = exports.writeTopLevelCredentials = exports.writeMachineCredentials = exports.writeRepoKeysSetting = exports.writeEventLogSetting = exports.writeHostCredentials = exports.removeHostCredentials = exports.readMachineCredentials = exports.readHostCredentials = exports.isLocalOnlyHostInstall = exports.credentialsFilePath = exports.renderSetupDisclosure = exports.REFUSALS = exports.FREE_TEXT_KEYS = exports.FAMILY_SENTENCES = exports.ALWAYS_SENT = exports.writeHookSettings = exports.trustProblemLines = exports.runCliAgentSetup = exports.registeredHookSets = exports.ourHookPositions = exports.isCliAgentManagementCommand = exports.findStaleHookCommands = exports.cliAgentHookBinPath = exports.resolveContextHashes = exports.resolveCliAgentInstallationId = exports.withPromptId = exports.withForgeKeys = exports.loadCliAgentConfig = exports.flushHookOutbox = exports.deliverHookEvents = exports.MissingInstallationIdError = exports.DEFAULT_API_BASE_URL = exports.resolveEventLogPath = void 0;
6558
+ exports.saverSupportDir = exports.saverStatusDir = exports.saverReplayPath = exports.saverContainerDir = exports.readSaverStatuses = exports.probeSocket = exports.heldForSaver = exports.holdForSaver = exports.LIVE_BUS_BACKGROUND_TRUST_MS = exports.liveBusSocketCandidates = exports.liveBusSocketPath = exports.bucketPromptSize = exports.deliverLine = exports.emitLiveSignal = exports.repoKeysEnabled = exports.deriveForgeKeysForCwd = exports.REPO_KEYS_ENV_VAR = exports.recordForgeProjectAlias = exports.forgeFullNameFromConfig = exports.readForgeFullName = exports.parseForgeFullName = exports.forgeBranchKey = exports.forgeRepoKey = 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 = void 0;
6559
+ 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.liveSignalDoctorLines = exports.doctorRow = exports.DOCTOR_VALUE_COLUMN = exports.replaceSettingsFile = exports.writeAtomically = exports.tidyHomePath = exports.stampLastHook = exports.resolveHookNode = exports.removeHookRunner = exports.readLastHook = exports.lastHookPath = exports.isDowngrade = exports.installHookRunner = exports.hookRunnerPaths = exports.hookRunnerCommand = exports.hookLauncherScript = exports.describeAge = exports.terminalStyle = exports.colourEnabled = exports.SAVER_REPLAY_WINDOW_MS = void 0;
6560
+ exports.runStudyJoin = exports.studyNoticeStatus = exports.runStudyObjection = exports.renderStudyNotices = exports.NOTICED_PURPOSES = exports.renderInitiatives = exports.initiativesStatusLines = exports.INITIATIVE_COPY = void 0;
5743
6561
  var commandClassifier_1 = require_commandClassifier();
5744
6562
  Object.defineProperty(exports, "classifyCommand", { enumerable: true, get: function() {
5745
6563
  return commandClassifier_1.classifyCommand;
@@ -5758,9 +6576,16 @@ var require_out3 = __commonJS({
5758
6576
  Object.defineProperty(exports, "classifyWorkMilestone", { enumerable: true, get: function() {
5759
6577
  return workMilestoneClassifier_1.classifyWorkMilestone;
5760
6578
  } });
6579
+ Object.defineProperty(exports, "classifyMcpWorkMilestone", { enumerable: true, get: function() {
6580
+ return workMilestoneClassifier_1.classifyMcpWorkMilestone;
6581
+ } });
5761
6582
  Object.defineProperty(exports, "invitesDebrief", { enumerable: true, get: function() {
5762
6583
  return workMilestoneClassifier_1.invitesDebrief;
5763
6584
  } });
6585
+ var shellFacts_1 = require_shellFacts();
6586
+ Object.defineProperty(exports, "shellCommandFacts", { enumerable: true, get: function() {
6587
+ return shellFacts_1.shellCommandFacts;
6588
+ } });
5764
6589
  var autonomyBand_1 = require_autonomyBand();
5765
6590
  Object.defineProperty(exports, "autonomyBand", { enumerable: true, get: function() {
5766
6591
  return autonomyBand_1.autonomyBand;
@@ -5830,6 +6655,28 @@ var require_out3 = __commonJS({
5830
6655
  Object.defineProperty(exports, "describeCollectorVersion", { enumerable: true, get: function() {
5831
6656
  return collectorVersion_1.describeCollectorVersion;
5832
6657
  } });
6658
+ var backgroundDelivery_1 = require_backgroundDelivery();
6659
+ Object.defineProperty(exports, "FLUSH_LOCK_FRESH_MS", { enumerable: true, get: function() {
6660
+ return backgroundDelivery_1.FLUSH_LOCK_FRESH_MS;
6661
+ } });
6662
+ Object.defineProperty(exports, "HOOK_DELIVERY_ENV_VAR", { enumerable: true, get: function() {
6663
+ return backgroundDelivery_1.HOOK_DELIVERY_ENV_VAR;
6664
+ } });
6665
+ Object.defineProperty(exports, "OUTBOX_FLUSH_COMMAND", { enumerable: true, get: function() {
6666
+ return backgroundDelivery_1.OUTBOX_FLUSH_COMMAND;
6667
+ } });
6668
+ Object.defineProperty(exports, "flushLockPath", { enumerable: true, get: function() {
6669
+ return backgroundDelivery_1.flushLockPath;
6670
+ } });
6671
+ Object.defineProperty(exports, "hookDeliveryInline", { enumerable: true, get: function() {
6672
+ return backgroundDelivery_1.hookDeliveryInline;
6673
+ } });
6674
+ Object.defineProperty(exports, "runOutboxFlush", { enumerable: true, get: function() {
6675
+ return backgroundDelivery_1.runOutboxFlush;
6676
+ } });
6677
+ Object.defineProperty(exports, "startBackgroundFlush", { enumerable: true, get: function() {
6678
+ return backgroundDelivery_1.startBackgroundFlush;
6679
+ } });
5833
6680
  var eventSender_1 = require_eventSender();
5834
6681
  Object.defineProperty(exports, "AscendaEventSender", { enumerable: true, get: function() {
5835
6682
  return eventSender_1.AscendaEventSender;
@@ -5888,9 +6735,18 @@ var require_out3 = __commonJS({
5888
6735
  Object.defineProperty(exports, "deliverHookEvents", { enumerable: true, get: function() {
5889
6736
  return hookAdapter_1.deliverHookEvents;
5890
6737
  } });
6738
+ Object.defineProperty(exports, "flushHookOutbox", { enumerable: true, get: function() {
6739
+ return hookAdapter_1.flushHookOutbox;
6740
+ } });
5891
6741
  Object.defineProperty(exports, "loadCliAgentConfig", { enumerable: true, get: function() {
5892
6742
  return hookAdapter_1.loadCliAgentConfig;
5893
6743
  } });
6744
+ Object.defineProperty(exports, "withForgeKeys", { enumerable: true, get: function() {
6745
+ return hookAdapter_1.withForgeKeys;
6746
+ } });
6747
+ Object.defineProperty(exports, "withPromptId", { enumerable: true, get: function() {
6748
+ return hookAdapter_1.withPromptId;
6749
+ } });
5894
6750
  Object.defineProperty(exports, "resolveCliAgentInstallationId", { enumerable: true, get: function() {
5895
6751
  return hookAdapter_1.resolveCliAgentInstallationId;
5896
6752
  } });
@@ -5907,12 +6763,18 @@ var require_out3 = __commonJS({
5907
6763
  Object.defineProperty(exports, "isCliAgentManagementCommand", { enumerable: true, get: function() {
5908
6764
  return cliAgentSetup_1.isCliAgentManagementCommand;
5909
6765
  } });
6766
+ Object.defineProperty(exports, "ourHookPositions", { enumerable: true, get: function() {
6767
+ return cliAgentSetup_1.ourHookPositions;
6768
+ } });
5910
6769
  Object.defineProperty(exports, "registeredHookSets", { enumerable: true, get: function() {
5911
6770
  return cliAgentSetup_1.registeredHookSets;
5912
6771
  } });
5913
6772
  Object.defineProperty(exports, "runCliAgentSetup", { enumerable: true, get: function() {
5914
6773
  return cliAgentSetup_1.runCliAgentSetup;
5915
6774
  } });
6775
+ Object.defineProperty(exports, "trustProblemLines", { enumerable: true, get: function() {
6776
+ return cliAgentSetup_1.trustProblemLines;
6777
+ } });
5916
6778
  Object.defineProperty(exports, "writeHookSettings", { enumerable: true, get: function() {
5917
6779
  return cliAgentSetup_1.writeHookSettings;
5918
6780
  } });
@@ -5954,6 +6816,9 @@ var require_out3 = __commonJS({
5954
6816
  Object.defineProperty(exports, "writeEventLogSetting", { enumerable: true, get: function() {
5955
6817
  return credentials_1.writeEventLogSetting;
5956
6818
  } });
6819
+ Object.defineProperty(exports, "writeRepoKeysSetting", { enumerable: true, get: function() {
6820
+ return credentials_1.writeRepoKeysSetting;
6821
+ } });
5957
6822
  Object.defineProperty(exports, "writeMachineCredentials", { enumerable: true, get: function() {
5958
6823
  return credentials_1.writeMachineCredentials;
5959
6824
  } });
@@ -5964,6 +6829,9 @@ var require_out3 = __commonJS({
5964
6829
  Object.defineProperty(exports, "consumeTurnDurationMs", { enumerable: true, get: function() {
5965
6830
  return turnState_1.consumeTurnDurationMs;
5966
6831
  } });
6832
+ Object.defineProperty(exports, "readTurnPromptId", { enumerable: true, get: function() {
6833
+ return turnState_1.readTurnPromptId;
6834
+ } });
5967
6835
  Object.defineProperty(exports, "recordTurnStart", { enumerable: true, get: function() {
5968
6836
  return turnState_1.recordTurnStart;
5969
6837
  } });
@@ -6098,6 +6966,12 @@ var require_out3 = __commonJS({
6098
6966
  Object.defineProperty(exports, "forgeProjectHash", { enumerable: true, get: function() {
6099
6967
  return forgeProject_1.forgeProjectHash;
6100
6968
  } });
6969
+ Object.defineProperty(exports, "forgeRepoKey", { enumerable: true, get: function() {
6970
+ return forgeProject_1.forgeRepoKey;
6971
+ } });
6972
+ Object.defineProperty(exports, "forgeBranchKey", { enumerable: true, get: function() {
6973
+ return forgeProject_1.forgeBranchKey;
6974
+ } });
6101
6975
  Object.defineProperty(exports, "parseForgeFullName", { enumerable: true, get: function() {
6102
6976
  return forgeProject_1.parseForgeFullName;
6103
6977
  } });
@@ -6110,6 +6984,16 @@ var require_out3 = __commonJS({
6110
6984
  Object.defineProperty(exports, "recordForgeProjectAlias", { enumerable: true, get: function() {
6111
6985
  return forgeProject_1.recordForgeProjectAlias;
6112
6986
  } });
6987
+ var forgeKeys_1 = require_forgeKeys();
6988
+ Object.defineProperty(exports, "REPO_KEYS_ENV_VAR", { enumerable: true, get: function() {
6989
+ return forgeKeys_1.REPO_KEYS_ENV_VAR;
6990
+ } });
6991
+ Object.defineProperty(exports, "deriveForgeKeysForCwd", { enumerable: true, get: function() {
6992
+ return forgeKeys_1.deriveForgeKeysForCwd;
6993
+ } });
6994
+ Object.defineProperty(exports, "repoKeysEnabled", { enumerable: true, get: function() {
6995
+ return forgeKeys_1.repoKeysEnabled;
6996
+ } });
6113
6997
  var liveBus_1 = require_liveBus();
6114
6998
  Object.defineProperty(exports, "emitLiveSignal", { enumerable: true, get: function() {
6115
6999
  return liveBus_1.emitLiveSignal;
@@ -6180,6 +7064,9 @@ var require_out3 = __commonJS({
6180
7064
  Object.defineProperty(exports, "installHookRunner", { enumerable: true, get: function() {
6181
7065
  return hookRunner_1.installHookRunner;
6182
7066
  } });
7067
+ Object.defineProperty(exports, "isDowngrade", { enumerable: true, get: function() {
7068
+ return hookRunner_1.isDowngrade;
7069
+ } });
6183
7070
  Object.defineProperty(exports, "lastHookPath", { enumerable: true, get: function() {
6184
7071
  return hookRunner_1.lastHookPath;
6185
7072
  } });
@@ -6198,6 +7085,13 @@ var require_out3 = __commonJS({
6198
7085
  Object.defineProperty(exports, "tidyHomePath", { enumerable: true, get: function() {
6199
7086
  return hookRunner_1.tidyHomePath;
6200
7087
  } });
7088
+ Object.defineProperty(exports, "writeAtomically", { enumerable: true, get: function() {
7089
+ return hookRunner_1.writeAtomically;
7090
+ } });
7091
+ var settingsFile_1 = require_settingsFile();
7092
+ Object.defineProperty(exports, "replaceSettingsFile", { enumerable: true, get: function() {
7093
+ return settingsFile_1.replaceSettingsFile;
7094
+ } });
6201
7095
  var liveSignalDoctor_1 = require_liveSignalDoctor();
6202
7096
  Object.defineProperty(exports, "DOCTOR_VALUE_COLUMN", { enumerable: true, get: function() {
6203
7097
  return liveSignalDoctor_1.DOCTOR_VALUE_COLUMN;
@@ -6363,8 +7257,9 @@ function normalizeToolInstallationId(value) {
6363
7257
 
6364
7258
  // src/mapForgeEvent.ts
6365
7259
  var import_tool_kit2 = __toESM(require_out3(), 1);
6366
- function mapForgeEvent(eventName, payload, viewerLogin) {
7260
+ function mapForgeEvent(eventName, payload, viewerLogin, options = {}) {
6367
7261
  if (!eventName || !viewerLogin) return [];
7262
+ const keys = options.repoKeys !== false;
6368
7263
  const action = str(payload["action"]);
6369
7264
  const viewer = viewerLogin.toLowerCase();
6370
7265
  if (eventName === "pull_request") {
@@ -6374,7 +7269,15 @@ function mapForgeEvent(eventName, payload, viewerLogin) {
6374
7269
  return [{
6375
7270
  eventType: "pull_request_opened",
6376
7271
  severity: "low",
6377
- metadata: base(payload)
7272
+ metadata: { ...base(payload, keys), ...pullRequestKeys(payload, pr, keys) }
7273
+ }];
7274
+ }
7275
+ if (action === "closed" && author === viewer) {
7276
+ const merged = pr["merged"] === true;
7277
+ return [{
7278
+ eventType: merged ? "pull_request_merged" : "pull_request_closed",
7279
+ severity: "low",
7280
+ metadata: { ...base(payload, keys), ...pullRequestKeys(payload, pr, keys), ...pullRequestTimes(pr, merged) }
6378
7281
  }];
6379
7282
  }
6380
7283
  if (action === "review_requested") {
@@ -6383,7 +7286,7 @@ function mapForgeEvent(eventName, payload, viewerLogin) {
6383
7286
  return [{
6384
7287
  eventType: "review_requested_of_me",
6385
7288
  severity: "low",
6386
- metadata: base(payload)
7289
+ metadata: { ...base(payload, keys), ...pullRequestKeys(payload, pr, keys) }
6387
7290
  }];
6388
7291
  }
6389
7292
  }
@@ -6397,7 +7300,8 @@ function mapForgeEvent(eventName, payload, viewerLogin) {
6397
7300
  eventType: "review_given",
6398
7301
  severity: "low",
6399
7302
  metadata: {
6400
- ...base(payload),
7303
+ ...base(payload, keys),
7304
+ ...pullRequestKeys(payload, obj(payload["pull_request"]), keys),
6401
7305
  // The verdict is a property of the checking work, not of the author,
6402
7306
  // and it is the closest thing to a "how heavy was this review" signal
6403
7307
  // that carries no content. `commented` and `changes_requested` are
@@ -6408,7 +7312,7 @@ function mapForgeEvent(eventName, payload, viewerLogin) {
6408
7312
  }
6409
7313
  return [];
6410
7314
  }
6411
- function base(payload) {
7315
+ function base(payload, keys) {
6412
7316
  const repo = str(obj(payload["repository"])["full_name"]);
6413
7317
  return {
6414
7318
  host: "github",
@@ -6422,9 +7326,49 @@ function base(payload) {
6422
7326
  // function now lives in tool-kit so a developer's own machine, which holds
6423
7327
  // both identities, can compute this exact digest and file it beside its
6424
7328
  // own; nothing about what this step emits has changed.
6425
- ...repo ? { projectHash: (0, import_tool_kit2.forgeProjectHash)(repo) } : {}
7329
+ ...repo ? { projectHash: (0, import_tool_kit2.forgeProjectHash)(repo) } : {},
7330
+ ...keys && repo && onGithub(obj(payload["repository"])) ? { repoKey: (0, import_tool_kit2.forgeRepoKey)(repo) } : {}
7331
+ };
7332
+ }
7333
+ function pullRequestKeys(payload, pr, keys) {
7334
+ if (!keys || !onGithub(obj(payload["repository"]))) return {};
7335
+ const head = obj(pr["head"]);
7336
+ const headRepo = obj(head["repo"]);
7337
+ const base2 = str(obj(obj(pr["base"])["repo"])["full_name"]) ?? str(obj(payload["repository"])["full_name"]);
7338
+ const headName = head["repo"] === void 0 ? base2 : str(headRepo["full_name"]);
7339
+ const branch = str(head["ref"]);
7340
+ const defaultBranch = head["repo"] === void 0 ? str(obj(payload["repository"])["default_branch"]) : str(headRepo["default_branch"]);
7341
+ const onDefault = branch !== void 0 && branch === defaultBranch;
7342
+ return {
7343
+ ...headName && base2 && headName.toLowerCase() !== base2.toLowerCase() ? { headRepoKey: (0, import_tool_kit2.forgeRepoKey)(headName) } : {},
7344
+ ...headName && branch && !onDefault ? { branchKey: (0, import_tool_kit2.forgeBranchKey)(headName, branch) } : {}
6426
7345
  };
6427
7346
  }
7347
+ function onGithub(repository) {
7348
+ const url = str(repository["html_url"]);
7349
+ if (!url) return true;
7350
+ try {
7351
+ return new URL(url).hostname.toLowerCase().replace(/^www\./, "") === "github.com";
7352
+ } catch {
7353
+ return false;
7354
+ }
7355
+ }
7356
+ function pullRequestTimes(pr, merged) {
7357
+ const created = timestamp(pr["created_at"]);
7358
+ const closed = timestamp(pr["closed_at"]);
7359
+ const mergedAt = merged ? timestamp(pr["merged_at"]) : void 0;
7360
+ return {
7361
+ ...created ? { prCreatedAt: created } : {},
7362
+ ...closed ? { prClosedAt: closed } : {},
7363
+ ...mergedAt ? { prMergedAt: mergedAt } : {}
7364
+ };
7365
+ }
7366
+ function timestamp(value) {
7367
+ const text = str(value);
7368
+ if (!text) return void 0;
7369
+ const ms = Date.parse(text);
7370
+ return Number.isNaN(ms) ? void 0 : new Date(ms).toISOString();
7371
+ }
6428
7372
  function reviewState(state) {
6429
7373
  return state?.toLowerCase() === "approved" ? "success" : "unknown";
6430
7374
  }
@@ -6438,10 +7382,12 @@ function str(value) {
6438
7382
  // src/cli.ts
6439
7383
  async function main() {
6440
7384
  const config = loadConfigFromEnv();
6441
- const eventName = process.env.GITHUB_EVENT_NAME ?? process.argv[2];
7385
+ const args = process.argv.slice(2);
7386
+ const repoKeys = !args.includes("--no-repo-keys") && (0, import_tool_kit3.repoKeysEnabled)();
7387
+ const eventName = process.env.GITHUB_EVENT_NAME ?? args.find((arg) => !arg.startsWith("--"));
6442
7388
  const payload = await readPayload();
6443
7389
  if (!payload) return;
6444
- const events = mapForgeEvent(eventName, payload, config.viewerLogin);
7390
+ const events = mapForgeEvent(eventName, payload, config.viewerLogin, { repoKeys });
6445
7391
  if (events.length === 0) return;
6446
7392
  const sender = new import_tool_kit3.AscendaEventSender({
6447
7393
  apiBaseUrl: config.apiBaseUrl,