worktrust 0.11.6 → 0.11.7

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/remote-daemon.mjs CHANGED
@@ -14,7 +14,10 @@ import { basename } from "node:path";
14
14
  import * as P from "./remote-protocol.mjs";
15
15
  import { confirmedFingerprints, controllerKeys, loadChannels, loadEndorsements, loadPhones, loadProjects, loadRoots, loadSettings, readJson, saveChannels, saveEndorsements, savePhones, saveProjects, saveSettings, writeJson } from "./remote-store.mjs";
16
16
  import { acceptEndorsement } from "./remote-endorse.mjs";
17
- import { createProject, rootLabel, worktreeMain } from "./remote-projects.mjs";
17
+ import { createProject, rootLabel, sessionProjects, worktreeMain } from "./remote-projects.mjs";
18
+ import { agentOptionsOf } from "./remote-inventory.mjs";
19
+ import { allowedModes, applySettingsChange } from "./remote-settings.mjs";
20
+ import { adminInventory } from "./remote-admin.mjs";
18
21
 
19
22
  // What a paused computer still answers: reading, configuring, disconnecting, and taking work away (a pipeline's cancel).
20
23
  const LIVE_COMMANDS = new Set(["preview.live_start", "preview.live_input", "preview.live_viewport", "preview.live_follow"]);
@@ -30,11 +33,21 @@ export function createDaemonCore(o) {
30
33
  const persist = () => saveChannels([...channels.values()]);
31
34
  let sessions = null, approvals = o.approvals ?? null, releases = null;
32
35
 
36
+ /**
37
+ * THE 0.11.7 INVENTORY FIELDS REACH ONLY A PHONE THAT ASKED FOR THEM (inventory.get `extended`): an older phone refuses
38
+ * unknown keys, so every other channel gets the inventory without them. Kept per phone for the daemon's life; a phone
39
+ * asks again on every inventory.get.
40
+ */
41
+ const extendedPeers = new Set();
42
+ const EXTENDED_KEYS = ["agent_options", "modes_allowed", "admin", "folders", "connections"];
43
+ const bodyFor = (channel, record) => (record.type !== "device.inventory" || extendedPeers.has(channel.peer_device_id) ? record.body
44
+ : Object.fromEntries(Object.entries(record.body).filter(([key]) => !EXTENDED_KEYS.includes(key))));
45
+
33
46
  function sealAll(record) {
34
47
  for (const [id, channel] of channels) {
35
48
  if (!confirmed().has(channel.peer_fingerprint)) { channels.delete(id); continue; } // a revoked phone hears nothing
36
49
  const draft = { protocol_version: channel.protocol_version, session_id: record.session_id, device_id: self, event_seq: record.event_seq, type: record.type, occurred_at: record.occurred_at, command_id: record.command_id, notify: record.notify, ...(record.lane ? { lane: record.lane } : {}) };
37
- const sealed = P.sealEvent(channel, draft, record.body, o.random);
50
+ const sealed = P.sealEvent(channel, draft, bodyFor(channel, record), o.random);
38
51
  if (!sealed.ok) { o.log("seal_refused", { type: record.type, code: sealed.code }); continue; }
39
52
  channels.set(id, sealed.value.channel);
40
53
  o.send({ frame: "event", envelope: sealed.value.envelope });
@@ -72,17 +85,24 @@ export function createDaemonCore(o) {
72
85
 
73
86
  function inventoryBody(refresh) {
74
87
  const settings = loadSettings();
88
+ const inv = o.inventory(refresh);
75
89
  return {
76
90
  remote_enabled: settings.enabled && settings.paused === null,
77
91
  default_adapter: settings.default_adapter ?? null,
78
92
  default_model: settings.default_model ?? null,
79
- adapters: o.inventory(refresh).reports,
93
+ adapters: inv.reports,
80
94
  // A worktree names its main repository (`main`), only when it is one: a phone groups its sessions under that project.
81
- projects: loadProjects().slice(0, 30).map((p) => {
95
+ // 0.11.7: the existing git projects inside each root follow the granted ones (root_id set), 30 in all.
96
+ projects: (o.projectSecret ? sessionProjects({ projects: loadProjects, roots: loadRoots, projectSecret: o.projectSecret }) : loadProjects().slice(0, 30)).map((p) => {
82
97
  const main = worktreeMain(p.path);
83
98
  return { project_id: p.project_id, label: (basename(p.path) || p.path).slice(0, 256), path: p.path.slice(0, 4096), last_used_at: null, root_id: p.root_id ?? null, ...(main ? { main: main.slice(0, 4096) } : {}) };
84
99
  }),
85
100
  roots: loadRoots().slice(0, 20).map((r) => ({ root_id: r.root_id, label: rootLabel(r.path), git_init: r.git_init === true })),
101
+ // Sealed only for a phone that asked `extended` (bodyFor above): what each agent offers, and the keyboard's ceiling.
102
+ ...(inv.features ? { agent_options: agentOptionsOf(inv), modes_allowed: allowedModes(settings) } : {}),
103
+ // Part B, also only for an `extended` phone: the admin switch, the folders this computer suggests (by its own ids),
104
+ // and the phones and browsers linked to it (remote-admin.mjs).
105
+ ...adminInventory({ projectSecret: o.projectSecret, settings }),
86
106
  // Every session this computer knows, live or in the journal, newest activity first, with its name and its release task.
87
107
  sessions: (sessions?.listAll?.() ?? sessions?.list() ?? []).map((s) => ({ ...s, ...(releases?.ownerOf(s.session_id) ?? {}) })).slice(0, 100),
88
108
  };
@@ -100,7 +120,29 @@ export function createDaemonCore(o) {
100
120
  emit(env.session_id, "command.rejected", { reason }, env.command_id);
101
121
  }
102
122
 
103
- async function configure(payload) {
123
+ /**
124
+ * PART B: one settings change from the app or the web (device.configure `settings_change`). applySettingsChange checks
125
+ * `remote admin on`, then the issuer-signed proof against THIS computer's pinned keys, device id and account (o.local,
126
+ * never the payload), then resolves the change from this computer's own lists by id. The run terminal says it in words.
127
+ */
128
+ function settingsChange(env, sent) {
129
+ const done = applySettingsChange(sent.change, { kind: "admin", proof: sent.proof, issuerKeys: o.issuerKeys, claims: o.local.claims, now: o.now() });
130
+ if (!done.ok) { o.log("settings_refused", { code: done.code ?? "not_allowed" }); return done.code ?? "not_allowed"; }
131
+ const by = loadPhones().confirmed.find((p) => p.device_id === env.sender_device_id);
132
+ o.log("settings_changed", { setting: done.setting, by: by?.name ?? by?.fingerprint ?? env.sender_device_id });
133
+ emit(null, "device.inventory", inventoryBody(false));
134
+ return "taken";
135
+ }
136
+
137
+ /** A phone's or browser's own name (inventory.get `device_name`, validated by the protocol), kept with its record here. */
138
+ function rememberName(deviceId, name) {
139
+ const phones = loadPhones();
140
+ if (!phones.confirmed.some((p) => p.device_id === deviceId && p.name !== name)) return;
141
+ savePhones({ ...phones, confirmed: phones.confirmed.map((p) => (p.device_id === deviceId ? { ...p, name: name.slice(0, 64) } : p)) });
142
+ }
143
+
144
+ async function configure(payload, env) {
145
+ if (payload.settings_change) return settingsChange(env, payload.settings_change);
104
146
  const settings = loadSettings();
105
147
  if (payload.remote_enabled === true && settings.paused === "desk") return "remote_paused"; // the desk's pause is the person's, at the keyboard
106
148
  const next = { ...settings };
@@ -137,8 +179,13 @@ export function createDaemonCore(o) {
137
179
  const settings = loadSettings();
138
180
  if (!settings.enabled) return "remote_paused";
139
181
  if (settings.paused !== null && !DEVICE_COMMANDS.has(env.type)) return "remote_paused";
140
- if (env.type === "inventory.get") { emit(null, "device.inventory", inventoryBody(payload.refresh_models)); return "taken"; }
141
- if (env.type === "device.configure") return configure(payload);
182
+ if (env.type === "inventory.get") {
183
+ if (payload.extended === true && env.sender_device_id) extendedPeers.add(env.sender_device_id);
184
+ if (payload.device_name && env.sender_device_id) rememberName(env.sender_device_id, payload.device_name);
185
+ emit(null, "device.inventory", inventoryBody(payload.refresh_models));
186
+ return "taken";
187
+ }
188
+ if (env.type === "device.configure") return configure(payload, env);
142
189
  if (env.type === "status.get" && payload.scope === "device") { emit(null, "device.inventory", inventoryBody(false)); return "taken"; }
143
190
  if (env.type === "pairing.revoke") return "taken";
144
191
  if (env.type === "project.create") {
@@ -210,6 +257,8 @@ export function createDaemonCore(o) {
210
257
  writeJson("invite.json", { ...live, used: true, used_at: o.now(), used_by: phone.fingerprint });
211
258
  savePhones({ ...phones, removed: phones.removed.filter((p) => p.device_id !== phone.device_id), pending: phones.pending.filter((p) => p.fingerprint !== phone.fingerprint), confirmed: [...phones.confirmed.filter((p) => p.fingerprint !== phone.fingerprint), { ...phone, how: "qr", confirmed_at: o.now() }] });
212
259
  }
260
+ // Last seen (0.11.7, `remote connections`): the moment this phone last opened a channel, kept with it on this computer only.
261
+ { const now = loadPhones(); savePhones({ ...now, confirmed: now.confirmed.map((p) => (p.fingerprint === phone.fingerprint ? { ...p, seen_at: o.now() } : p)) }); }
213
262
  for (const [id, c] of channels) if (c.peer_device_id === phone.device_id) channels.delete(id);
214
263
  channels.set(accepted.value.channel.channel_id, accepted.value.channel);
215
264
  persist();
@@ -64,9 +64,37 @@ export function claudeFeatures(help) {
64
64
  // The agent's planning tools run without a prompt (they only write a plan), and one line says to use them (2026-11-08).
65
65
  allowed: /--allowedTools/.test(h),
66
66
  appendPrompt: /--append-system-prompt/.test(h),
67
+ // CLI 0.11.7 (owner, 2026-11-12): the finer modes, the effort levels and the extra directories, each only as its help names it.
68
+ editMode: choices.includes("acceptEdits") ? "acceptEdits" : null,
69
+ autoMode: choices.includes("auto") ? "auto" : null,
70
+ efforts: claudeEfforts(h),
71
+ addDir: /--add-dir <directories?\.\.\.>/.test(h),
67
72
  };
68
73
  }
69
74
 
75
+ /** The effort levels Claude Code's own --effort help lists, in the protocol's order; none when the help names none. */
76
+ export function claudeEfforts(help) {
77
+ const block = /--effort <level>([\s\S]*?)(?=\n\s{2}-|\n\s*\n|$)/.exec(help ?? "")?.[1] ?? "";
78
+ const named = /\(([^)]*)\)/.exec(block.replace(/\s+/g, " "))?.[1]?.split(",").map((w) => w.trim()) ?? [];
79
+ return P.AGENT_EFFORTS.filter((e) => named.includes(e));
80
+ }
81
+
82
+ /**
83
+ * WHAT EACH OFFERED ADAPTER CAN DO BEYOND `permission_modes` (CLI 0.11.7), for an extended inventory: Claude Code
84
+ * structured from its own help (acceptEdits is `edit`, auto is `auto`, --effort, --add-dir); every other report, and Claude
85
+ * Code in a terminal, offers manual and plan as its permission modes say, no effort and one project (Codex's app-server
86
+ * sandbox keeps writable roots empty on purpose; owner decision open, PROTOCOL.md "Agent modes").
87
+ */
88
+ export function agentOptionsOf(inv) {
89
+ const f = inv.features?.["claude-code"] ?? {};
90
+ return inv.reports.filter((r) => r.installed && r.capabilities.start).map((r) => {
91
+ const base = r.capabilities.permission_modes.map((m) => (m === "plan" ? "plan" : "manual"));
92
+ if (r.adapter !== "claude-code" || r.mode !== "structured") return { adapter: r.adapter, mode: r.mode, agent_modes: P.AGENT_MODES.filter((m) => base.includes(m)), efforts: [], extra_projects: 0 };
93
+ const modes = new Set([...base, ...(f.editMode ? ["edit"] : []), ...(f.autoMode ? ["auto"] : [])]);
94
+ return { adapter: r.adapter, mode: r.mode, agent_modes: P.AGENT_MODES.filter((m) => modes.has(m)), efforts: [...(f.efforts ?? [])], extra_projects: f.addDir ? P.MAX_EXTRA_PROJECTS : 0 };
95
+ });
96
+ }
97
+
70
98
  /** The model aliases Claude Code's own --model help names, in its order; none when the help names none. */
71
99
  export function claudeAliases(help) {
72
100
  const block = /--model <model>([\s\S]*?)(?=\n\s{2}-|\n\s*\n|$)/.exec(help ?? "")?.[1]?.replace(/\s+/g, " ") ?? "";
@@ -26,13 +26,17 @@ export const renewBytes = (body) => P.concatBytes(RENEW, P.canonicalBytes(body))
26
26
 
27
27
  export class IssuerMissing extends Error {}
28
28
  export class PairingRefused extends Error {}
29
+ /** The request's window ended with no approval (0.11.7: the terminal offers a new QR code). */
30
+ export class PairingExpired extends PairingRefused {}
31
+ /** The person denied it on the phone or in the browser (0.11.7). */
32
+ export class PairingDenied extends PairingRefused {}
29
33
 
30
34
  async function post(origin, path, body) {
31
35
  const response = await fetch(`${origin}${path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body), signal: AbortSignal.timeout(20_000) });
32
36
  return { status: response.status, json: await response.json().catch(() => ({})) };
33
37
  }
34
38
 
35
- /** `remote enable`'s question: the app's QR here (Enter), or the browser. Not a terminal, or --yes: the browser, as before. */
39
+ /** Which road, the app's QR here (Enter) or the browser; not a terminal, or --yes: the browser. Since 0.11.7 the person names the road (`remote app` | `remote web`, or the menu); kept for a caller that asks. */
36
40
  export async function chooseRoad({ interactive = Boolean(process.stdin.isTTY), yes = false, prompt = null } = {}) {
37
41
  if (!interactive || yes) return "web";
38
42
  const rl = prompt ? null : createInterface({ input: process.stdin, output: process.stdout });
@@ -45,7 +49,7 @@ export async function chooseRoad({ interactive = Boolean(process.stdin.isTTY), y
45
49
  * Pair, and return the verified binding. `keys` holds the secret pair (never sent), `issuerKeys` the pinned keys. `road`:
46
50
  * "web" opens the approval page in the browser; "app" draws its link with `showQr` for the WorkTrust app and opens nothing.
47
51
  */
48
- export async function pairComputer({ origin, secret, publicKeys, host, os, device = false, road = "web", showQr = () => {}, issuerKeys, say, openBrowser, now = Date.now }) {
52
+ export async function pairComputer({ origin, secret, publicKeys, host, os, device = false, road = "web", showQr = () => {}, issuerKeys, say, openBrowser, now = Date.now, countdown = null }) {
49
53
  const verifier = randomBytes(32).toString("base64url");
50
54
  const code_challenge = createHash("sha256").update(verifier).digest("base64url");
51
55
  const state = randomBytes(24).toString("base64url");
@@ -62,12 +66,16 @@ export async function pairComputer({ origin, secret, publicKeys, host, os, devic
62
66
  });
63
67
  await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
64
68
  }
69
+ let bar = null;
70
+ const settle = (line) => { bar?.stop(line); bar = null; };
65
71
  try {
66
72
  const pairing = await post(origin, "/api/remote/pair", { flow: device ? "device" : "loopback", host, os, ...claim, code_challenge_method: "S256", proof, ...(device ? {} : { port: server.address().port, state }) }).catch(() => null);
67
73
  if (!pairing) throw new PairingRefused(`cannot reach ${origin}`);
68
74
  if (pairing.status === 404) throw new IssuerMissing(`${origin} has no remote-key issuer yet (POST /api/remote/pair answered 404). Nothing was changed; remote control needs a Passport app with the issuer (docs/remote-agents/ISSUER.md).`);
69
75
  if (pairing.status !== 200) throw new PairingRefused(`pairing refused (${pairing.json.error ?? pairing.status})`);
70
76
  const { device_code, user_code, expires_in = 600, interval = 3, authorize_url, verification_uri, features = [] } = pairing.json;
77
+ // THE WINDOW IS THE ISSUER'S (0.11.7): its expires_at when it says one, else its expires_in from now; the bar drains over it.
78
+ const asked = now(), until = Number.isFinite(pairing.json.expires_at) ? pairing.json.expires_at : asked + expires_in * 1000;
71
79
  if (!features.includes("remote-binding-v1")) throw new PairingRefused(`${origin} does not offer remote bindings (remote-binding-v1)`);
72
80
  const fingerprint = P.deviceFingerprint(publicKeys);
73
81
  say(` Your code: ${user_code} This computer's remote key: ${fingerprint}`);
@@ -85,7 +93,7 @@ export async function pairComputer({ origin, secret, publicKeys, host, os, devic
85
93
  // The browser's one-time code arrives at 127.0.0.1; a phone's approval only by polling (device code and verifier).
86
94
  let code = null;
87
95
  void answer.then((c) => { code = c; });
88
- const until = now() + expires_in * 1000;
96
+ bar = countdown?.({ expiresAt: until, windowMs: until - asked }) ?? null;
89
97
  let wait = Math.max(1, interval) * 1000;
90
98
  while (!code && !exchanged && now() < until) {
91
99
  await Promise.race([answer, new Promise((resolve) => setTimeout(resolve, wait))]);
@@ -93,22 +101,27 @@ export async function pairComputer({ origin, secret, publicKeys, host, os, devic
93
101
  const reply = await post(origin, "/api/remote/token", { device_code, code_verifier: verifier }).catch(() => null);
94
102
  if (reply?.status === 200) exchanged = reply;
95
103
  else if (reply?.json?.error === "slow_down") wait += 2000;
96
- else if (reply?.json?.error === "access_denied" || reply?.json?.error === "expired_token") throw new PairingRefused(`pairing ended (${reply.json.error})`);
104
+ else if (reply?.json?.error === "access_denied") { settle(`Denied ${road === "app" ? "on your phone" : "in the browser"}. Nothing was changed.`); throw new PairingDenied("pairing ended (access_denied)"); }
105
+ else if (reply?.json?.error === "expired_token") { settle("This request expired."); throw new PairingExpired("pairing ended (expired_token)"); }
97
106
  // authorization_pending, or invalid_grant from an issuer before 2026-11-12 (no codeless loopback poll): wait on.
98
107
  }
99
- if (!exchanged && !code) throw new PairingRefused("no approval arrived in time");
108
+ if (!exchanged && !code) { settle("This request expired."); throw new PairingExpired("no approval arrived in time"); }
109
+ settle(code || road !== "app" ? "✓ Approved in the browser" : "✓ Approved on your phone");
100
110
  if (!exchanged) exchanged = await post(origin, "/api/remote/token", { device_code, code, code_verifier: verifier });
101
111
  } else {
102
112
  say(` On any device open ${verification_uri} and type the code.`);
103
- const until = now() + expires_in * 1000;
113
+ bar = countdown?.({ expiresAt: until, windowMs: until - asked }) ?? null;
104
114
  let wait = interval * 1000;
105
115
  while (now() < until) {
106
116
  await new Promise((resolve) => setTimeout(resolve, wait));
107
117
  const reply = await post(origin, "/api/remote/token", { device_code, code_verifier: verifier }).catch(() => null);
108
- if (reply?.status === 200) { exchanged = reply; break; }
118
+ if (reply?.status === 200) { exchanged = reply; settle("✓ Approved"); break; }
109
119
  if (reply?.json?.error === "slow_down") wait += 2000;
110
- else if (reply?.json?.error && reply.json.error !== "authorization_pending") throw new PairingRefused(`pairing ended (${reply.json.error})`);
120
+ else if (reply?.json?.error === "access_denied") { settle("Denied. Nothing was changed."); throw new PairingDenied("pairing ended (access_denied)"); }
121
+ else if (reply?.json?.error === "expired_token") { settle("This request expired."); throw new PairingExpired("pairing ended (expired_token)"); }
122
+ else if (reply?.json?.error && reply.json.error !== "authorization_pending") { settle(); throw new PairingRefused(`pairing ended (${reply.json.error})`); }
111
123
  }
124
+ if (!exchanged) { settle("This request expired."); throw new PairingExpired("no approval arrived in time"); }
112
125
  }
113
126
  if (!exchanged || exchanged.status !== 200 || typeof exchanged.json.binding !== "string") throw new PairingRefused(`the approval could not be exchanged (${exchanged?.json?.error ?? "no answer"})`);
114
127
  if (Object.keys(issuerKeys).length === 0) throw new PairingRefused("this release pins no WorkTrust issuer key yet, so the binding cannot be verified; nothing was saved");
@@ -116,7 +129,7 @@ export async function pairComputer({ origin, secret, publicKeys, host, os, devic
116
129
  if (!verified.ok) throw new PairingRefused(`the binding does not verify (${verified.code}); nothing was saved`);
117
130
  if (verified.value.ed25519_pub !== publicKeys.ed25519_pub || verified.value.x25519_pub !== publicKeys.x25519_pub) throw new PairingRefused("the binding names other keys; nothing was saved");
118
131
  return { binding: exchanged.json.binding, device_id: verified.value.device_id, sub: verified.value.sub, exp: verified.value.exp, account: typeof exchanged.json.account === "string" ? exchanged.json.account.slice(0, 120) : null };
119
- } finally { server?.close(); }
132
+ } finally { settle(); server?.close(); }
120
133
  }
121
134
 
122
135
  /** A fresh binding for the same keys before the old one ends (POST /api/remote/renew). Null when the issuer has none. */
package/remote-policy.mjs CHANGED
@@ -193,6 +193,21 @@ export const REASONS = Object.freeze({
193
193
  other: "only edits inside the project, reviewed test, build and lint commands, and messages shown whole are approved from a phone",
194
194
  });
195
195
 
196
+ /**
197
+ * THE PROJECT AN ACTION IS JUDGED AGAINST (CLI 0.11.7, several projects in one session): the session's main project,
198
+ * unless the file the agent names lies inside one of the session's extra projects (`extraPaths`, resolved at the start
199
+ * from the computer's own inventory, never a phone's path); then that one. The action's files are absolute paths, so the
200
+ * phone shows which project an edit is in.
201
+ */
202
+ export function projectForAction(session, input) {
203
+ const extras = Array.isArray(session?.extraPaths) ? session.extraPaths : [];
204
+ const named = input && typeof input === "object" ? input.file_path ?? input.notebook_path ?? input.path : null;
205
+ if (extras.length === 0 || typeof named !== "string") return session.projectPath;
206
+ const target = canonicalTarget(named, session.projectPath);
207
+ if (!target || isInside(session.projectPath, target)) return session.projectPath;
208
+ return extras.find((p) => isInside(p, target)) ?? session.projectPath;
209
+ }
210
+
196
211
  /** The one gate between a classified action and the phone. Nothing else in the daemon may decide this. */
197
212
  export const phoneMayDecide = (action) => P.APPROVAL_CLASSES.includes(action?.class) && P.isRemoteApprovable(action.class);
198
213
 
@@ -8,10 +8,16 @@
8
8
  * name of [A-Za-z0-9._-] that does not start with a dot and does not exist yet. The computer makes that folder and nothing
9
9
  * else (no parents, no files), checks after making it that it sits directly inside the root, grants it as a project, and
10
10
  * runs `git init` in it only when the person enabled that for the root. Nothing a phone sends names a path.
11
+ *
12
+ * BROAD ROOTS OPEN EXISTING PROJECTS (owner, 2026-11-12: "broad roots, not full access"; CLI 0.11.7). The inventory also
13
+ * lists the git projects that already lie DIRECTLY inside each root (rootProjects), most recently changed first, within
14
+ * the inventory's 30; a phone may start a session in one by the id the inventory gave, never by a path. Each is held to
15
+ * the granted-project rule (canonicalProject: never the home folder or above it, never a folder of secrets) and must
16
+ * still sit directly inside its root once every link is resolved, so a link in a root that points elsewhere opens nothing.
11
17
  */
12
18
  import { execFileSync } from "node:child_process";
13
19
  import { createHmac } from "node:crypto";
14
- import { existsSync, lstatSync, mkdirSync, realpathSync, rmdirSync } from "node:fs";
20
+ import { existsSync, lstatSync, mkdirSync, readdirSync, realpathSync, rmdirSync, statSync } from "node:fs";
15
21
  import { homedir } from "node:os";
16
22
  import { basename, dirname, join, relative, sep } from "node:path";
17
23
  import * as P from "./remote-protocol.mjs";
@@ -85,3 +91,35 @@ export function createProject(o) {
85
91
  return { ok: true, git, project: { project_id, label: o.name.slice(0, 256), path: made.slice(0, 4096), root_id: o.root.root_id } };
86
92
  }
87
93
 
94
+
95
+ /** A git project's folder: it holds `.git` (a folder, or a worktree's file). */
96
+ const isGitProject = (path) => { try { lstatSync(join(path, ".git")); return true; } catch { return false; } };
97
+
98
+ /**
99
+ * The existing git projects directly inside the roots, as session projects { project_id, path, root_id, from_root: true },
100
+ * newest change first, leaving out what `granted` already lists; at most `limit`. Read at the computer, every time.
101
+ */
102
+ export function rootProjects(roots, projectSecret, granted = [], limit = MAX_PROJECTS) {
103
+ const taken = new Set(granted.map((p) => p.path)), found = [];
104
+ for (const r of roots) {
105
+ const root = checkRoot(r.path);
106
+ if (!root.ok || root.path !== r.path) continue; // moved, gone, or now a link elsewhere
107
+ let names = [];
108
+ try { names = readdirSync(root.path, { withFileTypes: true }).filter((d) => (d.isDirectory() || d.isSymbolicLink()) && !d.name.startsWith(".")).map((d) => d.name); } catch { continue; }
109
+ for (const name of names.slice(0, 2000)) {
110
+ const canonical = canonicalProject(join(root.path, name));
111
+ if (!canonical.ok || dirname(canonical.path) !== root.path || taken.has(canonical.path) || !isGitProject(canonical.path)) continue;
112
+ let changed = 0;
113
+ try { changed = statSync(canonical.path).mtimeMs; } catch { continue; }
114
+ taken.add(canonical.path);
115
+ found.push({ project_id: projectIdOf(projectSecret, canonical.path), path: canonical.path, root_id: r.root_id, from_root: true, changed });
116
+ }
117
+ }
118
+ return found.sort((a, b) => b.changed - a.changed).slice(0, Math.max(0, limit)).map(({ changed, ...p }) => p);
119
+ }
120
+
121
+ /** What a session may run in: the granted projects, then the existing projects inside the roots, 30 in all (the inventory's). */
122
+ export function sessionProjects({ projects, roots, projectSecret }) {
123
+ const granted = projects().slice(0, MAX_PROJECTS);
124
+ return [...granted, ...rootProjects(roots(), projectSecret, granted, MAX_PROJECTS - granted.length)];
125
+ }