Skip to content

Commit 00a625d

Browse files
committed
social: claim an inbound event before delivering it (#2308)
Part of #2308. A message event gets a lease before its text is handed to the executor, and the outcome is kept as a terminal fact on the record: handed off is replied, a delivery that throws is failed after three attempts, and an owner-policy refusal is needs-human. The records live in the social plugin's own settings file, beside the cursors and seen; list_inbox still peeks and consumes no server cursor. Cross-host claiming and the server cursor are the second slice.
1 parent 26dce9b commit 00a625d

9 files changed

Lines changed: 599 additions & 6 deletions

File tree

‎core/src/host/hooks.js‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import { currentParticipants, isFaceRoom } from './room-membership.js'
2222
import { faceMentions, mentionedByHandle } from './face-mentions.js'
2323
import { FEED_EVENTS, installFeed } from './flybot-feed.js'
2424
import { createHandoff } from './handoff.js'
25+
import * as inbox from './inbox.js'
2526
import { createPluginModel } from './plugin-model.js'
2627
import { defineTool } from './tool-schema.js'
2728
import { retiredBot } from './store.js'
@@ -1274,6 +1275,11 @@ export function install(rt) {
12741275
// A sanctioned, capped model call for THIS plugin (#450): allow-listed by config, text only,
12751276
// no side effect. Resolves `{ ok: true, text }` or `{ ok: false, code }`.
12761277
model: { ask: input => modelAsk(plugin, input) },
1278+
// The inbound claim (#2308): the pure lease/state machine an inbound plugin keeps in its
1279+
// own settings, so two poll loops over one event deliver it once and a failed turn leaves
1280+
// a terminal fact. Shared through the API rather than imported: a plugin package cannot
1281+
// import `core/src/*`. The caller owns the record and the `now`; this module does no I/O.
1282+
inbox,
12771283
// True while a FlyBot window on screen reads the team (#497): a plugin that polls a remote inbox
12781284
// reads it at its live cadence then, so what arrives shows in that window within seconds.
12791285
watched: () => rt.watched?.() === true,

‎core/src/host/inbox.js‎

Lines changed: 224 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,224 @@
1+
// The inbound claim (#2308): one message event, one holder, one result.
2+
//
3+
// An inbound event used to be marked `seen` the moment it was handed to this host's
4+
// executor, so a second poll loop over the same server inbox — or a restart between the
5+
// delivery and the settings write — could answer it again, and a delivery that failed
6+
// after the mark left no fact behind. This module is the state machine that fixes that:
7+
// a caller takes a lease before it delivers, submits the result when the turn was handed
8+
// off, and records a failure instead of only moving the cursor. The record is plain JSON
9+
// the caller owns and persists; this module does no I/O, reads no clock (`now` is passed
10+
// in), and knows nothing about the transport, a Bot Social server or `settings`.
11+
//
12+
// The shape follows `claimQueued` / `expireLeases` in tasks.js on purpose: one holder, a
13+
// lease with an expiry, compare-and-set by lease id, and a transition that cannot run
14+
// twice. A settled record never hands out a lease again, so a late submit from a holder
15+
// whose lease expired is refused rather than rewriting a terminal result.
16+
//
17+
// pending → claimed → replied | failed | needs-human
18+
// ↑ |
19+
// └── expired (attempts + 1, or `failed` at ATTEMPTS_MAX)
20+
//
21+
// `replied`, `failed` and `needs-human` are terminal. The first slice keeps the claim on
22+
// one host: cross-host claiming (the server cursor) is the second slice, and the caller's
23+
// record is the seam it will use.
24+
25+
import { randomUUID } from 'node:crypto'
26+
27+
// A delivery that keeps failing stops being retried after this many attempts; the record
28+
// then says `failed`, a fact an operator can read, instead of a cursor that silently moved.
29+
export const ATTEMPTS_MAX = 3
30+
// Long enough for a slow executor hand-off, short enough that a host that died mid-delivery
31+
// offers the event again on its next poll.
32+
export const LEASE_TTL_MS = 5 * 60 * 1000
33+
34+
const TERMINAL = new Set(['replied', 'failed', 'needs-human'])
35+
const ERROR_MAX = 300
36+
37+
const invalid = message => Object.assign(new Error(message), { code: 'inbox/invalid' })
38+
const at = value => (Number.isFinite(value) ? value : Date.now())
39+
const oneLine = value => String(value ?? '').replace(/[\u0000-\u001f\u007f]/g, ' ').replace(/\s+/g, ' ').trim()
40+
const bounded = (value, max = ERROR_MAX) => oneLine(value).slice(0, max)
41+
42+
export const isTerminal = record => TERMINAL.has(record?.status)
43+
44+
// A fresh record for one event id. `eventId` is the caller's key (Bot Social's `event_id`);
45+
// the module only requires it to be a non-empty string so `view()` and errors can name it.
46+
export function createRecord(eventId, { now = Date.now() } = {}) {
47+
const id = oneLine(eventId)
48+
if (id === '') throw invalid('a record needs an event id')
49+
const stamp = at(now)
50+
return {
51+
eventId: id,
52+
status: 'pending',
53+
attempts: 0,
54+
lease: null,
55+
resultKey: undefined,
56+
result: undefined,
57+
error: undefined,
58+
reason: undefined,
59+
settled: undefined,
60+
createdAt: stamp,
61+
updatedAt: stamp,
62+
}
63+
}
64+
65+
// Take the event for `holder`. The read of the lease and the write of the new one happen in
66+
// one synchronous call, so two callers over the same record cannot both see `pending`:
67+
// the first gets `claimed`, the second `held` (the caller persists the record and the next
68+
// caller reads the lease). `outcome` is one of:
69+
// claimed — the lease is yours; deliver, then submit or fail
70+
// held — a live lease belongs to someone else; do not deliver, do not move a cursor
71+
// exhausted — the attempt budget was already spent; the record is `failed`
72+
// settled — a terminal record; never deliver again
73+
export function claim(record, { holder, now = Date.now(), ttlMs = LEASE_TTL_MS } = {}) {
74+
const who = oneLine(holder)
75+
if (who === '') throw invalid('claim needs a holder')
76+
const stamp = at(now)
77+
const ttl = Number.isFinite(ttlMs) && ttlMs > 0 ? ttlMs : LEASE_TTL_MS
78+
if (TERMINAL.has(record.status)) return { outcome: 'settled', status: record.status, record }
79+
if (record.status === 'claimed') {
80+
const lease = record.lease
81+
if (lease !== null && typeof lease === 'object' && Number.isFinite(lease.expiresAt) && lease.expiresAt > stamp) {
82+
return { outcome: 'held', heldBy: lease.holder, until: lease.expiresAt, lease, record }
83+
}
84+
// The holder is gone or stalled: count the attempt before offering the event again.
85+
// This is the one place the count moves on expiry, so a read cannot both requeue and
86+
// hand out two leases (the shape of tasks.js `expireLeases`).
87+
retire(record, stamp, 'the lease expired before the delivery reported a result')
88+
if (record.status === 'failed') return { outcome: 'exhausted', status: record.status, record }
89+
}
90+
if ((record.attempts ?? 0) >= ATTEMPTS_MAX) {
91+
record.status = 'failed'
92+
record.error ??= 'the delivery used every attempt'
93+
record.updatedAt = stamp
94+
return { outcome: 'exhausted', status: record.status, record }
95+
}
96+
const lease = { id: randomUUID(), holder: who, takenAt: stamp, expiresAt: stamp + ttl }
97+
record.status = 'claimed'
98+
record.lease = lease
99+
record.updatedAt = stamp
100+
return { outcome: 'claimed', lease, record }
101+
}
102+
103+
// Push a live lease's expiry out. A holder that is still working renews rather than letting
104+
// the event be offered to a second poll loop. A stale lease id, another holder or an expired
105+
// lease is refused; it never resurrects the claim.
106+
export function renew(record, { holder, leaseId, now = Date.now(), ttlMs = LEASE_TTL_MS } = {}) {
107+
const who = oneLine(holder)
108+
const stamp = at(now)
109+
const ttl = Number.isFinite(ttlMs) && ttlMs > 0 ? ttlMs : LEASE_TTL_MS
110+
if (record.status !== 'claimed') return { ok: false, reason: record.status === 'pending' ? 'not-claimed' : 'settled', record }
111+
const lease = record.lease
112+
if (lease === null || typeof lease !== 'object' || lease.id !== leaseId || lease.holder !== who) {
113+
return { ok: false, reason: 'stale-holder', record }
114+
}
115+
if (!Number.isFinite(lease.expiresAt) || lease.expiresAt <= stamp) return { ok: false, reason: 'expired', record }
116+
lease.expiresAt = stamp + ttl
117+
record.updatedAt = stamp
118+
return { ok: true, lease, record }
119+
}
120+
121+
// The turn was handed off: the event is answered. The first submit wins; the same holder
122+
// submitting the same result key again is a duplicate answer, not a second write. A submit
123+
// under a lease that is no longer current is refused and leaves the record alone, so a
124+
// holder that lost its lease cannot overwrite the new holder's result.
125+
export function submit(record, { holder, leaseId, resultKey, result, now = Date.now() } = {}) {
126+
const who = oneLine(holder)
127+
const stamp = at(now)
128+
if (record.status === 'replied' && record.settled?.leaseId === leaseId && record.resultKey === resultKey) {
129+
return { ok: true, duplicate: true, record }
130+
}
131+
if (TERMINAL.has(record.status)) return { ok: false, reason: 'settled', record }
132+
if (record.status !== 'claimed') return { ok: false, reason: 'not-claimed', record }
133+
const lease = record.lease
134+
if (lease === null || typeof lease !== 'object' || lease.id !== leaseId || lease.holder !== who) {
135+
return { ok: false, reason: 'stale-holder', record }
136+
}
137+
if (!Number.isFinite(lease.expiresAt) || lease.expiresAt <= stamp) return { ok: false, reason: 'expired', record }
138+
record.status = 'replied'
139+
record.resultKey = resultKey
140+
record.result = result
141+
record.error = undefined
142+
record.settled = { leaseId: lease.id, holder: who, at: stamp }
143+
record.lease = null
144+
record.updatedAt = stamp
145+
return { ok: true, duplicate: false, record }
146+
}
147+
148+
// The delivery failed while the lease was ours. The attempt is spent; at the budget the
149+
// record turns terminal instead of being retried forever. The holder is named in the error
150+
// only in the caller's text — the record carries the reason, not a stack.
151+
export function fail(record, { holder, leaseId, error, now = Date.now() } = {}) {
152+
const who = oneLine(holder)
153+
const stamp = at(now)
154+
if (TERMINAL.has(record.status)) return { ok: false, reason: 'settled', record }
155+
if (record.status === 'claimed') {
156+
const lease = record.lease
157+
if (lease === null || typeof lease !== 'object' || lease.id !== leaseId || lease.holder !== who) {
158+
return { ok: false, reason: 'stale-holder', record }
159+
}
160+
if (!Number.isFinite(lease.expiresAt) || lease.expiresAt <= stamp) return { ok: false, reason: 'expired', record }
161+
}
162+
record.attempts = (record.attempts ?? 0) + 1
163+
record.lease = null
164+
record.error = bounded(error?.message ?? error)
165+
record.status = record.attempts >= ATTEMPTS_MAX ? 'failed' : 'pending'
166+
record.updatedAt = stamp
167+
return { ok: true, status: record.status, attempts: record.attempts, record }
168+
}
169+
170+
// A person has to decide: no further attempt is spent automatically, and the reason is kept
171+
// for the surface that reads it. Terminal, like `failed`.
172+
export function needsHuman(record, { reason, now = Date.now() } = {}) {
173+
const stamp = at(now)
174+
if (TERMINAL.has(record.status)) return { ok: false, reason: 'settled', record }
175+
record.reason = bounded(reason)
176+
record.error = undefined
177+
record.lease = null
178+
record.status = 'needs-human'
179+
record.updatedAt = stamp
180+
return { ok: true, record }
181+
}
182+
183+
// A poll that finds a lease past its expiry offers the event again (or ends it at the budget).
184+
// Idempotent: a second call at the same time sees `pending`, not a second attempt.
185+
export function expire(record, { now = Date.now() } = {}) {
186+
const stamp = at(now)
187+
if (record.status !== 'claimed') return { expired: false, record }
188+
const lease = record.lease
189+
if (lease !== null && typeof lease === 'object' && Number.isFinite(lease.expiresAt) && lease.expiresAt > stamp) {
190+
return { expired: false, record }
191+
}
192+
retire(record, stamp, 'the lease expired before the delivery reported a result')
193+
return { expired: true, status: record.status, attempts: record.attempts, record }
194+
}
195+
196+
// The read-only shape a surface (or a test) gets: no lease ids to guess with, the holder and
197+
// the deadline named, and the terminal facts (`resultKey`, `result`, `error`, `reason`).
198+
export function view(record, { now = Date.now() } = {}) {
199+
if (record === undefined || record === null) return undefined
200+
const stamp = at(now)
201+
const lease = record.lease !== null && typeof record.lease === 'object' ? record.lease : undefined
202+
const live = lease !== undefined && Number.isFinite(lease.expiresAt) && lease.expiresAt > stamp
203+
return {
204+
id: record.eventId,
205+
status: record.status,
206+
attempts: record.attempts ?? 0,
207+
...(live ? { heldBy: lease.holder, until: lease.expiresAt } : {}),
208+
...(record.resultKey === undefined ? {} : { resultKey: record.resultKey }),
209+
...(record.result === undefined ? {} : { result: record.result }),
210+
...(record.error === undefined ? {} : { error: record.error }),
211+
...(record.reason === undefined ? {} : { reason: record.reason }),
212+
...(record.settled === undefined ? {} : { settled: record.settled }),
213+
updatedAt: record.updatedAt,
214+
}
215+
}
216+
217+
// One attempt spent on an expiry: clear the lease, count it, and end the record at the budget.
218+
function retire(record, stamp, why) {
219+
record.lease = null
220+
record.attempts = (record.attempts ?? 0) + 1
221+
record.error = record.error ?? bounded(why)
222+
record.status = record.attempts >= ATTEMPTS_MAX ? 'failed' : 'pending'
223+
record.updatedAt = stamp
224+
}

‎core/test/inbox-claim.test.js‎

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
// The inbound claim (#2308). The six cases the slice named: one lease at a time, an expired
2+
// lease is reclaimed and the old holder cannot submit, a duplicate submit is one result, a
3+
// delivery that keeps failing becomes terminal, `needs-human` is terminal, and a settled
4+
// record is never resurrected by an expiry. `now` is passed in, so no test waits on a clock.
5+
6+
import assert from 'node:assert/strict'
7+
import { test } from 'node:test'
8+
import { ATTEMPTS_MAX, LEASE_TTL_MS, claim, createRecord, expire, fail, needsHuman, renew, submit, view } from '../src/host/inbox.js'
9+
10+
const T0 = 1_800_000_000_000
11+
const HOLDER = 'host-a'
12+
13+
test('#2308: two claims, one message — the second is held', () => {
14+
const record = createRecord('ev1', { now: T0 })
15+
const first = claim(record, { holder: HOLDER, now: T0 })
16+
assert.equal(first.outcome, 'claimed')
17+
assert.equal(record.status, 'claimed')
18+
19+
const second = claim(record, { holder: 'host-b', now: T0 + 1000 })
20+
assert.equal(second.outcome, 'held')
21+
assert.equal(second.heldBy, HOLDER)
22+
assert.equal(second.until, T0 + LEASE_TTL_MS)
23+
assert.equal(record.lease.id, first.lease.id, 'the held claim does not replace the lease')
24+
assert.equal(record.attempts, 0)
25+
})
26+
27+
test('#2308: an expired lease is claimable and the old holder’s submit is refused', () => {
28+
const record = createRecord('ev2', { now: T0 })
29+
const first = claim(record, { holder: HOLDER, now: T0 })
30+
const later = T0 + LEASE_TTL_MS + 1
31+
32+
const second = claim(record, { holder: 'host-b', now: later })
33+
assert.equal(second.outcome, 'claimed')
34+
assert.notEqual(second.lease.id, first.lease.id)
35+
assert.equal(record.attempts, 1, 'the expiry spent one attempt')
36+
37+
const stale = submit(record, { holder: HOLDER, leaseId: first.lease.id, resultKey: 'ev2', result: { ok: true }, now: later + 1 })
38+
assert.deepEqual(stale, { ok: false, reason: 'stale-holder', record })
39+
assert.equal(record.status, 'claimed')
40+
assert.equal(record.lease.id, second.lease.id)
41+
42+
const ok = submit(record, { holder: 'host-b', leaseId: second.lease.id, resultKey: 'ev2', result: { ok: true }, now: later + 2 })
43+
assert.equal(ok.ok, true)
44+
assert.equal(record.status, 'replied')
45+
})
46+
47+
test('#2308: the same submit twice is one result', () => {
48+
const record = createRecord('ev3', { now: T0 })
49+
const held = claim(record, { holder: HOLDER, now: T0 })
50+
const args = { holder: HOLDER, leaseId: held.lease.id, resultKey: 'ev3', result: { turn: 't1' }, now: T0 + 10 }
51+
assert.equal(submit(record, args).ok, true)
52+
const afterFirst = { status: record.status, attempts: record.attempts, updatedAt: record.updatedAt, result: record.result }
53+
54+
const again = submit(record, { ...args, now: T0 + 1000 })
55+
assert.equal(again.ok, true)
56+
assert.equal(again.duplicate, true)
57+
assert.deepEqual({ status: record.status, attempts: record.attempts, updatedAt: record.updatedAt, result: record.result }, afterFirst)
58+
})
59+
60+
test('#2308: a message that keeps failing becomes terminal', () => {
61+
const record = createRecord('ev4', { now: T0 })
62+
for (let attempt = 1; attempt <= ATTEMPTS_MAX; attempt += 1) {
63+
const held = claim(record, { holder: HOLDER, now: T0 + attempt * 1000 })
64+
assert.equal(held.outcome, 'claimed')
65+
const failed = fail(record, { holder: HOLDER, leaseId: held.lease.id, error: new Error(`down ${attempt}`), now: T0 + attempt * 1000 + 1 })
66+
assert.equal(failed.ok, true)
67+
assert.equal(failed.attempts, attempt)
68+
assert.equal(record.status, attempt < ATTEMPTS_MAX ? 'pending' : 'failed')
69+
}
70+
assert.equal(record.error, `down ${ATTEMPTS_MAX}`)
71+
72+
const after = claim(record, { holder: 'host-b', now: T0 + 60_000 })
73+
assert.equal(after.outcome, 'settled')
74+
assert.equal(after.lease, undefined)
75+
assert.equal(record.status, 'failed')
76+
assert.equal(record.attempts, ATTEMPTS_MAX)
77+
})
78+
79+
test('#2308: needs-human is a terminal state', () => {
80+
const record = createRecord('ev5', { now: T0 })
81+
claim(record, { holder: HOLDER, now: T0 })
82+
const marked = needsHuman(record, { reason: 'the owner must decide whether to answer', now: T0 + 5 })
83+
assert.equal(marked.ok, true)
84+
assert.equal(record.status, 'needs-human')
85+
assert.equal(record.lease, null)
86+
87+
const after = claim(record, { holder: 'host-b', now: T0 + LEASE_TTL_MS + 1 })
88+
assert.equal(after.outcome, 'settled')
89+
assert.equal(view(record).reason, 'the owner must decide whether to answer')
90+
})
91+
92+
test('#2308: an expired lease does not resurrect a settled message', () => {
93+
const record = createRecord('ev6', { now: T0 })
94+
const held = claim(record, { holder: HOLDER, now: T0 })
95+
submit(record, { holder: HOLDER, leaseId: held.lease.id, resultKey: 'ev6', result: { turn: 't6' }, now: T0 + 5 })
96+
97+
const answered = expire(record, { now: T0 + LEASE_TTL_MS + 1 })
98+
assert.equal(answered.expired, false)
99+
assert.equal(record.status, 'replied')
100+
101+
const after = claim(record, { holder: 'host-b', now: T0 + LEASE_TTL_MS + 2 })
102+
assert.equal(after.outcome, 'settled')
103+
assert.equal(record.attempts, 0, 'a settled answer is not an attempt')
104+
assert.equal(record.result.turn, 't6')
105+
// renew is refused on a settled record, and on a lease that was replaced.
106+
assert.equal(renew(record, { holder: HOLDER, leaseId: held.lease.id, now: T0 + 6 }).reason, 'settled')
107+
})

0 commit comments

Comments
 (0)