@futuvara/connect 0.3.5 → 0.4.0

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/bin/connect.js CHANGED
@@ -4,7 +4,8 @@
4
4
  // environment (FUTUVARA_KEY_<PROJECT>) and never written to a file.
5
5
  import { parseArgs as nodeParseArgs } from "node:util";
6
6
  import { spawnSync } from "node:child_process";
7
- import { mkdirSync, writeFileSync, readFileSync, existsSync, realpathSync, rmSync, chmodSync, readdirSync } from "node:fs";
7
+ import { createHash } from "node:crypto";
8
+ import { mkdirSync, writeFileSync, readFileSync, existsSync, realpathSync, rmSync, chmodSync, readdirSync, statSync } from "node:fs";
8
9
  import { homedir, tmpdir } from "node:os";
9
10
  import { basename, join, dirname } from "node:path";
10
11
  import { fileURLToPath } from "node:url";
@@ -117,13 +118,16 @@ export const SESSION_PATH = "/api/connect/session";
117
118
 
118
119
  /**
119
120
  * A SessionStart / SessionEnd hook: tells Futuvara the session started or ended, so it shows
120
- * on Terminals from its first second and leaves when it closes. Silent and never blocking:
121
- * no key, no network or a slow server (5 s) and it simply exits.
121
+ * on Terminals from its first second and leaves when it closes. It sends Claude Code's own
122
+ * session id, so a second session in the same worktree keeps the row, and prints the reply's
123
+ * `context` (Claude Code adds a SessionStart hook's output to the session: the report_session
124
+ * reminder). Never blocking: no key, no network or a slow server (5 s) and it simply exits.
122
125
  */
123
126
  export const sessionHook = (base, variable, event) =>
124
127
  `node -e "const k=process.env.${variable};if(k){let i={};try{i=JSON.parse(require('fs').readFileSync(0,'utf8'))}catch(e){}${WHERE_JS}` +
125
128
  `fetch('${base}${SESSION_PATH}',{method:'POST',headers:{...where,'content-type':'application/json',authorization:'Bearer '+k},` +
126
- `body:JSON.stringify({event:'${event}',source:i.source,reason:i.reason}),signal:AbortSignal.timeout(5000)}).catch(()=>{})}"`;
129
+ `body:JSON.stringify({event:'${event}',source:i.source,reason:i.reason,session:i.session_id}),signal:AbortSignal.timeout(5000)})` +
130
+ `.then(r=>r.json()).then(j=>{if(j.context)console.log(j.context)}).catch(()=>{})}"`;
127
131
 
128
132
  /**
129
133
  * A PostToolUse hook on Write / Edit: sends the markdown file the session just wrote (a plan,
@@ -139,6 +143,89 @@ export const docHook = (base, variable) =>
139
143
  `if(c&&p&&c.length<2e6)fetch('${base}${SESSION_PATH}',{method:'POST',headers:{...where,'content-type':'application/json',authorization:'Bearer '+k},` +
140
144
  `body:JSON.stringify({event:'doc',path:p,content:c}),signal:AbortSignal.timeout(5000)}).catch(()=>{})}}"`;
141
145
 
146
+ /** `report` runs at most this often per worktree and branch, except at a session's start. */
147
+ export const REPORT_EVERY_MS = 60_000;
148
+ /** In every report file's name, so `futuvaraSettings` knows its own report hooks. */
149
+ const REPORT_MARK = "futuvara-report-";
150
+ const REPORT_RUNNER = "npx -y @futuvara/connect@latest";
151
+
152
+ /** The file `report` and its hook share for one worktree and branch: touched at each send, it holds each markdown file's last-sent hash. */
153
+ export const reportStamp = (top, branch, dir = tmpdir()) =>
154
+ join(dir, `${REPORT_MARK}${createHash("sha1").update(`${top}|${branch}`).digest("hex").slice(0, 16)}.json`);
155
+
156
+ /**
157
+ * A Stop hook (after each turn, at most once a minute) and a second SessionStart hook (`now`): start
158
+ * `report` in the background, so the worktree's facts — the local worktree dashboard's — and markdown
159
+ * changed outside Write/Edit reach Terminals (docs/plans/2026-11-10-terminals-mcp-sessions.md, 6.2).
160
+ * It only decides and spawns, so a turn never waits on git; no key, no repository and it exits.
161
+ */
162
+ export const reportHook = (base, variable, now = false, runner = REPORT_RUNNER) =>
163
+ `node -e "const k=process.env.${variable};if(k){${WHERE_JS}const fs=require('fs'),t=g('rev-parse --show-toplevel');` +
164
+ `const f=require('path').join(require('os').tmpdir(),'${REPORT_MARK}'+require('crypto').createHash('sha1').update(t+'|'+where['X-Futuvara-Branch']).digest('hex').slice(0,16)+'.json');` +
165
+ `let m=0;try{m=fs.statSync(f).mtimeMs}catch(e){}if(t&&(${now}||Date.now()-m>${REPORT_EVERY_MS})){try{fs.utimesSync(f,new Date(),new Date())}catch(e){fs.writeFileSync(f,'{}')}` +
166
+ `require('child_process').spawn('${runner} report --url ${base} --key-var ${variable}',{shell:true,detached:true,stdio:'ignore',windowsHide:true}).unref()}}"`;
167
+
168
+ /** The branch's markdown: changed since `base` (committed or not) and untracked, newest first, at most 30, each under 2 MB. */
169
+ export function changedMarkdown(top, base) {
170
+ const git = (args) => {
171
+ const r = spawnSync("git", ["-c", "core.quotepath=off", ...args], { cwd: top, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 20_000 });
172
+ return r.status === 0 ? r.stdout.split("\n").map((l) => l.trim()).filter(Boolean) : [];
173
+ };
174
+ const names = [...(base ? git(["diff", "--name-only", "--diff-filter=AMR", base]) : []), ...git(["ls-files", "--others", "--exclude-standard"])];
175
+ return [...new Set(names)]
176
+ .filter((p) => /\.(md|markdown)$/i.test(p))
177
+ .map((p) => {
178
+ try {
179
+ const st = statSync(join(top, p));
180
+ return st.isFile() && st.size < 2e6 ? { p, t: st.mtimeMs } : null;
181
+ } catch {
182
+ return null;
183
+ }
184
+ })
185
+ .filter(Boolean)
186
+ .sort((a, b) => b.t - a.t)
187
+ .slice(0, 30)
188
+ .map((x) => x.p);
189
+ }
190
+
191
+ /** The worktree dashboard's collector: bundled into the package on publish (`prepack`), else this repository's own. */
192
+ function dashboardModule() {
193
+ const bundled = new URL("../lib/worktree-dashboard.mjs", import.meta.url);
194
+ return existsSync(fileURLToPath(bundled)) ? bundled.href : new URL("../../../tools/worktree-dashboard/server.mjs", import.meta.url).href;
195
+ }
196
+
197
+ /**
198
+ * `report --url U --key-var V`: this worktree's facts (the worktree dashboard's `collectOne`) and its
199
+ * markdown changed since the last send, posted to the session on Hub › Projects › Terminals. Run by
200
+ * `reportHook` in the background. No key or no repository and it does nothing.
201
+ */
202
+ export async function reportMain(argv, { env = process.env, cwd = process.cwd(), fetchImpl = fetch, collect = null, stampDir = tmpdir() } = {}) {
203
+ const { values } = nodeParseArgs({ args: argv, options: { url: { type: "string", default: DEFAULT_URL }, "key-var": { type: "string", default: "" } } });
204
+ const key = values["key-var"] ? env[values["key-var"]] : "";
205
+ const top = gitRoot(cwd);
206
+ if (!key || !top) return 0;
207
+ const headers = { ...sessionHeaders(top), "content-type": "application/json", authorization: `Bearer ${key}` };
208
+ const post = (body) =>
209
+ fetchImpl(`${values.url.replace(/\/+$/, "")}${SESSION_PATH}`, { method: "POST", headers, body: JSON.stringify(body), signal: AbortSignal.timeout(15_000) });
210
+ const report = await (collect ?? (await import(dashboardModule())).collectOne)(top);
211
+ await post({ event: "worktree", report });
212
+ const stamp = reportStamp(top, headers["X-Futuvara-Branch"], stampDir);
213
+ let sent = {};
214
+ try {
215
+ sent = JSON.parse(readFileSync(stamp, "utf8")).docs ?? {};
216
+ } catch {
217
+ // first send from this worktree and branch
218
+ }
219
+ for (const path of changedMarkdown(top, report.mergeBase)) {
220
+ const content = readFileSync(join(top, path), "utf8");
221
+ const hash = createHash("sha1").update(content).digest("hex");
222
+ if (sent[path] === hash) continue;
223
+ if ((await post({ event: "doc", path, content })).ok) sent[path] = hash;
224
+ }
225
+ writeFileSync(stamp, JSON.stringify({ docs: sent }));
226
+ return 0;
227
+ }
228
+
142
229
  // https://code.claude.com/docs/en/mcp — .mcp.json expands ${VAR} in url and headers; headersHelper adds headers at connect.
143
230
  export const claudeEntry = (mcpUrl, variable) => ({
144
231
  type: "http",
@@ -159,12 +246,19 @@ export function futuvaraSettings(existing, base, variable) {
159
246
  if (!approved.includes(SERVER_NAME)) settings.enabledMcpjsonServers = [...approved, SERVER_NAME];
160
247
  settings.hooks = settings.hooks ?? {};
161
248
  const ours = {
162
- SessionStart: { hooks: [{ type: "command", command: sessionHook(base, variable, "start"), timeout: 10 }] },
249
+ SessionStart: {
250
+ hooks: [
251
+ { type: "command", command: sessionHook(base, variable, "start"), timeout: 10 },
252
+ { type: "command", command: reportHook(base, variable, true), timeout: 10 },
253
+ ],
254
+ },
163
255
  SessionEnd: { hooks: [{ type: "command", command: sessionHook(base, variable, "end"), timeout: 10 }] },
164
256
  PostToolUse: { matcher: "Write|Edit|MultiEdit", hooks: [{ type: "command", command: docHook(base, variable), timeout: 10 }] },
257
+ Stop: { hooks: [{ type: "command", command: reportHook(base, variable), timeout: 10 }] },
165
258
  };
259
+ const isOurs = (g) => JSON.stringify(g).includes(SESSION_PATH) || JSON.stringify(g).includes(REPORT_MARK);
166
260
  for (const [name, group] of Object.entries(ours)) {
167
- const others = (Array.isArray(settings.hooks[name]) ? settings.hooks[name] : []).filter((g) => !JSON.stringify(g).includes(SESSION_PATH));
261
+ const others = (Array.isArray(settings.hooks[name]) ? settings.hooks[name] : []).filter((g) => !isOurs(g));
168
262
  settings.hooks[name] = [...others, group];
169
263
  }
170
264
  return JSON.stringify(settings, null, 2) + "\n";
@@ -511,11 +605,11 @@ export function verify(opts, names, { home = homedir(), cwd = process.cwd(), rep
511
605
  if (opts.agent === "claude-code") {
512
606
  const read = (p) => (existsSync(p) ? readFileSync(p, "utf8") : "");
513
607
  const settings = read(join(repo, ".claude", "settings.json"));
514
- const current = read(config).includes("headersHelper") && settings.includes("enabledMcpjsonServers") && settings.includes("event:'doc'");
608
+ const current = read(config).includes("headersHelper") && settings.includes("enabledMcpjsonServers") && settings.includes("event:'doc'") && settings.includes("session:i.session_id") && settings.includes(REPORT_MARK);
515
609
  checks.push(
516
610
  current
517
- ? { status: "ok", label: "sessions report their worktree, branch, start and end to Futuvara (Terminals)" }
518
- : { status: "warn", label: "sessions here do not report their worktree, branch, start and end to Futuvara — connected before 0.3.5", fix: rerun },
611
+ ? { status: "ok", label: "sessions report their worktree, branch, start, end and worktree facts to Futuvara (Terminals)" }
612
+ : { status: "warn", label: "sessions here do not report their worktree, branch, start, end and worktree facts to Futuvara — connected before 0.4.0", fix: rerun },
519
613
  );
520
614
  }
521
615
  }
@@ -564,6 +658,7 @@ export async function callMain(argv, env = process.env, fetchImpl = fetch) {
564
658
  /** @returns {Promise<number>} the exit code */
565
659
  export async function main(argv = process.argv.slice(2)) {
566
660
  if (argv[0] === "call") return callMain(argv.slice(1));
661
+ if (argv[0] === "report") return reportMain(argv.slice(1));
567
662
  let opts;
568
663
  try {
569
664
  opts = parseArgs(argv);