shadok-ai 0.19.91 → 0.19.93

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.
@@ -28,7 +28,8 @@ and automatically starts the shadok-ai server when it is not running (port
28
28
  | `freetext <id> <n> "text"` | the "Type something" option: a free answer |
29
29
  | `list [--cwd DIR]` | driven agents (local state + alive/dead) and resumable sessions. With `--peer X`: the agents running ON X (from X itself, tagged `peer`), plus X's resumable sessions only for a `--cwd` you name — a path on X |
30
30
  | `diff <id>` | the agent's changes (git status + diff against the worktree's base) |
31
- | `stop <id>` | ends the session (for ALL its clients) |
31
+ | `stop <id> [--force]` | ends the session (for ALL its clients), whether it is running or dormant — sent by id, nothing is resumed — and answers `stopped:true` only once the server confirms. Works over `--peer` with no local state (a restricted peer may close only what it spawned). A local agent this pilotctl never drove needs `--force` |
32
+ | `reap [--idle 30m] [--dry-run]` | closes every finished agent you spawned: not busy, nobody watching, idle for `--idle` (default 30m). Over a restricted `--peer` that is every agent the peer lists for you (its own, dormant ones included); anywhere else only the ids in your local state. Use it to clear a backlog |
32
33
  | `set-parent <id> <parent-id\|none>` | re-link an agent to a parent, or **detach** it with `none` (it then reports to nobody). The link is what makes the parent hear when the agent finishes, blocks or dies — set automatically at spawn, flipped here when a side task is done and you want it off a lead's back |
33
34
  | `screen <id>` | raw TUI screen (debug) |
34
35
  | `profile-prompt "<text>" [--name NAME] [--readonly]` | rewrites a profile's **system prompt**: your own by default; any of them (and creation with `--name`) under the lead profile |
@@ -190,7 +191,8 @@ pilotctl peer add brasdroit1 https://brasdroit1.example.com <token> # once
190
191
  pilotctl spawn --peer brasdroit1 --profile dev --cwd /workspace # spawn there
191
192
  pilotctl prompt <id> "run the migration" --peer brasdroit1 # drive it
192
193
  pilotctl diff <id> --peer brasdroit1 # read its work
193
- pilotctl stop <id> --peer brasdroit1
194
+ pilotctl stop <id> --peer brasdroit1 # close it when done
195
+ pilotctl reap --peer brasdroit1 --dry-run # what you left open there
194
196
  ```
195
197
 
196
198
  - The **token** is minted by the REMOTE instance's admin (a human, in its
@@ -200,8 +202,10 @@ pilotctl stop <id> --peer brasdroit1
200
202
  - What you may touch on X depends on the **scope** its admin gave you when they
201
203
  invited you:
202
204
  - **restricted** (the default) — only the agents YOU spawned on X; `--peer X
203
- list` and a diff of someone else's agent come back refused (`peer-scope` /
204
- `403`). Assume this one unless you were told otherwise.
205
+ list` shows those (dormant ones included) and nothing else, and a diff or
206
+ stop of someone else's agent comes back refused (`peer-scope` / `403`). An
207
+ older X refuses `list` outright. Assume this scope unless you were told
208
+ otherwise.
205
209
  - **member** — you act like an invited user: `list`, `diff`, resume/drive/stop
206
210
  **any** agent on X, spawn more, read its usage. You are not an admin (no
207
211
  account or peer management).
@@ -149,10 +149,10 @@ export function parseArgs(argv) {
149
149
  const pos = [];
150
150
  for (let i = 0; i < rest.length; i++) {
151
151
  const a = rest[i];
152
- if (a === "--worktree" || a === "--continue" || a === "--readonly") flags[a.slice(2)] = true;
152
+ if (a === "--worktree" || a === "--continue" || a === "--readonly" || a === "--force" || a === "--dry-run") flags[a.slice(2)] = true;
153
153
  else if (
154
154
  a === "--cwd" || a === "--resume" || a === "--timeout" || a === "--profile" || a === "--parent" ||
155
- a === "--name" || a === "--peer" || a === "--peer-url" || a === "--peer-token"
155
+ a === "--name" || a === "--peer" || a === "--peer-url" || a === "--peer-token" || a === "--idle"
156
156
  ) flags[a.slice(2)] = rest[++i];
157
157
  // Repeatable: a Skill Factory skill the new agent is born with, `name` or `name@N`.
158
158
  else if (a === "--skill") (flags.skill ||= []).push(rest[++i]);
@@ -565,45 +565,113 @@ async function cmdSetParent(id, parentArg, flags) {
565
565
  return { sessionId: id, parent: r.parent ?? null };
566
566
  }
567
567
 
568
- async function cmdStop(id) {
568
+ /**
569
+ * Send `stop` for `id` on a BARE socket — no `start`, so nothing is resumed —
570
+ * and wait for the server's `stop-result`. The old path went through the local
571
+ * holder: with the holder gone (it is, once a `prompt` over a peer link returns
572
+ * and its socket drops) it sent NOTHING and only cleared local state, so the
573
+ * agent stayed open on the other instance for ever. Whether the caller may stop
574
+ * it is the server's call (a restricted peer: only its own), not the holder's.
575
+ */
576
+ async function stopById(id) {
577
+ const ws = await connect();
578
+ try {
579
+ return await new Promise((resolve) => {
580
+ const t = setTimeout(() => resolve({ type: "timeout" }), 30_000);
581
+ ws.on("message", (raw) => {
582
+ let m;
583
+ try {
584
+ m = JSON.parse(String(raw));
585
+ } catch {
586
+ return;
587
+ }
588
+ if ((m.type === "stop-result" && m.sessionId === id) || m.type === "error") {
589
+ clearTimeout(t);
590
+ resolve(m);
591
+ }
592
+ });
593
+ ws.on("close", () => {
594
+ clearTimeout(t);
595
+ resolve({ type: "socket-closed" });
596
+ });
597
+ ws.send(JSON.stringify({ type: "stop", sessionId: id }));
598
+ });
599
+ } finally {
600
+ ws.close();
601
+ }
602
+ }
603
+
604
+ /** Pure: what a `stop-result` / refusal means for the caller. */
605
+ export function stopOutcome(id, reply) {
606
+ if (reply.type === "stop-result" && reply.ok) return { stopped: true, sessionId: id };
607
+ if (reply.type === "stop-result") return { stopped: false, sessionId: id, note: "the server kept it (the home agent is never closed)" };
608
+ if (reply.type === "error") return { stopped: false, sessionId: id, error: reply.message, ...(reply.code ? { code: reply.code } : {}) };
609
+ return {
610
+ stopped: false,
611
+ sessionId: id,
612
+ note: "the server did not confirm the stop within 30s (an older shadok-ai answers nothing) — check with `list`",
613
+ };
614
+ }
615
+
616
+ async function cmdStop(id, flags = {}) {
569
617
  await ensureServer();
570
618
  const st = readState(id);
571
- const holderLive = !!(st?.holderPid && pidAlive(st.holderPid));
572
- if (!holderLive) {
573
- // No holder → we never kept this session alive; don't resurrect it just
574
- // to stop it (it may belong to a browser client). Clear local state only.
575
- deleteState(id);
576
- return { stopped: false, sessionId: id, note: "no live holder; local state cleared" };
577
- }
578
- let client;
579
- try {
580
- client = await openSession({ resume: id, cwd: st?.cwd ?? undefined });
581
- } catch (err) {
582
- // Holder pid is alive but session is dead (zombie holder, dead server session).
583
- // Kill the holder and clean up state.
584
- if (st.holderPid !== process.pid && pidAlive(st.holderPid)) {
619
+ // A LOCAL agent this pilotctl never drove may be someone's in the web UI: ask
620
+ // for --force. Over a peer link the peer's own scope already decides (a
621
+ // restricted peer can only close what it spawned).
622
+ if (!st && !PEER && !flags.force)
623
+ return { stopped: false, sessionId: id, note: "not an agent this pilotctl drove — pass --force to stop it anyway" };
624
+ const out = stopOutcome(id, await stopById(id));
625
+ if (out.stopped) {
626
+ if (st?.holderPid && st.holderPid !== process.pid && pidAlive(st.holderPid)) {
585
627
  try {
586
628
  process.kill(st.holderPid);
587
629
  } catch {}
588
630
  }
589
631
  deleteState(id);
590
- const msg = err instanceof Error ? err.message : String(err);
591
- return { stopped: false, sessionId: id, note: `session not reattachable (${msg}); holder killed and local state cleared` };
592
- }
593
- client.send({ type: "stop" });
594
- const result = await client.waitFor(["stopped", "socket-closed"], 30_000);
595
- client.ws.close();
596
- if (result.type === "timeout") {
597
- // Stop was not confirmed within 30s; don't kill holder or delete state (leave for retry).
598
- return { stopped: false, sessionId: id, note: "stop not confirmed within 30s; session may still be running" };
599
632
  }
600
- if (st.holderPid !== process.pid && pidAlive(st.holderPid)) {
601
- try {
602
- process.kill(st.holderPid);
603
- } catch {}
604
- }
605
- deleteState(id);
606
- return { stopped: true, sessionId: id };
633
+ return out;
634
+ }
635
+
636
+ /**
637
+ * Pure: which agents `reap` closes. Never a busy one, never one with someone
638
+ * watching it, never one active more recently than `idleSec` (a non-running
639
+ * row, idleSec -1, is idle by definition). Over a RESTRICTED peer link the list
640
+ * is already narrowed to what this peer spawned, so every row is ours; anywhere
641
+ * else the list holds other people's agents too, so only the ids this pilotctl
642
+ * spawned (its state files) are eligible.
643
+ */
644
+ export function reapCandidates(rows, { restricted, ownIds, idleSec }) {
645
+ return rows
646
+ .filter((r) => restricted || ownIds.has(r.id))
647
+ .filter((r) => !r.busy && !(r.clients > 0) && (r.idleSec < 0 || r.idleSec >= idleSec))
648
+ .map((r) => r.id);
649
+ }
650
+
651
+ /** Parse `30m` / `2h` / `90s` / a bare number of minutes → seconds. */
652
+ export function parseIdle(v, dflt = 1800) {
653
+ if (v === undefined || v === true) return dflt;
654
+ const m = /^(\d+)\s*([smh]?)$/.exec(String(v).trim());
655
+ if (!m) throw new Error(`--idle: expected e.g. 30m, 2h, 90s — got "${v}"`);
656
+ return Number(m[1]) * ({ s: 1, m: 60, h: 3600 }[m[2] || "m"]);
657
+ }
658
+
659
+ /** Close every finished agent this caller spawned — the backlog `stop` left behind. */
660
+ async function cmdReap(flags) {
661
+ await ensureServer();
662
+ const r = await fetch(`${httpBase()}/live`, { headers: authHeaders() });
663
+ if (!r.ok) throw new Error(`${httpBase()} answered HTTP ${r.status} to /live`);
664
+ const rows = await r.json();
665
+ const dir = stateDir();
666
+ const ownIds = new Set(
667
+ fs.existsSync(dir) ? fs.readdirSync(dir).filter((f) => f.endsWith(".json")).map((f) => f.slice(0, -5)) : [],
668
+ );
669
+ const restricted = r.headers.get("x-shadok-peer-scope") === "restricted";
670
+ const ids = reapCandidates(rows, { restricted, ownIds, idleSec: parseIdle(flags.idle) });
671
+ if (flags["dry-run"]) return { wouldStop: ids };
672
+ const results = [];
673
+ for (const id of ids) results.push(await cmdStop(id, { force: true }));
674
+ return { stopped: results.filter((x) => x.stopped).map((x) => x.sessionId), failed: results.filter((x) => !x.stopped) };
607
675
  }
608
676
 
609
677
  /**
@@ -690,7 +758,7 @@ async function cmdScreen(id, flags) {
690
758
  }
691
759
 
692
760
  const HELP =
693
- "usage: pilotctl <spawn|prompt|dialog|choose|toggle|confirm|freetext|list|diff|stop|set-parent|screen|profile-prompt|talk|talk-handle|peer> …\n" +
761
+ "usage: pilotctl <spawn|prompt|dialog|choose|toggle|confirm|freetext|list|diff|stop|reap|set-parent|screen|profile-prompt|talk|talk-handle|peer> …\n" +
694
762
  " pilotctl set-parent <id> <parent-id|none> # re-link or detach an agent from its parent\n" +
695
763
  " add --peer <alias> to any command to run it against another instance's agents\n" +
696
764
  " pilotctl peer <add <alias> <url> <ticket> [--token]|list|rm <alias>>";
@@ -797,7 +865,9 @@ export async function run(argv) {
797
865
  case "diff":
798
866
  return cmdDiff(pos[0]);
799
867
  case "stop":
800
- return cmdStop(pos[0]);
868
+ return cmdStop(pos[0], flags);
869
+ case "reap":
870
+ return cmdReap(flags);
801
871
  case "set-parent":
802
872
  return cmdSetParent(pos[0], pos[1], flags);
803
873
  case "screen":
@@ -36,3 +36,25 @@ test("state: write, read, delete", () => {
36
36
  deleteState("abc");
37
37
  assert.equal(readState("abc"), null);
38
38
  });
39
+
40
+ test("reapCandidates: only our ids outside a restricted peer, never busy/watched/recent", async () => {
41
+ const { reapCandidates } = await import("../pilotctl.mjs");
42
+ const rows = [
43
+ { id: "mine-idle", busy: false, clients: 0, idleSec: 4000 },
44
+ { id: "theirs-idle", busy: false, clients: 0, idleSec: 4000 },
45
+ { id: "mine-busy", busy: true, clients: 0, idleSec: 4000 },
46
+ ];
47
+ const ownIds = new Set(["mine-idle", "mine-busy"]);
48
+ assert.deepEqual(reapCandidates(rows, { restricted: false, ownIds, idleSec: 1800 }), ["mine-idle"]);
49
+ assert.deepEqual(reapCandidates(rows, { restricted: true, ownIds: new Set(), idleSec: 1800 }), ["mine-idle", "theirs-idle"]);
50
+ });
51
+
52
+ test("parseIdle reads 30m / 2h / 90s / bare minutes", async () => {
53
+ const { parseIdle } = await import("../pilotctl.mjs");
54
+ assert.equal(parseIdle(undefined), 1800);
55
+ assert.equal(parseIdle("30m"), 1800);
56
+ assert.equal(parseIdle("2h"), 7200);
57
+ assert.equal(parseIdle("90s"), 90);
58
+ assert.equal(parseIdle("45"), 2700);
59
+ assert.throws(() => parseIdle("soon"));
60
+ });
@@ -130,32 +130,81 @@ test("the diff fallback includes untracked files", async () => {
130
130
  }
131
131
  });
132
132
 
133
- test("stop with no live holder cleans the state without reattaching", async () => {
134
- const mock = await startMockServer();
133
+ // `stop` used to go through the local holder: with the holder gone (always, once
134
+ // a `prompt` over a peer link returned) it sent nothing and only cleared local
135
+ // state, so peers piled up finished agents. It now sends `stop` by id on a bare
136
+ // socket — no `start`, nothing resumed — and trusts only the server's answer.
137
+ test("stop with no live holder still stops the agent, by id, without resuming it", async () => {
138
+ const mock = await startMockServer({ stop: [{ type: "stop-result", sessionId: "dead", ok: true }] });
135
139
  process.env.SHADOK_PORT = String(mock.port);
136
140
  writeState("dead", { sessionId: "dead", cwd: "/tmp/x", holderPid: 999999 });
137
141
  try {
138
142
  const r = await run(["stop", "dead"]);
139
- assert.equal(r.stopped, false);
143
+ assert.equal(r.stopped, true);
140
144
  assert.equal(readState("dead"), null);
141
- assert.equal(mock.received.length, 0); // no start sent
145
+ assert.deepEqual(mock.received.map((m) => m.type), ["stop"]); // no start → no resume
146
+ assert.equal(mock.received[0].sessionId, "dead");
147
+ } finally {
148
+ await mock.close();
149
+ }
150
+ });
151
+
152
+ test("stop over a peer link needs no local state and sends the stop to the peer", async () => {
153
+ const mock = await startMockServer({ stop: [{ type: "stop-result", sessionId: "w1", ok: true }] });
154
+ try {
155
+ const r = await run(["stop", "w1", "--peer-url", `http://127.0.0.1:${mock.port}`, "--peer-token", "T"]);
156
+ assert.equal(r.stopped, true);
157
+ assert.deepEqual(mock.received.map((m) => m.type), ["stop"]);
142
158
  } finally {
143
159
  await mock.close();
144
160
  }
145
161
  });
146
162
 
147
- test("stop with a live session sends stop and cleans up", async () => {
163
+ test("a refused stop keeps the local state and says why", async () => {
164
+ const mock = await startMockServer({ stop: [{ type: "error", message: "a restricted peer may only stop its own agents", code: "peer-scope" }] });
165
+ process.env.SHADOK_PORT = String(mock.port);
166
+ writeState("theirs", { sessionId: "theirs", cwd: "/tmp/x", holderPid: null });
167
+ try {
168
+ const r = await run(["stop", "theirs"]);
169
+ assert.equal(r.stopped, false);
170
+ assert.equal(r.code, "peer-scope");
171
+ assert.ok(readState("theirs"));
172
+ } finally {
173
+ await mock.close();
174
+ }
175
+ });
176
+
177
+ test("a local agent pilotctl never drove needs --force", async () => {
178
+ const mock = await startMockServer({ stop: [{ type: "stop-result", sessionId: "ui-1", ok: true }] });
179
+ process.env.SHADOK_PORT = String(mock.port);
180
+ try {
181
+ const r = await run(["stop", "ui-1"]);
182
+ assert.equal(r.stopped, false);
183
+ assert.match(r.note, /--force/);
184
+ assert.equal(mock.received.length, 0);
185
+ assert.equal((await run(["stop", "ui-1", "--force"])).stopped, true);
186
+ } finally {
187
+ await mock.close();
188
+ }
189
+ });
190
+
191
+ test("reap over a restricted peer closes its idle leftovers, never a busy or watched one", async () => {
148
192
  const mock = await startMockServer({
149
- start: [{ type: "ready", sessionId: "abc", cwd: "/tmp/x" }],
150
- stop: [{ type: "stopped" }],
193
+ live: [
194
+ { id: "done", busy: false, clients: 0, idleSec: 4000 },
195
+ { id: "dormant", busy: false, clients: 0, idleSec: -1, running: false },
196
+ { id: "working", busy: true, clients: 0, idleSec: 9000 },
197
+ { id: "watched", busy: false, clients: 1, idleSec: 9000 },
198
+ { id: "fresh", busy: false, clients: 0, idleSec: 60 },
199
+ ],
200
+ liveHeaders: { "x-shadok-peer-scope": "restricted" },
201
+ stop: [{ type: "stop-result", sessionId: "done", ok: true }],
151
202
  });
152
- process.env.SHADOK_PORT = String(mock.port);
153
- // the test process' pid: alive, simulates an active holder
154
- writeState("abc", { sessionId: "abc", cwd: "/tmp/x", holderPid: process.pid });
155
203
  try {
156
- const r = await run(["stop", "abc"]);
157
- assert.equal(r.stopped, true);
158
- assert.equal(readState("abc"), null);
204
+ const url = `http://127.0.0.1:${mock.port}`;
205
+ const dry = await run(["reap", "--peer-url", url, "--peer-token", "T", "--dry-run"]);
206
+ assert.deepEqual(dry.wouldStop, ["done", "dormant"]);
207
+ assert.equal(mock.received.length, 0);
159
208
  } finally {
160
209
  await mock.close();
161
210
  }
@@ -178,18 +227,3 @@ test("screen returns the last screen received", async () => {
178
227
  }
179
228
  });
180
229
 
181
- test("stop with a live holder but a dead session cleans up and reports stopped:false", async () => {
182
- const mock = await startMockServer({
183
- start: [{ type: "error", message: "no session" }],
184
- });
185
- process.env.SHADOK_PORT = String(mock.port);
186
- writeState("zombie", { sessionId: "zombie", cwd: "/tmp/x", holderPid: process.pid });
187
- try {
188
- const r = await run(["stop", "zombie"]);
189
- assert.equal(r.stopped, false);
190
- assert.match(r.note, /not reattachable/);
191
- assert.equal(readState("zombie"), null);
192
- } finally {
193
- await mock.close();
194
- }
195
- });
@@ -23,6 +23,7 @@ export function startMockServer(script = {}) {
23
23
  res.setHeader("content-type", "application/json");
24
24
  if (req.url.startsWith("/live")) {
25
25
  if (script.liveStatus) res.statusCode = script.liveStatus;
26
+ for (const [k, v] of Object.entries(script.liveHeaders ?? {})) res.setHeader(k, v);
26
27
  return res.end(JSON.stringify(script.live ?? []));
27
28
  }
28
29
  if (req.url.startsWith("/sessions")) return res.end(JSON.stringify(script.sessions ?? []));
@@ -147,7 +147,14 @@ export async function main(argv) {
147
147
 
148
148
  const value = (await readStdin()).trim();
149
149
  if (!value) die("nothing on stdin — pipe the value in, e.g. `gh auth token | ... --stdin`");
150
- await api(ctx, "PUT", "/secrets", { name: parsed.name, value });
150
+ // `--attach` rides on the SAME request: the server creates the secret and
151
+ // binds it to this agent's own profile in one write, or refuses before
152
+ // storing anything. Two calls used to leave "stored, but NOT attached".
153
+ const stored = await api(ctx, "PUT", "/secrets", {
154
+ name: parsed.name,
155
+ value,
156
+ ...(parsed.attach ? { attach: true } : {}),
157
+ });
151
158
  // Never echo the value back: this output lands in the transcript, and may be
152
159
  // mirrored to Telegram.
153
160
  console.log(`stored ${parsed.name} in the vault`);
@@ -156,15 +163,20 @@ export async function main(argv) {
156
163
  console.log("or re-run with --attach to attach it to your own profile).");
157
164
  return;
158
165
  }
159
- // The vault write already succeeded, so a refusal here must not read as
160
- // "nothing was stored" — say both halves, and still exit non-zero so the
161
- // agent notices it did not get what it asked for.
162
- const att = await apiSoft(ctx, "PUT", "/profiles/secret", { name: parsed.name });
163
- if (!att.ok) {
164
- process.stderr.write(`stored, but NOT attached: ${att.error}\n`);
165
- process.exit(1);
166
+ let profile = stored.attached;
167
+ if (!profile) {
168
+ // An older server ignores `attach` (this script can be newer than the
169
+ // server it calls, invariant 57): fall back to the separate attach route.
170
+ // The vault write already succeeded, so a refusal here must not read as
171
+ // "nothing was stored" — say both halves, and still exit non-zero.
172
+ const att = await apiSoft(ctx, "PUT", "/profiles/secret", { name: parsed.name });
173
+ if (!att.ok) {
174
+ process.stderr.write(`stored, but NOT attached: ${att.error}\n`);
175
+ process.exit(1);
176
+ }
177
+ profile = att.body.profile;
166
178
  }
167
- console.log(`attached to your profile (${att.body.profile}).`);
179
+ console.log(`attached to your profile (${profile}).`);
168
180
  console.log("It is injected as an environment variable at your next reload, not in this");
169
181
  console.log("process: node ~/.claude/skills/shadok-reload/reload.mjs");
170
182
  }
@@ -4,12 +4,13 @@ import http from "node:http";
4
4
  // Deliberately not shared with the shadok-ai-agents skill's `mock-server.mjs`,
5
5
  // which is built around the WebSocket protocol and pilotctl's own routes.
6
6
  export async function fakeCockpit(status, body) {
7
- const seen = { body: undefined, cookie: undefined, method: undefined };
7
+ const seen = { body: undefined, cookie: undefined, method: undefined, paths: [] };
8
8
  const server = http.createServer((req, res) => {
9
9
  let raw = "";
10
10
  req.on("data", (c) => (raw += c));
11
11
  req.on("end", () => {
12
12
  seen.method = req.method;
13
+ seen.paths.push(`${req.method} ${req.url}`);
13
14
  seen.body = raw ? JSON.parse(raw) : null;
14
15
  seen.cookie = req.headers.cookie;
15
16
  res.writeHead(status, { "content-type": "application/json" });
@@ -36,6 +36,30 @@ test("set reads the value from stdin and sends it in the body", async () => {
36
36
  assert.match(res.out, /profile/i);
37
37
  });
38
38
 
39
+ test("set --attach creates and attaches in ONE request", async () => {
40
+ // Two calls (store, then attach) used to leave "stored, but NOT attached"
41
+ // behind; the server now does both in the same write, or neither.
42
+ const srv = await fakeCockpit(200, { names: ["A"], result: "created", attached: "Shadok-Marketing" });
43
+ const res = await run(["set", "A", "--stdin", "--attach"], srv.port, "s3cr3t\n");
44
+ await srv.close();
45
+ assert.equal(res.code, 0, res.err);
46
+ assert.deepEqual(srv.seen.paths, ["PUT /secrets"]);
47
+ assert.deepEqual(srv.seen.body, { name: "A", value: "s3cr3t", attach: true });
48
+ assert.match(res.out, /attached to your profile \(Shadok-Marketing\)/);
49
+ assert.doesNotMatch(res.out, /s3cr3t/);
50
+ });
51
+
52
+ test("set --attach falls back to the attach route on a server that ignores `attach`", async () => {
53
+ // A seeded script can be newer than the server it calls (invariant 57).
54
+ const srv = await fakeCockpit(200, { names: ["A"], result: "created", profile: "Shadok-dev" });
55
+ const res = await run(["set", "A", "--stdin", "--attach"], srv.port, "s3cr3t\n");
56
+ await srv.close();
57
+ assert.equal(res.code, 0, res.err);
58
+ assert.deepEqual(srv.seen.paths, ["PUT /secrets", "PUT /profiles/secret"]);
59
+ assert.deepEqual(srv.seen.body, { name: "A" });
60
+ assert.match(res.out, /attached to your profile \(Shadok-dev\)/);
61
+ });
62
+
39
63
  test("set requires --stdin, so a value can never be passed in argv", async () => {
40
64
  const srv = await fakeCockpit(200, {});
41
65
  const res = await run(["set", "A"], srv.port, "");
package/dist/secrets.d.ts CHANGED
@@ -184,8 +184,12 @@ export declare function loadVault(): Vault;
184
184
  export declare function saveVault(v: Vault): void;
185
185
  /** Secret names (never the values) in one group's own slice, sorted. */
186
186
  export declare function secretNames(groupId?: string): string[];
187
- /** Create or update a secret in `groupId` (default Main); an update keeps its sharing and provenance. */
188
- export declare function setSecret(name: string, value: string, groupId?: string, createdBy?: string): void;
187
+ /**
188
+ * Create or update a secret in `groupId` (default Main); an update keeps its
189
+ * sharing, provenance and profile binding. `profiles` applies to a CREATION
190
+ * only — it is how an agent's create-and-attach lands in one write.
191
+ */
192
+ export declare function setSecret(name: string, value: string, groupId?: string, createdBy?: string, profiles?: readonly string[]): void;
189
193
  export declare function deleteSecret(name: string, groupId?: string): void;
190
194
  /**
191
195
  * Replace a secret's `sharedWith` list (the groups it is lent to) — an
@@ -201,32 +205,34 @@ export declare function setSecretSharing(name: string, groupId: string, sharedWi
201
205
  */
202
206
  export declare function setSecretProfiles(name: string, groupId: string, profiles: string[]): boolean;
203
207
  /**
204
- * Provenance, kept in a SIDECAR file rather than in the vault: the vault is a
205
- * nested per-group `Vault` read by several paths (and migrated from an older
206
- * shape), and the one thing worse than losing provenance is corrupting the
207
- * credentials while adding it.
208
+ * The profile of the AGENT that created `entry`, or null — null means "a
209
+ * person put it there", or a creator we can no longer resolve.
208
210
  *
209
- * It exists for exactly one decision — an agent may attach to its profile a
210
- * secret IT created, and nothing else (see `secretAttachVerdict`). So a missing
211
- * entry must read as "a human put this here", which is the safe answer: absence
212
- * denies, it never grants.
213
- */
214
- export type SecretOrigin = {
215
- profile: string;
216
- at: number;
217
- };
218
- export type Origins = Record<string, SecretOrigin>;
219
- export declare function normalizeOrigins(raw: unknown): Origins;
220
- export declare function loadOrigins(): Origins;
221
- /** The profile that created this secret, or null — null means "a human did". */
222
- export declare function originProfile(name: string): string | null;
223
- /**
224
- * Record a creator. Called ONLY when a secret is created, never on an
225
- * overwrite: otherwise an agent could overwrite a human's secret with junk to
226
- * become its "creator", then attach the name. The value would be worthless,
227
- * but the laundering path should not exist at all.
228
- */
229
- export declare function recordOrigin(name: string, profile: string): void;
211
+ * It exists for exactly one decision: an agent may bind to its own profile a
212
+ * secret IT created, and nothing else (see `secretAttachVerdict`). So it reads
213
+ * the entry's own `createdBy` — stamped server-side at creation, kept on an
214
+ * overwrite, and scoped to the entry's group — and fails closed on anything
215
+ * else: absence denies, it never grants.
216
+ *
217
+ * It replaced a name-keyed sidecar (`secret-origin.json`) that could not be
218
+ * trusted once groups existed: one name lives in several groups, so a creation
219
+ * in one group re-stamped the "creator" of a same-named secret in another, and
220
+ * a person who deleted and re-created a name inherited the old agent creator.
221
+ */
222
+ export declare function creatorProfile(entry: Pick<SecretEntry, "createdBy"> | undefined, profileOfAgent: (agentId: string) => string | null): string | null;
223
+ /**
224
+ * Pure: may a `PUT /secrets` that asked to bind the new secret to the caller's
225
+ * own profile (`attach: true`) go ahead? Decided BEFORE anything is written, so
226
+ * a refusal never leaves a stored-but-unbound secret behind.
227
+ *
228
+ * Only a CREATION may carry the bind: the value is the one the agent just
229
+ * handed over, so binding it grants nothing it did not already hold. An
230
+ * overwrite must not, or an agent could replace a person's secret and claim it.
231
+ */
232
+ export declare function createAttachRefusal(opts: {
233
+ verdict: SecretWrite;
234
+ callerProfile: string | null;
235
+ }): string | null;
230
236
  /**
231
237
  * The `{ NAME: value }` env for a set of referenced names (unknown ones skipped),
232
238
  * resolved from `groupId` (own → shared-in → Main). `groupId` defaults to Main,