Skip to content

Where agent teams gather. Cross-platform team chat where AI agents are first-class teammates — with cloud or bring-your-own (Claude Code / Codex) brains.

TypeScript

Scope agent memory to the current project. (#54)

Ri Liu12d19ada8e30
diff --git a/docs/COORDINATION.md b/docs/COORDINATION.md
index 8c1087e..08d055c 100644
--- a/docs/COORDINATION.md
+++ b/docs/COORDINATION.md
@@ -722,11 +722,21 @@ The recurring methodology that paid off, in priority order:
minutes. Reading the upstream's logs (`account_select_failed: no
available accounts`) named the actual root cause.
4. **Memory files are state too.** Agents persist learnings to
- `~/.cumora/agents/<id>/memory/<file>.md`. Useful, but they can ENCODE
- the wrong lesson from a single weird game (e.g. an explicit-cap counting
- game becomes a universal "never lap" rule). Wiping the overfit files is
- the surgical move; the rest of the agent's notes stay intact. **Don't
- delete files you didn't audit first** — read each one's frontmatter.
+ `~/.cumora/agents/<id>/memory/` (global identity, indexed by
+ `MEMORY.md`) and `memory/projects/<projectId>/` (unpinned work facts
+ of that project). Useful, but they can ENCODE the wrong lesson from a
+ single weird game (e.g. an explicit-cap counting game becomes a
+ universal "never lap" rule).
+
+ Cross-group bleed of *work* facts is a scoping bug, not a wipe bug:
+ cloud `loadMemory` and the BYOA wake digest share `memory-scope.ts`
+ and inject **global + the current project only** (pinned / identity /
+ persona / skills / climate stay global; a conversation with no project
+ gets global memory only). Existing files stay global — we do not
+ guess-migrate old notes into a project. Wiping an overfit file is
+ still the surgical move when the *lesson* is wrong; the rest of the
+ agent's notes stay intact. **Don't delete files you didn't audit
+ first** — read each one's frontmatter.
The breakthrough moment was the user's reframing: *"AI-native means making
AI agents behave like real humans collaborating. Don't be limited in
@@ -768,6 +778,7 @@ fallback) and absent-member coverage (team-adapts principle).
| File | Role |
|---|---|
| `server/src/agents/glance-protocol.ts` | The `GLANCE_YIELD_RULES` const, shared verbatim BYOA ↔ cloud. **Edit minimally.** Holds the three principles (cap-clarification, count-items, team-adapts). |
+| `server/src/agents/memory-scope.ts` | Shared write/filter contract for project-scoped memory (cloud `loadMemory` + BYOA `memoryDigest`). Pure; unit-tested without Postgres. |
| `server/src/agents/computer/daemon.ts` | `standingPrompt()` (the BYOA system prompt), `chatDelta()` / `agendaDelta()` (per-turn briefs), `runTurn()` (the busy/triage/sem/spawn flow), `BigBrainSemaphore`, `AdaptivePacer`, cooldown. |
| `server/src/agents/triage-core.ts` | Small-brain triage instructions + parsing. The ▸YOU rule lives here. |
| `server/src/agents/cli.ts` | `cmdReply` server-side: seen-cursor freshness preflight, pre-INSERT verbatim-dup, atomic in-transaction verbatim-dup + sequence-claim. Plus `doc create` / `calendar create` recently-created same-title dedup (HELD, `--force` hold-token-gated). |
diff --git a/server/src/__tests__/agents-memory-scope.test.ts b/server/src/__tests__/agents-memory-scope.test.ts
new file mode 100644
index 0000000..435f158
--- /dev/null
+++ b/server/src/__tests__/agents-memory-scope.test.ts
@@ -0,0 +1,274 @@
+/**
+ * Project-scoped memory contract (issue #45). Pure helpers — no Postgres,
+ * no Redis. Cloud `loadMemory` and the BYOA `memoryDigest` both call these.
+ *
+ * Run: node --import tsx --test server/src/__tests__/agents-memory-scope.test.ts
+ */
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+import {
+ GLOBAL_MEMORY_INDEX,
+ asMemorySource,
+ buildMemoryMeta,
+ buildMemorySource,
+ clipMemoryDigest,
+ composeMemoryDigest,
+ conversationHeader,
+ filterMemories,
+ memoryIndexPathsForScope,
+ memoryVisibleInScope,
+ memoryWritePath,
+ parseMemoryPath,
+ pickWriteProvenance,
+ projectIdFromMemoryPath,
+ projectMemoryIndexPath,
+ rowProjectId,
+ uniqueProjectIds,
+} from '../agents/memory-scope.js'
+
+const P = 'proj-paper'
+const Q = 'proj-ppt'
+const scopeP = { projectIds: [P] }
+const scopeQ = { projectIds: [Q] }
+const scopeNone = { projectIds: [] as string[] }
+const scopeBoth = { projectIds: [P, Q] }
+
+const pinned = { pinned: true, source: { conversationId: 'c-a', projectId: P } }
+const globalLegacy = { pinned: false, source: null }
+const globalExplicit = { pinned: false, source: { conversationId: 'c-x', projectId: null } }
+const workP = { pinned: false, source: { conversationId: 'c-a', projectId: P } }
+const workQ = { pinned: false, source: { conversationId: 'c-b', projectId: Q } }
+
+// ── truth table ────────────────────────────────────────────────────────
+
+test('pinned memory is visible in every scope, including no-project', () => {
+ assert.equal(memoryVisibleInScope(pinned, 'memory/note/p.md', scopeP), true)
+ assert.equal(memoryVisibleInScope(pinned, 'memory/note/p.md', scopeQ), true)
+ assert.equal(memoryVisibleInScope(pinned, 'memory/note/p.md', scopeNone), true)
+ assert.equal(memoryVisibleInScope(pinned, 'memory/projects/' + P + '/note/p.md', scopeQ), true)
+})
+
+test('legacy source:null (all existing memories) stays GLOBAL', () => {
+ assert.equal(memoryVisibleInScope(globalLegacy, 'memory/note/old.md', scopeP), true)
+ assert.equal(memoryVisibleInScope(globalLegacy, 'memory/note/old.md', scopeNone), true)
+ assert.equal(memoryVisibleInScope(undefined, 'memory/MEMORY.md', scopeQ), true)
+})
+
+test('unpinned write with null projectId is GLOBAL', () => {
+ assert.equal(memoryVisibleInScope(globalExplicit, 'memory/fact/n.md', scopeP), true)
+ assert.equal(memoryVisibleInScope(globalExplicit, 'memory/fact/n.md', scopeNone), true)
+})
+
+test('unpinned project-P work is visible only when P is in scope', () => {
+ assert.equal(memoryVisibleInScope(workP, 'memory/decision/d.md', scopeP), true)
+ assert.equal(memoryVisibleInScope(workP, 'memory/decision/d.md', scopeQ), false)
+ assert.equal(memoryVisibleInScope(workP, 'memory/decision/d.md', scopeNone), false)
+ assert.equal(memoryVisibleInScope(workP, 'memory/decision/d.md', scopeBoth), true)
+})
+
+test('path memory/projects/<id>/ is enough to scope even if meta.source is empty', () => {
+ const pathP = 'memory/projects/' + P + '/note/x.md'
+ assert.equal(memoryVisibleInScope({ pinned: false, source: null }, pathP, scopeP), true)
+ assert.equal(memoryVisibleInScope({ pinned: false, source: null }, pathP, scopeQ), false)
+ assert.equal(memoryVisibleInScope({ pinned: false, source: null }, pathP, scopeNone), false)
+})
+
+test('filterMemories drops other-project unpinned rows and keeps pinned + global', () => {
+ const rows = [
+ { path: 'memory/note/pin.md', meta: pinned },
+ { path: 'memory/note/old.md', meta: globalLegacy },
+ { path: 'memory/decision/p.md', meta: workP },
+ { path: 'memory/decision/q.md', meta: workQ },
+ ]
+ const kept = filterMemories(rows, scopeP).map((r) => r.path)
+ assert.deepEqual(kept, ['memory/note/pin.md', 'memory/note/old.md', 'memory/decision/p.md'])
+ assert.deepEqual(
+ filterMemories(rows, scopeNone).map((r) => r.path),
+ ['memory/note/pin.md', 'memory/note/old.md'],
+ )
+})
+
+// ── write provenance ───────────────────────────────────────────────────
+
+test('pickWriteProvenance: path memory/projects/<id> wins', () => {
+ const s = pickWriteProvenance({
+ path: 'memory/projects/' + P + '/note/x.md',
+ explicitProjectId: Q,
+ thinking: [{ conversationId: 'c-b', projectId: Q }],
+ })
+ assert.equal(s.projectId, P)
+})
+
+test('pickWriteProvenance: explicit conversation + matching thinking row', () => {
+ const s = pickWriteProvenance({
+ explicitConversationId: 'c-a',
+ thinking: [
+ { conversationId: 'c-a', projectId: P },
+ { conversationId: 'c-b', projectId: Q },
+ ],
+ })
+ assert.deepEqual(s, { conversationId: 'c-a', projectId: P })
+})
+
+test('pickWriteProvenance: a single thinking conversation is unambiguous', () => {
+ const s = pickWriteProvenance({
+ thinking: [{ conversationId: 'c-a', projectId: P }],
+ })
+ assert.deepEqual(s, { conversationId: 'c-a', projectId: P })
+})
+
+test('pickWriteProvenance: several rooms of the SAME project stamp that project', () => {
+ const s = pickWriteProvenance({
+ thinking: [
+ { conversationId: 'c-a', projectId: P },
+ { conversationId: 'c-a2', projectId: P },
+ ],
+ })
+ assert.equal(s.projectId, P)
+ assert.equal(s.conversationId, null, 'two convos — do not pick one at random')
+})
+
+test('pickWriteProvenance: mixed projects fall back to GLOBAL (do not guess)', () => {
+ const s = pickWriteProvenance({
+ thinking: [
+ { conversationId: 'c-a', projectId: P },
+ { conversationId: 'c-b', projectId: Q },
+ ],
+ })
+ assert.deepEqual(s, { conversationId: null, projectId: null })
+})
+
+test('pickWriteProvenance: no-project thinking conversation stays global', () => {
+ const s = pickWriteProvenance({
+ thinking: [{ conversationId: 'c-dm', projectId: null }],
+ })
+ assert.deepEqual(s, { conversationId: 'c-dm', projectId: null })
+})
+
+test('buildMemoryMeta records source instead of null', () => {
+ const meta = buildMemoryMeta({
+ path: 'memory/note/x.md',
+ kind: 'note',
+ conversationId: 'c-a',
+ projectId: P,
+ })
+ assert.equal(meta.type, 'memory')
+ assert.equal(meta.pinned, false)
+ assert.deepEqual(meta.source, { conversationId: 'c-a', projectId: P })
+})
+
+test('memoryWritePath: global vs project layout', () => {
+ assert.equal(memoryWritePath('fact', 'mem-1'), 'memory/fact/mem-1.md')
+ assert.equal(memoryWritePath('fact', 'mem-1', P), 'memory/projects/' + P + '/fact/mem-1.md')
+})
+
+// ── path parsing / BYOA index selection ────────────────────────────────
+
+test('parseMemoryPath understands both layouts', () => {
+ assert.deepEqual(parseMemoryPath('memory/note/mem-abc.md'), {
+ kind: 'note', id: 'mem-abc', projectId: null,
+ })
+ assert.deepEqual(parseMemoryPath('memory/projects/' + P + '/decision/mem-xyz.md'), {
+ kind: 'decision', id: 'mem-xyz', projectId: P,
+ })
+ assert.deepEqual(parseMemoryPath(GLOBAL_MEMORY_INDEX), {
+ kind: 'index', id: 'MEMORY', projectId: null,
+ })
+ assert.deepEqual(parseMemoryPath(projectMemoryIndexPath(P)), {
+ kind: 'index', id: 'MEMORY', projectId: P,
+ })
+})
+
+test('memoryIndexPathsForScope: existing MEMORY.md stays global; projects add their own', () => {
+ assert.deepEqual(memoryIndexPathsForScope([]), [GLOBAL_MEMORY_INDEX])
+ assert.deepEqual(memoryIndexPathsForScope([P]), [
+ GLOBAL_MEMORY_INDEX,
+ 'memory/projects/' + P + '/MEMORY.md',
+ ])
+ assert.deepEqual(memoryIndexPathsForScope([P, P, Q]), [
+ GLOBAL_MEMORY_INDEX,
+ 'memory/projects/' + P + '/MEMORY.md',
+ 'memory/projects/' + Q + '/MEMORY.md',
+ ])
+})
+
+test('composeMemoryDigest: lone global index is byte-identical (clipped)', () => {
+ const body = '• paper review is NOT in this file'
+ assert.equal(
+ composeMemoryDigest([{ label: GLOBAL_MEMORY_INDEX, body }]),
+ body,
+ )
+})
+
+test('composeMemoryDigest: concatenates global + current project only', () => {
+ const digest = composeMemoryDigest([
+ { label: GLOBAL_MEMORY_INDEX, body: 'I am nova.' },
+ { label: projectMemoryIndexPath(P), body: 'paper-review decision: accept' },
+ { label: projectMemoryIndexPath(Q), body: 'ppt deck outline' },
+ ])
+ assert.match(digest, /I am nova/)
+ assert.match(digest, /paper-review decision: accept/)
+ assert.match(digest, /ppt deck outline/)
+ assert.match(digest, /## global/)
+ assert.match(digest, new RegExp('## project ' + P))
+})
+
+test('clipMemoryDigest truncates with a recovery hint', () => {
+ const out = clipMemoryDigest('abcdefghij', 4)
+ assert.equal(out.startsWith('abcd'), true)
+ assert.match(out, /truncated/)
+})
+
+test('conversationHeader: project-less is unchanged; Project: sits above Topic:', () => {
+ assert.equal(
+ conversationHeader({
+ conversation_id: 'c1',
+ conversation_kind: 'group',
+ conversation_title: 'general',
+ conversation_topic: 'chatter',
+ }),
+ '# c1 [group] "general"\n Topic: chatter',
+ )
+ assert.equal(
+ conversationHeader({
+ conversation_id: 'c1',
+ conversation_kind: 'group',
+ conversation_title: 'papers',
+ conversation_topic: 'review',
+ project_name: 'Paper Review',
+ }),
+ '# c1 [group] "papers"\n Project: Paper Review\n Topic: review',
+ )
+})
+
+test('uniqueProjectIds drops null/empty/dupes and preserves order', () => {
+ assert.deepEqual(uniqueProjectIds([P, null, '', P, Q, undefined]), [P, Q])
+})
+
+test('rowProjectId prefers meta over path', () => {
+ assert.equal(rowProjectId(workP, 'memory/note/x.md'), P)
+ assert.equal(rowProjectId(null, 'memory/projects/' + Q + '/note/x.md'), Q)
+ assert.equal(rowProjectId(globalLegacy, 'memory/note/x.md'), null)
+})
+
+test('buildMemorySource defaults both fields to null (global)', () => {
+ assert.deepEqual(buildMemorySource({}), { conversationId: null, projectId: null })
+})
+
+test('projectIdFromMemoryPath ignores non-project memory paths', () => {
+ assert.equal(projectIdFromMemoryPath('memory/note/x.md'), null)
+ assert.equal(projectIdFromMemoryPath('skills/foo/SKILL.md'), null)
+})
+
+test('asMemorySource fills missing fields with null', () => {
+ assert.deepEqual(asMemorySource(undefined), null)
+ assert.deepEqual(asMemorySource({}), { conversationId: null, projectId: null })
+ assert.deepEqual(asMemorySource({ projectId: P }), { conversationId: null, projectId: P })
+})
+
+test('no-project / empty scope list hides unpinned project work (memory list default)', () => {
+ assert.equal(memoryVisibleInScope(workP, 'memory/decision/d.md', scopeNone), false)
+ assert.equal(memoryVisibleInScope(workQ, 'memory/decision/q.md', scopeNone), false)
+ assert.equal(memoryVisibleInScope(globalLegacy, 'memory/note/old.md', scopeNone), true)
+ assert.equal(memoryVisibleInScope(pinned, 'memory/note/p.md', scopeNone), true)
+})
diff --git a/server/src/agents/cli.ts b/server/src/agents/cli.ts
index c4dc3ea..f41ef6f 100644
--- a/server/src/agents/cli.ts
+++ b/server/src/agents/cli.ts
@@ -14,6 +14,13 @@ import { storage, freshenAttachmentUrl, type StoredAttachment } from '../storage
import { env } from '../env.js'
import type { CliResult, CliSideEffect } from './cli-result.js'
import { stripLoneSurrogates } from './text-safety.js'
+import {
+ asMemorySource,
+ memoryVisibleInScope,
+ memoryWritePath,
+ parseMemoryPath,
+} from './memory-scope.js'
+import { memoryMetaForWrite, resolveMemoryWriteSource } from './memory-write.js'
// Every CLI result flows through ok()/err(), so scrubbing lone UTF-16 surrogates
// here means CLI output (read by agents as tool results) can never carry a split
@@ -186,8 +193,8 @@ INTROSPECTION:
participants-status
PRIVATE TO EACH AGENT (these write/read state owned by --as):
- memory list [--as <id>] [--about <subject>] [--kind <kind>] [--limit N]
- memory note <body> [--as <id>] [--about <subject>] [--kind <kind>]
+ memory list [--as <id>] [--about <subject>] [--kind <kind>] [--limit N] [--in <convo>] [--all]
+ memory note <body> [--as <id>] [--about <subject>] [--kind <kind>] [--in <convo>]
memory pin <id>
memory delete <id>
@@ -3581,14 +3588,16 @@ function normalizeMemoryKind(raw: unknown): MemoryKind {
}
/** Memory is stored as files inside the agent's workspace under
- * `memory/<kind>/<id>.md`. Structured fields (`kind`, `about`, `pinned`,
- * `source`, `createdAt`) live in the `meta` JSONB column. Reads use a
- * `path LIKE 'memory/%'` prefix plus a partial JSONB index on
- * `meta->>'about'` for the common `--about <subject>` filter. See
- * migrate.ts for the one-shot copy from the legacy `agent_memory` table. */
+ * `memory/<kind>/<id>.md` (global) or `memory/projects/<projectId>/<kind>/<id>.md`.
+ * Structured fields (`kind`, `about`, `pinned`, `source`, `createdAt`) live
+ * in the `meta` JSONB column. New writes stamp `source.conversationId` /
+ * `source.projectId` (issue #45); existing `source: null` rows stay GLOBAL
+ * — we never guess-migrate them into a project. See memory-scope.ts. */
async function cmdMemory(parsed: ParsedArgs): Promise<CliResult> {
const op = parsed.positional[0]
const me = resolveAs(parsed)
+ const explicitConvo = (typeof parsed.flags.in === 'string' ? parsed.flags.in : null)
+ ?? (typeof parsed.flags.conversation === 'string' ? parsed.flags.conversation : null)
if (op === 'list') {
const params: unknown[] = [me]
let where = `agent_id = $1 AND path LIKE 'memory/%'`
@@ -3599,10 +3608,14 @@ async function cmdMemory(parsed: ParsedArgs): Promise<CliResult> {
if (parsed.flags.kind) {
const k = normalizeMemoryKind(parsed.flags.kind)
params.push(`memory/${k}/%`)
- where += ` AND path LIKE $${params.length}`
+ params.push(`memory/projects/%/${k}/%`)
+ where += ` AND (path LIKE $${params.length - 1} OR path LIKE $${params.length})`
}
const limit = Math.min(100, Math.max(1, Number(parsed.flags.limit ?? 20)))
- params.push(limit)
+ // Fetch extra rows so in-memory project filtering can still fill `limit`.
+ // `--all` is the only path that skips isolation.
+ const fetchLimit = Boolean(parsed.flags.all) ? limit : Math.min(500, Math.max(limit * 10, 100))
+ params.push(fetchLimit)
const limitParam = `$${params.length}`
const { rows } = await pool.query<{
path: string; body: string; meta: Record<string, unknown> | null; updated_at: string
@@ -3613,36 +3626,58 @@ async function cmdMemory(parsed: ParsedArgs): Promise<CliResult> {
LIMIT ${limitParam}`,
params,
)
- // Path segment encodes the kind; file stem is the id (sans `.md`).
const parsed_rows = rows.map((r) => {
- const segs = r.path.split('/')
- const kind = segs[1] ?? 'note'
- const id = (segs[2] ?? '').replace(/\.md$/, '')
+ const parsedPath = parseMemoryPath(r.path)
+ const kind = parsedPath?.kind ?? 'note'
+ const id = parsedPath?.id ?? ''
const about = (r.meta?.about as string | undefined) ?? null
const pinned = Boolean(r.meta?.pinned)
- return { id, kind, about, body: r.body, pinned, created_at: r.updated_at }
+ const source = asMemorySource(r.meta?.source)
+ return {
+ id, kind, about, body: r.body, pinned, created_at: r.updated_at,
+ path: r.path,
+ projectId: parsedPath?.projectId ?? source?.projectId ?? null,
+ meta: r.meta,
+ source,
+ }
})
- if (parsed.flags.json) return ok(JSON.stringify(parsed_rows, null, 2))
- if (parsed_rows.length === 0) return ok(`(${me} has no memory yet)`)
+ const showAll = Boolean(parsed.flags.all)
+ let scoped = parsed_rows
+ if (!showAll) {
+ const writeSource = await resolveMemoryWriteSource(me, { conversationId: explicitConvo })
+ const projectIds = writeSource.projectId ? [writeSource.projectId] : []
+ scoped = parsed_rows.filter((r) => memoryVisibleInScope(
+ { pinned: r.pinned, source: r.source },
+ r.path,
+ { projectIds },
+ ))
+ scoped = scoped.slice(0, limit)
+ }
+ if (parsed.flags.json) return ok(JSON.stringify(scoped.map(({ meta, path, ...rest }) => rest), null, 2))
+ if (scoped.length === 0) return ok(`(${me} has no memory yet)`)
return ok([
- `${parsed_rows.length} memory record(s) for ${me}:`,
+ `${scoped.length} memory record(s) for ${me}:`,
'',
- ...parsed_rows.map((m) => {
+ ...scoped.map((m) => {
const t = new Date(m.created_at).toLocaleDateString()
const pin = m.pinned ? '★ ' : ' '
- return ` ${pin}[${m.id.slice(0, 10)}] ${m.kind.padEnd(11)} ${(m.about ?? '-').padEnd(10)} ${t}\n ${m.body.slice(0, 280).replace(/\n/g, ' \\n ')}`
+ const proj = m.projectId ? ` proj:${m.projectId}` : ' global'
+ return ` ${pin}[${m.id.slice(0, 10)}] ${m.kind.padEnd(11)} ${(m.about ?? '-').padEnd(10)} ${t}${proj}\n ${m.body.slice(0, 280).replace(/\n/g, ' \\n ')}`
}),
].join('\n'))
}
if (op === 'note') {
const body = parsed.positional[1]
- if (!body) return err('usage: memory note <body> [--about subject] [--kind kind] [--as id]')
+ if (!body) return err('usage: memory note <body> [--about subject] [--kind kind] [--in convo] [--as id]')
const kind = normalizeMemoryKind(parsed.flags.kind ?? 'observation')
const about = parsed.flags.about ? String(parsed.flags.about) : null
const id = `mem-${randomUUID().slice(0, 12)}`
- const path = `memory/${kind}/${id}.md`
+ const source = await resolveMemoryWriteSource(me, { conversationId: explicitConvo })
+ const path = memoryWritePath(kind, id, source.projectId)
const tenant = await agentCompany(me)
- const meta = { type: 'memory', kind, about, pinned: false, source: null, createdAt: new Date().toISOString() }
+ const meta = await memoryMetaForWrite(me, {
+ path, kind, about, conversationId: explicitConvo, projectId: source.projectId,
+ })
// Compute the embedding before INSERT so the row lands with both
// body + vector in one shot. `embedText` returns null on failure
// (rate limit, network blip, etc.) — we still write the row so the
@@ -3679,9 +3714,6 @@ async function cmdMemory(parsed: ParsedArgs): Promise<CliResult> {
if (op === 'pin') {
const id = parsed.positional[1]
if (!id) return err('usage: memory pin <id>')
- // Toggle the `pinned` flag in meta JSONB. `||` on jsonb merges keys
- // (right-hand side wins), so we read+rewrite by setting just that
- // key and let Postgres handle the rest.
const r = await pool.query<{ meta: Record<string, unknown> }>(
`UPDATE agent_workspace
SET meta = COALESCE(meta, '{}'::jsonb)
@@ -3897,10 +3929,18 @@ async function cmdWorkspace(parsed: ParsedArgs): Promise<CliResult> {
const path = parsed.positional[1]
const body = parsed.positional.slice(2).join(' ')
if (!path || !body) return err('usage: workspace write <path> <body> [--as id]')
+ const memMeta = path.startsWith('memory/')
+ ? await memoryMetaForWrite(me, { path })
+ : null
await pool.query(
- `INSERT INTO agent_workspace (agent_id, path, body, company_id, updated_at) VALUES ($1, $2, $3, $4, NOW())
- ON CONFLICT (agent_id, path) DO UPDATE SET body = EXCLUDED.body, company_id = EXCLUDED.company_id, updated_at = NOW()`,
- [me, path, body, tenant],
+ `INSERT INTO agent_workspace (agent_id, path, body, meta, company_id, updated_at)
+ VALUES ($1, $2, $3, $4::jsonb, $5, NOW())
+ ON CONFLICT (agent_id, path) DO UPDATE
+ SET body = EXCLUDED.body,
+ company_id = EXCLUDED.company_id,
+ meta = COALESCE(agent_workspace.meta, EXCLUDED.meta),
+ updated_at = NOW()`,
+ [me, path, body, memMeta ? JSON.stringify(memMeta) : null, tenant],
)
return ok(`wrote ${path} (${body.length} chars)`, [{
event: 'workspace.file_written',
diff --git a/server/src/agents/computer/daemon.ts b/server/src/agents/computer/daemon.ts
index 7d4876f..99167a6 100644
--- a/server/src/agents/computer/daemon.ts
+++ b/server/src/agents/computer/daemon.ts
@@ -32,6 +32,14 @@ import { usageFromClaude, type TokenUsage } from '../cost.js'
import { parseTriage, finalizeTriage, isRateLimited } from '../triage-core.js'
import { GLANCE_YIELD_RULES } from '../glance-protocol.js'
import { SKYPE_EMOTICONS_GUIDE } from '../skype-emoticons.js'
+import {
+ composeMemoryDigest,
+ conversationHeader,
+ memoryIndexPathsForScope,
+ uniqueProjectIds,
+} from '../memory-scope.js'
+
+export { conversationHeader }
const CONFIG_DIR = join(homedir(), '.cumora')
const CONFIG_PATH = join(CONFIG_DIR, 'computer.json')
@@ -319,6 +327,7 @@ interface RuntimeInboxResponse {
conversation_kind?: string
conversation_title?: string
conversation_topic?: string | null
+ project_id?: string | null
project_name?: string | null
author_name?: string
author_kind?: string
@@ -351,31 +360,6 @@ const DIGEST_MAX_MESSAGE_LINES = 40
* shown, exactly as before.
*
* Exported for tests — pure, no server and no engine. */
-/** The per-conversation header the wake digest opens each group with: the id,
- * its kind/title, the project it belongs to, and the topic it exists for.
- *
- * Project matters as much as topic here. An agent that sits in several project
- * groups otherwise cannot tell them apart from the digest alone, so everything
- * it has learned reads as one undifferentiated context — which is how work from
- * one project ends up quoted as background in another. The cloud turn has
- * always rendered a project line; this is the BYOA counterpart.
- *
- * Exported for tests — pure, no server and no engine. */
-export function conversationHeader(row: {
- conversation_id?: string
- conversation_kind?: string
- conversation_title?: string
- project_name?: string | null
- conversation_topic?: string | null
-}): string {
- const kind = row.conversation_kind ? ` [${row.conversation_kind}]` : ''
- const title = row.conversation_title ? ` "${row.conversation_title}"` : ''
- let head = `# ${row.conversation_id}${kind}${title}`
- if (row.project_name) head += `\n Project: ${row.project_name}`
- if (row.conversation_topic) head += `\n Topic: ${row.conversation_topic}`
- return head
-}
-
export function renderInboxDigest(
byConvo: Map<string, { head: string; msgs: string[] }>,
budget = DIGEST_MAX_MESSAGE_LINES,
@@ -1349,16 +1333,19 @@ class AgentRunner {
return [...ids]
}
- /** Preload the memory index (memory/MEMORY.md) so it's ALWAYS in the wake
- * prompt — the lightweight BYOA analog of the cloud agent's RAG memory
- * preload. We inject only the small index; the agent opens detail files on
- * demand. Capped so a runaway index can't blow up the prompt. */
- private async memoryDigest(): Promise<string> {
- try {
- const txt = (await readFile(join(this.home, 'memory', 'MEMORY.md'), 'utf8')).trim()
- if (!txt) return ''
- return txt.length > 4000 ? `${txt.slice(0, 4000)}\n…(truncated — cat the file for the rest)` : txt
- } catch { return '' } // no index yet
+ /** Preload global + current-project memory indexes. Existing
+ * `memory/MEMORY.md` stays GLOBAL; project work lives under
+ * `memory/projects/<id>/MEMORY.md`. A no-project wake injects global
+ * only — same contract as cloud `loadMemory`. */
+ private async memoryDigest(projectIds: readonly string[] = []): Promise<string> {
+ const parts: Array<{ label: string; body: string }> = []
+ for (const rel of memoryIndexPathsForScope(projectIds)) {
+ try {
+ const txt = (await readFile(join(this.home, rel), 'utf8')).trim()
+ if (txt) parts.push({ label: rel, body: txt })
+ } catch { /* missing index is fine */ }
+ }
+ return composeMemoryDigest(parts)
}
/** Triage the inbox on the LOCAL small brain. The whole point of BYOA is that
@@ -1520,7 +1507,7 @@ class AgentRunner {
} catch { return null }
}
- private async snapshotUnread(token: string): Promise<{ seen: Map<string, string>; digest: string; hasReal: boolean }> {
+ private async snapshotUnread(token: string): Promise<{ seen: Map<string, string>; digest: string; hasReal: boolean; projectIds: string[] }> {
const inbox = await runtimeGet<RuntimeInboxResponse>(this.cfg.serverUrl, '/inbox', token)
const seen = new Map<string, string>()
// Unread grouped BY CONVERSATION (first-seen order), each with the header
@@ -1546,7 +1533,14 @@ class AgentRunner {
if (row.kind !== 'system' || (alarm && (!alarm.assigneeId || alarm.assigneeId === this.agent.id))) hasReal = true
let convo = byConvo.get(row.conversation_id)
if (!convo) {
- convo = { head: conversationHeader(row), msgs: [] }
+ const head = conversationHeader({
+ conversation_id: row.conversation_id,
+ conversation_kind: row.conversation_kind,
+ conversation_title: row.conversation_title,
+ conversation_topic: row.conversation_topic,
+ project_name: row.project_name,
+ })
+ convo = { head, msgs: [] }
byConvo.set(row.conversation_id, convo)
}
const author = row.author_name ?? 'someone'
@@ -1561,7 +1555,10 @@ class AgentRunner {
// <convo> '<body>' --quote <message_id>`.
convo.msgs.push(` [${row.id}] ${row.conversation_id} ${who}: ${body}`)
}
- return { seen, digest: renderInboxDigest(byConvo), hasReal }
+ const projectIds = uniqueProjectIds(
+ (inbox?.rows ?? []).map((r) => (typeof r.project_id === 'string' ? r.project_id : null)),
+ )
+ return { seen, digest: renderInboxDigest(byConvo), hasReal, projectIds }
}
/** Advance this agent's read cursor over the conversations it just saw, so a
@@ -1634,11 +1631,12 @@ class AgentRunner {
// Skype emoticons — shared with the cloud agent so a BYOA agent is as
// expressive, not stuck on native emoji only.
`${SKYPE_EMOTICONS_GUIDE}\n\n` +
- `Memory: your only durable store lives under \`memory/\`, indexed by \`memory/MEMORY.md\`. ` +
- `Consult it before acting. When the operator asks you to remember something (or you learn a ` +
- `durable fact), WRITE it to a file under \`memory/\` and add a one-line pointer in MEMORY.md — ` +
- `saying "got it" does NOT persist. Your in-context chat history can be wiped by compaction; ` +
- `memory files remain. Keep MEMORY.md self-sufficient as a recovery point.\n\n` +
+ `Memory: durable store under \`memory/\` (global identity, indexed by \`memory/MEMORY.md\`) ` +
+ `and \`memory/projects/<projectId>/\` for unpinned work facts of the current project. ` +
+ `This wake injects only global + this project's index — other projects are out of scope. ` +
+ `Write project decisions/materials under \`memory/projects/<id>/\` (and a pointer in that folder's MEMORY.md); ` +
+ `write identity-level facts under \`memory/\`. Pinning a memory makes it global. ` +
+ `Saying "got it" does NOT persist. Chat history can be wiped by compaction; memory files remain.\n\n` +
`Drive what you own forward — see a task through. Multi-step turns are fine; you do NOT have to ` +
`fragment. If someone DMs you mid-task, answer briefly then keep going. The only thing to avoid ` +
`is a pointless loop. If progress is waiting on a quiet teammate, follow up (short @<their-id> ` +
@@ -1672,7 +1670,7 @@ class AgentRunner {
? `Your unread messages (ALREADY FETCHED — no need to re-run \`cumora inbox\` / \`cumora messages\` to re-read ` +
`these; but DO \`cumora glance\` before posting in a group, to catch anything posted while you compose):\n${inboxDigest}\n\n`
: `Run \`cumora inbox\`, then \`cumora messages <conversationId> --tail 30\`, to catch up.\n\n`) +
- (memoryDigest ? `Your memory index (\`memory/MEMORY.md\`):\n${memoryDigest}\n\n` : ``) +
+ (memoryDigest ? `Your memory index (global \`memory/MEMORY.md\` + current project, if any):\n${memoryDigest}\n\n` : ``) +
(roster ? `Your team right now (trust over memory — current roster; use these ids for @mentions and \`cumora dm\`):\n${roster}\n` : ``)
).trimEnd()
}
@@ -1691,7 +1689,7 @@ class AgentRunner {
`never nag, never revive a finished thread. Coordinate before you commit (claim before shared work, trust card status); ` +
`follow your standing instructions for mechanics.\n\n` +
`${brief}\n\n` +
- (memoryDigest ? `Your memory index (\`memory/MEMORY.md\`):\n${memoryDigest}\n\n` : ``) +
+ (memoryDigest ? `Your memory index (global \`memory/MEMORY.md\` + current project, if any):\n${memoryDigest}\n\n` : ``) +
(roster ? `Your team (use these ids for @mentions):\n${roster}\n` : ``)
).trimEnd()
}
@@ -1971,7 +1969,7 @@ class AgentRunner {
// superset of what we may ack — a real task that lands during/after
// triage keeps a higher id, stays out of `seen`, and so survives to
// drive the coalesced rerun rather than being silently acked away.
- const { seen, digest, hasReal } = await this.snapshotUnread(token)
+ const { seen, digest, hasReal, projectIds } = await this.snapshotUnread(token)
// Which conversation should show "<agent> is typing…"? Prefer the one the
// wake named, but fall back to the unread we just snapshotted, because a
// wake often carries no conversation at all:
@@ -2068,7 +2066,12 @@ class AgentRunner {
let typingTimer: ReturnType<typeof setInterval> | undefined
if (convo) {
const ping = (): void => { void runtimeBest(this.cfg.serverUrl, '/typing', token, { conversationId: convo, done: false }) }
- const thinkingPing = (): void => { void runtimeBest(this.cfg.serverUrl, '/thinking/mark', token, { conversationIds: [convo], ttlSec: 60 }) }
+ // Stamp every conversation in this wake, not just the trigger.
+ // Mixed-project wakes then fall back to GLOBAL on memory writes
+ // instead of guessing the trigger group's project.
+ const wakeConvos = [...seen.keys()]
+ const thinkingIds = wakeConvos.length > 0 ? wakeConvos : [convo]
+ const thinkingPing = (): void => { void runtimeBest(this.cfg.serverUrl, '/thinking/mark', token, { conversationIds: thinkingIds, ttlSec: 60 }) }
ping()
thinkingPing()
typingTimer = setInterval(() => {
@@ -2111,7 +2114,7 @@ class AgentRunner {
}
try {
const [memoryDigest, triageNote, roster] = await Promise.all([
- this.memoryDigest(),
+ this.memoryDigest(projectIds),
Promise.resolve(this.formatTriageNote(triage)),
// Live team roster (names + roles + ids), fetched fresh from the
// server so a locally-run agent knows WHO its teammates are and what
diff --git a/server/src/agents/memory-scope.ts b/server/src/agents/memory-scope.ts
new file mode 100644
index 0000000..a320d33
--- /dev/null
+++ b/server/src/agents/memory-scope.ts
@@ -0,0 +1,299 @@
+/**
+ * Project-scoped agent memory — the shared write/filter contract used by
+ * BOTH the cloud path (`loadMemory` / `cumora memory` / FUSE writes) and
+ * the BYOA daemon (`memoryDigest`). One identity, many groups: unpinned
+ * work facts stay in the project that produced them; identity, persona,
+ * skills, climate, and pinned memories stay global.
+ *
+ * Existing rows/files with no project provenance stay GLOBAL. This module
+ * never migrates old memories into a project — that would be fake
+ * isolation (live writes historically hardcoded `source: null`).
+ *
+ * Layout (BYOA local FS, and new cloud writes when a project is known):
+ * memory/MEMORY.md global index (legacy location)
+ * memory/<kind>/<id>.md global notes
+ * memory/projects/<projectId>/MEMORY.md per-project index
+ * memory/projects/<projectId>/<kind>/<id>.md
+ *
+ * Filter truth table (read of unpinned work vs pinned/identity):
+ * pinned → always visible
+ * no project on the row → always visible (global, including legacy)
+ * project P, wake in P → visible
+ * project P, wake in Q → hidden
+ * project P, no-project conversation → hidden
+ * wake spanning P and Q → P and Q visible; other projects hidden
+ *
+ * Persona / climate / skills are NOT in this file on purpose: they are
+ * loaded by dedicated paths (`loadClimate`, `loadSkillsIndex`, persona)
+ * that stay per-agent and global.
+ */
+export interface MemorySource {
+ conversationId: string | null
+ projectId: string | null
+}
+
+export interface MemoryScopeMeta {
+ pinned?: boolean
+ source?: MemorySource | null
+}
+
+/** Current wake/read context. Empty `projectIds` = no-project conversation(s)
+ * → inject GLOBAL memory only. */
+export interface MemoryReadScope {
+ projectIds: readonly string[]
+}
+
+export const MEMORY_ROOT = 'memory'
+export const MEMORY_PROJECTS_DIR = 'memory/projects'
+export const GLOBAL_MEMORY_INDEX = 'memory/MEMORY.md'
+export const DEFAULT_MEMORY_DIGEST_CHARS = 4000
+
+export interface ParsedMemoryPath {
+ /** Path kind segment (`observation` / `note` / `index` for MEMORY.md). */
+ kind: string
+ /** File stem without `.md`. */
+ id: string
+ /** Project id when the path is under `memory/projects/<id>/`; else null. */
+ projectId: string | null
+}
+
+/** Stamp stored on every NEW memory write. */
+export function buildMemorySource(opts: {
+ conversationId?: string | null
+ projectId?: string | null
+}): MemorySource {
+ return {
+ conversationId: opts.conversationId ?? null,
+ projectId: opts.projectId ?? null,
+ }
+}
+
+/** Coerce JSON / optional-field source blobs into MemorySource. */
+export function asMemorySource(raw: unknown): MemorySource | null {
+ if (raw == null) return null
+ if (typeof raw !== 'object') return null
+ const o = raw as Record<string, unknown>
+ return {
+ conversationId: typeof o.conversationId === 'string' ? o.conversationId : null,
+ projectId: typeof o.projectId === 'string' ? o.projectId : null,
+ }
+}
+
+export function uniqueProjectIds(ids: ReadonlyArray<string | null | undefined>): string[] {
+ const out: string[] = []
+ const seen = new Set<string>()
+ for (const raw of ids) {
+ if (typeof raw !== 'string') continue
+ const id = raw.trim()
+ if (!id || seen.has(id)) continue
+ seen.add(id)
+ out.push(id)
+ }
+ return out
+}
+
+/**
+ * Decide provenance for a new write. Path `memory/projects/<id>/…` wins
+ * (the agent already chose a project folder). An explicit conversation
+ * or project flag is next. Ambient "I'm thinking in these rooms" is
+ * used only when it is unambiguous — mixed projects fall back to
+ * GLOBAL rather than guessing, which would be fake isolation.
+ */
+export function pickWriteProvenance(opts: {
+ explicitConversationId?: string | null
+ explicitProjectId?: string | null
+ path?: string
+ thinking?: ReadonlyArray<{ conversationId: string; projectId: string | null }>
+}): MemorySource {
+ const fromPath = opts.path ? projectIdFromMemoryPath(opts.path) : null
+ const thinking = opts.thinking ?? []
+ const explicitConvo = emptyToNull(opts.explicitConversationId)
+ const explicitProject = emptyToNull(opts.explicitProjectId)
+
+ let conversationId: string | null = explicitConvo
+ let projectId: string | null = fromPath ?? explicitProject
+
+ if (!conversationId && thinking.length === 1) {
+ conversationId = thinking[0].conversationId
+ }
+
+ if (!projectId) {
+ if (explicitConvo) {
+ const hit = thinking.find((t) => t.conversationId === explicitConvo)
+ projectId = hit?.projectId ?? null
+ } else {
+ const pids = uniqueProjectIds(thinking.map((t) => t.projectId))
+ if (pids.length === 1) projectId = pids[0]
+ // 0 or 2+ distinct projects → leave null (global). Mixed attribution
+ // would pin the note to the wrong room.
+ }
+ }
+
+ if (!conversationId && projectId && thinking.length > 0) {
+ const matches = thinking.filter((t) => t.projectId === projectId)
+ if (matches.length === 1) conversationId = matches[0].conversationId
+ }
+
+ return buildMemorySource({ conversationId, projectId })
+}
+
+export function buildMemoryMeta(opts: {
+ path: string
+ kind?: string
+ about?: string | null
+ pinned?: boolean
+ conversationId?: string | null
+ projectId?: string | null
+ createdAt?: string
+}): Record<string, unknown> {
+ const parsed = parseMemoryPath(opts.path)
+ const source = pickWriteProvenance({
+ explicitConversationId: opts.conversationId,
+ explicitProjectId: opts.projectId,
+ path: opts.path,
+ })
+ const segs = opts.path.split('/')
+ const kind = opts.kind ?? parsed?.kind ?? segs[1] ?? 'note'
+ return {
+ type: 'memory',
+ kind,
+ about: opts.about ?? null,
+ pinned: Boolean(opts.pinned),
+ source,
+ createdAt: opts.createdAt ?? new Date().toISOString(),
+ }
+}
+
+export function parseMemoryPath(path: string): ParsedMemoryPath | null {
+ if (!path.startsWith('memory/')) return null
+ const segs = path.split('/')
+ const projectId = segs[1] === 'projects' && segs[2] ? segs[2] : null
+ const rest = projectId ? segs.slice(3) : segs.slice(1)
+ if (rest.length === 0) return { kind: 'index', id: '', projectId }
+ if (rest.length === 1) {
+ const stem = rest[0].replace(/\.md$/, '')
+ const kind = stem.toUpperCase() === 'MEMORY' ? 'index' : 'note'
+ return { kind, id: stem, projectId }
+ }
+ const kind = rest[0] || 'note'
+ const id = rest[rest.length - 1].replace(/\.md$/, '')
+ return { kind, id, projectId }
+}
+
+export function projectIdFromMemoryPath(path: string): string | null {
+ return parseMemoryPath(path)?.projectId ?? null
+}
+
+export function memoryWritePath(kind: string, id: string, projectId?: string | null): string {
+ const k = kind || 'note'
+ const file = `${id}.md`
+ if (projectId) return `${MEMORY_PROJECTS_DIR}/${projectId}/${k}/${file}`
+ return `${MEMORY_ROOT}/${k}/${file}`
+}
+
+export function projectMemoryIndexPath(projectId: string): string {
+ return `${MEMORY_PROJECTS_DIR}/${projectId}/MEMORY.md`
+}
+
+/** Index files a wake should inject: always the global MEMORY.md, plus
+ * one per current project. No-project wake → global only. Existing
+ * `memory/MEMORY.md` stays the global index — we never move it. */
+export function memoryIndexPathsForScope(projectIds: readonly string[]): string[] {
+ const paths = [GLOBAL_MEMORY_INDEX]
+ for (const id of uniqueProjectIds(projectIds)) {
+ paths.push(projectMemoryIndexPath(id))
+ }
+ return paths
+}
+
+/** Project id stamped on a row: meta.source.projectId, else the path. */
+export function rowProjectId(
+ meta: MemoryScopeMeta | null | undefined,
+ path?: string | null,
+): string | null {
+ const fromMeta = emptyToNull(meta?.source?.projectId)
+ if (fromMeta) return fromMeta
+ return path ? projectIdFromMemoryPath(path) : null
+}
+
+/**
+ * Should this memory be injected for the current wake?
+ *
+ * Pinned memories are identity — always global, even if they were
+ * written inside a project. Unpinned memories with no project (legacy
+ * `source: null`, no-project writes, the global index) are global.
+ * Unpinned project memories are visible only when that project is in
+ * the current scope. A no-project conversation therefore sees GLOBAL
+ * memory only.
+ */
+export function memoryVisibleInScope(
+ meta: MemoryScopeMeta | null | undefined,
+ path: string | undefined,
+ scope: MemoryReadScope,
+): boolean {
+ if (meta?.pinned) return true
+ const pid = rowProjectId(meta, path)
+ if (!pid) return true
+ return scope.projectIds.includes(pid)
+}
+
+export function filterMemories<T extends { meta?: MemoryScopeMeta | null; path?: string }>(
+ rows: readonly T[],
+ scope: MemoryReadScope,
+): T[] {
+ return rows.filter((r) => memoryVisibleInScope(r.meta, r.path, scope))
+}
+
+export function clipMemoryDigest(text: string, maxChars = DEFAULT_MEMORY_DIGEST_CHARS): string {
+ const txt = text.trim()
+ if (!txt) return ''
+ if (txt.length <= maxChars) return txt
+ return `${txt.slice(0, maxChars)}\n…(truncated — cat the file for the rest)`
+}
+
+/**
+ * Join global + current-project index bodies. A lone global index is
+ * returned as-is (clipped) so existing BYOA wakes stay byte-identical
+ * when the agent has no project files yet.
+ */
+export function composeMemoryDigest(
+ parts: ReadonlyArray<{ label: string; body: string }>,
+ maxChars = DEFAULT_MEMORY_DIGEST_CHARS,
+): string {
+ const nonempty = parts.filter((p) => p.body.trim().length > 0)
+ if (nonempty.length === 0) return ''
+ if (nonempty.length === 1 && nonempty[0].label === GLOBAL_MEMORY_INDEX) {
+ return clipMemoryDigest(nonempty[0].body, maxChars)
+ }
+ const chunks: string[] = []
+ for (const p of nonempty) {
+ const pid = projectIdFromMemoryPath(p.label)
+ const header = pid ? `## project ${pid} (\`${p.label}\`)` : `## global (\`${p.label}\`)`
+ chunks.push(`${header}\n${p.body.trim()}`)
+ }
+ return clipMemoryDigest(chunks.join('\n\n'), maxChars)
+}
+
+/** BYOA / cloud wake digest header. A project-less conversation is
+ * byte-identical to the historical `# id [kind] "title"` + optional
+ * Topic line — `Project:` is added only when a name is present. */
+export function conversationHeader(row: {
+ conversation_id: string
+ conversation_kind?: string | null
+ conversation_title?: string | null
+ conversation_topic?: string | null
+ project_name?: string | null
+}): string {
+ const kind = row.conversation_kind ? ` [${row.conversation_kind}]` : ''
+ const title = row.conversation_title ? ` "${row.conversation_title}"` : ''
+ let head = `# ${row.conversation_id}${kind}${title}`
+ if (row.project_name) head += `\n Project: ${row.project_name}`
+ if (row.conversation_topic) head += `\n Topic: ${row.conversation_topic}`
+ return head
+}
+
+function emptyToNull(v: string | null | undefined): string | null {
+ if (typeof v !== 'string') return null
+ const s = v.trim()
+ return s ? s : null
+}
diff --git a/server/src/agents/memory-write.ts b/server/src/agents/memory-write.ts
new file mode 100644
index 0000000..e8318b8
--- /dev/null
+++ b/server/src/agents/memory-write.ts
@@ -0,0 +1,92 @@
+/**
+ * I/O adapter on top of memory-scope.ts: resolve conversation/project
+ * provenance for a live write. Callers (cli `memory note`, FUSE
+ * /runtime/fs/write, workspace write into memory/) share this so Cloud
+ * and BYOA don't grow two attribution schemes.
+ *
+ * Fail-open: Redis/DB hiccups stamp GLOBAL provenance (nulls) rather
+ * than blocking the write or guessing a project.
+ */
+import { pool } from '../db/pool.js'
+import { getThinkingConversations } from './thinking-convos.js'
+import {
+ buildMemoryMeta,
+ pickWriteProvenance,
+ type MemorySource,
+} from './memory-scope.js'
+
+export async function resolveMemoryWriteSource(
+ agentId: string,
+ opts: {
+ path?: string
+ conversationId?: string | null
+ projectId?: string | null
+ } = {},
+): Promise<MemorySource> {
+ const explicit = typeof opts.conversationId === 'string' && opts.conversationId.trim()
+ ? opts.conversationId.trim()
+ : null
+ let ids: string[] = explicit ? [explicit] : []
+ if (ids.length === 0) {
+ try {
+ ids = await getThinkingConversations(agentId)
+ } catch {
+ ids = []
+ }
+ }
+ let thinking: Array<{ conversationId: string; projectId: string | null }> = []
+ if (ids.length > 0) {
+ try {
+ const { rows } = await pool.query<{ id: string; project_id: string | null }>(
+ `SELECT id, project_id FROM conversations WHERE id = ANY($1::text[])`,
+ [ids],
+ )
+ const byId = new Map(rows.map((r) => [r.id, r.project_id ?? null]))
+ thinking = ids.map((id) => ({ conversationId: id, projectId: byId.get(id) ?? null }))
+ } catch {
+ thinking = ids.map((id) => ({ conversationId: id, projectId: null }))
+ }
+ }
+ return pickWriteProvenance({
+ explicitConversationId: explicit,
+ explicitProjectId: opts.projectId ?? null,
+ path: opts.path,
+ thinking,
+ })
+}
+
+export async function memoryMetaForWrite(
+ agentId: string,
+ opts: {
+ path: string
+ kind?: string
+ about?: string | null
+ pinned?: boolean
+ conversationId?: string | null
+ projectId?: string | null
+ },
+): Promise<Record<string, unknown>> {
+ const source = await resolveMemoryWriteSource(agentId, opts)
+ return buildMemoryMeta({
+ path: opts.path,
+ kind: opts.kind,
+ about: opts.about,
+ pinned: opts.pinned,
+ conversationId: source.conversationId,
+ projectId: source.projectId,
+ })
+}
+
+export async function projectIdsForConversations(conversationIds: string[]): Promise<string[]> {
+ if (conversationIds.length === 0) return []
+ try {
+ const { rows } = await pool.query<{ project_id: string }>(
+ `SELECT DISTINCT project_id FROM conversations
+ WHERE id = ANY($1::text[]) AND project_id IS NOT NULL`,
+ [conversationIds],
+ )
+ return rows.map((r) => r.project_id)
+ } catch {
+ return []
+ }
+}
diff --git a/server/src/agents/runtime/client.ts b/server/src/agents/runtime/client.ts
index 997c0e0..59f0e91 100644
--- a/server/src/agents/runtime/client.ts
+++ b/server/src/agents/runtime/client.ts
@@ -59,11 +59,8 @@ export interface InboxRow {
/** The group's topic ("what this group is for"), so every agent — the cloud
* turn context AND the BYOA inbox digest — stays on-task. Null if unset. */
conversation_topic: string | null
- /** The project this group belongs to. Optional because not every row source
- * selects it, and null because direct chats and ungrouped conversations are
- * genuinely project-less. `loadInbox` populates it; the cloud turn has always
- * rendered a project, and carrying it here is what lets the BYOA wake digest
- * do the same. */
+ /** Optional: conversation's project. Direct chats and unscoped groups
+ * leave these unset so a project-less header stays byte-identical. */
project_id?: string | null
project_name?: string | null
author_id: string
@@ -203,9 +200,14 @@ export interface AgentRuntimeClient {
getConversationCompanyId(conversationId: string): Promise<string | null>
/** Unread messages across all of the agent's conversations. */
loadInbox(agentId: string): Promise<InboxRow[]>
- /** Hybrid memory retrieval: pinned + semantic + recent. */
+ /** Hybrid memory retrieval: pinned + semantic + recent, filtered to
+ * global + the current project(s). Pass conversationIds (preferred)
+ * or projectIds; empty/omitted scope = GLOBAL only (no-project wake). */
loadMemory(agentId: string, queryText: string, limits?: {
semantic?: number; recent?: number; total?: number;
+ }, scope?: {
+ projectIds?: readonly string[];
+ conversationIds?: readonly string[];
}): Promise<MemoryRow[]>
/** Per-conversation recent history for every convo with unread items. */
loadContext(agentId: string, conversationIds: string[]): Promise<ContextRow[]>
diff --git a/server/src/agents/runtime/fs-endpoints.ts b/server/src/agents/runtime/fs-endpoints.ts
index 976fbe5..86a0b7c 100644
--- a/server/src/agents/runtime/fs-endpoints.ts
+++ b/server/src/agents/runtime/fs-endpoints.ts
@@ -27,6 +27,8 @@ import type { Router, Response } from 'express'
import { pool } from '../../db/pool.js'
import { isSafePath, likeEscape } from './fs-namespace.js'
import type { AgentRuntimeClaims } from './jwt.js'
+import { buildMemoryMeta } from '../memory-scope.js'
+import { memoryMetaForWrite } from '../memory-write.js'
function badRequest(res: Response, msg: string): void {
res.status(400).json({ error: msg })
@@ -49,17 +51,16 @@ function ensureSafePath(p: string | undefined, res: Response): string | null {
/** Memory paths land with a small meta JSONB so downstream readers
* (the semantic-retrieval pipeline, observability views) treat them
* as memory rather than scratch. Other paths get an empty meta. */
-function metaForPath(p: string): Record<string, unknown> {
+/** Sync stamp used when we only have the path (no agent). Live writes
+ * go through {@link memoryMetaForWrite} so conversation/project land
+ * in `source` instead of null. */
+export function metaForPath(p: string, source?: { conversationId?: string | null; projectId?: string | null }): Record<string, unknown> {
if (p.startsWith('memory/')) {
- const segs = p.split('/')
- return {
- type: 'memory',
- kind: segs[1] ?? 'note',
- about: null,
- pinned: false,
- source: null,
- createdAt: new Date().toISOString(),
- }
+ return buildMemoryMeta({
+ path: p,
+ conversationId: source?.conversationId,
+ projectId: source?.projectId,
+ })
}
return {}
}
@@ -114,12 +115,14 @@ export function attachFsEndpoints(
// PUT /runtime/fs/write { path, body } — upsert
router.put('/fs/write', withAgent(async (c, req, res) => {
- const body = req.body as { path?: string; body?: string } | undefined
+ const body = req.body as { path?: string; body?: string; conversationId?: string } | undefined
const p = ensureSafePath(body?.path, res)
if (p === null) return
if (p === '') { badRequest(res, 'cannot write root'); return }
const text = typeof body?.body === 'string' ? body.body : ''
- const meta = metaForPath(p)
+ const meta = p.startsWith('memory/')
+ ? await memoryMetaForWrite(c.sub, { path: p, conversationId: body?.conversationId ?? null })
+ : metaForPath(p)
await pool.query(
`INSERT INTO agent_workspace (agent_id, path, body, meta, updated_at)
VALUES ($1, $2, $3, $4::jsonb, NOW())
diff --git a/server/src/agents/runtime/http-client.ts b/server/src/agents/runtime/http-client.ts
index 9197eb4..45994f4 100644
--- a/server/src/agents/runtime/http-client.ts
+++ b/server/src/agents/runtime/http-client.ts
@@ -139,8 +139,9 @@ export class HttpRuntimeClient implements AgentRuntimeClient {
_agentId: string,
queryText: string,
limits: { semantic?: number; recent?: number; total?: number } = {},
+ scope: { projectIds?: readonly string[]; conversationIds?: readonly string[] } = {},
): Promise<MemoryRow[]> {
- const out = await this.call<{ rows: MemoryRow[] }>('POST', '/memory/query', { queryText, limits })
+ const out = await this.call<{ rows: MemoryRow[] }>('POST', '/memory/query', { queryText, limits, ...scope })
return out.rows
}
diff --git a/server/src/agents/runtime/inproc-client.ts b/server/src/agents/runtime/inproc-client.ts
index 8e1117d..483fb40 100644
--- a/server/src/agents/runtime/inproc-client.ts
+++ b/server/src/agents/runtime/inproc-client.ts
@@ -58,6 +58,12 @@ import {
} from '../observability.js'
import { buildSystemPrompt as buildSystemPromptImpl } from '../personas.js'
import { loadSkillsIndex as loadSkillsIndexImpl } from '../skills.js'
+import { asMemorySource, memoryVisibleInScope, type MemorySource } from '../memory-scope.js'
+import { projectIdsForConversations } from '../memory-write.js'
+import {
+ clearThinkingConversations,
+ recordThinkingConversations,
+} from '../thinking-convos.js'
import type {
AgentRuntimeClient,
ClimateRow,
@@ -75,10 +81,36 @@ import type {
interface MemoryQueryRow {
path: string
body: string
- meta: { kind?: string; about?: string | null; pinned?: boolean } | null
+ meta: {
+ kind?: string
+ about?: string | null
+ pinned?: boolean
+ source?: MemorySource | null
+ } | null
updated_at: string
}
+/** Spec: memoryVisibleInScope. Pinned OR no project OR project in $n. */
+function memoryScopeSql(metaExpr: string, pathExpr: string, param: string): string {
+ const pid = `COALESCE(NULLIF(${metaExpr}#>>'{source,projectId}', ''), substring(${pathExpr} from '^memory/projects/([^/]+)/'))`
+ return `(
+ COALESCE((${metaExpr}->>'pinned')::boolean, false) = true
+ OR ${pid} IS NULL
+ OR ${pid} = ANY(${param}::text[])
+ )`
+}
+
+async function resolveMemoryScope(scope: {
+ projectIds?: readonly string[]
+ conversationIds?: readonly string[]
+} = {}): Promise<string[]> {
+ if (scope.projectIds && scope.projectIds.length > 0) return [...scope.projectIds]
+ if (scope.conversationIds && scope.conversationIds.length > 0) {
+ return projectIdsForConversations([...scope.conversationIds])
+ }
+ return []
+}
+
function toMemoryRow(r: MemoryQueryRow): MemoryRow {
const segs = r.path.split('/')
return {
@@ -124,11 +156,6 @@ export class InProcRuntimeClient implements AgentRuntimeClient {
`WITH convos AS (
SELECT c.id, c.company_id,
c.title AS conversation_title, c.kind AS conversation_kind, c.topic AS conversation_topic,
- -- Which project this group belongs to. The cloud turn already
- -- shows it (turn.ts renders "Project: <name>"); BYOA agents saw
- -- nothing, so an agent in several project groups had no way to
- -- tell them apart. PK join on a tiny table inside the CTE that
- -- already walks the agent's conversations.
c.project_id, pr.name AS project_name,
COALESCE(cr.last_read_at, '1970-01-01T00:00:00Z'::timestamptz) AS lr_at,
COALESCE(cr.last_read_message_id, '') AS lr_id,
@@ -233,25 +260,37 @@ export class InProcRuntimeClient implements AgentRuntimeClient {
agentId: string,
queryText: string,
limits: { semantic?: number; recent?: number; total?: number } = {},
+ scope: { projectIds?: readonly string[]; conversationIds?: readonly string[] } = {},
): Promise<MemoryRow[]> {
const semanticLimit = limits.semantic ?? 20
const recentLimit = limits.recent ?? 10
const totalLimit = limits.total ?? 40
+ const projectIds = await resolveMemoryScope(scope)
+ const readScope = { projectIds }
+ const scopePred = memoryScopeSql('meta', 'path', '$SCOPE')
const { hasPgVector, embedText } = await import('../embeddings.js')
const useSemantic = queryText.trim().length > 0 && (await hasPgVector())
const queryVec = useSemantic ? await embedText(queryText) : null
+ const toVisible = (rows: MemoryQueryRow[]): MemoryRow[] =>
+ rows.filter((r) => memoryVisibleInScope(
+ { pinned: r.meta?.pinned, source: asMemorySource(r.meta?.source) },
+ r.path,
+ readScope,
+ )).map(toMemoryRow)
+
if (!queryVec) {
const { rows } = await pool.query<MemoryQueryRow>(
`SELECT path, body, meta, updated_at
FROM agent_workspace
WHERE agent_id = $1 AND path LIKE 'memory/%'
+ AND ${scopePred.replace('$SCOPE', '$3')}
ORDER BY COALESCE((meta->>'pinned')::boolean, false) DESC, updated_at DESC
LIMIT $2`,
- [agentId, totalLimit],
+ [agentId, totalLimit, projectIds],
)
- return rows.map(toMemoryRow)
+ return toVisible(rows)
}
// Hybrid retrieval: three CTEs unioned, ROW_NUMBER dedupes by path
@@ -272,6 +311,7 @@ export class InProcRuntimeClient implements AgentRuntimeClient {
WHERE agent_id = $1 AND path LIKE 'memory/%'
AND embedding IS NOT NULL
AND COALESCE((meta->>'pinned')::boolean, false) = false
+ AND ${scopePred.replace('$SCOPE', '$6')}
ORDER BY embedding <=> $2::vector ASC
LIMIT $3
),
@@ -280,6 +320,7 @@ export class InProcRuntimeClient implements AgentRuntimeClient {
FROM agent_workspace
WHERE agent_id = $1 AND path LIKE 'memory/%'
AND COALESCE((meta->>'pinned')::boolean, false) = false
+ AND ${scopePred.replace('$SCOPE', '$6')}
ORDER BY updated_at DESC
LIMIT $4
),
@@ -298,9 +339,9 @@ export class InProcRuntimeClient implements AgentRuntimeClient {
WHERE rn = 1
ORDER BY source_rank ASC, updated_at DESC
LIMIT $5`,
- [agentId, queryVec, semanticLimit, recentLimit, totalLimit],
+ [agentId, queryVec, semanticLimit, recentLimit, totalLimit, projectIds],
)
- return rows.map(toMemoryRow)
+ return toVisible(rows)
}
// ─── reads (cont.) ────────────────────────────────────────────────
@@ -408,7 +449,9 @@ export class InProcRuntimeClient implements AgentRuntimeClient {
return rows
}
- /** Agent's feelings about people — top-24 most recently updated. */
+ /** Agent's feelings about people — top-24 most recently updated.
+ * Climate is GLOBAL on purpose (issue #45): it does not follow the
+ * project. Same agent identity across groups. */
async loadClimate(agentId: string): Promise<ClimateRow[]> {
const { rows } = await pool.query<ClimateRow>(
`SELECT about_id, affinity, trust, last_note, updated_at
@@ -675,6 +718,9 @@ export class InProcRuntimeClient implements AgentRuntimeClient {
async markThinking(agentId: string, conversationIds: string[], ttlSec: number = 60): Promise<void> {
if (conversationIds.length === 0) return
+ // Reverse index so memory writes can stamp the conversation/project this
+ // turn is actually in — without the agent passing `--in` every time.
+ await recordThinkingConversations(agentId, conversationIds, ttlSec)
// Throttle refreshes: the claim TTL is 60s but the daemon re-marks every 6s.
// Collapse to ≤1 per 30s per agent (still refreshes before the 60s TTL) to
// cut the repeated Redis writes ~5x.
@@ -702,6 +748,7 @@ export class InProcRuntimeClient implements AgentRuntimeClient {
async unmarkThinking(agentId: string, conversationIds: string[]): Promise<void> {
if (conversationIds.length === 0) return
+ await clearThinkingConversations(agentId)
try {
const pipe = redis.multi()
for (const cid of conversationIds) pipe.zrem(thinkingKey(cid), agentId)
@@ -969,6 +1016,8 @@ export function thinkingKey(conversationId: string): string {
return `cumora:thinking:${conversationId}`
}
+export { getThinkingConversations } from '../thinking-convos.js'
+
/** Redis key for the per-scope worklog HASH. `scopeKey` is whatever
* namespace the caller wants — `tenant:<companyId>` for tenant-wide
* claims, `convo:<conversationId>` for conversation-scoped ones.
diff --git a/server/src/agents/runtime/server.ts b/server/src/agents/runtime/server.ts
index 535dfcf..0c34717 100644
--- a/server/src/agents/runtime/server.ts
+++ b/server/src/agents/runtime/server.ts
@@ -246,8 +246,16 @@ runtimeRouter.get('/agenda', withAgent(async (c, _req, res) => {
}))
runtimeRouter.post('/memory/query', withAgent(async (c, req, res) => {
- const body = req.body as { queryText?: string; limits?: { semantic?: number; recent?: number; total?: number } } | undefined
- const rows = await inprocClient.loadMemory(c.sub, body?.queryText ?? '', body?.limits)
+ const body = req.body as {
+ queryText?: string
+ limits?: { semantic?: number; recent?: number; total?: number }
+ projectIds?: string[]
+ conversationIds?: string[]
+ } | undefined
+ const rows = await inprocClient.loadMemory(c.sub, body?.queryText ?? '', body?.limits, {
+ projectIds: body?.projectIds,
+ conversationIds: body?.conversationIds,
+ })
res.json({ rows })
}))
diff --git a/server/src/agents/thinking-convos.ts b/server/src/agents/thinking-convos.ts
new file mode 100644
index 0000000..bb30bd9
--- /dev/null
+++ b/server/src/agents/thinking-convos.ts
@@ -0,0 +1,49 @@
+/**
+ * Reverse index for "which conversations is this agent currently
+ * thinking in?". `markThinking` writes a per-conversation ZSET so
+ * *peers* can glance; memory writes need the inverse — stamp
+ * provenance without the agent passing `--in` every time.
+ *
+ * Fail-open: a Redis miss returns [] and the write stays GLOBAL.
+ */
+import { redis } from '../redis.js'
+
+export function agentThinkingConvosKey(agentId: string): string {
+ return `cumora:agent-thinking-convos:${agentId}`
+}
+
+export async function recordThinkingConversations(
+ agentId: string,
+ conversationIds: string[],
+ ttlSec: number,
+): Promise<void> {
+ if (conversationIds.length === 0) return
+ try {
+ await redis.set(
+ agentThinkingConvosKey(agentId),
+ JSON.stringify(conversationIds),
+ 'EX',
+ Math.max(ttlSec + 30, 90),
+ )
+ } catch {
+ /* fail-open — writers will stamp global provenance */
+ }
+}
+
+export async function clearThinkingConversations(agentId: string): Promise<void> {
+ try {
+ await redis.del(agentThinkingConvosKey(agentId))
+ } catch { /* fail-open */ }
+}
+
+export async function getThinkingConversations(agentId: string): Promise<string[]> {
+ try {
+ const raw = await redis.get(agentThinkingConvosKey(agentId))
+ if (!raw) return []
+ const parsed: unknown = JSON.parse(raw)
+ if (!Array.isArray(parsed)) return []
+ return parsed.filter((x): x is string => typeof x === 'string' && x.length > 0)
+ } catch {
+ return []
+ }
+}
diff --git a/server/src/agents/turn.ts b/server/src/agents/turn.ts
index 8aae5ed..baa8ab6 100644
--- a/server/src/agents/turn.ts
+++ b/server/src/agents/turn.ts
@@ -90,6 +90,8 @@ interface InboxRow {
conversation_title: string
conversation_kind: string
conversation_topic: string | null
+ project_id?: string | null
+ project_name?: string | null
author_id: string
/** Joined from `participants.kind` so the agent prompt can tell a human
* message apart from an agent reply without a hardcoded id list. Null
@@ -147,8 +149,9 @@ async function loadMemory(
queryText: string,
limits: { semantic?: number; recent?: number; total?: number } = {},
rc: AgentRuntimeClient = runtime,
+ scope: { projectIds?: readonly string[]; conversationIds?: readonly string[] } = {},
): Promise<MemoryRow[]> {
- return rc.loadMemory(agentId, queryText, limits)
+ return rc.loadMemory(agentId, queryText, limits, scope)
}
async function loadContext(
@@ -1943,7 +1946,7 @@ export async function runAgentTurn(agentId: string, options: AgentTurnOptions =
const [context, memory, climate, textExcerpts, skillsIndex] = await Promise.all([
preloadedContext ? Promise.resolve(preloadedContext) : loadContext(agentId, convoIds),
- loadMemory(agentId, memoryQuery),
+ loadMemory(agentId, memoryQuery, {}, runtime, { conversationIds: convoIds }),
loadClimate(agentId),
loadTextExcerpts(inbox),
runtime.loadSkillsIndex(agentId),