Skip to content

feat(cli): commonly inbox — an operator's own attention queue (TASK-176) - #1985

Merged
lilyshen0722 merged 4 commits into
mainfrom
kai/task176-inbox
Sep 28, 2026
Merged

lilyshen0722 merged 4 commits into
mainfrom
kai/task176-inbox

Conversation

@lilyshen0722

@lilyshen0722 lilyshen0722 commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

TASK-176 — commonly inbox: one account's own attention queue, read from a token file and from nowhere else.

Why

The server side already existed. Operator accounts are human-class recipients, so the kernel materializes AttentionItems for them (recordMentionedUsers for mentions, the currentHumanMembers fan-out for decisions and handoffs). Measured on 2026-09-28 while building this: 550 open items for connector-ops, 485 for lily-shen, none of them ever read. What was missing was a consumer.

The reason the count stayed at zero is the second half of the row, and it is why this PR is mostly about identity: every host helper built on the CLI's saved login read Sam's queue, because the saved login on a shared operator host is Sam's. A queue you believe you are reading and are not is worse than no queue.

What ships

commonly inbox list | ack | choose.

list [--since <iso>] [--cursor-file <path>] [--kind <k>] [--pod <podId>] [--json] Pages /api/activity/decision-queue through hasMore; prints the account, a per-kind count line, one line per item and the next cursor.
ack <attentionItemId> POST /api/activity/:id/acknowledge.
choose <decisionId> <value> POST /api/activity/decisions/:id/choose.

A 429 from /api/activity — an ordinary busy signal on that route, see the residuals — is backed off on the server's Retry-After (capped at 60 s, twice, then reported).

Identity. The account comes from --token-file <path> (or COMMONLY_TOKEN_FILE) and from nowhere else. With neither set the command refuses before it makes a request; it never falls back to the saved login or to COMMONLY_TOKEN. Every run prints the resolved account on its first line, from GET /api/auth/user. A file holding an cm_agent_* token is refused by name — agent attention arrives as runtime events and there is no human queue behind that token (that half of the row is explicitly out of scope).

Two ids, labelled. An item has an attentionItemId (the AttentionItem row; acknowledgeAttention matches on _id and rejects a non-24-hex value) and id (the source row — the decision id for a card). list prints item=… and source=…, so neither command has to be discovered by failing first. The stopgap this replaces acked with the source id, which is a 400.

The cursor is a timestamp, not an offset. The queue's order moves as items are acknowledged (priority, then newest first), so an offset cursor would skip rows; createdAt never moves. --cursor-file reads it, prints only what is new and writes the advanced cursor back, so a watcher keeps no seen-list; --since wins over the file. An item whose createdAt cannot be parsed is KEPT under a cursor — dropping it would lose a row silently, and re-printing is the recoverable error.

Verification

Unit — cli/__tests__/inbox.test.mjs, 43 tests. The identity arms assert "no request was made" (fetchImpl is injected, so that is observable rather than inferred from a message), and the banner arm plants a saved login and COMMONLY_TOKEN and asserts every request carries the FILE's token.

Mutation ledger — 42 mutations, NO SURVIVORS (/tmp/kai-176-ledger.py, run asserting (suites, tests) = (1, 52) on every run so a suite that fails to load cannot read as a kill; each cell prints the failing-test count, because a mutant that throws and a mutant that is killed look identical in a pass/fail column). Mutations dropped the env fallback, the flag, the empty-file refusal, the cm_agent_ refusal, the JSON token form, the scrubber floor, the scrubber itself, the 401 and 429 hints, the unparseable-timestamp keep, the cursor fallback, the batch-length offset advance, the count guard, the kind filter and its validation, the kind fail-fast ordering, the pod scope, the cursor-file write, --since, --json, both ack arms and choose's body — and six built for this fix: the boundary clause, the delivered-id set, the carry-forward, the carry-when-moved, the id serialization and the id parse.

Three of them are the ones I would have missed without the ledger:

  • M6 — the scrubber's length floor. The first version scrubbed every occurrence of the token string, and with a one-character token it turned Attention item not found into A[redacted][redacted]en[redacted]ion …. A redactor whose needle is short mangles the message it is meant to clean. Real tokens are ≥ 32 chars; the floor is 16.
  • M15 — a needle written against a line that then changed. After the retry work I added sleep to the connect(...) call, and M15's needle (which moved --kind validation after the connect) stopped matching. The ledger reported applied: False instead of counting it killed — without that column the run would have shown a survivor that no code had ever produced. A ledger that cannot distinguish "the mutation did not apply" from "the mutation survived" is a ledger that invents findings.
  • M13 — the paging stops. The first mutation removed the count guard and the run never wrote a JSON report at all (the loop grew an array until the process died), which reads as "not killed" in a ledger that only checks for failures. The arm's mock now serves a finite second page, so the mutation fails cleanly. A mutation that hangs is not a mutation that is killed.

Regression sweep, measured against a clean base worktree of origin/main (bbab5c31):

suites tests failed skipped runtime errors
origin/main 51 972 0 10 0
this head 52 1021 0 10 0

(+1 suite, +43 tests — exactly this file. The first base run showed 2 failures; they were that worktree missing the symlinked backend/node_modules, and they disappeared when it was added — an instrument artefact, not a baseline.)

npx eslint src --ext .js exits 0.

Live, at the consumer (read-only, https://api.commonly.me, saved login on this host is Sam):

connector-ops file -> account: connector-ops @ https://api.commonly.me | count 550 | {mention 550}
lily file          -> account: lily-shen    @ https://api.commonly.me | count 485 | {approval 4, handoff 6, mention 475}
  • The saved login on this host is Sam; two different token files resolved two different accounts. That is the row's requirement, witnessed against the real instance rather than only in a mock.
  • Over 1035 live items: attentionItemId is 24-hex every time; id is source-shaped — a message number (74932) for a mention, <taskId>:<seq> for a task handoff, the bare decision id for a card. choose depends on the last of those; recordDecision sets sourceId from the DecisionRequest._id, and the queue's id is exactly that because attentionItemService.sourceKey(type, id) ignores its type argument and returns String(id).trim().
  • --since <cursor> printed the 2 items newer than a cursor taken minutes earlier; --kind approval filtered 487 open items to the 2 approvals.
  • --cursor-file round trip: run A wrote 2026-09-28T04:06:17.373Z; a minute later, with the queue at 488, run B printed (no items newer than 2026-09-28T04:06:17.373Z) and left the cursor unchanged.
  • ack 000000000000000000000000 (a non-existent id — no real item is mutated by this check) returned Attention item not found plus the hint naming attentionItemId.

Residuals, named

  • list reads the WHOLE queue, and the limiter it reads through is shared. One request per 50 items, so 550 open items is 11 requests. /api/activity is limited to 60 requests a minute keyed on the caller's IP (backend/routes/activity.ts:43-53, cloudflareIpRateLimitKeyGenerator, applied with router.use to the whole router, answering {code:'rate_limited'} with standardHeaders), so the budget is shared by every session on one host and by the operator's own browser — a watcher tick and a human opening their Activity page draw on the same 60. That is what I hit live, and the first version of this command made it worse: a bare HTTP 429 (the body's field is code, not error/message, so the detail fell through) cannot be told apart from a dead token. Now: the server's code is reported, the limiter is named as IP-keyed, and the read backs off and retries.
    The underlying cost is not fixed by the backoff: a cursor narrows what is PRINTED, not what is READ — the route accepts podId/messageIds/limit/offset and has no created-since filter, so every run pages the whole queue. A since/updatedSince parameter would collapse a watcher's tick to one page and is the change that actually matters here — follow-up, kernel-side, not this row. Cost is stated in --help and in the docs rather than left for an operator to discover from a 429.
  • No ack --all, deliberately. A bulk ack shares that same per-IP minute with the human's browser: 571 acks paced at 20 a minute is half an hour of somebody else's budget. A single ack <id> is one request, so there is no unpaced loop in this PR; the right answer for a backlog is a bulk route taking ids[] in one request, which is kernel-side.
  • The cursor boundary is a millisecond, and it is exclusive. Items that share the newest delivered millisecond are all delivered in the same run (the filter is ms > since), so the case that can be missed is an item created at exactly T that ARRIVES after the run which set the cursor to T. A watcher that must not miss it can keep ids from --json, or hold the cursor a millisecond behind. Chosen over >=, which would re-print the newest item on every tick until somebody acknowledged it.
  • Doc prose has no automated witness. The docs/cli/README.md section and the help text are read by humans only; the two registration/help arms cover the flags and the identity sentence, not the prose around them.
    The millisecond boundary (Vera's HOLD on the first gated head). An item that shares the cursor's millisecond and was inserted after the cursor was written was never printed — not that run, and not any later one, because the cursor cannot move past a millisecond it already passed. Reproduced on the gated head and again on this one, three runs each, same entry points:
GATED 26f14657 — ms > since
  run 1 printed X    run 2 printed Z (the control)   run 3 printed nothing
  => Y ever printed? false
HEAD — timestamp + ids delivered at it
  run 1 printed X    run 2 printed Y,Z               run 3 printed nothing
  => Y ever printed? true     X re-printed in run 2? false

The cursor is therefore the timestamp plus the ids delivered at exactly that timestamp, and the filter is ms > sinceMs || (ms === sinceMs && !delivered.has(id)): a boundary item already delivered is not re-printed, and one that was not is not lost. Those ids are dropped when the timestamp moves — the check needs ms === sinceMs, so a stale id could never match again — and that reset is asserted, not incidental. A bare ISO timestamp (what older versions wrote, and what the printed cursor: line shows) still parses, with an empty id set: it re-prints its millisecond instead of dropping it, which is the direction filterItems already picks for an unparseable createdAt. --since is consequently inclusive of its own millisecond, named in the arm and in docs/cli/README.md rather than left as an aside.

The second HOLD: a cursor is valid only for the query that wrote it

Vera's re-gate on the boundary fix found a second silent loss on the same cursor, pre-existing and reachable with two flags the README invites together:

run1 --kind mention printed ['m-new']   cursor advanced to m-new's millisecond
run2 no --kind        printed ['d-new']
=> d-old, a decision one minute older, is never printed by either run

nextCursorFrom is fed the FILTERED list, so a kind-filtered read advances the high-water mark past items of every other kind — items that read never printed, and that no later read can reach because the mark has already moved beyond them.

The rule, now on the module header: a resume cursor is valid only for the query that wrote it. Both cursor bugs here are that rule — the first was the millisecond axis of the query, this is the kind axis — and the fix for one did not cover the other, because I had only accounted for the axis I had been shown.

The fix implements the rule rather than policing the flags. A cursor file now records which --kind wrote it ({"at":…,"ids":[…],"kind":"mention"}; kind appears only when there is one, so an unfiltered cursor keeps the exact shape it had), and a read whose filter differs from the file's refuses before it connects — it does not even cost the identity request. One cursor file per kind is the remedy and the message names the file's own kind.

This is deliberately not the literal one-line refusal of --kind + --cursor-file: that combination is the remedy the refusal's own message names, so the two cannot both be right. Recording the kind keeps a single-kind watcher possible and refuses exactly the read that would lose rows.

Only one direction is refused. A cursor written without --kind, read by a --kind read, is allowed — that earlier read printed every kind, so nothing sits behind the mark unprinted. Refusing there would be a false positive, and the arm for it is what keeps this from being a check that fires on any mismatch.

Residual, stated in the README too: a row whose createdAt is older than a timestamp this command has already advanced past (a backdated insert, or clock skew between writers) is still invisible to a cursor. The fix belongs on the server as a created-since filter on the route (TASK-177), which is also what makes a watcher tick one request instead of a full scan.

  • cli/__tests__/*.mjs is outside the CI lint glob (eslint src --ext .js), so the new test file is covered by jest only. Disclosed, not claimed.
  • --json carries the account as a field instead of a first line: the spec's "first line" is a text-mode promise, and a bare account line in front of a JSON document would break every parser. Text mode prints it first.
  • An explicit decision id from --json is the same value as the line's source=, so choose works from either.

Gate

Vera. cli 0.1.79 → 0.1.80 (cli/src moved, so the version guard requires it; no other open PR is on 0.1.80).

The server side already existed. Operator accounts are human-class recipients,
so the kernel materializes AttentionItems for them — 550 open for connector-ops
and 485 for lily-shen on 2026-09-28, none of them ever read. What was missing was
a consumer, and every host helper built on the CLI's saved login read SAM's
queue, because the saved login on a shared operator host is Sam's.

`commonly inbox list | ack | choose`:

- The account comes from `--token-file <path>` (or COMMONLY_TOKEN_FILE) and from
  nowhere else. With neither set the command refuses BEFORE it makes a request;
  it never falls back to the saved login or to COMMONLY_TOKEN. Every run prints
  the resolved account on its first line, from GET /api/auth/user.
- `list` pages /api/activity/decision-queue through hasMore and prints both ids
  an item has: `item=` (attentionItemId, what `ack` takes) and `source=` (the
  source row, the decision id for a card, what `choose` takes).
- The cursor is an ISO-8601 timestamp compared against createdAt, not an offset:
  the queue's ORDER moves as items are acknowledged (priority, then newest
  first), so an offset cursor would skip rows. `--cursor-file` reads it, prints
  only what is new and writes the advanced cursor back, so a watcher keeps no
  seen-list; an explicit `--since` wins over the file.
- A file holding an `cm_agent_*` token is refused by name — agent attention
  arrives as runtime events, and there is no human queue behind that token.
- A 401 names the token FILE and never says "run commonly login"; a 429 says the
  session limiter answered, because a bare "HTTP 429" cannot be told apart from
  a dead token.

cli 0.1.79 → 0.1.80 (`cli/src` moved).
…ASK-176)

Live verification found the limiter, and the first version handled it wrongly.
/api/activity is limited to 60 requests a minute KEYED ON THE CALLER IP
(routes/activity.ts:43-53), so the budget is shared by every session on a host
and by the operator's own browser, and it answers {code:'rate_limited'} with
standardHeaders — which the error path did not read, because it looked for
error/message/msg and fell through to a bare `HTTP 429` that cannot be told
apart from a dead token.

- Report the server's `code`, and name the limiter as IP-keyed and shared.
- Back off on `Retry-After` (capped at 60s, twice) and continue; report only
  when the budget is still gone after the retries.
- `ack` ships without `--all`, deliberately: a burst of acks draws on the same
  per-IP minute the human's browser uses, so a bulk `ids[]` route is the answer
  and an unpaced loop is not shipped here.
… boundary cannot skip a row (TASK-176)

Vera's HOLD, reproduced before it was fixed: an item that shares the cursor's
millisecond and was inserted AFTER the cursor was written is never printed. Not
that run, and not any later run — the cursor cannot move past a millisecond it
already passed, so `ms > sinceMs` drops it silently and forever. For a queue
whose whole problem is 576 open items that nobody ever read, that is the one
outcome worth a guard.

Measured on the gated head and on this one, same three-run sequence:

  GATED 26f1465 — ms > since
    run 1 printed X      run 2 printed Z (the control)   run 3 printed nothing
    => Y ever printed? false
  HEAD — timestamp + ids delivered at it
    run 1 printed X      run 2 printed Y,Z               run 3 printed nothing
    => Y ever printed? true    X re-printed in run 2? false

The fix is Vera's option A: the cursor is the timestamp PLUS the ids delivered at
exactly that timestamp, and the filter is

  ms > sinceMs || (ms === sinceMs && !delivered.has(id))

so a boundary item already delivered is not re-printed and one that was not is
not lost. The ids are dropped when the timestamp moves, because the check needs
`ms === sinceMs` and stale ids could never match again. A bare ISO timestamp —
what older versions wrote, and what an operator copies off the `cursor:` line —
still parses, with an EMPTY id set: that degrades to re-printing the millisecond,
which is the direction this module already picked for an unparseable `createdAt`.

`--since` is therefore inclusive of its own millisecond, stated in the arm name
and in docs/cli/README.md rather than left as an aside.

Residual, named in the README: a row backdated behind a timestamp already
advanced past is still invisible to a cursor; that fix is a created-since filter
on the route (TASK-177).

49 tests (+6), 37 ledger mutations no survivors, full cli suite 52/1021/0 failed.
…different filter refuses (TASK-176)

Vera's second HOLD, reproduced before it was fixed. A cursor file shared with
`--kind` loses every item of the other kinds, permanently:

  run1 --kind mention printed ['m-new']   cursor advanced to m-new's millisecond
  run2 no --kind        printed ['d-new']
  => d-old, a decision one minute older, is never printed by either run

`nextCursorFrom` is fed the FILTERED list, so a kind-filtered read advances the
high-water mark past items of every other kind — which that read never printed,
and which no later read can reach because the mark has already moved beyond them.
Pre-existing rather than caused by the millisecond fix, but reachable with two
flags the README invites together and nothing warned about.

Her rule is the right general form, and it is on the module header now: **a resume
cursor is valid only for the query that wrote it.** Both bugs on this cursor are
that rule: the first HOLD was the millisecond axis of the query, this is the kind
axis, and the fix for one did not cover the other because I had only accounted
for the axis I had been shown.

The fix implements the rule instead of policing the flags. A cursor file now
records the `--kind` filter that wrote it (`{"at":…,"ids":[…],"kind":"mention"}`;
`kind` is written only when there IS one, so an unfiltered cursor keeps the exact
shape it had), and a read whose filter differs from the file's refuses BEFORE it
connects — so it costs not even the identity request. One cursor file per kind is
the remedy and the message names the file's own kind.

This is deliberately not Vera's literal one-line refusal of `--kind` +
`--cursor-file`: that combination is the remedy her own message names, so the
refusal and its fix cannot both be right. Recording the kind keeps a single-kind
watcher possible and refuses exactly the read that would lose rows.

Only one direction is refused. A cursor written WITHOUT `--kind`, read by a
`--kind` read, is allowed: that earlier read printed every kind, so nothing sits
behind the mark unprinted. Refusing there would be a false positive, and the arm
for it is what keeps this from being a check that fires on any mismatch.

Tests (+3): the refusal arm (the file is written by a kind read, then read with no
filter and with another kind — both refused, no request made, the file's kind
named); the allowed direction (broad cursor, then a filtered read, request made);
and the per-kind contract the message points at, where an OLDER decision still
prints because it has its own cursor file. That third one passes before this
change too, so it is labelled a contract test rather than a fix-witness — with a
shared file it fails, which is the loss being prevented.
@lilyshen0722
lilyshen0722 added this pull request to the merge queue Sep 28, 2026
Merged via the queue into main with commit 67fc3c1 Sep 28, 2026
17 of 22 checks passed
lilyshen0722 added a commit to thantiklermcirony/commonly that referenced this pull request Oct 9, 2026
…-set counts, windowCount, nextSince (TASK-177) (Team-Commonly#1987)

* feat(attention): narrow the decision queue to a created-since instant (TASK-177)

An operator watcher asking "what is new since my last tick" had to page the whole
queue: `GET /api/activity/decision-queue` offered `podId`/`messageIds`/`limit`/
`offset` and nothing about time, so 550 open items was eleven requests per tick.
That is not a private cost — `/api/activity` is limited to 60 requests a minute
keyed on the client IP, shared with every other session on the host and with the
person's own Activity page, so a watcher tick spent somebody else's budget every
time. Measured live on 2026-09-28 by tripping the 429 while reading a real
operator queue (TASK-176).

A client cannot solve this by looking at page contents: the queue is ordered
priority-then-`createdAt` desc, so a page that appears entirely older than the
cursor can still be followed by rows the cursor should see — an old mention sorts
into a later priority bucket than a fresh approval. The narrowing has to be
server-side.

`since` is INCLUSIVE of its own millisecond (`createdAt >= since`), which is a
deliberate departure from the "exclusive on createdAt" shape the follow-up task
described, and the CLI's own cursor is the reason: a cursor written at T cannot
know about a row INSERTED at T after it was written, so an exclusive bound would
drop that row from every later read — silently and for good. This is the exact
failure TASK-176's cursor had to fix one layer up (Vera's HOLD on Team-Commonly#1985:
`ms > sinceMs` lost the boundary row permanently). A caller re-printing a row it
already has is recoverable; never seeing it is not, so the bound rounds toward
visibility and the client's cursor id-set does the dedup.

The bound is applied to the QUERY — before supersession, membership, the counts
and pagination all run — so `count`, `countsByKind`, `countsByPod`, `remaining`
and `hasMore` describe the narrowed view. A narrowed list reporting a count that
contradicts its rows is worse than a slow query, and the pod scope already
follows exactly this rule for exactly this reason. The query also rides the
existing `{recipientUserId, status, createdAt}` index.

An unreadable value: the route refuses it with a 400 rather than reading the
whole queue, because a caller that asked to narrow and silently received
everything cannot tell that its bound was ignored. The service, as the second
line, treats an unusable bound as narrowing nothing — that direction can only
return a superset, never hide a row, which is how a malformed `podId` is already
treated beside it.

Not included, deliberately: `updatedSince`. Rows leave this queue when resolved,
so a modified-since bound would report work that is no longer waiting on anyone
while the created-since bound is what a watcher's cursor actually needs. No
consumer exists, and an unused parameter is a shape to maintain for nothing.

Tests (+5): the boundary row is kept and only older rows drop, with a control one
millisecond past it; every count is asserted for the narrowed view, including
`remaining`/`hasMore` where a filter applied after the slice would differ; a bound
is accepted as a `Date` or a string, and an unusable one narrows nothing rather
than emptying the queue; the route forwards the millisecond of the instant, and
refuses values it cannot read (including a repeated parameter, which arrives as
an array and parses fine as a string). Ledger 9 mutations, no survivors.

* feat(attention): rework the created-since bound to the amended spec — whole-set counts, windowCount, nextSince (TASK-177)

The row's spec was amended while this PR was open (connector-ops 177, after Wren's
probe): `since` on `createdAt`, INCLUSIVE, on the EXISTING index with no new index,
and the counts do NOT narrow — a filtered call adds `windowCount` (rows in the
window) and `nextSince` (the newest instant delivered), with pagination inside the
window. My first cut narrowed `count`/`countsByKind`/`countsByPod`/`remaining` with
the bound, which is the shape the ruling rejects: an Activity badge or any caller
that passes no bound must read exactly what it read before.

Why the spec moved, and what it settles. Vera argued for `updatedSince` on the
grounds that a late insert carries a fresh `updatedAt`; Wren measured that no writer
in this codebase produces that shape — every row comes from one `$setOnInsert`
upsert through `recordForRecipients`, mongoose stamps `createdAt` and `updatedAt`
from one `now`, and the source's own time lives in a separate `sourceCreatedAt`. So
no column choice closes the gap; a lookback window does, and it needs only the
`createdAt` index that already exists. Vera then conceded with the same mechanism.

What changed:
- The query reads the whole open set again (it has to: the counts are whole-set) and
  the window is applied in JS after the counts and before the slice.
- `windowCount` and `nextSince` are on the response for EVERY caller, not only a
  bounded one, so a consumer can read them unconditionally; `windowCount === count`
  when no bound is given. `nextSince` is the max `createdAt` over the page that was
  DELIVERED, not over the window — a caller resumes from it, and a value it has not
  seen must not be skipped past.
- `offset`/`limit`/`remaining`/`hasMore` page INSIDE the window. The ruling lists
  `remaining` among the whole-set numbers and also says pagination applies within the
  window; those cannot both hold, since rows outside the window are never delivered
  and a whole-set `remaining` could never be worked off. I took the reading that
  terminates and flagged it on the row rather than guessing silently.
- The route comment pins the inclusivity and states the residual honestly: an
  arrival more than W behind a cursor already passed is missed, so W must exceed
  write-commit latency, not clock skew. Not backdating, and not closed.

Tests are rewritten for the shape (+3 arms, 6 total in the file): the page narrows
while every count stays whole-set; an EMPTY window still reports the total count and
`countsByKind`; pagination reaches `remaining: 0` inside the window while `count`
stays 4; `nextSince` is asserted with a ONE-row page, where window-max and delivered-
max differ; a second row on the boundary instant, ticked from the `nextSince` the
first tick returned, must come back (this is the arm an exclusive bound dies on); and
a lookback that includes a near row and excludes a far one, with a control behind it.
Rows are placed in time with explicit `createdAt`; nothing asserts that a BACKDATED
row survives a bound, per the ruling's caution that no writer produces that shape.

* test(attention): shorten one arm name to fit the lint line budget (TASK-177)

* fix(attention): refuse a since bound that is not the ISO form it must be (TASK-177)

* docs(attention): the since bound does not touch the index, and stamp order is not commit order (TASK-177)

* docs(attention): the route comment carried the same false clause the service comment did (TASK-177)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant