@joe-broadhead/opencode-mem 0.12.3 → 0.12.5

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/CHANGELOG.md CHANGED
@@ -3,6 +3,91 @@
3
3
  The format follows Keep a Changelog 1.1.0: one `## [x.y.z] - date` section per
4
4
  release.
5
5
 
6
+ ## [0.12.5] - 2026-11-18
7
+
8
+ ### Fixed
9
+
10
+ - A host-bound source (`history`) is collected on its own machine again. 0.12.4 compared the binding's account with
11
+ the raw host name, so a machine whose name differed from the account only by case or a `.local` suffix left its own
12
+ history alone. The plugin's own probe, run on this machine, now decides; without an answer, the account and the host
13
+ name are compared the way the plugin writes them (lowercase, no `.local`, punctuation as `-`).
14
+ - A bind request learns its account from the plugin. The probe is called without naming an account, so a plugin
15
+ signed in under a real account name, such as a code host's login or a tracker's workspace user, reports it instead of
16
+ refusing `default` with `ACCOUNT_MISMATCH`. A structured "read as" answer is adopted; a real `default` stays `default`.
17
+ - The daily routine sends each model call only the context linked to its units: the people and projects among the
18
+ units' actors or named in their text, and at most 10 current memories and the open commitments linked to them. At a
19
+ large space's sizes, a call's fixed part falls from about 11,000 to about 700 tokens, so a day fits its budget.
20
+ Memories are ranked: those linked to the batch's entities first, then by the distinctive terms they share with the
21
+ batch's text, then by recency. Validation still refuses an id the model invents.
22
+ - Greetings and acknowledgements are noise. An event is noise only when its author is a bot, a service or an
23
+ automation: a bot elsewhere on an event, such as a meeting's notetaker or a notifications address in Cc, is ignored,
24
+ and the event's items are kept.
25
+ - An agent, bot or service actor never becomes a person page: by the role `agent`, by an `opencode-agent:` id, by a
26
+ declared kind, or by an OpenCode agent's name.
27
+ - A model answer cut off at the output cap keeps its complete items, instead of failing the whole batch.
28
+ - Lint skips an item a person forgot, and counts it, instead of failing the run.
29
+ - `RECORDS_ACTIONS_ENABLED` accepts any act the build registers, three-part names such as `space.joinRequest.decide`
30
+ included. An unknown name still fails startup.
31
+
32
+ ### Added
33
+
34
+ - The journal's summary says how many items the run dropped, already knew, rejected and found truncated, and how many
35
+ wait for review.
36
+ - `RECORDS_ROUTINE_BATCH_CHARS` and `RECORDS_ROUTINE_MAX_OUTPUT_TOKENS` set a call's data size and output cap. The
37
+ defaults are unchanged.
38
+ - `commitments.list` items carry `space` and `revision`, so a host can act on a listed commitment without reading it
39
+ again. An item stored without a version carries no `revision`, and the act reads the record's own.
40
+ - `memory.saveLine` saves a line from a conversation as a cited fact. It is the person's statement only when the
41
+ line's author is the person. The line and its citation are both checked for secrets and emails.
42
+
43
+ ### Deploy
44
+
45
+ The records service needs a deploy for the routine, act and list changes. No schema change and no migration.
46
+
47
+ ## [0.12.4] - 2026-11-18
48
+
49
+ ### Fixed
50
+
51
+ - X is collected once a day. Its reads are billed, so the owner's cadence policy now outranks both the
52
+ registry's own cadence and a plugin's declared `cadence.providerMinMinutes`, for a legacy binding
53
+ and a declared source alike.
54
+ - A failed collection no longer uses up its binding's cadence: a binding that fails is due again after
55
+ the shorter of its cadence and an hour. A successful binding keeps its cadence. Live at 22:37Z on
56
+ 2026-11-17, X failed and the next timer run skipped it as not due, which a daily cadence would have
57
+ stretched to a day.
58
+ - Memory reads the plugin list OpenCode actually answers: `ctx.plugin.list()` gives
59
+ `{ location, data: [...] }` on 2.2.6, not an array. Discovery and re-verification read only an array,
60
+ so they saw no plugin, published no declaration, and every bind fell back to the previous contract.
61
+ An answer that is neither shape is read as no list, with a warning.
62
+ - A configuration reload that leaves two instances in one process no longer leaves the surviving one
63
+ without the collector lease until its next 30-minute tick: an instance that is not the holder takes
64
+ a lease that is free at its next heartbeat, and collects what is due, so a reload does not read a
65
+ billed source whose cadence is not up.
66
+ - A run whose collector service was asked to stop writes no source status and reports nothing, so an
67
+ instance being disposed cannot mark every binding failing with its own missing plugin RPCs. An
68
+ `RPC is unavailable` answer is transient: the binding keeps its last good state, and the run says
69
+ retry next run.
70
+ - A collection's failure reads as one line of text with its code (`Why: AUTH_REQUIRED: the Slack
71
+ plugin is not signed in`), never `Why: [object Object]`. The placeholder came from a failure that
72
+ arrived as an object and met `String()`: at the records service, which stored it, and at the
73
+ console, which rendered it. Both now read a failure for its `code` and `message`, and the
74
+ collector reports its own failures with the code the contract's table named.
75
+ - A collector on another machine no longer marks a binding failing. Every report names the machine
76
+ that made it, and a binding's failing state stands only when the collector that last succeeded
77
+ for it is the one that failed; another machine's failure is kept beside the binding, named and
78
+ timed, and said on Sources without calling it failing. A pause from that machine is not applied
79
+ either. A machine started from a snapshot with the person's Memory sign-in and none of the
80
+ source's can no longer stop the machine that reads the source.
81
+ - A source whose account names the machine that reads it (`history`) is never read or reported by
82
+ a collector on another machine, so a guest cannot turn it failing.
83
+
84
+ ### Deploy
85
+
86
+ The records service needs a deploy before these reports are read as here: `sources.collected` and
87
+ `plugins.pause` take a `host`, and `source_collections` gains `host`, `elsewhere_host`,
88
+ `elsewhere_at` and `elsewhere_error`. Additive, with no migration: an older service ignores the
89
+ fields, and an older collector sends none, which keeps the previous rule.
90
+
6
91
  ## [0.12.3] - 2026-11-17
7
92
 
8
93
  ### Fixed
package/README.md CHANGED
@@ -590,7 +590,7 @@ machine collects every 30 minutes (`collect`, `collectEveryMinutes`,
590
590
  console as the next step), outside the person's own personal space, and for
591
591
  any account their own collector did not report.
592
592
  - **Cadence and setup.** Each source has its own cadence in the registry (X,
593
- which is billed, every 120 minutes). A bind passes on the source's own setup
593
+ which is billed, once a day). A bind passes on the source's own setup
594
594
  step: Slack needs its `events.channels` option, and X should have
595
595
  `"events": {"maxCalls": 2}` (and `ownsXApp` only if the account owns the app).
596
596
  - **Without routines, collection only buffers.** The records service's
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@joe-broadhead/opencode-mem",
3
- "version": "0.12.3",
3
+ "version": "0.12.5",
4
4
  "type": "module",
5
5
  "description": "Durable private and shared-space memory for OpenCode agents",
6
6
  "license": "MIT",
@@ -1174,7 +1174,8 @@
1174
1174
  "state",
1175
1175
  "when",
1176
1176
  "overdue",
1177
- "dueToday"
1177
+ "dueToday",
1178
+ "space"
1178
1179
  ],
1179
1180
  "properties": {
1180
1181
  "id": {
@@ -1219,6 +1220,14 @@
1219
1220
  "type": "string",
1220
1221
  "maxLength": 80
1221
1222
  },
1223
+ "space": {
1224
+ "type": "string",
1225
+ "maxLength": 128
1226
+ },
1227
+ "revision": {
1228
+ "type": "integer",
1229
+ "minimum": 1
1230
+ },
1222
1231
  "closed": {
1223
1232
  "type": "string",
1224
1233
  "maxLength": 40
@@ -7534,6 +7543,134 @@
7534
7543
  },
7535
7544
  "tool": "mem.revise"
7536
7545
  },
7546
+ {
7547
+ "name": "memory.saveLine",
7548
+ "label": "save a line to Memory",
7549
+ "target": "engine",
7550
+ "class": "chat",
7551
+ "confirm": "never",
7552
+ "views": [
7553
+ "memory"
7554
+ ],
7555
+ "done": "Saved.",
7556
+ "input": {
7557
+ "type": "object",
7558
+ "additionalProperties": false,
7559
+ "required": [
7560
+ "text",
7561
+ "from"
7562
+ ],
7563
+ "properties": {
7564
+ "text": {
7565
+ "type": "string",
7566
+ "maxLength": 4000
7567
+ },
7568
+ "from": {
7569
+ "type": "object",
7570
+ "additionalProperties": false,
7571
+ "required": [
7572
+ "conversation",
7573
+ "line"
7574
+ ],
7575
+ "properties": {
7576
+ "conversation": {
7577
+ "type": "string",
7578
+ "maxLength": 200
7579
+ },
7580
+ "line": {
7581
+ "type": "string",
7582
+ "maxLength": 200
7583
+ },
7584
+ "author": {
7585
+ "type": "string",
7586
+ "maxLength": 200
7587
+ },
7588
+ "at": {
7589
+ "type": "string",
7590
+ "maxLength": 40
7591
+ }
7592
+ }
7593
+ },
7594
+ "space": {
7595
+ "type": "string",
7596
+ "maxLength": 128
7597
+ },
7598
+ "jellySpeaker": {
7599
+ "type": "string"
7600
+ }
7601
+ }
7602
+ },
7603
+ "output": {
7604
+ "type": "object",
7605
+ "required": [
7606
+ "ok"
7607
+ ],
7608
+ "properties": {
7609
+ "ok": {
7610
+ "type": "boolean"
7611
+ },
7612
+ "id": {
7613
+ "type": "string",
7614
+ "maxLength": 200
7615
+ },
7616
+ "version": {
7617
+ "type": "integer",
7618
+ "minimum": 0
7619
+ },
7620
+ "state": {
7621
+ "type": "string",
7622
+ "maxLength": 40
7623
+ },
7624
+ "applied": {
7625
+ "type": "string",
7626
+ "maxLength": 200
7627
+ },
7628
+ "space": {
7629
+ "anyOf": [
7630
+ {
7631
+ "type": "string",
7632
+ "maxLength": 200
7633
+ },
7634
+ {
7635
+ "type": "object",
7636
+ "properties": {
7637
+ "id": {
7638
+ "type": "string",
7639
+ "maxLength": 200
7640
+ },
7641
+ "name": {
7642
+ "type": "string",
7643
+ "maxLength": 200
7644
+ }
7645
+ },
7646
+ "additionalProperties": false
7647
+ }
7648
+ ]
7649
+ },
7650
+ "count": {
7651
+ "type": "integer",
7652
+ "minimum": 0
7653
+ },
7654
+ "snapshot": {
7655
+ "type": "string",
7656
+ "maxLength": 64
7657
+ },
7658
+ "erased": {
7659
+ "type": "integer",
7660
+ "minimum": 0
7661
+ },
7662
+ "code": {
7663
+ "type": "string",
7664
+ "maxLength": 40
7665
+ },
7666
+ "message": {
7667
+ "type": "string",
7668
+ "maxLength": 600
7669
+ }
7670
+ }
7671
+ },
7672
+ "tool": "mem.remember"
7673
+ },
7537
7674
  {
7538
7675
  "name": "inbox.decide",
7539
7676
  "label": "decide what waits in your Inbox",
@@ -57,7 +57,7 @@ await tools.mem.spaces({ action: "sources", unbind: { source: "gmail", account:
57
57
 
58
58
  Collection runs with no model: every 30 minutes while OpenCode runs (one process
59
59
  per machine), and on Jelly a declared routine also wakes it. A billed source
60
- runs less often (X every 120 minutes). `spaces` `health` shows the last run,
60
+ runs less often (X, which is billed, once a day). `spaces` `health` shows the last run,
61
61
  each source's counts and errors, and whether **routines** run, with the model.
62
62
 
63
63
  **Collection without routines only buffers.** When health says `routines: off`,
package/src/actions.js CHANGED
@@ -107,7 +107,8 @@ export const HELD_FOR_CONTROL_P2 = Object.freeze(["share.transfer", "share.decid
107
107
  * The two acts built for Jelly's #77 and #78, now declared: Jelly 0.4.0-beta.20
108
108
  * carries protocol major 7 and caps a declaration at 48 actions, so 28 declared
109
109
  * plus the four for control's P2 plus these two are 34. Nothing was merged or
110
- * trimmed to make room. `memory.saveLine` is not built and is not declared here.
110
+ * trimmed to make room. `memory.saveLine` (#58 A14) is the thirty-fifth, built
111
+ * and declared here.
111
112
  */
112
113
  export const ACTIONS_NEED_ROOM = true
113
114
 
@@ -353,6 +354,36 @@ export const ACTIONS = Object.freeze([
353
354
  output: actionOutput,
354
355
  tool: "mem.revise",
355
356
  },
357
+ // A14: "Save to Memory" on one line of a Messages conversation. The click on
358
+ // the line is the whole confirmation (it adds to memory and removes nothing),
359
+ // so `chat` and `never`; the line's citation is required, because a memory
360
+ // the person cannot trace back is one they cannot check. It writes a `fact`
361
+ // and never a preference or a procedure: an instruction-shaped line must not
362
+ // come back as a rule.
363
+ {
364
+ name: "memory.saveLine",
365
+ label: "save a line to Memory",
366
+ target: "engine",
367
+ class: "chat",
368
+ confirm: "never",
369
+ views: ["memory"],
370
+ done: "Saved.",
371
+ input: actionInput(
372
+ {
373
+ text: text(4000),
374
+ from: {
375
+ type: "object",
376
+ additionalProperties: false,
377
+ required: ["conversation", "line"],
378
+ properties: { conversation: text(200), line: text(200), author: text(200), at: text(40) },
379
+ },
380
+ space: text(128),
381
+ },
382
+ ["text", "from"],
383
+ ),
384
+ output: actionOutput,
385
+ tool: "mem.remember",
386
+ },
356
387
  // The Inbox's own decision (Jelly's answers 2 and 6): Memory's key for the
357
388
  // item, the decisions the Inbox offers, and the version it showed. It routes
358
389
  // to the same review and held-write decisions a review makes.
@@ -852,6 +883,10 @@ const CODES = Object.freeze({
852
883
  invalid_id: "NOT_FOUND",
853
884
  team_delete_console_only: "NEEDS_APPROVAL",
854
885
  page_lines_kept: "NEEDS_APPROVAL",
886
+ // What may not be stored (#58 A14, and any act whose words records refuses):
887
+ // a secret, a person's email address, a home path; and text a person forgot.
888
+ refused: "NOT_STORED",
889
+ forgotten: "FORGOTTEN",
855
890
  })
856
891
 
857
892
  /** What this module refuses in its own words, and the code the page shows. */
@@ -1,9 +1,10 @@
1
1
  import fs from "node:fs"
2
+ import os from "node:os"
2
3
  import path from "node:path"
3
4
  import { DEFAULT_ACCOUNT, cadenceMs, collectSessionId, collectSessionRules, collectableSources, createCollector, hostBrokerTransport, hostSourceLister, hostSourceProber, rulesHash } from "./collector.js"
4
5
  import { createLease } from "./collector-lock.js"
5
6
  import { knownSources, sourceEntry } from "./sources.js"
6
- import { errorMessage, isPlainObject, oneLine } from "./util.js"
7
+ import { errorMessage, failureText, isPlainObject, oneLine } from "./util.js"
7
8
  import { recordsOf } from "./tools/share.js"
8
9
  import { unboundOwner } from "./backend/records.js"
9
10
 
@@ -18,7 +19,9 @@ export const CATCH_UP_RUNS = 10
18
19
  export const STARTUP_JITTER_MS = Object.freeze([10_000, 60_000])
19
20
  /** A source is due this long before its cadence is up, so a 30-minute timer does not skip a 30-minute source by a few seconds. */
20
21
  export const DUE_SLACK_MS = 60_000
21
- /** Triggers a person started: they collect every bound source, whatever its cadence. */
22
+ /** A binding whose last attempt failed is due again after the shorter of its cadence and this (0.12.4). */
23
+ export const RETRY_MS = 60 * 60_000
24
+ /** Triggers a person started: they collect every bound source, whatever its cadence. A take-over is not one: it is a startup run, and collects what is due. */
22
25
  const ASKED = new Set(["tool", "command", "request"])
23
26
 
24
27
  const REAL_CLOCK = Object.freeze({
@@ -46,7 +49,8 @@ const REAL_CLOCK = Object.freeze({
46
49
  * request (`mem_collect`, `/mem-collect`). `collect: false` (or
47
50
  * `MEMORY_COLLECT=0`) turns the timer off; a request still runs. A timer
48
51
  * run collects a source only when its own cadence is up (the registry's
49
- * `everyMinutes`: X every 120 minutes); a request collects every source.
52
+ * `everyMinutes`: X, which is billed, once a day); a request collects every
53
+ * source.
50
54
  * - **Bind requests:** each run first answers the person's bind requests
51
55
  * (`sources.list` `requests`): only for those sources, it reads the
52
56
  * signed-in account and reports it (`sources.report`) for the person to
@@ -71,7 +75,7 @@ const REAL_CLOCK = Object.freeze({
71
75
  * lease?: ReturnType<typeof createLease>,
72
76
  * }} input
73
77
  */
74
- export function createCollectorService({ ctx, runtime, toolkit, clock = REAL_CLOCK, random = Math.random, waitMs = COLLECT_WAIT_MS, lease }) {
78
+ export function createCollectorService({ ctx, runtime, toolkit, clock = REAL_CLOCK, random = Math.random, waitMs = COLLECT_WAIT_MS, lease, host = os.hostname() }) {
75
79
  const config = runtime.config
76
80
  const log = runtime.log
77
81
  const stateDir = config.stateDir
@@ -246,6 +250,7 @@ export function createCollectorService({ ctx, runtime, toolkit, clock = REAL_CLO
246
250
  const brokerState = { timedOut: false, embedded: new Set() }
247
251
  const collector = createCollector({
248
252
  scheduler: null,
253
+ host,
249
254
  lister: hostSourceLister(ctx, { broker: hostBrokerTransport(ctx, { state: brokerState }), brokerState }),
250
255
  prober: hostSourceProber(ctx),
251
256
  log,
@@ -263,6 +268,8 @@ export function createCollectorService({ ctx, runtime, toolkit, clock = REAL_CLO
263
268
 
264
269
  /** A run's refusal once the lease is another process's: it must not read, write or report as a holder. */
265
270
  const LOST = "another OpenCode process holds the collector lease now; this run stopped before writing more"
271
+ /** A run's refusal once the service was asked to stop: a reload disposed this instance, so its run writes nothing more. */
272
+ const STOPPING = "this collector service was asked to stop; the run stopped before writing more"
266
273
 
267
274
  function writeStatus(status) {
268
275
  try {
@@ -326,7 +333,7 @@ export function createCollectorService({ ctx, runtime, toolkit, clock = REAL_CLO
326
333
  * Start one collection unless one is running here, memory is unavailable, or
327
334
  * another process holds the lease. Returns at once.
328
335
  *
329
- * @param {"startup" | "timer" | "catch-up" | "request" | "tool" | "command"} trigger
336
+ * @param {"startup" | "timer" | "catch-up" | "takeover" | "request" | "tool" | "command"} trigger
330
337
  * @returns {Promise<{ started: true } | { running: true, since: string } | { skipped: string }>}
331
338
  */
332
339
  async function begin(trigger, { only, sessionID } = {}) {
@@ -382,6 +389,7 @@ export function createCollectorService({ ctx, runtime, toolkit, clock = REAL_CLO
382
389
  * taker) never writes as a holder — not even the run's first status line.
383
390
  */
384
391
  function guard() {
392
+ if (stopped) throw new Error(STOPPING)
385
393
  if (stillHolder()) return
386
394
  throw new Error(LOST)
387
395
  }
@@ -424,6 +432,7 @@ export function createCollectorService({ ctx, runtime, toolkit, clock = REAL_CLO
424
432
  const rpc = (binding) => {
425
433
  // Read nothing as a holder that has lost the lease (a machine that woke
426
434
  // after another process took over): the binding is reported, not read.
435
+ if (stopped) throw new Error(STOPPING)
427
436
  if (!stillHolder()) throw new Error(LOST)
428
437
  return rpcSession(null, binding)
429
438
  }
@@ -449,7 +458,15 @@ export function createCollectorService({ ctx, runtime, toolkit, clock = REAL_CLO
449
458
  // The reason is the source's own failure text and the store keeps it for
450
459
  // every process and the console to read: redacted here, where it is
451
460
  // stored, not only where it is shown (0.10.4's gate; review F1).
452
- pause: (binding, reason, code) => call("plugins.pause", { source: binding.source, account: binding.account, reason: oneLine(errorMessage(reason), 200), code }, where),
461
+ // `host` says which machine asked: a pause from one that is not the
462
+ // binding's collector is not applied (0.12.3), as its collection report
463
+ // does not turn the binding failing.
464
+ pause: (binding, reason, code) => {
465
+ // A run whose service was asked to stop pauses nothing: the instance is
466
+ // being disposed, and the store is not told what its dead RPCs said.
467
+ if (stopped) return Promise.resolve()
468
+ return call("plugins.pause", { source: binding.source, account: binding.account, reason: oneLine(errorMessage(reason), 200), code, host }, where)
469
+ },
453
470
  ingest: async (input) => {
454
471
  // And write nothing as one: the page never lands, and the run leaves the
455
472
  // status to the holder that has the lease.
@@ -476,12 +493,22 @@ export function createCollectorService({ ctx, runtime, toolkit, clock = REAL_CLO
476
493
  * report never fails the collection.
477
494
  */
478
495
  async function reportCollections(call, where, results) {
496
+ // A service asked to stop reports nothing: its run is the instance being
497
+ // disposed, and its plugin RPCs are already gone (0.12.4, live at 22:19Z on
498
+ // 2026-11-17), so every binding would be reported failing for the host's
499
+ // state rather than its own.
500
+ if (stopped) return
479
501
  for (const result of results) {
480
- if (result.notDue || typeof result.source !== "string") continue
502
+ if (stopped) return
503
+ // Not due, and another machine's binding, are not this run's reports.
504
+ if (result.notDue || result.otherHost || result.transient || typeof result.source !== "string") continue
481
505
  // `more` travels with the report (review S5): the console's Sources row says
482
506
  // "catching up" from records, so it must know the run left pages behind.
483
- const body = { source: result.source, account: result.account ?? "default", ok: !result.error, accepted: Number.isInteger(result.accepted) ? result.accepted : undefined, more: result.more === true }
484
- if (result.error) body.error = oneLine(errorMessage(result.error), 300)
507
+ // `host` is this machine: the records service shows a binding's failing
508
+ // state only for the collector that last succeeded for it, so a machine
509
+ // with no sign-in to the source cannot turn it failing (0.12.3).
510
+ const body = { source: result.source, account: result.account ?? "default", ok: !result.error, accepted: Number.isInteger(result.accepted) ? result.accepted : undefined, more: result.more === true, host }
511
+ if (result.error) body.error = reasonText(result, 300)
485
512
  try {
486
513
  await call("sources.collected", body, where)
487
514
  } catch (error) {
@@ -492,9 +519,14 @@ export function createCollectorService({ ctx, runtime, toolkit, clock = REAL_CLO
492
519
 
493
520
  function finish(trigger, started, results, error, none = false, { probes = [], collected } = {}) {
494
521
  const ended = clock.now()
495
- // When each binding was last attempted, for its cadence: kept across runs and processes in collector.json.
522
+ // The point each binding's cadence counts from, kept across runs and
523
+ // processes in collector.json. A success counts from the run's start; a
524
+ // failed attempt counts from earlier, so the binding is due again after the
525
+ // shorter of its cadence and an hour (0.12.4). A failure must not use up a
526
+ // billed source's day: live at 22:37Z on 2026-11-17, X failed, and the
527
+ // 22:49Z run skipped it as not due.
496
528
  const at = { ...(collected ?? (isPlainObject(readStatus()?.collected) ? readStatus().collected : {})) }
497
- for (const result of results) if (!result.notDue) at[keyOf(result)] = new Date(started).toISOString()
529
+ for (const result of results) if (!result.notDue && !result.otherHost) at[keyOf(result)] = new Date(cadencePoint(result, started)).toISOString()
498
530
  last = {
499
531
  state: error ? "failed" : "done",
500
532
  trigger,
@@ -508,9 +540,12 @@ export function createCollectorService({ ctx, runtime, toolkit, clock = REAL_CLO
508
540
  collected: at,
509
541
  }
510
542
  // A run writes no status as a holder unless the lock still proves it is
511
- // one: the check is made now, not only when the run first noticed.
512
- if (!leaseLost) stillHolder()
513
- if (leaseLost) log?.info?.("collection run stopped: the lease is another process's", { trigger })
543
+ // one: the check is made now, not only when the run first noticed. A
544
+ // service asked to stop writes none either: its run is the instance being
545
+ // disposed, and its state is not the machine's (0.12.4).
546
+ if (!stopped && !leaseLost) stillHolder()
547
+ if (stopped) log?.info?.("collection run stopped with the service; it wrote no status", { trigger })
548
+ else if (leaseLost) log?.info?.("collection run stopped: the lease is another process's", { trigger })
514
549
  else writeStatus(last)
515
550
  const behind = results.some((result) => result.more && !result.error)
516
551
  if (behind && catchUps < CATCH_UP_RUNS && !stopped) {
@@ -541,11 +576,27 @@ export function createCollectorService({ ctx, runtime, toolkit, clock = REAL_CLO
541
576
  /* already taken */
542
577
  }
543
578
  }
579
+ // The holder may have gone without its lease going stale: a configuration
580
+ // reload disposes one of two instances and its stop() releases the lease,
581
+ // and the survivor that skipped its startup run must not wait for its next
582
+ // interval tick (0.12.4, live at 22:19Z on 2026-11-17). Take a lease that
583
+ // is free now and collect once; the one-holder rule is the same acquire.
584
+ if (!leader && !active && !stopped && freeLease()) safely("takeover")
544
585
  } catch (error) {
545
586
  log?.warn?.("collector heartbeat failed", { error: errorMessage(error) })
546
587
  }
547
588
  }
548
589
 
590
+ /** True when no process holds the lease, or the one it names stopped beating: the next beat may take it. */
591
+ function freeLease() {
592
+ try {
593
+ const current = lock.holder()
594
+ return !current || lock.isStale(current)
595
+ } catch {
596
+ return false
597
+ }
598
+ }
599
+
549
600
  /** Start the timers. Returns at once; the first run comes after a short random wait. */
550
601
  function start() {
551
602
  if (!config.collect) {
@@ -697,6 +748,31 @@ function keyOf(row) {
697
748
  return `${row?.source ?? ""}\u0000${row?.account || DEFAULT_ACCOUNT}`
698
749
  }
699
750
 
751
+ /**
752
+ * The point a binding's cadence counts from after a run: the run's start, or
753
+ * for a failed attempt earlier by the part of the cadence beyond an hour, so the
754
+ * binding is due again after the shorter of its cadence and an hour. A billed
755
+ * source that fails is retried no more often than that, and a transient failure
756
+ * costs at most that (0.12.4).
757
+ */
758
+ function cadencePoint(result, started) {
759
+ if (!result.error) return started
760
+ const cadence = cadenceMs(result.source)
761
+ return started - (cadence - Math.min(cadence, RETRY_MS))
762
+ }
763
+
764
+ /**
765
+ * A result's reason as one line: `CODE: message` when the run kept the
766
+ * contract's code (`AUTH_REQUIRED` is a sign-in), else the message alone. A
767
+ * failure that arrived as an object reads as its own words; `String(object)`,
768
+ * which is `[object Object]`, is never what a person sees (0.12.3).
769
+ */
770
+ function reasonText(result, max = 300) {
771
+ const raw = result?.error
772
+ if (typeof raw === "string") return failureText({ code: result?.code, message: raw }, max)
773
+ return failureText(raw ?? result?.reason, max)
774
+ }
775
+
700
776
  /**
701
777
  * What the status file keeps of one result. The file is read by every process
702
778
  * and by the console, and it holds text a source or a plugin wrote — a
@@ -706,7 +782,7 @@ function keyOf(row) {
706
782
  */
707
783
  export function storedResult(result) {
708
784
  const kept = { ...result }
709
- if (kept.error) kept.error = oneLine(errorMessage(kept.error), 300)
785
+ if (kept.error) kept.error = reasonText(kept, 300)
710
786
  if (kept.refused_reason) kept.refused_reason = oneLine(errorMessage(kept.refused_reason), 200)
711
787
  if (kept.setup) kept.setup = oneLine(errorMessage(kept.setup), 400)
712
788
  if (kept.held) kept.held = oneLine(errorMessage(kept.held), 100)
@@ -729,6 +805,12 @@ export function describeProbe(probe) {
729
805
  /** One source's line: its counts, what it refused, and why it stopped. */
730
806
  export function describeResult(result) {
731
807
  if (result.notDue) return `${oneLine(result.source ?? "?", 40)}:${oneLine(result.account ?? "?", 80)}: not due (collected every ${Number(result.everyMinutes) || 30} minutes)`
808
+ // Another machine's host-bound binding (0.12.3): said, and not a failure.
809
+ if (result.otherHost) return `${oneLine(result.source ?? "?", 40)}:${oneLine(result.account ?? "?", 80)}: only ${oneLine(result.otherHost, 80)} collects it, so this machine leaves it alone`
810
+ // The plugin's RPC is not registered yet, or no longer (a reload): the host's
811
+ // state, not the binding's failure, so it is not called stopped and it keeps
812
+ // the state it had (0.12.4).
813
+ if (result.transient) return `${oneLine(result.source ?? "?", 40)}:${oneLine(result.account ?? "?", 80)}: ${oneLine(errorMessage(result.error ?? "the plugin's RPC is not available"), 240)}; retry next run`
732
814
  const counts = `${Number(result.accepted) || 0} new, ${Number(result.duplicates) || 0} already had, ${Number(result.refused) || 0} refused, ${Number(result.pages) || 0} page(s)`
733
815
  // A refused event is a real loss — the contract's cursor moves past it — so
734
816
  // the line names the newest one and why, not only how many (DESIGN §2.3.1).
@@ -741,5 +823,5 @@ export function describeResult(result) {
741
823
  // object, and the 0.10.3 gate (A15) caught an answer repeating the placeholder.
742
824
  // The refusal trace is build/0.11’s (fix/source-kinds): a refused event is a
743
825
  // real loss, so the line names the newest one and why.
744
- return `${name}: ${result.error ? `stopped (${oneLine(errorMessage(result.error), 240)}); ` : ""}${counts}${refused}${result.more ? "; more waits for the next run" : ""}${result.setup ? `; the source says: ${oneLine(errorMessage(result.setup), 240)}` : ""}`
826
+ return `${name}: ${result.error ? `stopped (${reasonText(result, 240)}); ` : ""}${counts}${refused}${result.more ? "; more waits for the next run" : ""}${result.setup ? `; the source says: ${oneLine(errorMessage(result.setup), 240)}` : ""}`
745
827
  }
package/src/collector.js CHANGED
@@ -1,10 +1,10 @@
1
1
  import { errorMessage, isPlainObject, oneLine } from "./util.js"
2
2
  import { createHash } from "node:crypto"
3
3
  import { isSourceName } from "./source-ids.js"
4
- import { ACCOUNT_NAME, DEFAULT_EVERY_MINUTES, contractRefusal, resolveDeclaredSource, rpcDefinition, sourceAllowRules, sourceEntry } from "./sources.js"
4
+ import { ACCOUNT_NAME, DEFAULT_EVERY_MINUTES, contractRefusal, hostBoundSource, resolveDeclaredSource, rpcDefinition, sourceAllowRules, sourceEntry } from "./sources.js"
5
5
  import { acceptAnswer, probe, read } from "./plugins/source-contract/vendor/read.js"
6
6
  import { isBrokerAnswer, sourceReader } from "./plugins/source-contract/vendor/broker-client.js"
7
- import { probeResultProblems } from "./plugins/source-contract/vendor/events.js"
7
+ import { canonicalCode, parseSourceError, probeResultProblems } from "./plugins/source-contract/vendor/events.js"
8
8
  import { cursorAdvance, failureAction, failureFromError } from "./plugins/source-contract/policy.js"
9
9
  import { memoryResourceAvailable } from "./credentials.js"
10
10
 
@@ -134,6 +134,25 @@ export function isAccountName(value) {
134
134
  return typeof value === "string" && ACCOUNT_NAME.test(value)
135
135
  }
136
136
 
137
+ /**
138
+ * The account a plugin's own structured refusal says to read as, or null. Only
139
+ * an `ACCOUNT_MISMATCH` source error whose own `next` (or `what`) says
140
+ * `read as "<account>"` names one: never free text that does not parse, and
141
+ * never another code (0.12.5).
142
+ *
143
+ * @param {unknown} error
144
+ * @returns {string | null}
145
+ */
146
+ export function suggestedAccount(error) {
147
+ const read = parseSourceError(error)
148
+ if (!read || (canonicalCode(read.code) ?? read.code) !== "ACCOUNT_MISMATCH") return null
149
+ for (const text of [read.next, read.what]) {
150
+ const match = /read as "([^"]{1,128})"/i.exec(String(text ?? ""))
151
+ if (match && isAccountName(match[1])) return match[1]
152
+ }
153
+ return null
154
+ }
155
+
137
156
  function bindingKey(binding) {
138
157
  return `${binding.source}\u0000${binding.account || DEFAULT_ACCOUNT}`
139
158
  }
@@ -165,6 +184,121 @@ export function collectableSources(sources, { only } = {}) {
165
184
  return [...seen.values()].sort((a, b) => bindingKey(a).localeCompare(bindingKey(b)))
166
185
  }
167
186
 
187
+ /**
188
+ * The name a plugin gives a machine: lowercase, without a trailing `.local`, and
189
+ * slugged — the history plugin's `identityOf` does
190
+ * `slug(host.replace(/\.local\.?$/i, ""), 63)`, so `Joes-MacBook-Air.local`
191
+ * names the account `joes-macbook-air` (0.12.4).
192
+ *
193
+ * @param {string | null | undefined} name
194
+ * @returns {string}
195
+ */
196
+ export function machineSlug(name) {
197
+ return String(name ?? "")
198
+ .trim()
199
+ .toLowerCase()
200
+ .replace(/\.local\.?$/, "")
201
+ .replace(/[^a-z0-9]+/g, "-")
202
+ .replace(/^-+|-+$/g, "")
203
+ .slice(0, 63)
204
+ }
205
+
206
+ /**
207
+ * The machine a host-bound binding belongs to, when it is not this one, or
208
+ * null. A host-bound source's account names the machine whose own files it
209
+ * reads (src/sources.js `hostBoundSource`): another machine's collector never
210
+ * reads it, and never reports on it, so it cannot turn the binding failing
211
+ * (0.12.3).
212
+ *
213
+ * **Names are compared the way the plugin names them** (0.12.4): a case or
214
+ * `.local` difference is never another machine. Live at 00:14Z on 2026-11-18,
215
+ * the owner's own `history:joes-macbook-air` was left alone on
216
+ * `Joes-MacBook-Air.local`, so it was never collected.
217
+ *
218
+ * @param {{ source?: string, account?: string }} binding
219
+ * @param {string | null | undefined} host this collector's machine
220
+ * @returns {string | null} the machine the binding names
221
+ */
222
+ export function foreignHostSource(binding, host) {
223
+ if (!hostBoundSource(binding?.source)) return null
224
+ const named = String(binding?.account ?? "").trim()
225
+ const here = String(host ?? "").trim()
226
+ if (!named || !here) return null
227
+ return machineSlug(named) === machineSlug(here) ? null : named
228
+ }
229
+
230
+ /** The host's tools RPC has no plugin registered under that id right now: the plugin is starting, reloading or unloaded. */
231
+ function rpcUnavailable(error) {
232
+ return error?.type === "rpc.unavailable" || /^RPC is unavailable\b/.test(String(error?.message ?? ""))
233
+ }
234
+
235
+ /**
236
+ * The account the source's own probe names on this machine, or null when it
237
+ * answers nothing (its RPC is not registered, or the read failed). A probe is a
238
+ * read of the source, so a failure here is not the binding's failure and is not
239
+ * reported as one (0.12.4).
240
+ *
241
+ * @param {{ source: string, account?: string }} binding
242
+ * @param {{ lister: any, prober: any, sessionID?: string | ((binding: object) => Promise<string>), log?: any }} where
243
+ * @returns {Promise<string | null>}
244
+ */
245
+ async function probedMachineAccount(binding, { lister, prober, sessionID, log }) {
246
+ try {
247
+ const entry = resolveDeclaredSource(binding.source).entry ?? sourceEntry(binding.source)
248
+ if (!entry) return null
249
+ const session = typeof sessionID === "function" ? await sessionID(binding) : sessionID
250
+ const answer = entry.contract === "sources"
251
+ ? prober
252
+ ? await prober(entry.source, { account: binding.account }, session)
253
+ : null
254
+ : lister
255
+ ? await lister(binding.source, probeInput(entry, binding.account), session, null)
256
+ : null
257
+ const named = answer?.account ?? answer?.owner?.account
258
+ return typeof named === "string" && named.trim() ? named.trim() : null
259
+ } catch (error) {
260
+ log?.debug?.("a host-bound binding's probe answered nothing", { source: binding?.source, error: errorMessage(error) })
261
+ return null
262
+ }
263
+ }
264
+
265
+ /**
266
+ * Is a host-bound binding another machine's? **The plugin's own probe, run on
267
+ * this machine, wins over the host name** (0.12.4): it names the account this
268
+ * machine's plugin reads, so a binding of that account is this machine's
269
+ * whatever the host is called, and a probe naming another account leaves the
270
+ * binding alone even when the name matches. With no probe answer, the name is
271
+ * compared the way the plugin writes it (`machineSlug`), so a case or `.local`
272
+ * difference is never another machine.
273
+ *
274
+ * @returns {Promise<string | null>} the machine the binding names, when it is not this one
275
+ */
276
+ async function foreignHostBinding(binding, host, { lister, prober, sessionID, log }) {
277
+ if (!hostBoundSource(binding?.source)) return null
278
+ const named = String(binding?.account ?? "").trim()
279
+ if (!named) return null
280
+ const probed = await probedMachineAccount(binding, { lister, prober, sessionID, log })
281
+ if (probed) return machineSlug(probed) === machineSlug(named) ? null : named
282
+ return foreignHostSource(binding, host)
283
+ }
284
+
285
+ /**
286
+ * Mark a result whose failure is the host's RPC, not the binding's: it keeps
287
+ * its last good state in the store (nothing is reported for it), and the run
288
+ * says when it reads again (0.12.4, live at 22:19Z on 2026-11-17: a plugin
289
+ * being reloaded answered `RPC is unavailable`, and five bindings were reported
290
+ * failing).
291
+ */
292
+ function transient(result, error, failure) {
293
+ if (!rpcUnavailable(error)) return false
294
+ result.transient = true
295
+ result.retry = "next run"
296
+ result.error = failure.message
297
+ result.code = undefined
298
+ result.action = undefined
299
+ return true
300
+ }
301
+
168
302
  /** The input every `events_list` call to a binding sends: the page, its account, and the registry's input. */
169
303
  /**
170
304
  * The account an events_list call names: a named binding's, and for a source
@@ -759,7 +893,38 @@ export async function probeSource({ entry, ctx, sessionID, account, timeoutMs =
759
893
  },
760
894
  }
761
895
  const installed = { package: entry.package, version: entry.version ?? "0.0.0", directory: "", sources: entry.descriptor, hash: entry.descriptorHash }
762
- const outcome = await probe(host, { installed, source: entry.source, account: account ?? DEFAULT_ACCOUNT, identityOperations: ["probe"] })
896
+ // **No account named: the probe learns it** (0.12.5). The contract's own
897
+ // `probe` always names the account it expects and refuses an answer for
898
+ // another, which is exactly what a bind request does not yet know: live at
899
+ // 00:43Z on 2026-11-18, Memory named `default` and github, granola and linear
900
+ // each answered ACCOUNT_MISMATCH. So the method is called with the source's
901
+ // declared input alone, and its answer is checked by the contract's own
902
+ // `probeResultProblems`, which needs no expected account.
903
+ if (account === undefined || account === null) {
904
+ const client = ctx.rpc({ id: entry.rpc, events: {}, methods })
905
+ if (typeof client?.probe !== "function") throw missingMethod("probe")
906
+ const name = typeof entry.item.input?.source === "string" ? { source: entry.item.input.source } : {}
907
+ let answer
908
+ try {
909
+ answer = await boundedSourceCall(client, "probe", name, sessionID, timeoutMs)
910
+ } catch (error) {
911
+ if (error?.type === "rpc.method_not_found") throw missingMethod("probe")
912
+ throw error
913
+ }
914
+ if (answer?.owner === undefined || answer?.owner === null) {
915
+ const error = new Error(`NEEDS_SIGN_IN: ${oneLine(String(entry.source), 40)} is not signed in. Next step: sign the plugin in to the account you mean.`)
916
+ error.code = "NEEDS_SIGN_IN"
917
+ throw error
918
+ }
919
+ const problems = probeResultProblems(answer, name)
920
+ if (problems.length > 0) {
921
+ const error = new Error(`SCHEMA_VIOLATION: ${entry.source}'s probe answer is not the contract's: ${problems[0]} Next step: report it to the plugin's maintainers.`)
922
+ error.code = "SCHEMA_VIOLATION"
923
+ throw error
924
+ }
925
+ return answer
926
+ }
927
+ const outcome = await probe(host, { installed, source: entry.source, account, identityOperations: ["probe"] })
763
928
  if (!outcome.ok) {
764
929
  const error = new Error(outcome.failure.message)
765
930
  error.code = outcome.failure.code
@@ -768,7 +933,7 @@ export async function probeSource({ entry, ctx, sessionID, account, timeoutMs =
768
933
  }
769
934
  // The contract's one probe check, called by the consumer too: the answer names the source and the account,
770
935
  // carries owner { id, label } (never null) and trust: "untrusted", and reads no content (D8, D230).
771
- const problems = probeResultProblems(outcome.answer, { ...(entry.pageSource ? { source: entry.pageSource } : {}), account: account ?? DEFAULT_ACCOUNT })
936
+ const problems = probeResultProblems(outcome.answer, { ...(entry.pageSource ? { source: entry.pageSource } : {}), account })
772
937
  if (problems.length > 0) {
773
938
  const error = new Error(`SCHEMA_VIOLATION: ${entry.source}'s probe answer is not the contract's: ${problems[0]} Next step: report it to the plugin's maintainers.`)
774
939
  error.code = "SCHEMA_VIOLATION"
@@ -784,7 +949,9 @@ export function hostSourceProber(ctx) {
784
949
  const entry = sourceEntry(source)
785
950
  if (!entry) throw new Error(`${oneLine(source, 40)} is not a source Memory knows`)
786
951
  if (entry.contract !== "sources") throw new Error(`${oneLine(source, 40)} is read through its events_list, not probed`)
787
- return probeSource({ entry, ctx, sessionID, account: input?.account ?? DEFAULT_ACCOUNT })
952
+ // An account is named only when the caller names one: a bind request asks the
953
+ // plugin which account it is signed in to (0.12.5).
954
+ return probeSource({ entry, ctx, sessionID, ...(input?.account ? { account: input.account } : {}) })
788
955
  }
789
956
  }
790
957
 
@@ -811,7 +978,7 @@ function noteRefusal(result, refusal) {
811
978
  *
812
979
  * @param {{ scheduler?: { list(): Promise<any[]>, create(input: any): Promise<any>, remove(id: string): Promise<void> } | null, lister?: ReturnType<typeof hostSourceLister>, prober?: ReturnType<typeof hostSourceProber>, log?: any }} [input]
813
980
  */
814
- export function createCollector({ scheduler = null, lister = null, prober = null, log } = {}) {
981
+ export function createCollector({ scheduler = null, lister = null, prober = null, log, host = null } = {}) {
815
982
  const reported = new Map()
816
983
 
817
984
  function noteOwner(source, account, owner) {
@@ -879,6 +1046,14 @@ export function createCollector({ scheduler = null, lister = null, prober = null
879
1046
  // One broker deadline per tick (N7b): a broker that timed out this run does not cost each later binding.
880
1047
  lister?.resetBrokerTick?.()
881
1048
  for (const binding of collectableSources(sources, { only })) {
1049
+ // Another machine's host-bound binding: not read, not reported, and so
1050
+ // never turned failing here (0.12.3). The row says whose it is. The
1051
+ // plugin's probe on this machine decides first (0.12.4).
1052
+ const elsewhere = await foreignHostBinding(binding, host, { lister, prober, sessionID, log })
1053
+ if (elsewhere) {
1054
+ results.push({ ...binding, pages: 0, accepted: 0, duplicates: 0, refused: 0, more: false, otherHost: elsewhere, done: true })
1055
+ continue
1056
+ }
882
1057
  if (!due(binding)) {
883
1058
  results.push({ ...binding, pages: 0, accepted: 0, duplicates: 0, refused: 0, more: false, notDue: true, everyMinutes: cadenceMs(binding.source) / 60_000, done: true })
884
1059
  continue
@@ -1004,6 +1179,10 @@ export function createCollector({ scheduler = null, lister = null, prober = null
1004
1179
  // §8.3.4: a code is a pause, a hold or a reset. A reset reads once more
1005
1180
  // from the window; a pause pauses the binding through its callback.
1006
1181
  const failure = failureFromError(error)
1182
+ // A plugin whose RPC is not registered yet (or no longer) is the
1183
+ // host's state: the binding keeps the state it had, and this run
1184
+ // retries next run rather than failing the binding (0.12.4).
1185
+ if (transient(result, error, failure)) break
1007
1186
  // A PERMISSION_DENIED is decided by fact, never by its message: the broker's refusal is a changed
1008
1187
  // declaration only when the digest installed now differs from the one the person confirmed. Equal
1009
1188
  // digests mean the access itself was refused (a withdrawn grant, or the provider), which re-consenting
@@ -1059,6 +1238,9 @@ export function createCollector({ scheduler = null, lister = null, prober = null
1059
1238
  result.error = failure.message
1060
1239
  result.code = failure.code
1061
1240
  result.action = failureAction(failure.code).action
1241
+ // The same transient read outside the page loop (a session, a cursor):
1242
+ // the binding keeps its state, and the run retries next run (0.12.4).
1243
+ transient(result, error, failure)
1062
1244
  } finally {
1063
1245
  result.done = true
1064
1246
  }
@@ -1113,8 +1295,24 @@ export function createCollector({ scheduler = null, lister = null, prober = null
1113
1295
  // A declared source has the contract's `probe` (D11); the owner-only
1114
1296
  // `events_list({ limit: 0 })` page is the previous contract's, and only
1115
1297
  // for a plugin that declares no source.
1298
+ // **A declared source's probe is not told an account** (0.12.5): the
1299
+ // plugin answers the account it is signed in to. Live at 00:43Z on
1300
+ // 2026-11-18, Memory named `default`, and github, granola and linear
1301
+ // each answered ACCOUNT_MISMATCH, so none of the three could bind. A
1302
+ // plugin that still refuses is asked once with the account its own
1303
+ // structured answer names, and nothing is adopted from unparsed text.
1304
+ const ask = (input) => (prober ? prober(reading.source, input, session) : Promise.reject(new Error("this host gives plugins no tools RPC, so a source cannot be probed")))
1305
+ const declaredAnswer = async () => {
1306
+ try {
1307
+ return await ask({})
1308
+ } catch (error) {
1309
+ const suggested = suggestedAccount(error)
1310
+ if (!suggested) throw error
1311
+ return ask({ account: suggested })
1312
+ }
1313
+ }
1116
1314
  const answer = reading.contract === "sources"
1117
- ? await (prober ? prober(reading.source, { account: asked.account }, session) : Promise.reject(new Error("this host gives plugins no tools RPC, so a source cannot be probed")))
1315
+ ? await declaredAnswer()
1118
1316
  : await (lister ? lister(asked.source, probeInput(reading, asked.account), session) : Promise.reject(new Error("this host gives plugins no way to call another plugin's events_list")))
1119
1317
  // A name the declaration has replaced says which source binds instead:
1120
1318
  // the store refuses a retired name, so the person needs the one to use.
@@ -1126,7 +1324,10 @@ export function createCollector({ scheduler = null, lister = null, prober = null
1126
1324
  source: asked.source,
1127
1325
  account: asked.account,
1128
1326
  owner,
1129
- reported_account: answer.account,
1327
+ // The account the probe names is the binding's account: the store
1328
+ // confirms it, and a page of a declared source always names it
1329
+ // (0.12.3). A name Memory cannot hold is not reported.
1330
+ ...(isAccountName(answer.account) ? { reported_account: answer.account } : {}),
1130
1331
  // The installed declaration's digest, read from disk: a re-consent records the digest the installed
1131
1332
  // package has now, so jelly never refuses a read made under the old one. Only for the declared id
1132
1333
  // itself: a consent recorded under a retired name never reads that declaration.
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Discovery of plugin-declared Memory (DESIGN-PLUGIN-MEMORY §2.3), read-only:
3
3
  *
4
- * 1. **List** `ctx.plugin.list()`: active `package` and `local` plugins, not
4
+ * 1. **List** `ctx.plugin.list()` (an array, or the host's `{ location, data }`): active `package` and `local` plugins, not
5
5
  * `builtin`, `sdk` or Memory itself.
6
6
  * 2. **Find** each one's installed package (src/plugins/locate.js).
7
7
  * 3. **Read** `name`, `version` and `memory` from that `package.json`. No
@@ -27,6 +27,7 @@
27
27
  * or the protocol.
28
28
  */
29
29
  import { LAYOUT_CHANGED, cacheRoot, locate } from "./locate.js"
30
+ import { pluginList } from "./list.js"
30
31
  import { canonicalJSON, validateManifest } from "./manifest.js"
31
32
  import { CONTRACT_LABELS, readDeclared } from "./descriptor.js"
32
33
  import { setDeclaredSources, setInstalledVersions, sourceEntriesOf } from "../sources.js"
@@ -245,7 +246,7 @@ export function createPluginDiscovery({ ctx, runtime, toolkit, clock = REAL_CLOC
245
246
  if (resolved.invalid || resolved.error) throw new Error(resolved.invalid || resolved.error)
246
247
  where = { space: resolved.context.space_id }
247
248
  }
248
- const result = await discover({ plugins: await ctx.plugin.list(), root: await root(), readRpc: reader, clock })
249
+ const result = await discover({ plugins: pluginList(await ctx.plugin.list(), log), root: await root(), readRpc: reader, clock })
249
250
  // A full report: every plugin this machine has; the records service marks the ones it no longer names as missing.
250
251
  await records.call("plugins.report", { layout: result.layout, full: true, plugins: result.plugins }, where)
251
252
  // The declarations the collector reads under are published **only after**
@@ -0,0 +1,18 @@
1
+ /**
2
+ * What `ctx.plugin.list()` answers, as its list of plugins.
3
+ *
4
+ * OpenCode 2.2.6 answers `{ location, data: [...] }`, not an array (live on the
5
+ * owner's machine at 19:10Z on 2026-11-17: 116 entries), while `/api/plugin`
6
+ * answers a bare array. Both are read here, and anything else is no list at
7
+ * all: a warning in the log, never a throw, and never a plugin.
8
+ *
9
+ * @param {unknown} answer what the host answered
10
+ * @param {{ warn?: (message: string, detail?: object) => void } | null} [log]
11
+ * @returns {any[]} the plugins the answer names, or none
12
+ */
13
+ export function pluginList(answer, log = null) {
14
+ if (Array.isArray(answer)) return answer
15
+ if (answer !== null && typeof answer === "object" && Array.isArray(answer.data)) return answer.data
16
+ log?.warn?.("plugin list is not a list", { shape: answer === null ? "null" : typeof answer })
17
+ return []
18
+ }
@@ -4,7 +4,8 @@
4
4
  * Memory's credential can report a plugin. So before a binding collects, the
5
5
  * collector itself:
6
6
  *
7
- * 1. finds the plugin in OpenCode's own list (`ctx.plugin.list()`), active,
7
+ * 1. finds the plugin in OpenCode's own list (`ctx.plugin.list()`: `{ location, data }` on
8
+ * 2.2.6, a bare array from `/api/plugin`), active,
8
9
  * with no failed twin of the same id;
9
10
  * 2. checks the pin: the same source kind and target or path, and the same
10
11
  * package name, as the person confirmed;
@@ -20,6 +21,7 @@
20
21
  * collector accept what is really on disk, intersected with the consent.
21
22
  */
22
23
  import { LAYOUT_CHANGED, locate } from "./locate.js"
24
+ import { pluginList } from "./list.js"
23
25
  import { validateManifest } from "./manifest.js"
24
26
  import { effectiveSource } from "./grants.js"
25
27
 
@@ -27,12 +29,12 @@ const stop = (kind, reason) => ({ ok: false, stop: kind, reason })
27
29
 
28
30
  /**
29
31
  * @param {{ plugin_id: string, source: string, package: string, pin: { kind: string, ref: string }, digest: string, live_digest?: string | null, snapshot: { source: any }, state: string }} consent
30
- * @param {{ plugins: any[], root: string }} where OpenCode's plugin list and the cache root
32
+ * @param {{ plugins: any[] | { data: any[] }, root: string, log?: { warn?: (message: string, detail?: object) => void } | null }} where OpenCode's plugin list (either shape) and the cache root
31
33
  * @returns {Promise<{ ok: true, effective: ReturnType<typeof effectiveSource>, live: any, digest: string } | { ok: false, stop: string, reason: string }>}
32
34
  */
33
- export async function verifyConsent(consent, { plugins, root }) {
35
+ export async function verifyConsent(consent, { plugins, root, log = null }) {
34
36
  if (consent.state !== "on") return stop("stopped", consent.reason ?? `the binding is ${consent.state}`)
35
- const all = Array.isArray(plugins) ? plugins : []
37
+ const all = pluginList(plugins, log)
36
38
  const info = all.find((entry) => entry?.id === consent.plugin_id && entry?.state?.status === "active")
37
39
  if (!info) return stop("missing", `${consent.plugin_id} is not running in this OpenCode`)
38
40
  if (all.some((entry) => entry?.id === consent.plugin_id && entry?.state?.status === "failed" && /^Duplicate plugin ID\b/.test(String(entry.state.error ?? "")))) {
package/src/records.js CHANGED
@@ -109,6 +109,9 @@ export function itemOfRecord(record) {
109
109
  link: fields.link,
110
110
  created: fields.created_day ?? dayOf(record?.created),
111
111
  updated: dayOf(record?.updated),
112
+ // The version a change must name, as the commitment acts take it (#97): a
113
+ // list answer carries it, so a control needs no second read of the item.
114
+ revision: Number.isSafeInteger(Number(record?.version)) && Number(record.version) > 0 ? Number(record.version) : undefined,
112
115
  closed: fields.closed_at ? dayOf(fields.closed_at) : undefined,
113
116
  session: record?.source?.session,
114
117
  legacy_id: fields.legacy_id,
package/src/sources.js CHANGED
@@ -31,9 +31,41 @@ import { maxBytesOf } from "./plugins/source-contract/vendor/descriptor.js"
31
31
  /** A binding's account name: no wildcard (`*`, `?`), separator (`:`, `/`) or space, and never empty. */
32
32
  export const ACCOUNT_NAME = /^[A-Za-z0-9][A-Za-z0-9_.@+-]{0,127}$/
33
33
 
34
+ /**
35
+ * The sources whose **account names the machine that reads them**: the
36
+ * sessions a history source indexes live in this machine's own files, so a
37
+ * binding of one is that machine's binding, and no other machine can read it
38
+ * (0.12.3). A collector on another machine leaves such a binding alone: it is
39
+ * not read, not reported, and so never turned failing.
40
+ *
41
+ * It is named here, beside the catalog, because the account is the only place
42
+ * a machine is named: the contract has no field for it. A declared
43
+ * `history.sessions` is the same source under its contract id.
44
+ */
45
+ const HOST_BOUND = new Set(["history", "history.sessions"])
46
+
47
+ /** True when only the machine its account names may collect this source (0.12.3). */
48
+ export function hostBoundSource(source) {
49
+ return HOST_BOUND.has(String(source ?? ""))
50
+ }
51
+
34
52
  /** The timer's default cadence per source, in minutes. */
35
53
  export const DEFAULT_EVERY_MINUTES = 30
36
54
 
55
+ /**
56
+ * The owner's cadence policy, by namespace (0.12.4): **X's reads are billed**, so
57
+ * a binding of one of its sources is read once a day, whatever the plugin's own
58
+ * declaration or cadence says. A plugin's `cadence.providerMinMinutes` is the
59
+ * floor the provider imposes, never the person's choice, so it cannot shorten
60
+ * this; it can only lengthen it.
61
+ */
62
+ const OWNER_CADENCE_MINUTES = Object.freeze({ x: 1440 })
63
+
64
+ /** The shortest cadence the owner allows this namespace, in minutes, or 0 where they set none. */
65
+ function ownerCadence(namespace) {
66
+ return OWNER_CADENCE_MINUTES[String(namespace ?? "")] ?? 0
67
+ }
68
+
37
69
  function freezePermission(permission) {
38
70
  return Object.freeze({
39
71
  ...permission,
@@ -89,7 +121,7 @@ export const PREVIOUS_CONTRACT_SOURCES = Object.freeze(
89
121
  namespace: "x",
90
122
  package: "@joe-broadhead/opencode-x",
91
123
  minVersion: "0.0.4",
92
- everyMinutes: 120,
124
+ // Once a day: its reads are billed, and the owner's cadence policy is below (`ownerCadence`).
93
125
  permission: { actions: ["x_get_users_me", "x_get_users_mentions", "x_get_users_bookmarks", "x_get_users_timeline"] },
94
126
  setupOptions:
95
127
  'X reads are billed. Set the x plugin\'s options "events": {"feeds": ["mentions", "bookmarks"], "maxCalls": 2}, and "ownsXApp": true only if the signed-in account owns the developer app (it lowers the price X charges); then restart OpenCode.',
@@ -145,7 +177,6 @@ export const PREVIOUS_CONTRACT_SOURCES = Object.freeze(
145
177
  tool: "events_list",
146
178
  input: {},
147
179
  minVersion: null,
148
- everyMinutes: DEFAULT_EVERY_MINUTES,
149
180
  ownerProbe: "limit1",
150
181
  setupOptions: null,
151
182
  namesAccount: false,
@@ -153,6 +184,9 @@ export const PREVIOUS_CONTRACT_SOURCES = Object.freeze(
153
184
  contractLabel: "events_list (previous)",
154
185
  kind: "events",
155
186
  ...entry,
187
+ // The owner's cadence outranks the registry's own: X is read once a day
188
+ // because its reads are billed (0.12.4).
189
+ everyMinutes: Math.max(DEFAULT_EVERY_MINUTES, Number(entry.everyMinutes) || 0, ownerCadence(entry.namespace)),
156
190
  input: Object.freeze({ ...(entry.input ?? {}) }),
157
191
  permission: freezePermission({
158
192
  events: `${entry.namespace}_events_list`,
@@ -432,13 +466,14 @@ function declaredEntry(plugin, item) {
432
466
  const named = item.accounts?.named === true
433
467
  const stated = Number(item.cadence?.providerMinMinutes)
434
468
  const floor = Number.isInteger(stated) && stated >= 1 ? stated : null
469
+ const namespace = String(item.id).split(".")[0]
435
470
  return Object.freeze({
436
471
  source: item.id,
437
472
  pluginId: plugin.id,
438
473
  package: plugin.package,
439
474
  version: plugin.version ?? null,
440
475
  rpc: `${plugin.id}.tools`,
441
- namespace: String(item.id).split(".")[0],
476
+ namespace,
442
477
  tool: item.tool,
443
478
  kind: item.kind,
444
479
  reads: item.reads ?? null,
@@ -450,7 +485,9 @@ function declaredEntry(plugin, item) {
450
485
  // rules and the plugin's account always agree.
451
486
  namesAccount: named,
452
487
  ownerProbe: "probe",
453
- everyMinutes: Math.max(DEFAULT_EVERY_MINUTES, floor ?? 0),
488
+ // A declared X source is read once a day too: the plugin's own cadence can
489
+ // only lengthen the owner's policy, never shorten it (0.12.4).
490
+ everyMinutes: Math.max(DEFAULT_EVERY_MINUTES, floor ?? 0, ownerCadence(namespace)),
454
491
  minVersion: null,
455
492
  setupOptions: null,
456
493
  contract: "sources",
@@ -495,7 +532,8 @@ function memoryEntries(plugin) {
495
532
  pageSource: pageSourceOf({ id: source.id, input: source.input }),
496
533
  namesAccount: source.accounts === "multi",
497
534
  ownerProbe: "limit0",
498
- everyMinutes: Math.max(DEFAULT_EVERY_MINUTES, Number(source.cadence?.everyMinutes) || 0),
535
+ // The owner's cadence applies to a previous-contract declaration too, by the source id's namespace.
536
+ everyMinutes: Math.max(DEFAULT_EVERY_MINUTES, Number(source.cadence?.everyMinutes) || 0, ownerCadence(String(source.id).split(".")[0])),
499
537
  minVersion: null,
500
538
  setupOptions: null,
501
539
  contract: "memory",
package/src/util.js CHANGED
@@ -174,6 +174,34 @@ export function errorMessage(error) {
174
174
  return NO_ERROR_MESSAGE
175
175
  }
176
176
 
177
+ /** A message that already names a code (`AUTH_REQUIRED: …`): a second one would be noise. */
178
+ const CODED_PREFIX = /^[A-Z][A-Z0-9_]+: /
179
+
180
+ /**
181
+ * A failure as one line of text a person reads: `CODE: what happened`, or the
182
+ * message alone when it names no code (or only the contract's own
183
+ * `UNAVAILABLE`, which says the read failed and no more). The code is kept
184
+ * because a provider's refusal is diagnosed by it (`AUTH_REQUIRED` is a
185
+ * sign-in, `RATE_LIMITED` is a wait), and the message alone has lost it by the
186
+ * time it is stored.
187
+ *
188
+ * It is built from `errorMessage`, so a failure that arrives as a plain object
189
+ * reads as its own words: never `String(object)`, which is `[object Object]`.
190
+ * A message that already names the code (`AUTH_REQUIRED: …`, which is how a
191
+ * coded error is written) is not prefixed twice.
192
+ *
193
+ * @param {unknown} error
194
+ * @param {number} [max]
195
+ */
196
+ export function failureText(error, max = 300) {
197
+ const text = oneLine(errorMessage(error), max)
198
+ const code = oneLine(codeOf(error), 60)
199
+ // `UNAVAILABLE` is the contract's word for "the read failed, retry": a
200
+ // failure that names nothing more specific reads as its own sentence.
201
+ if (!code || code === "UNAVAILABLE" || text === code || CODED_PREFIX.test(text)) return text
202
+ return oneLine(`${code}: ${text}`, max)
203
+ }
204
+
177
205
  /** The withheld phrase, naming the code so a failure is still diagnosable. */
178
206
  function withheld(code) {
179
207
  return code ? `${ERROR_WITHHELD} (code ${oneLine(code, 60)})` : ERROR_WITHHELD
@@ -655,7 +655,9 @@ const commitmentsOutput = {
655
655
  items: {
656
656
  type: "object",
657
657
  additionalProperties: false,
658
- required: ["id", "what", "owner", "state", "when", "overdue", "dueToday"],
658
+ // `revision` is not required: a read that cannot name a version leaves
659
+ // it out, and the act then reads the record's own (0.12.5 review, L).
660
+ required: ["id", "what", "owner", "state", "when", "overdue", "dueToday", "space"],
659
661
  properties: {
660
662
  id,
661
663
  what: line(300),
@@ -670,6 +672,10 @@ const commitmentsOutput = {
670
672
  dueToday: { type: "boolean" },
671
673
  trigger: line(200),
672
674
  project: line(80),
675
+ /** The space the item is in, as its acts take it (`commitment.done` and the rest). */
676
+ space: line(128),
677
+ /** The item's version, as its acts take it: a press names the one the person saw. */
678
+ revision: { type: "integer", minimum: 1 },
673
679
  /** The day it was closed, as "Tue 3 Nov"; closed items only. */
674
680
  closed: line(40),
675
681
  },
package/src/views/rpc.js CHANGED
@@ -418,6 +418,10 @@ export function createViewReads({ runtime, agents = async () => [], operations =
418
418
  * The person's commitments, from their personal space's records wiki: open
419
419
  * ones overdue first, or closed ones newest first. Only the caller's own
420
420
  * space is read; a view can change nothing (closing one opens the agent).
421
+ *
422
+ * Each item carries the two fields every commitment act takes (`space` and
423
+ * `revision`), so a control acts on what the list answered without reading
424
+ * the item again (#97).
421
425
  */
422
426
  async function commitmentsList(input) {
423
427
  await available()
@@ -426,6 +430,8 @@ export function createViewReads({ runtime, agents = async () => [], operations =
426
430
  const records = (await runtime.records.read(first.scope)).records
427
431
  const zone = runtime.clock.zone
428
432
  const today = dayIn(runtime.clock.now(), zone)
433
+ // The space this list read, as the acts take it, and its name for the row.
434
+ const here = clip(idOf(first.context?.space_id) || "", 128)
429
435
  let items = filterItems(records.items, { state: state === "open" ? "open" : "all" }, zone)
430
436
  if (state === "closed") {
431
437
  items = items
@@ -447,6 +453,12 @@ export function createViewReads({ runtime, agents = async () => [], operations =
447
453
  dueToday: item.state === "open" && day === today,
448
454
  ...(item.trigger ? { trigger: clip(item.trigger, 200) } : {}),
449
455
  ...(item.project ? { project: clip(item.project, 80) } : {}),
456
+ space: here,
457
+ // The version the item's acts take, and only when the read named one:
458
+ // a list that could not name a version leaves it out (the act then
459
+ // reads the record's own), rather than claiming 1, which would make
460
+ // the press stale before it started (0.12.5 review, L).
461
+ ...(Number.isSafeInteger(item.revision) && item.revision > 0 ? { revision: item.revision } : {}),
450
462
  ...(item.state !== "open" && (item.closed || item.updated) ? { closed: clip(formatDay(item.closed ?? item.updated), 40) } : {}),
451
463
  }
452
464
  }),
@@ -101,13 +101,23 @@ export async function mapLimit(list, limit, work) {
101
101
  return out
102
102
  }
103
103
 
104
- /** A where-it-came-from line for a record's `source` ({ event, turn, session, routine, record, url }), or "". */
104
+ /**
105
+ * A where-it-came-from line for a record's `source` ({ event, turn, session,
106
+ * routine, record, url }), or "". A saved line's citation (#58 A14) is the one
107
+ * pair: `conversation <id> line <id>`, so a memory says which conversation and
108
+ * which line it was taken from.
109
+ */
105
110
  export function sourceLabel(source) {
106
111
  if (!source || typeof source !== "object") return ""
107
112
  for (const key of ["event", "turn", "session", "routine", "record"]) {
108
113
  const ref = typeof source[key] === "string" ? source[key].trim() : ""
109
114
  if (ref && /^[\w.:@/-]{1,120}$/.test(ref)) return `${key} ${ref}`
110
115
  }
116
+ const conversation = typeof source.conversation === "string" ? source.conversation.trim() : ""
117
+ const line = typeof source.line === "string" ? source.line.trim() : ""
118
+ const named = (value) => Boolean(value) && /^[\w.:@/-]{1,120}$/.test(value)
119
+ if (named(conversation)) return named(line) ? `conversation ${conversation} line ${line}` : `conversation ${conversation}`
120
+ if (named(line)) return `line ${line}`
111
121
  const url = typeof source.url === "string" ? source.url.trim() : ""
112
122
  return /^https?:\/\/[^\s<>"']{1,190}$/.test(url) ? `url ${url}` : ""
113
123
  }