slashvibe-mcp 0.9.18 → 0.9.19

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
@@ -218,6 +218,9 @@ opened a line with. Anyone else waits where `vibe start` lists what is waiting.
218
218
  You are still told when that happens. When a session opens, one line says how many people
219
219
  you have not written to are waiting, and how to ask: `what's waiting on /vibe`. It says
220
220
  nothing about who they are or what they wrote, to you or to your agent, until you ask.
221
+ If one of them first wrote after you were given your invite line (`setup --from @you`), it
222
+ says it may be someone you invited: that is from timing on your machine alone, since /vibe
223
+ does not yet tell you who accepted an invite.
221
224
 
222
225
  ```bash
223
226
  npx slashvibe-mcp quiet # nothing surfaces until: unquiet
@@ -264,7 +267,10 @@ the line above, and `vibe_people` when you ask.
264
267
  ## What is promised
265
268
 
266
269
  - **Nothing your agent wrote is sent without your Send.** The approval is bound to the
267
- exact text you saw; a draft changed since is refused.
270
+ exact text you saw; a draft changed since is refused. A changed draft must be shown again
271
+ before it can be sent: in Claude Code, a draft prepared after your last message is not
272
+ sent until you have had a turn to see it (the arrival hook records that you typed, and
273
+ when; never what).
268
274
  - **Other people's words are data.** A message, or what someone says they are working on,
269
275
  is shown to you and never acted on.
270
276
  - **Arrival is presentation, not delivery.** The hook reads one local file, makes no
@@ -282,7 +288,9 @@ npx slashvibe-mcp hook uninstall
282
288
  ```
283
289
 
284
290
  Two Claude Code hooks: one shows what was waiting when a session opens, one brings a
285
- message in at your next prompt or after the next tool call. Set `VIBE_ARRIVALS=off` in the
291
+ message in at your next prompt or after the next tool call. A conversation you have answered
292
+ is not waiting, even while their message is still unread; it is waiting again when they
293
+ write again. Set `VIBE_ARRIVALS=off` in the
286
294
  server's env to turn arrival off.
287
295
 
288
296
  **Live push (optional, Claude Code research preview).** To have a message arrive while a
@@ -295,7 +303,7 @@ unless you always launch with it.
295
303
 
296
304
  ## Manual setup
297
305
 
298
- If you'd rather wire it yourself, add to `~/.claude.json` (or your host's MCP config):
306
+ If you'd rather wire it yourself, add to Claude Code's `~/.claude.json`:
299
307
 
300
308
  ```json
301
309
  {
package/draft-cli.js CHANGED
@@ -64,7 +64,9 @@ async function main() {
64
64
 
65
65
  if (verb === 'send') {
66
66
  if (!id || !rev) return out({ error: 'usage', message: 'vibe-draft send <id> <rev>' }, 2);
67
- const r = await moves.vibe_send.handler({ id, rev });
67
+ // The person chose Send here, themselves: that choice is their turn, so the
68
+ // agent-side check (a person-turn after the rev was prepared) does not apply.
69
+ const r = await moves.sendByPerson({ id, rev });
68
70
  const data = (r && r.data) || {};
69
71
  const stored = storedStatus(id);
70
72
  return out({ id, sent: Boolean(data.sent), message_id: data.message_id || null, status: stored.status, unconfirmed: stored.unconfirmed, display: r && r.display ? String(r.display) : null, definite: Boolean(data.definite) });
@@ -14,7 +14,8 @@
14
14
  * most of a second). The spool is the sibling directory, so the copy always
15
15
  * reads the identity it was installed for.
16
16
  *
17
- * Presentation only: writes no receipt and no read state.
17
+ * Presentation only: writes no receipt and no read state. The one thing it
18
+ * records is that the person prompted, and when (recordTurn, for vibe_send).
18
19
  *
19
20
  * One more thing it does on a prompt: when the person says they are stuck, it
20
21
  * reminds the agent, once per session, that vibe_bump exists (see stuckNudge).
@@ -56,6 +57,9 @@ function main() {
56
57
  try { input = JSON.parse(fs.readFileSync(0, 'utf8') || '{}'); } catch {}
57
58
  const event = input.hook_event_name;
58
59
  if (!EVENTS.has(event)) return quiet();
60
+ // The person typed: a draft prepared before now is one they could have seen.
61
+ // Only on a prompt, never after a tool call (the agent's own turn).
62
+ if (event === 'UserPromptSubmit') recordTurn(input);
59
63
 
60
64
  const dir = process.env.VIBE_ARRIVALS_DIR || path.join(__dirname, '..', 'arrivals');
61
65
  const session = String(input.session_id || '').replace(/[^A-Za-z0-9_-]/g, '').slice(0, 80);
@@ -80,6 +84,36 @@ function main() {
80
84
  }));
81
85
  }
82
86
 
87
+ // ── a person's turn (turns.js) ──────────────────────────────────────────────
88
+ // vibe_send sends a draft revision only if the person has prompted since that
89
+ // revision was prepared. This records the prompt: a timestamp in a file named
90
+ // by a hash of the project directory. No prompt text, no path in clear.
91
+ // Keyed by CLAUDE_PROJECT_DIR (the project root, unmoved by a cd) and by the
92
+ // input cwd as well when it differs, so a server started in either place
93
+ // finds it. key() must match turns.js (a test pins it).
94
+ function turnKey(dir) {
95
+ let real = String(dir || '');
96
+ if (!real) return null;
97
+ try { real = fs.realpathSync(real); } catch { real = path.resolve(real); }
98
+ return require('crypto').createHash('sha256').update(real, 'utf8').digest('hex').slice(0, 32);
99
+ }
100
+
101
+ function recordTurn(input) {
102
+ try {
103
+ const dir = process.env.VIBE_TURNS_DIR || path.join(__dirname, '..', 'turns');
104
+ const keys = new Set([process.env.CLAUDE_PROJECT_DIR, input.cwd].filter((d) => typeof d === 'string' && d.trim()).map(turnKey).filter(Boolean));
105
+ if (keys.size === 0) return;
106
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
107
+ const at = JSON.stringify({ at: Date.now() });
108
+ for (const k of keys) {
109
+ const file = path.join(dir, `${k}.json`);
110
+ const tmp = `${file}.${process.pid}.tmp`;
111
+ fs.writeFileSync(tmp, at, { mode: 0o600 });
112
+ fs.renameSync(tmp, file);
113
+ }
114
+ } catch {}
115
+ }
116
+
83
117
  // ── the bump, made dependable ───────────────────────────────────────────────
84
118
  // vibe_bump exists for the moment a person is stuck, but whether the agent
85
119
  // thinks of it was left to the agent, and measured it mostly did not: one
package/index.js CHANGED
@@ -67,8 +67,9 @@ if (CHANNEL_ENABLED) SERVER_CAPABILITIES.experimental = { 'claude/channel': {} }
67
67
 
68
68
  const SERVER_INSTRUCTIONS = [
69
69
  '/vibe lets the person you are working with exchange messages with other people from inside this session, without stopping to write them.',
70
- 'When their work produces a question for someone or a result someone would want, you may offer to send it: choose who with vibe_people, write 1-3 sentences from the work, and open it with vibe_prepare. That shows a preview and sends nothing. Only vibe_send with the draft id and rev sends, and only after the person chose Send.',
70
+ 'When their work produces a question for someone or a result someone would want, you may offer to send it: choose who with vibe_people, write 1-3 sentences from the work, and open it with vibe_prepare. That shows a preview and sends nothing. Only vibe_send with the draft id and rev sends, and only after the person chose Send. A changed draft must be shown again before it can be sent: if the person asks for a change and Send in the same message, prepare the change, show it, and wait for their next message.',
71
71
  'When a message arrives for them, tell them in one line and, if this session holds something true to say back, prepare the answer the same way.',
72
+ 'Before you tell them someone has not replied (or has not written), read the conversation with vibe_thread: not every message is announced in this session.',
72
73
  'With a person marked "open line" in vibe_people, the two of them have agreed their agents may consult each other unattended: vibe_ask asks that person\'s agent a question from the work and waits for the answer; an arrival over an open line may be answered with vibe_answer when this session\'s work truly holds the answer. The tools refuse anyone without a line. Always tell the person afterwards what was asked and what was said.',
73
74
  'Once per teammate, a vibe_send result may end with a line suggesting the person open a line themselves (data.rapport_offer); show it as written, never run or suggest running trust on the person\'s behalf beyond that line, and never bring it up again.',
74
75
  'A person can leave a door: a link to the thing they are building, shared with people they know. vibe_people shows a door beside its owner. When the person asks to visit someone, call vibe_visit; it opens the link in their browser, sends nothing, and the owner is not told. Never visit unless the person asked. You cannot set or share a door; that is a terminal command the person types (npx slashvibe-mcp door).',
package/invite.js CHANGED
@@ -14,7 +14,10 @@
14
14
 
15
15
  'use strict';
16
16
 
17
+ const fs = require('fs');
18
+ const path = require('path');
17
19
  const reach = require('./reach');
20
+ const { vibeHome } = require('./vibe-home');
18
21
 
19
22
  const validHandle = (h) => /^[a-z0-9][a-z0-9_-]{1,38}$/.test(h);
20
23
 
@@ -122,4 +125,40 @@ function line(me) {
122
125
  return { command: `npx slashvibe-mcp setup --from @${h}`, link: `https://www.slashvibe.dev/join?from=${h}` };
123
126
  }
124
127
 
125
- module.exports = { fromArg, accept, line, lookup, resolveRecipient };
128
+ // ── the inviter's side ──────────────────────────────────────────────────────
129
+ // `setup --from @sam` marks Sam as known on the NEWCOMER's machine only. The
130
+ // platform is told nothing, so Sam's machine cannot know who accepted, and the
131
+ // newcomer's first message reaches Sam as one from "a person you have not
132
+ // written to" (lab 2026-11-20, p08 and p13). Until the platform can say who
133
+ // accepted an invite of yours, the one true thing this machine knows is WHEN
134
+ // it gave the person their invite line to pass on. The session-start line uses
135
+ // that, and only that: someone you have not written to who first wrote after
136
+ // that moment "may be someone you invited". It names nobody and quotes nothing.
137
+ const GIVEN_TTL_MS = 30 * 24 * 60 * 60 * 1000;
138
+ const givenFile = (env) => path.join(vibeHome(env), 'invite-given.json');
139
+
140
+ /** When this machine last started showing the person their invite line, or null. */
141
+ function givenAt(env = process.env, now = Date.now()) {
142
+ try {
143
+ const at = Number(JSON.parse(fs.readFileSync(givenFile(env), 'utf8')).at);
144
+ return Number.isFinite(at) && at > 0 && at <= now && now - at <= GIVEN_TTL_MS ? at : null;
145
+ } catch { return null; }
146
+ }
147
+
148
+ /**
149
+ * The person was shown their invite line. Keeps the EARLIEST moment that is
150
+ * still recent, so a line shown again does not hide someone who already came.
151
+ * Local, a timestamp only; never sent anywhere. Never throws.
152
+ */
153
+ function noteGiven(env = process.env, now = Date.now()) {
154
+ try {
155
+ if (givenAt(env, now) !== null) return;
156
+ const target = givenFile(env);
157
+ fs.mkdirSync(path.dirname(target), { recursive: true, mode: 0o700 });
158
+ const tmp = `${target}.${process.pid}.tmp`;
159
+ fs.writeFileSync(tmp, JSON.stringify({ at: now }), { mode: 0o600 });
160
+ fs.renameSync(tmp, target);
161
+ } catch {}
162
+ }
163
+
164
+ module.exports = { fromArg, accept, line, lookup, resolveRecipient, noteGiven, givenAt, GIVEN_TTL_MS };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "slashvibe-mcp",
3
- "version": "0.9.18",
3
+ "version": "0.9.19",
4
4
  "mcpName": "io.github.vibecodinginc/vibe",
5
5
  "description": "Telepathic messaging between people, from inside Claude Code",
6
6
  "main": "index.js",
@@ -70,6 +70,7 @@
70
70
  "store/api.js",
71
71
  "store/index.js",
72
72
  "store/local.js",
73
+ "turns.js",
73
74
  "tools/_shared.js",
74
75
  "tools/deliver.js",
75
76
  "tools/drafts.js",
@@ -158,9 +158,10 @@ function live() {
158
158
  const parsed = JSON.parse(stdout);
159
159
  // Only a count ever crosses from the reader to the presenter.
160
160
  const strangers = Number.isInteger(parsed && parsed.strangers) && parsed.strangers > 0 ? parsed.strangers : 0;
161
- return { messages: normalizeMessages(parsed), here: normalizeHere(parsed && parsed.here), doors: normalizeDoors(parsed && parsed.doors), strangers, signin: normalizeSignin(parsed && parsed.signin) };
161
+ const invited = Number.isInteger(parsed && parsed.invited) && parsed.invited > 0 ? Math.min(parsed.invited, strangers) : 0;
162
+ return { messages: normalizeMessages(parsed), here: normalizeHere(parsed && parsed.here), doors: normalizeDoors(parsed && parsed.doors), strangers, invited, signin: normalizeSignin(parsed && parsed.signin) };
162
163
  } catch {
163
- return { messages: [], here: [], doors: [], strangers: 0, signin: null };
164
+ return { messages: [], here: [], doors: [], strangers: 0, invited: 0, signin: null };
164
165
  }
165
166
  }
166
167
 
@@ -192,8 +193,9 @@ function normalizeDoors(value) {
192
193
  * Up to three things, each one line for the person and a short note for the
193
194
  * model: who is here, a door someone left, and messages that were waiting.
194
195
  */
195
- function hookOutput(messages, here = [], doors = [], strangers = 0, signin = null) {
196
+ function hookOutput(messages, here = [], doors = [], strangers = 0, signin = null, invited = 0) {
196
197
  const waitingUnknown = Number.isInteger(strangers) && strangers > 0 ? Math.min(strangers, 99) : 0;
198
+ const mayBeInvited = Number.isInteger(invited) && invited > 0 ? Math.min(invited, waitingUnknown) : 0;
197
199
  const signinNotice = signinLine(normalizeSignin(signin));
198
200
  if (messages.length === 0 && here.length === 0 && doors.length === 0 && waitingUnknown === 0 && !signinNotice) {
199
201
  emptyOutput();
@@ -232,8 +234,13 @@ function hookOutput(messages, here = [], doors = [], strangers = 0, signin = nul
232
234
  // in a session, so it carries nothing a stranger wrote.
233
235
  if (waitingUnknown > 0) {
234
236
  const who = waitingUnknown === 1 ? '1 person you have not written to is' : `${waitingUnknown} people you have not written to are`;
235
- shown.push(`/vibe · ${who} waiting. Say: what's waiting on /vibe`);
236
- context.push(`/vibe: ${who} waiting with a message. Who they are and what they wrote is deliberately not given here. The person has been shown this line. Do not open or read those conversations unless the person asks what is waiting.`);
237
+ // The inviter's side (invite.js): the platform does not say who accepted
238
+ // an invite, so this is said from timing alone, as a possibility, and
239
+ // still with no handle and none of their words.
240
+ const invitedNote = mayBeInvited === 0 ? ''
241
+ : ` ${mayBeInvited === waitingUnknown ? (waitingUnknown === 1 ? 'They' : 'They all') : `${mayBeInvited} of them`} first wrote after you were given your invite line, so it may be someone you invited.`;
242
+ shown.push(`/vibe · ${who} waiting.${invitedNote} Say: what's waiting on /vibe`);
243
+ context.push(`/vibe: ${who} waiting with a message.${invitedNote ? `${invitedNote} That is a guess from timing only: do not name or guess who.` : ''} Who they are and what they wrote is deliberately not given here. The person has been shown this line. Do not open or read those conversations unless the person asks what is waiting.`);
237
244
  }
238
245
 
239
246
  if (messages.length > 0) {
@@ -274,7 +281,7 @@ async function fetchLive() {
274
281
  const store = require('./store');
275
282
 
276
283
  authStore.hydrate();
277
- const none = { messages: [], here: [], doors: [], strangers: 0 };
284
+ const none = { messages: [], here: [], doors: [], strangers: 0, invited: 0 };
278
285
  const token = authStore.getToken();
279
286
  if (!token || !authStore.inspectToken(token).ok) return none;
280
287
 
@@ -292,6 +299,9 @@ async function fetchLive() {
292
299
  const rows = (await store.getRawInbox(verified.handle)).slice(0, 8);
293
300
  const kept = [];
294
301
  const unknown = new Set(); // senders they have never written to: counted, never shown
302
+ const invited = new Set(); // of those, ones who first wrote after this machine gave out an invite line
303
+ let given = null;
304
+ try { given = require('./invite').givenAt(); } catch {}
295
305
  for (const row of rows) {
296
306
  const from = row && row.from;
297
307
  if (!from || reach.isMuted(from)) continue;
@@ -308,6 +318,8 @@ async function fetchLive() {
308
318
  read = true;
309
319
  known = thread.some((m) => String(m.from || '').toLowerCase() === me);
310
320
  if (known) reach.know(from);
321
+ const first = Math.min(...thread.map((m) => Number(m.timestamp)).filter(Number.isFinite));
322
+ if (!known && given !== null && Number.isFinite(first) && first >= given) invited.add(String(from).toLowerCase());
311
323
  }
312
324
  } catch {}
313
325
  }
@@ -328,7 +340,7 @@ async function fetchLive() {
328
340
  try { door.note(row.from, text, row.id); } catch {}
329
341
  if (!card.closed && arrival.claim(row.id)) doors.push({ from: String(row.from).toLowerCase(), name: card.name || door.shortUrl(card.url) });
330
342
  }
331
- return { messages: normalizeMessages(messages), here: await fetchHere(store, me, reach, line), doors, strangers: unknown.size };
343
+ return { messages: normalizeMessages(messages), here: await fetchHere(store, me, reach, line), doors, strangers: unknown.size, invited: invited.size };
332
344
  }
333
345
 
334
346
  /** The people this person knows who are in a session now. A failed read is nobody, never a guess. */
@@ -355,9 +367,9 @@ async function main() {
355
367
  // Read before anything touches the network: it must survive the service
356
368
  // being unreachable, which is exactly when a person needs to be told.
357
369
  const signin = readSignin();
358
- const found = await fetchLive().catch(() => ({ messages: [], here: [], doors: [], strangers: 0 }));
370
+ const found = await fetchLive().catch(() => ({ messages: [], here: [], doors: [], strangers: 0, invited: 0 }));
359
371
  if (signin) markSigninShown();
360
- process.stdout.write(JSON.stringify({ messages: found.messages, here: found.here, doors: found.doors, strangers: found.strangers, signin }));
372
+ process.stdout.write(JSON.stringify({ messages: found.messages, here: found.here, doors: found.doors, strangers: found.strangers, invited: found.invited || 0, signin }));
361
373
  return;
362
374
  }
363
375
 
@@ -370,7 +382,25 @@ async function main() {
370
382
  const fixture = fixtureMessages(process.env.VIBE_SESSION_START_FIXTURE);
371
383
  if (fixture !== null) { hookOutput(fixture); return; }
372
384
  const now = live();
373
- hookOutput(now.messages, now.here, now.doors, now.strangers, now.signin);
385
+ hookOutput(now.messages, now.here, now.doors, now.strangers, now.signin, now.invited);
386
+ claimShown(now.messages);
387
+ }
388
+
389
+ /**
390
+ * A message this hook has just put in front of the person is theirs to have
391
+ * seen, so the arrival hook must not announce it again a moment later as
392
+ * "@x wrote you" (lab 2026-11-20: the same words twice in one turn, when a
393
+ * message landed in the minute before the session opened and the server took
394
+ * it for an arrival). The session-start line owns it: the same one-per-machine
395
+ * `.shown` claim the arrival presenters use, taken here only after the line
396
+ * was handed over, so a start that timed out claims nothing. It records no
397
+ * read state; another session that opens later still lists it as waiting.
398
+ */
399
+ function claimShown(messages) {
400
+ try {
401
+ const arrival = require('./arrival');
402
+ for (const m of messages || []) if (m && m.id) arrival.claim(m.id);
403
+ } catch {}
374
404
  }
375
405
 
376
406
  if (require.main === module) main().catch(emptyOutput);
package/setup.js CHANGED
@@ -520,6 +520,7 @@ async function setup() {
520
520
  }
521
521
  const bring = invite.line(authResult.handle);
522
522
  if (bring) {
523
+ invite.noteGiven();
523
524
  console.log(`${colors.bold} /vibe takes two. Send this to the person you build with:${colors.reset}`);
524
525
  console.log(`${colors.cyan} ${bring.command}${colors.reset}`);
525
526
  console.log(`${colors.dim} or the page: ${bring.link}${colors.reset}`);
package/store/api.js CHANGED
@@ -762,39 +762,23 @@ async function getRawInbox(handle) {
762
762
  // for compatibility with notification system
763
763
  const me = String(handle || '').toLowerCase();
764
764
  const isMine = (m) => String(m?.from || '').toLowerCase() === me;
765
- const candidates = threads.filter((t) => t.unread > 0 && t.last_message);
766
-
767
- // "Waiting" means THEIR words. When the newest message is mine — I replied
768
- // and their earlier message is still unread — the thread's last_message
769
- // is my own send, and presenting it as "MESSAGE from @me" told a person
770
- // their own words had arrived (Seth, 2026-09-02, the day of the invite).
771
- // For those threads read the TAIL of the thread (the API pages oldest-first)
772
- // and take the newest message of theirs. Bounded parallelism: the session-
773
- // start hook runs this under a 4s deadline (codex P2 ×2 on #38).
774
- const TAIL = 50;
775
- const resolveWaiting = async (thread) => {
776
- if (!isMine(thread.last_message)) return thread.last_message;
777
- try {
778
- const count = Number(thread.message_count);
779
- const offset = Number.isFinite(count) && count > TAIL ? count - TAIL : 0;
780
- const t = await request('GET', `/api/v2/threads/${encodeURIComponent(thread.id)}?limit=${TAIL}&offset=${offset}`);
781
- const theirs = (t.messages || []).filter((m) => !isMine(m));
782
- return theirs.length ? theirs[theirs.length - 1] : null;
783
- } catch {
784
- return null;
785
- }
786
- };
787
- const CONCURRENCY = 6;
788
- const resolved = new Array(candidates.length);
789
- let next = 0;
790
- await Promise.all(Array.from({ length: Math.min(CONCURRENCY, candidates.length) }, async () => {
791
- while (next < candidates.length) { const i = next++; resolved[i] = await resolveWaiting(candidates[i]); }
792
- }));
793
765
 
766
+ // "Waiting" means THEIR words, and only words nobody has answered yet.
767
+ // Replying does not mark anything read (seeing is not reading), so a
768
+ // conversation the person has answered can still hold an unread message
769
+ // of theirs. That message is not waiting: the newest word in the
770
+ // conversation is the person's own, however it was sent (a draft they
771
+ // approved, their agent over an open line, the terminal). Showing it as
772
+ // "1 message waiting" made the next session offer to answer it again
773
+ // (lab 2026-11-20, p01 in two runs). When they write again, their new
774
+ // message is the newest, and the conversation is waiting again.
775
+ // (Before this, the tail of the thread was read for their newest message,
776
+ // so the person's own reply was never shown as theirs: 2026-09-02.)
794
777
  const unreadMessages = [];
795
- candidates.forEach((thread, i) => {
796
- const waiting = resolved[i];
797
- if (!waiting) return; // nothing of theirs to show — not a waiting message
778
+ threads.forEach((thread) => {
779
+ if (!(thread.unread > 0) || !thread.last_message) return;
780
+ const waiting = thread.last_message;
781
+ if (isMine(waiting)) return; // answered: their word is not the last one
798
782
  unreadMessages.push({
799
783
  id: waiting.id,
800
784
  from: waiting.from,
package/tools/drafts.js CHANGED
@@ -19,6 +19,9 @@
19
19
  * never leave the machine.
20
20
  * - The approval is bound to bytes: Send names the rev of the preview the
21
21
  * person saw; a draft changed since is refused.
22
+ * - Seen, not just bound: Send goes only if the person has had a turn (a
23
+ * prompt, recorded by the arrival hook) after the rev was prepared, so an
24
+ * agent cannot prepare and send in one turn (turns.js).
22
25
  * - Exactly once: Send claims the draft under a whole-file lock, sends with
23
26
  * an idempotency key derived from the exact text, and finalizes against
24
27
  * the latest stored state. A draft whose delivery could not be confirmed
@@ -270,7 +273,7 @@ function compose(d) { return `${d.body || ''}${refLines(d.refs)}`; }
270
273
 
271
274
  const draftDefinition = {
272
275
  name: 'vibe_prepare',
273
- description: "Prepare a message to a person for review. Sends NOTHING. Use this whenever YOU wrote the words (from the work in this session, or as an answer to a message that arrived): pass handle + message, and reply_to when it answers a specific message. Returns the exact preview and the three choices: Send / Edit / Cancel. To edit, call again with the draft id and the new message. If the handle is not on /vibe yet, the preview says so and the message is held for that GitHub account instead.",
276
+ description: "Prepare a message to a person for review. Sends NOTHING. Use this whenever YOU wrote the words (from the work in this session, or as an answer to a message that arrived): pass handle + message, and reply_to when it answers a specific message. Returns the exact preview and the three choices: Send / Edit / Cancel. To edit, call again with the draft id and the new message. A changed draft must be shown again before it can be sent: show the person the new preview and wait for their next message. If the handle is not on /vibe yet, the preview says so and the message is held for that GitHub account instead.",
274
277
  inputSchema: {
275
278
  type: 'object',
276
279
  properties: {
@@ -399,6 +402,10 @@ async function draftHandler(args) {
399
402
  if (compose(d).length > 2000) return { display: `Not ready — the message is ${compose(d).length} chars and the limit is 2000. Edit it shorter; nothing was sent.` };
400
403
  // The first preview actually shown fixes the rev that "unchanged" is measured against.
401
404
  if (d.firstRev === null) d.firstRev = revOf(d);
405
+ // When THIS text was prepared: Send needs a person's turn after it (turns.js).
406
+ // Re-showing the same text keeps the time; any change, even back to an
407
+ // earlier text, starts it again.
408
+ stampRev(d);
402
409
  return { draft: { ...d } };
403
410
  });
404
411
  if (out.display) return out;
@@ -406,6 +413,16 @@ async function draftHandler(args) {
406
413
  return preview(out.draft, await findPerson(out.draft.to));
407
414
  }
408
415
 
416
+ function stampRev(d) {
417
+ const rev = revOf(d);
418
+ if (d.revFor !== rev || !Number.isFinite(d.revAt)) { d.revFor = rev; d.revAt = Date.now(); }
419
+ }
420
+ /** When the stored text was prepared. A draft from before revAt existed: its creation (or now, if edited since). */
421
+ function revPreparedAt(d) {
422
+ if (d.revFor === revOf(d) && Number.isFinite(d.revAt)) return d.revAt;
423
+ return d.edited ? Date.now() : (d.createdAt || Date.now());
424
+ }
425
+
409
426
  function heldPreview(d) {
410
427
  const att = d.refs && d.refs.length ? d.refs.map(r => `${r.title}: ${r.url}`).join('\n') : 'none';
411
428
  const message = compose(d);
@@ -470,7 +487,7 @@ async function discardHandler(args) {
470
487
 
471
488
  const sendDefinition = {
472
489
  name: 'vibe_send',
473
- description: "Send a prepared draft: pass id AND rev from the preview vibe_prepare showed. Call this only when the person chose Send; that choice is the approval, do not ask again. It sends exactly the previewed text, once. There is no other way to send: to write to someone, even in words the person dictated, open a draft with vibe_prepare first.",
490
+ description: "Send a prepared draft: pass id AND rev from the preview vibe_prepare showed. Call this only when the person chose Send; that choice is the approval, do not ask again. It sends exactly the previewed text, once. A changed draft must be shown again before it can be sent: a rev prepared after the person's last message is not sent, and the preview comes back to show them. There is no other way to send: to write to someone, even in words the person dictated, open a draft with vibe_prepare first.",
474
491
  inputSchema: {
475
492
  type: 'object',
476
493
  properties: {
@@ -479,7 +496,16 @@ const sendDefinition = {
479
496
  },
480
497
  },
481
498
  };
482
- async function sendHandler(args) {
499
+ /** The MCP tool: an agent's call. Sends only a rev the person has had a turn to see. */
500
+ async function sendHandler(args) { return send(args, { byPerson: false }); }
501
+ /**
502
+ * The person's own Send from a surface they act in directly (draft-cli: Buddy,
503
+ * or a terminal command they type). Their act IS the turn, so the turn check
504
+ * does not apply. Not reachable from a tool call: the MCP handler takes args only.
505
+ */
506
+ async function sendByPerson(args) { return send(args, { byPerson: true }); }
507
+
508
+ async function send(args, { byPerson }) {
483
509
  const initCheck = requireInit();
484
510
  if (initCheck) return initCheck;
485
511
  const id = args && args.id;
@@ -504,6 +530,7 @@ async function sendHandler(args) {
504
530
  // 1. Claim under the lock: nothing leaves the machine until this draft is
505
531
  // marked 'sending' with a key derived from the exact text — and the
506
532
  // text is the one the person SAW (rev), not one edited since (codex P1).
533
+ let turn = null;
507
534
  const claim = transact(drafts => {
508
535
  const d = drafts.find(x => x.id === id);
509
536
  if (!d) return { display: `No draft ${id} — nothing sent. Open it with vibe_prepare first.` };
@@ -529,6 +556,10 @@ async function sendHandler(args) {
529
556
  // honest options are to cancel (with the warning) or write anew.
530
557
  return { display: `Draft ${d.id}: the earlier Send to @${d.to} did not confirm, and this transport cannot deduplicate a retry. Cancel it (the earlier attempt may have reached them) and open a new draft if you still want to say it. Nothing sent.` };
531
558
  }
559
+ // The person must have had a turn since THIS text was prepared (turns.js):
560
+ // an agent cannot prepare a new rev and send it inside one turn.
561
+ turn = turnCheck(d, byPerson);
562
+ if (turn.check === 'needs_turn') return { unseen: { ...d } };
532
563
  d.status = 'sending'; d.claimedAt = Date.now(); d.claimedBy = process.pid;
533
564
  d.idempotencyKey = sendKey(d);
534
565
  const message = compose(d).trim();
@@ -538,8 +569,9 @@ async function sendHandler(args) {
538
569
  return { snapshot: { id: d.id, to: d.to, body: d.body, refs: d.refs, context: d.context, replyTo: d.replyTo || null, message, key: d.idempotencyKey, approvedSha256: d.approvedSha256, held: Boolean(d.held), unchanged } };
539
570
  });
540
571
  if (claim.display) return claim;
572
+ if (claim.unseen) return unseenRefusal(claim.unseen);
541
573
  const s = claim.snapshot;
542
- if (s.held) return keepHeld(s, me);
574
+ if (s.held) return withTurn(await keepHeld(s, me), turn);
543
575
 
544
576
  // 2. Deliver, outside the lock.
545
577
  let result;
@@ -578,7 +610,44 @@ async function sendHandler(args) {
578
610
  result = { ...result, display: `${result.display}\n\n_Draft ${s.id} is kept as unconfirmed: Send again retries exactly this text (delivers once), or Cancel._` };
579
611
  }
580
612
  if (sent) result = withRapport(result, s);
581
- return result;
613
+ return withTurn(result, turn);
614
+ }
615
+
616
+ /**
617
+ * Whether this send may go without a recorded person-turn, and why. Every case
618
+ * that sends without one is named here:
619
+ * by_person the person's own Send (draft-cli), not an agent's call;
620
+ * agent_identity an agent signed in as ITSELF sends in its own name: there is
621
+ * no person whose words these are;
622
+ * unavailable the arrival hook has never recorded a turn under this
623
+ * VIBE_HOME, or the host is not Claude Code (no hook there).
624
+ */
625
+ function turnCheck(d, byPerson) {
626
+ if (byPerson) return { check: 'by_person' };
627
+ try { if (require('../agent-auth').isAgent()) return { check: 'agent_identity' }; } catch {}
628
+ return require('../turns').judge(revPreparedAt(d));
629
+ }
630
+ function withTurn(result, turn) {
631
+ if (!result || !turn) return result;
632
+ return { ...result, data: { ...(result.data || {}), turn_check: turn.check } };
633
+ }
634
+ /**
635
+ * Not sent: this text was prepared after the person's last turn, so they have
636
+ * not seen it. Normal, not an error: the preview is shown again, and the next
637
+ * Send after their answer goes. Nothing reached the network on this path.
638
+ */
639
+ async function unseenRefusal(d) {
640
+ const changed = typeof d.firstRev === 'string' && d.firstRev !== revOf(d);
641
+ const p = d.held ? heldPreview(d) : preview(d, await findPerson(d.to));
642
+ const lead = changed
643
+ ? 'Not sent yet: the text changed, and the person has not seen this version. A changed draft must be shown again before it can be sent.'
644
+ : 'Not sent yet: the person has not seen this draft. A draft must be shown before it can be sent.';
645
+ const ask = `Show them the preview below exactly as it is and wait for their choice. If they choose ${d.held ? 'Keep' : 'Send'}, call vibe_send again with this id and rev.`;
646
+ return {
647
+ ...p,
648
+ display: `${lead} ${ask}\n\n${p.display}`,
649
+ data: { ...(p.data || {}), sent: false, definite: true, reason: changed ? 'changed_since_seen' : 'not_yet_seen', turn_check: 'needs_turn' },
650
+ };
582
651
  }
583
652
 
584
653
  /**
@@ -654,7 +723,7 @@ async function keepHeld(s, me) {
654
723
  `Held for @${s.to}. /vibe created the invitation.`,
655
724
  `**Join link:** ${joinUrl}`,
656
725
  ];
657
- if (pass) lines.push(`**Pass on with it:** ${pass.command}`);
726
+ if (pass) { lines.push(`**Pass on with it:** ${pass.command}`); invite.noteGiven(); }
658
727
  lines.push(`Your message is kept for the GitHub account ${s.to} for ${HELD_DAYS} days${until}. It arrives as your first message when they sign in to /vibe with that account; nothing reaches them before then.`);
659
728
 
660
729
  // Writing to someone is what lets their answer reach you mid-work. Their
@@ -719,6 +788,8 @@ module.exports = {
719
788
  vibe_prepare: { definition: draftDefinition, handler: draftHandler },
720
789
  vibe_send: { definition: sendDefinition, handler: sendHandler },
721
790
  vibe_discard: { definition: discardDefinition, handler: discardHandler },
791
+ // the person's own Send (draft-cli), never a tool
792
+ sendByPerson,
722
793
  // for the arrival path, the thread view, and Buddy's `vibe-draft` CLI
723
794
  isQaHandle, getReturnBinding, clearReturnBinding, loadDrafts, transact, DRAFTS_FILE, BINDINGS_FILE,
724
795
  compose, revOf, reconcileAbandoned,
package/tools/start.js CHANGED
@@ -93,7 +93,10 @@ async function handler(args = {}) {
93
93
  if (unreadSenders.length > 0) {
94
94
  display += '\n';
95
95
  unreadSenders.slice(0, 5).forEach((t) => {
96
- display += `\n@${cell(t.handle, 39)} (${t.unread})${t.lastMessageId ? ` · #${cell(t.lastMessageId, 40)}` : ''}`;
96
+ // Unread, and already answered: replying does not mark read, so say so
97
+ // rather than let it read as something still owed.
98
+ const answered = t.lastFrom && normalizeHandle(t.lastFrom) === me ? ' · you wrote last' : '';
99
+ display += `\n@${cell(t.handle, 39)} (${t.unread})${t.lastMessageId ? ` · #${cell(t.lastMessageId, 40)}` : ''}${answered}`;
97
100
  });
98
101
  if (unreadSenders.length > 5) display += `\n_+${unreadSenders.length - 5} more_`;
99
102
  } else if (inboxRead && threads.length === 0) {
@@ -105,6 +108,7 @@ async function handler(args = {}) {
105
108
  // waiting as "1 person you have not written to". Without a usable handle
106
109
  // the bare install still works; it just cannot name anyone.
107
110
  const bring = invite.line(myHandle);
111
+ if (bring) invite.noteGiven();
108
112
  display += `\n\nno conversations yet. /vibe takes two: send the person you work with this, then message them.\n ${bring ? bring.command : 'npx slashvibe-mcp setup'}`;
109
113
  }
110
114
 
package/turns.js ADDED
@@ -0,0 +1,104 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Turns — has the person had a turn since this exact text was prepared?
5
+ *
6
+ * The promise: nothing is sent unless the person saw the exact text and chose
7
+ * Send. The rev binds Send to bytes, but on its own it cannot tell whether the
8
+ * person ever SAW those bytes: an agent could prepare a new rev and send it in
9
+ * the same model turn ("send it, and add one line…" went out with a line the
10
+ * person never read). The one thing an agent cannot do from inside its turn is
11
+ * end that turn and have the person type. So:
12
+ *
13
+ * the arrival hook (hooks/arrival-hook.cjs) runs on every UserPromptSubmit
14
+ * and records "a person prompted at T" for the project, here, under
15
+ * <VIBE_HOME>/turns/<hash of the project directory>.json = {"at": T};
16
+ *
17
+ * vibe_send sends a rev only if a turn was recorded for this project
18
+ * strictly AFTER that rev was prepared.
19
+ *
20
+ * What is stored: a timestamp, in a file named by a hash of the directory.
21
+ * No prompt text, no path in clear, no session id. Mode 0600.
22
+ *
23
+ * The project is Claude Code's CLAUDE_PROJECT_DIR, which both the hook and the
24
+ * MCP server receive (checked in a live session: it stays the project root
25
+ * after the agent cd's into a subdirectory, while the hook's input `cwd`
26
+ * follows the cd). Without it, the hook falls back to its input cwd and the
27
+ * server to its own working directory, which Claude Code sets to the project
28
+ * root (also when the server is launched through npx). Both sides realpath the
29
+ * directory before hashing, so /tmp and /private/tmp are one project.
30
+ *
31
+ * The hook keeps its own copy of key() (it must load nothing); a test pins
32
+ * that the two agree.
33
+ */
34
+
35
+ const fs = require('fs');
36
+ const path = require('path');
37
+ const crypto = require('crypto');
38
+ const { vibeHome } = require('./vibe-home');
39
+
40
+ function turnsDir(env = process.env) {
41
+ return env.VIBE_TURNS_DIR || path.join(vibeHome(env), 'turns');
42
+ }
43
+
44
+ /** The file name for a project directory: sha256 of its realpath, 32 hex chars. */
45
+ function key(dir) {
46
+ let real = String(dir || '');
47
+ if (!real) return null;
48
+ try { real = fs.realpathSync(real); } catch { real = path.resolve(real); }
49
+ return crypto.createHash('sha256').update(real, 'utf8').digest('hex').slice(0, 32);
50
+ }
51
+
52
+ /** This server's project: what Claude Code says it is, else where it was started. */
53
+ function projectDir(env = process.env, cwd = process.cwd) {
54
+ const named = typeof env.CLAUDE_PROJECT_DIR === 'string' && env.CLAUDE_PROJECT_DIR.trim();
55
+ if (named) return named;
56
+ try { return cwd(); } catch { return null; }
57
+ }
58
+
59
+ /** Has the hook ever recorded a turn under this VIBE_HOME? */
60
+ function anyRecorded(env = process.env) {
61
+ try { return fs.readdirSync(turnsDir(env)).some((n) => /^[0-9a-f]{32}\.json$/.test(n)); } catch { return false; }
62
+ }
63
+
64
+ /** The last recorded person-turn for a project directory, or null. */
65
+ function lastTurn(dir, env = process.env) {
66
+ const k = key(dir);
67
+ if (!k) return null;
68
+ try {
69
+ const at = JSON.parse(fs.readFileSync(path.join(turnsDir(env), `${k}.json`), 'utf8')).at;
70
+ return Number.isFinite(at) ? at : null;
71
+ } catch { return null; }
72
+ }
73
+
74
+ /** Record a person-turn (the hook's job; here for tests and the lab). */
75
+ function record(dir, at = Date.now(), env = process.env) {
76
+ const k = key(dir);
77
+ if (!k) return false;
78
+ const d = turnsDir(env);
79
+ fs.mkdirSync(d, { recursive: true, mode: 0o700 });
80
+ const file = path.join(d, `${k}.json`);
81
+ const tmp = `${file}.${process.pid}.${crypto.randomBytes(3).toString('hex')}.tmp`;
82
+ fs.writeFileSync(tmp, JSON.stringify({ at }), { mode: 0o600 });
83
+ fs.renameSync(tmp, file);
84
+ return true;
85
+ }
86
+
87
+ /**
88
+ * May a revision prepared at `revAt` be sent now?
89
+ * { check: 'passed' } a turn for this project came strictly after it
90
+ * { check: 'needs_turn' } no turn since (or none at all for this project)
91
+ * { check: 'unavailable' } the hook has never recorded a turn here, or this
92
+ * host is not Claude Code: today's behaviour
93
+ * A turn in the same millisecond as the rev does not count as after it.
94
+ */
95
+ function judge(revAt, { env = process.env, cwd = process.cwd, host } = {}) {
96
+ const agent = host || (() => { try { return require('./host').getHost().agent; } catch { return null; } })();
97
+ if (agent !== 'claude-code') return { check: 'unavailable', why: 'host_without_turn_hook' };
98
+ if (!anyRecorded(env)) return { check: 'unavailable', why: 'no_turn_recorded' };
99
+ const at = lastTurn(projectDir(env, cwd), env);
100
+ if (at !== null && Number.isFinite(revAt) && at > revAt) return { check: 'passed' };
101
+ return { check: 'needs_turn' };
102
+ }
103
+
104
+ module.exports = { turnsDir, key, projectDir, anyRecorded, lastTurn, record, judge };