@unhuman/wsync-cli 0.1.1 → 0.1.2

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 (2) hide show
  1. package/dist/wsync.mjs +209 -57
  2. package/package.json +1 -1
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
  });
@@ -5782,6 +5782,14 @@ var require_render_context = __commonJS({
5782
5782
  priority: 1,
5783
5783
  render: () => {
5784
5784
  const lines = [`## wsync context \u2014 ${ctx.project?.name ?? "unknown project"}`];
5785
+ if (ctx.workstream) {
5786
+ const w = ctx.workstream;
5787
+ const handle = w.key && w.key.toLowerCase() !== w.slug ? `${w.slug}, ${w.key}` : w.slug;
5788
+ const moved = w.lastActivityAt ? `, last activity ${w.lastActivityAt.toISOString().slice(0, 10)}` : "";
5789
+ const fresh = w.sessions === 0 ? " No sessions filed yet \u2014 the briefing below is project-wide." : "";
5790
+ lines.push(`Workstream: ${w.title} (${handle}) \u2014 ${w.status}${moved}.${fresh}`);
5791
+ lines.push("Working on something else? Call wsync_start_work with a handle, branch or one sentence.");
5792
+ }
5785
5793
  if (ctx.tickets.length) {
5786
5794
  lines.push(`Tickets: ${ctx.tickets.slice(0, 6).map((t) => t.summary ? `${t.key} (${t.summary})` : t.key).join(", ")}`);
5787
5795
  }
@@ -6101,6 +6109,58 @@ var init_links = __esm({
6101
6109
  }
6102
6110
  });
6103
6111
 
6112
+ // src/spool.ts
6113
+ import { writeFileSync as writeFileSync2, readdirSync, readFileSync as readFileSync3, unlinkSync, renameSync, existsSync as existsSync3 } from "node:fs";
6114
+ import { join as join3 } from "node:path";
6115
+ import { randomUUID } from "node:crypto";
6116
+ function enqueue(entry) {
6117
+ ensureDirs();
6118
+ const name = `${Date.now()}-${randomUUID().slice(0, 8)}.json`;
6119
+ const tmp = join3(SPOOL_DIR, `.${name}.tmp`);
6120
+ const dest = join3(SPOOL_DIR, name);
6121
+ writeFileSync2(tmp, JSON.stringify({ ...entry, queuedAt: (/* @__PURE__ */ new Date()).toISOString(), attempts: 0 }), { mode: 384 });
6122
+ renameSync(tmp, dest);
6123
+ return dest;
6124
+ }
6125
+ function listSpool() {
6126
+ if (!existsSync3(SPOOL_DIR)) return [];
6127
+ return readdirSync(SPOOL_DIR).filter((f) => f.endsWith(".json") && !f.startsWith(".")).sort().flatMap((f) => {
6128
+ const p = join3(SPOOL_DIR, f);
6129
+ try {
6130
+ return [{ path: p, entry: JSON.parse(readFileSync3(p, "utf8")) }];
6131
+ } catch {
6132
+ return [];
6133
+ }
6134
+ });
6135
+ }
6136
+ function dequeue(path) {
6137
+ try {
6138
+ unlinkSync(path);
6139
+ } catch {
6140
+ }
6141
+ }
6142
+ function recordAttempt(path, entry) {
6143
+ try {
6144
+ writeFileSync2(path, JSON.stringify({ ...entry, attempts: entry.attempts + 1 }), { mode: 384 });
6145
+ } catch {
6146
+ }
6147
+ }
6148
+ function trimSpool() {
6149
+ const all = listSpool();
6150
+ if (all.length <= MAX_SPOOL_ENTRIES) return 0;
6151
+ const excess = all.slice(0, all.length - MAX_SPOOL_ENTRIES);
6152
+ for (const e of excess) dequeue(e.path);
6153
+ return excess.length;
6154
+ }
6155
+ var MAX_SPOOL_ENTRIES;
6156
+ var init_spool = __esm({
6157
+ "src/spool.ts"() {
6158
+ "use strict";
6159
+ init_config();
6160
+ MAX_SPOOL_ENTRIES = 500;
6161
+ }
6162
+ });
6163
+
6104
6164
  // src/artifact.ts
6105
6165
  import { createReadStream } from "node:fs";
6106
6166
  import { gzipSync } from "node:zlib";
@@ -6143,9 +6203,9 @@ async function fitArtifactEnd(path, start, fileEnd) {
6143
6203
  }
6144
6204
  }
6145
6205
  function readRange(path, start, end) {
6146
- return new Promise((resolve4, reject) => {
6206
+ return new Promise((resolve5, reject) => {
6147
6207
  const chunks = [];
6148
- createReadStream(path, { start, end: end - 1 }).on("data", (c) => chunks.push(c)).on("end", () => resolve4(Buffer.concat(chunks))).on("error", reject);
6208
+ createReadStream(path, { start, end: end - 1 }).on("data", (c) => chunks.push(c)).on("end", () => resolve5(Buffer.concat(chunks))).on("error", reject);
6149
6209
  });
6150
6210
  }
6151
6211
  var import_wsync_core2, ARTIFACT_GZ_TARGET, MIN_FIT_SPAN;
@@ -6165,7 +6225,7 @@ var init_package = __esm({
6165
6225
  "package.json"() {
6166
6226
  package_default = {
6167
6227
  name: "@unhuman/wsync-cli",
6168
- version: "0.1.1",
6228
+ version: "0.1.2",
6169
6229
  description: "Capture Claude Code sessions to an Unhuman Work Context project: link a checkout, install the hooks, drain the spool.",
6170
6230
  license: "UNLICENSED",
6171
6231
  repository: {
@@ -6374,6 +6434,18 @@ async function link(key, opts = {}) {
6374
6434
  console.log(` Linked ${cwd} \u2192 ${who.projectName ?? who.project} (${who.project})`);
6375
6435
  const hooks = await installHooks({ quiet: true });
6376
6436
  console.log(hooks.added > 0 ? " \u2713 capture hooks installed" : " \u2713 capture hooks already present");
6437
+ const health = hookHealth();
6438
+ if (!health.targetExists) {
6439
+ console.log(` ! the hooks point at ${health.target ?? "nothing"}, which does not exist \u2014 nothing will be captured`);
6440
+ console.log(" Re-run install-hooks from the installed package, or report this with `wsync status`.");
6441
+ process.exitCode = 1;
6442
+ } else {
6443
+ console.log(` they run ${health.target}`);
6444
+ }
6445
+ const pending = listSpool().length;
6446
+ if (pending > 0) {
6447
+ console.log(` ! ${pending} spooled event(s) still pending \u2014 run \`wsync flush --verbose\` to see why`);
6448
+ }
6377
6449
  spawnSync("claude", ["mcp", "remove", "wsync", "--scope", "local"], { cwd, stdio: "ignore" });
6378
6450
  const mcp = spawnSync("claude", [
6379
6451
  "mcp",
@@ -6402,6 +6474,7 @@ var init_link = __esm({
6402
6474
  init_config();
6403
6475
  init_links();
6404
6476
  init_install();
6477
+ init_spool();
6405
6478
  }
6406
6479
  });
6407
6480
 
@@ -6685,64 +6758,122 @@ var init_enrich = __esm({
6685
6758
  }
6686
6759
  });
6687
6760
 
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 [];
6719
- }
6761
+ // src/commands/setup.ts
6762
+ var setup_exports = {};
6763
+ __export(setup_exports, {
6764
+ setup: () => setup
6765
+ });
6766
+ import { hostname as osHostname } from "node:os";
6767
+ import { resolve as resolve4 } from "node:path";
6768
+ async function setup(token, opts = {}) {
6769
+ const cfg = loadConfig();
6770
+ const server = (opts.server ?? cfg.server).replace(/\/+$/, "");
6771
+ const cwd = resolve4(process.cwd());
6772
+ if (!token || token.startsWith("wsp_")) {
6773
+ console.error("setup takes a workspace API token. If you already have a wsp_ capture key, run: wsync link <key>");
6774
+ process.exitCode = 1;
6775
+ return;
6776
+ }
6777
+ const existing = resolveLink(cfg.links, cwd);
6778
+ if (existing && !opts.force) {
6779
+ console.log(` ${existing.path} is already linked. Nothing to do.`);
6780
+ console.log(" Re-run with --force to mint a new key for this machine, or `wsync status` to see the links.");
6781
+ return;
6782
+ }
6783
+ const projectKey = opts.project?.trim() || await remoteProject(cwd);
6784
+ if (!projectKey) {
6785
+ console.error(
6786
+ `No git remote in ${cwd}, so there is nothing to name the project after. Pass --project <key> (e.g. github.com/team/repo).`
6787
+ );
6788
+ process.exitCode = 1;
6789
+ return;
6790
+ }
6791
+ const result = await callTool(server, token, {
6792
+ name: "wsync_setup",
6793
+ arguments: { projectKey, ...opts.name ? { name: opts.name } : {}, machine: opts.machine ?? hostname3() }
6720
6794
  });
6795
+ if (!result.ok) {
6796
+ console.error(result.message);
6797
+ process.exitCode = 1;
6798
+ return;
6799
+ }
6800
+ const key = /link\s+(wsp_[A-Za-z0-9_-]+)/.exec(result.command)?.[1];
6801
+ if (!key) {
6802
+ console.error(`${server} answered, but without a capture key to use. Check the token has owner or admin rights.`);
6803
+ process.exitCode = 1;
6804
+ return;
6805
+ }
6806
+ console.log(
6807
+ ` ${result.created ? "Created" : "Found"} project ${result.projectName ?? projectKey} (${result.projectKey ?? projectKey})`
6808
+ );
6809
+ await link(key, { server });
6721
6810
  }
6722
- function dequeue(path) {
6811
+ async function remoteProject(cwd) {
6812
+ const root = (0, import_wsync_core6.nearestGitRoot)(cwd);
6813
+ if (!root) return null;
6814
+ const remote = await (0, import_wsync_core6.getRemote)(root);
6815
+ return remote ? (0, import_wsync_core6.normaliseRemote)(remote) : null;
6816
+ }
6817
+ function hostname3() {
6818
+ return osHostname().trim() || "this machine";
6819
+ }
6820
+ async function callTool(server, token, params) {
6821
+ let res;
6723
6822
  try {
6724
- unlinkSync(path);
6725
- } catch {
6823
+ res = await fetch(`${server}/mcp`, {
6824
+ method: "POST",
6825
+ headers: { authorization: `Bearer ${token}`, "content-type": "application/json", accept: "application/json" },
6826
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params }),
6827
+ signal: AbortSignal.timeout(2e4)
6828
+ });
6829
+ } catch (e) {
6830
+ return { ok: false, message: `Could not reach ${server}: ${String(e)}` };
6726
6831
  }
6727
- }
6728
- function recordAttempt(path, entry) {
6832
+ if (res.status === 401) return { ok: false, message: `${server} rejected that token. Mint one in Settings \u2192 Claude (MCP).` };
6833
+ if (!res.ok) return { ok: false, message: `${server} answered ${res.status}.` };
6834
+ const body = await res.json().catch(() => ({}));
6835
+ if (body.error) return { ok: false, message: body.error.message ?? "The server refused the call." };
6836
+ const text = body.result?.content?.[0]?.text ?? "";
6837
+ if (body.result?.isError) return { ok: false, message: text || "The server refused the call." };
6729
6838
  try {
6730
- writeFileSync2(path, JSON.stringify({ ...entry, attempts: entry.attempts + 1 }), { mode: 384 });
6839
+ const parsed = JSON.parse(text);
6840
+ if (!parsed.command) return { ok: false, message: text || "No command came back from the server." };
6841
+ return {
6842
+ ok: true,
6843
+ command: parsed.command,
6844
+ projectKey: parsed.project?.projectKey,
6845
+ projectName: parsed.project?.name,
6846
+ created: Boolean(parsed.project?.created)
6847
+ };
6731
6848
  } catch {
6849
+ return { ok: false, message: text || "The server answered in a shape this CLI does not understand." };
6732
6850
  }
6733
6851
  }
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
- }
6852
+ var import_wsync_core6;
6853
+ var init_setup = __esm({
6854
+ "src/commands/setup.ts"() {
6855
+ "use strict";
6856
+ import_wsync_core6 = __toESM(require_dist(), 1);
6857
+ init_config();
6858
+ init_links();
6859
+ init_link();
6860
+ }
6861
+ });
6862
+
6863
+ // src/commands/flush.ts
6864
+ var import_wsync_core3 = __toESM(require_dist(), 1);
6865
+ init_config();
6866
+ init_links();
6867
+ init_spool();
6868
+ import { statSync as statSync2, existsSync as existsSync6, writeFileSync as writeFileSync5 } from "node:fs";
6869
+ import { createHash as createHash2 } from "node:crypto";
6870
+ import { join as join6 } from "node:path";
6871
+ import { hostname, platform } from "node:os";
6742
6872
 
6743
6873
  // src/commands/hook.ts
6744
6874
  init_config();
6745
6875
  init_links();
6876
+ init_spool();
6746
6877
  import { spawn } from "node:child_process";
6747
6878
  import { readFileSync as readFileSync4, writeFileSync as writeFileSync3, existsSync as existsSync4, statSync, appendFileSync } from "node:fs";
6748
6879
  import { join as join4 } from "node:path";
@@ -6752,6 +6883,7 @@ import { createHash } from "node:crypto";
6752
6883
  var import_wsync_core = __toESM(require_dist(), 1);
6753
6884
  init_config();
6754
6885
  init_links();
6886
+ init_spool();
6755
6887
  import { randomUUID as randomUUID2 } from "node:crypto";
6756
6888
  var EVENT_SUBCOMMANDS = {
6757
6889
  "event-prompt": "prompt",
@@ -7199,6 +7331,7 @@ async function refreshContext(cwd) {
7199
7331
 
7200
7332
  // src/bin.ts
7201
7333
  init_install();
7334
+ init_spool();
7202
7335
  init_config();
7203
7336
  var [cmd, sub, ...rest] = process.argv.slice(2);
7204
7337
  var args = [sub, ...rest].filter(Boolean);
@@ -7209,6 +7342,8 @@ var val = (n) => {
7209
7342
  };
7210
7343
  var USAGE = `wsync \u2014 work context across machines
7211
7344
 
7345
+ wsync setup <api-token> [--server URL] [--project KEY] [--machine NAME]
7346
+ one paste: mint this machine's key and link
7212
7347
  wsync link <key> [--server URL] link this directory to a project
7213
7348
  wsync backfill [--limit N] [--key wsp_\u2026] [--verbose]
7214
7349
  import existing transcripts over HTTP
@@ -7294,6 +7429,23 @@ try {
7294
7429
  }
7295
7430
  break;
7296
7431
  }
7432
+ case "setup": {
7433
+ const { setup: setup2 } = await Promise.resolve().then(() => (init_setup(), setup_exports));
7434
+ const token = args[0];
7435
+ if (!token || token.startsWith("--")) {
7436
+ console.error("Usage: wsync setup <api-token> [--server URL] [--project KEY] [--machine NAME]");
7437
+ process.exitCode = 1;
7438
+ break;
7439
+ }
7440
+ await setup2(token, {
7441
+ server: val("server"),
7442
+ project: val("project"),
7443
+ name: val("name"),
7444
+ machine: val("machine"),
7445
+ force: has("force")
7446
+ });
7447
+ break;
7448
+ }
7297
7449
  case "install-hooks":
7298
7450
  await installHooks({ dryRun: has("dry-run") });
7299
7451
  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.1.2",
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": {