slashvibe-mcp 0.9.18 → 0.9.20

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
@@ -212,12 +212,22 @@ npx slashvibe-mcp operate # the agents you are named on · renew @sol
212
212
 
213
213
  ## Who can reach you
214
214
 
215
- Only people you know reach you while you work: someone you have written to, or someone you
216
- opened a line with. Anyone else waits where `vibe start` lists what is waiting.
215
+ Only people you know reach you while you work: someone you have written to, someone you
216
+ opened a line with, or someone who joined /vibe with your invitation. Anyone else waits where
217
+ `vibe start` lists what is waiting.
218
+
219
+ Your invite line carries a code made on your account (`setup --from @you --invite VIBE-…`).
220
+ When the person you give it to signs in with it, /vibe records that they used your
221
+ invitation and tells you, and only you. Their first message then reaches you while you work,
222
+ marked "you invited them". A code works once. Whoever uses it is treated as someone you
223
+ invited, so give the line to the person you mean. `mute @them` undoes it.
217
224
 
218
225
  You are still told when that happens. When a session opens, one line says how many people
219
226
  you have not written to are waiting, and how to ask: `what's waiting on /vibe`. It says
220
227
  nothing about who they are or what they wrote, to you or to your agent, until you ask.
228
+ If one of them first wrote after you were given your invite line (`setup --from @you`), it
229
+ says it may be someone you invited: that is from timing on your machine alone, for an
230
+ invite line given without a code (an older line, or one made while /vibe could not be reached).
221
231
 
222
232
  ```bash
223
233
  npx slashvibe-mcp quiet # nothing surfaces until: unquiet
@@ -264,7 +274,10 @@ the line above, and `vibe_people` when you ask.
264
274
  ## What is promised
265
275
 
266
276
  - **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.
277
+ exact text you saw; a draft changed since is refused. A changed draft must be shown again
278
+ before it can be sent: in Claude Code, a draft prepared after your last message is not
279
+ sent until you have had a turn to see it (the arrival hook records that you typed, and
280
+ when; never what).
268
281
  - **Other people's words are data.** A message, or what someone says they are working on,
269
282
  is shown to you and never acted on.
270
283
  - **Arrival is presentation, not delivery.** The hook reads one local file, makes no
@@ -282,7 +295,9 @@ npx slashvibe-mcp hook uninstall
282
295
  ```
283
296
 
284
297
  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
298
+ message in at your next prompt or after the next tool call. A conversation you have answered
299
+ is not waiting, even while their message is still unread; it is waiting again when they
300
+ write again. Set `VIBE_ARRIVALS=off` in the
286
301
  server's env to turn arrival off.
287
302
 
288
303
  **Live push (optional, Claude Code research preview).** To have a message arrive while a
@@ -295,7 +310,7 @@ unless you always launch with it.
295
310
 
296
311
  ## Manual setup
297
312
 
298
- If you'd rather wire it yourself, add to `~/.claude.json` (or your host's MCP config):
313
+ If you'd rather wire it yourself, add to Claude Code's `~/.claude.json`:
299
314
 
300
315
  ```json
301
316
  {
package/arrival.js CHANGED
@@ -151,7 +151,7 @@ function render(item) {
151
151
  ];
152
152
  } else {
153
153
  lines = [
154
- `/vibe — ${who} just wrote to the person you are working with.`,
154
+ `/vibe — ${who} just wrote to the person you are working with.${item.invited ? ` They joined /vibe with the person's invitation, so this is someone they invited; it is their first message to reach them.` : ''}`,
155
155
  '',
156
156
  'What to do, in this order:',
157
157
  '1. Tell them now, in one line: who wrote, and quote what they said.',
@@ -177,7 +177,8 @@ function render(item) {
177
177
  // carry their own mark; anything else is simply something they wrote.
178
178
  const verb = lineOpen && line.isAgentAnswer(item.text) ? "'s agent answered"
179
179
  : (lineOpen && line.isAgentAsk(item.text) ? "'s agent asked over your open line" : ' wrote you');
180
- return { context, line: `/vibe · @${from}${verb}: "${inertField(text, 140)}"` };
180
+ const invited = item.invited && !lineOpen ? ' (you invited them)' : '';
181
+ return { context, line: `/vibe · @${from}${invited}${verb}: "${inertField(text, 140)}"` };
181
182
  }
182
183
 
183
184
  // ── the spool ───────────────────────────────────────────────────────────────
@@ -235,6 +236,9 @@ function record(threads, me, { since = 0, roster = [], bindingFor = null, env =
235
236
  at: Date.now(),
236
237
  // An open line with this person changes what the agent may do (line.js).
237
238
  line: line.isOpen(t.lastFrom, env),
239
+ // The platform said they redeemed this person's invitation, and that is
240
+ // what made them known just now (presence.js knownByInvite): said once.
241
+ invited: t.introducedByInvite === true,
238
242
  };
239
243
  if (item.line && line.isAgentAnswer(item.text)) {
240
244
  // What this side asked, so the answer is read beside its question.
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
 
@@ -115,11 +118,104 @@ async function accept(typed, me, opts = {}) {
115
118
  };
116
119
  }
117
120
 
121
+ // ── the invitation code ─────────────────────────────────────────────────────
122
+ // The line a person gives out carries an invitation code minted on THEIR
123
+ // account. The newcomer's sign-in redeems it (the platform records who created
124
+ // it and who used it, under its own lock), and from then on the inviter's
125
+ // inbox serves `invited_by_you` for that one person, so their first message
126
+ // reaches the inviter while they work instead of waiting as a stranger's.
127
+ // The code is only a key to the platform's own record: this machine never
128
+ // decides who invited whom, and a code the newcomer types cannot make them
129
+ // known to anyone the platform did not record.
130
+ const validCode = (c) => typeof c === 'string' && /^VIBE-[A-Z0-9]{2,16}(?:-[A-Z0-9]{1,16}){0,3}$/.test(c);
131
+
132
+ /** `--invite CODE` / `--invite=CODE` out of an argv. null when absent or malformed. */
133
+ function inviteArg(argv = process.argv) {
134
+ for (let i = 0; i < argv.length; i++) {
135
+ const a = String(argv[i]);
136
+ const v = a === '--invite' ? argv[i + 1] : (a.startsWith('--invite=') ? a.slice(9) : null);
137
+ if (v == null) continue;
138
+ const c = String(v).trim().toUpperCase();
139
+ return validCode(c) ? c : null;
140
+ }
141
+ return null;
142
+ }
143
+
144
+ const DAY_MS = 24 * 60 * 60 * 1000;
145
+
146
+ /**
147
+ * A code for this person's invite line: one of their own live, plain codes
148
+ * (not named for anyone, carrying no note or thought) with at least a day
149
+ * left, else a new one. At most one auto-made code is live at a time, so the
150
+ * three-code allowance is not spent by showing the line again. null on any
151
+ * failure: the line then goes out without a code, exactly as before.
152
+ */
153
+ async function codeFor(me, { store = require('./store'), now = Date.now() } = {}) {
154
+ try {
155
+ if (!validHandle(reach.norm(me))) return null;
156
+ if (!store || typeof store.listMyInvites !== 'function' || typeof store.createInvite !== 'function') return null;
157
+ const mine = await store.listMyInvites();
158
+ if (!mine || mine.success === false) return null;
159
+ const plain = (Array.isArray(mine.codes) ? mine.codes : []).find((c) => c && c.status === 'available' &&
160
+ !c.named_for && !c.for_email_hash && !c.carries_thought && validCode(String(c.code || '')) &&
161
+ Date.parse(c.expires_at) - now > DAY_MS);
162
+ if (plain) return String(plain.code);
163
+ if (mine.can_generate === false) return null;
164
+ const made = await store.createInvite({});
165
+ const code = made && made.success !== false ? String(made.code || '') : '';
166
+ return validCode(code) ? code : null;
167
+ } catch {
168
+ return null;
169
+ }
170
+ }
171
+
118
172
  /** What a person sends to whoever they build with. */
119
- function line(me) {
173
+ function line(me, code = null) {
120
174
  const h = reach.norm(me);
121
175
  if (!validHandle(h)) return null;
122
- return { command: `npx slashvibe-mcp setup --from @${h}`, link: `https://www.slashvibe.dev/join?from=${h}` };
176
+ const c = validCode(code) ? code : null;
177
+ return {
178
+ command: `npx slashvibe-mcp setup --from @${h}${c ? ` --invite ${c}` : ''}`,
179
+ link: `https://www.slashvibe.dev/join?from=${h}${c ? `&invite=${c}` : ''}`,
180
+ };
181
+ }
182
+
183
+ // ── the inviter's side ──────────────────────────────────────────────────────
184
+ // `setup --from @sam` marks Sam as known on the NEWCOMER's machine only. A line
185
+ // that also carries a code (`--invite`, codeFor above) lets the platform tell
186
+ // Sam who accepted (`invited_by_you`, presence.js). A line WITHOUT a code (an
187
+ // older line, or one made offline) tells the platform nothing, so Sam's
188
+ // machine cannot know who accepted, and the newcomer's first message reaches
189
+ // Sam as one from "a person you have not written to" (lab 2026-11-20, p08 and
190
+ // p13). For those, the one true thing this machine knows is WHEN it gave the
191
+ // person their invite line to pass on. The session-start line uses
192
+ // that, and only that: someone you have not written to who first wrote after
193
+ // that moment "may be someone you invited". It names nobody and quotes nothing.
194
+ const GIVEN_TTL_MS = 30 * 24 * 60 * 60 * 1000;
195
+ const givenFile = (env) => path.join(vibeHome(env), 'invite-given.json');
196
+
197
+ /** When this machine last started showing the person their invite line, or null. */
198
+ function givenAt(env = process.env, now = Date.now()) {
199
+ try {
200
+ const at = Number(JSON.parse(fs.readFileSync(givenFile(env), 'utf8')).at);
201
+ return Number.isFinite(at) && at > 0 && at <= now && now - at <= GIVEN_TTL_MS ? at : null;
202
+ } catch { return null; }
203
+ }
204
+
205
+ /**
206
+ * The person was shown their invite line. Keeps the EARLIEST moment that is
207
+ * still recent, so a line shown again does not hide someone who already came.
208
+ * Local, a timestamp only; never sent anywhere. Never throws.
209
+ */
210
+ function noteGiven(env = process.env, now = Date.now()) {
211
+ try {
212
+ if (givenAt(env, now) !== null) return;
213
+ const target = givenFile(env);
214
+ fs.mkdirSync(path.dirname(target), { recursive: true, mode: 0o700 });
215
+ const tmp = `${target}.${process.pid}.tmp`;
216
+ fs.writeFileSync(tmp, JSON.stringify({ at: now }), { mode: 0o600 });
217
+ fs.renameSync(tmp, target);
218
+ } catch {}
123
219
  }
124
220
 
125
- module.exports = { fromArg, accept, line, lookup, resolveRecipient };
221
+ module.exports = { fromArg, inviteArg, codeFor, validCode, accept, line, lookup, resolveRecipient, noteGiven, givenAt, GIVEN_TTL_MS };
package/oauth-callback.js CHANGED
@@ -194,6 +194,7 @@ function listen(server, port) {
194
194
  async function beginOAuth({
195
195
  requestedHandle,
196
196
  actorAware = false,
197
+ inviteCode = null,
197
198
  timeoutMs = DEFAULT_TIMEOUT_MS,
198
199
  graceMs = DEFAULT_GRACE_MS,
199
200
  } = {}) {
@@ -365,6 +366,10 @@ async function beginOAuth({
365
366
  loginUrl.searchParams.set('state', state);
366
367
  if (requestedHandle) loginUrl.searchParams.set('handle', requestedHandle);
367
368
  if (actorAware) loginUrl.searchParams.set('actor_aware', 'true');
369
+ // An invitation code from the line someone gave this person (setup --invite).
370
+ // The platform redeems it only for a newly created account, and only once;
371
+ // an older platform ignores it and sign-in is unchanged.
372
+ if (inviteCode && require('./invite').validCode(inviteCode)) loginUrl.searchParams.set('invite_code', inviteCode);
368
373
 
369
374
  timeoutTimer = setTimeout(() => {
370
375
  if (phase !== 'waiting' && phase !== 'waitingActor') return;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "slashvibe-mcp",
3
- "version": "0.9.18",
3
+ "version": "0.9.20",
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",
package/presence.js CHANGED
@@ -179,6 +179,23 @@ let waitingAtStart = null;
179
179
  const parked = new Map(); // sender (lowercase) -> { ids: Set, row }
180
180
  const lower = (h) => String(h || '').toLowerCase();
181
181
 
182
+ /**
183
+ * The platform says this person redeemed an invitation the person here gave
184
+ * out (`invited_by_you`, served for the caller only; absent on an older
185
+ * platform). That makes them someone the person knows, the same way writing to
186
+ * them does: marked in reach.json (so `mute` undoes it) and returned true.
187
+ * Only for a row that is theirs: the conversation's other person is the sender.
188
+ * Returns whether this call is what made them known, so the arrival can say
189
+ * "you invited them" once, the first time, and not on every message after.
190
+ */
191
+ function knownByInvite(t) {
192
+ if (!t || t.invitedByYou !== true || !t.lastFrom || lower(t.handle) !== lower(t.lastFrom)) return false;
193
+ if (reach.isMuted(t.lastFrom)) return false;
194
+ if (line.isOpen(t.lastFrom) || reach.isKnown(t.lastFrom)) return false;
195
+ reach.know(t.lastFrom);
196
+ return reach.isKnown(t.lastFrom);
197
+ }
198
+
182
199
  function park(t) {
183
200
  const h = lower(t.lastFrom);
184
201
  const e = parked.get(h) || { ids: new Set(), row: null };
@@ -204,7 +221,9 @@ const isParked = (id) => { for (const e of parked.values()) if (e.ids.has(id)) r
204
221
  function releaseParked(me, threads) {
205
222
  const extra = [];
206
223
  for (const [h, e] of parked) {
207
- if (!(line.isOpen(h) || reach.isKnown(h))) continue;
224
+ // Parked before the platform said they redeemed this person's invitation
225
+ // (a cached inbox, an older platform until now): that releases it too.
226
+ if (!(line.isOpen(h) || reach.isKnown(h)) && !knownByInvite(threads.find((t) => t && lower(t.handle) === h))) continue;
208
227
  const id = e.row.lastMessageId;
209
228
  if (reach.isMuted(h)) { for (const x of e.ids) waitingAtStart.add(x); parked.delete(h); continue; }
210
229
  const row = threads.find((t) => t && lower(t.handle) === h);
@@ -250,6 +269,9 @@ async function noteArrivals(handle, threads) {
250
269
  const unknown = arrival.pickArrivals(threads.filter((t) => waitingAtStart.has(t.lastMessageId) &&
251
270
  !reach.isMuted(t.lastFrom) && !line.isOpen(t.lastFrom) && !reach.isKnown(t.lastFrom)), handle);
252
271
  for (const t of unknown) {
272
+ // Someone they invited is known now; what they wrote stays waiting (the
273
+ // session-start line shows it), it is not parked.
274
+ if (knownByInvite(t)) continue;
253
275
  if (await knows(handle, t.lastFrom) === false) { waitingAtStart.delete(t.lastMessageId); park(t); }
254
276
  }
255
277
  }
@@ -267,6 +289,7 @@ async function noteArrivals(handle, threads) {
267
289
  const candidates = [];
268
290
  for (const t of wanted) {
269
291
  if (reach.isMuted(t.lastFrom)) { waitingAtStart.add(t.lastMessageId); continue; }
292
+ if (knownByInvite(t)) { t.introducedByInvite = true; candidates.push(t); continue; }
270
293
  const known = await knows(handle, t.lastFrom);
271
294
  if (known === true) candidates.push(t);
272
295
  else if (known === false) park(t);
@@ -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,9 +299,16 @@ 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
+ // The platform says they redeemed an invitation this person gave out
309
+ // (served for this person only; absent on an older platform): known, as
310
+ // if written to, and remembered so `mute` undoes it.
311
+ if (row.invitedByYou === true && !line.isOpen(from) && !reach.isKnown(from)) reach.know(from);
298
312
  let known = line.isOpen(from) || reach.isKnown(from);
299
313
  // "Never written to" is a claim about the conversation, so it is made only
300
314
  // when the conversation was actually read. A read that failed comes back
@@ -308,6 +322,8 @@ async function fetchLive() {
308
322
  read = true;
309
323
  known = thread.some((m) => String(m.from || '').toLowerCase() === me);
310
324
  if (known) reach.know(from);
325
+ const first = Math.min(...thread.map((m) => Number(m.timestamp)).filter(Number.isFinite));
326
+ if (!known && given !== null && Number.isFinite(first) && first >= given) invited.add(String(from).toLowerCase());
311
327
  }
312
328
  } catch {}
313
329
  }
@@ -328,7 +344,7 @@ async function fetchLive() {
328
344
  try { door.note(row.from, text, row.id); } catch {}
329
345
  if (!card.closed && arrival.claim(row.id)) doors.push({ from: String(row.from).toLowerCase(), name: card.name || door.shortUrl(card.url) });
330
346
  }
331
- return { messages: normalizeMessages(messages), here: await fetchHere(store, me, reach, line), doors, strangers: unknown.size };
347
+ return { messages: normalizeMessages(messages), here: await fetchHere(store, me, reach, line), doors, strangers: unknown.size, invited: invited.size };
332
348
  }
333
349
 
334
350
  /** The people this person knows who are in a session now. A failed read is nobody, never a guess. */
@@ -355,9 +371,9 @@ async function main() {
355
371
  // Read before anything touches the network: it must survive the service
356
372
  // being unreachable, which is exactly when a person needs to be told.
357
373
  const signin = readSignin();
358
- const found = await fetchLive().catch(() => ({ messages: [], here: [], doors: [], strangers: 0 }));
374
+ const found = await fetchLive().catch(() => ({ messages: [], here: [], doors: [], strangers: 0, invited: 0 }));
359
375
  if (signin) markSigninShown();
360
- process.stdout.write(JSON.stringify({ messages: found.messages, here: found.here, doors: found.doors, strangers: found.strangers, signin }));
376
+ process.stdout.write(JSON.stringify({ messages: found.messages, here: found.here, doors: found.doors, strangers: found.strangers, invited: found.invited || 0, signin }));
361
377
  return;
362
378
  }
363
379
 
@@ -370,7 +386,25 @@ async function main() {
370
386
  const fixture = fixtureMessages(process.env.VIBE_SESSION_START_FIXTURE);
371
387
  if (fixture !== null) { hookOutput(fixture); return; }
372
388
  const now = live();
373
- hookOutput(now.messages, now.here, now.doors, now.strangers, now.signin);
389
+ hookOutput(now.messages, now.here, now.doors, now.strangers, now.signin, now.invited);
390
+ claimShown(now.messages);
391
+ }
392
+
393
+ /**
394
+ * A message this hook has just put in front of the person is theirs to have
395
+ * seen, so the arrival hook must not announce it again a moment later as
396
+ * "@x wrote you" (lab 2026-11-20: the same words twice in one turn, when a
397
+ * message landed in the minute before the session opened and the server took
398
+ * it for an arrival). The session-start line owns it: the same one-per-machine
399
+ * `.shown` claim the arrival presenters use, taken here only after the line
400
+ * was handed over, so a start that timed out claims nothing. It records no
401
+ * read state; another session that opens later still lists it as waiting.
402
+ */
403
+ function claimShown(messages) {
404
+ try {
405
+ const arrival = require('./arrival');
406
+ for (const m of messages || []) if (m && m.id) arrival.claim(m.id);
407
+ } catch {}
374
408
  }
375
409
 
376
410
  if (require.main === module) main().catch(emptyOutput);
package/setup.js CHANGED
@@ -458,7 +458,7 @@ async function setup() {
458
458
  try {
459
459
  // The callback listener is bound before beginOAuth returns, so the browser
460
460
  // cannot race a listener that does not exist yet.
461
- oauth = await beginOAuth({ actorAware: true });
461
+ oauth = await beginOAuth({ actorAware: true, inviteCode: require('./invite').inviteArg() });
462
462
  openBrowser(oauth.loginUrl);
463
463
  console.log(`${colors.dim} → Waiting for authentication...${colors.reset}`);
464
464
  // Always say where to go. The browser may have opened on a screen nobody is
@@ -518,8 +518,11 @@ async function setup() {
518
518
  for (const l of got.lines) console.log(`${colors.dim} ${l}${colors.reset}`);
519
519
  if (got.lines.length) console.log('');
520
520
  }
521
- const bring = invite.line(authResult.handle);
521
+ // The line carries a code minted on this account, so whoever installs from
522
+ // it is someone this person knows once they sign in (invite.codeFor).
523
+ const bring = invite.line(authResult.handle, await invite.codeFor(authResult.handle));
522
524
  if (bring) {
525
+ invite.noteGiven();
523
526
  console.log(`${colors.bold} /vibe takes two. Send this to the person you build with:${colors.reset}`);
524
527
  console.log(`${colors.cyan} ${bring.command}${colors.reset}`);
525
528
  console.log(`${colors.dim} or the page: ${bring.link}${colors.reset}`);
package/store/api.js CHANGED
@@ -659,6 +659,9 @@ async function getInboxInner(handle) {
659
659
  // Drafting tools use it so an agent is never suggested as a person.
660
660
  lastActorKind: t.last_message?.actor?.kind || null,
661
661
  muted: t.preferences?.muted || false,
662
+ // Served for the caller only: this person redeemed an invitation the
663
+ // caller gave out. Absent on older platforms, which reads as false.
664
+ invitedByYou: t.invited_by_you === true,
662
665
  lastTimestamp: t.last_message?.created_at ? new Date(t.last_message.created_at).getTime() : null
663
666
  }));
664
667
  }
@@ -705,6 +708,7 @@ async function getInboxV1(handle) {
705
708
  // Actor metadata of the newest message, as served (#272: server-owned).
706
709
  // Drafting tools use it so an agent is never suggested as a person.
707
710
  lastActorKind: t.last_message?.actor?.kind || null,
711
+ invitedByYou: t.invited_by_you === true,
708
712
  lastTimestamp: t.last_message?.created_at ? new Date(t.last_message.created_at).getTime() : null
709
713
  }));
710
714
  }
@@ -762,39 +766,23 @@ async function getRawInbox(handle) {
762
766
  // for compatibility with notification system
763
767
  const me = String(handle || '').toLowerCase();
764
768
  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
769
 
770
+ // "Waiting" means THEIR words, and only words nobody has answered yet.
771
+ // Replying does not mark anything read (seeing is not reading), so a
772
+ // conversation the person has answered can still hold an unread message
773
+ // of theirs. That message is not waiting: the newest word in the
774
+ // conversation is the person's own, however it was sent (a draft they
775
+ // approved, their agent over an open line, the terminal). Showing it as
776
+ // "1 message waiting" made the next session offer to answer it again
777
+ // (lab 2026-11-20, p01 in two runs). When they write again, their new
778
+ // message is the newest, and the conversation is waiting again.
779
+ // (Before this, the tail of the thread was read for their newest message,
780
+ // so the person's own reply was never shown as theirs: 2026-09-02.)
794
781
  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
782
+ threads.forEach((thread) => {
783
+ if (!(thread.unread > 0) || !thread.last_message) return;
784
+ const waiting = thread.last_message;
785
+ if (isMine(waiting)) return; // answered: their word is not the last one
798
786
  unreadMessages.push({
799
787
  id: waiting.id,
800
788
  from: waiting.from,
@@ -805,6 +793,8 @@ async function getRawInbox(handle) {
805
793
  read: false, // If it's in unread threads, it's unread
806
794
  thread_id: thread.id,
807
795
  unread_count: thread.unread,
796
+ // The caller invited this person (served for the caller only; absent = false).
797
+ invitedByYou: thread.invited_by_you === true,
808
798
  });
809
799
  });
810
800
 
@@ -943,6 +933,11 @@ async function createInvite(body) {
943
933
  return request('POST', '/api/invites', body, { maxRetries: 0 });
944
934
  }
945
935
 
936
+ /** GET /api/invites/my — the person's own invitation codes (their credential only). */
937
+ async function listMyInvites() {
938
+ return request('GET', '/api/invites/my', null, { maxRetries: 0 });
939
+ }
940
+
946
941
  // ============ AUTH ============
947
942
 
948
943
  /**
@@ -1059,6 +1054,7 @@ module.exports = {
1059
1054
 
1060
1055
  // Invites (a held message for someone not on /vibe yet)
1061
1056
  createInvite,
1057
+ listMyInvites,
1062
1058
 
1063
1059
  // Hermetic request-count tests for the named-thread fast path.
1064
1060
  _testing: { getThreadWithRequest, markThreadReadWithRequest },
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) {
@@ -104,7 +107,8 @@ async function handler(args = {}) {
104
107
  // the message sent next reaches the friend while they work instead of
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
- const bring = invite.line(myHandle);
110
+ const bring = invite.line(myHandle, await invite.codeFor(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 };