@ascenda-one/history-import 0.1.37 → 0.1.39
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/README.md +111 -0
- package/dist/cli.js +2094 -527
- package/dist/cli.js.map +1 -1
- package/dist/credentials.js +144 -0
- package/dist/credentials.js.map +1 -0
- package/dist/extractors/claudeCode.js +25 -27
- package/dist/extractors/claudeCode.js.map +1 -1
- package/dist/extractors/git.js +262 -7
- package/dist/extractors/git.js.map +1 -1
- package/dist/participate.js +726 -0
- package/dist/participate.js.map +1 -0
- package/dist/schedule.js +239 -0
- package/dist/schedule.js.map +1 -0
- package/dist/ship.js +23 -19
- package/dist/ship.js.map +1 -1
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -378,9 +378,9 @@ var require_buckets = __commonJS({
|
|
|
378
378
|
"../packages/tool-kit/out/buckets.js"(exports) {
|
|
379
379
|
"use strict";
|
|
380
380
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
381
|
-
exports.bucketLinesChanged =
|
|
381
|
+
exports.bucketLinesChanged = bucketLinesChanged3;
|
|
382
382
|
exports.bucketDurationMs = bucketDurationMs5;
|
|
383
|
-
function
|
|
383
|
+
function bucketLinesChanged3(count) {
|
|
384
384
|
if (count <= 0)
|
|
385
385
|
return "0";
|
|
386
386
|
if (count <= 10)
|
|
@@ -506,6 +506,24 @@ var require_metricKeys = __commonJS({
|
|
|
506
506
|
cacheReadTokens: { family: "context", readBy: ["backend"], backendAliases: ["cacheReadTokens", "cache_read_tokens"], unit: "tokens" },
|
|
507
507
|
queuedPrompts: { family: "counts", readBy: ["backend"], backendAliases: ["queuedPrompts", "queued_prompts"] },
|
|
508
508
|
linesChangedBucket: { family: "edits", readBy: ["backend"], backendAliases: ["linesChangedBucket", "lines_changed_bucket"] },
|
|
509
|
+
gitAction: {
|
|
510
|
+
family: "git",
|
|
511
|
+
readBy: ["backend"],
|
|
512
|
+
backendAliases: ["gitAction", "git_action"],
|
|
513
|
+
note: "The live hooks set it on a shell event; the git extractor sets it to commit on each commit event it emits."
|
|
514
|
+
},
|
|
515
|
+
repoKey: {
|
|
516
|
+
family: "repo",
|
|
517
|
+
readBy: ["backend"],
|
|
518
|
+
backendAliases: ["repoKey", "repo_key"],
|
|
519
|
+
note: "Same derivation as the live hooks (forgeRepoKey of the github.com remote), so a commit joins a session and a pull request. Absent for other forges, a checkout with no remote, and when repo keys are turned off."
|
|
520
|
+
},
|
|
521
|
+
branchKey: {
|
|
522
|
+
family: "repo",
|
|
523
|
+
readBy: ["backend"],
|
|
524
|
+
backendAliases: ["branchKey", "branch_key"],
|
|
525
|
+
note: "forgeBranchKey of the repository and the branch a commit is reachable from. Absent on the default branch, like the live hooks."
|
|
526
|
+
},
|
|
509
527
|
// ── Read by the local handoff only ──────────────────────────────────────
|
|
510
528
|
activeMinutes: { family: "session", readBy: ["handoff"], unit: "minutes" },
|
|
511
529
|
syntheticPromptLines: {
|
|
@@ -728,6 +746,23 @@ var require_metricKeys = __commonJS({
|
|
|
728
746
|
backendAliases: ["toolName", "tool_name"],
|
|
729
747
|
note: "Set per ai_tool_call_started event by #43's extractors. Declared diagnostic until 23 Sep 2026 on the belief that nothing resolved it server-side; two backend readers do \u2014 one to see a sub-agent dispatch, one composing per-tool metrics. This is the inverse of the mismatch this module was written for: contextUsagePercent was a key nobody read, and a key a reader resolves without being declared drops nothing, so it has no symptom at all. What it costs is that readBy stops being a true census of what the server sees, which is what you consult when deciding what a collector should stop sending. Registered after the fact in the first place: #38 and #43 merged past each other, and the union caught it on the next compile \u2014 metaLines all over again."
|
|
730
748
|
},
|
|
749
|
+
activity: {
|
|
750
|
+
family: "git",
|
|
751
|
+
readBy: ["diagnostic"],
|
|
752
|
+
note: "Names what an editor_activity row is. The git extractor sends git_commit; the backend cadence reader keys on gitAction, and this is how a person reading the row tells it from an editor event."
|
|
753
|
+
},
|
|
754
|
+
isMergeCommit: { family: "git", readBy: ["diagnostic"], note: "True when the commit has more than one parent. A merge commit carries no size figures: they would only restate the commits it merged." },
|
|
755
|
+
authoredByMe: { family: "git", readBy: ["diagnostic"], note: "Whether the commit's author email matches the git config email on this machine. The extractor emits only commits where it does, so today this is always true; the key exists so a wider read can be told apart." },
|
|
756
|
+
linesAddedBucket: { family: "git", readBy: ["diagnostic"], note: "Lines added by a commit, in the same buckets as linesChangedBucket." },
|
|
757
|
+
linesRemovedBucket: { family: "git", readBy: ["diagnostic"], note: "Lines removed by a commit, in the same buckets as linesChangedBucket." },
|
|
758
|
+
gitReposRead: { family: "reading", readBy: ["diagnostic"], note: "Git extractor epoch: repositories whose history was read." },
|
|
759
|
+
gitReposSkipped: { family: "reading", readBy: ["diagnostic"], note: "Git extractor epoch: repositories a transcript named that could not be read (deleted, not a repository, git failed)." },
|
|
760
|
+
gitReposWithoutIdentity: { family: "reading", readBy: ["diagnostic"], note: "Git extractor epoch: repositories with no user.email in git config, so no commit could be called mine and none was emitted." },
|
|
761
|
+
compactionOrdinal: {
|
|
762
|
+
family: "context",
|
|
763
|
+
readBy: ["diagnostic"],
|
|
764
|
+
note: "Claude Code only: 1-based position of this compaction within its session, counting manual and auto together. Present on per-compaction context_compression_* rows. Older imports wrote one row per session and trigger at the session's last timestamp, with no ordinal and compactionCount set to the session total. Where a session has ordinal rows, a reader should ignore its rows without one."
|
|
765
|
+
},
|
|
731
766
|
toolResultCount: { family: "tools", readBy: ["diagnostic"] },
|
|
732
767
|
toolResultErrorCount: { family: "outcome", readBy: ["diagnostic"] },
|
|
733
768
|
unknownBubbles: { family: "reading", readBy: ["diagnostic"] },
|
|
@@ -887,7 +922,10 @@ var require_out = __commonJS({
|
|
|
887
922
|
importSchema: "transport",
|
|
888
923
|
// The version of the Ascenda collector that sent this event. Names the
|
|
889
924
|
// build, and nothing about the work it observed.
|
|
890
|
-
collectorVersion: "transport"
|
|
925
|
+
collectorVersion: "transport",
|
|
926
|
+
// The operating system the collector runs on, from a closed list. Names
|
|
927
|
+
// the machine's system, and nothing about the work it observed.
|
|
928
|
+
collectorPlatform: "transport"
|
|
891
929
|
};
|
|
892
930
|
exports.EVENT_METADATA_FIELDS = [
|
|
893
931
|
"language",
|
|
@@ -931,7 +969,8 @@ var require_out = __commonJS({
|
|
|
931
969
|
"importKey",
|
|
932
970
|
"extractionId",
|
|
933
971
|
"importSchema",
|
|
934
|
-
"collectorVersion"
|
|
972
|
+
"collectorVersion",
|
|
973
|
+
"collectorPlatform"
|
|
935
974
|
];
|
|
936
975
|
exports.DELIVERY_ENVELOPE_KEYS = ["toolInstallationId", "idempotencyKey"];
|
|
937
976
|
function joinEventPayload(envelope, body) {
|
|
@@ -1081,9 +1120,9 @@ var require_payload = __commonJS({
|
|
|
1081
1120
|
}
|
|
1082
1121
|
return void 0;
|
|
1083
1122
|
}
|
|
1084
|
-
function getNested(input,
|
|
1123
|
+
function getNested(input, path15) {
|
|
1085
1124
|
let current = input;
|
|
1086
|
-
for (const segment of
|
|
1125
|
+
for (const segment of path15) {
|
|
1087
1126
|
if (!current || typeof current !== "object")
|
|
1088
1127
|
return void 0;
|
|
1089
1128
|
current = current[segment];
|
|
@@ -1091,16 +1130,16 @@ var require_payload = __commonJS({
|
|
|
1091
1130
|
return current;
|
|
1092
1131
|
}
|
|
1093
1132
|
function getNestedString(input, paths) {
|
|
1094
|
-
for (const
|
|
1095
|
-
const value = getNested(input,
|
|
1133
|
+
for (const path15 of paths) {
|
|
1134
|
+
const value = getNested(input, path15);
|
|
1096
1135
|
if (typeof value === "string" && value.trim())
|
|
1097
1136
|
return value;
|
|
1098
1137
|
}
|
|
1099
1138
|
return void 0;
|
|
1100
1139
|
}
|
|
1101
1140
|
function getNestedNumber(input, paths) {
|
|
1102
|
-
for (const
|
|
1103
|
-
const value = getNested(input,
|
|
1141
|
+
for (const path15 of paths) {
|
|
1142
|
+
const value = getNested(input, path15);
|
|
1104
1143
|
if (typeof value === "number" && Number.isFinite(value))
|
|
1105
1144
|
return value;
|
|
1106
1145
|
}
|
|
@@ -1135,6 +1174,79 @@ var require_payload = __commonJS({
|
|
|
1135
1174
|
}
|
|
1136
1175
|
});
|
|
1137
1176
|
|
|
1177
|
+
// ../packages/tool-kit/out/collectorPlatform.js
|
|
1178
|
+
var require_collectorPlatform = __commonJS({
|
|
1179
|
+
"../packages/tool-kit/out/collectorPlatform.js"(exports) {
|
|
1180
|
+
"use strict";
|
|
1181
|
+
var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
1182
|
+
if (k2 === void 0) k2 = k;
|
|
1183
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
1184
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
1185
|
+
desc = { enumerable: true, get: function() {
|
|
1186
|
+
return m[k];
|
|
1187
|
+
} };
|
|
1188
|
+
}
|
|
1189
|
+
Object.defineProperty(o, k2, desc);
|
|
1190
|
+
} : function(o, m, k, k2) {
|
|
1191
|
+
if (k2 === void 0) k2 = k;
|
|
1192
|
+
o[k2] = m[k];
|
|
1193
|
+
});
|
|
1194
|
+
var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
|
|
1195
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
1196
|
+
} : function(o, v) {
|
|
1197
|
+
o["default"] = v;
|
|
1198
|
+
});
|
|
1199
|
+
var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
|
|
1200
|
+
var ownKeys = function(o) {
|
|
1201
|
+
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
1202
|
+
var ar = [];
|
|
1203
|
+
for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
|
|
1204
|
+
return ar;
|
|
1205
|
+
};
|
|
1206
|
+
return ownKeys(o);
|
|
1207
|
+
};
|
|
1208
|
+
return function(mod) {
|
|
1209
|
+
if (mod && mod.__esModule) return mod;
|
|
1210
|
+
var result = {};
|
|
1211
|
+
if (mod != null) {
|
|
1212
|
+
for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
1213
|
+
}
|
|
1214
|
+
__setModuleDefault(result, mod);
|
|
1215
|
+
return result;
|
|
1216
|
+
};
|
|
1217
|
+
}();
|
|
1218
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
1219
|
+
exports.COLLECTOR_PLATFORM = void 0;
|
|
1220
|
+
exports.detectCollectorPlatform = detectCollectorPlatform;
|
|
1221
|
+
var os6 = __importStar(__require("os"));
|
|
1222
|
+
function detectCollectorPlatform(probe = {}) {
|
|
1223
|
+
const platform = probe.platform ?? process.platform;
|
|
1224
|
+
switch (platform) {
|
|
1225
|
+
case "darwin":
|
|
1226
|
+
case "win32":
|
|
1227
|
+
return platform;
|
|
1228
|
+
case "linux": {
|
|
1229
|
+
const env = probe.env ?? process.env;
|
|
1230
|
+
if (env.WSL_DISTRO_NAME || env.WSL_INTEROP)
|
|
1231
|
+
return "wsl";
|
|
1232
|
+
const release = probe.release ?? safeRelease();
|
|
1233
|
+
return /microsoft/i.test(release) ? "wsl" : "linux";
|
|
1234
|
+
}
|
|
1235
|
+
default:
|
|
1236
|
+
return "other";
|
|
1237
|
+
}
|
|
1238
|
+
}
|
|
1239
|
+
function safeRelease() {
|
|
1240
|
+
try {
|
|
1241
|
+
return os6.release();
|
|
1242
|
+
} catch {
|
|
1243
|
+
return "";
|
|
1244
|
+
}
|
|
1245
|
+
}
|
|
1246
|
+
exports.COLLECTOR_PLATFORM = detectCollectorPlatform();
|
|
1247
|
+
}
|
|
1248
|
+
});
|
|
1249
|
+
|
|
1138
1250
|
// ../packages/tool-kit/out/collectorVersion.js
|
|
1139
1251
|
var require_collectorVersion = __commonJS({
|
|
1140
1252
|
"../packages/tool-kit/out/collectorVersion.js"(exports) {
|
|
@@ -1143,7 +1255,7 @@ var require_collectorVersion = __commonJS({
|
|
|
1143
1255
|
exports.COLLECTOR_VERSION = exports.UNRELEASED_COLLECTOR_VERSION = void 0;
|
|
1144
1256
|
exports.describeCollectorVersion = describeCollectorVersion;
|
|
1145
1257
|
exports.UNRELEASED_COLLECTOR_VERSION = "unreleased";
|
|
1146
|
-
exports.COLLECTOR_VERSION = "0.1.
|
|
1258
|
+
exports.COLLECTOR_VERSION = "0.1.39" ? "0.1.39" : exports.UNRELEASED_COLLECTOR_VERSION;
|
|
1147
1259
|
function describeCollectorVersion(version = exports.COLLECTOR_VERSION) {
|
|
1148
1260
|
return version === exports.UNRELEASED_COLLECTOR_VERSION ? `${version} (built from a checkout, not a release)` : version;
|
|
1149
1261
|
}
|
|
@@ -1193,65 +1305,65 @@ var require_tokenStore = __commonJS({
|
|
|
1193
1305
|
}();
|
|
1194
1306
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
1195
1307
|
exports.EVENT_TOKEN_TTL_MS = void 0;
|
|
1196
|
-
exports.ascendaHome =
|
|
1197
|
-
exports.defaultTokenFilePath =
|
|
1308
|
+
exports.ascendaHome = ascendaHome6;
|
|
1309
|
+
exports.defaultTokenFilePath = defaultTokenFilePath3;
|
|
1198
1310
|
exports.tokenExpiryFilePath = tokenExpiryFilePath;
|
|
1199
|
-
exports.persistEventWriteToken =
|
|
1200
|
-
exports.readTokenExpiry =
|
|
1201
|
-
exports.listPersistedToolInstallationIds =
|
|
1202
|
-
exports.readTokenFile =
|
|
1311
|
+
exports.persistEventWriteToken = persistEventWriteToken2;
|
|
1312
|
+
exports.readTokenExpiry = readTokenExpiry2;
|
|
1313
|
+
exports.listPersistedToolInstallationIds = listPersistedToolInstallationIds2;
|
|
1314
|
+
exports.readTokenFile = readTokenFile3;
|
|
1203
1315
|
exports.sanitizeFilePart = sanitizeFilePart;
|
|
1204
|
-
var
|
|
1205
|
-
var
|
|
1206
|
-
var
|
|
1207
|
-
function
|
|
1208
|
-
return process.env.ASCENDA_HOME ??
|
|
1316
|
+
var fs15 = __importStar(__require("fs"));
|
|
1317
|
+
var os6 = __importStar(__require("os"));
|
|
1318
|
+
var path15 = __importStar(__require("path"));
|
|
1319
|
+
function ascendaHome6(home = os6.homedir()) {
|
|
1320
|
+
return process.env.ASCENDA_HOME ?? path15.join(home, ".ascenda");
|
|
1209
1321
|
}
|
|
1210
|
-
function
|
|
1211
|
-
return
|
|
1322
|
+
function defaultTokenFilePath3(toolInstallationId) {
|
|
1323
|
+
return path15.join(ascendaHome6(), "tokens", sanitizeFilePart(toolInstallationId));
|
|
1212
1324
|
}
|
|
1213
1325
|
function tokenExpiryFilePath(tokenFilePath) {
|
|
1214
|
-
return
|
|
1326
|
+
return path15.join(path15.dirname(tokenFilePath), "expiry", path15.basename(tokenFilePath));
|
|
1215
1327
|
}
|
|
1216
|
-
function
|
|
1217
|
-
const dir =
|
|
1218
|
-
|
|
1219
|
-
|
|
1328
|
+
function persistEventWriteToken2(tokenFilePath, token, expiresAt) {
|
|
1329
|
+
const dir = path15.dirname(tokenFilePath);
|
|
1330
|
+
fs15.mkdirSync(dir, { recursive: true, mode: 448 });
|
|
1331
|
+
fs15.writeFileSync(tokenFilePath, token, { encoding: "utf8", mode: 384 });
|
|
1220
1332
|
if (process.platform !== "win32") {
|
|
1221
|
-
|
|
1222
|
-
|
|
1333
|
+
fs15.chmodSync(dir, 448);
|
|
1334
|
+
fs15.chmodSync(tokenFilePath, 384);
|
|
1223
1335
|
}
|
|
1224
1336
|
const expiryFile = tokenExpiryFilePath(tokenFilePath);
|
|
1225
1337
|
try {
|
|
1226
1338
|
if (expiresAt && Number.isFinite(Date.parse(expiresAt))) {
|
|
1227
|
-
|
|
1228
|
-
|
|
1339
|
+
fs15.mkdirSync(path15.dirname(expiryFile), { recursive: true, mode: 448 });
|
|
1340
|
+
fs15.writeFileSync(expiryFile, expiresAt, { encoding: "utf8", mode: 384 });
|
|
1229
1341
|
} else {
|
|
1230
|
-
|
|
1342
|
+
fs15.rmSync(expiryFile, { force: true });
|
|
1231
1343
|
}
|
|
1232
1344
|
} catch {
|
|
1233
1345
|
}
|
|
1234
1346
|
}
|
|
1235
1347
|
exports.EVENT_TOKEN_TTL_MS = 30 * 24 * 60 * 60 * 1e3;
|
|
1236
|
-
function
|
|
1348
|
+
function readTokenExpiry2(tokenFilePath) {
|
|
1237
1349
|
try {
|
|
1238
|
-
const recorded = Date.parse(
|
|
1350
|
+
const recorded = Date.parse(fs15.readFileSync(tokenExpiryFilePath(tokenFilePath), "utf8").trim());
|
|
1239
1351
|
if (Number.isFinite(recorded))
|
|
1240
1352
|
return recorded;
|
|
1241
1353
|
} catch {
|
|
1242
1354
|
}
|
|
1243
1355
|
try {
|
|
1244
|
-
return
|
|
1356
|
+
return fs15.statSync(tokenFilePath).mtimeMs + exports.EVENT_TOKEN_TTL_MS;
|
|
1245
1357
|
} catch {
|
|
1246
1358
|
return void 0;
|
|
1247
1359
|
}
|
|
1248
1360
|
}
|
|
1249
|
-
function
|
|
1361
|
+
function listPersistedToolInstallationIds2(toolType) {
|
|
1250
1362
|
const prefix = `${sanitizeFilePart(toolType)}_`;
|
|
1251
|
-
const dir =
|
|
1363
|
+
const dir = path15.join(ascendaHome6(), "tokens");
|
|
1252
1364
|
let names;
|
|
1253
1365
|
try {
|
|
1254
|
-
names =
|
|
1366
|
+
names = fs15.readdirSync(dir);
|
|
1255
1367
|
} catch {
|
|
1256
1368
|
return [];
|
|
1257
1369
|
}
|
|
@@ -1259,24 +1371,24 @@ var require_tokenStore = __commonJS({
|
|
|
1259
1371
|
for (const name of names.sort()) {
|
|
1260
1372
|
if (!name.startsWith(prefix) || name.length === prefix.length)
|
|
1261
1373
|
continue;
|
|
1262
|
-
const file =
|
|
1374
|
+
const file = path15.join(dir, name);
|
|
1263
1375
|
try {
|
|
1264
|
-
if (!
|
|
1376
|
+
if (!fs15.statSync(file).isFile())
|
|
1265
1377
|
continue;
|
|
1266
1378
|
} catch {
|
|
1267
1379
|
continue;
|
|
1268
1380
|
}
|
|
1269
|
-
if (
|
|
1381
|
+
if (readTokenFile3(file) === void 0)
|
|
1270
1382
|
continue;
|
|
1271
1383
|
ids.push(`${toolType}:${name.slice(prefix.length)}`);
|
|
1272
1384
|
}
|
|
1273
1385
|
return ids;
|
|
1274
1386
|
}
|
|
1275
|
-
function
|
|
1387
|
+
function readTokenFile3(tokenFilePath) {
|
|
1276
1388
|
try {
|
|
1277
|
-
if (!
|
|
1389
|
+
if (!fs15.existsSync(tokenFilePath))
|
|
1278
1390
|
return void 0;
|
|
1279
|
-
const value =
|
|
1391
|
+
const value = fs15.readFileSync(tokenFilePath, "utf8").trim();
|
|
1280
1392
|
return value || void 0;
|
|
1281
1393
|
} catch {
|
|
1282
1394
|
return void 0;
|
|
@@ -1338,13 +1450,13 @@ var require_stateStore = __commonJS({
|
|
|
1338
1450
|
exports.recordOutboxDiscard = recordOutboxDiscard;
|
|
1339
1451
|
exports.shouldAnnounceFailure = shouldAnnounceFailure;
|
|
1340
1452
|
exports.markFailureNotified = markFailureNotified;
|
|
1341
|
-
var
|
|
1342
|
-
var
|
|
1453
|
+
var fs15 = __importStar(__require("fs"));
|
|
1454
|
+
var path15 = __importStar(__require("path"));
|
|
1343
1455
|
var tokenStore_1 = require_tokenStore();
|
|
1344
1456
|
function defaultStateFilePath(toolInstallationId) {
|
|
1345
1457
|
const dir = process.env.ASCENDA_STATE_DIR?.trim();
|
|
1346
|
-
const base = dir ? dir :
|
|
1347
|
-
return
|
|
1458
|
+
const base = dir ? dir : path15.join((0, tokenStore_1.ascendaHome)(), "state");
|
|
1459
|
+
return path15.join(base, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.json`);
|
|
1348
1460
|
}
|
|
1349
1461
|
function unresolvedToolInstallationId(toolType) {
|
|
1350
1462
|
return `${toolType}:unresolved`;
|
|
@@ -1354,9 +1466,9 @@ var require_stateStore = __commonJS({
|
|
|
1354
1466
|
}
|
|
1355
1467
|
function readCollectorState(stateFilePath) {
|
|
1356
1468
|
try {
|
|
1357
|
-
if (!
|
|
1469
|
+
if (!fs15.existsSync(stateFilePath))
|
|
1358
1470
|
return void 0;
|
|
1359
|
-
const raw =
|
|
1471
|
+
const raw = fs15.readFileSync(stateFilePath, "utf8").trim();
|
|
1360
1472
|
if (!raw)
|
|
1361
1473
|
return void 0;
|
|
1362
1474
|
const parsed = JSON.parse(raw);
|
|
@@ -1423,17 +1535,17 @@ var require_stateStore = __commonJS({
|
|
|
1423
1535
|
function writeStateFile(stateFilePath, state) {
|
|
1424
1536
|
const temporaryPath = `${stateFilePath}.${process.pid}.tmp`;
|
|
1425
1537
|
try {
|
|
1426
|
-
const dir =
|
|
1427
|
-
|
|
1428
|
-
|
|
1538
|
+
const dir = path15.dirname(stateFilePath);
|
|
1539
|
+
fs15.mkdirSync(dir, { recursive: true, mode: 448 });
|
|
1540
|
+
fs15.writeFileSync(temporaryPath, `${JSON.stringify(state, null, 2)}
|
|
1429
1541
|
`, { encoding: "utf8", mode: 384 });
|
|
1430
|
-
|
|
1542
|
+
fs15.renameSync(temporaryPath, stateFilePath);
|
|
1431
1543
|
if (process.platform !== "win32")
|
|
1432
|
-
|
|
1544
|
+
fs15.chmodSync(stateFilePath, 384);
|
|
1433
1545
|
} catch {
|
|
1434
1546
|
try {
|
|
1435
|
-
if (
|
|
1436
|
-
|
|
1547
|
+
if (fs15.existsSync(temporaryPath))
|
|
1548
|
+
fs15.unlinkSync(temporaryPath);
|
|
1437
1549
|
} catch {
|
|
1438
1550
|
}
|
|
1439
1551
|
}
|
|
@@ -1494,8 +1606,8 @@ var require_outbox = __commonJS({
|
|
|
1494
1606
|
exports.readOutboxSummary = readOutboxSummary;
|
|
1495
1607
|
exports.claimOutbox = claimOutbox;
|
|
1496
1608
|
exports.enforceOutboxBounds = enforceOutboxBounds;
|
|
1497
|
-
var
|
|
1498
|
-
var
|
|
1609
|
+
var fs15 = __importStar(__require("fs"));
|
|
1610
|
+
var path15 = __importStar(__require("path"));
|
|
1499
1611
|
var stateStore_1 = require_stateStore();
|
|
1500
1612
|
var tokenStore_1 = require_tokenStore();
|
|
1501
1613
|
exports.OUTBOX_DRAIN_ENV_VAR = "ASCENDA_OUTBOX_DRAIN";
|
|
@@ -1511,25 +1623,25 @@ var require_outbox = __commonJS({
|
|
|
1511
1623
|
return !(value === "0" || value === "false" || value === "no" || value === "off");
|
|
1512
1624
|
}
|
|
1513
1625
|
function defaultOutboxFilePath(toolInstallationId) {
|
|
1514
|
-
const dir =
|
|
1515
|
-
return
|
|
1626
|
+
const dir = path15.dirname((0, stateStore_1.defaultStateFilePath)(toolInstallationId));
|
|
1627
|
+
return path15.join(dir, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.outbox.jsonl`);
|
|
1516
1628
|
}
|
|
1517
1629
|
function appendToOutbox(outboxFilePath, payload, now = /* @__PURE__ */ new Date()) {
|
|
1518
1630
|
try {
|
|
1519
|
-
const dir =
|
|
1520
|
-
|
|
1631
|
+
const dir = path15.dirname(outboxFilePath);
|
|
1632
|
+
fs15.mkdirSync(dir, { recursive: true, mode: 448 });
|
|
1521
1633
|
const entry = { queuedAt: now.toISOString(), payload };
|
|
1522
|
-
|
|
1634
|
+
fs15.appendFileSync(outboxFilePath, `${JSON.stringify(entry)}
|
|
1523
1635
|
`, { encoding: "utf8", mode: 384 });
|
|
1524
1636
|
if (process.platform !== "win32")
|
|
1525
|
-
|
|
1637
|
+
fs15.chmodSync(outboxFilePath, 384);
|
|
1526
1638
|
return true;
|
|
1527
1639
|
} catch {
|
|
1528
1640
|
return false;
|
|
1529
1641
|
}
|
|
1530
1642
|
}
|
|
1531
1643
|
function readOutboxSummary(outboxFilePath) {
|
|
1532
|
-
const files = [outboxFilePath, ...listClaimFiles(outboxFilePath)].filter((file) =>
|
|
1644
|
+
const files = [outboxFilePath, ...listClaimFiles(outboxFilePath)].filter((file) => fs15.existsSync(file));
|
|
1533
1645
|
if (files.length === 0)
|
|
1534
1646
|
return void 0;
|
|
1535
1647
|
let depth = 0;
|
|
@@ -1550,7 +1662,7 @@ var require_outbox = __commonJS({
|
|
|
1550
1662
|
const claimPath = `${outboxFilePath}.${process.pid}${CLAIM_SUFFIX}`;
|
|
1551
1663
|
const claimed = [];
|
|
1552
1664
|
try {
|
|
1553
|
-
|
|
1665
|
+
fs15.renameSync(outboxFilePath, claimPath);
|
|
1554
1666
|
claimed.push(claimPath);
|
|
1555
1667
|
} catch {
|
|
1556
1668
|
}
|
|
@@ -1559,10 +1671,10 @@ var require_outbox = __commonJS({
|
|
|
1559
1671
|
if (claimed.includes(orphan))
|
|
1560
1672
|
continue;
|
|
1561
1673
|
try {
|
|
1562
|
-
if (now -
|
|
1674
|
+
if (now - fs15.statSync(orphan).mtimeMs < ORPHANED_CLAIM_AGE_MS)
|
|
1563
1675
|
continue;
|
|
1564
1676
|
const mine = `${claimPath}.${orphanIndex++}`;
|
|
1565
|
-
|
|
1677
|
+
fs15.renameSync(orphan, mine);
|
|
1566
1678
|
claimed.push(mine);
|
|
1567
1679
|
} catch {
|
|
1568
1680
|
}
|
|
@@ -1587,18 +1699,18 @@ var require_outbox = __commonJS({
|
|
|
1587
1699
|
released = true;
|
|
1588
1700
|
if (remainder.length > 0) {
|
|
1589
1701
|
try {
|
|
1590
|
-
|
|
1591
|
-
|
|
1702
|
+
fs15.mkdirSync(path15.dirname(outboxFilePath), { recursive: true, mode: 448 });
|
|
1703
|
+
fs15.appendFileSync(outboxFilePath, remainder.map((entry) => `${JSON.stringify(entry)}
|
|
1592
1704
|
`).join(""), { encoding: "utf8", mode: 384 });
|
|
1593
1705
|
if (process.platform !== "win32")
|
|
1594
|
-
|
|
1706
|
+
fs15.chmodSync(outboxFilePath, 384);
|
|
1595
1707
|
} catch {
|
|
1596
1708
|
return;
|
|
1597
1709
|
}
|
|
1598
1710
|
}
|
|
1599
1711
|
for (const file of claimed) {
|
|
1600
1712
|
try {
|
|
1601
|
-
|
|
1713
|
+
fs15.unlinkSync(file);
|
|
1602
1714
|
} catch {
|
|
1603
1715
|
}
|
|
1604
1716
|
}
|
|
@@ -1631,10 +1743,10 @@ var require_outbox = __commonJS({
|
|
|
1631
1743
|
return { kept, discarded: { count, reasons, ...oldestQueuedAt !== void 0 ? { oldestQueuedAt } : {} } };
|
|
1632
1744
|
}
|
|
1633
1745
|
function listClaimFiles(outboxFilePath) {
|
|
1634
|
-
const dir =
|
|
1635
|
-
const prefix = `${
|
|
1746
|
+
const dir = path15.dirname(outboxFilePath);
|
|
1747
|
+
const prefix = `${path15.basename(outboxFilePath)}.`;
|
|
1636
1748
|
try {
|
|
1637
|
-
return
|
|
1749
|
+
return fs15.readdirSync(dir).filter((name) => name.startsWith(prefix) && name.includes(CLAIM_SUFFIX)).map((name) => path15.join(dir, name)).sort();
|
|
1638
1750
|
} catch {
|
|
1639
1751
|
return [];
|
|
1640
1752
|
}
|
|
@@ -1642,7 +1754,7 @@ var require_outbox = __commonJS({
|
|
|
1642
1754
|
function readEntries(file) {
|
|
1643
1755
|
let raw;
|
|
1644
1756
|
try {
|
|
1645
|
-
raw =
|
|
1757
|
+
raw = fs15.readFileSync(file, "utf8");
|
|
1646
1758
|
} catch {
|
|
1647
1759
|
return { entries: [], unreadable: 0 };
|
|
1648
1760
|
}
|
|
@@ -1714,7 +1826,7 @@ var require_backgroundDelivery = __commonJS({
|
|
|
1714
1826
|
exports.flushLockPath = flushLockPath;
|
|
1715
1827
|
exports.startBackgroundFlush = startBackgroundFlush;
|
|
1716
1828
|
exports.runOutboxFlush = runOutboxFlush;
|
|
1717
|
-
var
|
|
1829
|
+
var fs15 = __importStar(__require("fs"));
|
|
1718
1830
|
var child_process_1 = __require("child_process");
|
|
1719
1831
|
var outbox_1 = require_outbox();
|
|
1720
1832
|
exports.HOOK_DELIVERY_ENV_VAR = "ASCENDA_HOOK_DELIVERY";
|
|
@@ -1730,27 +1842,27 @@ var require_backgroundDelivery = __commonJS({
|
|
|
1730
1842
|
}
|
|
1731
1843
|
function lockIsFresh(lockPath, now) {
|
|
1732
1844
|
try {
|
|
1733
|
-
return now -
|
|
1845
|
+
return now - fs15.statSync(lockPath).mtimeMs < exports.FLUSH_LOCK_FRESH_MS;
|
|
1734
1846
|
} catch {
|
|
1735
1847
|
return false;
|
|
1736
1848
|
}
|
|
1737
1849
|
}
|
|
1738
1850
|
function touchLock(lockPath) {
|
|
1739
1851
|
try {
|
|
1740
|
-
|
|
1852
|
+
fs15.writeFileSync(lockPath, `${process.pid}
|
|
1741
1853
|
`, { encoding: "utf8", mode: 384 });
|
|
1742
1854
|
} catch {
|
|
1743
1855
|
}
|
|
1744
1856
|
}
|
|
1745
1857
|
function removeLock(lockPath) {
|
|
1746
1858
|
try {
|
|
1747
|
-
|
|
1859
|
+
fs15.unlinkSync(lockPath);
|
|
1748
1860
|
} catch {
|
|
1749
1861
|
}
|
|
1750
1862
|
}
|
|
1751
1863
|
function outboxHasEntries(outboxFilePath) {
|
|
1752
1864
|
try {
|
|
1753
|
-
return
|
|
1865
|
+
return fs15.statSync(outboxFilePath).size > 0;
|
|
1754
1866
|
} catch {
|
|
1755
1867
|
return false;
|
|
1756
1868
|
}
|
|
@@ -1909,8 +2021,8 @@ var require_agentEvent = __commonJS({
|
|
|
1909
2021
|
return "pr_created";
|
|
1910
2022
|
if (milestone === "pr_merged")
|
|
1911
2023
|
return "pr_merged";
|
|
1912
|
-
const
|
|
1913
|
-
return
|
|
2024
|
+
const git2 = stringField(metadata.gitAction);
|
|
2025
|
+
return git2 === "commit" || git2 === "push" ? git2 : void 0;
|
|
1914
2026
|
}
|
|
1915
2027
|
function waitReasonOf(metadata) {
|
|
1916
2028
|
switch (stringField(metadata.interruptionKind)) {
|
|
@@ -2013,24 +2125,24 @@ var require_credentials = __commonJS({
|
|
|
2013
2125
|
}();
|
|
2014
2126
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
2015
2127
|
exports.credentialsFilePath = credentialsFilePath;
|
|
2016
|
-
exports.readMachineCredentials =
|
|
2128
|
+
exports.readMachineCredentials = readMachineCredentials3;
|
|
2017
2129
|
exports.writeMachineCredentials = writeMachineCredentials;
|
|
2018
2130
|
exports.writeTopLevelCredentials = writeTopLevelCredentials;
|
|
2019
2131
|
exports.writeRepoKeysSetting = writeRepoKeysSetting;
|
|
2020
2132
|
exports.writeEventLogSetting = writeEventLogSetting;
|
|
2021
2133
|
exports.isLocalOnlyHostInstall = isLocalOnlyHostInstall;
|
|
2022
|
-
exports.readHostCredentials =
|
|
2134
|
+
exports.readHostCredentials = readHostCredentials2;
|
|
2023
2135
|
exports.writeHostCredentials = writeHostCredentials;
|
|
2024
2136
|
exports.removeHostCredentials = removeHostCredentials;
|
|
2025
|
-
var
|
|
2026
|
-
var
|
|
2137
|
+
var fs15 = __importStar(__require("fs"));
|
|
2138
|
+
var path15 = __importStar(__require("path"));
|
|
2027
2139
|
var tokenStore_1 = require_tokenStore();
|
|
2028
2140
|
function credentialsFilePath() {
|
|
2029
|
-
return
|
|
2141
|
+
return path15.join((0, tokenStore_1.ascendaHome)(), "credentials.json");
|
|
2030
2142
|
}
|
|
2031
|
-
function
|
|
2143
|
+
function readMachineCredentials3() {
|
|
2032
2144
|
try {
|
|
2033
|
-
const raw =
|
|
2145
|
+
const raw = fs15.readFileSync(credentialsFilePath(), "utf8").trim();
|
|
2034
2146
|
if (!raw)
|
|
2035
2147
|
return void 0;
|
|
2036
2148
|
const parsed = JSON.parse(raw);
|
|
@@ -2043,16 +2155,16 @@ var require_credentials = __commonJS({
|
|
|
2043
2155
|
}
|
|
2044
2156
|
function writeMachineCredentials(credentials) {
|
|
2045
2157
|
const file = credentialsFilePath();
|
|
2046
|
-
|
|
2047
|
-
|
|
2158
|
+
fs15.mkdirSync(path15.dirname(file), { recursive: true, mode: 448 });
|
|
2159
|
+
fs15.writeFileSync(file, `${JSON.stringify(credentials, null, 2)}
|
|
2048
2160
|
`, { encoding: "utf8", mode: 384 });
|
|
2049
2161
|
if (process.platform !== "win32") {
|
|
2050
|
-
|
|
2051
|
-
|
|
2162
|
+
fs15.chmodSync(path15.dirname(file), 448);
|
|
2163
|
+
fs15.chmodSync(file, 384);
|
|
2052
2164
|
}
|
|
2053
2165
|
}
|
|
2054
2166
|
function writeTopLevelCredentials(credentials) {
|
|
2055
|
-
const existing =
|
|
2167
|
+
const existing = readMachineCredentials3();
|
|
2056
2168
|
const eventLogPath = credentials.eventLogPath ?? existing?.eventLogPath;
|
|
2057
2169
|
const repoKeys = credentials.repoKeys ?? existing?.repoKeys;
|
|
2058
2170
|
writeMachineCredentials({
|
|
@@ -2063,34 +2175,34 @@ var require_credentials = __commonJS({
|
|
|
2063
2175
|
});
|
|
2064
2176
|
}
|
|
2065
2177
|
function writeRepoKeysSetting(on) {
|
|
2066
|
-
const existing =
|
|
2178
|
+
const existing = readMachineCredentials3() ?? {};
|
|
2067
2179
|
const { repoKeys: _dropped, ...rest } = existing;
|
|
2068
2180
|
writeMachineCredentials(on ? rest : { ...rest, repoKeys: false });
|
|
2069
2181
|
}
|
|
2070
2182
|
function writeEventLogSetting(value) {
|
|
2071
|
-
const existing =
|
|
2183
|
+
const existing = readMachineCredentials3() ?? {};
|
|
2072
2184
|
writeMachineCredentials({ ...existing, eventLogPath: value });
|
|
2073
2185
|
}
|
|
2074
2186
|
function isLocalOnlyHostInstall(host, hasToken) {
|
|
2075
|
-
const credentials =
|
|
2187
|
+
const credentials = readHostCredentials2(host);
|
|
2076
2188
|
if (!credentials?.localOnly)
|
|
2077
2189
|
return false;
|
|
2078
2190
|
if (process.env.ASCENDA_EVENT_WRITE_TOKEN)
|
|
2079
2191
|
return false;
|
|
2080
2192
|
return !(credentials.toolInstallationId && hasToken(credentials.toolInstallationId));
|
|
2081
2193
|
}
|
|
2082
|
-
function
|
|
2083
|
-
const entry =
|
|
2194
|
+
function readHostCredentials2(host) {
|
|
2195
|
+
const entry = readMachineCredentials3()?.tools?.[host];
|
|
2084
2196
|
if (!entry || typeof entry !== "object" || Array.isArray(entry))
|
|
2085
2197
|
return void 0;
|
|
2086
2198
|
return entry;
|
|
2087
2199
|
}
|
|
2088
2200
|
function writeHostCredentials(host, credentials) {
|
|
2089
|
-
const existing =
|
|
2201
|
+
const existing = readMachineCredentials3() ?? {};
|
|
2090
2202
|
writeMachineCredentials({ ...existing, tools: { ...existing.tools ?? {}, [host]: credentials } });
|
|
2091
2203
|
}
|
|
2092
2204
|
function removeHostCredentials(host) {
|
|
2093
|
-
const existing =
|
|
2205
|
+
const existing = readMachineCredentials3();
|
|
2094
2206
|
if (!existing?.tools || !(host in existing.tools))
|
|
2095
2207
|
return;
|
|
2096
2208
|
const tools = { ...existing.tools };
|
|
@@ -2155,9 +2267,9 @@ var require_eventLog = __commonJS({
|
|
|
2155
2267
|
exports.describeEventLog = describeEventLog;
|
|
2156
2268
|
exports.parseEventLogFlag = parseEventLogFlag;
|
|
2157
2269
|
exports.appendEventLog = appendEventLog;
|
|
2158
|
-
var
|
|
2159
|
-
var
|
|
2160
|
-
var
|
|
2270
|
+
var fs15 = __importStar(__require("fs"));
|
|
2271
|
+
var os6 = __importStar(__require("os"));
|
|
2272
|
+
var path15 = __importStar(__require("path"));
|
|
2161
2273
|
var agentEvent_1 = require_agentEvent();
|
|
2162
2274
|
var credentials_1 = require_credentials();
|
|
2163
2275
|
var tokenStore_1 = require_tokenStore();
|
|
@@ -2169,13 +2281,13 @@ var require_eventLog = __commonJS({
|
|
|
2169
2281
|
if (!value)
|
|
2170
2282
|
return void 0;
|
|
2171
2283
|
if (value === "~")
|
|
2172
|
-
return
|
|
2284
|
+
return os6.homedir();
|
|
2173
2285
|
if (value.startsWith("~/"))
|
|
2174
|
-
return
|
|
2175
|
-
return
|
|
2286
|
+
return path15.join(os6.homedir(), value.slice(2));
|
|
2287
|
+
return path15.resolve(value);
|
|
2176
2288
|
}
|
|
2177
2289
|
function defaultEventLogPath() {
|
|
2178
|
-
return
|
|
2290
|
+
return path15.join((0, tokenStore_1.ascendaHome)(), "events.jsonl");
|
|
2179
2291
|
}
|
|
2180
2292
|
function resolveEventLog(options = {}) {
|
|
2181
2293
|
for (const [source, raw] of [
|
|
@@ -2219,21 +2331,21 @@ var require_eventLog = __commonJS({
|
|
|
2219
2331
|
function appendEventLog(logFilePath, entry) {
|
|
2220
2332
|
try {
|
|
2221
2333
|
rotateIfLarge(logFilePath);
|
|
2222
|
-
const dir =
|
|
2223
|
-
|
|
2334
|
+
const dir = path15.dirname(logFilePath);
|
|
2335
|
+
fs15.mkdirSync(dir, { recursive: true, mode: 448 });
|
|
2224
2336
|
const line = { ...entry, event: entry.event ?? (0, agentEvent_1.toAgentEvent)(entry.payload) };
|
|
2225
|
-
|
|
2337
|
+
fs15.appendFileSync(logFilePath, `${JSON.stringify(line)}
|
|
2226
2338
|
`, { encoding: "utf8", mode: 384 });
|
|
2227
2339
|
if (process.platform !== "win32")
|
|
2228
|
-
|
|
2340
|
+
fs15.chmodSync(logFilePath, 384);
|
|
2229
2341
|
} catch {
|
|
2230
2342
|
}
|
|
2231
2343
|
}
|
|
2232
2344
|
function rotateIfLarge(logFilePath) {
|
|
2233
2345
|
try {
|
|
2234
|
-
if (
|
|
2346
|
+
if (fs15.statSync(logFilePath).size < MAX_BYTES)
|
|
2235
2347
|
return;
|
|
2236
|
-
|
|
2348
|
+
fs15.renameSync(logFilePath, `${logFilePath}.1`);
|
|
2237
2349
|
} catch {
|
|
2238
2350
|
}
|
|
2239
2351
|
}
|
|
@@ -2254,7 +2366,7 @@ var require_http = __commonJS({
|
|
|
2254
2366
|
exports.readStudyNotices = readStudyNotices;
|
|
2255
2367
|
exports.setStudyObjection = setStudyObjection;
|
|
2256
2368
|
exports.markStudyNoticeShown = markStudyNoticeShown;
|
|
2257
|
-
exports.renewToolToken =
|
|
2369
|
+
exports.renewToolToken = renewToolToken2;
|
|
2258
2370
|
exports.isRetryableStatus = isRetryableStatus;
|
|
2259
2371
|
exports.postToolEvent = postToolEvent;
|
|
2260
2372
|
exports.postToolEventsBatch = postToolEventsBatch;
|
|
@@ -2271,14 +2383,14 @@ var require_http = __commonJS({
|
|
|
2271
2383
|
}
|
|
2272
2384
|
};
|
|
2273
2385
|
exports.AscendaApiError = AscendaApiError;
|
|
2274
|
-
async function createPairingSession(apiBaseUrl, toolInstallationId, toolType, displayName) {
|
|
2386
|
+
async function createPairingSession(apiBaseUrl, toolInstallationId, toolType, displayName, orgJoinCode) {
|
|
2275
2387
|
const response = await fetch(`${apiBaseUrl}/v1/tool-pairing-sessions`, {
|
|
2276
2388
|
method: "POST",
|
|
2277
2389
|
headers: { "Content-Type": "application/json" },
|
|
2278
|
-
body: JSON.stringify({ toolInstallationId, toolType, displayName })
|
|
2390
|
+
body: JSON.stringify({ toolInstallationId, toolType, displayName, ...orgJoinCode ? { orgJoinCode, mode: "report" } : {} })
|
|
2279
2391
|
});
|
|
2280
2392
|
if (!response.ok)
|
|
2281
|
-
throw
|
|
2393
|
+
throw await apiError(response);
|
|
2282
2394
|
return await response.json();
|
|
2283
2395
|
}
|
|
2284
2396
|
async function getPairingStatus(apiBaseUrl, pairingSessionId) {
|
|
@@ -2392,7 +2504,7 @@ var require_http = __commonJS({
|
|
|
2392
2504
|
}
|
|
2393
2505
|
return new AscendaApiError(response.status, errorCode, body);
|
|
2394
2506
|
}
|
|
2395
|
-
async function
|
|
2507
|
+
async function renewToolToken2(apiBaseUrl, eventWriteToken, signal) {
|
|
2396
2508
|
const response = await fetch(`${apiBaseUrl}/v1/tool-events/renew-token`, {
|
|
2397
2509
|
method: "POST",
|
|
2398
2510
|
headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
|
|
@@ -2528,6 +2640,7 @@ var require_eventSender = __commonJS({
|
|
|
2528
2640
|
var tokenStore_1 = require_tokenStore();
|
|
2529
2641
|
var stateStore_1 = require_stateStore();
|
|
2530
2642
|
var payload_1 = require_payload();
|
|
2643
|
+
var collectorPlatform_1 = require_collectorPlatform();
|
|
2531
2644
|
var collectorVersion_1 = require_collectorVersion();
|
|
2532
2645
|
var AscendaSemanticEventError = class extends Error {
|
|
2533
2646
|
constructor(message) {
|
|
@@ -2555,7 +2668,7 @@ var require_eventSender = __commonJS({
|
|
|
2555
2668
|
return (0, tool_contract_1.joinEventPayload)({ toolInstallationId: identity.toolInstallationId, idempotencyKey: (0, payload_1.mintIdempotencyKey)() }, buildEventBody(identity, mapped));
|
|
2556
2669
|
}
|
|
2557
2670
|
function withCollectorVersion(metadata) {
|
|
2558
|
-
return { ...metadata, collectorVersion: collectorVersion_1.COLLECTOR_VERSION };
|
|
2671
|
+
return { ...metadata, collectorVersion: collectorVersion_1.COLLECTOR_VERSION, collectorPlatform: collectorPlatform_1.COLLECTOR_PLATFORM };
|
|
2559
2672
|
}
|
|
2560
2673
|
var DEFAULT_TIMEOUT_MS = 5e3;
|
|
2561
2674
|
var RETRY_DELAY_MS = 250;
|
|
@@ -3021,16 +3134,16 @@ var require_contextRegistry = __commonJS({
|
|
|
3021
3134
|
exports.readWorkContextRegistry = readWorkContextRegistry;
|
|
3022
3135
|
exports.recordWorkContext = recordWorkContext2;
|
|
3023
3136
|
exports.recordWorkContextAlias = recordWorkContextAlias2;
|
|
3024
|
-
var
|
|
3025
|
-
var
|
|
3026
|
-
var
|
|
3137
|
+
var fs15 = __importStar(__require("fs"));
|
|
3138
|
+
var os6 = __importStar(__require("os"));
|
|
3139
|
+
var path15 = __importStar(__require("path"));
|
|
3027
3140
|
var MAX_PATHS_PER_ENTRY = 8;
|
|
3028
3141
|
function workContextRegistryFilePath() {
|
|
3029
|
-
return
|
|
3142
|
+
return path15.join(os6.homedir(), ".ascenda", "work-contexts.json");
|
|
3030
3143
|
}
|
|
3031
3144
|
function readWorkContextRegistry(registryFilePath = workContextRegistryFilePath()) {
|
|
3032
3145
|
try {
|
|
3033
|
-
const parsed = JSON.parse(
|
|
3146
|
+
const parsed = JSON.parse(fs15.readFileSync(registryFilePath, "utf8"));
|
|
3034
3147
|
if (parsed && parsed.version === 1 && parsed.contexts && typeof parsed.contexts === "object") {
|
|
3035
3148
|
return parsed;
|
|
3036
3149
|
}
|
|
@@ -3106,14 +3219,14 @@ var require_contextRegistry = __commonJS({
|
|
|
3106
3219
|
return iso.slice(0, 10);
|
|
3107
3220
|
}
|
|
3108
3221
|
function writeRegistry(registryFilePath, registry) {
|
|
3109
|
-
const dir =
|
|
3110
|
-
|
|
3222
|
+
const dir = path15.dirname(registryFilePath);
|
|
3223
|
+
fs15.mkdirSync(dir, { recursive: true, mode: 448 });
|
|
3111
3224
|
const tmp = `${registryFilePath}.${process.pid}.tmp`;
|
|
3112
|
-
|
|
3225
|
+
fs15.writeFileSync(tmp, `${JSON.stringify(registry, null, 2)}
|
|
3113
3226
|
`, { encoding: "utf8", mode: 384 });
|
|
3114
|
-
|
|
3227
|
+
fs15.renameSync(tmp, registryFilePath);
|
|
3115
3228
|
if (process.platform !== "win32") {
|
|
3116
|
-
|
|
3229
|
+
fs15.chmodSync(registryFilePath, 384);
|
|
3117
3230
|
}
|
|
3118
3231
|
}
|
|
3119
3232
|
}
|
|
@@ -3162,14 +3275,14 @@ var require_forgeProject = __commonJS({
|
|
|
3162
3275
|
}();
|
|
3163
3276
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3164
3277
|
exports.forgeProjectHash = forgeProjectHash;
|
|
3165
|
-
exports.forgeRepoKey =
|
|
3166
|
-
exports.forgeBranchKey =
|
|
3278
|
+
exports.forgeRepoKey = forgeRepoKey2;
|
|
3279
|
+
exports.forgeBranchKey = forgeBranchKey2;
|
|
3167
3280
|
exports.parseForgeFullName = parseForgeFullName;
|
|
3168
|
-
exports.readForgeFullName =
|
|
3281
|
+
exports.readForgeFullName = readForgeFullName2;
|
|
3169
3282
|
exports.forgeFullNameFromConfig = forgeFullNameFromConfig;
|
|
3170
3283
|
exports.recordForgeProjectAlias = recordForgeProjectAlias;
|
|
3171
|
-
var
|
|
3172
|
-
var
|
|
3284
|
+
var fs15 = __importStar(__require("fs"));
|
|
3285
|
+
var path15 = __importStar(__require("path"));
|
|
3173
3286
|
var contextRegistry_1 = require_contextRegistry();
|
|
3174
3287
|
function forgeProjectHash(value) {
|
|
3175
3288
|
let h = 2166136261;
|
|
@@ -3179,10 +3292,10 @@ var require_forgeProject = __commonJS({
|
|
|
3179
3292
|
}
|
|
3180
3293
|
return h.toString(16).padStart(8, "0");
|
|
3181
3294
|
}
|
|
3182
|
-
function
|
|
3295
|
+
function forgeRepoKey2(fullName) {
|
|
3183
3296
|
return forgeProjectHash(fullName.toLowerCase());
|
|
3184
3297
|
}
|
|
3185
|
-
function
|
|
3298
|
+
function forgeBranchKey2(fullName, branch) {
|
|
3186
3299
|
const input = `${fullName.toLowerCase()}
|
|
3187
3300
|
${branch}`;
|
|
3188
3301
|
let h = 0xcbf29ce484222325n;
|
|
@@ -3223,12 +3336,12 @@ ${branch}`;
|
|
|
3223
3336
|
return null;
|
|
3224
3337
|
return `${owner}/${repo}`;
|
|
3225
3338
|
}
|
|
3226
|
-
function
|
|
3339
|
+
function readForgeFullName2(repositoryRoot) {
|
|
3227
3340
|
if (!repositoryRoot)
|
|
3228
3341
|
return null;
|
|
3229
3342
|
let config;
|
|
3230
3343
|
try {
|
|
3231
|
-
config =
|
|
3344
|
+
config = fs15.readFileSync(path15.join(repositoryRoot, ".git", "config"), "utf8");
|
|
3232
3345
|
} catch {
|
|
3233
3346
|
return null;
|
|
3234
3347
|
}
|
|
@@ -3269,7 +3382,7 @@ ${branch}`;
|
|
|
3269
3382
|
try {
|
|
3270
3383
|
if (!context?.projectHash || !context.projectLabel || !context.projectPath)
|
|
3271
3384
|
return false;
|
|
3272
|
-
const fullName =
|
|
3385
|
+
const fullName = readForgeFullName2(context.projectPath);
|
|
3273
3386
|
if (!fullName)
|
|
3274
3387
|
return false;
|
|
3275
3388
|
const variants = [fullName, fullName.toLowerCase()].filter((value, index, all) => all.indexOf(value) === index);
|
|
@@ -3335,31 +3448,31 @@ var require_salt = __commonJS({
|
|
|
3335
3448
|
exports.readOrCreateMachineSalt = readOrCreateMachineSalt;
|
|
3336
3449
|
exports.hashWithMachineSalt = hashWithMachineSalt2;
|
|
3337
3450
|
var crypto = __importStar(__require("crypto"));
|
|
3338
|
-
var
|
|
3339
|
-
var
|
|
3451
|
+
var fs15 = __importStar(__require("fs"));
|
|
3452
|
+
var path15 = __importStar(__require("path"));
|
|
3340
3453
|
var tokenStore_1 = require_tokenStore();
|
|
3341
3454
|
function machineSaltFilePath() {
|
|
3342
|
-
return
|
|
3455
|
+
return path15.join((0, tokenStore_1.ascendaHome)(), "salt");
|
|
3343
3456
|
}
|
|
3344
3457
|
var cache = /* @__PURE__ */ new Map();
|
|
3345
3458
|
function readOrCreateMachineSalt(saltFilePath = machineSaltFilePath()) {
|
|
3346
3459
|
const hit = cache.get(saltFilePath);
|
|
3347
3460
|
if (hit)
|
|
3348
3461
|
return hit;
|
|
3349
|
-
const dir =
|
|
3350
|
-
|
|
3462
|
+
const dir = path15.dirname(saltFilePath);
|
|
3463
|
+
fs15.mkdirSync(dir, { recursive: true, mode: 448 });
|
|
3351
3464
|
let salt;
|
|
3352
3465
|
try {
|
|
3353
3466
|
salt = crypto.randomBytes(32).toString("hex");
|
|
3354
|
-
|
|
3467
|
+
fs15.writeFileSync(saltFilePath, salt, { encoding: "utf8", mode: 384, flag: "wx" });
|
|
3355
3468
|
} catch (error) {
|
|
3356
3469
|
if (error.code !== "EEXIST")
|
|
3357
3470
|
throw error;
|
|
3358
|
-
salt =
|
|
3471
|
+
salt = fs15.readFileSync(saltFilePath, "utf8").trim();
|
|
3359
3472
|
}
|
|
3360
3473
|
if (process.platform !== "win32") {
|
|
3361
|
-
|
|
3362
|
-
|
|
3474
|
+
fs15.chmodSync(dir, 448);
|
|
3475
|
+
fs15.chmodSync(saltFilePath, 384);
|
|
3363
3476
|
}
|
|
3364
3477
|
cache.set(saltFilePath, salt);
|
|
3365
3478
|
return salt;
|
|
@@ -3414,16 +3527,16 @@ var require_workContext = __commonJS({
|
|
|
3414
3527
|
};
|
|
3415
3528
|
}();
|
|
3416
3529
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3417
|
-
exports.deriveWorkContext =
|
|
3530
|
+
exports.deriveWorkContext = deriveWorkContext4;
|
|
3418
3531
|
exports.normalizeBranchName = normalizeBranchName;
|
|
3419
|
-
exports.deriveBranchHash =
|
|
3532
|
+
exports.deriveBranchHash = deriveBranchHash3;
|
|
3420
3533
|
exports.readBranchName = readBranchName;
|
|
3421
3534
|
exports.deriveBranchHashForCwd = deriveBranchHashForCwd;
|
|
3422
|
-
var
|
|
3423
|
-
var
|
|
3535
|
+
var fs15 = __importStar(__require("fs"));
|
|
3536
|
+
var path15 = __importStar(__require("path"));
|
|
3424
3537
|
var salt_1 = require_salt();
|
|
3425
3538
|
var MAX_WALK_DEPTH = 64;
|
|
3426
|
-
function
|
|
3539
|
+
function deriveWorkContext4(cwd, saltFilePath) {
|
|
3427
3540
|
if (!cwd || !cwd.trim())
|
|
3428
3541
|
return null;
|
|
3429
3542
|
const startPath = stripTrailingSeparators(cwd.trim());
|
|
@@ -3451,14 +3564,14 @@ var require_workContext = __commonJS({
|
|
|
3451
3564
|
};
|
|
3452
3565
|
}
|
|
3453
3566
|
function resolveRepositoryRoots(startDir) {
|
|
3454
|
-
if (!
|
|
3567
|
+
if (!fs15.existsSync(startDir))
|
|
3455
3568
|
return null;
|
|
3456
3569
|
let dir = startDir;
|
|
3457
3570
|
for (let depth = 0; depth < MAX_WALK_DEPTH; depth++) {
|
|
3458
|
-
const dotGit =
|
|
3571
|
+
const dotGit = path15.join(dir, ".git");
|
|
3459
3572
|
let stat6 = null;
|
|
3460
3573
|
try {
|
|
3461
|
-
stat6 =
|
|
3574
|
+
stat6 = fs15.statSync(dotGit);
|
|
3462
3575
|
} catch {
|
|
3463
3576
|
stat6 = null;
|
|
3464
3577
|
}
|
|
@@ -3469,7 +3582,7 @@ var require_workContext = __commonJS({
|
|
|
3469
3582
|
const canonicalRoot = (gitDir ? worktreeParentRoot(gitDir) : null) ?? dir;
|
|
3470
3583
|
return { checkoutRoot: dir, canonicalRoot, gitDir };
|
|
3471
3584
|
}
|
|
3472
|
-
const parent =
|
|
3585
|
+
const parent = path15.dirname(dir);
|
|
3473
3586
|
if (parent === dir)
|
|
3474
3587
|
return null;
|
|
3475
3588
|
dir = parent;
|
|
@@ -3478,31 +3591,31 @@ var require_workContext = __commonJS({
|
|
|
3478
3591
|
}
|
|
3479
3592
|
function readGitdirPointer(dotGitFile, containingDir) {
|
|
3480
3593
|
try {
|
|
3481
|
-
const match = /^gitdir:\s*(.+)\s*$/m.exec(
|
|
3594
|
+
const match = /^gitdir:\s*(.+)\s*$/m.exec(fs15.readFileSync(dotGitFile, "utf8"));
|
|
3482
3595
|
if (!match)
|
|
3483
3596
|
return null;
|
|
3484
|
-
return
|
|
3597
|
+
return path15.resolve(containingDir, match[1].trim());
|
|
3485
3598
|
} catch {
|
|
3486
3599
|
return null;
|
|
3487
3600
|
}
|
|
3488
3601
|
}
|
|
3489
3602
|
function worktreeParentRoot(resolvedGitDir) {
|
|
3490
|
-
const marker = `${
|
|
3603
|
+
const marker = `${path15.sep}.git${path15.sep}worktrees${path15.sep}`;
|
|
3491
3604
|
const idx = resolvedGitDir.indexOf(marker);
|
|
3492
3605
|
if (idx === -1)
|
|
3493
3606
|
return null;
|
|
3494
3607
|
return resolvedGitDir.slice(0, idx);
|
|
3495
3608
|
}
|
|
3496
3609
|
function inferRootsFromPath(startPath) {
|
|
3497
|
-
const
|
|
3498
|
-
const leading = /^[\\/]/.test(startPath) ?
|
|
3610
|
+
const sep2 = startPath.includes("\\") && !startPath.includes("/") ? "\\" : "/";
|
|
3611
|
+
const leading = /^[\\/]/.test(startPath) ? sep2 : "";
|
|
3499
3612
|
const segments = startPath.split(/[\\/]/).filter(Boolean);
|
|
3500
|
-
const
|
|
3613
|
+
const join14 = (count) => leading + segments.slice(0, count).join(sep2);
|
|
3501
3614
|
for (let i = 0; i + 2 < segments.length; i++) {
|
|
3502
3615
|
if (segments[i] === ".claude" && segments[i + 1] === "worktrees") {
|
|
3503
3616
|
if (i === 0)
|
|
3504
3617
|
return null;
|
|
3505
|
-
return { checkoutRoot:
|
|
3618
|
+
return { checkoutRoot: join14(i + 3), canonicalRoot: join14(i), gitDir: null };
|
|
3506
3619
|
}
|
|
3507
3620
|
}
|
|
3508
3621
|
for (let i = 0; i + 1 < segments.length; i++) {
|
|
@@ -3511,8 +3624,8 @@ var require_workContext = __commonJS({
|
|
|
3511
3624
|
if (!suffix)
|
|
3512
3625
|
continue;
|
|
3513
3626
|
const repoName = folder.slice(0, -suffix.length);
|
|
3514
|
-
const canonicalRoot = leading + [...segments.slice(0, i), repoName].join(
|
|
3515
|
-
return { checkoutRoot:
|
|
3627
|
+
const canonicalRoot = leading + [...segments.slice(0, i), repoName].join(sep2);
|
|
3628
|
+
return { checkoutRoot: join14(i + 2), canonicalRoot, gitDir: null };
|
|
3516
3629
|
}
|
|
3517
3630
|
return null;
|
|
3518
3631
|
}
|
|
@@ -3537,7 +3650,7 @@ var require_workContext = __commonJS({
|
|
|
3537
3650
|
return null;
|
|
3538
3651
|
return name;
|
|
3539
3652
|
}
|
|
3540
|
-
function
|
|
3653
|
+
function deriveBranchHash3(branch, saltFilePath) {
|
|
3541
3654
|
const name = normalizeBranchName(branch);
|
|
3542
3655
|
if (!name)
|
|
3543
3656
|
return null;
|
|
@@ -3560,7 +3673,7 @@ var require_workContext = __commonJS({
|
|
|
3560
3673
|
return null;
|
|
3561
3674
|
let head;
|
|
3562
3675
|
try {
|
|
3563
|
-
head =
|
|
3676
|
+
head = fs15.readFileSync(path15.join(gitDir, "HEAD"), "utf8").trim();
|
|
3564
3677
|
} catch {
|
|
3565
3678
|
return null;
|
|
3566
3679
|
}
|
|
@@ -3573,7 +3686,7 @@ var require_workContext = __commonJS({
|
|
|
3573
3686
|
return normalizeBranchName(ref);
|
|
3574
3687
|
}
|
|
3575
3688
|
function deriveBranchHashForCwd(cwd, saltFilePath) {
|
|
3576
|
-
return
|
|
3689
|
+
return deriveBranchHash3(readBranchName(cwd), saltFilePath);
|
|
3577
3690
|
}
|
|
3578
3691
|
}
|
|
3579
3692
|
});
|
|
@@ -3621,15 +3734,15 @@ var require_forgeKeys = __commonJS({
|
|
|
3621
3734
|
}();
|
|
3622
3735
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3623
3736
|
exports.REPO_KEYS_ENV_VAR = void 0;
|
|
3624
|
-
exports.repoKeysEnabled =
|
|
3737
|
+
exports.repoKeysEnabled = repoKeysEnabled2;
|
|
3625
3738
|
exports.deriveForgeKeysForCwd = deriveForgeKeysForCwd;
|
|
3626
|
-
var
|
|
3627
|
-
var
|
|
3739
|
+
var fs15 = __importStar(__require("fs"));
|
|
3740
|
+
var path15 = __importStar(__require("path"));
|
|
3628
3741
|
var credentials_1 = require_credentials();
|
|
3629
3742
|
var forgeProject_1 = require_forgeProject();
|
|
3630
3743
|
var workContext_1 = require_workContext();
|
|
3631
3744
|
exports.REPO_KEYS_ENV_VAR = "ASCENDA_REPO_KEYS";
|
|
3632
|
-
function
|
|
3745
|
+
function repoKeysEnabled2() {
|
|
3633
3746
|
const env = process.env[exports.REPO_KEYS_ENV_VAR]?.trim().toLowerCase();
|
|
3634
3747
|
if (env === "off" || env === "0" || env === "false")
|
|
3635
3748
|
return false;
|
|
@@ -3639,7 +3752,7 @@ var require_forgeKeys = __commonJS({
|
|
|
3639
3752
|
}
|
|
3640
3753
|
function readDefaultBranch(repositoryRoot) {
|
|
3641
3754
|
try {
|
|
3642
|
-
const head =
|
|
3755
|
+
const head = fs15.readFileSync(path15.join(repositoryRoot, ".git", "refs", "remotes", "origin", "HEAD"), "utf8").trim();
|
|
3643
3756
|
const match = /^ref:\s*refs\/remotes\/origin\/(.+)$/.exec(head);
|
|
3644
3757
|
return match ? (0, workContext_1.normalizeBranchName)(match[1]) : null;
|
|
3645
3758
|
} catch {
|
|
@@ -3648,7 +3761,7 @@ var require_forgeKeys = __commonJS({
|
|
|
3648
3761
|
}
|
|
3649
3762
|
function deriveForgeKeysForCwd(cwd) {
|
|
3650
3763
|
try {
|
|
3651
|
-
if (!cwd || !
|
|
3764
|
+
if (!cwd || !repoKeysEnabled2())
|
|
3652
3765
|
return {};
|
|
3653
3766
|
const root = (0, workContext_1.deriveWorkContext)(cwd)?.projectPath;
|
|
3654
3767
|
const fullName = (0, forgeProject_1.readForgeFullName)(root);
|
|
@@ -3899,58 +4012,36 @@ var require_hookAdapter = __commonJS({
|
|
|
3899
4012
|
}
|
|
3900
4013
|
});
|
|
3901
4014
|
|
|
3902
|
-
// ../packages/tool-kit/out/
|
|
3903
|
-
var
|
|
3904
|
-
"../packages/tool-kit/out/
|
|
4015
|
+
// ../packages/tool-kit/out/confirmLinks.js
|
|
4016
|
+
var require_confirmLinks = __commonJS({
|
|
4017
|
+
"../packages/tool-kit/out/confirmLinks.js"(exports) {
|
|
3905
4018
|
"use strict";
|
|
3906
4019
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3907
|
-
exports.
|
|
3908
|
-
exports.
|
|
3909
|
-
exports.
|
|
3910
|
-
|
|
3911
|
-
|
|
3912
|
-
|
|
3913
|
-
|
|
3914
|
-
|
|
3915
|
-
|
|
3916
|
-
|
|
3917
|
-
|
|
3918
|
-
|
|
3919
|
-
|
|
3920
|
-
|
|
3921
|
-
const index = argv.indexOf(exports.HOOK_SET_FLAG);
|
|
3922
|
-
if (index === -1)
|
|
3923
|
-
return void 0;
|
|
3924
|
-
const raw = argv[index + 1];
|
|
3925
|
-
if (raw === void 0 || !/^[1-9]\d*$/.test(raw))
|
|
4020
|
+
exports.pairingConfirmUrl = pairingConfirmUrl;
|
|
4021
|
+
exports.pairingConfirmLines = pairingConfirmLines;
|
|
4022
|
+
exports.studyJoinConfirmUrl = studyJoinConfirmUrl;
|
|
4023
|
+
function pairingConfirmUrl(qrUrl) {
|
|
4024
|
+
return isHttps(qrUrl) ? qrUrl : void 0;
|
|
4025
|
+
}
|
|
4026
|
+
function pairingConfirmLines(qrUrl, code) {
|
|
4027
|
+
const url = pairingConfirmUrl(qrUrl);
|
|
4028
|
+
if (!url)
|
|
4029
|
+
return [`Confirm in the Ascenda app \u2014 code ${code}`];
|
|
4030
|
+
return [`Open this link to confirm: ${url}`, `Or paste code ${code} in the Ascenda app.`];
|
|
4031
|
+
}
|
|
4032
|
+
function studyJoinConfirmUrl(apiBaseUrl, deviceCode) {
|
|
4033
|
+
if (!isHttps(apiBaseUrl))
|
|
3926
4034
|
return void 0;
|
|
3927
|
-
|
|
3928
|
-
return isHookSet(value) ? value : void 0;
|
|
3929
|
-
}
|
|
3930
|
-
function isHookSet(value) {
|
|
3931
|
-
return typeof value === "number" && Number.isSafeInteger(value) && value >= 1;
|
|
3932
|
-
}
|
|
3933
|
-
function readViaPlugin(env) {
|
|
3934
|
-
return env.CLAUDE_PLUGIN_ROOT ? true : void 0;
|
|
3935
|
-
}
|
|
3936
|
-
function hookSetOfCommand(command) {
|
|
3937
|
-
const match = command.match(/--hook-set\s+(\d+)/);
|
|
3938
|
-
return match ? Number(match[1]) : exports.UNVERSIONED_HOOK_SET;
|
|
3939
|
-
}
|
|
3940
|
-
function hookSetChanges(before, events) {
|
|
3941
|
-
const added = events.filter((event) => !before.has(event));
|
|
3942
|
-
const sets = [...before.values()];
|
|
3943
|
-
return sets.length ? { added, previousSet: Math.min(...sets) } : { added };
|
|
4035
|
+
return `${apiBaseUrl.replace(/\/+$/, "")}/join/${encodeURIComponent(deviceCode)}`;
|
|
3944
4036
|
}
|
|
3945
|
-
function
|
|
3946
|
-
if (
|
|
3947
|
-
return
|
|
3948
|
-
|
|
3949
|
-
|
|
3950
|
-
|
|
3951
|
-
|
|
3952
|
-
|
|
3953
|
-
return parts.length ? `upgraded: ${parts.join("; ")}` : void 0;
|
|
4037
|
+
function isHttps(value) {
|
|
4038
|
+
if (!value)
|
|
4039
|
+
return false;
|
|
4040
|
+
try {
|
|
4041
|
+
return new URL(value).protocol === "https:";
|
|
4042
|
+
} catch {
|
|
4043
|
+
return false;
|
|
4044
|
+
}
|
|
3954
4045
|
}
|
|
3955
4046
|
}
|
|
3956
4047
|
});
|
|
@@ -3997,14 +4088,19 @@ var require_studyJoin = __commonJS({
|
|
|
3997
4088
|
};
|
|
3998
4089
|
}();
|
|
3999
4090
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4000
|
-
exports.runStudyJoin =
|
|
4001
|
-
exports.formatWindow =
|
|
4002
|
-
|
|
4091
|
+
exports.runStudyJoin = runStudyJoin2;
|
|
4092
|
+
exports.formatWindow = formatWindow2;
|
|
4093
|
+
exports.describeStudyGrant = describeStudyGrant2;
|
|
4094
|
+
exports.describeStudyKind = describeStudyKind2;
|
|
4095
|
+
exports.describeRefusal = describeRefusal;
|
|
4096
|
+
var readline2 = __importStar(__require("node:readline"));
|
|
4097
|
+
var confirmLinks_1 = require_confirmLinks();
|
|
4003
4098
|
var http_1 = require_http();
|
|
4004
4099
|
var STUDY_JOIN_MODE = "report";
|
|
4005
4100
|
var POLL_INTERVAL_MS = 3e3;
|
|
4006
4101
|
var POLL_TIMEOUT_MS = 11 * 60 * 1e3;
|
|
4007
|
-
async function
|
|
4102
|
+
async function runStudyJoin2(ctx) {
|
|
4103
|
+
const report = (outcome) => ctx.onOutcome?.(outcome);
|
|
4008
4104
|
const stdin = ctx.stdin ?? process.stdin;
|
|
4009
4105
|
const stdout = ctx.stdout ?? process.stdout;
|
|
4010
4106
|
const stderr = ctx.stderr ?? process.stderr;
|
|
@@ -4012,10 +4108,12 @@ var require_studyJoin = __commonJS({
|
|
|
4012
4108
|
`);
|
|
4013
4109
|
if (!stdin.isTTY || !stdout.isTTY) {
|
|
4014
4110
|
stderr.write("join needs an interactive terminal (stdin and stdout). Run it directly, not from a script or a pipe.\n");
|
|
4111
|
+
report({ status: "no_terminal", granted: [] });
|
|
4015
4112
|
return 0;
|
|
4016
4113
|
}
|
|
4017
4114
|
if (!ctx.joinCode) {
|
|
4018
4115
|
stderr.write("Usage: join <code>\n");
|
|
4116
|
+
report({ status: "failed", granted: [], message: "No join code given." });
|
|
4019
4117
|
return 1;
|
|
4020
4118
|
}
|
|
4021
4119
|
let start;
|
|
@@ -4024,15 +4122,16 @@ var require_studyJoin = __commonJS({
|
|
|
4024
4122
|
} catch (error) {
|
|
4025
4123
|
stderr.write(`${describeStartError(error)}
|
|
4026
4124
|
`);
|
|
4125
|
+
report({ status: "failed", granted: [], message: describeStartError(error) });
|
|
4027
4126
|
return 1;
|
|
4028
4127
|
}
|
|
4029
4128
|
print("");
|
|
4030
|
-
print(`${start.organisationName}: ${
|
|
4031
|
-
print(
|
|
4129
|
+
print(`${start.organisationName}: ${describeStudyKind2(start.studyKind)}`);
|
|
4130
|
+
print(formatWindow2(start.windowStartUtc, start.windowEndUtc));
|
|
4032
4131
|
print("");
|
|
4033
4132
|
print("Report (30 days) grants:");
|
|
4034
4133
|
for (const grant of start.grants)
|
|
4035
|
-
print(` ${
|
|
4134
|
+
print(` ${describeStudyGrant2(grant)}`);
|
|
4036
4135
|
print("");
|
|
4037
4136
|
print("Study mode needs the Ascenda app. Open the app to join that way instead.");
|
|
4038
4137
|
print("");
|
|
@@ -4043,10 +4142,17 @@ var require_studyJoin = __commonJS({
|
|
|
4043
4142
|
const answer = await askChoice(stdin, stdout);
|
|
4044
4143
|
if (!/^(1|report)$/i.test(answer)) {
|
|
4045
4144
|
print("Not now.");
|
|
4145
|
+
report({ status: "not_now", start, granted: [] });
|
|
4046
4146
|
return 0;
|
|
4047
4147
|
}
|
|
4048
4148
|
print("");
|
|
4049
|
-
|
|
4149
|
+
const confirmUrl = (0, confirmLinks_1.studyJoinConfirmUrl)(ctx.apiBaseUrl, start.deviceCode);
|
|
4150
|
+
if (confirmUrl) {
|
|
4151
|
+
print(`Open this link to confirm: ${confirmUrl}`);
|
|
4152
|
+
print(`Or confirm in the Ascenda app with code ${start.deviceCode}.`);
|
|
4153
|
+
} else {
|
|
4154
|
+
print(`Confirm in the Ascenda app with code ${start.deviceCode}`);
|
|
4155
|
+
}
|
|
4050
4156
|
print(`Waiting for confirmation (expires ${formatLocalTime(start.expiresAt)})...`);
|
|
4051
4157
|
const pollIntervalMs = ctx.pollIntervalMs ?? POLL_INTERVAL_MS;
|
|
4052
4158
|
const deadline = Math.min(Date.parse(start.expiresAt) || Date.now() + POLL_TIMEOUT_MS, Date.now() + POLL_TIMEOUT_MS);
|
|
@@ -4060,6 +4166,7 @@ var require_studyJoin = __commonJS({
|
|
|
4060
4166
|
continue;
|
|
4061
4167
|
stderr.write(`${describeStartError(error)}
|
|
4062
4168
|
`);
|
|
4169
|
+
report({ status: "failed", start, granted: [], message: describeStartError(error) });
|
|
4063
4170
|
return 1;
|
|
4064
4171
|
}
|
|
4065
4172
|
if (poll.status === "pending")
|
|
@@ -4069,20 +4176,23 @@ var require_studyJoin = __commonJS({
|
|
|
4069
4176
|
if (granted.length === 0) {
|
|
4070
4177
|
print("");
|
|
4071
4178
|
print("Nothing was granted. Run join again, or check with your organisation.");
|
|
4179
|
+
report({ status: "refused", start, granted: [], message: "Nothing was granted." });
|
|
4072
4180
|
return 1;
|
|
4073
4181
|
}
|
|
4074
4182
|
print("");
|
|
4075
4183
|
print("Joined. Granted:");
|
|
4076
4184
|
for (const grant of granted)
|
|
4077
|
-
print(` ${
|
|
4185
|
+
print(` ${describeStudyGrant2(grant)}`);
|
|
4078
4186
|
print("");
|
|
4079
4187
|
print("Each of these can be turned off separately, in the app's consent settings.");
|
|
4080
4188
|
print("The organisation sees group counts, never who joined.");
|
|
4189
|
+
report({ status: "joined", start, granted });
|
|
4081
4190
|
return 0;
|
|
4082
4191
|
}
|
|
4083
4192
|
if (poll.status === "expired") {
|
|
4084
4193
|
print("");
|
|
4085
4194
|
print("This code expired before it was confirmed. Run join again for a fresh code.");
|
|
4195
|
+
report({ status: "expired", start, granted: [] });
|
|
4086
4196
|
return 1;
|
|
4087
4197
|
}
|
|
4088
4198
|
if (poll.refusedReason === "grant_failed") {
|
|
@@ -4093,19 +4203,22 @@ var require_studyJoin = __commonJS({
|
|
|
4093
4203
|
print("");
|
|
4094
4204
|
print("Granted before the failure:");
|
|
4095
4205
|
for (const grant of granted)
|
|
4096
|
-
print(` ${
|
|
4206
|
+
print(` ${describeStudyGrant2(grant)}`);
|
|
4097
4207
|
print("");
|
|
4098
4208
|
print("Each of these can be turned off separately, in the app's consent settings.");
|
|
4099
4209
|
}
|
|
4100
4210
|
print("Run join again, or check with your organisation.");
|
|
4211
|
+
report({ status: "refused", start, granted, refusedReason: poll.refusedReason, message: describeRefusal(poll.refusedReason) });
|
|
4101
4212
|
return 1;
|
|
4102
4213
|
}
|
|
4103
4214
|
print("");
|
|
4104
4215
|
print(describeRefusal(poll.refusedReason));
|
|
4216
|
+
report({ status: "refused", start, granted: [], refusedReason: poll.refusedReason, message: describeRefusal(poll.refusedReason) });
|
|
4105
4217
|
return 1;
|
|
4106
4218
|
}
|
|
4107
4219
|
print("");
|
|
4108
4220
|
print("Timed out waiting for confirmation. Run join again for a fresh code.");
|
|
4221
|
+
report({ status: "expired", start, granted: [] });
|
|
4109
4222
|
return 1;
|
|
4110
4223
|
}
|
|
4111
4224
|
function isRetryablePollError(error) {
|
|
@@ -4115,7 +4228,7 @@ var require_studyJoin = __commonJS({
|
|
|
4115
4228
|
}
|
|
4116
4229
|
function askChoice(stdin, stdout) {
|
|
4117
4230
|
return new Promise((resolve3) => {
|
|
4118
|
-
const rl =
|
|
4231
|
+
const rl = readline2.createInterface({ input: stdin, output: stdout });
|
|
4119
4232
|
let settled = false;
|
|
4120
4233
|
const finish = (value) => {
|
|
4121
4234
|
if (settled)
|
|
@@ -4134,7 +4247,7 @@ var require_studyJoin = __commonJS({
|
|
|
4134
4247
|
return iso;
|
|
4135
4248
|
return new Intl.DateTimeFormat(void 0, { day: "numeric", month: "short", hour: "numeric", minute: "2-digit" }).format(date);
|
|
4136
4249
|
}
|
|
4137
|
-
function
|
|
4250
|
+
function formatWindow2(startUtc, endUtc) {
|
|
4138
4251
|
const start = new Date(startUtc);
|
|
4139
4252
|
const end = new Date(endUtc);
|
|
4140
4253
|
const sameYear = start.getUTCFullYear() === end.getUTCFullYear();
|
|
@@ -4148,14 +4261,14 @@ var require_studyJoin = __commonJS({
|
|
|
4148
4261
|
501: "AI assistant data processing consent",
|
|
4149
4262
|
507: "Import of the AI-work history already on your machine"
|
|
4150
4263
|
};
|
|
4151
|
-
function
|
|
4264
|
+
function describeStudyGrant2(grant) {
|
|
4152
4265
|
return GRANT_SENTENCES[grant.code] ?? humanise(grant.name);
|
|
4153
4266
|
}
|
|
4154
4267
|
var STUDY_KIND_SENTENCES = {
|
|
4155
4268
|
Report30: "a 30-day report",
|
|
4156
4269
|
Study90: "a 90-day study"
|
|
4157
4270
|
};
|
|
4158
|
-
function
|
|
4271
|
+
function describeStudyKind2(studyKind) {
|
|
4159
4272
|
return STUDY_KIND_SENTENCES[studyKind] ?? humanise(studyKind);
|
|
4160
4273
|
}
|
|
4161
4274
|
function humanise(name) {
|
|
@@ -4168,7 +4281,7 @@ var require_studyJoin = __commonJS({
|
|
|
4168
4281
|
// table is ever consulted — present so the type stays exhaustive, and as
|
|
4169
4282
|
// a plain fallback should something call this function with it directly.
|
|
4170
4283
|
grant_failed: "Join failed partway through. Some grants may not have gone through.",
|
|
4171
|
-
declined: "You declined
|
|
4284
|
+
declined: "You declined the join. Nothing was granted.",
|
|
4172
4285
|
not_enrolled: "That study couldn't enrol you, so nothing was granted."
|
|
4173
4286
|
};
|
|
4174
4287
|
function describeRefusal(refusedReason) {
|
|
@@ -4196,6 +4309,182 @@ var require_studyJoin = __commonJS({
|
|
|
4196
4309
|
}
|
|
4197
4310
|
});
|
|
4198
4311
|
|
|
4312
|
+
// ../packages/tool-kit/out/pairingStudyJoin.js
|
|
4313
|
+
var require_pairingStudyJoin = __commonJS({
|
|
4314
|
+
"../packages/tool-kit/out/pairingStudyJoin.js"(exports) {
|
|
4315
|
+
"use strict";
|
|
4316
|
+
var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
4317
|
+
if (k2 === void 0) k2 = k;
|
|
4318
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
4319
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
4320
|
+
desc = { enumerable: true, get: function() {
|
|
4321
|
+
return m[k];
|
|
4322
|
+
} };
|
|
4323
|
+
}
|
|
4324
|
+
Object.defineProperty(o, k2, desc);
|
|
4325
|
+
} : function(o, m, k, k2) {
|
|
4326
|
+
if (k2 === void 0) k2 = k;
|
|
4327
|
+
o[k2] = m[k];
|
|
4328
|
+
});
|
|
4329
|
+
var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
|
|
4330
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
4331
|
+
} : function(o, v) {
|
|
4332
|
+
o["default"] = v;
|
|
4333
|
+
});
|
|
4334
|
+
var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
|
|
4335
|
+
var ownKeys = function(o) {
|
|
4336
|
+
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
4337
|
+
var ar = [];
|
|
4338
|
+
for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
|
|
4339
|
+
return ar;
|
|
4340
|
+
};
|
|
4341
|
+
return ownKeys(o);
|
|
4342
|
+
};
|
|
4343
|
+
return function(mod) {
|
|
4344
|
+
if (mod && mod.__esModule) return mod;
|
|
4345
|
+
var result = {};
|
|
4346
|
+
if (mod != null) {
|
|
4347
|
+
for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
4348
|
+
}
|
|
4349
|
+
__setModuleDefault(result, mod);
|
|
4350
|
+
return result;
|
|
4351
|
+
};
|
|
4352
|
+
}();
|
|
4353
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4354
|
+
exports.PAIR_JOIN_OUTCOME_FILE_ENV = exports.PAIR_ORG_JOIN_CODE_ENV = void 0;
|
|
4355
|
+
exports.createPairingAttempt = createPairingAttempt;
|
|
4356
|
+
exports.pairingAttemptLines = pairingAttemptLines;
|
|
4357
|
+
exports.settleStudyJoin = settleStudyJoin;
|
|
4358
|
+
exports.writePairingJoinOutcome = writePairingJoinOutcome;
|
|
4359
|
+
exports.pairingJoinOutcome = pairingJoinOutcome;
|
|
4360
|
+
var fs15 = __importStar(__require("node:fs"));
|
|
4361
|
+
var confirmLinks_1 = require_confirmLinks();
|
|
4362
|
+
var studyJoin_1 = require_studyJoin();
|
|
4363
|
+
var http_1 = require_http();
|
|
4364
|
+
exports.PAIR_ORG_JOIN_CODE_ENV = "ASCENDA_PAIR_ORG_JOIN_CODE";
|
|
4365
|
+
exports.PAIR_JOIN_OUTCOME_FILE_ENV = "ASCENDA_PAIR_JOIN_OUTCOME_FILE";
|
|
4366
|
+
var CREATE_REFUSALS = {
|
|
4367
|
+
join_code_not_found: "That code is not a study anyone can join. Check it and try again.",
|
|
4368
|
+
no_live_study: "There's nothing open to join with that code right now.",
|
|
4369
|
+
unknown_mode: "This tool only offers Report mode from the command line."
|
|
4370
|
+
};
|
|
4371
|
+
var JOIN_SETTLE_MS = 6e4;
|
|
4372
|
+
async function createPairingAttempt(apiBaseUrl, toolInstallationId, toolType, displayName, env = process.env) {
|
|
4373
|
+
const orgJoinCode = env[exports.PAIR_ORG_JOIN_CODE_ENV]?.trim();
|
|
4374
|
+
if (!orgJoinCode)
|
|
4375
|
+
return { session: await (0, http_1.createPairingSession)(apiBaseUrl, toolInstallationId, toolType, displayName), carriesJoin: false };
|
|
4376
|
+
let refusal;
|
|
4377
|
+
try {
|
|
4378
|
+
const session = await (0, http_1.createPairingSession)(apiBaseUrl, toolInstallationId, toolType, displayName, orgJoinCode);
|
|
4379
|
+
return { session, carriesJoin: session.studyJoin !== void 0 };
|
|
4380
|
+
} catch (error) {
|
|
4381
|
+
if (!(error instanceof http_1.AscendaApiError) || error.status >= 500)
|
|
4382
|
+
throw error;
|
|
4383
|
+
refusal = error.errorCode ? CREATE_REFUSALS[error.errorCode] : void 0;
|
|
4384
|
+
}
|
|
4385
|
+
return { session: await (0, http_1.createPairingSession)(apiBaseUrl, toolInstallationId, toolType, displayName), carriesJoin: false, refusal };
|
|
4386
|
+
}
|
|
4387
|
+
function pairingAttemptLines(attempt) {
|
|
4388
|
+
const { session } = attempt;
|
|
4389
|
+
const join14 = attempt.carriesJoin ? session.studyJoin : void 0;
|
|
4390
|
+
if (!join14)
|
|
4391
|
+
return (0, confirmLinks_1.pairingConfirmLines)(session.qrUrl, session.code);
|
|
4392
|
+
return [
|
|
4393
|
+
`This also joins ${join14.organisationName} (${(0, studyJoin_1.formatWindow)(join14.windowStartUtc, join14.windowEndUtc)}). The page shows what you'd share before you confirm.`,
|
|
4394
|
+
`Open this link to confirm: ${session.qrUrl}`
|
|
4395
|
+
];
|
|
4396
|
+
}
|
|
4397
|
+
async function settleStudyJoin(apiBaseUrl, pairingSessionId, last, wait = 1e3) {
|
|
4398
|
+
let current = last;
|
|
4399
|
+
const deadline = Date.now() + JOIN_SETTLE_MS;
|
|
4400
|
+
while (current && current.status === "pending" && Date.now() < deadline) {
|
|
4401
|
+
await new Promise((resolve3) => setTimeout(resolve3, wait));
|
|
4402
|
+
let status;
|
|
4403
|
+
try {
|
|
4404
|
+
status = await (0, http_1.getPairingStatus)(apiBaseUrl, pairingSessionId);
|
|
4405
|
+
} catch {
|
|
4406
|
+
continue;
|
|
4407
|
+
}
|
|
4408
|
+
current = status.studyJoin ?? current;
|
|
4409
|
+
}
|
|
4410
|
+
return current;
|
|
4411
|
+
}
|
|
4412
|
+
function writePairingJoinOutcome(outcome, env = process.env) {
|
|
4413
|
+
const file = env[exports.PAIR_JOIN_OUTCOME_FILE_ENV]?.trim();
|
|
4414
|
+
if (!file)
|
|
4415
|
+
return;
|
|
4416
|
+
try {
|
|
4417
|
+
fs15.writeFileSync(file, `${JSON.stringify(outcome)}
|
|
4418
|
+
`, { mode: 384 });
|
|
4419
|
+
} catch {
|
|
4420
|
+
}
|
|
4421
|
+
}
|
|
4422
|
+
function pairingJoinOutcome(attempt, pairing, studyJoin) {
|
|
4423
|
+
if (!attempt)
|
|
4424
|
+
return { join: "none", pairing };
|
|
4425
|
+
if (attempt.refusal)
|
|
4426
|
+
return { join: "refused", pairing, message: attempt.refusal };
|
|
4427
|
+
return { join: attempt.carriesJoin ? "carried" : "not_carried", pairing, studyJoin };
|
|
4428
|
+
}
|
|
4429
|
+
}
|
|
4430
|
+
});
|
|
4431
|
+
|
|
4432
|
+
// ../packages/tool-kit/out/hookSet.js
|
|
4433
|
+
var require_hookSet = __commonJS({
|
|
4434
|
+
"../packages/tool-kit/out/hookSet.js"(exports) {
|
|
4435
|
+
"use strict";
|
|
4436
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4437
|
+
exports.UNVERSIONED_HOOK_SET = exports.HOOK_SET_FLAG = void 0;
|
|
4438
|
+
exports.hookSetArgument = hookSetArgument;
|
|
4439
|
+
exports.readHookSet = readHookSet;
|
|
4440
|
+
exports.isHookSet = isHookSet;
|
|
4441
|
+
exports.readViaPlugin = readViaPlugin;
|
|
4442
|
+
exports.hookSetOfCommand = hookSetOfCommand;
|
|
4443
|
+
exports.hookSetChanges = hookSetChanges;
|
|
4444
|
+
exports.describeHookSetChanges = describeHookSetChanges;
|
|
4445
|
+
exports.HOOK_SET_FLAG = "--hook-set";
|
|
4446
|
+
exports.UNVERSIONED_HOOK_SET = 1;
|
|
4447
|
+
function hookSetArgument(hookSet) {
|
|
4448
|
+
return hookSet === void 0 ? "" : ` ${exports.HOOK_SET_FLAG} ${hookSet}`;
|
|
4449
|
+
}
|
|
4450
|
+
function readHookSet(argv) {
|
|
4451
|
+
const index = argv.indexOf(exports.HOOK_SET_FLAG);
|
|
4452
|
+
if (index === -1)
|
|
4453
|
+
return void 0;
|
|
4454
|
+
const raw = argv[index + 1];
|
|
4455
|
+
if (raw === void 0 || !/^[1-9]\d*$/.test(raw))
|
|
4456
|
+
return void 0;
|
|
4457
|
+
const value = Number(raw);
|
|
4458
|
+
return isHookSet(value) ? value : void 0;
|
|
4459
|
+
}
|
|
4460
|
+
function isHookSet(value) {
|
|
4461
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 1;
|
|
4462
|
+
}
|
|
4463
|
+
function readViaPlugin(env) {
|
|
4464
|
+
return env.CLAUDE_PLUGIN_ROOT ? true : void 0;
|
|
4465
|
+
}
|
|
4466
|
+
function hookSetOfCommand(command) {
|
|
4467
|
+
const match = command.match(/--hook-set\s+(\d+)/);
|
|
4468
|
+
return match ? Number(match[1]) : exports.UNVERSIONED_HOOK_SET;
|
|
4469
|
+
}
|
|
4470
|
+
function hookSetChanges(before, events) {
|
|
4471
|
+
const added = events.filter((event) => !before.has(event));
|
|
4472
|
+
const sets = [...before.values()];
|
|
4473
|
+
return sets.length ? { added, previousSet: Math.min(...sets) } : { added };
|
|
4474
|
+
}
|
|
4475
|
+
function describeHookSetChanges(changes, hookSet) {
|
|
4476
|
+
if (changes.previousSet === void 0)
|
|
4477
|
+
return void 0;
|
|
4478
|
+
const parts = [];
|
|
4479
|
+
if (changes.added.length)
|
|
4480
|
+
parts.push(`added ${changes.added.join(", ")}`);
|
|
4481
|
+
if (changes.previousSet < hookSet)
|
|
4482
|
+
parts.push(`hook set ${changes.previousSet} \u2192 ${hookSet}`);
|
|
4483
|
+
return parts.length ? `upgraded: ${parts.join("; ")}` : void 0;
|
|
4484
|
+
}
|
|
4485
|
+
}
|
|
4486
|
+
});
|
|
4487
|
+
|
|
4199
4488
|
// ../packages/tool-kit/out/initiatives.js
|
|
4200
4489
|
var require_initiatives = __commonJS({
|
|
4201
4490
|
"../packages/tool-kit/out/initiatives.js"(exports) {
|
|
@@ -4418,20 +4707,20 @@ var require_hookRunner = __commonJS({
|
|
|
4418
4707
|
exports.installHookRunner = installHookRunner;
|
|
4419
4708
|
exports.removeHookRunner = removeHookRunner;
|
|
4420
4709
|
exports.hookRunnerCommand = hookRunnerCommand;
|
|
4421
|
-
exports.writeAtomically =
|
|
4710
|
+
exports.writeAtomically = writeAtomically2;
|
|
4422
4711
|
exports.lastHookPath = lastHookPath;
|
|
4423
4712
|
exports.stampLastHook = stampLastHook;
|
|
4424
4713
|
exports.readLastHook = readLastHook;
|
|
4425
4714
|
exports.describeAge = describeAge;
|
|
4426
4715
|
exports.resolveHookNode = resolveHookNode;
|
|
4427
|
-
exports.tidyHomePath =
|
|
4716
|
+
exports.tidyHomePath = tidyHomePath2;
|
|
4428
4717
|
var child_process_1 = __require("child_process");
|
|
4429
|
-
var
|
|
4430
|
-
var
|
|
4718
|
+
var fs15 = __importStar(__require("fs"));
|
|
4719
|
+
var path15 = __importStar(__require("path"));
|
|
4431
4720
|
var collectorVersion_1 = require_collectorVersion();
|
|
4432
4721
|
var tokenStore_1 = require_tokenStore();
|
|
4433
4722
|
function hookRunnerPaths(binaryName) {
|
|
4434
|
-
const launcher =
|
|
4723
|
+
const launcher = path15.join((0, tokenStore_1.ascendaHome)(), "bin", binaryName);
|
|
4435
4724
|
return { launcher, bundle: `${launcher}.mjs`, record: `${launcher}.node`, noNode: `${launcher}.no-node`, version: `${launcher}.version` };
|
|
4436
4725
|
}
|
|
4437
4726
|
var LAUNCHER_MANAGEMENT_COMMANDS = ["setup", "install", "status", "uninstall", "doctor", "pair", "join", "object", "-h", "--help"];
|
|
@@ -4543,7 +4832,7 @@ var require_hookRunner = __commonJS({
|
|
|
4543
4832
|
}
|
|
4544
4833
|
function readInstalledVersion(file) {
|
|
4545
4834
|
try {
|
|
4546
|
-
return
|
|
4835
|
+
return fs15.readFileSync(file, "utf8").trim() || void 0;
|
|
4547
4836
|
} catch {
|
|
4548
4837
|
return void 0;
|
|
4549
4838
|
}
|
|
@@ -4552,41 +4841,41 @@ var require_hookRunner = __commonJS({
|
|
|
4552
4841
|
const paths = hookRunnerPaths(options.binaryName);
|
|
4553
4842
|
if (options.dryRun)
|
|
4554
4843
|
return paths.launcher;
|
|
4555
|
-
const source =
|
|
4844
|
+
const source = path15.resolve(options.source ?? process.argv[1]);
|
|
4556
4845
|
const incoming = options.version ?? collectorVersion_1.COLLECTOR_VERSION;
|
|
4557
4846
|
const installed = readInstalledVersion(paths.version);
|
|
4558
4847
|
const installedFile = process.platform === "win32" ? paths.launcher : paths.bundle;
|
|
4559
|
-
if (installed &&
|
|
4848
|
+
if (installed && fs15.existsSync(installedFile) && isDowngrade(installed, incoming)) {
|
|
4560
4849
|
options.onKeptNewer?.(installed, incoming);
|
|
4561
|
-
if (process.platform !== "win32" && !
|
|
4562
|
-
|
|
4850
|
+
if (process.platform !== "win32" && !fs15.existsSync(paths.launcher))
|
|
4851
|
+
writeAtomically2(paths.launcher, hookLauncherScript(options), 493);
|
|
4563
4852
|
return paths.launcher;
|
|
4564
4853
|
}
|
|
4565
|
-
|
|
4854
|
+
fs15.mkdirSync(path15.dirname(paths.launcher), { recursive: true });
|
|
4566
4855
|
if (process.platform === "win32") {
|
|
4567
|
-
if (source !==
|
|
4568
|
-
|
|
4569
|
-
|
|
4856
|
+
if (source !== path15.resolve(paths.launcher))
|
|
4857
|
+
fs15.copyFileSync(source, paths.launcher);
|
|
4858
|
+
writeAtomically2(paths.version, `${incoming}
|
|
4570
4859
|
`, 420);
|
|
4571
4860
|
return paths.launcher;
|
|
4572
4861
|
}
|
|
4573
|
-
if (source !==
|
|
4574
|
-
|
|
4575
|
-
|
|
4576
|
-
|
|
4862
|
+
if (source !== path15.resolve(paths.bundle))
|
|
4863
|
+
writeAtomically2(paths.bundle, fs15.readFileSync(source), 493);
|
|
4864
|
+
writeAtomically2(paths.launcher, hookLauncherScript(options), 493);
|
|
4865
|
+
writeAtomically2(paths.record, `${process.execPath}
|
|
4577
4866
|
`, 420);
|
|
4578
|
-
if (source !==
|
|
4579
|
-
|
|
4867
|
+
if (source !== path15.resolve(paths.bundle))
|
|
4868
|
+
writeAtomically2(paths.version, `${incoming}
|
|
4580
4869
|
`, 420);
|
|
4581
|
-
|
|
4870
|
+
fs15.rmSync(paths.noNode, { force: true });
|
|
4582
4871
|
return paths.launcher;
|
|
4583
4872
|
}
|
|
4584
4873
|
function removeHookRunner(binaryName) {
|
|
4585
4874
|
const removed = [];
|
|
4586
4875
|
for (const file of Object.values(hookRunnerPaths(binaryName))) {
|
|
4587
|
-
if (!
|
|
4876
|
+
if (!fs15.existsSync(file))
|
|
4588
4877
|
continue;
|
|
4589
|
-
|
|
4878
|
+
fs15.rmSync(file, { force: true });
|
|
4590
4879
|
removed.push(file);
|
|
4591
4880
|
}
|
|
4592
4881
|
return removed;
|
|
@@ -4594,30 +4883,30 @@ var require_hookRunner = __commonJS({
|
|
|
4594
4883
|
function hookRunnerCommand(launcher, platform = process.platform) {
|
|
4595
4884
|
return platform === "win32" ? `"${process.execPath}" "${launcher}"` : `"${launcher}"`;
|
|
4596
4885
|
}
|
|
4597
|
-
function
|
|
4886
|
+
function writeAtomically2(target, contents, mode) {
|
|
4598
4887
|
const tmp = `${target}.${process.pid}.tmp`;
|
|
4599
|
-
|
|
4600
|
-
|
|
4601
|
-
|
|
4888
|
+
fs15.writeFileSync(tmp, contents, { mode });
|
|
4889
|
+
fs15.chmodSync(tmp, mode);
|
|
4890
|
+
fs15.renameSync(tmp, target);
|
|
4602
4891
|
}
|
|
4603
|
-
var stateDir = () => process.env.ASCENDA_STATE_DIR ??
|
|
4892
|
+
var stateDir = () => process.env.ASCENDA_STATE_DIR ?? path15.join((0, tokenStore_1.ascendaHome)(), "state");
|
|
4604
4893
|
function lastHookPath(tool) {
|
|
4605
|
-
return
|
|
4894
|
+
return path15.join(stateDir(), `${tool}-last-hook.json`);
|
|
4606
4895
|
}
|
|
4607
4896
|
function stampLastHook(tool, event, now = /* @__PURE__ */ new Date()) {
|
|
4608
4897
|
try {
|
|
4609
|
-
|
|
4898
|
+
fs15.mkdirSync(stateDir(), { recursive: true });
|
|
4610
4899
|
const file = lastHookPath(tool);
|
|
4611
4900
|
const tmp = `${file}.${process.pid}.tmp`;
|
|
4612
|
-
|
|
4901
|
+
fs15.writeFileSync(tmp, `${JSON.stringify({ event, at: now.toISOString() })}
|
|
4613
4902
|
`, { mode: 384 });
|
|
4614
|
-
|
|
4903
|
+
fs15.renameSync(tmp, file);
|
|
4615
4904
|
} catch {
|
|
4616
4905
|
}
|
|
4617
4906
|
}
|
|
4618
4907
|
function readLastHook(tool) {
|
|
4619
4908
|
try {
|
|
4620
|
-
const parsed = JSON.parse(
|
|
4909
|
+
const parsed = JSON.parse(fs15.readFileSync(lastHookPath(tool), "utf8"));
|
|
4621
4910
|
if (typeof parsed.event !== "string" || typeof parsed.at !== "string")
|
|
4622
4911
|
return void 0;
|
|
4623
4912
|
return { event: parsed.event, at: parsed.at };
|
|
@@ -4640,7 +4929,7 @@ var require_hookRunner = __commonJS({
|
|
|
4640
4929
|
return `${Math.round(hours / 24)} days ago`;
|
|
4641
4930
|
}
|
|
4642
4931
|
function resolveHookNode(launcher) {
|
|
4643
|
-
if (!
|
|
4932
|
+
if (!fs15.existsSync(launcher))
|
|
4644
4933
|
return { problem: "the hook launcher is not installed" };
|
|
4645
4934
|
const probe = (0, child_process_1.spawnSync)("/bin/sh", [launcher], {
|
|
4646
4935
|
encoding: "utf8",
|
|
@@ -4656,7 +4945,7 @@ var require_hookRunner = __commonJS({
|
|
|
4656
4945
|
return { node, how, problem: `${node} did not run` };
|
|
4657
4946
|
return { node, how, version: version.stdout.trim() };
|
|
4658
4947
|
}
|
|
4659
|
-
function
|
|
4948
|
+
function tidyHomePath2(file, home = process.env.HOME ?? "") {
|
|
4660
4949
|
return home && file.startsWith(`${home}/`) ? `~${file.slice(home.length)}` : file;
|
|
4661
4950
|
}
|
|
4662
4951
|
}
|
|
@@ -4705,19 +4994,19 @@ var require_settingsFile = __commonJS({
|
|
|
4705
4994
|
}();
|
|
4706
4995
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4707
4996
|
exports.replaceSettingsFile = replaceSettingsFile;
|
|
4708
|
-
var
|
|
4709
|
-
var
|
|
4997
|
+
var fs15 = __importStar(__require("fs"));
|
|
4998
|
+
var path15 = __importStar(__require("path"));
|
|
4710
4999
|
var hookRunner_1 = require_hookRunner();
|
|
4711
5000
|
function replaceSettingsFile(settingsFile, contents) {
|
|
4712
|
-
const exists =
|
|
4713
|
-
const target = exists ?
|
|
5001
|
+
const exists = fs15.existsSync(settingsFile);
|
|
5002
|
+
const target = exists ? fs15.realpathSync(settingsFile) : settingsFile;
|
|
4714
5003
|
if (exists) {
|
|
4715
5004
|
const backup = `${settingsFile}.ascenda-backup`;
|
|
4716
|
-
if (!
|
|
4717
|
-
|
|
5005
|
+
if (!fs15.existsSync(backup))
|
|
5006
|
+
fs15.copyFileSync(target, backup);
|
|
4718
5007
|
}
|
|
4719
|
-
|
|
4720
|
-
const mode = exists ?
|
|
5008
|
+
fs15.mkdirSync(path15.dirname(target), { recursive: true });
|
|
5009
|
+
const mode = exists ? fs15.statSync(target).mode & 511 : 420;
|
|
4721
5010
|
(0, hookRunner_1.writeAtomically)(target, contents, mode);
|
|
4722
5011
|
}
|
|
4723
5012
|
}
|
|
@@ -4822,22 +5111,22 @@ var require_saverHandoff = __commonJS({
|
|
|
4822
5111
|
exports.heldForSaver = heldForSaver;
|
|
4823
5112
|
exports.readSaverStatuses = readSaverStatuses;
|
|
4824
5113
|
exports.probeSocket = probeSocket;
|
|
4825
|
-
var
|
|
5114
|
+
var fs15 = __importStar(__require("fs"));
|
|
4826
5115
|
var net = __importStar(__require("net"));
|
|
4827
|
-
var
|
|
4828
|
-
var
|
|
5116
|
+
var os6 = __importStar(__require("os"));
|
|
5117
|
+
var path15 = __importStar(__require("path"));
|
|
4829
5118
|
var SAVER_HOST_BUNDLE_ID = "com.apple.ScreenSaver.Engine.legacyScreenSaver";
|
|
4830
5119
|
function saverContainerDir() {
|
|
4831
|
-
return process.env.ASCENDA_SAVER_CONTAINER ??
|
|
5120
|
+
return process.env.ASCENDA_SAVER_CONTAINER ?? path15.join(os6.homedir(), "Library", "Containers", SAVER_HOST_BUNDLE_ID, "Data");
|
|
4832
5121
|
}
|
|
4833
5122
|
function saverSupportDir() {
|
|
4834
|
-
return
|
|
5123
|
+
return path15.join(saverContainerDir(), "Library", "Application Support", "AscendaWaterlineSaver");
|
|
4835
5124
|
}
|
|
4836
5125
|
function saverReplayPath() {
|
|
4837
|
-
return
|
|
5126
|
+
return path15.join(saverContainerDir(), "l.replay.json");
|
|
4838
5127
|
}
|
|
4839
5128
|
function saverStatusDir() {
|
|
4840
|
-
return
|
|
5129
|
+
return path15.join(saverSupportDir(), "status");
|
|
4841
5130
|
}
|
|
4842
5131
|
exports.SAVER_REPLAY_WINDOW_MS = 30 * 60 * 1e3;
|
|
4843
5132
|
var SAVER_REPLAY_MAX = 32;
|
|
@@ -4846,7 +5135,7 @@ var require_saverHandoff = __commonJS({
|
|
|
4846
5135
|
try {
|
|
4847
5136
|
if (process.env.ASCENDA_LIVE_BUS_SOCKET && !process.env.ASCENDA_SAVER_CONTAINER)
|
|
4848
5137
|
return;
|
|
4849
|
-
if (!
|
|
5138
|
+
if (!fs15.existsSync(saverSupportDir()))
|
|
4850
5139
|
return;
|
|
4851
5140
|
const wire = signal;
|
|
4852
5141
|
const tool = wire.tool;
|
|
@@ -4860,15 +5149,15 @@ var require_saverHandoff = __commonJS({
|
|
|
4860
5149
|
kept.sort((a, b) => a.at - b.at);
|
|
4861
5150
|
const body = JSON.stringify({ schema: exports.SAVER_REPLAY_SCHEMA, signals: kept.slice(-SAVER_REPLAY_MAX) });
|
|
4862
5151
|
const tmp = `${file}.${process.pid}.tmp`;
|
|
4863
|
-
|
|
5152
|
+
fs15.writeFileSync(tmp, `${body}
|
|
4864
5153
|
`, { mode: 384 });
|
|
4865
|
-
|
|
5154
|
+
fs15.renameSync(tmp, file);
|
|
4866
5155
|
} catch {
|
|
4867
5156
|
}
|
|
4868
5157
|
}
|
|
4869
5158
|
function readHeld(file) {
|
|
4870
5159
|
try {
|
|
4871
|
-
const parsed = JSON.parse(
|
|
5160
|
+
const parsed = JSON.parse(fs15.readFileSync(file, "utf8"));
|
|
4872
5161
|
if (parsed.schema !== exports.SAVER_REPLAY_SCHEMA || !Array.isArray(parsed.signals))
|
|
4873
5162
|
return [];
|
|
4874
5163
|
return parsed.signals.filter((held) => typeof held === "object" && held !== null && typeof held.tool === "string" && typeof held.session === "string" && typeof held.event === "string" && typeof held.at === "number");
|
|
@@ -4885,14 +5174,14 @@ var require_saverHandoff = __commonJS({
|
|
|
4885
5174
|
function readSaverStatuses(now = Date.now()) {
|
|
4886
5175
|
let names;
|
|
4887
5176
|
try {
|
|
4888
|
-
names =
|
|
5177
|
+
names = fs15.readdirSync(saverStatusDir()).filter((name) => name.endsWith(".json"));
|
|
4889
5178
|
} catch {
|
|
4890
5179
|
return [];
|
|
4891
5180
|
}
|
|
4892
5181
|
const readings = [];
|
|
4893
5182
|
for (const name of names) {
|
|
4894
5183
|
try {
|
|
4895
|
-
const status = JSON.parse(
|
|
5184
|
+
const status = JSON.parse(fs15.readFileSync(path15.join(saverStatusDir(), name), "utf8"));
|
|
4896
5185
|
if (typeof status.pid !== "number" || typeof status.updatedAt !== "string")
|
|
4897
5186
|
continue;
|
|
4898
5187
|
readings.push({ ...status, alive: processAlive(status.pid), ageMs: now - Date.parse(status.updatedAt) });
|
|
@@ -4912,7 +5201,7 @@ var require_saverHandoff = __commonJS({
|
|
|
4912
5201
|
function probeSocket(socketPath, timeoutMs = 300) {
|
|
4913
5202
|
return new Promise((resolve3) => {
|
|
4914
5203
|
try {
|
|
4915
|
-
if (!
|
|
5204
|
+
if (!fs15.statSync(socketPath).isSocket()) {
|
|
4916
5205
|
resolve3("absent");
|
|
4917
5206
|
return;
|
|
4918
5207
|
}
|
|
@@ -4987,10 +5276,10 @@ var require_liveBus = __commonJS({
|
|
|
4987
5276
|
exports.bucketPromptSize = bucketPromptSize;
|
|
4988
5277
|
exports.emitLiveSignal = emitLiveSignal;
|
|
4989
5278
|
exports.deliverLine = deliverLine;
|
|
4990
|
-
var
|
|
5279
|
+
var fs15 = __importStar(__require("fs"));
|
|
4991
5280
|
var net = __importStar(__require("net"));
|
|
4992
|
-
var
|
|
4993
|
-
var
|
|
5281
|
+
var os6 = __importStar(__require("os"));
|
|
5282
|
+
var path15 = __importStar(__require("path"));
|
|
4994
5283
|
var hookSet_1 = require_hookSet();
|
|
4995
5284
|
var saverHandoff_1 = require_saverHandoff();
|
|
4996
5285
|
var WRITE_TIMEOUT_MS = 50;
|
|
@@ -5001,11 +5290,11 @@ var require_liveBus = __commonJS({
|
|
|
5001
5290
|
const override = process.env.ASCENDA_LIVE_BUS_SOCKET;
|
|
5002
5291
|
if (override)
|
|
5003
5292
|
return [override];
|
|
5004
|
-
const home =
|
|
5293
|
+
const home = os6.homedir();
|
|
5005
5294
|
return [
|
|
5006
|
-
|
|
5007
|
-
|
|
5008
|
-
|
|
5295
|
+
path15.join(home, ".ascenda", "live.sock"),
|
|
5296
|
+
path15.join(home, "Library", "Containers", APP_BUNDLE_ID2, "Data", ".ascenda", "live.sock"),
|
|
5297
|
+
path15.join(home, "Library", "Containers", exports.SAVER_HOST_BUNDLE_ID, "Data", "l.sock")
|
|
5009
5298
|
];
|
|
5010
5299
|
}
|
|
5011
5300
|
function existingSocketCandidates() {
|
|
@@ -5014,7 +5303,7 @@ var require_liveBus = __commonJS({
|
|
|
5014
5303
|
return candidates;
|
|
5015
5304
|
return candidates.filter((candidate) => {
|
|
5016
5305
|
try {
|
|
5017
|
-
return
|
|
5306
|
+
return fs15.statSync(candidate).isSocket();
|
|
5018
5307
|
} catch {
|
|
5019
5308
|
return false;
|
|
5020
5309
|
}
|
|
@@ -5127,9 +5416,9 @@ var require_terminalStyle = __commonJS({
|
|
|
5127
5416
|
"../packages/tool-kit/out/terminalStyle.js"(exports) {
|
|
5128
5417
|
"use strict";
|
|
5129
5418
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
5130
|
-
exports.colourEnabled =
|
|
5131
|
-
exports.terminalStyle =
|
|
5132
|
-
function
|
|
5419
|
+
exports.colourEnabled = colourEnabled2;
|
|
5420
|
+
exports.terminalStyle = terminalStyle2;
|
|
5421
|
+
function colourEnabled2(stream = process.stdout, env = process.env) {
|
|
5133
5422
|
if (env.NO_COLOR !== void 0 && env.NO_COLOR !== "")
|
|
5134
5423
|
return false;
|
|
5135
5424
|
if (env.FORCE_COLOR !== void 0)
|
|
@@ -5138,7 +5427,7 @@ var require_terminalStyle = __commonJS({
|
|
|
5138
5427
|
return false;
|
|
5139
5428
|
return Boolean(stream.isTTY);
|
|
5140
5429
|
}
|
|
5141
|
-
function
|
|
5430
|
+
function terminalStyle2(enabled = colourEnabled2()) {
|
|
5142
5431
|
const wrap = (open2, close) => (text) => enabled ? `\x1B[${open2}m${text}\x1B[${close}m` : text;
|
|
5143
5432
|
const bold = wrap(1, 22);
|
|
5144
5433
|
const dim = wrap(2, 22);
|
|
@@ -5464,13 +5753,13 @@ var require_studyNotices = __commonJS({
|
|
|
5464
5753
|
return `${lines.join("\n")}
|
|
5465
5754
|
`;
|
|
5466
5755
|
}
|
|
5467
|
-
function describeObjectionError(error, purpose, undo,
|
|
5756
|
+
function describeObjectionError(error, purpose, undo, pairCommand2) {
|
|
5468
5757
|
if (error instanceof http_1.AscendaApiError) {
|
|
5469
5758
|
if (error.status === 404 && error.errorCode === "not_noticed") {
|
|
5470
5759
|
return undo ? `Your organisation doesn't count you for ${purpose.title} unless you object, so there's no objection to undo.` : `Your organisation doesn't count you for ${purpose.title} unless you object, so there's nothing to object to.`;
|
|
5471
5760
|
}
|
|
5472
5761
|
if (error.status === 401)
|
|
5473
|
-
return `The server turned this install's request down. If that keeps happening, pair again with \`${
|
|
5762
|
+
return `The server turned this install's request down. If that keeps happening, pair again with \`${pairCommand2}\`.`;
|
|
5474
5763
|
if (error.status === 404)
|
|
5475
5764
|
return "This server doesn't take objections yet. Nothing changed.";
|
|
5476
5765
|
return `Couldn't record that (HTTP ${error.status}). Nothing changed. Run it again to retry.`;
|
|
@@ -5541,14 +5830,15 @@ var require_cliAgentSetup = __commonJS({
|
|
|
5541
5830
|
exports.findStaleHookCommands = findStaleHookCommands;
|
|
5542
5831
|
exports.cliAgentRegistrations = cliAgentRegistrations;
|
|
5543
5832
|
var crypto = __importStar(__require("crypto"));
|
|
5544
|
-
var
|
|
5545
|
-
var
|
|
5546
|
-
var
|
|
5833
|
+
var fs15 = __importStar(__require("fs"));
|
|
5834
|
+
var os6 = __importStar(__require("os"));
|
|
5835
|
+
var path15 = __importStar(__require("path"));
|
|
5547
5836
|
var collectorVersion_1 = require_collectorVersion();
|
|
5548
5837
|
var credentials_1 = require_credentials();
|
|
5549
5838
|
var eventLog_1 = require_eventLog();
|
|
5550
5839
|
var hookAdapter_1 = require_hookAdapter();
|
|
5551
5840
|
var http_1 = require_http();
|
|
5841
|
+
var pairingStudyJoin_1 = require_pairingStudyJoin();
|
|
5552
5842
|
var hookSet_1 = require_hookSet();
|
|
5553
5843
|
var initiatives_1 = require_initiatives();
|
|
5554
5844
|
var settingsFile_1 = require_settingsFile();
|
|
@@ -5568,7 +5858,7 @@ var require_cliAgentSetup = __commonJS({
|
|
|
5568
5858
|
return (0, hookRunner_1.hookRunnerPaths)(binaryName).launcher;
|
|
5569
5859
|
}
|
|
5570
5860
|
function cliAgentSelfCommand(spec) {
|
|
5571
|
-
return process.platform === "win32" ? `npx ${spec.packageName}` : (0, hookRunner_1.tidyHomePath)(cliAgentHookBinPath(spec.binaryName),
|
|
5861
|
+
return process.platform === "win32" ? `npx ${spec.packageName}` : (0, hookRunner_1.tidyHomePath)(cliAgentHookBinPath(spec.binaryName), os6.homedir());
|
|
5572
5862
|
}
|
|
5573
5863
|
function usage(spec) {
|
|
5574
5864
|
return `${spec.binaryName} setup \u2014 wire ${spec.displayName} to Ascenda telemetry
|
|
@@ -5605,7 +5895,7 @@ Options
|
|
|
5605
5895
|
return runCliAgentStudyObjection(argv.slice(1), spec);
|
|
5606
5896
|
let options;
|
|
5607
5897
|
try {
|
|
5608
|
-
options =
|
|
5898
|
+
options = parseArgs2(argv, spec);
|
|
5609
5899
|
} catch (error) {
|
|
5610
5900
|
console.error(error instanceof Error ? error.message : String(error));
|
|
5611
5901
|
return 1;
|
|
@@ -5635,9 +5925,9 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
|
|
|
5635
5925
|
const binary = installBinary(spec, options.dryRun);
|
|
5636
5926
|
const node = options.dryRun || process.platform === "win32" ? void 0 : (0, hookRunner_1.resolveHookNode)(binary);
|
|
5637
5927
|
if (node?.problem)
|
|
5638
|
-
row("bad", "hook binary", `${(0, hookRunner_1.tidyHomePath)(binary,
|
|
5928
|
+
row("bad", "hook binary", `${(0, hookRunner_1.tidyHomePath)(binary, os6.homedir())}, but ${node.problem}. Install Node 20 or newer, then run setup again`);
|
|
5639
5929
|
else
|
|
5640
|
-
row("ok", "hook binary", `${(0, hookRunner_1.tidyHomePath)(binary,
|
|
5930
|
+
row("ok", "hook binary", `${(0, hookRunner_1.tidyHomePath)(binary, os6.homedir())}${node?.version ? ui.dim(` (Node ${node.version})`) : ""}`);
|
|
5641
5931
|
if (!options.dryRun) {
|
|
5642
5932
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
5643
5933
|
const toolInstallationId = identity?.toolInstallationId ?? options.toolInstallationId ?? (0, credentials_1.readHostCredentials)(spec.host)?.toolInstallationId ?? `${spec.toolType}:${crypto.randomUUID()}`;
|
|
@@ -5661,18 +5951,18 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
|
|
|
5661
5951
|
if (written === null)
|
|
5662
5952
|
return 1;
|
|
5663
5953
|
const reach = options.scope === "user" ? "every project" : "this project only";
|
|
5664
|
-
row("ok", "hooks", `${(0, hookRunner_1.tidyHomePath)(settingsFile,
|
|
5954
|
+
row("ok", "hooks", `${(0, hookRunner_1.tidyHomePath)(settingsFile, os6.homedir())} ${ui.dim(`(${spec.hookEvents.length} events, ${reach}${written ? "" : ", already current"})`)}`);
|
|
5665
5955
|
const changes = spec.hookSet === void 0 ? void 0 : (0, hookSet_1.describeHookSetChanges)((0, hookSet_1.hookSetChanges)(before, spec.hookEvents), spec.hookSet);
|
|
5666
5956
|
if (changes)
|
|
5667
5957
|
detail("", changes);
|
|
5668
5958
|
const otherFile = spec.settings.settingsPath(options.scope === "user" ? "project" : "user", options.projectDir);
|
|
5669
5959
|
if (otherFile !== settingsFile && registeredHookSets(readSettings(otherFile), spec).size > 0) {
|
|
5670
5960
|
if (options.dryRun) {
|
|
5671
|
-
row("info", "moved", `would remove the copy in ${(0, hookRunner_1.tidyHomePath)(otherFile,
|
|
5961
|
+
row("info", "moved", `would remove the copy in ${(0, hookRunner_1.tidyHomePath)(otherFile, os6.homedir())}, so each event runs once`);
|
|
5672
5962
|
} else if (removeOurHookEntries(otherFile, spec)) {
|
|
5673
|
-
row("ok", "moved", `removed the copy in ${(0, hookRunner_1.tidyHomePath)(otherFile,
|
|
5963
|
+
row("ok", "moved", `removed the copy in ${(0, hookRunner_1.tidyHomePath)(otherFile, os6.homedir())}, so each event runs once ${ui.dim("(backup beside it)")}`);
|
|
5674
5964
|
} else {
|
|
5675
|
-
row("warn", "note", `${(0, hookRunner_1.tidyHomePath)(otherFile,
|
|
5965
|
+
row("warn", "note", `${(0, hookRunner_1.tidyHomePath)(otherFile, os6.homedir())} registers these hooks too, so each event runs twice.`);
|
|
5676
5966
|
detail("", `Remove the ${spec.binaryName} entries from one of the two files.`);
|
|
5677
5967
|
}
|
|
5678
5968
|
}
|
|
@@ -5683,10 +5973,10 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
|
|
|
5683
5973
|
row("info", "pairing", `none, as asked ${ui.dim("(--no-pair)")}`);
|
|
5684
5974
|
else
|
|
5685
5975
|
row("warn", "pairing", "not paired: pairing did not finish");
|
|
5686
|
-
detail("credentials", `${(0, hookRunner_1.tidyHomePath)((0, credentials_1.credentialsFilePath)(),
|
|
5976
|
+
detail("credentials", `${(0, hookRunner_1.tidyHomePath)((0, credentials_1.credentialsFilePath)(), os6.homedir())} (tools.${spec.host})`);
|
|
5687
5977
|
const eventLog = (0, eventLog_1.resolveEventLog)({ localOnly: !identity });
|
|
5688
5978
|
if (eventLog.path)
|
|
5689
|
-
row("ok", "events", `${(0, hookRunner_1.tidyHomePath)(eventLog.path,
|
|
5979
|
+
row("ok", "events", `${(0, hookRunner_1.tidyHomePath)(eventLog.path, os6.homedir())} ${ui.dim("(on this machine only)")}`);
|
|
5690
5980
|
else if (options.eventLog !== void 0)
|
|
5691
5981
|
row("info", "events", "off");
|
|
5692
5982
|
if (options.dryRun) {
|
|
@@ -5700,7 +5990,7 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
|
|
|
5700
5990
|
console.log(`${ui.mark("ok")} ${ui.bold("Ready.")} The screen saver and the Ascenda app's live view work now.`);
|
|
5701
5991
|
console.log(" They run on this machine and need no account or pairing.");
|
|
5702
5992
|
if (eventLog.path)
|
|
5703
|
-
console.log(` Every event is also written to ${(0, hookRunner_1.tidyHomePath)(eventLog.path,
|
|
5993
|
+
console.log(` Every event is also written to ${(0, hookRunner_1.tidyHomePath)(eventLog.path, os6.homedir())}, for you or any tool to read.`);
|
|
5704
5994
|
} else if (!identity) {
|
|
5705
5995
|
console.log(`${ui.mark("warn")} ${ui.bold("Installed, not paired.")} The screen saver and the live view work now.`);
|
|
5706
5996
|
console.log(" Your sessions won't reach Ascenda's servers until pairing completes.");
|
|
@@ -5723,9 +6013,9 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
|
|
|
5723
6013
|
return 0;
|
|
5724
6014
|
}
|
|
5725
6015
|
function isHomeProject(options) {
|
|
5726
|
-
return options.scope === "project" &&
|
|
6016
|
+
return options.scope === "project" && path15.resolve(options.projectDir) === path15.resolve(os6.homedir());
|
|
5727
6017
|
}
|
|
5728
|
-
function
|
|
6018
|
+
function parseArgs2(argv, spec) {
|
|
5729
6019
|
const options = {
|
|
5730
6020
|
scope: "user",
|
|
5731
6021
|
projectDir: process.cwd(),
|
|
@@ -5778,7 +6068,7 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
|
|
|
5778
6068
|
break;
|
|
5779
6069
|
}
|
|
5780
6070
|
case "--project-dir":
|
|
5781
|
-
options.projectDir =
|
|
6071
|
+
options.projectDir = path15.resolve(next());
|
|
5782
6072
|
break;
|
|
5783
6073
|
case "--dry-run":
|
|
5784
6074
|
options.dryRun = true;
|
|
@@ -5873,16 +6163,19 @@ ${usage(spec)}`);
|
|
|
5873
6163
|
return { toolInstallationId: existingId ?? `${spec.toolType}:<paired at run time>`, paired: false };
|
|
5874
6164
|
}
|
|
5875
6165
|
const toolInstallationId = existingId ?? `${spec.toolType}:${crypto.randomUUID()}`;
|
|
5876
|
-
let
|
|
6166
|
+
let attempt;
|
|
5877
6167
|
try {
|
|
5878
|
-
|
|
6168
|
+
attempt = await (0, pairingStudyJoin_1.createPairingAttempt)(apiBaseUrl, toolInstallationId, spec.toolType, `${spec.displayName} on ${os6.hostname()}`);
|
|
5879
6169
|
} catch (error) {
|
|
5880
6170
|
console.error(`
|
|
5881
6171
|
Could not reach ${apiBaseUrl} to pair: ${error instanceof Error ? error.message : String(error)}`);
|
|
5882
6172
|
console.error("Start the local dev server and use --local, or pass --api-base-url for your backend.");
|
|
5883
6173
|
return void 0;
|
|
5884
6174
|
}
|
|
5885
|
-
|
|
6175
|
+
if (attempt.refusal)
|
|
6176
|
+
console.log(`
|
|
6177
|
+
${attempt.refusal} Pairing without the study.`);
|
|
6178
|
+
const token = await pollForToken(apiBaseUrl, attempt);
|
|
5886
6179
|
if (!token)
|
|
5887
6180
|
return void 0;
|
|
5888
6181
|
(0, tokenStore_1.persistEventWriteToken)((0, tokenStore_1.defaultTokenFilePath)(toolInstallationId), token);
|
|
@@ -5900,27 +6193,32 @@ Could not reach ${apiBaseUrl} to pair: ${error instanceof Error ? error.message
|
|
|
5900
6193
|
}
|
|
5901
6194
|
return "keep";
|
|
5902
6195
|
}
|
|
5903
|
-
async function pollForToken(apiBaseUrl,
|
|
5904
|
-
const
|
|
5905
|
-
|
|
6196
|
+
async function pollForToken(apiBaseUrl, attempt) {
|
|
6197
|
+
const { session } = attempt;
|
|
6198
|
+
const deadline = Math.min(Date.parse(session.expiresAt) || Date.now() + 3e5, Date.now() + 3e5);
|
|
6199
|
+
let studyJoin;
|
|
6200
|
+
console.log("");
|
|
6201
|
+
for (const line of (0, pairingStudyJoin_1.pairingAttemptLines)(attempt))
|
|
6202
|
+
console.log(` ${line}`);
|
|
6203
|
+
console.log(" Waiting...");
|
|
5906
6204
|
while (Date.now() < deadline) {
|
|
5907
|
-
const status = await (0, http_1.getPairingStatus)(apiBaseUrl, pairingSessionId);
|
|
5908
|
-
|
|
6205
|
+
const status = await (0, http_1.getPairingStatus)(apiBaseUrl, session.pairingSessionId);
|
|
6206
|
+
studyJoin = status.studyJoin ?? studyJoin;
|
|
6207
|
+
if (status.status === "paired" && status.eventWriteToken) {
|
|
6208
|
+
studyJoin = await (0, pairingStudyJoin_1.settleStudyJoin)(apiBaseUrl, session.pairingSessionId, studyJoin);
|
|
6209
|
+
(0, pairingStudyJoin_1.writePairingJoinOutcome)((0, pairingStudyJoin_1.pairingJoinOutcome)(attempt, "paired", studyJoin));
|
|
5909
6210
|
return status.eventWriteToken;
|
|
6211
|
+
}
|
|
5910
6212
|
if (status.status === "expired" || status.status === "cancelled") {
|
|
5911
6213
|
console.error(`
|
|
5912
6214
|
Pairing ${status.status}. Run setup again.`);
|
|
6215
|
+
(0, pairingStudyJoin_1.writePairingJoinOutcome)((0, pairingStudyJoin_1.pairingJoinOutcome)(attempt, status.status, studyJoin));
|
|
5913
6216
|
return void 0;
|
|
5914
6217
|
}
|
|
5915
|
-
if (!announced) {
|
|
5916
|
-
console.log(`
|
|
5917
|
-
Confirm in the Ascenda app \u2014 code ${code}`);
|
|
5918
|
-
console.log(" Waiting...");
|
|
5919
|
-
announced = true;
|
|
5920
|
-
}
|
|
5921
6218
|
await new Promise((resolve3) => setTimeout(resolve3, 2e3));
|
|
5922
6219
|
}
|
|
5923
6220
|
console.error("\nPairing timed out. Run setup again.");
|
|
6221
|
+
(0, pairingStudyJoin_1.writePairingJoinOutcome)((0, pairingStudyJoin_1.pairingJoinOutcome)(attempt, "gave_up", studyJoin));
|
|
5924
6222
|
return void 0;
|
|
5925
6223
|
}
|
|
5926
6224
|
function installBinary(spec, dryRun) {
|
|
@@ -5933,9 +6231,9 @@ Pairing ${status.status}. Run setup again.`);
|
|
|
5933
6231
|
}
|
|
5934
6232
|
function writeHookSettings(settingsFile, binary, spec, dryRun) {
|
|
5935
6233
|
let settings = { ...spec.settings.scaffold ?? {} };
|
|
5936
|
-
const exists =
|
|
6234
|
+
const exists = fs15.existsSync(settingsFile);
|
|
5937
6235
|
if (exists) {
|
|
5938
|
-
const raw =
|
|
6236
|
+
const raw = fs15.readFileSync(settingsFile, "utf8").trim();
|
|
5939
6237
|
if (raw) {
|
|
5940
6238
|
try {
|
|
5941
6239
|
settings = JSON.parse(raw);
|
|
@@ -5954,7 +6252,7 @@ ${settingsFile} is not valid JSON. Fix or move it, then run setup again.`);
|
|
|
5954
6252
|
const updated = { ...settings, hooks };
|
|
5955
6253
|
const serialised = `${JSON.stringify(updated, null, 2)}
|
|
5956
6254
|
`;
|
|
5957
|
-
if (exists &&
|
|
6255
|
+
if (exists && fs15.readFileSync(settingsFile, "utf8") === serialised)
|
|
5958
6256
|
return false;
|
|
5959
6257
|
if (dryRun) {
|
|
5960
6258
|
console.log(`
|
|
@@ -6006,7 +6304,7 @@ ${serialised}`);
|
|
|
6006
6304
|
if (ours.length === 0)
|
|
6007
6305
|
return [];
|
|
6008
6306
|
const report = spec.trust.check(settingsFile, ours);
|
|
6009
|
-
const where = (0, hookRunner_1.tidyHomePath)(report.approvalsFile,
|
|
6307
|
+
const where = (0, hookRunner_1.tidyHomePath)(report.approvalsFile, os6.homedir());
|
|
6010
6308
|
const lines = [];
|
|
6011
6309
|
if (report.unreadable) {
|
|
6012
6310
|
lines.push(`${spec.displayName}'s approvals in ${where} could not be read, so whether these hooks are trusted is unknown.`);
|
|
@@ -6102,7 +6400,7 @@ ${serialised}`);
|
|
|
6102
6400
|
}
|
|
6103
6401
|
function readSettings(settingsFile) {
|
|
6104
6402
|
try {
|
|
6105
|
-
return JSON.parse(
|
|
6403
|
+
return JSON.parse(fs15.readFileSync(settingsFile, "utf8"));
|
|
6106
6404
|
} catch {
|
|
6107
6405
|
return {};
|
|
6108
6406
|
}
|
|
@@ -6121,7 +6419,7 @@ ${serialised}`);
|
|
|
6121
6419
|
console.log(`pairing ${credentials?.toolInstallationId ?? "\u2014 not paired"}${localOnly ? " (installed, not paired \u2014 local features active, telemetry inactive)" : ""}`);
|
|
6122
6420
|
console.log(`token ${localOnly ? "\u2014 none needed until this install is paired" : tokenFile && (0, tokenStore_1.readTokenFile)(tokenFile) ? "present" : "\u2014 missing"}`);
|
|
6123
6421
|
console.log(`event log ${(0, eventLog_1.describeEventLog)((0, eventLog_1.resolveEventLog)({ localOnly }), `npx ${spec.packageName} setup`)}`);
|
|
6124
|
-
console.log(`hook binary ${
|
|
6422
|
+
console.log(`hook binary ${fs15.existsSync(binary) ? binary : "\u2014 not installed"}`);
|
|
6125
6423
|
const node = process.platform === "win32" ? void 0 : (0, hookRunner_1.resolveHookNode)(binary);
|
|
6126
6424
|
if (node) {
|
|
6127
6425
|
console.log(node.problem ? `node \u2014 ${node.problem}. Install Node 20 or newer, then run setup again` : `node ${node.node} (${node.version}, ${node.how === "recorded" ? "recorded at setup" : "found by the launcher"})`);
|
|
@@ -6168,14 +6466,14 @@ ${serialised}`);
|
|
|
6168
6466
|
await notices.markShown();
|
|
6169
6467
|
const paired = localOnly || credentials?.toolInstallationId !== void 0;
|
|
6170
6468
|
const wired = registered === spec.hookEvents.length || options.scope === "project" && elsewhere === spec.hookEvents.length;
|
|
6171
|
-
const healthy = paired && wired &&
|
|
6469
|
+
const healthy = paired && wired && fs15.existsSync(binary) && !stale.length && !node?.problem && trustLines.length === 0;
|
|
6172
6470
|
return healthy ? 0 : 1;
|
|
6173
6471
|
}
|
|
6174
6472
|
function countRegistered(settings, spec) {
|
|
6175
6473
|
return spec.hookEvents.filter((event) => (settings.hooks?.[event] ?? []).some((entry) => isOurs(entry, spec))).length;
|
|
6176
6474
|
}
|
|
6177
6475
|
function cliAgentRegistrations(spec, projectDir = process.cwd()) {
|
|
6178
|
-
const home =
|
|
6476
|
+
const home = os6.homedir();
|
|
6179
6477
|
const userFile = spec.settings.settingsPath("user", projectDir);
|
|
6180
6478
|
const projectFile = spec.settings.settingsPath("project", projectDir);
|
|
6181
6479
|
const found = [];
|
|
@@ -6189,7 +6487,7 @@ ${serialised}`);
|
|
|
6189
6487
|
file: (0, hookRunner_1.tidyHomePath)(file, home),
|
|
6190
6488
|
registered,
|
|
6191
6489
|
scope,
|
|
6192
|
-
homeProject: scope === "project" &&
|
|
6490
|
+
homeProject: scope === "project" && path15.resolve(projectDir) === path15.resolve(home)
|
|
6193
6491
|
});
|
|
6194
6492
|
}
|
|
6195
6493
|
return found;
|
|
@@ -6233,7 +6531,7 @@ ${serialised}`);
|
|
|
6233
6531
|
continue;
|
|
6234
6532
|
const problems = trustProblemLines(spec, file, settings, "");
|
|
6235
6533
|
if (problems.length === 0) {
|
|
6236
|
-
out.push(` ${ui.mark("ok")} ${"Hook approvals".padEnd(20)} every hook in ${(0, hookRunner_1.tidyHomePath)(file,
|
|
6534
|
+
out.push(` ${ui.mark("ok")} ${"Hook approvals".padEnd(20)} every hook in ${(0, hookRunner_1.tidyHomePath)(file, os6.homedir())} is approved`);
|
|
6237
6535
|
continue;
|
|
6238
6536
|
}
|
|
6239
6537
|
out.push(` ${ui.mark("bad")} ${"Hook approvals".padEnd(20)} ${ui.red(problems[0])}`);
|
|
@@ -6269,10 +6567,10 @@ ${serialised}`);
|
|
|
6269
6567
|
];
|
|
6270
6568
|
}
|
|
6271
6569
|
function removeOurHookEntries(settingsFile, spec) {
|
|
6272
|
-
if (!
|
|
6570
|
+
if (!fs15.existsSync(settingsFile))
|
|
6273
6571
|
return true;
|
|
6274
6572
|
try {
|
|
6275
|
-
const settings = JSON.parse(
|
|
6573
|
+
const settings = JSON.parse(fs15.readFileSync(settingsFile, "utf8"));
|
|
6276
6574
|
const hooks = { ...settings.hooks ?? {} };
|
|
6277
6575
|
for (const event of Object.keys(hooks)) {
|
|
6278
6576
|
const kept = withoutOurEntries(hooks[event], spec);
|
|
@@ -6293,7 +6591,7 @@ ${serialised}`);
|
|
|
6293
6591
|
}
|
|
6294
6592
|
function uninstall(options, spec) {
|
|
6295
6593
|
const settingsFile = spec.settings.settingsPath(options.scope, options.projectDir);
|
|
6296
|
-
if (
|
|
6594
|
+
if (fs15.existsSync(settingsFile)) {
|
|
6297
6595
|
if (!removeOurHookEntries(settingsFile, spec)) {
|
|
6298
6596
|
console.error(`could not parse ${settingsFile} \u2014 remove the ascenda hook entries by hand`);
|
|
6299
6597
|
return 1;
|
|
@@ -6308,7 +6606,7 @@ ${serialised}`);
|
|
|
6308
6606
|
(0, credentials_1.removeHostCredentials)(spec.host);
|
|
6309
6607
|
console.log(`removed tools.${spec.host} from ${(0, credentials_1.credentialsFilePath)()}`);
|
|
6310
6608
|
}
|
|
6311
|
-
console.log(`tokens left in ${
|
|
6609
|
+
console.log(`tokens left in ${path15.join((0, tokenStore_1.ascendaHome)(), "tokens")} \u2014 revoke in the Ascenda app to invalidate them`);
|
|
6312
6610
|
return 0;
|
|
6313
6611
|
}
|
|
6314
6612
|
}
|
|
@@ -6360,12 +6658,12 @@ var require_turnState = __commonJS({
|
|
|
6360
6658
|
exports.readTurnPromptId = readTurnPromptId;
|
|
6361
6659
|
exports.consumeTurnDurationMs = consumeTurnDurationMs;
|
|
6362
6660
|
var crypto_1 = __require("crypto");
|
|
6363
|
-
var
|
|
6364
|
-
var
|
|
6661
|
+
var fs15 = __importStar(__require("fs"));
|
|
6662
|
+
var path15 = __importStar(__require("path"));
|
|
6365
6663
|
var tokenStore_1 = require_tokenStore();
|
|
6366
|
-
var stateDir = () => process.env.ASCENDA_STATE_DIR ??
|
|
6664
|
+
var stateDir = () => process.env.ASCENDA_STATE_DIR ?? path15.join((0, tokenStore_1.ascendaHome)(), "state");
|
|
6367
6665
|
function turnFile(agent, sessionId) {
|
|
6368
|
-
return
|
|
6666
|
+
return path15.join(stateDir(), `${sanitize(agent)}-turn-${sanitize(sessionId)}`);
|
|
6369
6667
|
}
|
|
6370
6668
|
function sanitize(value) {
|
|
6371
6669
|
return value.replace(/[^a-zA-Z0-9._-]/g, "_");
|
|
@@ -6375,8 +6673,8 @@ var require_turnState = __commonJS({
|
|
|
6375
6673
|
return void 0;
|
|
6376
6674
|
try {
|
|
6377
6675
|
const promptId = (0, crypto_1.randomUUID)();
|
|
6378
|
-
|
|
6379
|
-
|
|
6676
|
+
fs15.mkdirSync(stateDir(), { recursive: true });
|
|
6677
|
+
fs15.writeFileSync(turnFile(agent, sessionId), `${now} ${promptId}`, { encoding: "utf8", mode: 384 });
|
|
6380
6678
|
return promptId;
|
|
6381
6679
|
} catch {
|
|
6382
6680
|
return void 0;
|
|
@@ -6386,7 +6684,7 @@ var require_turnState = __commonJS({
|
|
|
6386
6684
|
if (!sessionId)
|
|
6387
6685
|
return void 0;
|
|
6388
6686
|
try {
|
|
6389
|
-
const id =
|
|
6687
|
+
const id = fs15.readFileSync(turnFile(agent, sessionId), "utf8").trim().split(/\s+/)[1];
|
|
6390
6688
|
return id && /^[A-Za-z0-9_-]{1,128}$/.test(id) ? id : void 0;
|
|
6391
6689
|
} catch {
|
|
6392
6690
|
return void 0;
|
|
@@ -6397,8 +6695,8 @@ var require_turnState = __commonJS({
|
|
|
6397
6695
|
return void 0;
|
|
6398
6696
|
const file = turnFile(agent, sessionId);
|
|
6399
6697
|
try {
|
|
6400
|
-
const started = Number(
|
|
6401
|
-
|
|
6698
|
+
const started = Number(fs15.readFileSync(file, "utf8").trim().split(/\s+/)[0]);
|
|
6699
|
+
fs15.rmSync(file, { force: true });
|
|
6402
6700
|
if (!Number.isFinite(started) || started <= 0 || started > now)
|
|
6403
6701
|
return void 0;
|
|
6404
6702
|
return now - started;
|
|
@@ -6454,30 +6752,30 @@ var require_pluginBundle = __commonJS({
|
|
|
6454
6752
|
exports.pluginBundlePaths = pluginBundlePaths;
|
|
6455
6753
|
exports.installPluginBundle = installPluginBundle;
|
|
6456
6754
|
exports.describePluginBundleOutcome = describePluginBundleOutcome;
|
|
6457
|
-
var
|
|
6458
|
-
var
|
|
6755
|
+
var fs15 = __importStar(__require("fs"));
|
|
6756
|
+
var path15 = __importStar(__require("path"));
|
|
6459
6757
|
var collectorVersion_1 = require_collectorVersion();
|
|
6460
6758
|
var hookRunner_1 = require_hookRunner();
|
|
6461
6759
|
var tokenStore_1 = require_tokenStore();
|
|
6462
6760
|
function pluginBundlePaths(name) {
|
|
6463
|
-
const base =
|
|
6761
|
+
const base = path15.join((0, tokenStore_1.ascendaHome)(), "plugin", name);
|
|
6464
6762
|
return { bundle: `${base}.mjs`, version: `${base}.version`, checked: `${base}.checked` };
|
|
6465
6763
|
}
|
|
6466
6764
|
function installPluginBundle(options) {
|
|
6467
6765
|
const paths = pluginBundlePaths(options.name);
|
|
6468
|
-
const source =
|
|
6766
|
+
const source = path15.resolve(options.source ?? process.argv[1]);
|
|
6469
6767
|
const incoming = options.version ?? collectorVersion_1.COLLECTOR_VERSION;
|
|
6470
6768
|
const installed = readVersion(paths.version);
|
|
6471
|
-
const present =
|
|
6472
|
-
if (source ===
|
|
6769
|
+
const present = fs15.existsSync(paths.bundle);
|
|
6770
|
+
if (source === path15.resolve(paths.bundle))
|
|
6473
6771
|
return { kind: "current", version: installed ?? incoming };
|
|
6474
6772
|
if (present && installed && (0, hookRunner_1.isDowngrade)(installed, incoming))
|
|
6475
6773
|
return { kind: "kept-newer", installed, incoming };
|
|
6476
|
-
const contents =
|
|
6477
|
-
if (present && installed === incoming && contents.equals(
|
|
6774
|
+
const contents = fs15.readFileSync(source);
|
|
6775
|
+
if (present && installed === incoming && contents.equals(fs15.readFileSync(paths.bundle))) {
|
|
6478
6776
|
return { kind: "current", version: incoming };
|
|
6479
6777
|
}
|
|
6480
|
-
|
|
6778
|
+
fs15.mkdirSync(path15.dirname(paths.bundle), { recursive: true });
|
|
6481
6779
|
(0, hookRunner_1.writeAtomically)(paths.bundle, contents, 420);
|
|
6482
6780
|
(0, hookRunner_1.writeAtomically)(paths.version, `${incoming}
|
|
6483
6781
|
`, 420);
|
|
@@ -6495,7 +6793,7 @@ var require_pluginBundle = __commonJS({
|
|
|
6495
6793
|
}
|
|
6496
6794
|
function readVersion(file) {
|
|
6497
6795
|
try {
|
|
6498
|
-
return
|
|
6796
|
+
return fs15.readFileSync(file, "utf8").trim() || void 0;
|
|
6499
6797
|
} catch {
|
|
6500
6798
|
return void 0;
|
|
6501
6799
|
}
|
|
@@ -6551,14 +6849,14 @@ var require_agentProcess = __commonJS({
|
|
|
6551
6849
|
exports.findAgentPid = findAgentPid;
|
|
6552
6850
|
exports.livePidFields = livePidFields;
|
|
6553
6851
|
var child_process_1 = __require("child_process");
|
|
6554
|
-
var
|
|
6852
|
+
var path15 = __importStar(__require("path"));
|
|
6555
6853
|
exports.AGENT_PROCESS = {
|
|
6556
6854
|
claude_code: {
|
|
6557
|
-
executable: (command) =>
|
|
6855
|
+
executable: (command) => path15.basename(command) === "claude" || /\/claude\/versions\/[^/]+$/.test(command) || /\/@anthropic-ai\/claude-code\/bin\/claude\.exe$/.test(command),
|
|
6558
6856
|
scriptMarkers: ["@anthropic-ai/claude-code"]
|
|
6559
6857
|
},
|
|
6560
6858
|
codex: {
|
|
6561
|
-
executable: (command) => /^codex(-(aarch64|x86_64)-apple-darwin)?$/.test(
|
|
6859
|
+
executable: (command) => /^codex(-(aarch64|x86_64)-apple-darwin)?$/.test(path15.basename(command)),
|
|
6562
6860
|
args: (args) => !/\s(app-server|mcp-server)(\s|$)/.test(args)
|
|
6563
6861
|
},
|
|
6564
6862
|
gemini_cli: {
|
|
@@ -6612,7 +6910,7 @@ var require_agentProcess = __commonJS({
|
|
|
6612
6910
|
if (rule.executable(info.command)) {
|
|
6613
6911
|
return accepts(rule, rule.args ? argsLookup(pid) : "") ? { pid, match: "executable" } : void 0;
|
|
6614
6912
|
}
|
|
6615
|
-
if (markers.length > 0 && SCRIPT_RUNTIME.test(
|
|
6913
|
+
if (markers.length > 0 && SCRIPT_RUNTIME.test(path15.basename(info.command))) {
|
|
6616
6914
|
const args = argsLookup(pid);
|
|
6617
6915
|
const marker = args === void 0 ? void 0 : scriptMarkerIn(args, markers);
|
|
6618
6916
|
if (marker !== void 0) {
|
|
@@ -6647,11 +6945,11 @@ var require_out3 = __commonJS({
|
|
|
6647
6945
|
"../packages/tool-kit/out/index.js"(exports) {
|
|
6648
6946
|
"use strict";
|
|
6649
6947
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6650
|
-
exports.
|
|
6651
|
-
exports.
|
|
6652
|
-
exports.
|
|
6653
|
-
exports.
|
|
6654
|
-
exports.runStudyJoin = exports.studyNoticeStatus = exports.runStudyObjection = exports.renderStudyNotices = exports.NOTICED_PURPOSES = exports.renderInitiatives = exports.initiativesStatusLines = exports.INITIATIVE_COPY = exports.startStudyJoin = exports.setStudyObjection = exports.markStudyNoticeShown = void 0;
|
|
6948
|
+
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.detectCollectorPlatform = exports.COLLECTOR_PLATFORM = 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;
|
|
6949
|
+
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 = exports.resolveEventLog = exports.parseEventLogFlag = void 0;
|
|
6950
|
+
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 = exports.unresolvedStateFilePath = exports.markFailureNotified = void 0;
|
|
6951
|
+
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.pluginBundlePaths = exports.installPluginBundle = exports.describePluginBundleOutcome = 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 = exports.saverSupportDir = exports.saverStatusDir = void 0;
|
|
6952
|
+
exports.writePairingJoinOutcome = exports.settleStudyJoin = exports.pairingJoinOutcome = exports.pairingAttemptLines = exports.createPairingAttempt = exports.PAIR_ORG_JOIN_CODE_ENV = exports.PAIR_JOIN_OUTCOME_FILE_ENV = exports.studyJoinConfirmUrl = exports.pairingConfirmUrl = exports.pairingConfirmLines = exports.runStudyJoin = exports.formatWindow = exports.describeStudyGrant = exports.describeStudyKind = exports.describeStudyJoinRefusal = 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 = void 0;
|
|
6655
6953
|
var commandClassifier_1 = require_commandClassifier();
|
|
6656
6954
|
Object.defineProperty(exports, "classifyCommand", { enumerable: true, get: function() {
|
|
6657
6955
|
return commandClassifier_1.classifyCommand;
|
|
@@ -6739,6 +7037,13 @@ var require_out3 = __commonJS({
|
|
|
6739
7037
|
Object.defineProperty(exports, "mintIdempotencyKey", { enumerable: true, get: function() {
|
|
6740
7038
|
return payload_1.mintIdempotencyKey;
|
|
6741
7039
|
} });
|
|
7040
|
+
var collectorPlatform_1 = require_collectorPlatform();
|
|
7041
|
+
Object.defineProperty(exports, "COLLECTOR_PLATFORM", { enumerable: true, get: function() {
|
|
7042
|
+
return collectorPlatform_1.COLLECTOR_PLATFORM;
|
|
7043
|
+
} });
|
|
7044
|
+
Object.defineProperty(exports, "detectCollectorPlatform", { enumerable: true, get: function() {
|
|
7045
|
+
return collectorPlatform_1.detectCollectorPlatform;
|
|
7046
|
+
} });
|
|
6742
7047
|
var collectorVersion_1 = require_collectorVersion();
|
|
6743
7048
|
Object.defineProperty(exports, "COLLECTOR_VERSION", { enumerable: true, get: function() {
|
|
6744
7049
|
return collectorVersion_1.COLLECTOR_VERSION;
|
|
@@ -7323,15 +7628,59 @@ var require_out3 = __commonJS({
|
|
|
7323
7628
|
return studyNotices_1.studyNoticeStatus;
|
|
7324
7629
|
} });
|
|
7325
7630
|
var studyJoin_1 = require_studyJoin();
|
|
7631
|
+
Object.defineProperty(exports, "describeStudyJoinRefusal", { enumerable: true, get: function() {
|
|
7632
|
+
return studyJoin_1.describeRefusal;
|
|
7633
|
+
} });
|
|
7634
|
+
Object.defineProperty(exports, "describeStudyKind", { enumerable: true, get: function() {
|
|
7635
|
+
return studyJoin_1.describeStudyKind;
|
|
7636
|
+
} });
|
|
7637
|
+
Object.defineProperty(exports, "describeStudyGrant", { enumerable: true, get: function() {
|
|
7638
|
+
return studyJoin_1.describeStudyGrant;
|
|
7639
|
+
} });
|
|
7640
|
+
Object.defineProperty(exports, "formatWindow", { enumerable: true, get: function() {
|
|
7641
|
+
return studyJoin_1.formatWindow;
|
|
7642
|
+
} });
|
|
7326
7643
|
Object.defineProperty(exports, "runStudyJoin", { enumerable: true, get: function() {
|
|
7327
7644
|
return studyJoin_1.runStudyJoin;
|
|
7328
7645
|
} });
|
|
7329
|
-
|
|
7646
|
+
var confirmLinks_1 = require_confirmLinks();
|
|
7647
|
+
Object.defineProperty(exports, "pairingConfirmLines", { enumerable: true, get: function() {
|
|
7648
|
+
return confirmLinks_1.pairingConfirmLines;
|
|
7649
|
+
} });
|
|
7650
|
+
Object.defineProperty(exports, "pairingConfirmUrl", { enumerable: true, get: function() {
|
|
7651
|
+
return confirmLinks_1.pairingConfirmUrl;
|
|
7652
|
+
} });
|
|
7653
|
+
Object.defineProperty(exports, "studyJoinConfirmUrl", { enumerable: true, get: function() {
|
|
7654
|
+
return confirmLinks_1.studyJoinConfirmUrl;
|
|
7655
|
+
} });
|
|
7656
|
+
var pairingStudyJoin_1 = require_pairingStudyJoin();
|
|
7657
|
+
Object.defineProperty(exports, "PAIR_JOIN_OUTCOME_FILE_ENV", { enumerable: true, get: function() {
|
|
7658
|
+
return pairingStudyJoin_1.PAIR_JOIN_OUTCOME_FILE_ENV;
|
|
7659
|
+
} });
|
|
7660
|
+
Object.defineProperty(exports, "PAIR_ORG_JOIN_CODE_ENV", { enumerable: true, get: function() {
|
|
7661
|
+
return pairingStudyJoin_1.PAIR_ORG_JOIN_CODE_ENV;
|
|
7662
|
+
} });
|
|
7663
|
+
Object.defineProperty(exports, "createPairingAttempt", { enumerable: true, get: function() {
|
|
7664
|
+
return pairingStudyJoin_1.createPairingAttempt;
|
|
7665
|
+
} });
|
|
7666
|
+
Object.defineProperty(exports, "pairingAttemptLines", { enumerable: true, get: function() {
|
|
7667
|
+
return pairingStudyJoin_1.pairingAttemptLines;
|
|
7668
|
+
} });
|
|
7669
|
+
Object.defineProperty(exports, "pairingJoinOutcome", { enumerable: true, get: function() {
|
|
7670
|
+
return pairingStudyJoin_1.pairingJoinOutcome;
|
|
7671
|
+
} });
|
|
7672
|
+
Object.defineProperty(exports, "settleStudyJoin", { enumerable: true, get: function() {
|
|
7673
|
+
return pairingStudyJoin_1.settleStudyJoin;
|
|
7674
|
+
} });
|
|
7675
|
+
Object.defineProperty(exports, "writePairingJoinOutcome", { enumerable: true, get: function() {
|
|
7676
|
+
return pairingStudyJoin_1.writePairingJoinOutcome;
|
|
7677
|
+
} });
|
|
7678
|
+
}
|
|
7330
7679
|
});
|
|
7331
7680
|
|
|
7332
7681
|
// src/cli.ts
|
|
7333
|
-
import * as
|
|
7334
|
-
import * as
|
|
7682
|
+
import * as fs14 from "node:fs/promises";
|
|
7683
|
+
import * as path14 from "node:path";
|
|
7335
7684
|
|
|
7336
7685
|
// src/stores.ts
|
|
7337
7686
|
import * as os from "node:os";
|
|
@@ -8568,6 +8917,7 @@ function newFold(sessionId, projectSlug) {
|
|
|
8568
8917
|
compactionCount: 0,
|
|
8569
8918
|
compactionManualCount: 0,
|
|
8570
8919
|
compactionAutoCount: 0,
|
|
8920
|
+
compactions: [],
|
|
8571
8921
|
toolResultErrorCount: 0,
|
|
8572
8922
|
apiErrorCount: 0,
|
|
8573
8923
|
contextWindowPeakTokens: 0,
|
|
@@ -8871,6 +9221,10 @@ async function foldLinesInto(fold, filePath, opts) {
|
|
|
8871
9221
|
const trigger = record.compactMetadata?.trigger;
|
|
8872
9222
|
if (trigger === "manual") fold.compactionManualCount += 1;
|
|
8873
9223
|
else if (trigger === "auto") fold.compactionAutoCount += 1;
|
|
9224
|
+
fold.compactions.push({
|
|
9225
|
+
at: sniffed.occurredAt,
|
|
9226
|
+
trigger: trigger === "manual" || trigger === "auto" ? trigger : null
|
|
9227
|
+
});
|
|
8874
9228
|
} else if (record.subtype === "api_error") {
|
|
8875
9229
|
fold.apiErrorCount += 1;
|
|
8876
9230
|
}
|
|
@@ -9221,29 +9575,17 @@ async function* extractClaudeCode(snapshotDir, extractionId) {
|
|
|
9221
9575
|
extractionId
|
|
9222
9576
|
};
|
|
9223
9577
|
}
|
|
9224
|
-
|
|
9225
|
-
|
|
9226
|
-
occurredAt: fold.lastTs,
|
|
9227
|
-
store: "claude_code",
|
|
9228
|
-
sourceVersion: fold.sourceVersion,
|
|
9229
|
-
sessionRef: fold.sessionId,
|
|
9230
|
-
repoRef: fold.cwd ?? fold.projectSlug,
|
|
9231
|
-
eventKind: "context_compression_manual",
|
|
9232
|
-
metrics: { compactionCount: fold.compactionManualCount },
|
|
9233
|
-
provenance: HISTORICAL_PROVENANCE.derived,
|
|
9234
|
-
extractionId
|
|
9235
|
-
};
|
|
9236
|
-
}
|
|
9237
|
-
if (fold.compactionAutoCount > 0) {
|
|
9578
|
+
for (const [index, compaction] of fold.compactions.entries()) {
|
|
9579
|
+
if (!compaction.at || !compaction.trigger) continue;
|
|
9238
9580
|
yield {
|
|
9239
|
-
occurredAt:
|
|
9581
|
+
occurredAt: compaction.at,
|
|
9240
9582
|
store: "claude_code",
|
|
9241
9583
|
sourceVersion: fold.sourceVersion,
|
|
9242
9584
|
sessionRef: fold.sessionId,
|
|
9243
9585
|
repoRef: fold.cwd ?? fold.projectSlug,
|
|
9244
|
-
eventKind: "context_compression_auto",
|
|
9245
|
-
metrics: { compactionCount:
|
|
9246
|
-
provenance: HISTORICAL_PROVENANCE.
|
|
9586
|
+
eventKind: compaction.trigger === "manual" ? "context_compression_manual" : "context_compression_auto",
|
|
9587
|
+
metrics: { compactionCount: 1, compactionOrdinal: index + 1 },
|
|
9588
|
+
provenance: HISTORICAL_PROVENANCE.direct,
|
|
9247
9589
|
extractionId
|
|
9248
9590
|
};
|
|
9249
9591
|
}
|
|
@@ -9530,8 +9872,8 @@ function rolloutIdentityOf(meta, fileName) {
|
|
|
9530
9872
|
const isSubagent = meta.thread_source === "subagent" || subagentSource !== void 0;
|
|
9531
9873
|
let subagentParentId = null;
|
|
9532
9874
|
if (isSubagent) {
|
|
9533
|
-
const
|
|
9534
|
-
subagentParentId = nonEmptyString(meta.parent_thread_id) ?? nonEmptyString(
|
|
9875
|
+
const spawn3 = asRecord(asRecord(subagentSource)?.thread_spawn) ?? asRecord(meta.thread_spawn);
|
|
9876
|
+
subagentParentId = nonEmptyString(meta.parent_thread_id) ?? nonEmptyString(spawn3?.parent_thread_id);
|
|
9535
9877
|
if (subagentParentId === threadId) subagentParentId = null;
|
|
9536
9878
|
}
|
|
9537
9879
|
const historyBase = meta.history_base;
|
|
@@ -9613,8 +9955,8 @@ function foldLinesInto2(fold, lines, identity) {
|
|
|
9613
9955
|
if (typeof payload.cli_version === "string" && (!sub || !fold.sourceVersion)) {
|
|
9614
9956
|
fold.sourceVersion = payload.cli_version;
|
|
9615
9957
|
}
|
|
9616
|
-
const
|
|
9617
|
-
if (
|
|
9958
|
+
const git2 = asRecord(payload.git);
|
|
9959
|
+
if (git2 && typeof git2.branch === "string" && (takeOver || !fold.gitBranch)) fold.gitBranch = git2.branch;
|
|
9618
9960
|
if (!sub) fold.hasPrimary = true;
|
|
9619
9961
|
if (identity.forkedFromId && !identity.isContinuation) {
|
|
9620
9962
|
replaying = true;
|
|
@@ -10669,9 +11011,9 @@ function toolInvocationsOf(request) {
|
|
|
10669
11011
|
var JSONL_KIND_HEADER = 0;
|
|
10670
11012
|
var JSONL_KIND_SET = 1;
|
|
10671
11013
|
var JSONL_KIND_SPLICE = 2;
|
|
10672
|
-
function resolvePath(root,
|
|
11014
|
+
function resolvePath(root, path15) {
|
|
10673
11015
|
let cur = root;
|
|
10674
|
-
for (const seg of
|
|
11016
|
+
for (const seg of path15) {
|
|
10675
11017
|
if (typeof seg === "number") {
|
|
10676
11018
|
if (!Array.isArray(cur) || seg >= cur.length) return null;
|
|
10677
11019
|
cur = cur[seg];
|
|
@@ -10682,10 +11024,10 @@ function resolvePath(root, path13) {
|
|
|
10682
11024
|
}
|
|
10683
11025
|
return cur ?? null;
|
|
10684
11026
|
}
|
|
10685
|
-
function applySet(root,
|
|
10686
|
-
if (
|
|
10687
|
-
const parent = resolvePath(root,
|
|
10688
|
-
const last =
|
|
11027
|
+
function applySet(root, path15, value) {
|
|
11028
|
+
if (path15.length === 0) return;
|
|
11029
|
+
const parent = resolvePath(root, path15.slice(0, -1));
|
|
11030
|
+
const last = path15[path15.length - 1];
|
|
10689
11031
|
if (typeof last === "number") {
|
|
10690
11032
|
if (!Array.isArray(parent)) return;
|
|
10691
11033
|
while (parent.length <= last) parent.push(null);
|
|
@@ -10695,8 +11037,8 @@ function applySet(root, path13, value) {
|
|
|
10695
11037
|
parent[last] = value;
|
|
10696
11038
|
}
|
|
10697
11039
|
}
|
|
10698
|
-
function applySplice(root,
|
|
10699
|
-
const target = resolvePath(root,
|
|
11040
|
+
function applySplice(root, path15, values, index) {
|
|
11041
|
+
const target = resolvePath(root, path15);
|
|
10700
11042
|
if (!Array.isArray(target)) return;
|
|
10701
11043
|
if (index !== null && index >= 0 && index <= target.length) target.splice(index, 0, ...values);
|
|
10702
11044
|
else target.push(...values);
|
|
@@ -11081,16 +11423,207 @@ async function* extractVsCode(source, extractionId) {
|
|
|
11081
11423
|
}
|
|
11082
11424
|
}
|
|
11083
11425
|
|
|
11084
|
-
// src/
|
|
11426
|
+
// src/extractors/git.ts
|
|
11085
11427
|
var import_tool_kit7 = __toESM(require_out3(), 1);
|
|
11428
|
+
import { execFile as execFile4 } from "node:child_process";
|
|
11086
11429
|
import { createHash as createHash2 } from "node:crypto";
|
|
11087
|
-
import { createReadStream as createReadStream2, existsSync } from "node:fs";
|
|
11088
11430
|
import * as fs8 from "node:fs/promises";
|
|
11431
|
+
import { promisify as promisify4 } from "node:util";
|
|
11432
|
+
var execFileAsync4 = promisify4(execFile4);
|
|
11433
|
+
var DEFAULT_GIT_SINCE_DAYS = 365;
|
|
11434
|
+
async function git(repo, args) {
|
|
11435
|
+
const { stdout } = await execFileAsync4("git", ["-C", repo, ...args], {
|
|
11436
|
+
maxBuffer: 256 * 1024 * 1024,
|
|
11437
|
+
env: { ...process.env, GIT_TERMINAL_PROMPT: "0", LC_ALL: "C" }
|
|
11438
|
+
});
|
|
11439
|
+
return stdout;
|
|
11440
|
+
}
|
|
11441
|
+
async function repoRootOf(ref) {
|
|
11442
|
+
try {
|
|
11443
|
+
await fs8.access(ref);
|
|
11444
|
+
const root = (await git(ref, ["rev-parse", "--show-toplevel"])).trim();
|
|
11445
|
+
return root || null;
|
|
11446
|
+
} catch {
|
|
11447
|
+
return null;
|
|
11448
|
+
}
|
|
11449
|
+
}
|
|
11450
|
+
async function branchOrder(repo) {
|
|
11451
|
+
let names = [];
|
|
11452
|
+
try {
|
|
11453
|
+
names = (await git(repo, ["for-each-ref", "--format=%(refname:short)", "refs/heads"])).split("\n").map((n) => n.trim()).filter(Boolean);
|
|
11454
|
+
} catch {
|
|
11455
|
+
return { branches: [], defaultBranch: null };
|
|
11456
|
+
}
|
|
11457
|
+
let defaultBranch = null;
|
|
11458
|
+
try {
|
|
11459
|
+
const head = (await git(repo, ["symbolic-ref", "--short", "refs/remotes/origin/HEAD"])).trim();
|
|
11460
|
+
if (head.startsWith("origin/")) defaultBranch = head.slice("origin/".length);
|
|
11461
|
+
} catch {
|
|
11462
|
+
}
|
|
11463
|
+
if (!defaultBranch) defaultBranch = names.find((n) => n === "main" || n === "master") ?? null;
|
|
11464
|
+
const rest = names.filter((n) => n !== defaultBranch);
|
|
11465
|
+
const branches = defaultBranch && names.includes(defaultBranch) ? [...rest, defaultBranch] : rest;
|
|
11466
|
+
return { branches, defaultBranch };
|
|
11467
|
+
}
|
|
11468
|
+
var COMMIT_MARK = "";
|
|
11469
|
+
function parseGitLog(output) {
|
|
11470
|
+
const commits = [];
|
|
11471
|
+
for (const block of output.split(COMMIT_MARK)) {
|
|
11472
|
+
if (!block.trim()) continue;
|
|
11473
|
+
const [header, ...stat6] = block.split("\n");
|
|
11474
|
+
const [sha, parentField, epoch, email, source] = header.split("");
|
|
11475
|
+
if (!sha || !epoch) continue;
|
|
11476
|
+
const seconds = Number(epoch);
|
|
11477
|
+
if (!Number.isFinite(seconds)) continue;
|
|
11478
|
+
let files = 0;
|
|
11479
|
+
let added = 0;
|
|
11480
|
+
let removed = 0;
|
|
11481
|
+
for (const line of stat6) {
|
|
11482
|
+
const m = /^(\d+|-)\t(\d+|-)\t/.exec(line);
|
|
11483
|
+
if (!m) continue;
|
|
11484
|
+
files += 1;
|
|
11485
|
+
if (m[1] !== "-") added += Number(m[1]);
|
|
11486
|
+
if (m[2] !== "-") removed += Number(m[2]);
|
|
11487
|
+
}
|
|
11488
|
+
commits.push({
|
|
11489
|
+
sha,
|
|
11490
|
+
parents: parentField.trim() === "" ? 0 : parentField.trim().split(" ").length,
|
|
11491
|
+
at: new Date(seconds * 1e3).toISOString(),
|
|
11492
|
+
email: (email ?? "").trim().toLowerCase(),
|
|
11493
|
+
branch: source ? source.trim() : null,
|
|
11494
|
+
files,
|
|
11495
|
+
added,
|
|
11496
|
+
removed
|
|
11497
|
+
});
|
|
11498
|
+
}
|
|
11499
|
+
return commits;
|
|
11500
|
+
}
|
|
11501
|
+
async function* extractGit(repoRefs, extractionId, options = {}) {
|
|
11502
|
+
const now = options.now ?? /* @__PURE__ */ new Date();
|
|
11503
|
+
const sinceDays = options.sinceDays ?? DEFAULT_GIT_SINCE_DAYS;
|
|
11504
|
+
const since = new Date(now.getTime() - sinceDays * 864e5).toISOString();
|
|
11505
|
+
const roots = /* @__PURE__ */ new Map();
|
|
11506
|
+
let skipped = 0;
|
|
11507
|
+
for (const ref of new Set(repoRefs)) {
|
|
11508
|
+
const root = await repoRootOf(ref);
|
|
11509
|
+
if (!root) {
|
|
11510
|
+
skipped += 1;
|
|
11511
|
+
continue;
|
|
11512
|
+
}
|
|
11513
|
+
const canonical = (0, import_tool_kit7.deriveWorkContext)(root)?.projectPath ?? root;
|
|
11514
|
+
if (!roots.has(canonical)) roots.set(canonical, root);
|
|
11515
|
+
}
|
|
11516
|
+
let read = 0;
|
|
11517
|
+
let withoutIdentity = 0;
|
|
11518
|
+
let windowOldest = null;
|
|
11519
|
+
let windowNewest = null;
|
|
11520
|
+
for (const [canonical, checkout] of roots) {
|
|
11521
|
+
let me = "";
|
|
11522
|
+
try {
|
|
11523
|
+
me = (await git(checkout, ["config", "user.email"])).trim().toLowerCase();
|
|
11524
|
+
} catch {
|
|
11525
|
+
me = "";
|
|
11526
|
+
}
|
|
11527
|
+
if (!me) {
|
|
11528
|
+
withoutIdentity += 1;
|
|
11529
|
+
continue;
|
|
11530
|
+
}
|
|
11531
|
+
const { branches, defaultBranch } = await branchOrder(checkout);
|
|
11532
|
+
if (branches.length === 0) {
|
|
11533
|
+
skipped += 1;
|
|
11534
|
+
continue;
|
|
11535
|
+
}
|
|
11536
|
+
let output;
|
|
11537
|
+
try {
|
|
11538
|
+
output = await git(checkout, [
|
|
11539
|
+
"log",
|
|
11540
|
+
"--source",
|
|
11541
|
+
"--numstat",
|
|
11542
|
+
"--no-renames",
|
|
11543
|
+
`--since=${since}`,
|
|
11544
|
+
`--format=${COMMIT_MARK}%H%P%ct%ae%S`,
|
|
11545
|
+
...branches,
|
|
11546
|
+
"--"
|
|
11547
|
+
]);
|
|
11548
|
+
} catch {
|
|
11549
|
+
skipped += 1;
|
|
11550
|
+
continue;
|
|
11551
|
+
}
|
|
11552
|
+
read += 1;
|
|
11553
|
+
const fullName = (0, import_tool_kit7.repoKeysEnabled)() ? (0, import_tool_kit7.readForgeFullName)(canonical) : null;
|
|
11554
|
+
const context = (0, import_tool_kit7.deriveWorkContext)(canonical);
|
|
11555
|
+
const seen = /* @__PURE__ */ new Set();
|
|
11556
|
+
for (const commit of parseGitLog(output)) {
|
|
11557
|
+
if (seen.has(commit.sha)) continue;
|
|
11558
|
+
seen.add(commit.sha);
|
|
11559
|
+
if (commit.email !== me) continue;
|
|
11560
|
+
const isMerge = commit.parents > 1;
|
|
11561
|
+
const metrics = {
|
|
11562
|
+
activity: "git_commit",
|
|
11563
|
+
gitAction: "commit",
|
|
11564
|
+
isMergeCommit: isMerge,
|
|
11565
|
+
authoredByMe: true,
|
|
11566
|
+
filesChangedCount: commit.files,
|
|
11567
|
+
linesAddedBucket: (0, import_tool_kit7.bucketLinesChanged)(commit.added),
|
|
11568
|
+
linesRemovedBucket: (0, import_tool_kit7.bucketLinesChanged)(commit.removed),
|
|
11569
|
+
linesChangedBucket: (0, import_tool_kit7.bucketLinesChanged)(commit.added + commit.removed)
|
|
11570
|
+
};
|
|
11571
|
+
const onDefault = commit.branch !== null && commit.branch === defaultBranch;
|
|
11572
|
+
if (commit.branch && !onDefault) {
|
|
11573
|
+
if ((0, import_tool_kit7.deriveBranchHash)(commit.branch)) metrics.gitBranch = commit.branch;
|
|
11574
|
+
}
|
|
11575
|
+
if (fullName) {
|
|
11576
|
+
metrics.repoKey = (0, import_tool_kit7.forgeRepoKey)(fullName);
|
|
11577
|
+
if (commit.branch && !onDefault) metrics.branchKey = (0, import_tool_kit7.forgeBranchKey)(fullName, commit.branch);
|
|
11578
|
+
}
|
|
11579
|
+
if (!windowOldest || commit.at < windowOldest) windowOldest = commit.at;
|
|
11580
|
+
if (!windowNewest || commit.at > windowNewest) windowNewest = commit.at;
|
|
11581
|
+
yield {
|
|
11582
|
+
occurredAt: commit.at,
|
|
11583
|
+
store: "git",
|
|
11584
|
+
sourceVersion: null,
|
|
11585
|
+
// A digest of the commit id: unique per commit and stable across
|
|
11586
|
+
// runs, which is what keeps two commits in one second apart without
|
|
11587
|
+
// putting the id itself on the wire.
|
|
11588
|
+
sessionRef: "git:" + createHash2("sha256").update(commit.sha).digest("hex").slice(0, 16),
|
|
11589
|
+
repoRef: context?.projectPath ?? canonical,
|
|
11590
|
+
eventKind: "editor_activity",
|
|
11591
|
+
metrics,
|
|
11592
|
+
provenance: HISTORICAL_PROVENANCE.direct,
|
|
11593
|
+
extractionId
|
|
11594
|
+
};
|
|
11595
|
+
}
|
|
11596
|
+
}
|
|
11597
|
+
if (read > 0 || skipped > 0 || withoutIdentity > 0) {
|
|
11598
|
+
yield {
|
|
11599
|
+
occurredAt: windowNewest ?? now.toISOString(),
|
|
11600
|
+
store: "git",
|
|
11601
|
+
sourceVersion: null,
|
|
11602
|
+
sessionRef: null,
|
|
11603
|
+
repoRef: null,
|
|
11604
|
+
eventKind: "extraction_epoch",
|
|
11605
|
+
metrics: {
|
|
11606
|
+
...windowOldest && windowNewest ? { windowOldest, windowNewest } : {},
|
|
11607
|
+
gitReposRead: read,
|
|
11608
|
+
gitReposSkipped: skipped,
|
|
11609
|
+
gitReposWithoutIdentity: withoutIdentity
|
|
11610
|
+
},
|
|
11611
|
+
provenance: HISTORICAL_PROVENANCE.derived,
|
|
11612
|
+
extractionId
|
|
11613
|
+
};
|
|
11614
|
+
}
|
|
11615
|
+
}
|
|
11616
|
+
|
|
11617
|
+
// src/archive.ts
|
|
11618
|
+
var import_tool_kit8 = __toESM(require_out3(), 1);
|
|
11619
|
+
import { createHash as createHash3 } from "node:crypto";
|
|
11620
|
+
import { createReadStream as createReadStream2, existsSync } from "node:fs";
|
|
11621
|
+
import * as fs9 from "node:fs/promises";
|
|
11089
11622
|
import * as path9 from "node:path";
|
|
11090
11623
|
import { pipeline } from "node:stream/promises";
|
|
11091
11624
|
var ARCHIVE_SCHEMA = 1;
|
|
11092
11625
|
function defaultArchiveRoot(home) {
|
|
11093
|
-
return path9.join((0,
|
|
11626
|
+
return path9.join((0, import_tool_kit8.ascendaHome)(home), "history-import", "archive");
|
|
11094
11627
|
}
|
|
11095
11628
|
function defaultArchiveSources(paths, includeVsCodeSessions = false) {
|
|
11096
11629
|
const sources = [
|
|
@@ -11136,14 +11669,14 @@ function manifestDir(archiveRoot) {
|
|
|
11136
11669
|
return path9.join(archiveRoot, "manifests");
|
|
11137
11670
|
}
|
|
11138
11671
|
async function hashFile(file) {
|
|
11139
|
-
const hash =
|
|
11672
|
+
const hash = createHash3("sha256");
|
|
11140
11673
|
await pipeline(createReadStream2(file), hash);
|
|
11141
11674
|
return hash.digest("hex");
|
|
11142
11675
|
}
|
|
11143
11676
|
async function walkFiles(root) {
|
|
11144
11677
|
let st;
|
|
11145
11678
|
try {
|
|
11146
|
-
st = await
|
|
11679
|
+
st = await fs9.stat(root);
|
|
11147
11680
|
} catch {
|
|
11148
11681
|
return [];
|
|
11149
11682
|
}
|
|
@@ -11152,7 +11685,7 @@ async function walkFiles(root) {
|
|
|
11152
11685
|
async function walk(dir, prefix) {
|
|
11153
11686
|
let entries;
|
|
11154
11687
|
try {
|
|
11155
|
-
entries = await
|
|
11688
|
+
entries = await fs9.readdir(dir, { withFileTypes: true });
|
|
11156
11689
|
} catch {
|
|
11157
11690
|
return;
|
|
11158
11691
|
}
|
|
@@ -11168,14 +11701,14 @@ async function walkFiles(root) {
|
|
|
11168
11701
|
}
|
|
11169
11702
|
async function listManifests(archiveRoot) {
|
|
11170
11703
|
try {
|
|
11171
|
-
return (await
|
|
11704
|
+
return (await fs9.readdir(manifestDir(archiveRoot))).filter((f) => f.endsWith(".json")).map((f) => f.slice(0, -".json".length)).sort();
|
|
11172
11705
|
} catch {
|
|
11173
11706
|
return [];
|
|
11174
11707
|
}
|
|
11175
11708
|
}
|
|
11176
11709
|
async function readManifest(archiveRoot, generation) {
|
|
11177
11710
|
try {
|
|
11178
|
-
const raw = await
|
|
11711
|
+
const raw = await fs9.readFile(path9.join(manifestDir(archiveRoot), `${generation}.json`), "utf8");
|
|
11179
11712
|
const parsed = JSON.parse(raw);
|
|
11180
11713
|
if (parsed.schema !== ARCHIVE_SCHEMA) return null;
|
|
11181
11714
|
return parsed;
|
|
@@ -11200,8 +11733,8 @@ async function archiveStores(options) {
|
|
|
11200
11733
|
perStore: {},
|
|
11201
11734
|
unreadable: 0
|
|
11202
11735
|
};
|
|
11203
|
-
await
|
|
11204
|
-
await
|
|
11736
|
+
await fs9.mkdir(path9.join(archiveRoot, "objects"), { recursive: true });
|
|
11737
|
+
await fs9.mkdir(manifestDir(archiveRoot), { recursive: true });
|
|
11205
11738
|
const previous = await readLatestManifest(archiveRoot);
|
|
11206
11739
|
const previousByKey = /* @__PURE__ */ new Map();
|
|
11207
11740
|
for (const file of previous?.files ?? []) {
|
|
@@ -11215,7 +11748,7 @@ async function archiveStores(options) {
|
|
|
11215
11748
|
for (const suffix of source.siblings ?? []) {
|
|
11216
11749
|
const absolute = source.root + suffix;
|
|
11217
11750
|
try {
|
|
11218
|
-
await
|
|
11751
|
+
await fs9.stat(absolute);
|
|
11219
11752
|
targets.push({ absolute, relative: path9.basename(absolute) });
|
|
11220
11753
|
} catch {
|
|
11221
11754
|
}
|
|
@@ -11228,7 +11761,7 @@ async function archiveStores(options) {
|
|
|
11228
11761
|
const relativePath = `${source.label}/${target.relative}`;
|
|
11229
11762
|
let st;
|
|
11230
11763
|
try {
|
|
11231
|
-
st = await
|
|
11764
|
+
st = await fs9.stat(target.absolute);
|
|
11232
11765
|
} catch {
|
|
11233
11766
|
result.unreadable += 1;
|
|
11234
11767
|
continue;
|
|
@@ -11237,7 +11770,7 @@ async function archiveStores(options) {
|
|
|
11237
11770
|
let sha256 = null;
|
|
11238
11771
|
if (prior && prior.size === st.size && prior.mtimeMs === st.mtimeMs) {
|
|
11239
11772
|
try {
|
|
11240
|
-
await
|
|
11773
|
+
await fs9.stat(blobPath(archiveRoot, prior.sha256));
|
|
11241
11774
|
sha256 = prior.sha256;
|
|
11242
11775
|
} catch {
|
|
11243
11776
|
sha256 = null;
|
|
@@ -11254,22 +11787,22 @@ async function archiveStores(options) {
|
|
|
11254
11787
|
const destination = blobPath(archiveRoot, sha256);
|
|
11255
11788
|
let alreadyHeld = true;
|
|
11256
11789
|
try {
|
|
11257
|
-
await
|
|
11790
|
+
await fs9.stat(destination);
|
|
11258
11791
|
} catch {
|
|
11259
11792
|
alreadyHeld = false;
|
|
11260
11793
|
}
|
|
11261
11794
|
if (alreadyHeld) {
|
|
11262
11795
|
result.filesDeduplicated += 1;
|
|
11263
11796
|
} else {
|
|
11264
|
-
await
|
|
11797
|
+
await fs9.mkdir(path9.dirname(destination), { recursive: true });
|
|
11265
11798
|
const temporary2 = `${destination}.tmp-${generation}`;
|
|
11266
11799
|
try {
|
|
11267
|
-
await
|
|
11268
|
-
await
|
|
11800
|
+
await fs9.copyFile(target.absolute, temporary2);
|
|
11801
|
+
await fs9.rename(temporary2, destination);
|
|
11269
11802
|
result.newBytes += st.size;
|
|
11270
11803
|
storeStats.newBytes += st.size;
|
|
11271
11804
|
} catch {
|
|
11272
|
-
await
|
|
11805
|
+
await fs9.rm(temporary2, { force: true });
|
|
11273
11806
|
result.unreadable += 1;
|
|
11274
11807
|
continue;
|
|
11275
11808
|
}
|
|
@@ -11294,8 +11827,8 @@ async function archiveStores(options) {
|
|
|
11294
11827
|
files
|
|
11295
11828
|
};
|
|
11296
11829
|
const temporary = `${result.manifestPath}.tmp`;
|
|
11297
|
-
await
|
|
11298
|
-
await
|
|
11830
|
+
await fs9.writeFile(temporary, JSON.stringify(manifest, null, 2) + "\n", "utf8");
|
|
11831
|
+
await fs9.rename(temporary, result.manifestPath);
|
|
11299
11832
|
return result;
|
|
11300
11833
|
}
|
|
11301
11834
|
async function verifyArchive(archiveRoot, manifest, deep = true) {
|
|
@@ -11305,7 +11838,7 @@ async function verifyArchive(archiveRoot, manifest, deep = true) {
|
|
|
11305
11838
|
const blob = blobPath(archiveRoot, file.sha256);
|
|
11306
11839
|
result.checked += 1;
|
|
11307
11840
|
try {
|
|
11308
|
-
await
|
|
11841
|
+
await fs9.stat(blob);
|
|
11309
11842
|
} catch {
|
|
11310
11843
|
result.missing.push(file.relativePath);
|
|
11311
11844
|
continue;
|
|
@@ -11329,8 +11862,8 @@ async function restoreArchive(archiveRoot, manifest, destination) {
|
|
|
11329
11862
|
const blob = blobPath(archiveRoot, file.sha256);
|
|
11330
11863
|
const target = path9.join(destination, file.store, file.relativePath);
|
|
11331
11864
|
try {
|
|
11332
|
-
await
|
|
11333
|
-
await
|
|
11865
|
+
await fs9.mkdir(path9.dirname(target), { recursive: true });
|
|
11866
|
+
await fs9.copyFile(blob, target);
|
|
11334
11867
|
result.restored += 1;
|
|
11335
11868
|
} catch {
|
|
11336
11869
|
result.skipped += 1;
|
|
@@ -11344,7 +11877,7 @@ async function pruneArchive(archiveRoot, keep) {
|
|
|
11344
11877
|
const doomed = keep >= generations.length ? [] : generations.slice(0, generations.length - keep);
|
|
11345
11878
|
for (const generation of doomed) {
|
|
11346
11879
|
try {
|
|
11347
|
-
await
|
|
11880
|
+
await fs9.rm(path9.join(manifestDir(archiveRoot), `${generation}.json`), { force: true });
|
|
11348
11881
|
result.generationsRemoved.push(generation);
|
|
11349
11882
|
} catch {
|
|
11350
11883
|
}
|
|
@@ -11357,14 +11890,14 @@ async function pruneArchive(archiveRoot, keep) {
|
|
|
11357
11890
|
const objectsRoot = path9.join(archiveRoot, "objects");
|
|
11358
11891
|
let shards = [];
|
|
11359
11892
|
try {
|
|
11360
|
-
shards = (await
|
|
11893
|
+
shards = (await fs9.readdir(objectsRoot, { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name);
|
|
11361
11894
|
} catch {
|
|
11362
11895
|
return result;
|
|
11363
11896
|
}
|
|
11364
11897
|
for (const shard of shards) {
|
|
11365
11898
|
let blobs = [];
|
|
11366
11899
|
try {
|
|
11367
|
-
blobs = await
|
|
11900
|
+
blobs = await fs9.readdir(path9.join(objectsRoot, shard));
|
|
11368
11901
|
} catch {
|
|
11369
11902
|
continue;
|
|
11370
11903
|
}
|
|
@@ -11373,12 +11906,12 @@ async function pruneArchive(archiveRoot, keep) {
|
|
|
11373
11906
|
const target = path9.join(objectsRoot, shard, blob);
|
|
11374
11907
|
let size = 0;
|
|
11375
11908
|
try {
|
|
11376
|
-
size = (await
|
|
11909
|
+
size = (await fs9.stat(target)).size;
|
|
11377
11910
|
} catch {
|
|
11378
11911
|
continue;
|
|
11379
11912
|
}
|
|
11380
11913
|
try {
|
|
11381
|
-
await
|
|
11914
|
+
await fs9.rm(target, { force: true });
|
|
11382
11915
|
result.blobsRemoved += 1;
|
|
11383
11916
|
result.freedBytes += size;
|
|
11384
11917
|
} catch {
|
|
@@ -11392,20 +11925,20 @@ async function archiveSizeBytes(archiveRoot) {
|
|
|
11392
11925
|
let total = 0;
|
|
11393
11926
|
let shards = [];
|
|
11394
11927
|
try {
|
|
11395
|
-
shards = (await
|
|
11928
|
+
shards = (await fs9.readdir(objectsRoot, { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name);
|
|
11396
11929
|
} catch {
|
|
11397
11930
|
return 0;
|
|
11398
11931
|
}
|
|
11399
11932
|
for (const shard of shards) {
|
|
11400
11933
|
let blobs = [];
|
|
11401
11934
|
try {
|
|
11402
|
-
blobs = await
|
|
11935
|
+
blobs = await fs9.readdir(path9.join(objectsRoot, shard));
|
|
11403
11936
|
} catch {
|
|
11404
11937
|
continue;
|
|
11405
11938
|
}
|
|
11406
11939
|
for (const blob of blobs) {
|
|
11407
11940
|
try {
|
|
11408
|
-
total += (await
|
|
11941
|
+
total += (await fs9.stat(path9.join(objectsRoot, shard, blob))).size;
|
|
11409
11942
|
} catch {
|
|
11410
11943
|
}
|
|
11411
11944
|
}
|
|
@@ -11414,25 +11947,111 @@ async function archiveSizeBytes(archiveRoot) {
|
|
|
11414
11947
|
}
|
|
11415
11948
|
|
|
11416
11949
|
// src/ship.ts
|
|
11417
|
-
var
|
|
11418
|
-
import { createHash as
|
|
11950
|
+
var import_tool_kit10 = __toESM(require_out3(), 1);
|
|
11951
|
+
import { createHash as createHash4 } from "node:crypto";
|
|
11952
|
+
|
|
11953
|
+
// src/credentials.ts
|
|
11954
|
+
var import_tool_kit9 = __toESM(require_out3(), 1);
|
|
11419
11955
|
var DEFAULT_API_BASE_URL = "https://api.ascenda.one";
|
|
11420
|
-
|
|
11421
|
-
|
|
11422
|
-
|
|
11423
|
-
|
|
11424
|
-
|
|
11425
|
-
|
|
11956
|
+
var ShipConfigError = class extends Error {
|
|
11957
|
+
constructor(message) {
|
|
11958
|
+
super(message);
|
|
11959
|
+
this.name = "ShipConfigError";
|
|
11960
|
+
}
|
|
11961
|
+
};
|
|
11962
|
+
function pairCommand(toolInstallationId) {
|
|
11963
|
+
const type = toolInstallationId.split(":")[0];
|
|
11964
|
+
return type === "claude_code" ? "npx @ascenda-one/claude-code-hooks pair" : `npx @ascenda-one/claude-code-hooks pair --tool-type ${type}`;
|
|
11965
|
+
}
|
|
11966
|
+
function normalizeId(raw) {
|
|
11967
|
+
const id = raw.trim();
|
|
11968
|
+
return id.includes(":") ? id : `claude_code:${id}`;
|
|
11969
|
+
}
|
|
11970
|
+
var SETUP_HINT = "Run: npx @ascenda-one/claude-code-hooks setup";
|
|
11971
|
+
function resolveInstallationId(flags) {
|
|
11972
|
+
if (flags.installationId?.trim()) return { id: normalizeId(flags.installationId), source: "flag" };
|
|
11973
|
+
const fromEnv = process.env.ASCENDA_TOOL_INSTALLATION_ID?.trim();
|
|
11974
|
+
if (fromEnv) return { id: normalizeId(fromEnv), source: "env" };
|
|
11975
|
+
const credentials = (0, import_tool_kit9.readMachineCredentials)();
|
|
11976
|
+
const top = credentials?.toolInstallationId?.trim();
|
|
11977
|
+
if (top && !credentials?.localOnly) return { id: normalizeId(top), source: "credentials" };
|
|
11978
|
+
const hostIds = Object.keys(credentials?.tools ?? {}).map((host) => (0, import_tool_kit9.readHostCredentials)(host)?.toolInstallationId?.trim()).filter((id) => Boolean(id) && Boolean((0, import_tool_kit9.readTokenFile)((0, import_tool_kit9.defaultTokenFilePath)(id))));
|
|
11979
|
+
if (hostIds.length === 1) return { id: normalizeId(hostIds[0]), source: "credentials" };
|
|
11980
|
+
if (hostIds.length > 1) {
|
|
11981
|
+
throw new ShipConfigError(
|
|
11982
|
+
`${hostIds.length} paired tools in ~/.ascenda/credentials.json (${hostIds.join(", ")}) and no way to choose. Pass --installation-id <id> or set ASCENDA_TOOL_INSTALLATION_ID.`
|
|
11426
11983
|
);
|
|
11427
11984
|
}
|
|
11428
|
-
const
|
|
11429
|
-
|
|
11430
|
-
|
|
11985
|
+
const onDisk = (0, import_tool_kit9.listPersistedToolInstallationIds)("claude_code");
|
|
11986
|
+
if (onDisk.length === 1) return { id: onDisk[0], source: "disk" };
|
|
11987
|
+
if (onDisk.length > 1) {
|
|
11988
|
+
throw new ShipConfigError(
|
|
11989
|
+
`${onDisk.length} claude_code tokens in ${(0, import_tool_kit9.ascendaHome)()}/tokens (${onDisk.join(", ")}). Pass --installation-id <id> to choose one.`
|
|
11990
|
+
);
|
|
11991
|
+
}
|
|
11992
|
+
if (credentials?.localOnly) {
|
|
11993
|
+
throw new ShipConfigError(
|
|
11994
|
+
`This machine was set up without pairing (local only), so there is nothing to ship as. Pair it first: ${pairCommand("claude_code:x")}`
|
|
11995
|
+
);
|
|
11996
|
+
}
|
|
11997
|
+
throw new ShipConfigError(
|
|
11998
|
+
`No paired tool found: no --installation-id, no ASCENDA_TOOL_INSTALLATION_ID, nothing in ${(0, import_tool_kit9.ascendaHome)()}/credentials.json and no token in ${(0, import_tool_kit9.ascendaHome)()}/tokens. ${SETUP_HINT}`
|
|
11999
|
+
);
|
|
12000
|
+
}
|
|
12001
|
+
function loadShipConfig(flags = {}) {
|
|
12002
|
+
const { id: toolInstallationId } = resolveInstallationId(flags);
|
|
12003
|
+
const credentials = (0, import_tool_kit9.readMachineCredentials)();
|
|
12004
|
+
const apiBaseUrl = (flags.apiBaseUrl ?? process.env.ASCENDA_API_BASE_URL ?? credentials?.apiBaseUrl ?? DEFAULT_API_BASE_URL).replace(/\/$/, "");
|
|
12005
|
+
const tokenFilePath = flags.tokenFile ?? process.env.ASCENDA_EVENT_WRITE_TOKEN_FILE ?? (0, import_tool_kit9.defaultTokenFilePath)(toolInstallationId);
|
|
12006
|
+
const eventWriteToken = (0, import_tool_kit9.readTokenFile)(tokenFilePath) ?? process.env.ASCENDA_EVENT_WRITE_TOKEN?.trim();
|
|
11431
12007
|
if (!eventWriteToken) {
|
|
11432
|
-
throw new
|
|
12008
|
+
throw new ShipConfigError(
|
|
12009
|
+
`No event write token for ${toolInstallationId}: nothing at ${tokenFilePath} and ASCENDA_EVENT_WRITE_TOKEN is unset. Pair it: ${pairCommand(toolInstallationId)}`
|
|
12010
|
+
);
|
|
11433
12011
|
}
|
|
11434
|
-
return {
|
|
12012
|
+
return {
|
|
12013
|
+
apiBaseUrl,
|
|
12014
|
+
toolInstallationId,
|
|
12015
|
+
eventWriteToken,
|
|
12016
|
+
...(0, import_tool_kit9.readTokenFile)(tokenFilePath) ? { tokenFilePath } : {}
|
|
12017
|
+
};
|
|
11435
12018
|
}
|
|
12019
|
+
async function prepareToken(config, options = {}) {
|
|
12020
|
+
const now = options.now ?? Date.now;
|
|
12021
|
+
const lead = options.leadMs ?? import_tool_kit9.TOKEN_RENEW_LEAD_MS;
|
|
12022
|
+
if (!config.tokenFilePath) return { config, note: null };
|
|
12023
|
+
const expiresAt = (0, import_tool_kit9.readTokenExpiry)(config.tokenFilePath);
|
|
12024
|
+
if (expiresAt === void 0) return { config, note: null };
|
|
12025
|
+
if (now() >= expiresAt) {
|
|
12026
|
+
throw new ShipConfigError(
|
|
12027
|
+
`The event token for ${config.toolInstallationId} expired on ${new Date(expiresAt).toISOString().slice(0, 10)}, and an expired token can't renew itself. Pair again: ${pairCommand(config.toolInstallationId)}`
|
|
12028
|
+
);
|
|
12029
|
+
}
|
|
12030
|
+
if (now() < expiresAt - lead) return { config, note: null };
|
|
12031
|
+
const renew = options.renew ?? import_tool_kit9.renewToolToken;
|
|
12032
|
+
try {
|
|
12033
|
+
const renewed = await renew(config.apiBaseUrl, config.eventWriteToken, AbortSignal.timeout(15e3));
|
|
12034
|
+
if (!renewed) {
|
|
12035
|
+
const onDisk = (0, import_tool_kit9.readTokenFile)(config.tokenFilePath);
|
|
12036
|
+
if (onDisk && onDisk !== config.eventWriteToken) {
|
|
12037
|
+
return { config: { ...config, eventWriteToken: onDisk }, note: "token already renewed by another process" };
|
|
12038
|
+
}
|
|
12039
|
+
throw new ShipConfigError(
|
|
12040
|
+
`The server rejected the event token for ${config.toolInstallationId} when renewing it. Pair again: ${pairCommand(config.toolInstallationId)}`
|
|
12041
|
+
);
|
|
12042
|
+
}
|
|
12043
|
+
(0, import_tool_kit9.persistEventWriteToken)(config.tokenFilePath, renewed.eventWriteToken, renewed.expiresAt);
|
|
12044
|
+
return {
|
|
12045
|
+
config: { ...config, eventWriteToken: renewed.eventWriteToken },
|
|
12046
|
+
note: `renewed the event token (now valid until ${renewed.expiresAt.slice(0, 10)})`
|
|
12047
|
+
};
|
|
12048
|
+
} catch (error) {
|
|
12049
|
+
if (error instanceof ShipConfigError) throw error;
|
|
12050
|
+
return { config, note: "couldn't renew the event token (server unreachable); using the current one" };
|
|
12051
|
+
}
|
|
12052
|
+
}
|
|
12053
|
+
|
|
12054
|
+
// src/ship.ts
|
|
11436
12055
|
function importOrdinals(events) {
|
|
11437
12056
|
const seen = /* @__PURE__ */ new Map();
|
|
11438
12057
|
return events.map((event) => {
|
|
@@ -11445,7 +12064,7 @@ function importOrdinals(events) {
|
|
|
11445
12064
|
});
|
|
11446
12065
|
}
|
|
11447
12066
|
function importKeyOf(event, ordinal) {
|
|
11448
|
-
return
|
|
12067
|
+
return createHash4("sha256").update(
|
|
11449
12068
|
[event.store, event.sessionRef ?? "", event.eventKind, event.occurredAt, String(ordinal)].join(
|
|
11450
12069
|
"|"
|
|
11451
12070
|
)
|
|
@@ -11456,12 +12075,12 @@ function workContextOf(repoRef) {
|
|
|
11456
12075
|
if (!repoRef) return null;
|
|
11457
12076
|
const hit = workContextMemo.get(repoRef);
|
|
11458
12077
|
if (hit !== void 0) return hit;
|
|
11459
|
-
const context = (0,
|
|
12078
|
+
const context = (0, import_tool_kit10.deriveWorkContext)(repoRef);
|
|
11460
12079
|
if (context) {
|
|
11461
|
-
(0,
|
|
11462
|
-
const legacyHash = (0,
|
|
12080
|
+
(0, import_tool_kit10.recordWorkContext)(context);
|
|
12081
|
+
const legacyHash = (0, import_tool_kit10.hashWithMachineSalt)(repoRef);
|
|
11463
12082
|
if (legacyHash && legacyHash !== context.workspaceHash && legacyHash !== context.projectHash) {
|
|
11464
|
-
(0,
|
|
12083
|
+
(0, import_tool_kit10.recordWorkContextAlias)(legacyHash, context.workspaceLabel ?? repoRef, context.workspacePath);
|
|
11465
12084
|
}
|
|
11466
12085
|
}
|
|
11467
12086
|
workContextMemo.set(repoRef, context);
|
|
@@ -11471,8 +12090,8 @@ var legacyBranchDigestsSeen = /* @__PURE__ */ new Set();
|
|
|
11471
12090
|
function registerLegacyBranchDigest(rawBranch, branchHash) {
|
|
11472
12091
|
if (legacyBranchDigestsSeen.has(rawBranch)) return;
|
|
11473
12092
|
legacyBranchDigestsSeen.add(rawBranch);
|
|
11474
|
-
const legacyHash = (0,
|
|
11475
|
-
if (legacyHash && legacyHash !== branchHash) (0,
|
|
12093
|
+
const legacyHash = (0, import_tool_kit10.hashWithMachineSalt)(rawBranch);
|
|
12094
|
+
if (legacyHash && legacyHash !== branchHash) (0, import_tool_kit10.recordWorkContextAlias)(legacyHash, rawBranch);
|
|
11476
12095
|
}
|
|
11477
12096
|
function toWirePayload(event, ordinal, toolInstallationId) {
|
|
11478
12097
|
const metadata = {
|
|
@@ -11482,7 +12101,7 @@ function toWirePayload(event, ordinal, toolInstallationId) {
|
|
|
11482
12101
|
// The importer build that shipped this row. Extractors gain metrics from
|
|
11483
12102
|
// release to release, so a metric missing from an older import is a fact
|
|
11484
12103
|
// about the build that read the store, and this is how a reader knows.
|
|
11485
|
-
collectorVersion:
|
|
12104
|
+
collectorVersion: import_tool_kit10.COLLECTOR_VERSION
|
|
11486
12105
|
};
|
|
11487
12106
|
if (event.sourceVersion) metadata.sourceVersion = event.sourceVersion;
|
|
11488
12107
|
const host = STORE_HOST[event.store];
|
|
@@ -11493,13 +12112,13 @@ function toWirePayload(event, ordinal, toolInstallationId) {
|
|
|
11493
12112
|
if (typeof metadata.gitBranch === "string") {
|
|
11494
12113
|
const rawBranch = metadata.gitBranch;
|
|
11495
12114
|
delete metadata.gitBranch;
|
|
11496
|
-
const branchHash = (0,
|
|
12115
|
+
const branchHash = (0, import_tool_kit10.deriveBranchHash)(rawBranch);
|
|
11497
12116
|
if (branchHash) {
|
|
11498
12117
|
metadata.branchHash = branchHash;
|
|
11499
12118
|
registerLegacyBranchDigest(rawBranch, branchHash);
|
|
11500
12119
|
}
|
|
11501
12120
|
}
|
|
11502
|
-
const modelClass = (0,
|
|
12121
|
+
const modelClass = (0, import_tool_kit10.classifyModelClass)(metadata.primaryModel);
|
|
11503
12122
|
if (modelClass !== void 0) metadata.modelClass = modelClass;
|
|
11504
12123
|
const context = workContextOf(event.repoRef);
|
|
11505
12124
|
return {
|
|
@@ -11514,7 +12133,7 @@ function toWirePayload(event, ordinal, toolInstallationId) {
|
|
|
11514
12133
|
// The offset in force WHEN THE EVENT HAPPENED, not when the import ran.
|
|
11515
12134
|
// A nine-month backfill crosses DST boundaries; stamping today's
|
|
11516
12135
|
// offset on all of it would shift a whole season by an hour.
|
|
11517
|
-
utcOffsetMinutes: (0,
|
|
12136
|
+
utcOffsetMinutes: (0, import_tool_kit10.utcOffsetMinutesAt)(new Date(event.occurredAt)),
|
|
11518
12137
|
severity: "low",
|
|
11519
12138
|
sessionId: event.sessionRef,
|
|
11520
12139
|
workspaceHash: context?.workspaceHash ?? null,
|
|
@@ -11552,10 +12171,18 @@ async function shipEvents(events, config, onProgress) {
|
|
|
11552
12171
|
};
|
|
11553
12172
|
const wireEvents = shippableEvents(events);
|
|
11554
12173
|
const ordinals = importOrdinals(wireEvents);
|
|
12174
|
+
const notGranted = /* @__PURE__ */ new Set();
|
|
11555
12175
|
for (let offset = 0; offset < wireEvents.length; offset += BATCH_SIZE) {
|
|
11556
|
-
const
|
|
12176
|
+
const slice = wireEvents.slice(offset, offset + BATCH_SIZE);
|
|
12177
|
+
const keep = slice.map((event) => !notGranted.has(event.store));
|
|
12178
|
+
const chunk = slice.filter((_, i) => keep[i]);
|
|
12179
|
+
if (chunk.length === 0) {
|
|
12180
|
+
onProgress?.(Math.min(offset + BATCH_SIZE, wireEvents.length), wireEvents.length);
|
|
12181
|
+
continue;
|
|
12182
|
+
}
|
|
12183
|
+
const chunkOrdinals = ordinals.slice(offset, offset + BATCH_SIZE).filter((_, i) => keep[i]);
|
|
11557
12184
|
const payloads = chunk.map(
|
|
11558
|
-
(event, i) => toWirePayload(event,
|
|
12185
|
+
(event, i) => toWirePayload(event, chunkOrdinals[i], config.toolInstallationId)
|
|
11559
12186
|
);
|
|
11560
12187
|
let response;
|
|
11561
12188
|
try {
|
|
@@ -11607,6 +12234,15 @@ async function shipEvents(events, config, onProgress) {
|
|
|
11607
12234
|
result.rejectionReasons[reason] = (result.rejectionReasons[reason] ?? 0) + 1;
|
|
11608
12235
|
}
|
|
11609
12236
|
}
|
|
12237
|
+
if (attributable) {
|
|
12238
|
+
for (const store of new Set(chunk.map((event) => event.store))) {
|
|
12239
|
+
const mine = items.filter((_, i) => chunk[i].store === store);
|
|
12240
|
+
if (mine.every((item) => item.status === "rejected" && item.reason === "consent_source_not_granted")) {
|
|
12241
|
+
notGranted.add(store);
|
|
12242
|
+
result.storesNotGranted = [...notGranted];
|
|
12243
|
+
}
|
|
12244
|
+
}
|
|
12245
|
+
}
|
|
11610
12246
|
if (items.length === chunk.length && items.length > 0) {
|
|
11611
12247
|
const blocked = items.every(
|
|
11612
12248
|
(item) => item.status !== "accepted" && item.status !== "duplicate" && (item.reason === "consent_missing_or_expired" || item.reason === "unknown_consent_scope")
|
|
@@ -11627,8 +12263,793 @@ async function shipEvents(events, config, onProgress) {
|
|
|
11627
12263
|
return result;
|
|
11628
12264
|
}
|
|
11629
12265
|
|
|
12266
|
+
// src/schedule.ts
|
|
12267
|
+
import * as fs10 from "node:fs/promises";
|
|
12268
|
+
import * as os2 from "node:os";
|
|
12269
|
+
import * as path10 from "node:path";
|
|
12270
|
+
import { spawn } from "node:child_process";
|
|
12271
|
+
var DEFAULT_INTERVAL_DAYS = 14;
|
|
12272
|
+
var MAX_INTERVAL_DAYS = 90;
|
|
12273
|
+
var RUNS_OF_HEADROOM = 2;
|
|
12274
|
+
var LAUNCHD_LABEL = "one.ascenda.history-import";
|
|
12275
|
+
var SYSTEMD_UNIT = "ascenda-history-import";
|
|
12276
|
+
function platformOf(value = process.platform) {
|
|
12277
|
+
return value === "darwin" || value === "linux" || value === "win32" ? value : "other";
|
|
12278
|
+
}
|
|
12279
|
+
function parseInterval(raw) {
|
|
12280
|
+
const match = /^(\d{1,3})d?$/i.exec(raw.trim());
|
|
12281
|
+
const days = match ? Number(match[1]) : NaN;
|
|
12282
|
+
if (!Number.isInteger(days) || days < 1 || days > MAX_INTERVAL_DAYS) {
|
|
12283
|
+
throw new Error(`--every needs whole days between 1 and ${MAX_INTERVAL_DAYS}, like 14d (got "${raw}")`);
|
|
12284
|
+
}
|
|
12285
|
+
return days;
|
|
12286
|
+
}
|
|
12287
|
+
function checkRetention(plan, everyDays) {
|
|
12288
|
+
const effective = plan.currentCleanupPeriodDays ?? 30;
|
|
12289
|
+
if (effective >= everyDays * RUNS_OF_HEADROOM) return { ok: true };
|
|
12290
|
+
const label = plan.currentCleanupPeriodDays === null ? "30 days (the default)" : `${effective} days`;
|
|
12291
|
+
return {
|
|
12292
|
+
ok: false,
|
|
12293
|
+
reason: `Claude Code deletes transcripts after ${label} (cleanupPeriodDays), too soon for a run every ${everyDays} days. Run \`ascenda-history-import fix-retention --apply\` first, or pass --override-retention.`
|
|
12294
|
+
};
|
|
12295
|
+
}
|
|
12296
|
+
function scheduledCommand(entry = process.argv[1] ?? "", node = process.execPath, env = process.env) {
|
|
12297
|
+
const pinned = {};
|
|
12298
|
+
if (env.ASCENDA_HOME) pinned.ASCENDA_HOME = env.ASCENDA_HOME;
|
|
12299
|
+
if (env.ASCENDA_API_BASE_URL) pinned.ASCENDA_API_BASE_URL = env.ASCENDA_API_BASE_URL;
|
|
12300
|
+
const inNpxCache = entry.split(path10.sep).includes("_npx");
|
|
12301
|
+
if (inNpxCache || !entry) {
|
|
12302
|
+
return { argv: [path10.join(path10.dirname(node), "npx"), "-y", "@ascenda-one/history-import", "import", "--ship"], env: pinned };
|
|
12303
|
+
}
|
|
12304
|
+
return { argv: [node, entry, "import", "--ship"], env: pinned };
|
|
12305
|
+
}
|
|
12306
|
+
var xml = (value) => value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
12307
|
+
function launchdPlist(input) {
|
|
12308
|
+
const args = input.command.argv.map((a) => ` <string>${xml(a)}</string>`).join("\n");
|
|
12309
|
+
const env = { PATH: input.pathEnv, ...input.command.env };
|
|
12310
|
+
const envLines = Object.entries(env).map(([k, v]) => ` <key>${xml(k)}</key>
|
|
12311
|
+
<string>${xml(v)}</string>`).join("\n");
|
|
12312
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
12313
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
12314
|
+
<plist version="1.0">
|
|
12315
|
+
<dict>
|
|
12316
|
+
<key>Label</key>
|
|
12317
|
+
<string>${LAUNCHD_LABEL}</string>
|
|
12318
|
+
<key>ProgramArguments</key>
|
|
12319
|
+
<array>
|
|
12320
|
+
${args}
|
|
12321
|
+
</array>
|
|
12322
|
+
<key>StartInterval</key>
|
|
12323
|
+
<integer>${input.everyDays * 86400}</integer>
|
|
12324
|
+
<key>RunAtLoad</key>
|
|
12325
|
+
<false/>
|
|
12326
|
+
<key>EnvironmentVariables</key>
|
|
12327
|
+
<dict>
|
|
12328
|
+
${envLines}
|
|
12329
|
+
</dict>
|
|
12330
|
+
<key>StandardOutPath</key>
|
|
12331
|
+
<string>${xml(input.logFile)}</string>
|
|
12332
|
+
<key>StandardErrorPath</key>
|
|
12333
|
+
<string>${xml(input.logFile)}</string>
|
|
12334
|
+
</dict>
|
|
12335
|
+
</plist>
|
|
12336
|
+
`;
|
|
12337
|
+
}
|
|
12338
|
+
var shellQuote = (value) => /^[A-Za-z0-9_\/.:@=+-]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\''`)}'`;
|
|
12339
|
+
function systemdService(input) {
|
|
12340
|
+
const exec = input.command.argv.map(shellQuote).join(" ");
|
|
12341
|
+
const env = Object.entries(input.command.env).map(([k, v]) => `Environment=${k}=${v}
|
|
12342
|
+
`).join("");
|
|
12343
|
+
return `[Unit]
|
|
12344
|
+
Description=Ascenda history import (ships new AI-usage history)
|
|
12345
|
+
|
|
12346
|
+
[Service]
|
|
12347
|
+
Type=oneshot
|
|
12348
|
+
${env}ExecStart=${exec}
|
|
12349
|
+
StandardOutput=append:${input.logFile}
|
|
12350
|
+
StandardError=append:${input.logFile}
|
|
12351
|
+
`;
|
|
12352
|
+
}
|
|
12353
|
+
function systemdTimer(input) {
|
|
12354
|
+
return `[Unit]
|
|
12355
|
+
Description=Run the Ascenda history import every ${input.everyDays} days
|
|
12356
|
+
|
|
12357
|
+
[Timer]
|
|
12358
|
+
OnBootSec=1h
|
|
12359
|
+
OnUnitActiveSec=${input.everyDays}d
|
|
12360
|
+
Persistent=true
|
|
12361
|
+
|
|
12362
|
+
[Install]
|
|
12363
|
+
WantedBy=timers.target
|
|
12364
|
+
`;
|
|
12365
|
+
}
|
|
12366
|
+
function schtasksCommand(command, everyDays) {
|
|
12367
|
+
const run = command.argv.map((a) => /\s/.test(a) ? `\\"${a}\\"` : a).join(" ");
|
|
12368
|
+
return `schtasks /Create /TN "Ascenda history import" /SC DAILY /MO ${everyDays} /ST 09:00 /TR "${run}"`;
|
|
12369
|
+
}
|
|
12370
|
+
function defaultScheduleEnv() {
|
|
12371
|
+
return {
|
|
12372
|
+
platform: platformOf(),
|
|
12373
|
+
home: os2.homedir(),
|
|
12374
|
+
uid: typeof process.getuid === "function" ? process.getuid() : 0,
|
|
12375
|
+
run: (argv) => new Promise((resolve3) => {
|
|
12376
|
+
const child = spawn(argv[0], argv.slice(1), { stdio: ["ignore", "pipe", "pipe"] });
|
|
12377
|
+
let stdout = "";
|
|
12378
|
+
child.stdout.on("data", (d) => stdout += d);
|
|
12379
|
+
child.on("error", () => resolve3({ code: 127, stdout }));
|
|
12380
|
+
child.on("close", (code) => resolve3({ code: code ?? 1, stdout }));
|
|
12381
|
+
})
|
|
12382
|
+
};
|
|
12383
|
+
}
|
|
12384
|
+
function scheduleFiles(env) {
|
|
12385
|
+
const log = path10.join(env.home, ".ascenda", "logs", "history-import.log");
|
|
12386
|
+
if (env.platform === "darwin") {
|
|
12387
|
+
return { files: [path10.join(env.home, "Library", "LaunchAgents", `${LAUNCHD_LABEL}.plist`)], log };
|
|
12388
|
+
}
|
|
12389
|
+
const dir = path10.join(env.home, ".config", "systemd", "user");
|
|
12390
|
+
return { files: [path10.join(dir, `${SYSTEMD_UNIT}.service`), path10.join(dir, `${SYSTEMD_UNIT}.timer`)], log };
|
|
12391
|
+
}
|
|
12392
|
+
async function installSchedule(env, options) {
|
|
12393
|
+
if (env.platform === "win32") {
|
|
12394
|
+
return { written: [], printed: schtasksCommand(options.command, options.everyDays), activated: false };
|
|
12395
|
+
}
|
|
12396
|
+
if (env.platform === "other") throw new Error("Scheduling is supported on macOS, Linux and (as a printed command) Windows.");
|
|
12397
|
+
const { files, log } = scheduleFiles(env);
|
|
12398
|
+
await fs10.mkdir(path10.dirname(log), { recursive: true });
|
|
12399
|
+
for (const file of files) await fs10.mkdir(path10.dirname(file), { recursive: true });
|
|
12400
|
+
if (env.platform === "darwin") {
|
|
12401
|
+
await fs10.writeFile(
|
|
12402
|
+
files[0],
|
|
12403
|
+
launchdPlist({ command: options.command, everyDays: options.everyDays, logFile: log, pathEnv: options.pathEnv ?? "/usr/local/bin:/usr/bin:/bin" })
|
|
12404
|
+
);
|
|
12405
|
+
const domain = `gui/${env.uid}`;
|
|
12406
|
+
await env.run(["launchctl", "bootout", `${domain}/${LAUNCHD_LABEL}`]);
|
|
12407
|
+
const loaded = await env.run(["launchctl", "bootstrap", domain, files[0]]);
|
|
12408
|
+
return { written: files, activated: loaded.code === 0 };
|
|
12409
|
+
}
|
|
12410
|
+
await fs10.writeFile(files[0], systemdService({ command: options.command, logFile: log }));
|
|
12411
|
+
await fs10.writeFile(files[1], systemdTimer({ everyDays: options.everyDays }));
|
|
12412
|
+
await env.run(["systemctl", "--user", "daemon-reload"]);
|
|
12413
|
+
const enabled = await env.run(["systemctl", "--user", "enable", "--now", `${SYSTEMD_UNIT}.timer`]);
|
|
12414
|
+
return { written: files, activated: enabled.code === 0 };
|
|
12415
|
+
}
|
|
12416
|
+
async function removeSchedule(env) {
|
|
12417
|
+
if (env.platform === "win32") return { removed: [] };
|
|
12418
|
+
const { files } = scheduleFiles(env);
|
|
12419
|
+
if (env.platform === "darwin") {
|
|
12420
|
+
await env.run(["launchctl", "bootout", `gui/${env.uid}/${LAUNCHD_LABEL}`]);
|
|
12421
|
+
} else {
|
|
12422
|
+
await env.run(["systemctl", "--user", "disable", "--now", `${SYSTEMD_UNIT}.timer`]);
|
|
12423
|
+
}
|
|
12424
|
+
const removed = [];
|
|
12425
|
+
for (const file of files) {
|
|
12426
|
+
try {
|
|
12427
|
+
await fs10.rm(file);
|
|
12428
|
+
removed.push(file);
|
|
12429
|
+
} catch {
|
|
12430
|
+
}
|
|
12431
|
+
}
|
|
12432
|
+
if (env.platform === "linux") await env.run(["systemctl", "--user", "daemon-reload"]);
|
|
12433
|
+
return { removed };
|
|
12434
|
+
}
|
|
12435
|
+
async function scheduleStatus(env) {
|
|
12436
|
+
const { files, log } = scheduleFiles(env);
|
|
12437
|
+
const present = [];
|
|
12438
|
+
for (const file of files) {
|
|
12439
|
+
try {
|
|
12440
|
+
await fs10.access(file);
|
|
12441
|
+
present.push(file);
|
|
12442
|
+
} catch {
|
|
12443
|
+
}
|
|
12444
|
+
}
|
|
12445
|
+
if (present.length === 0) return { installed: false, files: [], everyDays: null, active: null, log };
|
|
12446
|
+
let everyDays = null;
|
|
12447
|
+
const text = await fs10.readFile(present.find((f) => f.endsWith(".plist") || f.endsWith(".timer")) ?? present[0], "utf8");
|
|
12448
|
+
const seconds = /<key>StartInterval<\/key>\s*<integer>(\d+)<\/integer>/.exec(text);
|
|
12449
|
+
const timer = /OnUnitActiveSec=(\d+)d/.exec(text);
|
|
12450
|
+
if (seconds) everyDays = Number(seconds[1]) / 86400;
|
|
12451
|
+
else if (timer) everyDays = Number(timer[1]);
|
|
12452
|
+
const probe = env.platform === "darwin" ? await env.run(["launchctl", "print", `gui/${env.uid}/${LAUNCHD_LABEL}`]) : await env.run(["systemctl", "--user", "is-active", `${SYSTEMD_UNIT}.timer`]);
|
|
12453
|
+
return { installed: true, files: present, everyDays, active: probe.code === 0, log };
|
|
12454
|
+
}
|
|
12455
|
+
|
|
12456
|
+
// src/participate.ts
|
|
12457
|
+
var import_tool_kit11 = __toESM(require_out3(), 1);
|
|
12458
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
12459
|
+
import * as fs11 from "node:fs";
|
|
12460
|
+
import * as os3 from "node:os";
|
|
12461
|
+
import * as path11 from "node:path";
|
|
12462
|
+
import * as readline from "node:readline";
|
|
12463
|
+
var HISTORICAL_IMPORT_GRANT = 507;
|
|
12464
|
+
var PARTICIPATE_AGENTS = [
|
|
12465
|
+
{
|
|
12466
|
+
id: "claude_code",
|
|
12467
|
+
displayName: "Claude Code",
|
|
12468
|
+
packageName: "@ascenda-one/claude-code-hooks",
|
|
12469
|
+
workspaceDir: "ascenda-claude-code-hooks",
|
|
12470
|
+
credentialsKey: null,
|
|
12471
|
+
configDirs: (home, env) => claudeConfigDirsOf(home, env).map((dirs) => dirs.configDir),
|
|
12472
|
+
binaries: ["claude"]
|
|
12473
|
+
},
|
|
12474
|
+
{
|
|
12475
|
+
id: "codex",
|
|
12476
|
+
displayName: "Codex CLI",
|
|
12477
|
+
packageName: "@ascenda-one/codex-hooks",
|
|
12478
|
+
workspaceDir: "ascenda-codex-hooks",
|
|
12479
|
+
credentialsKey: "codex",
|
|
12480
|
+
configDirs: (home, env) => [codexHomeOf(home, env)],
|
|
12481
|
+
binaries: ["codex"],
|
|
12482
|
+
afterPairing: "Codex runs them only once you approve them: open /hooks in Codex"
|
|
12483
|
+
},
|
|
12484
|
+
{
|
|
12485
|
+
id: "cursor",
|
|
12486
|
+
displayName: "Cursor",
|
|
12487
|
+
packageName: "@ascenda-one/cursor-hooks",
|
|
12488
|
+
workspaceDir: "ascenda-cursor-hooks",
|
|
12489
|
+
credentialsKey: "cursor",
|
|
12490
|
+
configDirs: (home) => [path11.join(home, ".cursor")],
|
|
12491
|
+
binaries: ["cursor", "cursor-agent"]
|
|
12492
|
+
},
|
|
12493
|
+
{
|
|
12494
|
+
id: "windsurf",
|
|
12495
|
+
displayName: "Windsurf",
|
|
12496
|
+
packageName: "@ascenda-one/windsurf-hooks",
|
|
12497
|
+
workspaceDir: "ascenda-windsurf-hooks",
|
|
12498
|
+
credentialsKey: "windsurf",
|
|
12499
|
+
configDirs: (home) => [path11.join(home, ".codeium", "windsurf")],
|
|
12500
|
+
binaries: ["windsurf"]
|
|
12501
|
+
},
|
|
12502
|
+
{
|
|
12503
|
+
id: "gemini",
|
|
12504
|
+
displayName: "Gemini CLI",
|
|
12505
|
+
packageName: "@ascenda-one/gemini-hooks",
|
|
12506
|
+
workspaceDir: "ascenda-gemini-hooks",
|
|
12507
|
+
credentialsKey: "gemini_cli",
|
|
12508
|
+
configDirs: (home) => [path11.join(home, ".gemini")],
|
|
12509
|
+
binaries: ["gemini"]
|
|
12510
|
+
}
|
|
12511
|
+
];
|
|
12512
|
+
var USAGE = `ascenda-history-import participate \u2014 join your organisation's study from this machine
|
|
12513
|
+
|
|
12514
|
+
npx -y @ascenda-one/history-import participate <code> [options]
|
|
12515
|
+
|
|
12516
|
+
Sets up every AI agent found on this machine (hooks for every project, paired
|
|
12517
|
+
to Ascenda), joins the study <code> names in Report mode, offers to keep
|
|
12518
|
+
Claude Code's transcripts longer, and sends the history already here.
|
|
12519
|
+
Safe to run again: anything already done is kept.
|
|
12520
|
+
|
|
12521
|
+
Options
|
|
12522
|
+
--api-base-url <url> Ascenda host (default ${import_tool_kit11.DEFAULT_API_BASE_URL})
|
|
12523
|
+
--local [port] the local dev server (default port 4477)
|
|
12524
|
+
--agents <ids> only these, comma-separated: ${PARTICIPATE_AGENTS.map((agent) => agent.id).join(", ")}
|
|
12525
|
+
--fix-retention keep Claude Code transcripts longer without asking
|
|
12526
|
+
--keep-retention leave Claude Code's retention as it is, without asking
|
|
12527
|
+
--no-backfill don't send the history already on this machine
|
|
12528
|
+
--rejoin join again even if this code was joined before
|
|
12529
|
+
-h, --help
|
|
12530
|
+
`;
|
|
12531
|
+
function parseArgs(argv) {
|
|
12532
|
+
const options = {
|
|
12533
|
+
retention: "ask",
|
|
12534
|
+
backfill: true,
|
|
12535
|
+
rejoin: false
|
|
12536
|
+
};
|
|
12537
|
+
for (let i = 0; i < argv.length; i++) {
|
|
12538
|
+
const arg = argv[i];
|
|
12539
|
+
const value = () => {
|
|
12540
|
+
const next = argv[++i];
|
|
12541
|
+
if (next === void 0) throw new Error(`${arg} needs a value`);
|
|
12542
|
+
return next;
|
|
12543
|
+
};
|
|
12544
|
+
switch (arg) {
|
|
12545
|
+
case "-h":
|
|
12546
|
+
case "--help":
|
|
12547
|
+
return "help";
|
|
12548
|
+
case "--api-base-url":
|
|
12549
|
+
options.apiBaseUrl = value().replace(/\/$/, "");
|
|
12550
|
+
break;
|
|
12551
|
+
case "--local": {
|
|
12552
|
+
const peek = argv[i + 1];
|
|
12553
|
+
options.apiBaseUrl = `http://localhost:${peek && /^\d+$/.test(peek) ? argv[++i] : "4477"}`;
|
|
12554
|
+
break;
|
|
12555
|
+
}
|
|
12556
|
+
case "--agents": {
|
|
12557
|
+
const ids = value().split(",").map((id) => id.trim()).filter(Boolean);
|
|
12558
|
+
const unknown = ids.filter((id) => !PARTICIPATE_AGENTS.some((agent) => agent.id === id));
|
|
12559
|
+
if (unknown.length) throw new Error(`unknown agent: ${unknown.join(", ")}. Known: ${PARTICIPATE_AGENTS.map((agent) => agent.id).join(", ")}`);
|
|
12560
|
+
options.agents = ids;
|
|
12561
|
+
break;
|
|
12562
|
+
}
|
|
12563
|
+
case "--fix-retention":
|
|
12564
|
+
options.retention = "apply";
|
|
12565
|
+
break;
|
|
12566
|
+
case "--keep-retention":
|
|
12567
|
+
options.retention = "keep";
|
|
12568
|
+
break;
|
|
12569
|
+
case "--no-backfill":
|
|
12570
|
+
options.backfill = false;
|
|
12571
|
+
break;
|
|
12572
|
+
case "--rejoin":
|
|
12573
|
+
options.rejoin = true;
|
|
12574
|
+
break;
|
|
12575
|
+
default:
|
|
12576
|
+
if (arg.startsWith("-")) throw new Error(`unknown argument: ${arg}
|
|
12577
|
+
|
|
12578
|
+
${USAGE}`);
|
|
12579
|
+
if (options.joinCode) throw new Error(`one code only, got ${options.joinCode} and ${arg}`);
|
|
12580
|
+
options.joinCode = arg.trim();
|
|
12581
|
+
}
|
|
12582
|
+
}
|
|
12583
|
+
if (!options.joinCode) throw new Error(`participate needs the code your organisation gave you.
|
|
12584
|
+
|
|
12585
|
+
${USAGE}`);
|
|
12586
|
+
return options;
|
|
12587
|
+
}
|
|
12588
|
+
function onPath(binary, env) {
|
|
12589
|
+
const extensions = process.platform === "win32" ? (env.PATHEXT ?? ".EXE;.CMD;.BAT").split(";") : [""];
|
|
12590
|
+
for (const dir of (env.PATH ?? "").split(path11.delimiter)) {
|
|
12591
|
+
if (!dir) continue;
|
|
12592
|
+
for (const extension of extensions) {
|
|
12593
|
+
const candidate = path11.join(dir, binary + extension.toLowerCase());
|
|
12594
|
+
try {
|
|
12595
|
+
const stat6 = fs11.statSync(candidate);
|
|
12596
|
+
if (stat6.isFile()) return true;
|
|
12597
|
+
} catch {
|
|
12598
|
+
}
|
|
12599
|
+
}
|
|
12600
|
+
}
|
|
12601
|
+
return false;
|
|
12602
|
+
}
|
|
12603
|
+
function detectAgent(agent, home, env) {
|
|
12604
|
+
const dir = agent.configDirs(home, env).find((candidate) => fs11.existsSync(candidate));
|
|
12605
|
+
if (dir) return (0, import_tool_kit11.tidyHomePath)(dir, home);
|
|
12606
|
+
const binary = agent.binaries.find((name) => onPath(name, env));
|
|
12607
|
+
return binary ? `${binary} on PATH` : void 0;
|
|
12608
|
+
}
|
|
12609
|
+
function credentialsOf(agent) {
|
|
12610
|
+
const machine = (0, import_tool_kit11.readMachineCredentials)();
|
|
12611
|
+
return agent.credentialsKey === null ? machine : machine?.tools?.[agent.credentialsKey];
|
|
12612
|
+
}
|
|
12613
|
+
function pairingOf(agent) {
|
|
12614
|
+
const credentials = credentialsOf(agent);
|
|
12615
|
+
const id = credentials?.toolInstallationId;
|
|
12616
|
+
if (!id || credentials.localOnly) return void 0;
|
|
12617
|
+
const tokenFile = (0, import_tool_kit11.defaultTokenFilePath)(id);
|
|
12618
|
+
if (!(0, import_tool_kit11.readTokenFile)(tokenFile)) return void 0;
|
|
12619
|
+
return { toolInstallationId: id, apiBaseUrl: (credentials.apiBaseUrl ?? import_tool_kit11.DEFAULT_API_BASE_URL).replace(/\/$/, ""), tokenFile };
|
|
12620
|
+
}
|
|
12621
|
+
function participationFilePath() {
|
|
12622
|
+
return path11.join((0, import_tool_kit11.ascendaHome)(), "participation.json");
|
|
12623
|
+
}
|
|
12624
|
+
function readParticipation() {
|
|
12625
|
+
try {
|
|
12626
|
+
const parsed = JSON.parse(fs11.readFileSync(participationFilePath(), "utf8"));
|
|
12627
|
+
return parsed && typeof parsed.joinCode === "string" ? parsed : void 0;
|
|
12628
|
+
} catch {
|
|
12629
|
+
return void 0;
|
|
12630
|
+
}
|
|
12631
|
+
}
|
|
12632
|
+
function writeParticipation(record) {
|
|
12633
|
+
fs11.mkdirSync(path11.dirname(participationFilePath()), { recursive: true, mode: 448 });
|
|
12634
|
+
(0, import_tool_kit11.writeAtomically)(participationFilePath(), `${JSON.stringify(record, null, 2)}
|
|
12635
|
+
`, 384);
|
|
12636
|
+
}
|
|
12637
|
+
function npxCommand(packageName, args) {
|
|
12638
|
+
const spec = import_tool_kit11.COLLECTOR_VERSION === import_tool_kit11.UNRELEASED_COLLECTOR_VERSION ? packageName : `${packageName}@${import_tool_kit11.COLLECTOR_VERSION}`;
|
|
12639
|
+
const win = process.platform === "win32";
|
|
12640
|
+
return { command: win ? "npx.cmd" : "npx", args: ["-y", spec, ...args], shell: win };
|
|
12641
|
+
}
|
|
12642
|
+
function defaultAdapterCommand(env) {
|
|
12643
|
+
const root = env.ASCENDA_PARTICIPATE_BUNDLE_ROOT?.trim();
|
|
12644
|
+
if (root) {
|
|
12645
|
+
return (agent, args) => ({ command: process.execPath, args: [path11.join(root, agent.workspaceDir, "dist", "cli.js"), ...args] });
|
|
12646
|
+
}
|
|
12647
|
+
return (agent, args) => npxCommand(agent.packageName, args);
|
|
12648
|
+
}
|
|
12649
|
+
function defaultImporterCommand(args) {
|
|
12650
|
+
return { command: process.execPath, args: [process.argv[1], ...args] };
|
|
12651
|
+
}
|
|
12652
|
+
function runChild(line, env, out) {
|
|
12653
|
+
return new Promise((resolve3) => {
|
|
12654
|
+
let child;
|
|
12655
|
+
try {
|
|
12656
|
+
child = spawn2(line.command, line.args, { env, stdio: ["ignore", "pipe", "pipe"], shell: line.shell ?? false });
|
|
12657
|
+
} catch (error) {
|
|
12658
|
+
out.write(` ${error instanceof Error ? error.message : String(error)}
|
|
12659
|
+
`);
|
|
12660
|
+
resolve3(127);
|
|
12661
|
+
return;
|
|
12662
|
+
}
|
|
12663
|
+
const indent = indenter(out, " \u2502 ");
|
|
12664
|
+
child.stdout?.on("data", indent);
|
|
12665
|
+
child.stderr?.on("data", indent);
|
|
12666
|
+
child.on("error", (error) => {
|
|
12667
|
+
out.write(` could not start ${line.command}: ${error.message}
|
|
12668
|
+
`);
|
|
12669
|
+
resolve3(127);
|
|
12670
|
+
});
|
|
12671
|
+
child.on("close", (code) => {
|
|
12672
|
+
indent.flush();
|
|
12673
|
+
resolve3(code ?? 1);
|
|
12674
|
+
});
|
|
12675
|
+
});
|
|
12676
|
+
}
|
|
12677
|
+
function indenter(out, prefix) {
|
|
12678
|
+
let atStart = true;
|
|
12679
|
+
const write = (chunk) => {
|
|
12680
|
+
let text = "";
|
|
12681
|
+
for (const char of chunk.toString("utf8")) {
|
|
12682
|
+
if (atStart && char !== "\n" && char !== "\r") text += prefix;
|
|
12683
|
+
text += char;
|
|
12684
|
+
atStart = char === "\n" || char === "\r";
|
|
12685
|
+
}
|
|
12686
|
+
out.write(text);
|
|
12687
|
+
};
|
|
12688
|
+
return Object.assign(write, {
|
|
12689
|
+
flush: () => {
|
|
12690
|
+
if (!atStart) out.write("\n");
|
|
12691
|
+
atStart = true;
|
|
12692
|
+
}
|
|
12693
|
+
});
|
|
12694
|
+
}
|
|
12695
|
+
function askYesNo(stdin, stdout, question) {
|
|
12696
|
+
return new Promise((resolve3) => {
|
|
12697
|
+
const rl = readline.createInterface({ input: stdin, output: stdout });
|
|
12698
|
+
let settled = false;
|
|
12699
|
+
const finish = (answer) => {
|
|
12700
|
+
if (settled) return;
|
|
12701
|
+
settled = true;
|
|
12702
|
+
rl.close();
|
|
12703
|
+
resolve3(/^y(es)?$/i.test(answer.trim()));
|
|
12704
|
+
};
|
|
12705
|
+
rl.question(question, finish);
|
|
12706
|
+
rl.once("close", () => finish(""));
|
|
12707
|
+
});
|
|
12708
|
+
}
|
|
12709
|
+
async function runParticipate(ctx) {
|
|
12710
|
+
const env = ctx.env ?? process.env;
|
|
12711
|
+
const stdin = ctx.stdin ?? process.stdin;
|
|
12712
|
+
const stdout = ctx.stdout ?? process.stdout;
|
|
12713
|
+
const stderr = ctx.stderr ?? process.stderr;
|
|
12714
|
+
const print = (line = "") => stdout.write(`${line}
|
|
12715
|
+
`);
|
|
12716
|
+
let options;
|
|
12717
|
+
try {
|
|
12718
|
+
const parsed = parseArgs(ctx.argv);
|
|
12719
|
+
if (parsed === "help") {
|
|
12720
|
+
print(USAGE);
|
|
12721
|
+
return 0;
|
|
12722
|
+
}
|
|
12723
|
+
options = parsed;
|
|
12724
|
+
} catch (error) {
|
|
12725
|
+
stderr.write(`${error instanceof Error ? error.message : String(error)}
|
|
12726
|
+
`);
|
|
12727
|
+
return 1;
|
|
12728
|
+
}
|
|
12729
|
+
const ui = (0, import_tool_kit11.terminalStyle)((0, import_tool_kit11.colourEnabled)(stdout, env));
|
|
12730
|
+
const home = os3.homedir();
|
|
12731
|
+
const adapterCommand = ctx.adapterCommand ?? defaultAdapterCommand(env);
|
|
12732
|
+
const importerCommand = ctx.importerCommand ?? defaultImporterCommand;
|
|
12733
|
+
const step = (n, title) => print(`
|
|
12734
|
+
${ui.bold(`${n}/4 ${title}`)}`);
|
|
12735
|
+
print(`${ui.bold("Ascenda participate")} ${ui.dim(`\xB7 code ${options.joinCode}${options.apiBaseUrl ? ` \xB7 ${options.apiBaseUrl}` : ""}`)}`);
|
|
12736
|
+
const candidates = PARTICIPATE_AGENTS.filter((agent) => !options.agents || options.agents.includes(agent.id));
|
|
12737
|
+
const found = candidates.map((agent) => ({ agent, foundAt: detectAgent(agent, home, env) })).filter((entry) => entry.foundAt !== void 0);
|
|
12738
|
+
if (found.length === 0) {
|
|
12739
|
+
print("");
|
|
12740
|
+
print(`No AI agent found on this machine (looked for ${candidates.map((agent) => agent.displayName).join(", ")}).`);
|
|
12741
|
+
print("Install one, run it once, then run this again.");
|
|
12742
|
+
return 1;
|
|
12743
|
+
}
|
|
12744
|
+
const record = readParticipation();
|
|
12745
|
+
const joinRemembered = !options.rejoin && rememberedJoin(record, options);
|
|
12746
|
+
const toPair = found.filter((entry) => !pairingOf(entry.agent));
|
|
12747
|
+
const carrier = !joinRemembered && stdin.isTTY && stdout.isTTY ? toPair[0]?.agent : void 0;
|
|
12748
|
+
const confirms = toPair.length + (joinRemembered || carrier ? 0 : 1);
|
|
12749
|
+
const confirmWhat = (agent) => `pair ${agent.displayName}${agent === carrier ? " and join the study" : ""}`;
|
|
12750
|
+
print("");
|
|
12751
|
+
print(`Found ${found.map((entry) => entry.agent.displayName).join(", ")}.`);
|
|
12752
|
+
print(confirms === 0 ? "Everything here is paired and the study is joined, so nothing needs confirming." : `This needs ${confirms === 1 ? "one confirm" : `${confirms} confirms`} in your browser: ${[
|
|
12753
|
+
toPair.length ? `${toPair.length === 1 ? "one" : toPair.length} to pair ${toPair.map((entry) => entry.agent.displayName).join(", ")}${carrier ? `, the first of them also joining the study` : ""}` : "",
|
|
12754
|
+
joinRemembered || carrier ? "" : "one to join the study"
|
|
12755
|
+
].filter(Boolean).join(", then ")}. Each is announced below before its link appears.`);
|
|
12756
|
+
step(1, "Agents");
|
|
12757
|
+
let confirmIndex = 0;
|
|
12758
|
+
const agents = [];
|
|
12759
|
+
let carried;
|
|
12760
|
+
for (const { agent, foundAt } of found) {
|
|
12761
|
+
const needsConfirm = !pairingOf(agent);
|
|
12762
|
+
print("");
|
|
12763
|
+
print(` ${ui.bold(agent.displayName)} ${ui.dim(`(found ${foundAt})`)}`);
|
|
12764
|
+
if (needsConfirm) print(` ${ui.cyan(`Confirm ${++confirmIndex} of ${confirms}:`)} ${confirmWhat(agent)} using the link below.`);
|
|
12765
|
+
const args = ["setup", "--scope", "user", ...options.apiBaseUrl ? ["--api-base-url", options.apiBaseUrl] : []];
|
|
12766
|
+
const outcomeDir = agent === carrier ? fs11.mkdtempSync(path11.join(os3.tmpdir(), "ascenda-participate-join-")) : void 0;
|
|
12767
|
+
const outcomeFile = outcomeDir ? path11.join(outcomeDir, "pairing-join.json") : void 0;
|
|
12768
|
+
const childEnv = { ...env };
|
|
12769
|
+
delete childEnv[import_tool_kit11.PAIR_ORG_JOIN_CODE_ENV];
|
|
12770
|
+
delete childEnv[import_tool_kit11.PAIR_JOIN_OUTCOME_FILE_ENV];
|
|
12771
|
+
if (outcomeFile) {
|
|
12772
|
+
childEnv[import_tool_kit11.PAIR_ORG_JOIN_CODE_ENV] = options.joinCode;
|
|
12773
|
+
childEnv[import_tool_kit11.PAIR_JOIN_OUTCOME_FILE_ENV] = outcomeFile;
|
|
12774
|
+
}
|
|
12775
|
+
let exit;
|
|
12776
|
+
try {
|
|
12777
|
+
exit = await runChild(adapterCommand(agent, args), childEnv, stdout);
|
|
12778
|
+
if (outcomeFile) carried = readPairingJoinOutcome(outcomeFile);
|
|
12779
|
+
} finally {
|
|
12780
|
+
if (outcomeDir) fs11.rmSync(outcomeDir, { recursive: true, force: true });
|
|
12781
|
+
}
|
|
12782
|
+
const pairing = pairingOf(agent);
|
|
12783
|
+
if (exit !== 0) agents.push({ agent, foundAt, state: "failed", detail: `setup exited ${exit}`, pairing });
|
|
12784
|
+
else if (!pairing) agents.push({ agent, foundAt, state: "unpaired", detail: carried?.pairing === "cancelled" ? "pairing declined" : "hooks installed, pairing didn't finish" });
|
|
12785
|
+
else agents.push({ agent, foundAt, state: "collecting", pairing });
|
|
12786
|
+
}
|
|
12787
|
+
const paired = agents.filter((result) => result.pairing);
|
|
12788
|
+
const lead = paired.find((result) => result.agent.id === "claude_code") ?? paired[0];
|
|
12789
|
+
step(2, "Study");
|
|
12790
|
+
let study;
|
|
12791
|
+
if (joinRemembered && record) {
|
|
12792
|
+
study = { state: "already", record };
|
|
12793
|
+
print(` Already joined ${record.organisationName} with this code ${ui.dim(`(${(0, import_tool_kit11.formatWindow)(record.windowStartUtc, record.windowEndUtc)})`)}. Not asking again.`);
|
|
12794
|
+
print(ui.dim(" To join again anyway, add --rejoin."));
|
|
12795
|
+
} else if (carried && settledByPairing(carried)) {
|
|
12796
|
+
study = studyFromPairing(carried, options, agents.find((result) => result.agent === carrier)?.pairing?.apiBaseUrl ?? lead?.pairing?.apiBaseUrl ?? "");
|
|
12797
|
+
if (study.state === "not_joined") print(` Not joined: ${study.reason}`);
|
|
12798
|
+
else {
|
|
12799
|
+
writeParticipation(study.record);
|
|
12800
|
+
print(` Joined ${study.record.organisationName} with the pairing confirmed above. No second confirm.`);
|
|
12801
|
+
}
|
|
12802
|
+
} else if (!lead?.pairing) {
|
|
12803
|
+
study = { state: "not_joined", reason: "no agent is paired, and joining needs one", granted: [] };
|
|
12804
|
+
print(" Skipped: joining needs a paired agent, and none paired above.");
|
|
12805
|
+
} else {
|
|
12806
|
+
if (carried?.join === "not_carried") print(ui.dim(" This server didn't take the code on the pairing, so the study is joined separately."));
|
|
12807
|
+
print(` ${ui.cyan(`Confirm ${++confirmIndex} of ${Math.max(confirms, confirmIndex)}:`)} join the study, after you answer the question below.`);
|
|
12808
|
+
let outcome;
|
|
12809
|
+
await (0, import_tool_kit11.runStudyJoin)({
|
|
12810
|
+
apiBaseUrl: lead.pairing.apiBaseUrl,
|
|
12811
|
+
eventWriteToken: (0, import_tool_kit11.readTokenFile)(lead.pairing.tokenFile) ?? "",
|
|
12812
|
+
displayName: lead.agent.displayName,
|
|
12813
|
+
joinCode: options.joinCode,
|
|
12814
|
+
stdin,
|
|
12815
|
+
stdout,
|
|
12816
|
+
stderr,
|
|
12817
|
+
pollIntervalMs: ctx.joinPollIntervalMs,
|
|
12818
|
+
onOutcome: (result) => {
|
|
12819
|
+
outcome = result;
|
|
12820
|
+
}
|
|
12821
|
+
});
|
|
12822
|
+
if (outcome?.status === "joined" && outcome.start) {
|
|
12823
|
+
const joined = {
|
|
12824
|
+
joinCode: options.joinCode,
|
|
12825
|
+
apiBaseUrl: lead.pairing.apiBaseUrl,
|
|
12826
|
+
organisationName: outcome.start.organisationName,
|
|
12827
|
+
studyKind: outcome.start.studyKind,
|
|
12828
|
+
windowStartUtc: outcome.start.windowStartUtc,
|
|
12829
|
+
windowEndUtc: outcome.start.windowEndUtc,
|
|
12830
|
+
granted: outcome.granted,
|
|
12831
|
+
joinedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
12832
|
+
};
|
|
12833
|
+
writeParticipation(joined);
|
|
12834
|
+
study = { state: "joined", record: joined };
|
|
12835
|
+
} else {
|
|
12836
|
+
study = { state: "not_joined", reason: describeJoinMiss(outcome), granted: outcome?.granted ?? [] };
|
|
12837
|
+
}
|
|
12838
|
+
}
|
|
12839
|
+
step(3, "Retention");
|
|
12840
|
+
const retention = await runRetention(options, home, env, stdin, stdout, print);
|
|
12841
|
+
step(4, "Backfill");
|
|
12842
|
+
const granted = study.state === "not_joined" ? study.granted : study.record.granted;
|
|
12843
|
+
let backfill;
|
|
12844
|
+
if (!options.backfill) {
|
|
12845
|
+
backfill = { state: "skipped", reason: "--no-backfill" };
|
|
12846
|
+
print(" Skipped, as asked (--no-backfill).");
|
|
12847
|
+
} else if (!lead?.pairing) {
|
|
12848
|
+
backfill = { state: "skipped", reason: "no agent is paired to send it as" };
|
|
12849
|
+
print(" Skipped: no agent is paired to send it as.");
|
|
12850
|
+
} else if (!granted.some((grant) => grant.code === HISTORICAL_IMPORT_GRANT)) {
|
|
12851
|
+
backfill = { state: "skipped", reason: "the study didn't grant importing your history, so it would be refused" };
|
|
12852
|
+
print(" Skipped: importing your history wasn't granted, so the backend would refuse it.");
|
|
12853
|
+
} else {
|
|
12854
|
+
backfill = await runBackfill(lead, importerCommand, env, stdout, print);
|
|
12855
|
+
}
|
|
12856
|
+
printSummary({ agents, study, retention, backfill, print, ui, home });
|
|
12857
|
+
const ok = agents.every((result) => result.state === "collecting") && study.state !== "not_joined" && retention.state !== "failed" && (backfill.state === "ran" ? backfill.summary.exitCode === 0 : backfill.state !== "failed");
|
|
12858
|
+
return ok ? 0 : 1;
|
|
12859
|
+
}
|
|
12860
|
+
function readPairingJoinOutcome(file) {
|
|
12861
|
+
try {
|
|
12862
|
+
const parsed = JSON.parse(fs11.readFileSync(file, "utf8"));
|
|
12863
|
+
return parsed && typeof parsed.join === "string" ? parsed : void 0;
|
|
12864
|
+
} catch {
|
|
12865
|
+
return void 0;
|
|
12866
|
+
}
|
|
12867
|
+
}
|
|
12868
|
+
function settledByPairing(outcome) {
|
|
12869
|
+
return outcome.join === "refused" || outcome.join === "carried";
|
|
12870
|
+
}
|
|
12871
|
+
function studyFromPairing(outcome, options, apiBaseUrl) {
|
|
12872
|
+
if (outcome.join === "refused") return { state: "not_joined", reason: outcome.message ?? "the code was refused", granted: [] };
|
|
12873
|
+
const join14 = outcome.studyJoin;
|
|
12874
|
+
if (!join14) {
|
|
12875
|
+
const reason = outcome.pairing === "paired" ? "the join didn't finish" : "the pairing wasn't confirmed, so neither was the join";
|
|
12876
|
+
return { state: "not_joined", reason, granted: [] };
|
|
12877
|
+
}
|
|
12878
|
+
const granted = join14.granted ?? [];
|
|
12879
|
+
if (join14.status === "confirmed" && granted.length > 0) {
|
|
12880
|
+
return {
|
|
12881
|
+
state: "joined",
|
|
12882
|
+
record: {
|
|
12883
|
+
joinCode: options.joinCode,
|
|
12884
|
+
apiBaseUrl,
|
|
12885
|
+
organisationName: join14.organisationName,
|
|
12886
|
+
studyKind: join14.studyKind,
|
|
12887
|
+
windowStartUtc: join14.windowStartUtc,
|
|
12888
|
+
windowEndUtc: join14.windowEndUtc,
|
|
12889
|
+
granted,
|
|
12890
|
+
joinedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
12891
|
+
}
|
|
12892
|
+
};
|
|
12893
|
+
}
|
|
12894
|
+
if (join14.status === "confirmed") return { state: "not_joined", reason: "nothing was granted", granted: [] };
|
|
12895
|
+
if (join14.status === "refused") return { state: "not_joined", reason: (0, import_tool_kit11.describeStudyJoinRefusal)(join14.refusedReason), granted };
|
|
12896
|
+
if (join14.status === "expired") return { state: "not_joined", reason: "the link expired before it was confirmed", granted: [] };
|
|
12897
|
+
return { state: "not_joined", reason: "the link wasn't confirmed in time", granted: [] };
|
|
12898
|
+
}
|
|
12899
|
+
function rememberedJoin(record, options) {
|
|
12900
|
+
if (!record || record.joinCode !== options.joinCode) return false;
|
|
12901
|
+
if (options.apiBaseUrl && options.apiBaseUrl !== record.apiBaseUrl) return false;
|
|
12902
|
+
const end = Date.parse(record.windowEndUtc);
|
|
12903
|
+
return Number.isFinite(end) && end > Date.now();
|
|
12904
|
+
}
|
|
12905
|
+
function describeJoinMiss(outcome) {
|
|
12906
|
+
switch (outcome?.status) {
|
|
12907
|
+
case "not_now":
|
|
12908
|
+
return "you chose not now";
|
|
12909
|
+
case "no_terminal":
|
|
12910
|
+
return "joining needs an interactive terminal";
|
|
12911
|
+
case "expired":
|
|
12912
|
+
return "the code expired before it was confirmed";
|
|
12913
|
+
case "refused":
|
|
12914
|
+
case "failed":
|
|
12915
|
+
return outcome.message ?? "the join didn't go through";
|
|
12916
|
+
default:
|
|
12917
|
+
return "the join didn't finish";
|
|
12918
|
+
}
|
|
12919
|
+
}
|
|
12920
|
+
async function runRetention(options, home, env, stdin, stdout, print) {
|
|
12921
|
+
const paths = resolveStorePaths(home, env);
|
|
12922
|
+
if (!fs11.existsSync(paths.claudeRoot)) {
|
|
12923
|
+
print(" Nothing to change: Claude Code isn't on this machine.");
|
|
12924
|
+
return { state: "absent" };
|
|
12925
|
+
}
|
|
12926
|
+
const plan = await planClaudeRetentionFix(paths);
|
|
12927
|
+
const where = (0, import_tool_kit11.tidyHomePath)(plan.settingsPath, home);
|
|
12928
|
+
if (!plan.changeNeeded) {
|
|
12929
|
+
print(` Claude Code keeps transcripts for ${plan.currentCleanupPeriodDays} days already. Nothing to change.`);
|
|
12930
|
+
return { state: "current", plan };
|
|
12931
|
+
}
|
|
12932
|
+
const before = plan.currentCleanupPeriodDays === null ? "30 days (the default)" : `${plan.currentCleanupPeriodDays} days`;
|
|
12933
|
+
print(` Claude Code deletes transcripts after ${before}, and the backfill can only send what's still there.`);
|
|
12934
|
+
print(` The change: cleanupPeriodDays \u2192 ${plan.proposedCleanupPeriodDays} in ${where}. Nothing else in that file changes.`);
|
|
12935
|
+
let apply = options.retention === "apply";
|
|
12936
|
+
if (options.retention === "ask") {
|
|
12937
|
+
if (stdin.isTTY && stdout.isTTY) {
|
|
12938
|
+
apply = await askYesNo(stdin, stdout, " Make this change? [y/N] ");
|
|
12939
|
+
} else {
|
|
12940
|
+
print(" Not changed: no terminal to ask in. Run with --fix-retention to make it.");
|
|
12941
|
+
}
|
|
12942
|
+
}
|
|
12943
|
+
if (!apply) {
|
|
12944
|
+
if (options.retention !== "ask" || stdin.isTTY && stdout.isTTY) print(" Left as it is.");
|
|
12945
|
+
return { state: "kept", plan };
|
|
12946
|
+
}
|
|
12947
|
+
try {
|
|
12948
|
+
await applyClaudeRetentionFix(plan);
|
|
12949
|
+
print(` Changed. Claude Code now keeps transcripts for ${plan.proposedCleanupPeriodDays} days.`);
|
|
12950
|
+
return { state: "changed", plan };
|
|
12951
|
+
} catch (error) {
|
|
12952
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
12953
|
+
print(` Not changed: ${reason}`);
|
|
12954
|
+
return { state: "failed", plan, reason };
|
|
12955
|
+
}
|
|
12956
|
+
}
|
|
12957
|
+
async function runBackfill(lead, importerCommand, env, stdout, print) {
|
|
12958
|
+
const pairing = lead.pairing;
|
|
12959
|
+
const summaryDir = fs11.mkdtempSync(path11.join(os3.tmpdir(), "ascenda-participate-"));
|
|
12960
|
+
const summaryFile = path11.join(summaryDir, "import-summary.json");
|
|
12961
|
+
print(` Sending as ${lead.agent.displayName}'s pairing ${pairing.toolInstallationId}.`);
|
|
12962
|
+
try {
|
|
12963
|
+
const exit = await runChild(importerCommand(["import", "--ship", "--summary-json", summaryFile]), {
|
|
12964
|
+
...env,
|
|
12965
|
+
ASCENDA_API_BASE_URL: pairing.apiBaseUrl,
|
|
12966
|
+
ASCENDA_TOOL_INSTALLATION_ID: pairing.toolInstallationId,
|
|
12967
|
+
ASCENDA_EVENT_WRITE_TOKEN_FILE: pairing.tokenFile
|
|
12968
|
+
}, stdout);
|
|
12969
|
+
let summary;
|
|
12970
|
+
try {
|
|
12971
|
+
summary = JSON.parse(fs11.readFileSync(summaryFile, "utf8"));
|
|
12972
|
+
} catch {
|
|
12973
|
+
return { state: "failed", reason: `the import exited ${exit} without a summary` };
|
|
12974
|
+
}
|
|
12975
|
+
if (summary.nothingToImport) return { state: "nothing" };
|
|
12976
|
+
return { state: "ran", summary, shippedAs: pairing.toolInstallationId };
|
|
12977
|
+
} finally {
|
|
12978
|
+
fs11.rmSync(summaryDir, { recursive: true, force: true });
|
|
12979
|
+
}
|
|
12980
|
+
}
|
|
12981
|
+
var REJECTION_SENTENCES = {
|
|
12982
|
+
consent_missing_or_expired: "no history-import consent on the account",
|
|
12983
|
+
consent_source_not_granted: "history import isn't granted for this agent's history",
|
|
12984
|
+
validation_failed: "the backend didn't accept the event's shape"
|
|
12985
|
+
};
|
|
12986
|
+
function printSummary(input) {
|
|
12987
|
+
const { agents, study, retention, backfill, print, ui } = input;
|
|
12988
|
+
const label = (text) => ` ${text.padEnd(11)}`;
|
|
12989
|
+
const pad = " ".repeat(13);
|
|
12990
|
+
print("");
|
|
12991
|
+
print("\u2500".repeat(60));
|
|
12992
|
+
print(ui.bold("Summary"));
|
|
12993
|
+
agents.forEach((result, i) => {
|
|
12994
|
+
const head = i === 0 ? label("Agents") : pad;
|
|
12995
|
+
const name = result.agent.displayName.padEnd(12);
|
|
12996
|
+
if (result.state === "collecting") {
|
|
12997
|
+
print(`${head}${ui.mark("ok")} ${name} collecting ${ui.dim(result.pairing.toolInstallationId)}`);
|
|
12998
|
+
if (result.agent.afterPairing) print(`${pad} ${" ".repeat(14)}${result.agent.afterPairing}`);
|
|
12999
|
+
} else if (result.state === "unpaired") print(`${head}${ui.mark("warn")} ${name} not collecting: ${result.detail}`);
|
|
13000
|
+
else print(`${head}${ui.mark("bad")} ${name} not collecting: ${result.detail}${result.pairing ? ui.dim(" (an earlier pairing is still saved)") : ""}`);
|
|
13001
|
+
});
|
|
13002
|
+
if (study.state === "not_joined") {
|
|
13003
|
+
print(`${label("Study")}${ui.mark("bad")} not joined: ${study.reason}`);
|
|
13004
|
+
if (study.granted.length) print(`${pad} granted before it stopped: ${study.granted.map(import_tool_kit11.describeStudyGrant).join("; ")}`);
|
|
13005
|
+
} else {
|
|
13006
|
+
const { record } = study;
|
|
13007
|
+
print(`${label("Study")}${ui.mark("ok")} ${record.organisationName}, ${(0, import_tool_kit11.describeStudyKind)(record.studyKind)}${study.state === "already" ? ui.dim(" (joined earlier)") : ""}`);
|
|
13008
|
+
print(`${pad} window ${(0, import_tool_kit11.formatWindow)(record.windowStartUtc, record.windowEndUtc)}`);
|
|
13009
|
+
for (const grant of record.granted) print(`${pad} granted: ${(0, import_tool_kit11.describeStudyGrant)(grant)}`);
|
|
13010
|
+
}
|
|
13011
|
+
const days = (plan) => plan.currentCleanupPeriodDays === null ? "30 days (default)" : `${plan.currentCleanupPeriodDays} days`;
|
|
13012
|
+
if (retention.state === "absent") print(`${label("Retention")}${ui.mark("info")} Claude Code isn't on this machine`);
|
|
13013
|
+
else if (retention.state === "current") print(`${label("Retention")}${ui.mark("ok")} ${days(retention.plan)}, unchanged`);
|
|
13014
|
+
else if (retention.state === "changed") print(`${label("Retention")}${ui.mark("ok")} ${days(retention.plan)} \u2192 ${retention.plan.proposedCleanupPeriodDays} days`);
|
|
13015
|
+
else if (retention.state === "kept") print(`${label("Retention")}${ui.mark("warn")} ${days(retention.plan)}, unchanged. Transcripts older than that are deleted`);
|
|
13016
|
+
else print(`${label("Retention")}${ui.mark("bad")} ${days(retention.plan)}, not changed: ${retention.reason}`);
|
|
13017
|
+
if (backfill.state === "skipped") print(`${label("Backfill")}${ui.mark("info")} skipped: ${backfill.reason}`);
|
|
13018
|
+
else if (backfill.state === "nothing") print(`${label("Backfill")}${ui.mark("info")} no agent history on this machine to send`);
|
|
13019
|
+
else if (backfill.state === "failed") print(`${label("Backfill")}${ui.mark("bad")} ${backfill.reason}`);
|
|
13020
|
+
else {
|
|
13021
|
+
const { summary } = backfill;
|
|
13022
|
+
const ship = summary.shipResult;
|
|
13023
|
+
const n = (value) => value.toLocaleString("en-US");
|
|
13024
|
+
if (!ship) {
|
|
13025
|
+
print(`${label("Backfill")}${ui.mark("bad")} ${n(summary.totalExtracted)} events read, none sent: ${summary.shipError ?? "the send didn't run"}`);
|
|
13026
|
+
} else {
|
|
13027
|
+
const tone = summary.exitCode === 0 ? "ok" : "bad";
|
|
13028
|
+
print(`${label("Backfill")}${ui.mark(tone)} ${n(ship.sent)} events sent: ${n(ship.accepted)} accepted, ${n(ship.duplicate)} already there, ${n(ship.rejected)} rejected`);
|
|
13029
|
+
for (const [store, counts] of Object.entries(ship.perStore)) {
|
|
13030
|
+
print(`${pad} ${store.padEnd(12)} ${n(counts.accepted)} accepted, ${n(counts.duplicate)} already there, ${n(counts.rejected)} rejected`);
|
|
13031
|
+
}
|
|
13032
|
+
for (const [reason, count] of Object.entries(ship.rejectionReasons)) {
|
|
13033
|
+
print(`${pad} ${n(count)} rejected: ${REJECTION_SENTENCES[reason] ?? reason}`);
|
|
13034
|
+
}
|
|
13035
|
+
if (ship.consentBlocked) print(`${pad} stopped early: the account has no consent for a history import, so nothing more was sent`);
|
|
13036
|
+
if (ship.httpFailures) print(`${pad} ${n(ship.httpFailures)} batch(es) failed to send. Run this again to fill the gaps`);
|
|
13037
|
+
}
|
|
13038
|
+
for (const outcome of summary.outcomes.filter((entry) => entry.status === "failed")) {
|
|
13039
|
+
print(`${pad} ${outcome.store} couldn't be read: ${outcome.error}`);
|
|
13040
|
+
}
|
|
13041
|
+
}
|
|
13042
|
+
print("");
|
|
13043
|
+
const unpaired = agents.filter((result) => result.state !== "collecting");
|
|
13044
|
+
if (unpaired.length || study.state === "not_joined" || backfill.state === "failed") {
|
|
13045
|
+
print("Run the same command again to finish. Anything already done is kept.");
|
|
13046
|
+
} else {
|
|
13047
|
+
print(`Done. Restart ${agents.map((result) => result.agent.displayName).join(", ")} so ${agents.length === 1 ? "it loads" : "they load"} the hooks.`);
|
|
13048
|
+
}
|
|
13049
|
+
}
|
|
13050
|
+
|
|
11630
13051
|
// src/localHandoff.ts
|
|
11631
|
-
var
|
|
13052
|
+
var import_tool_kit12 = __toESM(require_out3(), 1);
|
|
11632
13053
|
|
|
11633
13054
|
// src/handoffActiveTime.ts
|
|
11634
13055
|
var SESSION_SPLIT_QUANTITIES = {
|
|
@@ -11836,23 +13257,23 @@ function clipByLocalDay(interval) {
|
|
|
11836
13257
|
}
|
|
11837
13258
|
|
|
11838
13259
|
// src/localHandoff.ts
|
|
11839
|
-
import * as
|
|
11840
|
-
import * as
|
|
11841
|
-
import * as
|
|
13260
|
+
import * as fs12 from "node:fs/promises";
|
|
13261
|
+
import * as os4 from "node:os";
|
|
13262
|
+
import * as path12 from "node:path";
|
|
11842
13263
|
var APP_BUNDLE_ID = "one.ascenda.ascendaMissionControl";
|
|
11843
13264
|
var HANDOFF_SCHEMA = 6;
|
|
11844
|
-
function handoffDir(home =
|
|
11845
|
-
return
|
|
13265
|
+
function handoffDir(home = os4.homedir()) {
|
|
13266
|
+
return path12.join((0, import_tool_kit12.ascendaHome)(home), "history-import");
|
|
11846
13267
|
}
|
|
11847
|
-
function handoffFilePath(home =
|
|
11848
|
-
return
|
|
13268
|
+
function handoffFilePath(home = os4.homedir(), store = "claude_code") {
|
|
13269
|
+
return path12.join(handoffDir(home), `${store}.json`);
|
|
11849
13270
|
}
|
|
11850
13271
|
var projectLabelMemo = /* @__PURE__ */ new Map();
|
|
11851
13272
|
function projectLabelOf(repoRef) {
|
|
11852
13273
|
if (!repoRef) return null;
|
|
11853
13274
|
const hit = projectLabelMemo.get(repoRef);
|
|
11854
13275
|
if (hit !== void 0) return hit;
|
|
11855
|
-
const label = (0,
|
|
13276
|
+
const label = (0, import_tool_kit12.deriveWorkContext)(repoRef)?.projectLabel ?? null;
|
|
11856
13277
|
projectLabelMemo.set(repoRef, label);
|
|
11857
13278
|
return label;
|
|
11858
13279
|
}
|
|
@@ -11861,7 +13282,7 @@ function projectHashOf(repoRef) {
|
|
|
11861
13282
|
if (!repoRef) return null;
|
|
11862
13283
|
const hit = projectHashMemo.get(repoRef);
|
|
11863
13284
|
if (hit !== void 0) return hit;
|
|
11864
|
-
const hash = (0,
|
|
13285
|
+
const hash = (0, import_tool_kit12.deriveWorkContext)(repoRef)?.projectHash ?? null;
|
|
11865
13286
|
projectHashMemo.set(repoRef, hash);
|
|
11866
13287
|
return hash;
|
|
11867
13288
|
}
|
|
@@ -12205,17 +13626,17 @@ function buildVsCodeHandoff(events, extractionId, generatedAt) {
|
|
|
12205
13626
|
chatSessions
|
|
12206
13627
|
};
|
|
12207
13628
|
}
|
|
12208
|
-
async function writeHandoff(handoff, home =
|
|
13629
|
+
async function writeHandoff(handoff, home = os4.homedir()) {
|
|
12209
13630
|
if (!await appIsInstalled(home)) return null;
|
|
12210
13631
|
const dir = handoffDir(home);
|
|
12211
|
-
await
|
|
13632
|
+
await fs12.mkdir(dir, { recursive: true });
|
|
12212
13633
|
const target = handoffFilePath(home, handoff.store);
|
|
12213
13634
|
await writeJsonAtomically(target, handoff);
|
|
12214
13635
|
return target;
|
|
12215
13636
|
}
|
|
12216
13637
|
async function appIsInstalled(home) {
|
|
12217
13638
|
try {
|
|
12218
|
-
await
|
|
13639
|
+
await fs12.stat(path12.join(home, "Library", "Application Support", APP_BUNDLE_ID));
|
|
12219
13640
|
return true;
|
|
12220
13641
|
} catch {
|
|
12221
13642
|
return false;
|
|
@@ -12223,18 +13644,18 @@ async function appIsInstalled(home) {
|
|
|
12223
13644
|
}
|
|
12224
13645
|
async function writeJsonAtomically(target, payload) {
|
|
12225
13646
|
const temp = `${target}.tmp`;
|
|
12226
|
-
await
|
|
12227
|
-
await
|
|
13647
|
+
await fs12.writeFile(temp, JSON.stringify(payload, null, 2) + "\n", "utf8");
|
|
13648
|
+
await fs12.rename(temp, target);
|
|
12228
13649
|
}
|
|
12229
13650
|
|
|
12230
13651
|
// src/crossStoreElapsed.ts
|
|
12231
|
-
import * as
|
|
12232
|
-
import * as
|
|
12233
|
-
import * as
|
|
13652
|
+
import * as fs13 from "node:fs/promises";
|
|
13653
|
+
import * as os5 from "node:os";
|
|
13654
|
+
import * as path13 from "node:path";
|
|
12234
13655
|
var CROSS_STORE_ELAPSED_DIR_NAME = "elapsed";
|
|
12235
13656
|
var CROSS_STORE_ELAPSED_FILE_NAME = "cross-store.json";
|
|
12236
|
-
function crossStoreElapsedPath(home =
|
|
12237
|
-
return
|
|
13657
|
+
function crossStoreElapsedPath(home = os5.homedir()) {
|
|
13658
|
+
return path13.join(handoffDir(home), CROSS_STORE_ELAPSED_DIR_NAME, CROSS_STORE_ELAPSED_FILE_NAME);
|
|
12238
13659
|
}
|
|
12239
13660
|
var CrossStoreElapsedPool = class {
|
|
12240
13661
|
byKey = /* @__PURE__ */ new Map();
|
|
@@ -12293,18 +13714,18 @@ var CrossStoreElapsedPool = class {
|
|
|
12293
13714
|
};
|
|
12294
13715
|
}
|
|
12295
13716
|
};
|
|
12296
|
-
async function removeCrossStoreElapsed(home =
|
|
13717
|
+
async function removeCrossStoreElapsed(home = os5.homedir()) {
|
|
12297
13718
|
try {
|
|
12298
|
-
await
|
|
13719
|
+
await fs13.unlink(crossStoreElapsedPath(home));
|
|
12299
13720
|
return true;
|
|
12300
13721
|
} catch {
|
|
12301
13722
|
return false;
|
|
12302
13723
|
}
|
|
12303
13724
|
}
|
|
12304
|
-
async function writeCrossStoreElapsed(file, home =
|
|
13725
|
+
async function writeCrossStoreElapsed(file, home = os5.homedir()) {
|
|
12305
13726
|
if (!await appIsInstalled(home)) return null;
|
|
12306
13727
|
const target = crossStoreElapsedPath(home);
|
|
12307
|
-
await
|
|
13728
|
+
await fs13.mkdir(path13.dirname(target), { recursive: true });
|
|
12308
13729
|
await writeJsonAtomically(target, file);
|
|
12309
13730
|
return target;
|
|
12310
13731
|
}
|
|
@@ -12327,7 +13748,7 @@ function formatInventory(inv) {
|
|
|
12327
13748
|
}
|
|
12328
13749
|
async function pathExists(target) {
|
|
12329
13750
|
try {
|
|
12330
|
-
await
|
|
13751
|
+
await fs14.access(target);
|
|
12331
13752
|
return true;
|
|
12332
13753
|
} catch {
|
|
12333
13754
|
return false;
|
|
@@ -12419,12 +13840,16 @@ async function runSource(outcomes, store, inventory, allEvents, extract, buildSt
|
|
|
12419
13840
|
`);
|
|
12420
13841
|
}
|
|
12421
13842
|
crossStore?.add(store, collectProjectSpans(events));
|
|
12422
|
-
const handoffPath = await writeHandoff(buildStoreHandoff(events));
|
|
12423
|
-
|
|
12424
|
-
|
|
13843
|
+
const handoffPath = buildStoreHandoff ? await writeHandoff(buildStoreHandoff(events)) : null;
|
|
13844
|
+
if (buildStoreHandoff) {
|
|
13845
|
+
process.stdout.write(
|
|
13846
|
+
handoffPath ? ` handoff: \u2192 ${handoffPath}
|
|
12425
13847
|
|
|
12426
|
-
` : " handoff:
|
|
12427
|
-
|
|
13848
|
+
` : " handoff: no Flow app on this machine, none needed\n\n"
|
|
13849
|
+
);
|
|
13850
|
+
} else {
|
|
13851
|
+
process.stdout.write("\n");
|
|
13852
|
+
}
|
|
12428
13853
|
outcomes.push({
|
|
12429
13854
|
store,
|
|
12430
13855
|
status: "extracted",
|
|
@@ -12499,7 +13924,16 @@ shipped: sent=${shipResult.sent} accepted=${shipResult.accepted} duplicate=${shi
|
|
|
12499
13924
|
}
|
|
12500
13925
|
if (shipResult.consentBlocked) {
|
|
12501
13926
|
out.write(
|
|
12502
|
-
"\n stopped early: this account has no consent for a retrospective import, so the\n backend refused the whole batch and every remaining event would be refused too.\n Nothing was stored.
|
|
13927
|
+
"\n stopped early: this account has no consent for a retrospective import, so the\n backend refused the whole batch and every remaining event would be refused too.\n Nothing was stored. Turn on historical import for this account: in the Flow app\n under Connections > Bring in daily tools, or on the web where you joined your\n study. Then run this again; the import is idempotent, so nothing here is wasted.\n"
|
|
13928
|
+
);
|
|
13929
|
+
}
|
|
13930
|
+
if (shipResult.storesNotGranted?.length) {
|
|
13931
|
+
out.write(
|
|
13932
|
+
`
|
|
13933
|
+
not granted: ${shipResult.storesNotGranted.join(", ")}. Historical import is on for this account but
|
|
13934
|
+
doesn't include those stores, so their events were skipped. Add them to the grant
|
|
13935
|
+
(Flow app, or the web where you joined your study) and run this again.
|
|
13936
|
+
`
|
|
12503
13937
|
);
|
|
12504
13938
|
}
|
|
12505
13939
|
for (const [reason, n] of Object.entries(shipResult.rejectionReasons)) {
|
|
@@ -12512,6 +13946,11 @@ shipped: sent=${shipResult.sent} accepted=${shipResult.accepted} duplicate=${shi
|
|
|
12512
13946
|
);
|
|
12513
13947
|
}
|
|
12514
13948
|
}
|
|
13949
|
+
async function writeSummaryJson(file, summary) {
|
|
13950
|
+
if (!file) return;
|
|
13951
|
+
await fs14.mkdir(path14.dirname(file), { recursive: true });
|
|
13952
|
+
await fs14.writeFile(file, JSON.stringify(summary, null, 2) + "\n", "utf8");
|
|
13953
|
+
}
|
|
12515
13954
|
function exitCodeFor(outcomes, ship, shipResult, shipError) {
|
|
12516
13955
|
if (outcomes.some((o) => o.status === "failed")) return 1;
|
|
12517
13956
|
if (!ship) return 0;
|
|
@@ -12535,7 +13974,45 @@ async function main() {
|
|
|
12535
13974
|
case "import": {
|
|
12536
13975
|
const ship = rest.includes("--ship");
|
|
12537
13976
|
const keepStaging = rest.includes("--keep-staging");
|
|
13977
|
+
const flagValue = (name) => {
|
|
13978
|
+
const at = rest.indexOf(name);
|
|
13979
|
+
return at >= 0 && rest[at + 1] && !rest[at + 1].startsWith("--") ? rest[at + 1] : void 0;
|
|
13980
|
+
};
|
|
12538
13981
|
const snapshotSessions = rest.includes("--snapshot-sessions");
|
|
13982
|
+
const withGit = rest.includes("--git");
|
|
13983
|
+
const summaryAt = rest.indexOf("--summary-json");
|
|
13984
|
+
const summaryJson = summaryAt >= 0 ? rest[summaryAt + 1] ?? null : null;
|
|
13985
|
+
let shipConfig = null;
|
|
13986
|
+
let shipConfigProblem = null;
|
|
13987
|
+
if (ship) {
|
|
13988
|
+
let loaded = null;
|
|
13989
|
+
try {
|
|
13990
|
+
loaded = loadShipConfig({
|
|
13991
|
+
installationId: flagValue("--installation-id"),
|
|
13992
|
+
tokenFile: flagValue("--token-file"),
|
|
13993
|
+
apiBaseUrl: flagValue("--api-base-url")
|
|
13994
|
+
});
|
|
13995
|
+
} catch (error) {
|
|
13996
|
+
if (!(error instanceof ShipConfigError)) throw error;
|
|
13997
|
+
shipConfigProblem = error.message;
|
|
13998
|
+
process.stderr.write(`${error.message}
|
|
13999
|
+
`);
|
|
14000
|
+
}
|
|
14001
|
+
if (loaded) {
|
|
14002
|
+
try {
|
|
14003
|
+
const prepared = await prepareToken(loaded);
|
|
14004
|
+
shipConfig = prepared.config;
|
|
14005
|
+
if (prepared.note) process.stdout.write(`${prepared.note}
|
|
14006
|
+
`);
|
|
14007
|
+
} catch (error) {
|
|
14008
|
+
if (!(error instanceof ShipConfigError)) throw error;
|
|
14009
|
+
process.stderr.write(`${error.message}
|
|
14010
|
+
`);
|
|
14011
|
+
await writeSummaryJson(summaryJson, { exitCode: 2, outcomes: [], totalExtracted: 0, shipResult: null, shipError: error.message });
|
|
14012
|
+
return 2;
|
|
14013
|
+
}
|
|
14014
|
+
}
|
|
14015
|
+
}
|
|
12539
14016
|
const claudeScan = await safeScan(
|
|
12540
14017
|
"claude_code",
|
|
12541
14018
|
paths.claudeProjectsDirs.join(", "),
|
|
@@ -12555,6 +14032,7 @@ async function main() {
|
|
|
12555
14032
|
`no Claude Code store at ${claudeInventory.rootPath}, no Codex store at ${codexInventory.rootPath}, no Cursor store at ${cursorInventory.rootPath}, and no VS Code store at ${vsCodeInventory.rootPath} \u2014 nothing to import
|
|
12556
14033
|
`
|
|
12557
14034
|
);
|
|
14035
|
+
await writeSummaryJson(summaryJson, { exitCode: 2, nothingToImport: true, outcomes: [], totalExtracted: 0, shipResult: null, shipError: null });
|
|
12558
14036
|
return 2;
|
|
12559
14037
|
}
|
|
12560
14038
|
const stagingRoot = defaultStagingRoot(paths.home);
|
|
@@ -12590,52 +14068,52 @@ refusing to start rather than failing halfway through the copy
|
|
|
12590
14068
|
const crossStore = new CrossStoreElapsedPool();
|
|
12591
14069
|
try {
|
|
12592
14070
|
await runSource(outcomes, "claude_code", claudeInventory, allEvents, async (collect) => {
|
|
12593
|
-
const snapshotRoot =
|
|
14071
|
+
const snapshotRoot = path14.join(area.root, "claude_code");
|
|
12594
14072
|
for (const projectsDir of paths.claudeProjectsDirs) {
|
|
12595
14073
|
try {
|
|
12596
|
-
await
|
|
14074
|
+
await fs14.access(projectsDir);
|
|
12597
14075
|
} catch {
|
|
12598
14076
|
continue;
|
|
12599
14077
|
}
|
|
12600
|
-
await snapshotPath(area, projectsDir,
|
|
14078
|
+
await snapshotPath(area, projectsDir, path14.join("claude_code", "projects"));
|
|
12601
14079
|
}
|
|
12602
14080
|
for await (const event of extractClaudeCode(snapshotRoot, area.extractionId)) collect(event);
|
|
12603
14081
|
}, (events) => buildHandoff(events, area.extractionId, (/* @__PURE__ */ new Date()).toISOString()), claudeScan.scanError, crossStore);
|
|
12604
14082
|
await runSource(outcomes, "codex", codexInventory, allEvents, async (collect) => {
|
|
12605
|
-
const codexSnapshotRoot =
|
|
14083
|
+
const codexSnapshotRoot = path14.join(area.root, "codex");
|
|
12606
14084
|
const roots = {
|
|
12607
14085
|
sessions: paths.codexSessions,
|
|
12608
14086
|
archived_sessions: paths.codexArchivedSessions
|
|
12609
14087
|
};
|
|
12610
14088
|
for (const dir of CODEX_SNAPSHOT_DIRS) {
|
|
12611
14089
|
try {
|
|
12612
|
-
await
|
|
14090
|
+
await fs14.access(roots[dir]);
|
|
12613
14091
|
} catch {
|
|
12614
14092
|
continue;
|
|
12615
14093
|
}
|
|
12616
|
-
await snapshotPath(area, roots[dir],
|
|
14094
|
+
await snapshotPath(area, roots[dir], path14.join("codex", dir));
|
|
12617
14095
|
}
|
|
12618
14096
|
for await (const event of extractCodex(codexSnapshotRoot, area.extractionId)) collect(event);
|
|
12619
14097
|
}, (events) => buildCodexHandoff(events, area.extractionId, (/* @__PURE__ */ new Date()).toISOString()), codexScan.scanError, crossStore);
|
|
12620
14098
|
await runSource(outcomes, "cursor", cursorInventory, allEvents, async (collect) => {
|
|
12621
|
-
const cursorSnapshotRoot =
|
|
12622
|
-
await snapshotPath(area, paths.cursorStateDb,
|
|
14099
|
+
const cursorSnapshotRoot = path14.join(area.root, "cursor");
|
|
14100
|
+
await snapshotPath(area, paths.cursorStateDb, path14.join("cursor", "state.vscdb"));
|
|
12623
14101
|
for await (const event of extractCursor(cursorSnapshotRoot, area.extractionId)) collect(event);
|
|
12624
14102
|
}, (events) => buildCursorHandoff(events, area.extractionId, (/* @__PURE__ */ new Date()).toISOString()), cursorScan.scanError, crossStore);
|
|
12625
14103
|
await runSource(outcomes, "vscode", vsCodeInventory, allEvents, async (collect) => {
|
|
12626
14104
|
const roots = [];
|
|
12627
14105
|
for (const variant of paths.vscodeVariants) {
|
|
12628
14106
|
const suffix = variant.name === "Code" ? "" : `-${variant.name.toLowerCase().replace(/[^a-z0-9]+/g, "-")}`;
|
|
12629
|
-
const stagedHistory =
|
|
14107
|
+
const stagedHistory = path14.join(area.root, "vscode", `history${suffix}`);
|
|
12630
14108
|
if (await pathExists(variant.history)) {
|
|
12631
|
-
await snapshotPath(area, variant.history,
|
|
14109
|
+
await snapshotPath(area, variant.history, path14.join("vscode", `history${suffix}`));
|
|
12632
14110
|
}
|
|
12633
14111
|
let workspaceStorageDir = variant.workspaceStorage;
|
|
12634
14112
|
if (snapshotSessions && await pathExists(variant.workspaceStorage)) {
|
|
12635
14113
|
workspaceStorageDir = await snapshotVsCodeWorkspaceStorage(
|
|
12636
14114
|
area,
|
|
12637
14115
|
variant.workspaceStorage,
|
|
12638
|
-
|
|
14116
|
+
path14.join("vscode", `workspaceStorage${suffix}`)
|
|
12639
14117
|
);
|
|
12640
14118
|
}
|
|
12641
14119
|
roots.push({
|
|
@@ -12648,6 +14126,24 @@ refusing to start rather than failing halfway through the copy
|
|
|
12648
14126
|
const source = roots;
|
|
12649
14127
|
for await (const event of extractVsCode(source, area.extractionId)) collect(event);
|
|
12650
14128
|
}, (events) => buildVsCodeHandoff(events, area.extractionId, (/* @__PURE__ */ new Date()).toISOString()), vsCodeScan.scanError, crossStore);
|
|
14129
|
+
if (withGit) {
|
|
14130
|
+
const repoRefs = /* @__PURE__ */ new Set();
|
|
14131
|
+
for (const event of allEvents) {
|
|
14132
|
+
if (event.store !== "git" && event.repoRef && path14.isAbsolute(event.repoRef)) {
|
|
14133
|
+
repoRefs.add(event.repoRef);
|
|
14134
|
+
}
|
|
14135
|
+
}
|
|
14136
|
+
const gitInventory = {
|
|
14137
|
+
store: "git",
|
|
14138
|
+
rootPath: `${repoRefs.size} repositories named by the other stores`,
|
|
14139
|
+
present: repoRefs.size > 0,
|
|
14140
|
+
counts: { repos: repoRefs.size },
|
|
14141
|
+
notes: ["only commits whose author email matches your git config; metadata only"]
|
|
14142
|
+
};
|
|
14143
|
+
await runSource(outcomes, "git", gitInventory, allEvents, async (collect) => {
|
|
14144
|
+
for await (const event of extractGit(repoRefs, area.extractionId)) collect(event);
|
|
14145
|
+
}, null, null);
|
|
14146
|
+
}
|
|
12651
14147
|
try {
|
|
12652
14148
|
const crossStoreFile = crossStore.build(area.extractionId, (/* @__PURE__ */ new Date()).toISOString());
|
|
12653
14149
|
if (crossStoreFile) {
|
|
@@ -12655,7 +14151,7 @@ refusing to start rather than failing halfway through the copy
|
|
|
12655
14151
|
process.stdout.write(
|
|
12656
14152
|
crossStorePath ? `elapsed across ${crossStoreFile.stores.join(" + ")}: \u2192 ${crossStorePath}
|
|
12657
14153
|
|
|
12658
|
-
` : "elapsed across stores:
|
|
14154
|
+
` : "elapsed across stores: no Flow app on this machine, none needed\n\n"
|
|
12659
14155
|
);
|
|
12660
14156
|
} else if (outcomes.some((outcome) => outcome.handoffWritten)) {
|
|
12661
14157
|
if (await removeCrossStoreElapsed()) {
|
|
@@ -12670,16 +14166,17 @@ refusing to start rather than failing halfway through the copy
|
|
|
12670
14166
|
`
|
|
12671
14167
|
);
|
|
12672
14168
|
}
|
|
12673
|
-
const eventsFile =
|
|
12674
|
-
await
|
|
14169
|
+
const eventsFile = path14.join(area.root, "events.jsonl");
|
|
14170
|
+
await fs14.writeFile(eventsFile, allEvents.map((e) => JSON.stringify(e)).join("\n") + "\n", "utf8");
|
|
12675
14171
|
let shipResult = null;
|
|
12676
14172
|
let shipError = null;
|
|
12677
14173
|
if (ship) {
|
|
12678
|
-
|
|
12679
|
-
|
|
14174
|
+
try {
|
|
14175
|
+
if (!shipConfig) throw new ShipConfigError(shipConfigProblem ?? "no pairing to ship as");
|
|
14176
|
+
const config = shipConfig;
|
|
14177
|
+
process.stdout.write(`
|
|
12680
14178
|
shipping to ${config.apiBaseUrl} as ${config.toolInstallationId}\u2026
|
|
12681
14179
|
`);
|
|
12682
|
-
try {
|
|
12683
14180
|
shipResult = await shipEvents(allEvents, config, (done, total) => {
|
|
12684
14181
|
process.stdout.write(` ${done.toLocaleString("en-US")}/${total.toLocaleString("en-US")}\r`);
|
|
12685
14182
|
});
|
|
@@ -12698,7 +14195,9 @@ shipping to ${config.apiBaseUrl} as ${config.toolInstallationId}\u2026
|
|
|
12698
14195
|
shipResult,
|
|
12699
14196
|
shipError
|
|
12700
14197
|
});
|
|
12701
|
-
|
|
14198
|
+
const exitCode = exitCodeFor(outcomes, ship, shipResult, shipError);
|
|
14199
|
+
await writeSummaryJson(summaryJson, { exitCode, outcomes, totalExtracted: allEvents.length, shipResult, shipError });
|
|
14200
|
+
return exitCode;
|
|
12702
14201
|
} finally {
|
|
12703
14202
|
if (keepStaging) {
|
|
12704
14203
|
process.stdout.write(`
|
|
@@ -12853,6 +14352,8 @@ generation ${result.generation}
|
|
|
12853
14352
|
process.stdout.write("\nverify it: ascenda-history-import archive --verify\n");
|
|
12854
14353
|
return result.unreadable > 0 ? 1 : 0;
|
|
12855
14354
|
}
|
|
14355
|
+
case "participate":
|
|
14356
|
+
return runParticipate({ argv: rest });
|
|
12856
14357
|
case "fix-retention": {
|
|
12857
14358
|
const plan = await planClaudeRetentionFix(paths);
|
|
12858
14359
|
if (!plan.changeNeeded) {
|
|
@@ -12874,9 +14375,75 @@ generation ${result.generation}
|
|
|
12874
14375
|
}
|
|
12875
14376
|
return 0;
|
|
12876
14377
|
}
|
|
14378
|
+
case "schedule": {
|
|
14379
|
+
const [action, ...flags] = rest;
|
|
14380
|
+
const env = defaultScheduleEnv();
|
|
14381
|
+
if (action === "install") {
|
|
14382
|
+
const at = flags.indexOf("--every");
|
|
14383
|
+
let everyDays;
|
|
14384
|
+
try {
|
|
14385
|
+
everyDays = at >= 0 ? parseInterval(flags[at + 1] ?? "") : DEFAULT_INTERVAL_DAYS;
|
|
14386
|
+
} catch (error) {
|
|
14387
|
+
process.stderr.write(`${error instanceof Error ? error.message : String(error)}
|
|
14388
|
+
`);
|
|
14389
|
+
return 2;
|
|
14390
|
+
}
|
|
14391
|
+
const verdict = checkRetention(await planClaudeRetentionFix(paths), everyDays);
|
|
14392
|
+
if (!verdict.ok && !flags.includes("--override-retention")) {
|
|
14393
|
+
process.stderr.write(`${verdict.reason}
|
|
14394
|
+
`);
|
|
14395
|
+
return 2;
|
|
14396
|
+
}
|
|
14397
|
+
try {
|
|
14398
|
+
loadShipConfig();
|
|
14399
|
+
} catch (error) {
|
|
14400
|
+
process.stderr.write(`${error instanceof Error ? error.message : String(error)}
|
|
14401
|
+
`);
|
|
14402
|
+
return 2;
|
|
14403
|
+
}
|
|
14404
|
+
const result = await installSchedule(env, { everyDays, command: scheduledCommand(), pathEnv: process.env.PATH });
|
|
14405
|
+
if (result.printed) {
|
|
14406
|
+
process.stdout.write(`Windows: nothing written. Run this to schedule it:
|
|
14407
|
+
|
|
14408
|
+
${result.printed}
|
|
14409
|
+
`);
|
|
14410
|
+
return 0;
|
|
14411
|
+
}
|
|
14412
|
+
for (const file of result.written) process.stdout.write(`wrote ${file}
|
|
14413
|
+
`);
|
|
14414
|
+
process.stdout.write(
|
|
14415
|
+
result.activated ? `scheduled: import --ship every ${everyDays} days
|
|
14416
|
+
` : `files written, but the scheduler didn't load them \u2014 log out and in, or load them by hand
|
|
14417
|
+
`
|
|
14418
|
+
);
|
|
14419
|
+
return result.activated ? 0 : 1;
|
|
14420
|
+
}
|
|
14421
|
+
if (action === "remove") {
|
|
14422
|
+
const { removed } = await removeSchedule(env);
|
|
14423
|
+
process.stdout.write(removed.length ? removed.map((f) => `removed ${f}
|
|
14424
|
+
`).join("") : "no schedule installed\n");
|
|
14425
|
+
return 0;
|
|
14426
|
+
}
|
|
14427
|
+
if (action === "status") {
|
|
14428
|
+
const status = await scheduleStatus(env);
|
|
14429
|
+
if (!status.installed) {
|
|
14430
|
+
process.stdout.write("no schedule installed\n");
|
|
14431
|
+
return 0;
|
|
14432
|
+
}
|
|
14433
|
+
process.stdout.write(
|
|
14434
|
+
`installed: every ${status.everyDays ?? "?"} days, ${status.active ? "loaded" : "not loaded"}
|
|
14435
|
+
` + status.files.map((f) => ` ${f}
|
|
14436
|
+
`).join("") + ` log: ${status.log}
|
|
14437
|
+
`
|
|
14438
|
+
);
|
|
14439
|
+
return 0;
|
|
14440
|
+
}
|
|
14441
|
+
process.stderr.write("usage: ascenda-history-import schedule <install [--every 14d] [--override-retention] | remove | status>\n");
|
|
14442
|
+
return 2;
|
|
14443
|
+
}
|
|
12877
14444
|
default: {
|
|
12878
14445
|
process.stderr.write(
|
|
12879
|
-
"usage: ascenda-history-import <scan [--json] | import [--ship] | fix-retention [--apply] | archive [--verify|--list|--restore <dir>|--prune]>\n"
|
|
14446
|
+
"usage: ascenda-history-import <participate <code> | scan [--json] | import [--ship] [--git] | schedule <install|remove|status> | fix-retention [--apply] | archive [--verify|--list|--restore <dir>|--prune]>\n"
|
|
12880
14447
|
);
|
|
12881
14448
|
return command === void 0 || command === "--help" ? 0 : 2;
|
|
12882
14449
|
}
|