@joe-broadhead/opencode-mem 0.8.5 → 0.9.1

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.
Files changed (58) hide show
  1. package/CHANGELOG.md +512 -0
  2. package/README.md +127 -61
  3. package/docs/agent-protocol.md +67 -177
  4. package/package.json +1453 -100
  5. package/skills/mem.pages/SKILL.md +146 -0
  6. package/skills/mem.sharing/SKILL.md +91 -0
  7. package/skills/mem.sources/SKILL.md +94 -0
  8. package/skills/mem.usage/SKILL.md +129 -492
  9. package/src/backend/records.js +285 -0
  10. package/src/backend/v3.js +3 -0
  11. package/src/bootstrap.js +49 -45
  12. package/src/call-shapes.js +41 -10
  13. package/src/collector-lock.js +162 -0
  14. package/src/collector-service.js +441 -0
  15. package/src/collector.js +381 -0
  16. package/src/commands.js +3 -3
  17. package/src/config.js +15 -1
  18. package/src/credentials.js +26 -1
  19. package/src/curation.js +1 -1
  20. package/src/permissions.js +87 -10
  21. package/src/protocol.js +29 -20
  22. package/src/recall.js +104 -27
  23. package/src/records-store.js +267 -121
  24. package/src/records.js +63 -11
  25. package/src/runtime.js +23 -14
  26. package/src/skills.js +44 -18
  27. package/src/sources.js +58 -0
  28. package/src/spaces.js +93 -10
  29. package/src/tools/aliases.js +164 -0
  30. package/src/tools/commitments.js +12 -9
  31. package/src/tools/held-write.js +82 -0
  32. package/src/tools/index.js +100 -23
  33. package/src/tools/ingest.js +277 -0
  34. package/src/tools/knowledge.js +6 -1
  35. package/src/tools/memory.js +722 -229
  36. package/src/tools/page.js +423 -0
  37. package/src/tools/recall.js +371 -113
  38. package/src/tools/records-kit.js +142 -0
  39. package/src/tools/share.js +1042 -0
  40. package/src/tools/shared.js +16 -2
  41. package/src/tools/spaces.js +431 -143
  42. package/src/tools/status.js +87 -58
  43. package/src/tools/wiki.js +8 -4
  44. package/src/views/contracts.js +293 -3
  45. package/src/views/inbox-decision.js +59 -0
  46. package/src/views/recall-result.js +12 -0
  47. package/src/views/records-reads.js +675 -0
  48. package/src/views/rpc.js +58 -99
  49. package/src/views/shape.js +61 -0
  50. package/views/commitments.html +4 -0
  51. package/views/graph.html +753 -0
  52. package/views/home.html +11 -5
  53. package/views/journal.html +621 -0
  54. package/views/memory.html +7 -1
  55. package/views/pages.html +636 -0
  56. package/views/recall.html +123 -0
  57. package/views/review.html +406 -0
  58. package/views/today.html +309 -0
package/src/skills.js CHANGED
@@ -3,30 +3,51 @@ import path from "node:path"
3
3
  import { fileURLToPath } from "node:url"
4
4
  import { slug, oneLine, shortHash } from "./util.js"
5
5
 
6
- const BUILTIN_SKILL_PATH = fileURLToPath(new URL("../skills/mem.usage/SKILL.md", import.meta.url))
6
+ /**
7
+ * The plugin's own skills (docs/design/memory-v1-contracts.md §4.6), each
8
+ * `skills/<id>/SKILL.md`, shipped in the package and declared in `jelly.skills`
9
+ * in this order: the day-to-day guide, pages, sharing, and sources. The host
10
+ * loads one when its front matter's description matches the work, so each
11
+ * description is a precise trigger (test/skill-triggers.test.js).
12
+ */
13
+ export const BUILTIN_SKILLS = Object.freeze(["mem.usage", "mem.pages", "mem.sharing", "mem.sources"])
14
+ const builtinPath = (id) => fileURLToPath(new URL(`../skills/${id}/SKILL.md`, import.meta.url))
7
15
  const MAX_SKILLS = 24
8
16
 
9
17
  /**
10
- * Register the plugin's own usage guide as a native skill, so every agent that
11
- * can see the plugin also learns when to call it.
18
+ * Register the plugin's own skills as native skills, so every agent that can
19
+ * see the plugin also learns when to call it. A skill that cannot be read is
20
+ * left out and logged; the others still register.
12
21
  */
13
22
  export async function registerBuiltinSkill(ctx, runtime) {
14
23
  if (!ctx?.skill || typeof ctx.skill.transform !== "function") return null
24
+ const skills = []
25
+ for (const id of BUILTIN_SKILLS) {
26
+ try {
27
+ const path = builtinPath(id)
28
+ const content = await fs.readFile(path, "utf8")
29
+ skills.push({ id, path, content })
30
+ } catch (error) {
31
+ runtime.log.warn("builtin skill unreadable", { id, error: error?.message })
32
+ }
33
+ }
34
+ if (skills.length === 0) return null
15
35
  try {
16
- const content = await fs.readFile(BUILTIN_SKILL_PATH, "utf8")
17
36
  const registration = await ctx.skill.transform((editor) => {
18
- editor.add({
19
- id: "mem.usage",
20
- name: "memory",
21
- // The front matter's description is what decides when the skill loads,
22
- // so the host is given exactly that: one text, no second copy to drift.
23
- description: frontMatterDescription(content),
24
- path: BUILTIN_SKILL_PATH,
25
- content,
26
- autoinvoke: true,
27
- })
37
+ for (const { id, path, content } of skills) {
38
+ editor.add({
39
+ id,
40
+ name: frontMatterField(content, "name") || id,
41
+ // The front matter's description is what decides when the skill loads,
42
+ // so the host is given exactly that: one text, no second copy to drift.
43
+ description: frontMatterDescription(content),
44
+ path,
45
+ content,
46
+ autoinvoke: true,
47
+ })
48
+ }
28
49
  })
29
- runtime.log.info("builtin skill registered", { id: "mem.usage" })
50
+ runtime.log.info("builtin skills registered", { ids: skills.map((skill) => skill.id) })
30
51
  return registration
31
52
  } catch (error) {
32
53
  runtime.log.warn("builtin skill registration failed", error?.message)
@@ -34,11 +55,16 @@ export async function registerBuiltinSkill(ctx, runtime) {
34
55
  }
35
56
  }
36
57
 
58
+ /** One `key:` line of a skill's YAML front matter, or "". */
59
+ export function frontMatterField(content, key) {
60
+ const block = String(content).match(/^---\r?\n([\s\S]*?)\r?\n---/)
61
+ const line = block?.[1].split(/\r?\n/).find((entry) => entry.startsWith(`${key}:`))
62
+ return line ? line.slice(key.length + 1).trim() : ""
63
+ }
64
+
37
65
  /** The `description:` line of a skill's YAML front matter. */
38
66
  export function frontMatterDescription(content) {
39
- const block = String(content).match(/^---\r?\n([\s\S]*?)\r?\n---/)
40
- const line = block?.[1].split(/\r?\n/).find((entry) => entry.startsWith("description:"))
41
- return line ? line.slice("description:".length).trim() : ""
67
+ return frontMatterField(content, "description")
42
68
  }
43
69
 
44
70
  /**
package/src/sources.js ADDED
@@ -0,0 +1,58 @@
1
+ /**
2
+ * The source registry (docs/design/memory-v1-contracts.md §4.4): every source
3
+ * Memory can collect from, with the plugin that serves it. A source is added
4
+ * here and nowhere else.
5
+ *
6
+ * - `rpc`: the source plugin's tools-RPC id; the in-plugin collector and a
7
+ * bind call `events_list` through it (`ctx.rpc`).
8
+ * - `namespace` and `tool`: the Code Mode path a host schedule's check calls,
9
+ * `tools.<namespace>.<tool>`.
10
+ * - `input`: what every `events_list` call to this source adds; a plugin that
11
+ * serves several sources (gws: gmail, later calendar and drive) is told which.
12
+ * - `package` and `minVersion`: who to update when the plugin's `events_list`
13
+ * does not keep the source contract (§4.5). `minVersion` is the first release
14
+ * whose `events_list` answers `source` and `account`; null until lane SRC
15
+ * publishes it, and the error then names the contract instead.
16
+ */
17
+ export const SOURCE_REGISTRY = Object.freeze(
18
+ [
19
+ { source: "history", rpc: "history.sessions.tools", namespace: "history", package: "@joe-broadhead/opencode-history" },
20
+ { source: "gmail", rpc: "google-workspace.gws.tools", namespace: "gws", input: { source: "gmail" }, package: "@joe-broadhead/opencode-gws" },
21
+ { source: "slack", rpc: "slack.workspace.tools", namespace: "slack", package: "@joe-broadhead/opencode-slack" },
22
+ { source: "x", rpc: "x.posts.tools", namespace: "x", package: "@joe-broadhead/opencode-x" },
23
+ { source: "granola", rpc: "granola.meetings.tools", namespace: "granola", package: "@joe-broadhead/opencode-granola" },
24
+ { source: "plaud", rpc: "plaud.recordings.tools", namespace: "plaud", package: "@joe-broadhead/opencode-plaud" },
25
+ { source: "wisprflow", rpc: "wisprflow.meetings.tools", namespace: "wisprflow", package: "@joe-broadhead/opencode-wisprflow" },
26
+ { source: "github", rpc: "github.platform.tools", namespace: "github", package: "@joe-broadhead/opencode-github" },
27
+ { source: "linear", rpc: "linear.workspace.tools", namespace: "linear", package: "@joe-broadhead/opencode-linear" },
28
+ ].map((entry) => Object.freeze({ tool: "events_list", input: {}, minVersion: null, ...entry, input: Object.freeze({ ...(entry.input ?? {}) }) })),
29
+ )
30
+
31
+ const BY_SOURCE = new Map(SOURCE_REGISTRY.map((entry) => [entry.source, entry]))
32
+
33
+ /** The registry entry for a source name, or null. */
34
+ export function sourceEntry(source) {
35
+ return BY_SOURCE.get(String(source ?? "")) ?? null
36
+ }
37
+
38
+ /** Every source Memory knows, in the registry's order. */
39
+ export function knownSources() {
40
+ return SOURCE_REGISTRY.map((entry) => entry.source)
41
+ }
42
+
43
+ /** The source contract version a plugin's `events_list` must keep. */
44
+ export const SOURCE_CONTRACT = "the memory source contract v1 (events_list answers source and account)"
45
+
46
+ /**
47
+ * The one sentence for a plugin whose `events_list` answered without `source`
48
+ * and `account` (§4.5): it names the package and the release it needs.
49
+ */
50
+ export function contractRefusal(entry) {
51
+ const release = entry.minVersion ? `${entry.package} ${entry.minVersion} or newer` : `a release of ${entry.package} that keeps ${SOURCE_CONTRACT}`
52
+ return `${entry.package}'s events_list answered without source and account, so Memory refused it: update to ${release}.`
53
+ }
54
+
55
+ /** The RPC definition `ctx.rpc` takes for a source's `events_list`. */
56
+ export function rpcDefinition(entry) {
57
+ return { id: entry.rpc, events: {}, methods: { [entry.tool]: { input: { type: "object" }, output: { type: "object" } } } }
58
+ }
package/src/spaces.js CHANGED
@@ -257,15 +257,99 @@ export function createControlClient(input) {
257
257
  *
258
258
  * @param {{ userId: string, spaceId: string }} input
259
259
  */
260
- async function listGrants({ userId, spaceId } = {}) {
260
+ async function listGrants({ userId, spaceId, resourceId } = {}) {
261
261
  if (!userId) throw missing("grants", "user_id")
262
262
  if (!spaceId) throw missing("grants", "space_id")
263
+ // With resource_id: who a shared page or folder is shared with (its owner
264
+ // or a space admin may ask). Without: the grants that name the caller.
263
265
  const payload = await request("grants", "GET", "/v1/grants", {
264
- query: { space_id: String(spaceId) },
266
+ query: { space_id: String(spaceId), resource_id: resourceId ? String(resourceId) : undefined },
265
267
  })
266
268
  return extractGrantList(payload).map(normalizeGrant).filter((grant) => grant.grant_id)
267
269
  }
268
270
 
271
+ /**
272
+ * A space's registered resources of one kind (mem_share list):
273
+ * `GET /v1/spaces/:space_id/resources?kind=…`. Only a shared page or
274
+ * folder's `records:` id is kept as `upstream_id`; any other kind's upstream
275
+ * id is dropped here.
276
+ *
277
+ * @param {{ userId: string, spaceId: string, kind?: string }} input
278
+ */
279
+ async function listResources({ userId, spaceId, kind = "wiki_page" } = {}) {
280
+ if (!userId) throw missing("resources", "user_id")
281
+ if (!spaceId) throw missing("resources", "space_id")
282
+ const payload = await request("resources", "GET", `/v1/spaces/${encodeURIComponent(String(spaceId))}/resources`, {
283
+ query: { kind: String(kind) },
284
+ })
285
+ const rows = Array.isArray(payload) ? payload : Array.isArray(payload?.resources) ? payload.resources : []
286
+ return rows
287
+ .filter((row) => isPlainObject(row) && row.id && String(row.kind ?? kind) === kind)
288
+ .map((row) => ({
289
+ id: text(row.id),
290
+ kind: text(row.kind ?? kind),
291
+ upstream_id: /^records:[a-z0-9/-]{1,300}$/.test(text(row.upstream_id)) ? text(row.upstream_id) : "",
292
+ name: text(row.name),
293
+ owner_user_id: text(row.owner_user_id),
294
+ role: text(row.role),
295
+ }))
296
+ }
297
+
298
+ /**
299
+ * Create a grant (mem_share grant): `POST /v1/grants`, the public route the
300
+ * gateway allow-lists (target, principal, role, inherit, expiry). Control
301
+ * checks that the caller may grant on the target and audits it.
302
+ *
303
+ * @param {{ userId: string, grant: { target_type: string, target_id: string, principal_type: string, principal_id: string, role: string, expires_at?: string, space_id?: string } }} input
304
+ */
305
+ async function createGrant({ userId, grant } = {}) {
306
+ if (!userId) throw missing("grant", "user_id")
307
+ if (!grant?.target_id) throw missing("grant", "target_id")
308
+ if (!grant?.principal_id) throw missing("grant", "principal_id")
309
+ const payload = await request("grant", "POST", "/v1/grants", { body: grant })
310
+ const row = isPlainObject(payload?.grant) ? payload.grant : payload
311
+ return normalizeGrant(row)
312
+ }
313
+
314
+ /**
315
+ * Delete a grant (mem_share revoke): `DELETE /v1/grants/:id`. The gateway
316
+ * answers an unknown and a foreign grant alike (403 grant_access_denied).
317
+ *
318
+ * @param {{ userId: string, grantId: string }} input
319
+ */
320
+ async function deleteGrant({ userId, grantId } = {}) {
321
+ if (!userId) throw missing("grant", "user_id")
322
+ if (!grantId) throw missing("grant", "grant_id")
323
+ await request("grant", "DELETE", `/v1/grants/${encodeURIComponent(String(grantId))}`)
324
+ return { deleted: true }
325
+ }
326
+
327
+ /**
328
+ * Change the owner of a shared page or folder (mem_share transfer).
329
+ *
330
+ * `POST /v1/spaces/:space_id/resources/:resource_id/transfer` with
331
+ * `{ user_id }`, answering `{ resource: { id, owner_user_id, … }, transferred }`
332
+ * (deploy/auth/control-plane.md, Records route). Only the resource's owner or
333
+ * a space admin may, and the new owner must already be able to edit it
334
+ * (`400 new_owner_cannot_edit`); control audits it.
335
+ *
336
+ * @param {{ userId: string, spaceId: string, resourceId: string, toUserId: string }} input
337
+ */
338
+ async function transferResource({ userId, spaceId, resourceId, toUserId } = {}) {
339
+ if (!userId) throw missing("transfer", "user_id")
340
+ if (!spaceId) throw missing("transfer", "space_id")
341
+ if (!resourceId) throw missing("transfer", "resource_id")
342
+ if (!toUserId) throw missing("transfer", "user_id of the new owner")
343
+ const route = `/v1/spaces/${encodeURIComponent(String(spaceId))}/resources/${encodeURIComponent(String(resourceId))}/transfer`
344
+ const payload = await request("transfer", "POST", route, { body: { user_id: String(toUserId) } })
345
+ const resource = isPlainObject(payload?.resource) ? payload.resource : isPlainObject(payload) ? payload : {}
346
+ return {
347
+ id: text(resource.id ?? resourceId),
348
+ owner_user_id: text(resource.owner_user_id ?? resource.owner),
349
+ transferred: payload?.transferred !== false,
350
+ }
351
+ }
352
+
269
353
  /**
270
354
  * Read the member roster for one space. Membership and roles are never
271
355
  * inferred by the plugin.
@@ -294,6 +378,10 @@ export function createControlClient(input) {
294
378
  listMembers,
295
379
  createResource,
296
380
  deleteResource,
381
+ listResources,
382
+ createGrant,
383
+ deleteGrant,
384
+ transferResource,
297
385
  }
298
386
  }
299
387
 
@@ -375,14 +463,9 @@ function normalizeContext(payload, requested) {
375
463
  : {}
376
464
  const collection = isPlainObject(root.collection) ? root.collection : {}
377
465
  const session = isPlainObject(root.session) ? root.session : {}
378
- const personalEntry = Array.isArray(root.spaces)
379
- ? root.spaces.find((entry) => entry?.kind === "personal")
380
- : undefined
381
- const personal = isPlainObject(root.personal_space)
382
- ? root.personal_space
383
- : isPlainObject(personalEntry)
384
- ? personalEntry
385
- : {}
466
+ const personalEntries = Array.isArray(root.spaces) ? root.spaces.filter((entry) => entry?.kind === "personal") : []
467
+ const personalEntry = personalEntries.length === 1 ? personalEntries[0] : undefined
468
+ const personal = isPlainObject(root.personal_space) ? root.personal_space : {}
386
469
  const placement = isPlainObject(root.placement)
387
470
  ? root.placement
388
471
  : Array.isArray(root.placement) && isPlainObject(root.placement[0])
@@ -0,0 +1,164 @@
1
+ import { recordsOf } from "./share.js"
2
+
3
+ /**
4
+ * The old tool names, kept for one release (0.9.x; removed in 0.10), each
5
+ * described as "Deprecated: use X" (docs/design/memory-v1-contracts.md §4.1):
6
+ *
7
+ * - `forget` → `mem_revise` with "action": "forget". Ids from before 0.9
8
+ * (`m_…`, `msg-…`) and `match` keep today's behaviour exactly, through the
9
+ * legacy registration when the core tools still provide one;
10
+ * - `promote` → `mem_share` copy (and revoke). A 0.8 share (a `res_…` wiki
11
+ * share) is still revoked as before; with no records client, a copy falls
12
+ * back to the 0.8 wiki share, and says so;
13
+ * - `status` → `mem_spaces` health; `grants` → `mem_spaces` access;
14
+ * `members` → `mem_spaces` members.
15
+ *
16
+ * A core registration that still adds one of these names is captured, not
17
+ * added (src/tools/index.js), so each name is registered once, here.
18
+ */
19
+ export const LEGACY_TOOLS = Object.freeze(["forget", "promote", "status", "grants", "members"])
20
+
21
+ /** What each alias became, for descriptions and the teaching. */
22
+ export const REPLACED_BY = Object.freeze({
23
+ forget: 'mem_revise with "action": "forget"',
24
+ promote: 'mem_share with "action": "copy" (and "revoke")',
25
+ status: 'mem_spaces with "action": "health"',
26
+ grants: 'mem_spaces with "action": "access"',
27
+ members: 'mem_spaces with "action": "members"',
28
+ })
29
+
30
+ /** A records-service id (contract §2.3): `rec_` and a 26-character Crockford ULID. */
31
+ const RECORD_ID = /^rec_[0-9A-HJKMNP-TV-Z]{26}$/
32
+ const SPACES = Object.freeze({ health: "health", access: "access", members: "members" })
33
+ const FORGET = "forget"
34
+
35
+ /** An alias's whole description (contract §4.1): "Deprecated: use X" and nothing more. */
36
+ export const deprecated = (name) => `Deprecated: use ${REPLACED_BY[name]}.`
37
+
38
+ /**
39
+ * @param {any} editor the gated editor
40
+ * @param {ReturnType<import("./shared.js").createToolkit>} toolkit
41
+ * @param {{
42
+ * registered: Map<string, any>,
43
+ * legacy: Map<string, any>,
44
+ * share: ReturnType<import("./share.js").createShareActions>,
45
+ * spaces: ReturnType<import("./spaces.js").createSpacesActions>,
46
+ * }} parts
47
+ */
48
+ export function registerAliases(editor, toolkit, { registered, legacy, share, spaces }) {
49
+ const { text } = toolkit
50
+ const listInput = (what) => ({
51
+ type: "object",
52
+ properties: {
53
+ action: { type: "string", enum: ["list"], description: 'Required; the only value is "list". Example: {"action": "list"}' },
54
+ space: { type: "string", description: `Space id to ${what} (control plane); defaults to the active space` },
55
+ },
56
+ required: ["action"],
57
+ additionalProperties: false,
58
+ })
59
+
60
+ // forget → revise forget
61
+ const oldForget = legacy.get("forget")
62
+ editor.add({
63
+ name: "forget",
64
+ description: deprecated("forget"),
65
+ input: oldForget?.input ?? {
66
+ type: "object",
67
+ properties: { ids: { type: "array", items: { type: "string" }, description: "Memory ids to forget (rec_…, m_…, msg-…)" } },
68
+ required: ["ids"],
69
+ additionalProperties: false,
70
+ },
71
+ options: { namespace: "mem" },
72
+ execute: async (input, context) => {
73
+ const revise = registered.get("revise")
74
+ const ids = Array.isArray(input?.ids) ? [...new Set(input.ids.map((id) => String(id).trim()).filter(Boolean))] : []
75
+ const records = ids.filter((id) => RECORD_ID.test(id))
76
+ const older = ids.filter((id) => !RECORD_ID.test(id))
77
+ const parts = []
78
+ if (String(input?.match ?? "").trim() || older.length > 0 || ids.length === 0) {
79
+ if (oldForget) {
80
+ parts.push((await oldForget.execute(records.length > 0 ? { ...input, ids: older } : input, context))?.content ?? "")
81
+ } else if (revise && older.length > 0) {
82
+ for (const id of older) parts.push((await revise.execute({ action: FORGET, id }, context))?.content ?? "")
83
+ } else {
84
+ parts.push(`not forgotten: ${String(input?.match ?? "").trim() ? "match (persona and scenario lines)" : older.join(", ") || "nothing"} needs the old forget, which this build no longer has. Use mem_revise with "action": "forget" and an id.`)
85
+ }
86
+ }
87
+ if (records.length > 0) {
88
+ if (!revise) parts.push(`not forgotten: ${records.join(", ")} ${records.length === 1 ? "is a record" : "are records"}; this build has no mem_revise.`)
89
+ else for (const id of records) parts.push((await revise.execute({ action: FORGET, id }, context))?.content ?? "")
90
+ }
91
+ return text(parts.filter(Boolean).join("\n"))
92
+ },
93
+ })
94
+
95
+ // promote → share copy, revoke
96
+ const oldPromote = legacy.get("promote")
97
+ editor.add({
98
+ name: "promote",
99
+ description: deprecated("promote"),
100
+ input: {
101
+ type: "object",
102
+ properties: {
103
+ ids: { type: "array", items: { type: "string" }, description: 'To copy: private memory ids, with rationale. Example: {"ids": ["rec_..."], "rationale": "The team needs the logging rule", "space": "space-team"}' },
104
+ name: { type: "string", description: "Ignored since 0.9 (each copy is its own record); kept so old calls still validate" },
105
+ rationale: { type: "string", description: "Why the shared space should see this; required to copy, recorded on each copy" },
106
+ space: { type: "string", description: "Shared space id (control plane); defaults to the session's bound shared space; applies to this call only" },
107
+ revoke: { type: "string", description: 'To revoke instead: a copy\'s rec_ id, or the res_ id a 0.8 share returned. Example: {"revoke": "rec_...", "space": "space-team"}' },
108
+ },
109
+ additionalProperties: false,
110
+ },
111
+ options: { namespace: "mem" },
112
+ execute: async (input, context) => {
113
+ const revoke = String(input?.revoke ?? "").trim()
114
+ if (revoke) {
115
+ if (Array.isArray(input?.ids) && input.ids.length > 0) return text("pass ids to copy, or revoke to delete a copy, not both.")
116
+ if (RECORD_ID.test(revoke)) return share.revokeCopies({ ids: [revoke], space: input?.space }, context, { legacy: true })
117
+ // A 0.8 share: the legacy registration revokes it exactly as before
118
+ // (local mode included); without one, the port in share.js does.
119
+ if (oldPromote) return oldPromote.execute(input, context)
120
+ return share.revokeLegacyShare(input, context)
121
+ }
122
+ if (!recordsOf(toolkit) && oldPromote) {
123
+ if (toolkit.config?.heldTeamWrites) return text("not held: the records service is required for approval. Nothing was shared.")
124
+ const answer = (await oldPromote.execute(input, context))?.content ?? ""
125
+ return text(`${answer}${answer ? "\n" : ""}(No records service is reachable from this build, so this was a 0.8 wiki share.)`)
126
+ }
127
+ return share.copy({ ids: input?.ids, rationale: input?.rationale, space: input?.space }, context)
128
+ },
129
+ })
130
+
131
+ editor.add({
132
+ name: "status",
133
+ description: deprecated("status"),
134
+ input: {
135
+ type: "object",
136
+ properties: { space: { type: "string", description: "Optional; no argument is needed. Space id to report on (control plane); defaults to the active space" } },
137
+ additionalProperties: false,
138
+ },
139
+ options: { namespace: "mem" },
140
+ execute: (input, context) => spaces.run({ action: SPACES.health, ...(input?.space ? { space: input.space } : {}) }, context),
141
+ })
142
+
143
+ editor.add({
144
+ name: "grants",
145
+ description: deprecated("grants"),
146
+ input: listInput("inspect"),
147
+ options: { namespace: "mem" },
148
+ execute: async (input, context) => {
149
+ if (input?.action !== "list") return text('unsupported action: use "action": "list"')
150
+ return spaces.run({ action: SPACES.access, ...(input?.space ? { space: input.space } : {}) }, context)
151
+ },
152
+ })
153
+
154
+ editor.add({
155
+ name: "members",
156
+ description: deprecated("members"),
157
+ input: listInput("inspect"),
158
+ options: { namespace: "mem" },
159
+ execute: async (input, context) => {
160
+ if (input?.action !== "list") return text('unsupported action: use "action": "list"')
161
+ return spaces.run({ action: SPACES.members, ...(input?.space ? { space: input.space } : {}) }, context)
162
+ },
163
+ })
164
+ }
@@ -17,7 +17,7 @@ import { withNote } from "../errors.js"
17
17
  /** The list answer shows at most this many items; the rest are counted. */
18
18
  const LIST_MAX = 50
19
19
  export const COMMITMENT_ACTIONS = Object.freeze(["list", "add", "update", "delete"])
20
- /** The actions that change the records file; `list` only reads. */
20
+ /** The actions that change a commitment record; `list` only reads. */
21
21
  export const COMMITMENT_WRITE_ACTIONS = Object.freeze(["add", "update", "delete"])
22
22
 
23
23
  /**
@@ -27,9 +27,11 @@ export const COMMITMENT_WRITE_ACTIONS = Object.freeze(["add", "update", "delete"
27
27
  * The invariants are in the tool, not the words: `due` must be a date or a
28
28
  * date-time with an offset, states change only through `update`, an
29
29
  * instruction is never stored, the same open commitment is not added twice,
30
- * and two agents writing at once never drop each other's records
31
- * (`records-store.js`). Commitments are private: they live in the personal
32
- * space's reserved records wiki, and writing them never asks.
30
+ * and two agents writing at once never drop each other's change (a version
31
+ * check, `records-store.js`). Commitments are private: they are records of
32
+ * kind `commitment` in the personal space (memory-v1-contracts.md §4.1), and
33
+ * writing them never asks. The first use in a space migrates the hub's old
34
+ * `commitments.json` into records once.
33
35
  *
34
36
  * @param {any} editor
35
37
  * @param {ReturnType<import("./shared.js").createToolkit>} toolkit
@@ -56,7 +58,7 @@ export function registerCommitments(editor, toolkit) {
56
58
 
57
59
  /** How a saved commitment reads back: the weekday and date, so a wrong guess is visible. */
58
60
  function describe(item, zone) {
59
- const parts = [`${item.id}: ${oneLine(item.what, 300)}`, `owner ${oneLine(item.owner ?? "user", 80)}`]
61
+ const parts = [`${item.id}${item.legacy_id ? ` (was ${item.legacy_id})` : ""}: ${oneLine(item.what, 300)}`, `owner ${oneLine(item.owner ?? "user", 80)}`]
60
62
  if (item.due) parts.push(`due ${formatDue(item.due, zone)} (${item.due})`)
61
63
  if (item.trigger) parts.push(`when ${oneLine(item.trigger, 200)}`)
62
64
  if (item.project) parts.push(`project ${item.project}`)
@@ -68,7 +70,7 @@ export function registerCommitments(editor, toolkit) {
68
70
  editor.add({
69
71
  name: "commitments",
70
72
  description:
71
- "Keep track of things someone will do, with a due date or a trigger: the person's promises and reminders (\"remind me to send the Q4 numbers on Friday\"), what the agent promised, and what others owe the person (\"Kwame will send the results by Wednesday\"). action \"add\" when it is promised, \"update\" with state \"done\" or \"cancelled\" the moment it is met or dropped, \"list\" for \"what's on my plate\" or \"what am I waiting on\". Resolve relative dates against today first and echo the weekday and date back. Commitments are private, and writing them never asks. Team work items belong in the team's tracker when one is connected; preferences, decisions, and facts belong in mem_remember; where a project stands belongs in its page's Status section (mem_wiki).",
73
+ "Track things someone will do, with a due date or a trigger. Call it for the person's promises and reminders (\"remind me to send the Q4 numbers on Friday\"), what the agent promised, and what others owe the person (\"Kwame will send the results by Wednesday\"): action \"add\" when it is promised, \"update\" with state \"done\" or \"cancelled\" the moment it is met or dropped, \"list\" for \"what's on my plate\" or \"what am I waiting on\". The ones due soon are already in context (the Due list): list only for more. Resolve relative dates against today first and echo the weekday and date back. Every answer carries the commitment's id (rec_…), which update and delete take. Commitments are private, and writing them never asks. Never store an instruction here (it is refused); team work items belong in the team's tracker when one is connected; preferences, decisions, and facts belong in mem_remember; where a project stands belongs in its page's Status section (mem_page).",
72
74
  input: {
73
75
  type: "object",
74
76
  properties: {
@@ -78,7 +80,7 @@ export function registerCommitments(editor, toolkit) {
78
80
  description:
79
81
  'Required. Read-only: list. Writes: add (needs what), update and delete (need id). Example: {"action": "add", "what": "Send the Q4 numbers to Ama", "owner": "user", "due": "2026-11-06"}',
80
82
  },
81
- id: { type: "string", description: "The commitment id (cmt_…) for update and delete, from list or add" },
83
+ id: { type: "string", description: "The commitment id (rec_…, or a cmt_… id from before 0.9) for update and delete, from list or add" },
82
84
  what: {
83
85
  type: "string",
84
86
  description: "What will be done, in plain words starting with a verb (\"Send the Q4 numbers to Ama\"), at most 300 characters. Required for add",
@@ -151,7 +153,7 @@ export function registerCommitments(editor, toolkit) {
151
153
  }
152
154
 
153
155
  const id = String(input?.id ?? "").trim()
154
- if (action !== "add" && !id) return text(`id is required for ${action}: the cmt_… id from list or add`)
156
+ if (action !== "add" && !id) return text(`id is required for ${action}: the rec_… id from list or add`)
155
157
  if (action === "add" && id) return text("add makes a new id; to change a commitment, use update with its id")
156
158
  if (action !== "update" && input?.state !== undefined) return text("state is set with update; add always starts open")
157
159
 
@@ -188,7 +190,7 @@ export function registerCommitments(editor, toolkit) {
188
190
  if (action === "add" && result.unchanged) {
189
191
  return text(`already open, not added again: ${describe(result.item, zone)}`)
190
192
  }
191
- if (action === "delete") return text(`deleted ${oneLine(id, 40)}: ${oneLine(result.item.what, 300)}. It is gone from this space's records.`)
193
+ if (action === "delete") return text(`deleted ${oneLine(result.item.id || id, 40)}: ${oneLine(result.item.what, 300)}. It is gone from this space's records.`)
192
194
  const verb = action === "add" ? "added" : "updated"
193
195
  const lines = [`${verb} ${describe(result.item, zone)}`]
194
196
  if (action === "add") {
@@ -202,6 +204,7 @@ export function registerCommitments(editor, toolkit) {
202
204
  )
203
205
  }
204
206
  if (!result.item.due && !result.item.trigger) lines.push("It has no due date or trigger, so it appears only in lists, not in the Due list.")
207
+ lines.push(`When it is met or dropped: mem_commitments {"action": "update", "id": "${result.item.id}", "state": "done"} (or "cancelled").`)
205
208
  }
206
209
  if (result.item.state !== "open") lines.push(`Closed items are kept ${CLOSED_RETENTION_DAYS} days, then dropped.`)
207
210
  return text(lines.join("\n"))
@@ -0,0 +1,82 @@
1
+ import { createHash } from "node:crypto"
2
+ import { asVerifiedView } from "../credentials.js"
3
+ import { oneLine, redactSecrets } from "../util.js"
4
+ import { callRecords, RECORD_ID } from "./records-kit.js"
5
+
6
+ const hash = (value) => createHash("sha256").update(value).digest("hex")
7
+ const SPACE = /^[A-Za-z0-9_.-]{1,128}$/
8
+
9
+ /** A retry of one engine tool call has the same key; a distinct call does not. */
10
+ function writeKey(context, space) {
11
+ if (![context?.sessionID, context?.messageID, context?.id].every((value) => typeof value === "string" && value)) throw new Error("held write needs a stable session, message and tool call id")
12
+ return `hw_${hash(JSON.stringify([space, context.sessionID, context.messageID, context.id]))}`
13
+ }
14
+
15
+ /** Hold only the submitted records, in the caller's personal space. */
16
+ export async function holdTeamWrite(toolkit, context, spaceContext, records) {
17
+ if (!spaceContext?.space_id || !spaceContext?.space_name || spaceContext.space_kind !== "shared") throw new Error("held write needs a named shared space from control")
18
+ if (!Array.isArray(records) || records.length === 0 || records.length > 20) throw new Error("held write needs one to twenty records")
19
+ const resolved = await toolkit.resolvePrivateSpace({}, context)
20
+ if (resolved.invalid || resolved.error) throw new Error(resolved.invalid || resolved.error)
21
+ const personal = resolved.context
22
+ if (!personal || personal.space_kind !== "personal" || personal.space_id !== personal.personal_space_id || personal.role !== "owner" || !personal.user_id || personal.user_id !== spaceContext.user_id) throw new Error("control did not confirm the author's personal space")
23
+ const scoped = toolkit.scopeFor(personal, { agent: context?.agent })
24
+ const stats = await callRecords(toolkit, "space.stats", {}, personal, scoped)
25
+ if (stats?.idempotent_put !== true || stats?.held_receipts !== true) throw new Error("the personal records service does not support held writes")
26
+ const idempotencyKey = writeKey(context, spaceContext.space_id)
27
+ const content = String(records[0]?.body ?? "")
28
+ const preview = oneLine(redactSecrets(content), 400)
29
+ const record = {
30
+ kind: "proposal", type: "team_write", title: "Team write awaiting approval", body: JSON.stringify({ records }),
31
+ fields: { space_id: spaceContext.space_id, space_name: oneLine(spaceContext.space_name, 200), preview, key: idempotencyKey },
32
+ source: context?.sessionID ? { session: String(context.sessionID) } : {},
33
+ }
34
+ const answer = await callRecords(toolkit, "records.put", { record, idempotency_key: idempotencyKey }, personal, scoped)
35
+ if (!RECORD_ID.test(String(answer?.record?.id ?? ""))) throw new Error("the records service did not confirm the proposal")
36
+ if (answer.record.status === "applied") return `Already approved and saved in ${oneLine(spaceContext.space_name, 200)}; no new write was made.`
37
+ if (answer.record.status === "applied_private") return "Already saved privately; no new write was made."
38
+ if (answer.record.status === "declined") return "The person declined this write; nothing was saved and it must not be retried elsewhere."
39
+ if (answer.record.status === "accepting") return "Approval is being completed; retry the same acceptance."
40
+ return `Held for approval in the Inbox for ${oneLine(spaceContext.space_name, 200)}; not saved as a memory or page yet.`
41
+ }
42
+
43
+ /**
44
+ * Decide an Inbox proposal. `caller.speaker` must be the host-injected view
45
+ * speaker, never a value supplied by the page; its token scopes every call.
46
+ * `key` is `<personal-space>:<proposal-id>`, supplied by the Inbox.
47
+ */
48
+ export async function decideProposal({ key, decision, caller }) {
49
+ const runtime = caller?.runtime
50
+ const speaker = caller?.speaker
51
+ if (!runtime?.control || typeof speaker !== "string" || !/^view_[A-Za-z0-9_-]{1,123}$/.test(speaker)) throw new Error("a host-authenticated speaker and control plane are required")
52
+ const [space, id, extra] = String(key ?? "").split(":")
53
+ if (extra !== undefined || !SPACE.test(space ?? "") || !RECORD_ID.test(id ?? "")) throw new Error("invalid proposal key")
54
+ if (!["accept", "private", "decline"].includes(decision)) throw new Error("invalid decision")
55
+ return asVerifiedView(speaker, async () => {
56
+ if (typeof runtime.availability === "function" && await runtime.availability()) throw new Error("Memory is unavailable for this speaker")
57
+ const personal = await runtime.resolveContext({ space })
58
+ if (personal?.space_id !== space || personal?.space_kind !== "personal" || personal?.personal_space_id !== space || personal?.role !== "owner" || !personal.user_id) throw new Error("the caller's personal space could not be verified")
59
+ const options = { space }
60
+ const read = await runtime.recordsClient.call("records.get", { ids: [id] }, options)
61
+ const proposal = read?.records?.[0]
62
+ if (!proposal || proposal.kind !== "proposal" || proposal.type !== "team_write") throw new Error("team write proposal not found")
63
+ if (proposal.author?.user !== personal.user_id) throw new Error("only the proposal's author can decide")
64
+ let shared
65
+ if (decision === "accept" && ["proposed", "accepting"].includes(proposal.status)) {
66
+ shared = await runtime.resolveContext({ space: proposal.fields.space_id })
67
+ if (shared?.space_id !== proposal.fields.space_id || shared?.space_kind !== "shared" || shared?.user_id !== personal.user_id || !["editor", "admin", "owner"].includes(String(shared.role ?? "").toLowerCase())) throw new Error("the author no longer has write access to the target shared space")
68
+ }
69
+ let answer = await runtime.recordsClient.call("review.decide", { id, decision, base_version: proposal.version }, options)
70
+ const held = answer?.proposal
71
+ if (decision !== "accept" || held?.status !== "accepting") return answer
72
+ if (!shared) throw new Error("the shared space was not verified")
73
+ const target = { space: shared.space_id }
74
+ const stats = await runtime.recordsClient.call("space.stats", {}, target)
75
+ if (stats?.held_receipts !== true) throw new Error("the shared records service cannot verify held acceptance")
76
+ const records = JSON.parse(held.body).records
77
+ const written = await runtime.recordsClient.call("records.put", { held_batch: { key: held.fields.accept_key, records } }, target)
78
+ if (typeof written?.receipt !== "string") throw new Error("the shared write was not confirmed; retry acceptance")
79
+ answer = await runtime.recordsClient.call("review.decide", { id, decision: "accept", base_version: held.version, receipt: written.receipt }, options)
80
+ return answer
81
+ })
82
+ }