@unhuman/wsync-cli 0.1.1 → 0.2.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.
Files changed (3) hide show
  1. package/README.md +24 -1
  2. package/dist/wsync.mjs +280 -65
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -60,7 +60,7 @@ wsync link <key> [--server URL] link this directory to a project
60
60
  wsync backfill [--limit N] [--key wsp_…] [--verbose]
61
61
  import existing ~/.claude/projects transcripts
62
62
  wsync flush [--verbose] drain the offline spool to the server
63
- wsync status show config and pending spool
63
+ wsync status show config, links (keys by prefix) and pending spool
64
64
  wsync install-hooks [--dry-run] register hooks in ~/.claude/settings.json
65
65
  wsync uninstall-hooks remove them again
66
66
  wsync refresh-context --cwd PATH refresh the local context cache
@@ -72,6 +72,29 @@ haven't been capturing since the start — entirely over HTTP, using whichever l
72
72
  directory owns each transcript's working directory, or `--key` as a fallback for anything with no
73
73
  linked ancestor. Sessions that match neither are skipped and counted, never silently dropped.
74
74
 
75
+ **Where a session is filed** depends on which command captured it:
76
+
77
+ - **Live capture (the hooks)** files every session under the project the directory's key names.
78
+ Always. The checkout's git remote is recorded as evidence and shown in the app when it disagrees,
79
+ but it never overrules the key and never creates a project.
80
+ - **`backfill`** sends `mode: backfill`, and there the remote may choose the project — among the
81
+ projects that already exist in your workspace (by slug, by a remote the workspace has seen before,
82
+ or by an unambiguous bare name). A transcript whose remote matches nothing lands in the app's
83
+ **Needs filing** queue with the remote named, for a person to file. Neither mode invents a project;
84
+ one key can import a whole machine without funnelling twenty repositories into one project.
85
+
86
+ **Re-linking a directory moves it.** `link` on a directory that already has a key verifies the new
87
+ key, writes it, and then retires the previous one — with that key, on the server — so a directory
88
+ has one live key at a time and `status` never lists ghosts. A retire the server refuses is reported
89
+ and does not undo the link; revoke the old key from the app's Keys list in that case.
90
+
91
+ **`.wsync.json`** in a repository root is an optional marker (`{ "project": "<slug>", "ticket":
92
+ "<KEY>" }`) the identity layer reads ahead of the git remote. It does not change where live capture
93
+ files a session — the key does that — but it names the project `backfill` should look for and the
94
+ ticket to prefer. It lives in the repository, so committing it shares the choice with everyone who
95
+ clones; whether a project name belongs in a public repository is the owner's call. `link` never
96
+ writes it.
97
+
75
98
  ## Production server
76
99
 
77
100
  The default server (used when you pass no `--server` and have none configured) is
package/dist/wsync.mjs CHANGED
@@ -178,8 +178,8 @@ var require_git = __commonJS({
178
178
  Object.defineProperty(exports, "__esModule", { value: true });
179
179
  exports.getBranch = exports.getRemote = void 0;
180
180
  exports.outermostContiguousGitRoot = outermostContiguousGitRoot;
181
- exports.nearestGitRoot = nearestGitRoot2;
182
- exports.normaliseRemote = normaliseRemote;
181
+ exports.nearestGitRoot = nearestGitRoot3;
182
+ exports.normaliseRemote = normaliseRemote2;
183
183
  var node_child_process_1 = __require("node:child_process");
184
184
  var node_fs_1 = __require("node:fs");
185
185
  var node_path_1 = __require("node:path");
@@ -211,7 +211,7 @@ var require_git = __commonJS({
211
211
  }
212
212
  return best;
213
213
  }
214
- function nearestGitRoot2(dir) {
214
+ function nearestGitRoot3(dir) {
215
215
  let cur = (0, node_path_1.resolve)(dir);
216
216
  for (; ; ) {
217
217
  if ((0, node_fs_1.existsSync)((0, node_path_1.join)(cur, ".git")))
@@ -222,11 +222,11 @@ var require_git = __commonJS({
222
222
  cur = parent;
223
223
  }
224
224
  }
225
- var getRemote = (root) => git(root, ["remote", "get-url", "origin"]);
226
- exports.getRemote = getRemote;
225
+ var getRemote2 = (root) => git(root, ["remote", "get-url", "origin"]);
226
+ exports.getRemote = getRemote2;
227
227
  var getBranch2 = (root) => git(root, ["rev-parse", "--abbrev-ref", "HEAD"]);
228
228
  exports.getBranch = getBranch2;
229
- function normaliseRemote(url) {
229
+ function normaliseRemote2(url) {
230
230
  let s = url.trim();
231
231
  s = s.replace(/^[a-z+]+:\/\//i, "");
232
232
  s = s.replace(/^[^@/]+@/, "");
@@ -1136,7 +1136,7 @@ ${spine}`;
1136
1136
  return JSON.parse(extractJson(text));
1137
1137
  }
1138
1138
  function run(cmd2, args2, stdin, timeoutMs) {
1139
- return new Promise((resolve4, reject) => {
1139
+ return new Promise((resolve5, reject) => {
1140
1140
  const child = (0, node_child_process_1.spawn)(cmd2, args2, {
1141
1141
  stdio: ["pipe", "pipe", "pipe"],
1142
1142
  env: { ...process.env, WSYNC_CHILD: "1" }
@@ -1159,7 +1159,7 @@ ${spine}`;
1159
1159
  child.on("close", (code) => {
1160
1160
  clearTimeout(timer);
1161
1161
  if (code === 0)
1162
- resolve4(out);
1162
+ resolve5(out);
1163
1163
  else
1164
1164
  reject(new Error(`${cmd2} exited ${code}: ${err.slice(0, 400)}`));
1165
1165
  });
@@ -5515,6 +5515,14 @@ var require_schemas = __commonJS({
5515
5515
  exports.ingestSchema = zod_1.z.object({
5516
5516
  distillation: exports.distillationSchema,
5517
5517
  identity: exports.identitySchema,
5518
+ /**
5519
+ * Which rule files the session. `live` (the hooks): the capture key names the project, always, and
5520
+ * the identity's remote is recorded as evidence. `backfill` (`wsync backfill`, one key for a whole
5521
+ * machine of history): the remote may choose the project — among projects that exist — and an
5522
+ * unmatched one goes to triage. Neither mode ever creates a project. Absent from older clients,
5523
+ * and absent means live, the strict rule.
5524
+ */
5525
+ mode: zod_1.z.enum(["live", "backfill"]).default("live"),
5518
5526
  transcriptPath: zod_1.z.string().max(4096),
5519
5527
  transcriptShaPrefix: zod_1.z.string().max(128),
5520
5528
  machineHostname: zod_1.z.string().max(300).optional(),
@@ -5782,6 +5790,14 @@ var require_render_context = __commonJS({
5782
5790
  priority: 1,
5783
5791
  render: () => {
5784
5792
  const lines = [`## wsync context \u2014 ${ctx.project?.name ?? "unknown project"}`];
5793
+ if (ctx.workstream) {
5794
+ const w = ctx.workstream;
5795
+ const handle = w.key && w.key.toLowerCase() !== w.slug ? `${w.slug}, ${w.key}` : w.slug;
5796
+ const moved = w.lastActivityAt ? `, last activity ${w.lastActivityAt.toISOString().slice(0, 10)}` : "";
5797
+ const fresh = w.sessions === 0 ? " No sessions filed yet \u2014 the briefing below is project-wide." : "";
5798
+ lines.push(`Workstream: ${w.title} (${handle}) \u2014 ${w.status}${moved}.${fresh}`);
5799
+ lines.push("Working on something else? Call wsync_start_work with a handle, branch or one sentence.");
5800
+ }
5785
5801
  if (ctx.tickets.length) {
5786
5802
  lines.push(`Tickets: ${ctx.tickets.slice(0, 6).map((t) => t.summary ? `${t.key} (${t.summary})` : t.key).join(", ")}`);
5787
5803
  }
@@ -6087,10 +6103,13 @@ function saveLink(absPath, key, opts = {}) {
6087
6103
  }
6088
6104
  }
6089
6105
  const links = current["links"] ?? {};
6090
- links[resolve(absPath)] = key;
6106
+ const path = resolve(absPath);
6107
+ const previous = links[path];
6108
+ links[path] = key;
6091
6109
  current["links"] = links;
6092
6110
  if (opts.server) current["server"] = opts.server;
6093
6111
  writeFileSync(file, JSON.stringify(current, null, 2) + "\n", { mode: 384 });
6112
+ return previous && previous !== key ? previous : null;
6094
6113
  }
6095
6114
  var configFile;
6096
6115
  var init_links = __esm({
@@ -6101,6 +6120,58 @@ var init_links = __esm({
6101
6120
  }
6102
6121
  });
6103
6122
 
6123
+ // src/spool.ts
6124
+ import { writeFileSync as writeFileSync2, readdirSync, readFileSync as readFileSync3, unlinkSync, renameSync, existsSync as existsSync3 } from "node:fs";
6125
+ import { join as join3 } from "node:path";
6126
+ import { randomUUID } from "node:crypto";
6127
+ function enqueue(entry) {
6128
+ ensureDirs();
6129
+ const name = `${Date.now()}-${randomUUID().slice(0, 8)}.json`;
6130
+ const tmp = join3(SPOOL_DIR, `.${name}.tmp`);
6131
+ const dest = join3(SPOOL_DIR, name);
6132
+ writeFileSync2(tmp, JSON.stringify({ ...entry, queuedAt: (/* @__PURE__ */ new Date()).toISOString(), attempts: 0 }), { mode: 384 });
6133
+ renameSync(tmp, dest);
6134
+ return dest;
6135
+ }
6136
+ function listSpool() {
6137
+ if (!existsSync3(SPOOL_DIR)) return [];
6138
+ return readdirSync(SPOOL_DIR).filter((f) => f.endsWith(".json") && !f.startsWith(".")).sort().flatMap((f) => {
6139
+ const p = join3(SPOOL_DIR, f);
6140
+ try {
6141
+ return [{ path: p, entry: JSON.parse(readFileSync3(p, "utf8")) }];
6142
+ } catch {
6143
+ return [];
6144
+ }
6145
+ });
6146
+ }
6147
+ function dequeue(path) {
6148
+ try {
6149
+ unlinkSync(path);
6150
+ } catch {
6151
+ }
6152
+ }
6153
+ function recordAttempt(path, entry) {
6154
+ try {
6155
+ writeFileSync2(path, JSON.stringify({ ...entry, attempts: entry.attempts + 1 }), { mode: 384 });
6156
+ } catch {
6157
+ }
6158
+ }
6159
+ function trimSpool() {
6160
+ const all = listSpool();
6161
+ if (all.length <= MAX_SPOOL_ENTRIES) return 0;
6162
+ const excess = all.slice(0, all.length - MAX_SPOOL_ENTRIES);
6163
+ for (const e of excess) dequeue(e.path);
6164
+ return excess.length;
6165
+ }
6166
+ var MAX_SPOOL_ENTRIES;
6167
+ var init_spool = __esm({
6168
+ "src/spool.ts"() {
6169
+ "use strict";
6170
+ init_config();
6171
+ MAX_SPOOL_ENTRIES = 500;
6172
+ }
6173
+ });
6174
+
6104
6175
  // src/artifact.ts
6105
6176
  import { createReadStream } from "node:fs";
6106
6177
  import { gzipSync } from "node:zlib";
@@ -6143,9 +6214,9 @@ async function fitArtifactEnd(path, start, fileEnd) {
6143
6214
  }
6144
6215
  }
6145
6216
  function readRange(path, start, end) {
6146
- return new Promise((resolve4, reject) => {
6217
+ return new Promise((resolve5, reject) => {
6147
6218
  const chunks = [];
6148
- createReadStream(path, { start, end: end - 1 }).on("data", (c) => chunks.push(c)).on("end", () => resolve4(Buffer.concat(chunks))).on("error", reject);
6219
+ createReadStream(path, { start, end: end - 1 }).on("data", (c) => chunks.push(c)).on("end", () => resolve5(Buffer.concat(chunks))).on("error", reject);
6149
6220
  });
6150
6221
  }
6151
6222
  var import_wsync_core2, ARTIFACT_GZ_TARGET, MIN_FIT_SPAN;
@@ -6165,7 +6236,7 @@ var init_package = __esm({
6165
6236
  "package.json"() {
6166
6237
  package_default = {
6167
6238
  name: "@unhuman/wsync-cli",
6168
- version: "0.1.1",
6239
+ version: "0.2.0",
6169
6240
  description: "Capture Claude Code sessions to an Unhuman Work Context project: link a checkout, install the hooks, drain the spool.",
6170
6241
  license: "UNLICENSED",
6171
6242
  repository: {
@@ -6370,10 +6441,31 @@ async function link(key, opts = {}) {
6370
6441
  process.exitCode = 1;
6371
6442
  return;
6372
6443
  }
6373
- saveLink(cwd, key, { server });
6444
+ const previous = saveLink(cwd, key, { server });
6374
6445
  console.log(` Linked ${cwd} \u2192 ${who.projectName ?? who.project} (${who.project})`);
6446
+ if (previous) await retirePrevious(server, previous);
6447
+ if (opts.capture) await installCapture();
6448
+ else console.log(" \xB7 session capture is off \u2014 memories go through MCP. Add --capture to also record transcripts.");
6449
+ registerMcp(cwd, server, key);
6450
+ console.log("\n Start Claude Code. Nothing else to do.");
6451
+ }
6452
+ async function installCapture() {
6375
6453
  const hooks = await installHooks({ quiet: true });
6376
6454
  console.log(hooks.added > 0 ? " \u2713 capture hooks installed" : " \u2713 capture hooks already present");
6455
+ const health = hookHealth();
6456
+ if (!health.targetExists) {
6457
+ console.log(` ! the hooks point at ${health.target ?? "nothing"}, which does not exist \u2014 nothing will be captured`);
6458
+ console.log(" Re-run install-hooks from the installed package, or report this with `wsync status`.");
6459
+ process.exitCode = 1;
6460
+ } else {
6461
+ console.log(` they run ${health.target}`);
6462
+ }
6463
+ const pending = listSpool().length;
6464
+ if (pending > 0) {
6465
+ console.log(` ! ${pending} spooled event(s) still pending \u2014 run \`wsync flush --verbose\` to see why`);
6466
+ }
6467
+ }
6468
+ function registerMcp(cwd, server, key) {
6377
6469
  spawnSync("claude", ["mcp", "remove", "wsync", "--scope", "local"], { cwd, stdio: "ignore" });
6378
6470
  const mcp = spawnSync("claude", [
6379
6471
  "mcp",
@@ -6394,7 +6486,26 @@ async function link(key, opts = {}) {
6394
6486
  console.log(` claude mcp add --scope local --transport http wsync ${server}/mcp \\`);
6395
6487
  console.log(` --header "Authorization: Bearer ${key}"`);
6396
6488
  }
6397
- console.log("\n Start Claude Code. Nothing else to do.");
6489
+ }
6490
+ async function retirePrevious(server, previous) {
6491
+ let res;
6492
+ try {
6493
+ res = await fetch(`${server}/wsync/keys/retire`, {
6494
+ method: "POST",
6495
+ headers: { authorization: `Bearer ${previous}` },
6496
+ signal: AbortSignal.timeout(1e4)
6497
+ });
6498
+ } catch (e) {
6499
+ console.log(` ! could not retire the key this directory used before (${String(e)}) \u2014 revoke it in the app's Keys list`);
6500
+ return;
6501
+ }
6502
+ if (res.ok) {
6503
+ console.log(" \u2713 the key this directory used before is retired");
6504
+ } else if (res.status === 401) {
6505
+ console.log(" \xB7 the key this directory used before was already revoked");
6506
+ } else {
6507
+ console.log(` ! could not retire the key this directory used before (${res.status}) \u2014 revoke it in the app's Keys list`);
6508
+ }
6398
6509
  }
6399
6510
  var init_link = __esm({
6400
6511
  "src/commands/link.ts"() {
@@ -6402,6 +6513,7 @@ var init_link = __esm({
6402
6513
  init_config();
6403
6514
  init_links();
6404
6515
  init_install();
6516
+ init_spool();
6405
6517
  }
6406
6518
  });
6407
6519
 
@@ -6502,6 +6614,7 @@ async function backfill(opts = {}) {
6502
6614
  console.log(`discovered ${all.length} transcript(s) (${mb(all)}MB)`);
6503
6615
  let ingested = 0;
6504
6616
  let skipped = 0;
6617
+ let unfiled = 0;
6505
6618
  for (const f of all) {
6506
6619
  try {
6507
6620
  const d = await (0, import_wsync_core4.distillMechanically)(f.path, f.bytes);
@@ -6533,7 +6646,11 @@ async function backfill(opts = {}) {
6533
6646
  transcriptPath: f.path,
6534
6647
  transcriptShaPrefix: await (0, import_wsync_core4.transcriptPrefixSha)(f.path),
6535
6648
  // No `segment`: an absent segment tells the server this span is the
6536
- // whole file, not one tile of it.
6649
+ // whole file, not one tile of it. `mode` is what lets the remote choose
6650
+ // the project (among those that exist) instead of the key -- one key
6651
+ // imports a whole machine's history without funnelling it into one
6652
+ // project. Anything the remote does not match lands in triage.
6653
+ mode: "backfill",
6537
6654
  segmentKind: "backfill",
6538
6655
  isSidechain: f.isSidechain,
6539
6656
  parentSessionId: f.parentSessionId
@@ -6554,8 +6671,10 @@ async function backfill(opts = {}) {
6554
6671
  }
6555
6672
  }
6556
6673
  ingested++;
6674
+ if (body.projectId === null) unfiled++;
6557
6675
  if (opts.verbose) {
6558
- console.log(` [ok] ${d.sessionId.slice(0, 8)} ${identity.projectKey ?? "_unfiled"} (${identity.confidence.toFixed(2)})`);
6676
+ const where = body.projectId === null ? "-> triage (no project matches)" : "";
6677
+ console.log(` [ok] ${d.sessionId.slice(0, 8)} ${identity.projectKey ?? "_unfiled"} (${identity.confidence.toFixed(2)}) ${where}`.trimEnd());
6559
6678
  }
6560
6679
  } catch (e) {
6561
6680
  skipped++;
@@ -6563,7 +6682,10 @@ async function backfill(opts = {}) {
6563
6682
  }
6564
6683
  }
6565
6684
  console.log(`backfill: ${ingested} ingested, ${skipped} skipped, ${all.length} discovered`);
6566
- return { discovered: all.length, ingested, skipped };
6685
+ if (unfiled > 0) {
6686
+ console.log(` ${unfiled} session(s) matched no project and are waiting in triage. Create the project in the app, then file them from "Needs filing".`);
6687
+ }
6688
+ return { discovered: all.length, ingested, skipped, unfiled };
6567
6689
  }
6568
6690
  var import_wsync_core4, mb;
6569
6691
  var init_backfill = __esm({
@@ -6685,64 +6807,127 @@ var init_enrich = __esm({
6685
6807
  }
6686
6808
  });
6687
6809
 
6688
- // src/commands/flush.ts
6689
- var import_wsync_core3 = __toESM(require_dist(), 1);
6690
- init_config();
6691
- init_links();
6692
- import { statSync as statSync2, existsSync as existsSync6, writeFileSync as writeFileSync5 } from "node:fs";
6693
- import { createHash as createHash2 } from "node:crypto";
6694
- import { join as join6 } from "node:path";
6695
- import { hostname, platform } from "node:os";
6696
-
6697
- // src/spool.ts
6698
- init_config();
6699
- import { writeFileSync as writeFileSync2, readdirSync, readFileSync as readFileSync3, unlinkSync, renameSync, existsSync as existsSync3 } from "node:fs";
6700
- import { join as join3 } from "node:path";
6701
- import { randomUUID } from "node:crypto";
6702
- function enqueue(entry) {
6703
- ensureDirs();
6704
- const name = `${Date.now()}-${randomUUID().slice(0, 8)}.json`;
6705
- const tmp = join3(SPOOL_DIR, `.${name}.tmp`);
6706
- const dest = join3(SPOOL_DIR, name);
6707
- writeFileSync2(tmp, JSON.stringify({ ...entry, queuedAt: (/* @__PURE__ */ new Date()).toISOString(), attempts: 0 }), { mode: 384 });
6708
- renameSync(tmp, dest);
6709
- return dest;
6710
- }
6711
- function listSpool() {
6712
- if (!existsSync3(SPOOL_DIR)) return [];
6713
- return readdirSync(SPOOL_DIR).filter((f) => f.endsWith(".json") && !f.startsWith(".")).sort().flatMap((f) => {
6714
- const p = join3(SPOOL_DIR, f);
6715
- try {
6716
- return [{ path: p, entry: JSON.parse(readFileSync3(p, "utf8")) }];
6717
- } catch {
6718
- return [];
6810
+ // src/commands/setup.ts
6811
+ var setup_exports = {};
6812
+ __export(setup_exports, {
6813
+ setup: () => setup
6814
+ });
6815
+ import { hostname as osHostname } from "node:os";
6816
+ import { resolve as resolve4 } from "node:path";
6817
+ async function setup(token, opts = {}) {
6818
+ const cfg = loadConfig();
6819
+ const server = (opts.server ?? cfg.server).replace(/\/+$/, "");
6820
+ const cwd = resolve4(process.cwd());
6821
+ if (!token || token.startsWith("wsp_")) {
6822
+ console.error("setup takes a workspace API token. If you already have a wsp_ capture key, run: wsync link <key>");
6823
+ process.exitCode = 1;
6824
+ return;
6825
+ }
6826
+ const existing = resolveLink(cfg.links, cwd);
6827
+ if (existing && !opts.force) {
6828
+ console.log(` ${existing.path} is already linked. Nothing to do.`);
6829
+ console.log(" Re-run with --force to mint a new key for this machine, or `wsync status` to see the links.");
6830
+ return;
6831
+ }
6832
+ const projectKey = opts.project?.trim() || await remoteProject(cwd);
6833
+ if (!projectKey) {
6834
+ console.error(
6835
+ `No git remote in ${cwd}, so there is nothing to name the project after. Pass --project <key> (e.g. github.com/team/repo).`
6836
+ );
6837
+ process.exitCode = 1;
6838
+ return;
6839
+ }
6840
+ const result = await callTool(server, token, {
6841
+ name: "wsync_setup",
6842
+ arguments: {
6843
+ projectKey,
6844
+ ...opts.name ? { name: opts.name } : {},
6845
+ ...opts.create ? { create: true } : {},
6846
+ machine: opts.machine ?? hostname3()
6719
6847
  }
6720
6848
  });
6849
+ if (!result.ok) {
6850
+ console.error(result.message);
6851
+ process.exitCode = 1;
6852
+ return;
6853
+ }
6854
+ const key = /link\s+(wsp_[A-Za-z0-9_-]+)/.exec(result.command)?.[1];
6855
+ if (!key) {
6856
+ console.error(`${server} answered, but without a capture key to use. Check the token has owner or admin rights.`);
6857
+ process.exitCode = 1;
6858
+ return;
6859
+ }
6860
+ console.log(
6861
+ ` ${result.created ? "Created" : "Found"} project ${result.projectName ?? projectKey} (${result.projectKey ?? projectKey})`
6862
+ );
6863
+ await link(key, { server, capture: opts.capture });
6721
6864
  }
6722
- function dequeue(path) {
6865
+ async function remoteProject(cwd) {
6866
+ const root = (0, import_wsync_core6.nearestGitRoot)(cwd);
6867
+ if (!root) return null;
6868
+ const remote = await (0, import_wsync_core6.getRemote)(root);
6869
+ return remote ? (0, import_wsync_core6.normaliseRemote)(remote) : null;
6870
+ }
6871
+ function hostname3() {
6872
+ return osHostname().trim() || "this machine";
6873
+ }
6874
+ async function callTool(server, token, params) {
6875
+ let res;
6723
6876
  try {
6724
- unlinkSync(path);
6725
- } catch {
6877
+ res = await fetch(`${server}/mcp`, {
6878
+ method: "POST",
6879
+ headers: { authorization: `Bearer ${token}`, "content-type": "application/json", accept: "application/json" },
6880
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params }),
6881
+ signal: AbortSignal.timeout(2e4)
6882
+ });
6883
+ } catch (e) {
6884
+ return { ok: false, message: `Could not reach ${server}: ${String(e)}` };
6726
6885
  }
6727
- }
6728
- function recordAttempt(path, entry) {
6886
+ if (res.status === 401) return { ok: false, message: `${server} rejected that token. Mint one in Settings \u2192 Claude (MCP).` };
6887
+ if (!res.ok) return { ok: false, message: `${server} answered ${res.status}.` };
6888
+ const body = await res.json().catch(() => ({}));
6889
+ if (body.error) return { ok: false, message: body.error.message ?? "The server refused the call." };
6890
+ const text = body.result?.content?.[0]?.text ?? "";
6891
+ if (body.result?.isError) return { ok: false, message: text || "The server refused the call." };
6729
6892
  try {
6730
- writeFileSync2(path, JSON.stringify({ ...entry, attempts: entry.attempts + 1 }), { mode: 384 });
6893
+ const parsed = JSON.parse(text);
6894
+ if (!parsed.command) return { ok: false, message: text || "No command came back from the server." };
6895
+ return {
6896
+ ok: true,
6897
+ command: parsed.command,
6898
+ projectKey: parsed.project?.projectKey,
6899
+ projectName: parsed.project?.name,
6900
+ created: Boolean(parsed.project?.created)
6901
+ };
6731
6902
  } catch {
6903
+ return { ok: false, message: text || "The server answered in a shape this CLI does not understand." };
6732
6904
  }
6733
6905
  }
6734
- var MAX_SPOOL_ENTRIES = 500;
6735
- function trimSpool() {
6736
- const all = listSpool();
6737
- if (all.length <= MAX_SPOOL_ENTRIES) return 0;
6738
- const excess = all.slice(0, all.length - MAX_SPOOL_ENTRIES);
6739
- for (const e of excess) dequeue(e.path);
6740
- return excess.length;
6741
- }
6906
+ var import_wsync_core6;
6907
+ var init_setup = __esm({
6908
+ "src/commands/setup.ts"() {
6909
+ "use strict";
6910
+ import_wsync_core6 = __toESM(require_dist(), 1);
6911
+ init_config();
6912
+ init_links();
6913
+ init_link();
6914
+ }
6915
+ });
6916
+
6917
+ // src/commands/flush.ts
6918
+ var import_wsync_core3 = __toESM(require_dist(), 1);
6919
+ init_config();
6920
+ init_links();
6921
+ init_spool();
6922
+ import { statSync as statSync2, existsSync as existsSync6, writeFileSync as writeFileSync5 } from "node:fs";
6923
+ import { createHash as createHash2 } from "node:crypto";
6924
+ import { join as join6 } from "node:path";
6925
+ import { hostname, platform } from "node:os";
6742
6926
 
6743
6927
  // src/commands/hook.ts
6744
6928
  init_config();
6745
6929
  init_links();
6930
+ init_spool();
6746
6931
  import { spawn } from "node:child_process";
6747
6932
  import { readFileSync as readFileSync4, writeFileSync as writeFileSync3, existsSync as existsSync4, statSync, appendFileSync } from "node:fs";
6748
6933
  import { join as join4 } from "node:path";
@@ -6752,6 +6937,7 @@ import { createHash } from "node:crypto";
6752
6937
  var import_wsync_core = __toESM(require_dist(), 1);
6753
6938
  init_config();
6754
6939
  init_links();
6940
+ init_spool();
6755
6941
  import { randomUUID as randomUUID2 } from "node:crypto";
6756
6942
  var EVENT_SUBCOMMANDS = {
6757
6943
  "event-prompt": "prompt",
@@ -7140,6 +7326,8 @@ async function sendTile(cfg, key, entry, byteStart, byteEnd, proposedSeq, fileSi
7140
7326
  spoolDepth: listSpool().length,
7141
7327
  transcriptPath: entry.transcriptPath,
7142
7328
  transcriptShaPrefix: await (0, import_wsync_core3.transcriptPrefixSha)(entry.transcriptPath),
7329
+ // Live: the key names the project. Said explicitly, though absent means the same.
7330
+ mode: "live",
7143
7331
  segment: { seq: proposedSeq, kind: entry.trigger, byteStart, byteEnd }
7144
7332
  });
7145
7333
  const res = await fetch(apiUrl(cfg, "/wsync/ingest"), {
@@ -7199,6 +7387,7 @@ async function refreshContext(cwd) {
7199
7387
 
7200
7388
  // src/bin.ts
7201
7389
  init_install();
7390
+ init_spool();
7202
7391
  init_config();
7203
7392
  var [cmd, sub, ...rest] = process.argv.slice(2);
7204
7393
  var args = [sub, ...rest].filter(Boolean);
@@ -7209,7 +7398,14 @@ var val = (n) => {
7209
7398
  };
7210
7399
  var USAGE = `wsync \u2014 work context across machines
7211
7400
 
7212
- wsync link <key> [--server URL] link this directory to a project
7401
+ wsync setup <api-token> [--server URL] [--project KEY] [--machine NAME] [--create] [--capture]
7402
+ one paste: mint this machine's key and link
7403
+ (connects Claude Code to the project's memories
7404
+ over MCP; --capture also records transcripts)
7405
+ (--create opens a new project; without it an
7406
+ unknown project is refused, not invented)
7407
+ wsync link <key> [--server URL] [--capture]
7408
+ link this directory to a project
7213
7409
  wsync backfill [--limit N] [--key wsp_\u2026] [--verbose]
7214
7410
  import existing transcripts over HTTP
7215
7411
  wsync flush [--verbose] drain the offline spool to the server
@@ -7238,7 +7434,7 @@ try {
7238
7434
  break;
7239
7435
  }
7240
7436
  const { link: link2 } = await Promise.resolve().then(() => (init_link(), link_exports));
7241
- await link2(key, { server: val("server") });
7437
+ await link2(key, { server: val("server"), capture: has("capture") });
7242
7438
  break;
7243
7439
  }
7244
7440
  case "backfill": {
@@ -7285,7 +7481,7 @@ try {
7285
7481
  console.log(`hooks ${health.installed} installed -> ${health.target}`);
7286
7482
  }
7287
7483
  console.log(`links ${links.length}`);
7288
- for (const [path, key] of links) console.log(` - ${path} -> ${key}`);
7484
+ for (const [path, key] of links) console.log(` - ${path} -> ${key.slice(0, 12)}\u2026`);
7289
7485
  console.log(`spool ${spool.length} pending`);
7290
7486
  for (const s of spool.slice(0, 10)) {
7291
7487
  const e = s.entry;
@@ -7294,6 +7490,25 @@ try {
7294
7490
  }
7295
7491
  break;
7296
7492
  }
7493
+ case "setup": {
7494
+ const { setup: setup2 } = await Promise.resolve().then(() => (init_setup(), setup_exports));
7495
+ const token = args[0];
7496
+ if (!token || token.startsWith("--")) {
7497
+ console.error("Usage: wsync setup <api-token> [--server URL] [--project KEY] [--machine NAME]");
7498
+ process.exitCode = 1;
7499
+ break;
7500
+ }
7501
+ await setup2(token, {
7502
+ server: val("server"),
7503
+ project: val("project"),
7504
+ name: val("name"),
7505
+ machine: val("machine"),
7506
+ force: has("force"),
7507
+ create: has("create"),
7508
+ capture: has("capture")
7509
+ });
7510
+ break;
7511
+ }
7297
7512
  case "install-hooks":
7298
7513
  await installHooks({ dryRun: has("dry-run") });
7299
7514
  break;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@unhuman/wsync-cli",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "Capture Claude Code sessions to an Unhuman Work Context project: link a checkout, install the hooks, drain the spool.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {