@reasontrail/cli 0.1.2 → 0.1.4
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/CHANGELOG.md +13 -0
- package/README.md +79 -3
- package/package.json +1 -1
- package/runtime/reasontrail-credential-broker.mjs +43419 -0
- package/runtime/reasontrail-credential-broker.mjs.sha256 +1 -0
- package/src/cli.mjs +98 -11
- package/src/codex-sync.mjs +85 -12
- package/runtime/reasontrail-runtime.mjs +0 -18230
- package/runtime/reasontrail-runtime.mjs.sha256 +0 -1
- package/src/build-info.json +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
099f777f93e5882c75b4ee49f6420fbf76e4cb981a12ecdb91545ad8345e6c09 reasontrail-credential-broker.mjs
|
package/src/cli.mjs
CHANGED
|
@@ -69,13 +69,17 @@ function commandExists(name) {
|
|
|
69
69
|
return spawnSync("sh", ["-c", `command -v ${name}`], { stdio: "ignore" }).status === 0;
|
|
70
70
|
}
|
|
71
71
|
|
|
72
|
+
function osCredentialStoreEnabled() {
|
|
73
|
+
return !(process.env.NODE_ENV === "test" && process.env.REASONTRAIL_TEST_DISABLE_OS_CREDENTIAL_STORE === "1");
|
|
74
|
+
}
|
|
75
|
+
|
|
72
76
|
async function loadCredential(profile) {
|
|
73
77
|
const paths = profilePaths(profile);
|
|
74
|
-
if (process.platform === "darwin" && commandExists("security")) {
|
|
78
|
+
if (osCredentialStoreEnabled() && process.platform === "darwin" && commandExists("security")) {
|
|
75
79
|
const found = spawnSync("security", ["find-generic-password", "-s", KEYCHAIN_SERVICE, "-a", profile, "-w"], { encoding: "utf8" });
|
|
76
80
|
if (found.status === 0 && found.stdout.trim()) return { token: found.stdout.trim(), source: "macOS Keychain" };
|
|
77
81
|
}
|
|
78
|
-
if (process.platform === "linux" && commandExists("secret-tool")) {
|
|
82
|
+
if (osCredentialStoreEnabled() && process.platform === "linux" && commandExists("secret-tool")) {
|
|
79
83
|
const found = spawnSync("secret-tool", ["lookup", "service", KEYCHAIN_SERVICE, "account", profile], { encoding: "utf8" });
|
|
80
84
|
if (found.status === 0 && found.stdout.trim()) return { token: found.stdout.trim(), source: "Secret Service" };
|
|
81
85
|
}
|
|
@@ -87,12 +91,18 @@ async function loadCredential(profile) {
|
|
|
87
91
|
async function storeCredential(profile, token) {
|
|
88
92
|
const paths = profilePaths(profile);
|
|
89
93
|
if (!token.startsWith("rtmcp_")) throw new CliError("That is not a ReasonTrail MCP access token.", 2);
|
|
90
|
-
if (process.platform === "darwin" && commandExists("security")) {
|
|
91
|
-
|
|
94
|
+
if (osCredentialStoreEnabled() && process.platform === "darwin" && commandExists("security")) {
|
|
95
|
+
// Keep the bearer token out of argv. macOS security(1) reads it from
|
|
96
|
+
// stdin when `-w` is the final argument and prompts twice on creation.
|
|
97
|
+
const stored = spawnSync(
|
|
98
|
+
"security",
|
|
99
|
+
["add-generic-password", "-U", "-s", KEYCHAIN_SERVICE, "-a", profile, "-w"],
|
|
100
|
+
{ input: `${token}\n${token}\n`, encoding: "utf8" },
|
|
101
|
+
);
|
|
92
102
|
if (stored.status !== 0) throw new CliError(stored.stderr.trim() || "Could not store the credential in macOS Keychain.");
|
|
93
103
|
return "macOS Keychain";
|
|
94
104
|
}
|
|
95
|
-
if (process.platform === "linux" && commandExists("secret-tool")) {
|
|
105
|
+
if (osCredentialStoreEnabled() && process.platform === "linux" && commandExists("secret-tool")) {
|
|
96
106
|
const stored = spawnSync("secret-tool", ["store", "--label", `ReasonTrail CLI (${profile})`, "service", KEYCHAIN_SERVICE, "account", profile], { input: token, encoding: "utf8" });
|
|
97
107
|
if (stored.status !== 0) throw new CliError(stored.stderr.trim() || "Could not store the credential in Secret Service.");
|
|
98
108
|
return "Secret Service";
|
|
@@ -104,11 +114,11 @@ async function storeCredential(profile, token) {
|
|
|
104
114
|
async function removeCredential(profile) {
|
|
105
115
|
const paths = profilePaths(profile);
|
|
106
116
|
const removed = [];
|
|
107
|
-
if (process.platform === "darwin" && commandExists("security")) {
|
|
117
|
+
if (osCredentialStoreEnabled() && process.platform === "darwin" && commandExists("security")) {
|
|
108
118
|
const result = spawnSync("security", ["delete-generic-password", "-s", KEYCHAIN_SERVICE, "-a", profile], { encoding: "utf8" });
|
|
109
119
|
if (result.status === 0) removed.push("macOS Keychain");
|
|
110
120
|
}
|
|
111
|
-
if (process.platform === "linux" && commandExists("secret-tool")) {
|
|
121
|
+
if (osCredentialStoreEnabled() && process.platform === "linux" && commandExists("secret-tool")) {
|
|
112
122
|
const result = spawnSync("secret-tool", ["clear", "service", KEYCHAIN_SERVICE, "account", profile], { encoding: "utf8" });
|
|
113
123
|
if (result.status === 0) removed.push("Secret Service");
|
|
114
124
|
}
|
|
@@ -836,18 +846,33 @@ async function updateCommand(argv) {
|
|
|
836
846
|
if (Array.isArray(piped.turns) && piped.turns.length > 0) {
|
|
837
847
|
throw new CliError("Conversation turns must come from the authorized Codex capture adapter. Pass --session <native-session-id>; do not reconstruct the transcript in update JSON.", 2);
|
|
838
848
|
}
|
|
849
|
+
// Fields with an authoritative adapter-defined meaning remain execution
|
|
850
|
+
// history. They must not become Inbox proposals merely because the transport
|
|
851
|
+
// previously encoded their type as a prose prefix.
|
|
852
|
+
const operationalEvents = [
|
|
853
|
+
...(piped.operationalEvents || []),
|
|
854
|
+
...(piped.implementationFacts || piped.implementation_facts || []).map((value, index) => ({
|
|
855
|
+
eventType: "IMPLEMENTATION_FACT",
|
|
856
|
+
sourceEventId: `implementation-fact:${index}:${createHash("sha256").update(String(value)).digest("hex")}`,
|
|
857
|
+
summary: String(value),
|
|
858
|
+
})),
|
|
859
|
+
...(piped.taskOutcomes || piped.task_outcomes || []).map((value, index) => ({
|
|
860
|
+
eventType: "TASK_OUTCOME",
|
|
861
|
+
sourceEventId: `task-outcome:${index}:${createHash("sha256").update(String(value)).digest("hex")}`,
|
|
862
|
+
summary: String(value),
|
|
863
|
+
})),
|
|
864
|
+
];
|
|
839
865
|
const labeledFindings = [
|
|
840
866
|
...(piped.findings || []),
|
|
841
867
|
...(piped.discoveries || []).map((value) => `[discovery] ${value}`),
|
|
842
|
-
...(piped.implementationFacts || piped.implementation_facts || []).map((value) => `[implementation fact] ${value}`),
|
|
843
868
|
...(piped.rejectedApproaches || piped.rejected_approaches || []).map((value) => `[rejected approach] ${value}`),
|
|
844
869
|
...(piped.constraints || []).map((value) => `[constraint] ${value}`),
|
|
845
870
|
...(piped.openQuestions || piped.open_questions || []).map((value) => `[open question] ${value}`),
|
|
846
|
-
...(piped.taskOutcomes || piped.task_outcomes || []).map((value) => `[task outcome] ${value}`),
|
|
847
871
|
];
|
|
848
872
|
const args = {
|
|
849
873
|
...piped,
|
|
850
874
|
...(labeledFindings.length ? { findings: labeledFindings } : {}),
|
|
875
|
+
...(operationalEvents.length ? { operationalEvents } : {}),
|
|
851
876
|
...(opts.summary ? { taskSummary: opts.summary } : {}),
|
|
852
877
|
...(opts.remaining_work ? { remainingWork: opts.remaining_work } : {}),
|
|
853
878
|
turns: [],
|
|
@@ -973,7 +998,9 @@ async function bindCommand(argv) {
|
|
|
973
998
|
const slug = repository.projectSlug;
|
|
974
999
|
if (!slug) throw new CliError("ReasonTrail did not return a project for this repository. Nothing was bound.", 2);
|
|
975
1000
|
cfg.bindings ||= {};
|
|
976
|
-
cfg.bindings[root]
|
|
1001
|
+
const priorBinding = cfg.bindings[root];
|
|
1002
|
+
const captureFrom = priorBinding?.projectSlug === slug ? priorBinding.captureFrom : new Date().toISOString();
|
|
1003
|
+
cfg.bindings[root] = { captureFrom, projectSlug: slug, projectId: opts.project_id || null, repositoryId: repository.repositoryId || null, repositoryUrl: repository.url, boundAt: new Date().toISOString() };
|
|
977
1004
|
await saveJson(target.paths.config, cfg);
|
|
978
1005
|
let automaticCapture;
|
|
979
1006
|
try {
|
|
@@ -1164,6 +1191,7 @@ async function syncCommand(argv) {
|
|
|
1164
1191
|
if (sub === "managed") {
|
|
1165
1192
|
const codex = await syncCodex(client, tools, target.paths.dir, target.cfg, {
|
|
1166
1193
|
dryRun: !apply,
|
|
1194
|
+
managed: true,
|
|
1167
1195
|
since: opts.since || null,
|
|
1168
1196
|
project,
|
|
1169
1197
|
session: opts.session || null,
|
|
@@ -1593,6 +1621,8 @@ async function claudeHookCommand(argv) {
|
|
|
1593
1621
|
*/
|
|
1594
1622
|
const RUNTIME_BUNDLE = join(PACKAGE_ROOT, "runtime", "reasontrail-runtime.mjs");
|
|
1595
1623
|
const RUNTIME_CHECKSUM = `${RUNTIME_BUNDLE}.sha256`;
|
|
1624
|
+
const BROKER_BUNDLE = join(PACKAGE_ROOT, "runtime", "reasontrail-credential-broker.mjs");
|
|
1625
|
+
const BROKER_CHECKSUM = `${BROKER_BUNDLE}.sha256`;
|
|
1596
1626
|
|
|
1597
1627
|
async function runtimeBundleIntegrity() {
|
|
1598
1628
|
let bundle;
|
|
@@ -1612,6 +1642,24 @@ async function runtimeBundleIntegrity() {
|
|
|
1612
1642
|
return { state: actual === expected ? "verified" : "mismatch", expected, actual };
|
|
1613
1643
|
}
|
|
1614
1644
|
|
|
1645
|
+
async function brokerBundleIntegrity() {
|
|
1646
|
+
let bundle;
|
|
1647
|
+
let checksum;
|
|
1648
|
+
try {
|
|
1649
|
+
[bundle, checksum] = await Promise.all([
|
|
1650
|
+
readFile(BROKER_BUNDLE),
|
|
1651
|
+
readFile(BROKER_CHECKSUM, "utf8"),
|
|
1652
|
+
]);
|
|
1653
|
+
} catch (error) {
|
|
1654
|
+
if (error?.code === "ENOENT") return { state: "missing" };
|
|
1655
|
+
throw new CliError(`Could not verify the credential-broker bundle: ${error.message}`);
|
|
1656
|
+
}
|
|
1657
|
+
const expected = checksum.trim().split(/\s+/)[0]?.toLowerCase();
|
|
1658
|
+
if (!/^[0-9a-f]{64}$/.test(expected || "")) return { state: "invalid-checksum" };
|
|
1659
|
+
const actual = createHash("sha256").update(bundle).digest("hex");
|
|
1660
|
+
return { state: actual === expected ? "verified" : "mismatch", expected, actual };
|
|
1661
|
+
}
|
|
1662
|
+
|
|
1615
1663
|
async function runtimeConfig(profile) {
|
|
1616
1664
|
return readJson(profilePaths(profile).runtime, null);
|
|
1617
1665
|
}
|
|
@@ -1754,6 +1802,39 @@ async function runtimeCommand(argv) {
|
|
|
1754
1802
|
throw new CliError(`Unknown runtime command '${sub}'.\n\n` + runtimeUsage(), 2);
|
|
1755
1803
|
}
|
|
1756
1804
|
|
|
1805
|
+
function brokerUsage() {
|
|
1806
|
+
return (
|
|
1807
|
+
`Usage: reasontrail broker <command> --profile <development|production>\n\n` +
|
|
1808
|
+
` enroll --label <name> --allow-software-key\n` +
|
|
1809
|
+
` Enroll this user device in the explicitly weaker software-key tier\n` +
|
|
1810
|
+
` devices List this user's enrolled broker devices\n` +
|
|
1811
|
+
` store --project <slug> --name <label> --kind <kind> [--payload-stdin]\n` +
|
|
1812
|
+
` Encrypt locally to this device before upload (managers only on software-key devices)\n` +
|
|
1813
|
+
` migrate --project <slug> --secret <id> --version <number> --acknowledge-one-way-device-migration\n` +
|
|
1814
|
+
` One-way manager migration to this device\n` +
|
|
1815
|
+
` share --project <slug> --secret <id> --target-device <id>\n` +
|
|
1816
|
+
` Re-encrypt for another verified device\n` +
|
|
1817
|
+
` revoke Revoke this device and remove its local key\n` +
|
|
1818
|
+
` mcp Serve approved fixed operations over local MCP\n`
|
|
1819
|
+
);
|
|
1820
|
+
}
|
|
1821
|
+
|
|
1822
|
+
async function brokerCommand(argv) {
|
|
1823
|
+
const sub = argv[0];
|
|
1824
|
+
if (!sub || sub === "help" || sub === "--help") return stdout.write(brokerUsage());
|
|
1825
|
+
await resolveTarget(argv.slice(1), { allowMissing: false, confirm: true });
|
|
1826
|
+
const integrity = await brokerBundleIntegrity();
|
|
1827
|
+
if (integrity.state === "missing") {
|
|
1828
|
+
throw new CliError(`The credential-broker bundle or checksum is missing from this installation (${BROKER_BUNDLE}). Reinstall the CLI.`);
|
|
1829
|
+
}
|
|
1830
|
+
if (integrity.state !== "verified") {
|
|
1831
|
+
throw new CliError(`The credential-broker bundle failed its integrity check (${integrity.state}). Reinstall the CLI before using project credentials.`);
|
|
1832
|
+
}
|
|
1833
|
+
const result = spawnSync(process.execPath, [BROKER_BUNDLE, sub, ...argv.slice(1)], { stdio: "inherit" });
|
|
1834
|
+
if (result.error) throw new CliError(`Could not start the credential broker: ${result.error.message}`);
|
|
1835
|
+
process.exitCode = result.status ?? 0;
|
|
1836
|
+
}
|
|
1837
|
+
|
|
1757
1838
|
function helpCommand() {
|
|
1758
1839
|
stdout.write(`ReasonTrail CLI ${VERSION}\n\n` +
|
|
1759
1840
|
`Usage: reasontrail <command> --profile <development|production>\n\n` +
|
|
@@ -1779,16 +1860,21 @@ function helpCommand() {
|
|
|
1779
1860
|
` hook claude Receive a Claude Code lifecycle hook event\n` +
|
|
1780
1861
|
` config endpoint <url> --profile <profile> Configure an isolated named profile\n` +
|
|
1781
1862
|
` runtime enroll|start|status|logout ReasonTrail Runtime on this machine\n` +
|
|
1863
|
+
` broker enroll|devices|store|migrate|share|revoke|mcp Local approved credential operations\n` +
|
|
1782
1864
|
` upgrade Reserved until signed releases exist\n`);
|
|
1783
1865
|
}
|
|
1784
1866
|
|
|
1785
1867
|
async function main() {
|
|
1786
1868
|
const [command, ...argv] = process.argv.slice(2);
|
|
1787
|
-
|
|
1869
|
+
// `broker migrate --version <number>` names the credential version. Keep
|
|
1870
|
+
// that subcommand-owned option out of the CLI-wide executable-version path.
|
|
1871
|
+
const brokerMigration = command === "broker" && argv[0] === "migrate";
|
|
1872
|
+
if (command === "--version" || command === "-v" || (!brokerMigration && (argv.includes("--version") || argv.includes("-v")))) {
|
|
1788
1873
|
const build = await cliBuildIdentity();
|
|
1789
1874
|
return stdout.write(`${VERSION} revision ${build.source_revision || "unknown"}\n`);
|
|
1790
1875
|
}
|
|
1791
1876
|
if (!command || command === "help" || command === "--help" || command === "-h") return helpCommand();
|
|
1877
|
+
if (command === "broker" && (argv[0] === "help" || argv.includes("--help") || argv.includes("-h"))) return brokerCommand(argv);
|
|
1792
1878
|
if (argv.includes("--help") || argv.includes("-h") || argv[0] === "help") return helpCommand();
|
|
1793
1879
|
if (command === "status") return statusCommand(argv);
|
|
1794
1880
|
if (command === "doctor") return doctorCommand(argv);
|
|
@@ -1807,6 +1893,7 @@ async function main() {
|
|
|
1807
1893
|
if (command === "hook" && argv[0] === "claude") return claudeHookCommand(argv.slice(1));
|
|
1808
1894
|
if (command === "config") return configCommand(argv);
|
|
1809
1895
|
if (command === "runtime") return runtimeCommand(argv);
|
|
1896
|
+
if (command === "broker") return brokerCommand(argv);
|
|
1810
1897
|
if (command === "upgrade") throw new CliError("Automatic upgrade is unavailable until versioned signed artifacts are published. No changes were made.", 2);
|
|
1811
1898
|
throw new CliError(`Unknown command '${command}'. Run \`reasontrail help\`.`, 2);
|
|
1812
1899
|
}
|
package/src/codex-sync.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
|
-
import { mkdir, readdir, readFile, writeFile } from "node:fs/promises";
|
|
2
|
+
import { mkdir, readdir, readFile, stat, writeFile } from "node:fs/promises";
|
|
3
3
|
import { homedir } from "node:os";
|
|
4
4
|
import { basename, join, resolve } from "node:path";
|
|
5
5
|
import { spawnSync } from "node:child_process";
|
|
@@ -75,6 +75,12 @@ function isSystemOnlyText(text) {
|
|
|
75
75
|
return false;
|
|
76
76
|
}
|
|
77
77
|
|
|
78
|
+
// Suppress credential-bearing dialogue before managed capture makes an MCP call.
|
|
79
|
+
function containsCredential(text) {
|
|
80
|
+
return /-----BEGIN (?:[A-Z0-9 ]+ )?PRIVATE KEY-----|\b(?:github_pat_|gh[pousr]_|sk-(?:proj-)?|sk_(?:live|test)_|rk_live_|xox[baprs]-)[A-Za-z0-9_-]{16,}|\bBearer\s+[A-Za-z0-9._~+/-]{20,}/i.test(text)
|
|
81
|
+
|| /\b(?:password|client_secret|api[_-]?key|access[_-]?token)\s*["']?\s*[:=]\s*["']?[A-Za-z0-9+/_.=-]{12,}/i.test(text);
|
|
82
|
+
}
|
|
83
|
+
|
|
78
84
|
function isVisibleAssistant(item) {
|
|
79
85
|
// Current rollouts use phase; legacy rollouts may omit both fields.
|
|
80
86
|
const visible = new Set(["commentary", "final", "final_answer"]);
|
|
@@ -144,6 +150,7 @@ export async function parseCodexSessionFile(filePath, threadNames = {}) {
|
|
|
144
150
|
if (identity.error) return { ...identity, filePath };
|
|
145
151
|
const { threadId, parentThreadId, identitySource, historyStartLine } = identity;
|
|
146
152
|
let cwd = identity.cwd;
|
|
153
|
+
let turnCwd = cwd;
|
|
147
154
|
let excludedInheritedTurnCount = 0;
|
|
148
155
|
let startTs = null;
|
|
149
156
|
let endTs = null;
|
|
@@ -162,7 +169,10 @@ export async function parseCodexSessionFile(filePath, threadNames = {}) {
|
|
|
162
169
|
}
|
|
163
170
|
if (!startTs && d.timestamp) startTs = d.timestamp;
|
|
164
171
|
if (d.timestamp) endTs = d.timestamp;
|
|
165
|
-
if (
|
|
172
|
+
if (d.type === "turn_context" && typeof d.payload?.cwd === "string") {
|
|
173
|
+
turnCwd = d.payload.cwd;
|
|
174
|
+
cwd ||= turnCwd;
|
|
175
|
+
}
|
|
166
176
|
|
|
167
177
|
// Only structured runtime error events establish a quota interruption.
|
|
168
178
|
// Messages and tool output may quote error names while discussing code.
|
|
@@ -188,6 +198,7 @@ export async function parseCodexSessionFile(filePath, threadNames = {}) {
|
|
|
188
198
|
rawTurns.push({
|
|
189
199
|
id,
|
|
190
200
|
sourceLine: line,
|
|
201
|
+
cwd: turnCwd,
|
|
191
202
|
role,
|
|
192
203
|
content: cleaned,
|
|
193
204
|
// Missing source timestamps must stay missing. Substituting the
|
|
@@ -218,6 +229,7 @@ export async function parseCodexSessionFile(filePath, threadNames = {}) {
|
|
|
218
229
|
rawTurns.push({
|
|
219
230
|
id,
|
|
220
231
|
sourceLine: line,
|
|
232
|
+
cwd: turnCwd,
|
|
221
233
|
role,
|
|
222
234
|
content: cleaned,
|
|
223
235
|
timestamp: d.timestamp || null,
|
|
@@ -248,6 +260,7 @@ export async function parseCodexSessionFile(filePath, threadNames = {}) {
|
|
|
248
260
|
fingerprint,
|
|
249
261
|
nativeMessageId: t.id,
|
|
250
262
|
sourceLine: t.sourceLine,
|
|
263
|
+
cwd: t.cwd,
|
|
251
264
|
role: t.role,
|
|
252
265
|
content: t.content,
|
|
253
266
|
sequence: turns.length,
|
|
@@ -325,10 +338,32 @@ export async function discoverAndMapCodexSessions(options = {}) {
|
|
|
325
338
|
};
|
|
326
339
|
|
|
327
340
|
const bindings = options.bindings || {};
|
|
341
|
+
const gitCommon = new Map();
|
|
342
|
+
function commonDir(root) {
|
|
343
|
+
if (!root) return null;
|
|
344
|
+
if (!gitCommon.has(root)) {
|
|
345
|
+
const result = spawnSync("git", ["rev-parse", "--path-format=absolute", "--git-common-dir"], { cwd: root, encoding: "utf8" });
|
|
346
|
+
gitCommon.set(root, result.status === 0 ? result.stdout.trim() : null);
|
|
347
|
+
}
|
|
348
|
+
return gitCommon.get(root);
|
|
349
|
+
}
|
|
350
|
+
function bindingOf(cwd) {
|
|
351
|
+
const root = resolveGit(cwd);
|
|
352
|
+
if (!root) return null;
|
|
353
|
+
if (bindings[root]) return bindings[root];
|
|
354
|
+
const common = commonDir(root);
|
|
355
|
+
const siblings = common ? Object.entries(bindings).filter(([path]) => common === commonDir(path)).map(([, value]) => value) : [];
|
|
356
|
+
return new Set(siblings.map(binding => binding.projectSlug)).size === 1 ? siblings[0] : null;
|
|
357
|
+
}
|
|
358
|
+
const starts = Object.values(bindings).filter(b => !options.project || b.projectSlug === options.project)
|
|
359
|
+
.map(b => Date.parse(b.captureFrom ?? "")).filter(Number.isFinite);
|
|
360
|
+
const earliest = starts.length ? Math.min(...starts) : 0;
|
|
328
361
|
const sessions = [];
|
|
362
|
+
const observedProjects = new Map();
|
|
329
363
|
const parseFailures = [];
|
|
330
364
|
|
|
331
365
|
for (const file of files) {
|
|
366
|
+
if (options.managed && earliest && (await stat(file)).mtimeMs < earliest) continue;
|
|
332
367
|
const parsed = await parseCodexSessionFile(file, threadNames);
|
|
333
368
|
if (parsed.error) {
|
|
334
369
|
parseFailures.push({ filePath: file, reason: parsed.error });
|
|
@@ -352,13 +387,27 @@ export async function discoverAndMapCodexSessions(options = {}) {
|
|
|
352
387
|
}
|
|
353
388
|
|
|
354
389
|
const gitRoot = resolveGit(parsed.cwd);
|
|
355
|
-
const
|
|
356
|
-
const
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
390
|
+
const selected = parsed.turns.map(turn => ({ turn, binding: bindingOf(turn.cwd) }));
|
|
391
|
+
const slugs = new Set(selected.map(row => row.binding?.projectSlug).filter(Boolean));
|
|
392
|
+
const seen = observedProjects.get(parsed.threadId) ?? new Set();
|
|
393
|
+
for (const slug of slugs) seen.add(slug);
|
|
394
|
+
observedProjects.set(parsed.threadId, seen);
|
|
395
|
+
if (seen.size > 1) {
|
|
396
|
+
parseFailures.push({ filePath: file, reason: "multiple_bound_projects" });
|
|
360
397
|
continue;
|
|
361
398
|
}
|
|
399
|
+
const projectSlug = [...slugs][0] ?? bindingOf(parsed.cwd)?.projectSlug ?? null;
|
|
400
|
+
if (options.project && projectSlug !== options.project) continue;
|
|
401
|
+
if (projectSlug) {
|
|
402
|
+
const scoped = selected.filter(({ turn, binding }) => binding?.projectSlug === projectSlug
|
|
403
|
+
&& (!options.managed || !containsCredential(turn.content))
|
|
404
|
+
&& (!options.managed || !binding.captureFrom || Date.parse(turn.timestamp) >= Date.parse(binding.captureFrom)));
|
|
405
|
+
if (!scoped.length) continue;
|
|
406
|
+
if (scoped.length !== parsed.turns.length || options.managed) {
|
|
407
|
+
parsed.turns = scoped.map(({ turn }) => ({ ...turn, messageId: turn.stableMessageId }));
|
|
408
|
+
parsed.title = parsed.turns.find(turn => turn.role === "user")?.content.split("\n")[0].slice(0, 120) || "Codex project conversation";
|
|
409
|
+
}
|
|
410
|
+
}
|
|
362
411
|
|
|
363
412
|
const mapped = Boolean(projectSlug);
|
|
364
413
|
sessions.push({
|
|
@@ -377,13 +426,34 @@ export async function discoverAndMapCodexSessions(options = {}) {
|
|
|
377
426
|
if (!existing) {
|
|
378
427
|
byThread.set(s.threadId, s);
|
|
379
428
|
} else {
|
|
380
|
-
//
|
|
381
|
-
if (
|
|
382
|
-
|
|
429
|
+
// Desktop may rotate one native thread into several rollout files.
|
|
430
|
+
if (existing.projectSlug !== s.projectSlug) {
|
|
431
|
+
parseFailures.push({ filePath: s.filePath, reason: "rotated_project_mismatch" });
|
|
432
|
+
existing.ambiguous = true;
|
|
433
|
+
continue;
|
|
434
|
+
}
|
|
435
|
+
const known = new Map(existing.turns.map(turn => [turn.timestamp
|
|
436
|
+
? JSON.stringify([turn.timestamp, turn.role, turn.content]) : turn.fingerprint, turn]));
|
|
437
|
+
for (const turn of s.turns) {
|
|
438
|
+
const key = turn.timestamp ? JSON.stringify([turn.timestamp, turn.role, turn.content]) : turn.fingerprint;
|
|
439
|
+
if (!known.has(key)) known.set(key, turn);
|
|
440
|
+
}
|
|
441
|
+
existing.turns = [...known.values()].sort((a, b) => (a.timestamp ?? "").localeCompare(b.timestamp ?? ""))
|
|
442
|
+
.map(turn => ({ ...turn, messageId: turn.stableMessageId }));
|
|
443
|
+
if ((s.updatedAt ?? "") > (existing.updatedAt ?? "")) {
|
|
444
|
+
existing.updatedAt = s.updatedAt;
|
|
445
|
+
existing.interrupted = s.interrupted;
|
|
446
|
+
existing.interruptionReason = s.interruptionReason;
|
|
383
447
|
}
|
|
384
448
|
}
|
|
385
449
|
}
|
|
386
|
-
const resultSessions = Array.from(byThread.values());
|
|
450
|
+
const resultSessions = Array.from(byThread.values()).filter(s => !s.ambiguous && observedProjects.get(s.threadId)?.size <= 1);
|
|
451
|
+
for (const session of resultSessions) {
|
|
452
|
+
session.turnCount = session.turns.length;
|
|
453
|
+
session.userTurnCount = session.turns.filter(turn => turn.role === "user").length;
|
|
454
|
+
session.assistantTurnCount = session.turnCount - session.userTurnCount;
|
|
455
|
+
session.sourceCheckpoint = `codex:${session.threadId}:${session.turnCount}:${createHash("sha256").update(session.turns.map(t => t.fingerprint).join("\0")).digest("hex")}`;
|
|
456
|
+
}
|
|
387
457
|
|
|
388
458
|
// Sort chronologically
|
|
389
459
|
resultSessions.sort((a, b) => new Date(a.updatedAt || 0).getTime() - new Date(b.updatedAt || 0).getTime());
|
|
@@ -415,7 +485,9 @@ function turnChunks(turns) {
|
|
|
415
485
|
if (turns.length === 0) return [[]];
|
|
416
486
|
const chunks = [];
|
|
417
487
|
for (let offset = 0; offset < turns.length; offset += MAX_RECONCILIATION_TURNS) {
|
|
418
|
-
chunks.push(turns.slice(offset, offset + MAX_RECONCILIATION_TURNS)
|
|
488
|
+
chunks.push(turns.slice(offset, offset + MAX_RECONCILIATION_TURNS).map(
|
|
489
|
+
({ messageId, role, content, sequence, timestamp }) => ({ messageId, role, content, sequence, timestamp }),
|
|
490
|
+
));
|
|
419
491
|
}
|
|
420
492
|
return chunks;
|
|
421
493
|
}
|
|
@@ -461,6 +533,7 @@ export async function syncCodex(client, tools, configDir, config, options = {})
|
|
|
461
533
|
const bindings = config.bindings || {};
|
|
462
534
|
const sessions = await discoverAndMapCodexSessions({
|
|
463
535
|
codexHome: options.codexHome || defaultCodexHome(),
|
|
536
|
+
managed: options.managed === true,
|
|
464
537
|
bindings,
|
|
465
538
|
since: options.since,
|
|
466
539
|
session: options.session,
|