@zabuti/tools 0.1.10 → 0.1.11

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/README.md CHANGED
@@ -5,7 +5,7 @@ Claude Code skills. Needs a Zabuti license and a download token from zabuti.com/
5
5
  access).
6
6
 
7
7
  ```
8
- npx @zabuti/tools login zct_…
8
+ npx @zabuti/tools login # paste the token when it asks (it isn't shown)
9
9
  npx @zabuti/tools add logic-map
10
10
  npx @zabuti/tools add logic-optimizer
11
11
  npx @zabuti/tools add deadlock-map # beta
@@ -24,12 +24,19 @@ An update keeps the copy it replaces in `~/.zabuti/previous/<name>/`, outside th
24
24
  folder so Claude Code doesn't load it as a second skill. Running `rollback` again swaps back.
25
25
  Re-running `add` or `update` when nothing changed leaves the kept copy alone.
26
26
 
27
- Updates keep the changes you make to a skill. A file you never changed gets the new
28
- version. A file you changed is kept. When the update changes it too, the new version and the
29
- one yours started from wait in `~/.zabuti/updates/<name>/` (`.new` and `.original`), and the
30
- installer prints a prompt to paste into Claude Code to merge them. Files you add to the skill
31
- folder are never touched. `--overwrite` takes the new versions anyway (the replaced copy is
32
- still kept for `rollback`).
27
+ Nothing installed is overwritten without asking. If you didn't change a skill, `update`
28
+ lists the files it replaces and asks (Enter = yes). If you changed any file in it, `update`
29
+ writes nothing, not even the files you didn't touch. It lists your changes and offers to stage
30
+ the new version in `~/.zabuti/updates/<name>/` (`.new`, beside the `.original` yours started
31
+ from) with a prompt to paste into Claude Code to merge it. After merging a file, delete its
32
+ `.new`; the next `update` counts the new version as installed. Files you add to the skill
33
+ folder are never touched.
34
+
35
+ Outside an interactive terminal (scripts, CI), add `--yes` to answer yes. `--yes` never
36
+ replaces files you changed: a changed skill is staged. `--overwrite` takes the new versions
37
+ anyway, after asking, and backs up what it replaces to `~/.zabuti/backup/` (the replaced copy
38
+ is also kept for `rollback`). `--dry-run` shows the plan from the file list alone: nothing is
39
+ downloaded and no seat is taken. `logout` removes the saved token.
33
40
 
34
41
  The skill is written to `~/.claude/skills/<name>/`. The server checks your token and your
35
42
  organization's license on every download. Nothing from your project is sent. The free
@@ -4,10 +4,13 @@
4
4
  * Kept separate from the free `zabuti` CLI so that one never touches the network.
5
5
  */
6
6
  import { readFileSync } from "node:fs";
7
- import { cmdAddSkill, cmdLogin, cmdRollback, cmdStatus, cmdUpdate, SKILL_NAMES } from "./skills.js";
7
+ import { cmdLogin, cmdLogout } from "../../shared/token.js";
8
+ import { cmdAddSkill, cmdRollback, cmdStatus, cmdUpdate, SKILL_NAMES } from "./skills.js";
8
9
  const USAGE = `zabuti-tools: install the licensed Zabuti developer tools
9
10
 
10
- zabuti-tools login <token> save your download token (make one at zabuti.com/account)
11
+ zabuti-tools login save your download token (make one at zabuti.com/account);
12
+ asks for it without showing it (or pipe it in)
13
+ zabuti-tools logout remove the saved token
11
14
  zabuti-tools add <skill> install a skill into ~/.claude/skills/
12
15
  skills: ${SKILL_NAMES.join(", ")}
13
16
  zabuti-tools update [skill] update installed skills that have a newer version
@@ -16,13 +19,17 @@ const USAGE = `zabuti-tools: install the licensed Zabuti developer tools
16
19
  zabuti-tools status show what is installed and whether updates exist
17
20
  zabuti-tools --version
18
21
 
19
- Files you have changed are never overwritten: an update keeps yours and saves the new
20
- version to ~/.zabuti/updates/<skill>/ with a prompt for Claude Code to merge it.
22
+ Nothing installed is overwritten without asking. If you changed a skill, an update
23
+ writes nothing: it lists your changes and offers to stage the new version in
24
+ ~/.zabuti/updates/<skill>/ with a prompt for Claude Code to merge it.
21
25
 
22
- Options: --dry-run (add/update: show what would change, write nothing)
26
+ Options: --dry-run (add/update: show what would change, write nothing; fetches
27
+ only the file list, so it never takes a seat)
28
+ --yes (add/update: answer yes outside an interactive terminal; never
29
+ overwrites files you changed: a changed skill is staged)
23
30
  --out=<folder> (add: install there instead)
24
- --overwrite (add/update: take the new versions even where you changed a file;
25
- the copy it replaces is kept for rollback)
31
+ --overwrite (add/update: take the new versions even where you changed a file,
32
+ after asking; what it replaces is backed up to ~/.zabuti/backup/)
26
33
  An option a command doesn't take stops it before anything is written.`;
27
34
  function die(msg) {
28
35
  console.error(`zabuti-tools: ${msg}`);
@@ -38,8 +45,9 @@ const [command, name] = positionals;
38
45
  // the command writes.
39
46
  const ALLOWED = {
40
47
  login: [],
41
- add: ["--dry-run", "--out=", "--overwrite"],
42
- update: ["--dry-run", "--overwrite"],
48
+ logout: [],
49
+ add: ["--dry-run", "--out=", "--overwrite", "--yes"],
50
+ update: ["--dry-run", "--overwrite", "--yes"],
43
51
  rollback: [],
44
52
  status: [],
45
53
  help: [],
@@ -55,19 +63,22 @@ if (known) {
55
63
  try {
56
64
  switch (command) {
57
65
  case "login":
58
- cmdLogin(name);
66
+ await cmdLogin(name, "zabuti-tools", "Now: zabuti-tools add logic-map (or another skill)");
67
+ break;
68
+ case "logout":
69
+ cmdLogout("zabuti-tools");
59
70
  break;
60
71
  case "add":
61
72
  if (!name || !SKILL_NAMES.includes(name) || positionals.length > 2) {
62
73
  die(`add: name one skill (${SKILL_NAMES.join(" or ")}), e.g. \`zabuti-tools add logic-map\`.`);
63
74
  }
64
- await cmdAddSkill(name, flags.has("--dry-run"), outDir, flags.has("--overwrite"));
75
+ await cmdAddSkill(name, { dryRun: flags.has("--dry-run"), outDir, overwrite: flags.has("--overwrite"), yes: flags.has("--yes") });
65
76
  break;
66
77
  case "update":
67
78
  if ((name && !SKILL_NAMES.includes(name)) || positionals.length > 2) {
68
79
  die(`update: name one skill (${SKILL_NAMES.join(" or ")}) or none to update all installed ones.`);
69
80
  }
70
- await cmdUpdate(name, flags.has("--overwrite"), flags.has("--dry-run"));
81
+ await cmdUpdate(name, { dryRun: flags.has("--dry-run"), overwrite: flags.has("--overwrite"), yes: flags.has("--yes") });
71
82
  break;
72
83
  case "rollback":
73
84
  if (!name || !SKILL_NAMES.includes(name) || positionals.length > 2) {
@@ -1,43 +1,16 @@
1
1
  /**
2
- * Gated skills (Logic Map, Logic Optimizer): `zabuti-tools login <token>` stores a download
2
+ * Gated skills (Logic Map, Logic Optimizer): `zabuti-tools login` stores a download
3
3
  * token minted at zabuti.com/account; `zabuti-tools add logic-map` downloads the skill from
4
4
  * the site and writes it to ~/.claude/skills/<name>/. The server checks the token and
5
5
  * the account's license on every download. Nothing else is sent: no project files.
6
6
  */
7
- import { chmodSync, cpSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
7
+ import { cpSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
8
8
  import { homedir } from "node:os";
9
9
  import { basename, dirname, isAbsolute, join, resolve, sep } from "node:path";
10
- import { applyPlan, forgetOriginal, pendingFiles, planFiles, printMergeHelp, printPlan, sha256 } from "../../shared/keep-local-edits.js";
10
+ import { applyPlan, decide, pendingFiles, planProduct, printMergeHelp, printProductPlan, recordAfterApply, sha256, stagePlan, } from "../../shared/keep-local-edits.js";
11
+ import { CONFIG_DIR, storedToken } from "../../shared/token.js";
11
12
  export const SKILL_NAMES = ["logic-map", "logic-optimizer", "deadlock-map", "resource-drain-map"];
12
13
  const BASE_URL = (process.env.ZABUTI_URL ?? "https://zabuti.com").replace(/\/+$/, "");
13
- const CONFIG_DIR = join(homedir(), ".zabuti");
14
- const CONFIG_FILE = join(CONFIG_DIR, "config.json");
15
- const TOKEN_PREFIX = "zct_";
16
- function storedToken() {
17
- if (process.env.ZABUTI_TOKEN)
18
- return process.env.ZABUTI_TOKEN.trim();
19
- try {
20
- const t = JSON.parse(readFileSync(CONFIG_FILE, "utf8")).token;
21
- return typeof t === "string" ? t : null;
22
- }
23
- catch {
24
- return null;
25
- }
26
- }
27
- export function cmdLogin(token) {
28
- if (!token || !token.startsWith(TOKEN_PREFIX)) {
29
- throw new Error(`login: give the token from zabuti.com/account (starts with ${TOKEN_PREFIX}), e.g. \`zabuti-tools login ${TOKEN_PREFIX}…\`.`);
30
- }
31
- mkdirSync(CONFIG_DIR, { recursive: true });
32
- writeFileSync(CONFIG_FILE, JSON.stringify({ token }, null, 2) + "\n", { mode: 0o600 });
33
- try {
34
- chmodSync(CONFIG_FILE, 0o600);
35
- }
36
- catch {
37
- /* Windows: the home folder's ACL applies */
38
- }
39
- console.log(`✓ Saved to ${CONFIG_FILE}. Now: zabuti-tools add logic-map or zabuti-tools add logic-optimizer`);
40
- }
41
14
  /** A path from the server must stay inside the skill folder. */
42
15
  function safeJoin(root, rel) {
43
16
  const full = resolve(root, rel);
@@ -72,13 +45,15 @@ function unreachableMessage(e) {
72
45
  }
73
46
  return msg;
74
47
  }
75
- export async function cmdAddSkill(name, dryRun, outDir, overwrite = false) {
48
+ export async function cmdAddSkill(name, o = {}) {
76
49
  const token = storedToken();
77
50
  if (!token)
78
- throw new Error("not signed in. Make a token at zabuti.com/account, then run `zabuti-tools login <token>`.");
51
+ throw new Error("not signed in. Make a token at zabuti.com/account, then run `zabuti-tools login` and paste it.");
52
+ const dryRun = Boolean(o.dryRun);
53
+ // A dry run fetches paths + hashes only: no content, and it never takes a seat.
79
54
  let res;
80
55
  try {
81
- res = await fetch(`${BASE_URL}/api/cli/skills/${encodeURIComponent(name)}`, { headers: { authorization: `Bearer ${token}` } });
56
+ res = await fetch(`${BASE_URL}/api/cli/skills/${encodeURIComponent(name)}${dryRun ? "?check=1" : ""}`, { headers: { authorization: `Bearer ${token}` } });
82
57
  }
83
58
  catch (e) {
84
59
  throw new Error(unreachableMessage(e));
@@ -86,79 +61,73 @@ export async function cmdAddSkill(name, dryRun, outDir, overwrite = false) {
86
61
  const body = (await res.json().catch(() => null));
87
62
  if (!res.ok || !body?.files)
88
63
  throw new Error(body?.error ?? `the server answered ${res.status}.`);
89
- const root = outDir ? resolve(outDir) : skillRoot(name);
90
- const files = body.files.map((f) => ({ full: safeJoin(root, f.path), rel: f.path, content: f.content, sha256: f.sha256 }));
91
- for (const f of files) {
92
- if (f.sha256 && sha256(f.content) !== f.sha256) {
93
- throw new Error(`${f.rel} did not match its checksum; nothing was written. Run the command again.`);
64
+ const root = o.outDir ? resolve(o.outDir) : skillRoot(name);
65
+ const files = body.files.map((f) => {
66
+ const full = safeJoin(root, f.path);
67
+ if (typeof f.content === "string") {
68
+ const next = sha256(f.content);
69
+ if (f.sha256 && next !== f.sha256)
70
+ throw new Error(`${f.path} did not match its checksum; nothing was written. Run the command again.`);
71
+ return { rel: f.path, full, next, content: f.content };
94
72
  }
95
- }
73
+ if (!dryRun || !f.sha256)
74
+ throw new Error(`the server sent ${f.path} without its content; nothing was written. Run the command again.`);
75
+ return { rel: f.path, full, next: f.sha256 };
76
+ });
96
77
  const previous = previousDir(root, name);
97
78
  if (!dryRun)
98
79
  migrateLegacyBackup(root, previous);
99
80
  const manifest = readManifest(root);
100
81
  const installed = manifest?.files ? new Map(manifest.files.map((f) => [f.path, f.sha256])) : null;
101
- const plan = planFiles(files, installed, overwrite);
102
- // Files a newer version no longer ships: removed only if the user never changed them.
103
- const incoming = new Set(files.map((f) => f.rel));
104
- const dropped = (manifest?.files ?? [])
105
- .filter((f) => !incoming.has(f.path))
106
- .map((f) => {
107
- const full = safeJoin(root, f.path);
108
- const disk = existsSync(full) ? sha256(readFileSync(full, "utf8")) : null;
109
- return { rel: f.path, full, remove: disk !== null && (disk === f.sha256 || overwrite), gone: disk === null };
110
- });
111
- const removing = dropped.filter((d) => d.remove);
112
- const keptDropped = dropped.filter((d) => !d.remove && !d.gone);
113
82
  const store = editStore(root, name);
114
- const show = (f) => f.rel;
115
- if (dryRun) {
116
- console.log(`${name} → ${root}`);
117
- printPlan(plan, show, true);
118
- for (const d of removing)
119
- console.log(` - ${d.rel} (no longer part of ${name}; would be removed)`);
120
- for (const d of keptDropped)
121
- console.log(` · ${d.rel} (no longer part of ${name}; yours would be kept)`);
122
- if (!plan.some((f) => f.action !== "same") && !removing.length)
123
- console.log("Nothing would change.");
83
+ const plan = planProduct(files, installed, store, { dropRoot: (rel) => safeJoin(root, rel), dryRun });
84
+ const rerun = o.outDir ? `zabuti-tools add ${name} --out=${o.outDir}` : `zabuti-tools update ${name}`;
85
+ console.log(`${dryRun ? "[dry run] " : ""}${name} → ${root}`);
86
+ if (dryRun)
87
+ console.log("(dry run: file list and hashes only; nothing downloaded, no seat taken)");
88
+ printProductPlan(plan, store, name);
89
+ const decision = await decide(plan, { dryRun, yes: Boolean(o.yes), overwrite: Boolean(o.overwrite), product: name, rerun });
90
+ if (decision === "stage") {
91
+ const staged = stagePlan(plan, store);
92
+ if (plan.promoted.length && plan.installed)
93
+ writeManifest(root, name, plan.installed);
94
+ printMergeHelp(store, staged, rerun);
95
+ console.log(`\nOr, to drop your changes and take the new version: ${rerun} --overwrite (your files are backed up first)`);
124
96
  return;
125
97
  }
126
- const changesFolder = plan.some((f) => f.action === "write") || removing.length > 0;
127
- // Keep one previous copy so a bad update can be rolled back. It lives OUTSIDE
128
- // the skills folder: Claude Code loads every folder there as a skill. An update
129
- // that changes nothing leaves it alone, so it stays a real older version.
130
- if (changesFolder && existsSync(root)) {
98
+ if (decision === "none") {
99
+ // Current with no manifest (older install, or it was deleted): record it now.
100
+ if (!dryRun && plan.state === "current" && (!manifest || plan.promoted.length))
101
+ writeManifest(root, name, recordAfterApply(plan));
102
+ else if (!dryRun && plan.promoted.length && plan.installed)
103
+ writeManifest(root, name, plan.installed);
104
+ if (plan.state === "current") {
105
+ const yours = plan.files.filter((f) => f.kind === "yours").length;
106
+ console.log(`✓ ${name} is up to date at ${root}${yours ? ` (with your changes to ${yours} file(s))` : ""}`);
107
+ }
108
+ return;
109
+ }
110
+ // apply. Keep one previous copy so a bad update can be rolled back. It lives
111
+ // OUTSIDE the skills folder: Claude Code loads every folder there as a skill.
112
+ if (plan.state !== "install" && existsSync(root)) {
131
113
  rmSync(previous, { recursive: true, force: true });
132
114
  mkdirSync(dirname(previous), { recursive: true });
133
115
  cpSync(root, previous, { recursive: true });
134
116
  }
135
- applyPlan(plan, store);
136
- for (const d of removing) {
137
- rmSync(d.full, { force: true });
138
- forgetOriginal(store, d.rel);
139
- }
140
- writeManifest(root, name, files);
141
- const held = plan.filter((f) => f.action === "hold");
142
- if (!changesFolder && !held.length) {
143
- const kept = plan.filter((f) => f.action === "keep").length;
144
- console.log(`✓ ${name} is already up to date at ${root}${kept ? ` (your changes to ${kept} file(s) kept)` : ""}`);
145
- return;
146
- }
117
+ const backup = applyPlan(plan, store, Boolean(o.overwrite));
118
+ writeManifest(root, name, recordAfterApply(plan));
147
119
  console.log(`✓ ${manifest ? "Updated" : "Installed"} ${name} → ${root}`);
148
- printPlan(plan, show);
149
- for (const d of removing)
150
- console.log(` - ${d.rel} (no longer part of ${name}; removed)`);
151
- for (const d of keptDropped)
152
- console.log(` · ${d.rel} (no longer part of ${name}; you changed it, so it was kept)`);
153
- if (changesFolder && existsSync(previous))
120
+ if (backup)
121
+ console.log(` What it replaced is backed up in ${backup}`);
122
+ if (plan.state !== "install" && existsSync(previous))
154
123
  console.log(` Previous copy kept at ${previous} (undo with \`zabuti-tools rollback ${name}\`)`);
155
- printMergeHelp(store, held, `zabuti-tools add ${name} --overwrite (your current copy is kept for rollback)`);
156
124
  if (!manifest)
157
125
  console.log(" Open Claude Code in your project and ask it to use the skill.");
158
126
  }
159
127
  const MANIFEST = ".zabuti-install.json";
160
128
  function writeManifest(root, name, files) {
161
- const manifest = { name, installedAt: new Date().toISOString(), source: BASE_URL, files: files.map((f) => ({ path: f.rel, sha256: sha256(f.content) })) };
129
+ const list = [...files].sort(([a], [b]) => a.localeCompare(b)).map(([path, hash]) => ({ path, sha256: hash }));
130
+ const manifest = { name, installedAt: new Date().toISOString(), source: BASE_URL, files: list };
162
131
  writeFileSync(join(root, MANIFEST), JSON.stringify(manifest, null, 2));
163
132
  }
164
133
  const skillRoot = (name) => join(homedir(), ".claude", "skills", name);
@@ -172,12 +141,13 @@ const previousDir = (root, name) => join(CONFIG_DIR, "previous", storeKey(root,
172
141
  const editStore = (root, name) => ({
173
142
  originals: join(CONFIG_DIR, "original", storeKey(root, name)),
174
143
  pending: join(CONFIG_DIR, "updates", storeKey(root, name)),
144
+ backups: join(CONFIG_DIR, "backup", storeKey(root, name)),
175
145
  });
176
146
  /** " N changed file(s) have an update waiting…" when an earlier update held any back. */
177
147
  function waitingNote(root, name) {
178
148
  const store = editStore(root, name);
179
149
  const n = pendingFiles(store).length;
180
- return n ? ` ${n} changed file(s) have an update waiting to be merged: ${store.pending}` : "";
150
+ return n ? ` ${n} file(s) of a staged update are waiting to be merged: ${store.pending}` : "";
181
151
  }
182
152
  /** rename, falling back to copy + delete across drives (--out on another volume). */
183
153
  function moveDir(from, to) {
@@ -228,10 +198,11 @@ async function updateAvailable(name, m, token) {
228
198
  }
229
199
  }
230
200
  /** Update the named skill, or every installed one, only where zabuti.com has a newer copy. */
231
- export async function cmdUpdate(name, overwrite = false, dryRun = false) {
201
+ export async function cmdUpdate(name, o = {}) {
202
+ const dryRun = Boolean(o.dryRun);
232
203
  const token = storedToken();
233
204
  if (!token)
234
- throw new Error("not signed in. Make a token at zabuti.com/account, then run `zabuti-tools login <token>`.");
205
+ throw new Error("not signed in. Make a token at zabuti.com/account, then run `zabuti-tools login` and paste it.");
235
206
  const names = name ? [name] : SKILL_NAMES.filter((n) => existsSync(skillRoot(n)));
236
207
  if (!names.length) {
237
208
  console.log("No Zabuti skills are installed. Install one with `zabuti-tools add <skill>`.");
@@ -250,7 +221,7 @@ export async function cmdUpdate(name, overwrite = false, dryRun = false) {
250
221
  else if (typeof avail === "string")
251
222
  console.log(`${n}: skipped (${avail}).`);
252
223
  else
253
- await cmdAddSkill(n, dryRun, undefined, overwrite);
224
+ await cmdAddSkill(n, { ...o, outDir: undefined });
254
225
  }
255
226
  if (dryRun)
256
227
  console.log("Dry run: nothing was written. Run the same command without --dry-run to apply it.");
@@ -298,7 +269,7 @@ export async function cmdStatus() {
298
269
  if (typeof avail === "string")
299
270
  console.log(` Update check skipped (${avail}).`);
300
271
  else
301
- console.log(avail ? ` Update available: run \`zabuti-tools update\` (files you changed are kept).` : " Up to date.");
272
+ console.log(avail ? ` Update available: run \`zabuti-tools update\` (it asks first, and never overwrites files you changed).` : " Up to date.");
302
273
  const waiting = waitingNote(root, name);
303
274
  if (waiting)
304
275
  console.log(` ${waiting}`);
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Terminal prompts shared by `zabuti` and `zabuti-tools`. Nothing here writes files.
3
+ * Outside a terminal (CI, a pipe, Claude Code's shell) there is nobody to ask, so
4
+ * callers must treat "not interactive" as "no" unless the user passed --yes.
5
+ */
6
+ import { createInterface } from "node:readline";
7
+ export const interactive = () => Boolean(process.stdin.isTTY && process.stdout.isTTY);
8
+ function line(question) {
9
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
10
+ return new Promise((done) => rl.question(question, (a) => {
11
+ rl.close();
12
+ done(a.trim());
13
+ }));
14
+ }
15
+ /** Yes/no. Enter takes the default. */
16
+ export async function ask(question, defaultYes) {
17
+ const a = (await line(`${question} ${defaultYes ? "[Y/n]" : "[y/N]"} `)).toLowerCase();
18
+ if (!a)
19
+ return defaultYes;
20
+ return a === "y" || a === "yes";
21
+ }
22
+ /** One of a few choices by first letter. Enter takes the first. */
23
+ export async function choose(question, choices) {
24
+ const keys = choices.map((c, i) => (i === 0 ? c.label[0].toUpperCase() : c.label[0].toLowerCase()) + c.label.slice(1));
25
+ for (;;) {
26
+ const a = (await line(`${question} ${keys.map((k) => `[${k[0]}]${k.slice(1)}`).join(" / ")} `)).toLowerCase();
27
+ if (!a)
28
+ return choices[0].key;
29
+ const hit = choices.find((c) => c.label.toLowerCase().startsWith(a));
30
+ if (hit)
31
+ return hit.key;
32
+ }
33
+ }
34
+ /** Reads a secret without echoing it (raw mode); nothing reaches shell history. */
35
+ export function readSecret(prompt) {
36
+ const stdin = process.stdin;
37
+ process.stdout.write(prompt);
38
+ return new Promise((done, fail) => {
39
+ let value = "";
40
+ stdin.setRawMode(true);
41
+ stdin.resume();
42
+ stdin.setEncoding("utf8");
43
+ const onData = (chunk) => {
44
+ for (const ch of chunk) {
45
+ if (ch === "\r" || ch === "\n" || ch === "\u0004") {
46
+ finish();
47
+ done(value.trim());
48
+ return;
49
+ }
50
+ if (ch === "\u0003") {
51
+ finish();
52
+ fail(new Error("cancelled."));
53
+ return;
54
+ }
55
+ if (ch === "\u007f" || ch === "\b")
56
+ value = value.slice(0, -1);
57
+ else
58
+ value += ch;
59
+ }
60
+ };
61
+ const finish = () => {
62
+ stdin.off("data", onData);
63
+ stdin.setRawMode(false);
64
+ stdin.pause();
65
+ process.stdout.write("\n");
66
+ };
67
+ stdin.on("data", onData);
68
+ });
69
+ }
70
+ /** All of stdin (for `echo $TOKEN | zabuti login`). */
71
+ export async function readStdin() {
72
+ let s = "";
73
+ process.stdin.setEncoding("utf8");
74
+ for await (const chunk of process.stdin)
75
+ s += chunk;
76
+ return s.trim();
77
+ }
78
+ /** `zct_…abcd`: enough to recognise a saved token, never enough to use it. */
79
+ export const maskToken = (t) => (t.length > 12 ? `${t.slice(0, 4)}…${t.slice(-4)}` : "zct_…");
@@ -1,20 +1,37 @@
1
1
  /**
2
- * Updates that keep the user's own changes. Shared by `zabuti add` (components in a
3
- * project) and `zabuti-tools add/update` (skills in ~/.claude/skills).
2
+ * Installs and updates that never overwrite what the user has. Shared by `zabuti add`
3
+ * (components in a project) and `zabuti-tools add/update` (skills in ~/.claude/skills).
4
4
  *
5
- * Every install records the sha256 of each file as Zabuti wrote it. On the next
6
- * install, each incoming file is compared three ways (on disk, as installed, new):
7
- * same the file on disk already is the new version
8
- * write the user never touched it (or it is new): take the new version
9
- * keep the user changed it but this update doesn't: leave theirs alone
10
- * hold both changed (or it can't tell): leave theirs alone and put the new
11
- * version, with the version theirs started from, in a merge folder
12
- * Nothing the user changed is ever overwritten unless they pass --overwrite.
5
+ * Owner rule (2026-11-28): nothing we ship automatically overwrites anything the user
6
+ * has installed. If they changed a product, the install writes nothing: it says so,
7
+ * lists their changes, and offers to stage the update beside their copy with a merge
8
+ * plan. Even an unchanged product is only replaced after a yes.
9
+ *
10
+ * Every install records the sha256 of each file as Zabuti wrote it, and a copy
11
+ * (`<rel>.original`). Each incoming file is then one of:
12
+ * same the file on disk already is the new version
13
+ * new not on disk and never installed
14
+ * update the user never changed it; the update changes it
15
+ * yours the user changed (or deleted) it; the update doesn't change it
16
+ * conflict the user changed it (or it predates tracking) and the update changes it
17
+ * The product as a whole is then:
18
+ * current nothing to write
19
+ * install only new files (nothing of theirs is touched): written without asking
20
+ * update the user changed nothing; existing files would be replaced: ask first
21
+ * changed the user changed something the update would collide with or leave
22
+ * half-updated: write nothing; offer Stage update / Cancel
23
+ *
24
+ * Staging puts the full new version in the update folder (`<rel>.new`, plus the
25
+ * `<rel>.original` theirs started from) and a `<rel>.staged` copy beside the
26
+ * originals. When the user (or Claude) has merged a file and deleted its `.new`, the
27
+ * next run counts the staged version as installed, so their merge reads as theirs.
13
28
  */
14
29
  import { createHash } from "node:crypto";
15
- import { existsSync, mkdirSync, readdirSync, readFileSync, rmdirSync, rmSync, statSync, writeFileSync } from "node:fs";
30
+ import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmdirSync, rmSync, statSync, writeFileSync } from "node:fs";
16
31
  import { dirname, join, relative, sep } from "node:path";
32
+ import { ask, choose, interactive } from "./ask.js";
17
33
  export const sha256 = (s) => createHash("sha256").update(s, "utf8").digest("hex");
34
+ export const incoming = (rel, full, content) => ({ rel, full, next: sha256(content), content });
18
35
  function readText(path) {
19
36
  try {
20
37
  return readFileSync(path, "utf8");
@@ -23,92 +40,166 @@ function readText(path) {
23
40
  return null;
24
41
  }
25
42
  }
26
- /**
27
- * `installed` is rel -> sha256 from the last install, or null when there is no record
28
- * (installed before Zabuti tracked changes).
29
- */
30
- export function planFiles(files, installed, overwrite) {
31
- return files.map((f) => {
32
- const disk = readText(f.full);
33
- const next = sha256(f.content);
34
- const was = installed?.get(f.rel);
35
- const p = (action, note) => ({ ...f, action, note });
36
- if (disk !== null && sha256(disk) === next)
37
- return p("same", "");
38
- if (disk === null) {
39
- if (was === undefined || overwrite)
40
- return p("write", "new file");
41
- return was === next ? p("keep", "you deleted it; this update doesn't change it") : p("hold", "you deleted it; this update changes it");
42
- }
43
- if (overwrite)
44
- return p("write", "replaced (--overwrite)");
45
- if (was === undefined) {
46
- return p("hold", installed ? "a file of yours has the same name" : "it differs, and it was added before Zabuti tracked changes");
47
- }
48
- if (sha256(disk) === was)
49
- return p("write", "updated");
50
- if (was === next)
51
- return p("keep", "your changes kept; this update doesn't change it");
52
- return p("hold", "you changed it and this update changes it too");
53
- });
54
- }
55
- const originalPath = (store, rel) => join(store.originals, `${rel}.original`);
56
- const pendingNew = (store, rel) => join(store.pending, `${rel}.new`);
57
- const pendingOriginal = (store, rel) => join(store.pending, `${rel}.original`);
58
43
  function put(path, content) {
59
44
  mkdirSync(dirname(path), { recursive: true });
60
45
  writeFileSync(path, content);
61
46
  }
62
- /** Write the plan. `held` files get a `.new` (and `.original` when known) in the merge folder. */
63
- export function applyPlan(plan, store) {
64
- for (const f of plan) {
65
- if (f.action === "write")
66
- put(f.full, f.content);
67
- if (f.action === "hold") {
68
- put(pendingNew(store, f.rel), f.content);
69
- // Keep the oldest original: it is what the user's edits actually started from.
70
- const known = readText(originalPath(store, f.rel));
71
- if (!existsSync(pendingOriginal(store, f.rel)) && known !== null)
72
- put(pendingOriginal(store, f.rel), known);
73
- }
74
- else {
75
- // On disk matches (or the user keeps theirs on purpose): nothing left to merge.
76
- if (f.action !== "keep")
77
- clearPending(store, f.rel);
78
- }
79
- put(originalPath(store, f.rel), f.content);
80
- }
81
- pruneEmpty(store.pending);
82
- }
83
- export function clearPending(store, rel) {
84
- rmSync(pendingNew(store, rel), { force: true });
85
- rmSync(pendingOriginal(store, rel), { force: true });
86
- }
87
- export function forgetOriginal(store, rel) {
88
- rmSync(originalPath(store, rel), { force: true });
89
- }
90
- /** rel paths with an update waiting to be merged. */
91
- export function pendingFiles(store) {
47
+ const originalPath = (s, rel) => join(s.originals, `${rel}.original`);
48
+ const stagedPath = (s, rel) => join(s.originals, `${rel}.staged`);
49
+ const pendingNew = (s, rel) => join(s.pending, `${rel}.new`);
50
+ const pendingOriginal = (s, rel) => join(s.pending, `${rel}.original`);
51
+ function walkFiles(dir, suffix) {
92
52
  const out = [];
93
- const walk = (dir) => {
53
+ const walk = (d) => {
94
54
  let names;
95
55
  try {
96
- names = readdirSync(dir);
56
+ names = readdirSync(d);
97
57
  }
98
58
  catch {
99
59
  return;
100
60
  }
101
61
  for (const n of names) {
102
- const full = join(dir, n);
62
+ const full = join(d, n);
103
63
  if (statSync(full).isDirectory())
104
64
  walk(full);
105
- else if (n.endsWith(".new"))
106
- out.push(relative(store.pending, full).slice(0, -4).split(sep).join("/"));
65
+ else if (n.endsWith(suffix))
66
+ out.push(relative(dir, full).slice(0, -suffix.length).split(sep).join("/"));
107
67
  }
108
68
  };
109
- walk(store.pending);
69
+ walk(dir);
110
70
  return out.sort();
111
71
  }
72
+ /** rel paths with a staged update waiting to be merged. */
73
+ export const pendingFiles = (store) => walkFiles(store.pending, ".new");
74
+ /**
75
+ * `installed` is rel -> sha256 from the last install, or null when there is no record
76
+ * (installed before Zabuti tracked changes). `dropRoot` (rel -> full path): installed
77
+ * files missing from `files` belong to this product and were dropped by the new
78
+ * version (skills); leave it out when the record spans several products (a project's
79
+ * components). `dryRun` reads the store without changing it.
80
+ */
81
+ export function planProduct(files, recorded, store, { dropRoot, dryRun = false } = {}) {
82
+ // Staged files whose .new is gone were merged: their staged version is now "installed".
83
+ let installed = recorded ? new Map(recorded) : null;
84
+ const promoted = [];
85
+ for (const rel of walkFiles(store.originals, ".staged")) {
86
+ if (existsSync(pendingNew(store, rel)))
87
+ continue;
88
+ const staged = readText(stagedPath(store, rel));
89
+ if (staged === null)
90
+ continue;
91
+ promoted.push(rel);
92
+ installed ??= new Map();
93
+ installed.set(rel, sha256(staged));
94
+ if (!dryRun) {
95
+ renameSync(stagedPath(store, rel), originalPath(store, rel));
96
+ rmSync(pendingOriginal(store, rel), { force: true });
97
+ }
98
+ }
99
+ const knownInstalled = installed;
100
+ const planned = files.map((f) => {
101
+ const diskText = readText(f.full);
102
+ const disk = diskText === null ? null : sha256(diskText);
103
+ const was = knownInstalled?.get(f.rel);
104
+ const p = (kind, note) => ({ ...f, kind, note });
105
+ if (disk === f.next)
106
+ return p("same", "");
107
+ if (disk === null) {
108
+ if (was === undefined)
109
+ return p("new", "");
110
+ return was === f.next ? p("yours", "you deleted it") : p("conflict", "you deleted it");
111
+ }
112
+ if (was === undefined)
113
+ return p("conflict", knownInstalled ? "a file of yours has the same name" : "added before Zabuti tracked changes");
114
+ if (disk === was)
115
+ return p("update", "");
116
+ return was === f.next ? p("yours", "you changed it") : p("conflict", "you changed it");
117
+ });
118
+ const dropped = [];
119
+ if (dropRoot && knownInstalled) {
120
+ const shipped = new Set(files.map((f) => f.rel));
121
+ for (const [rel, was] of knownInstalled) {
122
+ if (shipped.has(rel))
123
+ continue;
124
+ const full = dropRoot(rel);
125
+ const diskText = readText(full);
126
+ dropped.push({ rel, full, kind: diskText === null ? "gone" : sha256(diskText) === was ? "remove" : "yours" });
127
+ }
128
+ }
129
+ const has = (k) => planned.some((f) => f.kind === k);
130
+ const replaces = has("update") || dropped.some((d) => d.kind === "remove");
131
+ const userChanged = has("yours") || has("conflict") || dropped.some((d) => d.kind === "yours");
132
+ const state = has("conflict") || (userChanged && replaces) ? "changed" : replaces ? "update" : has("new") ? "install" : "current";
133
+ return { files: planned, dropped, state, installed: knownInstalled, promoted };
134
+ }
135
+ /** rel -> sha256 to record after `apply`: every incoming file at its new version. */
136
+ export function recordAfterApply(plan) {
137
+ const out = new Map(plan.installed ?? []);
138
+ for (const d of plan.dropped)
139
+ if (d.kind !== "yours")
140
+ out.delete(d.rel);
141
+ for (const f of plan.files)
142
+ out.set(f.rel, f.next);
143
+ return out;
144
+ }
145
+ const stamp = () => new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
146
+ /**
147
+ * Write the new version. Without `overwrite` only new/update files are written and
148
+ * removable dropped files removed (callers only apply then for install/update states).
149
+ * With `overwrite` every differing file is written; whatever it replaces is first
150
+ * copied to the backup folder, whose path is returned.
151
+ */
152
+ export function applyPlan(plan, store, overwrite) {
153
+ const writes = plan.files.filter((f) => f.kind === "new" || f.kind === "update" || (overwrite && f.kind !== "same"));
154
+ const removes = plan.dropped.filter((d) => d.kind === "remove" || (overwrite && d.kind === "yours"));
155
+ let backup = null;
156
+ if (overwrite) {
157
+ const replaced = [...writes, ...removes].filter((f) => existsSync(f.full));
158
+ if (replaced.length) {
159
+ backup = join(store.backups, stamp());
160
+ for (const f of replaced) {
161
+ mkdirSync(dirname(join(backup, f.rel)), { recursive: true });
162
+ copyFileSync(f.full, join(backup, f.rel));
163
+ }
164
+ }
165
+ }
166
+ for (const f of writes) {
167
+ if (f.content === undefined)
168
+ throw new Error(`internal: ${f.rel} has no content to write`);
169
+ put(f.full, f.content);
170
+ }
171
+ for (const d of removes) {
172
+ rmSync(d.full, { force: true });
173
+ rmSync(originalPath(store, d.rel), { force: true });
174
+ }
175
+ for (const f of plan.files) {
176
+ // "yours" files keep their record: the update didn't change them.
177
+ if (f.kind === "yours" && !overwrite)
178
+ continue;
179
+ if (f.content !== undefined)
180
+ put(originalPath(store, f.rel), f.content);
181
+ rmSync(stagedPath(store, f.rel), { force: true });
182
+ rmSync(pendingNew(store, f.rel), { force: true });
183
+ rmSync(pendingOriginal(store, f.rel), { force: true });
184
+ }
185
+ pruneEmpty(store.pending);
186
+ return backup;
187
+ }
188
+ /** Stage the full new version for merging. Writes nothing outside the store. */
189
+ export function stagePlan(plan, store) {
190
+ const staged = plan.files.filter((f) => f.kind === "new" || f.kind === "update" || f.kind === "conflict");
191
+ for (const f of staged) {
192
+ if (f.content === undefined)
193
+ throw new Error(`internal: ${f.rel} has no content to stage`);
194
+ put(pendingNew(store, f.rel), f.content);
195
+ put(stagedPath(store, f.rel), f.content);
196
+ // Keep the oldest original: it is what the user's edits actually started from.
197
+ const known = readText(originalPath(store, f.rel));
198
+ if (!existsSync(pendingOriginal(store, f.rel)) && known !== null)
199
+ put(pendingOriginal(store, f.rel), known);
200
+ }
201
+ return staged;
202
+ }
112
203
  function pruneEmpty(dir) {
113
204
  if (!existsSync(dir))
114
205
  return;
@@ -120,38 +211,139 @@ function pruneEmpty(dir) {
120
211
  if (readdirSync(dir).length === 0)
121
212
  rmdirSync(dir);
122
213
  }
123
- /** One line per file that changed or was left alone. */
124
- export function printPlan(plan, show, dryRun = false) {
125
- const label = dryRun
126
- ? { write: "would write", keep: "would keep yours", hold: "would keep yours, new version saved to merge" }
127
- : { write: "written", keep: "kept yours", hold: "kept yours, new version saved to merge" };
128
- for (const action of ["write", "keep", "hold"]) {
129
- const fs = plan.filter((f) => f.action === action);
130
- if (!fs.length)
131
- continue;
132
- console.log(`${label[action]} (${fs.length}):`);
133
- for (const f of fs)
134
- console.log(` ${action === "write" ? "+" : action === "keep" ? "·" : "!"} ${show(f)}${f.note && f.note !== "updated" && f.note !== "new file" ? ` (${f.note})` : ""}`);
214
+ // ---------------------------------------------------------------------------
215
+ // reporting
216
+ // ---------------------------------------------------------------------------
217
+ /** "+3 −1 lines" against the copy Zabuti installed (line multiset; no diff engine). */
218
+ function lineChange(store, f) {
219
+ const was = readText(originalPath(store, f.rel));
220
+ const now = readText(f.full);
221
+ if (was === null || now === null)
222
+ return "";
223
+ const count = (s) => {
224
+ const m = new Map();
225
+ for (const l of s.split(/\r?\n/))
226
+ m.set(l, (m.get(l) ?? 0) + 1);
227
+ return m;
228
+ };
229
+ const a = count(was);
230
+ const b = count(now);
231
+ let added = 0;
232
+ let removed = 0;
233
+ for (const [l, n] of b)
234
+ added += Math.max(0, n - (a.get(l) ?? 0));
235
+ for (const [l, n] of a)
236
+ removed += Math.max(0, n - (b.get(l) ?? 0));
237
+ return added || removed ? ` (+${added} −${removed} lines)` : " (line endings or whitespace only)";
238
+ }
239
+ /** "folder/ (12 files)" for the new files; existing-file changes listed one by one, first. */
240
+ export function printProductPlan(plan, store, product) {
241
+ const existing = plan.files.filter((f) => f.kind === "update" || f.kind === "yours" || f.kind === "conflict");
242
+ const dropped = plan.dropped.filter((d) => d.kind !== "gone");
243
+ if (existing.length || dropped.length) {
244
+ console.log(`Files you already have (${existing.length + dropped.length}):`);
245
+ for (const f of existing) {
246
+ if (f.kind === "update")
247
+ console.log(` ~ ${f.rel} the update changes it (you didn't)`);
248
+ else {
249
+ const why = f.note === "you changed it" ? `you changed it${lineChange(store, f)}` : f.note;
250
+ console.log(` ! ${f.rel} ${why}; ${f.kind === "conflict" ? "this update changes it too" : "this update doesn't change it"}`);
251
+ }
252
+ }
253
+ for (const d of dropped) {
254
+ console.log(` - ${d.rel} no longer part of ${product}${d.kind === "yours" ? "; you changed it, so it stays" : "; would be removed"}`);
255
+ }
256
+ }
257
+ const fresh = plan.files.filter((f) => f.kind === "new");
258
+ if (fresh.length) {
259
+ const byDir = new Map();
260
+ for (const f of fresh) {
261
+ const d = f.rel.includes("/") ? f.rel.slice(0, f.rel.lastIndexOf("/") + 1) : "./";
262
+ byDir.set(d, [...(byDir.get(d) ?? []), f.rel.slice(d === "./" ? 0 : d.length)]);
263
+ }
264
+ console.log(`New files (${fresh.length}):`);
265
+ for (const [d, names] of [...byDir].sort(([a], [b]) => a.localeCompare(b))) {
266
+ console.log(names.length === 1 ? ` + ${d === "./" ? "" : d}${names[0]}` : ` + ${d} (${names.length} files)`);
267
+ }
135
268
  }
269
+ const same = plan.files.filter((f) => f.kind === "same").length;
270
+ if (same)
271
+ console.log(`Already current: ${same} file(s).`);
136
272
  }
137
- /** The steps for merging, plus a prompt to paste into Claude Code. */
138
- export function printMergeHelp(store, held, overwriteHint) {
139
- if (!held.length)
273
+ /** The merge steps, plus a prompt to paste into Claude Code. */
274
+ export function printMergeHelp(store, staged, rerun) {
275
+ if (!staged.length)
140
276
  return;
141
- const lines = held.map((f) => {
277
+ const merge = staged.filter((f) => f.kind === "conflict");
278
+ const take = staged.filter((f) => f.kind !== "conflict");
279
+ const mergeLines = merge.map((f) => {
142
280
  const hasOriginal = existsSync(pendingOriginal(store, f.rel));
143
- return `- ${f.full}\n new Zabuti version: ${pendingNew(store, f.rel)}` + (hasOriginal ? `\n version yours started from: ${pendingOriginal(store, f.rel)}` : "\n (the version yours started from wasn't recorded: compare yours with the new one)");
281
+ return (`- ${f.full}\n new Zabuti version: ${pendingNew(store, f.rel)}` +
282
+ (hasOriginal ? `\n version yours started from: ${pendingOriginal(store, f.rel)}` : "\n (the version yours started from wasn't recorded: compare yours with the new one)"));
144
283
  });
145
- console.log(`\nYour changes to ${held.length} file(s) were kept. The updates for them are waiting in:\n ${store.pending}`);
146
- console.log("To merge them, paste this into Claude Code:\n");
284
+ const takeLines = take.map((f) => `- ${pendingNew(store, f.rel)} -> ${f.full}`);
285
+ console.log(`\nThe full new version is staged in:\n ${store.pending}\nNothing in your copy was changed. To merge it, paste this into Claude Code:\n`);
147
286
  console.log([
148
- "Merge a Zabuti update into files I've changed. For each file below, keep my changes and bring in",
149
- "what changed between the version mine started from and the new Zabuti version. Show me anything",
150
- "where the two clash before deciding. When a file is merged, delete its .new and .original files.",
287
+ "Merge a staged Zabuti update into my copy. Show me the plan (each file, what changes) and wait",
288
+ "for my OK before editing anything.",
289
+ ...(merge.length
290
+ ? ["", "Files I changed that the update also changes: keep my changes and bring in what changed between", "the version mine started from and the new Zabuti version. Show me anything where the two clash.", ...mergeLines]
291
+ : []),
292
+ ...(take.length ? ["", "Files I didn't change: copy the new version over mine (or add it when it's new).", ...takeLines] : []),
151
293
  "",
152
- ...lines,
294
+ "As each file is done, delete its .new (and .original) file in the staged folder. When all are done,",
295
+ `run \`${rerun}\` again: it should then say everything is current.`,
153
296
  ]
154
297
  .map((l) => ` ${l}`)
155
298
  .join("\n"));
156
- console.log(`\nOr to drop your changes and take the new versions instead: ${overwriteHint}`);
299
+ }
300
+ /**
301
+ * What to do with a plan, asking when there is a terminal. Outside one, `--yes`
302
+ * stands in for the answer, and it never overwrites changed files: for a changed
303
+ * product it stages. Sets process.exitCode = 1 when it stopped for want of an answer.
304
+ */
305
+ export async function decide(plan, o) {
306
+ const replaced = plan.files.filter((f) => f.kind === "update").length + plan.dropped.filter((d) => d.kind === "remove").length;
307
+ const needsYes = (what) => {
308
+ console.log(`\nNothing was written: ${what} needs a yes, and this isn't an interactive terminal. Run it again in a terminal, or add --yes.`);
309
+ process.exitCode = 1;
310
+ return "none";
311
+ };
312
+ if (plan.state === "current")
313
+ return "none";
314
+ if (plan.state === "install")
315
+ return o.dryRun ? "none" : "apply";
316
+ if (plan.state === "update") {
317
+ if (o.dryRun) {
318
+ console.log(`\n[dry run] It would ask before replacing ${replaced} file(s) with the new version.`);
319
+ return "none";
320
+ }
321
+ if (!interactive())
322
+ return o.yes ? "apply" : needsYes(`replacing ${replaced} file(s)`);
323
+ return (await ask(`\nReplace ${replaced} file(s) with the new version of ${o.product}?`, true)) ? "apply" : "none";
324
+ }
325
+ // changed
326
+ console.log(`\nYou've changed ${o.product} since Zabuti installed it (the ! lines above), so nothing has been written.` +
327
+ "\nStaging puts the full new version beside yours with a merge plan; your copy stays as it is.");
328
+ if (o.overwrite) {
329
+ if (o.dryRun) {
330
+ console.log("[dry run] --overwrite would replace your changed files after backing them up.");
331
+ return "none";
332
+ }
333
+ if (!interactive())
334
+ return o.yes ? "apply" : needsYes("--overwrite");
335
+ return (await ask("--overwrite: replace your changed files with the new version? (they are backed up first)", false)) ? "apply" : "none";
336
+ }
337
+ if (o.dryRun) {
338
+ console.log("[dry run] It would offer: Stage update (default) / Cancel.");
339
+ return "none";
340
+ }
341
+ if (!interactive())
342
+ return o.yes ? "stage" : needsYes("staging the update");
343
+ return (await choose("What now?", [
344
+ { key: "stage", label: "stage update" },
345
+ { key: "cancel", label: "cancel" },
346
+ ])) === "stage"
347
+ ? "stage"
348
+ : "none";
157
349
  }
@@ -0,0 +1,72 @@
1
+ /**
2
+ * The download token, shared by `zabuti` and `zabuti-tools` (~/.zabuti/config.json,
3
+ * so one login covers both). `login` with no argument reads the token from a hidden
4
+ * prompt, or from stdin when piped, so it never lands in shell history.
5
+ */
6
+ import { chmodSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
7
+ import { homedir } from "node:os";
8
+ import { join } from "node:path";
9
+ import { interactive, maskToken, readSecret, readStdin } from "./ask.js";
10
+ export const CONFIG_DIR = join(homedir(), ".zabuti");
11
+ const CONFIG_FILE = join(CONFIG_DIR, "config.json");
12
+ const TOKEN_PREFIX = "zct_";
13
+ function readConfig() {
14
+ try {
15
+ const c = JSON.parse(readFileSync(CONFIG_FILE, "utf8").replace(/^\uFEFF/, ""));
16
+ return c && typeof c === "object" ? c : {};
17
+ }
18
+ catch {
19
+ return {};
20
+ }
21
+ }
22
+ function writeConfig(c) {
23
+ mkdirSync(CONFIG_DIR, { recursive: true });
24
+ writeFileSync(CONFIG_FILE, JSON.stringify(c, null, 2) + "\n", { mode: 0o600 });
25
+ try {
26
+ chmodSync(CONFIG_FILE, 0o600);
27
+ }
28
+ catch {
29
+ /* Windows: the home folder's ACL applies */
30
+ }
31
+ }
32
+ export function storedToken() {
33
+ if (process.env.ZABUTI_TOKEN)
34
+ return process.env.ZABUTI_TOKEN.trim();
35
+ const t = readConfig().token;
36
+ return typeof t === "string" ? t : null;
37
+ }
38
+ /** `cli` is the command name shown in messages ("zabuti" or "zabuti-tools"); `next` the hint after saving. */
39
+ export async function cmdLogin(arg, cli, next) {
40
+ const saved = readConfig().token;
41
+ let token = arg;
42
+ if (token) {
43
+ console.log("⚠ A token typed on the command line stays in your shell history (PowerShell keeps it in a plain-text file)." +
44
+ `\n Next time run \`${cli} login\` with no token: it asks for it without showing it.`);
45
+ }
46
+ else if (interactive()) {
47
+ if (typeof saved === "string")
48
+ console.log(`A token is already saved (${maskToken(saved)}). Paste a new one to replace it, or press Ctrl+C to keep it.`);
49
+ token = await readSecret("Paste your token from zabuti.com/account (it won't be shown): ");
50
+ }
51
+ else {
52
+ token = await readStdin();
53
+ }
54
+ if (!token || !token.startsWith(TOKEN_PREFIX)) {
55
+ throw new Error(`login: that isn't a token from zabuti.com/account (they start with ${TOKEN_PREFIX}). Run \`${cli} login\` and paste it when asked.`);
56
+ }
57
+ writeConfig({ ...readConfig(), token });
58
+ console.log(`✓ Saved ${maskToken(token)} to ${CONFIG_FILE}. ${next}`);
59
+ }
60
+ export function cmdLogout(cli) {
61
+ const c = readConfig();
62
+ if (typeof c.token !== "string") {
63
+ console.log(`No token is saved in ${CONFIG_FILE}.`);
64
+ }
65
+ else {
66
+ delete c.token;
67
+ writeConfig(c);
68
+ console.log(`✓ Removed the saved token from ${CONFIG_FILE}. Revoke it on zabuti.com/account if it may have leaked. \`${cli} login\` to sign in again.`);
69
+ }
70
+ if (process.env.ZABUTI_TOKEN)
71
+ console.log(" ZABUTI_TOKEN is still set in this shell and will be used until you clear it.");
72
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zabuti/tools",
3
- "version": "0.1.10",
3
+ "version": "0.1.11",
4
4
  "description": "Installs the licensed Zabuti developer tools (Logic Map, Logic Optimizer, Deadlock Map, Resource Drain Map) as Claude Code skills. Needs a license and a download token from zabuti.com.",
5
5
  "homepage": "https://zabuti.com",
6
6
  "license": "MIT",