weir-harness 1.1.4 → 1.1.6

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 (57) hide show
  1. package/cordis.patch.yml +48 -87
  2. package/icon.svg +1 -0
  3. package/lib/client.capability-badge.js +16 -16
  4. package/lib/client.capability-manager.js +87 -36
  5. package/lib/client.capability-model.js +151 -31
  6. package/lib/client.capability-presets.js +187 -39
  7. package/lib/client.edit-lock-maintenance.js +27 -12
  8. package/lib/client.edit-lock-panel.js +52 -19
  9. package/lib/client.js +270 -12
  10. package/lib/client.settings-page.js +13 -8
  11. package/lib/client.worktree-model.js +20 -1
  12. package/lib/client.worktree-view.js +32 -9
  13. package/package.json +4 -2
  14. package/skills/deep-work/SKILL.md +7 -3
  15. package/src/blackboard/durable.js +199 -0
  16. package/src/blackboard/index.js +62 -42
  17. package/src/blackboard/kernel.js +20 -1
  18. package/src/blackboard/remote.js +36 -28
  19. package/src/blackboard/storage.js +238 -0
  20. package/src/capabilities/capability-remote.js +122 -69
  21. package/src/capabilities/preset-library.js +113 -87
  22. package/src/capabilities/read-payloads.js +21 -4
  23. package/src/capabilities/skill-selection-plugin.js +188 -168
  24. package/src/capabilities/skill-selection-provider.js +13 -0
  25. package/src/capabilities/store/enumerate.js +46 -0
  26. package/src/capabilities/store/store.js +86 -1
  27. package/src/context-guard/index.js +222 -117
  28. package/src/context-guard/pressure.js +12 -3
  29. package/src/context-guard/recovery.js +25 -0
  30. package/src/core/doctrine.js +3 -3
  31. package/src/delegate/group-coordinator.js +2 -1
  32. package/src/delegate/supervision-mount.js +41 -2
  33. package/src/delegate/tool.js +11 -3
  34. package/src/edit-lock/admin-ledger.js +42 -6
  35. package/src/edit-lock/admin-recovery.js +4 -2
  36. package/src/edit-lock/binding-attestation.js +29 -0
  37. package/src/edit-lock/binding-guidance.js +43 -0
  38. package/src/edit-lock/domain.js +20 -5
  39. package/src/edit-lock/host.js +3 -3
  40. package/src/edit-lock/index.js +268 -57
  41. package/src/edit-lock/lifecycle.js +106 -47
  42. package/src/edit-lock/maintenance.js +12 -3
  43. package/src/edit-lock/manager.js +8 -3
  44. package/src/edit-lock/peer.js +2 -0
  45. package/src/edit-lock/publisher.js +57 -1
  46. package/src/edit-lock/remote.js +120 -52
  47. package/src/edit-lock/runtime.js +8 -0
  48. package/src/edit-lock/view.js +27 -12
  49. package/src/settings/sections.js +30 -6
  50. package/src/shared/audit.js +6 -0
  51. package/src/shared/delegate-edit-lifecycle.js +36 -0
  52. package/src/todo-driver/index.js +16 -1
  53. package/src/worktree/cards.js +47 -3
  54. package/src/worktree/command.js +29 -5
  55. package/src/worktree/git.js +39 -5
  56. package/src/worktree/lanes.js +83 -25
  57. package/src/worktree/prompts.js +2 -1
@@ -155,20 +155,28 @@ export function createBlackboardRemoteService(dependencies = {}) {
155
155
  * @param {any} agent
156
156
  * @returns {{ sessionId: string, boardId: string, faces: { kernel: any, boardOf: Function, ttlMs: Function } }}
157
157
  */
158
- function resolve(agent) {
158
+ async function resolve(agent) {
159
159
  if (!ensure()) throw new BlackboardRemoteError('channel-unavailable', 'blackboard remote is not registered with the gateway')
160
160
  const faces = bridgeFor()
161
161
  if (!faces) throw new BlackboardRemoteError('bridge-absent', 'blackboard remote is not offered (non-Weir preset or unmounted bridge)')
162
162
  const sessionId = typeof agent?.id === 'string' && agent.id.length > 0 ? agent.id : undefined
163
163
  if (sessionId === undefined) throw new BlackboardRemoteError('unknown-session', 'blackboard remote: the acting session identity is unavailable')
164
- const boardId = faces.boardOf(agent)
164
+ if (faces.run) {
165
+ // Keep admission and the eventual kernel operation in one lifecycle gate;
166
+ // resolving a root alone is not a transferable authority across awaits.
167
+ const kernel = Object.fromEntries(['list', 'read', 'apply', 'write', 'deleteKey', 'markPromoted'].map(method => [method,
168
+ (_boardId, ...args) => faces.run(agent, root => faces.kernel[method](root, ...args)),
169
+ ]))
170
+ return { sessionId, boardId: undefined, faces: { ...faces, kernel } }
171
+ }
172
+ const boardId = await faces.boardOf(agent)
165
173
  return { sessionId, boardId, faces }
166
174
  }
167
175
 
168
176
  /** Wrap a face failure uniformly; typed errors pass through untouched. */
169
- function payloadWrap(action, build) {
177
+ async function payloadWrap(action, build) {
170
178
  try {
171
- return build()
179
+ return await build()
172
180
  } catch (cause) {
173
181
  if (cause instanceof BlackboardRemoteError) throw cause
174
182
  throw new BlackboardRemoteError('payload-failed', `blackboard remote ${action} failed: ${cause instanceof Error ? cause.message : String(cause)}`, { cause })
@@ -177,10 +185,10 @@ export function createBlackboardRemoteService(dependencies = {}) {
177
185
 
178
186
  return {
179
187
  /** Aggregate rows: key + entryType + summary + counts, never content. */
180
- list(agent, args) {
181
- return payloadWrap('list', () => {
182
- const { boardId, faces } = resolve(agent)
183
- const rows = faces.kernel.list(boardId, { entryType: args?.type, query: args?.query })
188
+ async list(agent, args) {
189
+ return payloadWrap('list', async () => {
190
+ const { boardId, faces } = await resolve(agent)
191
+ const rows = await faces.kernel.list(boardId, { entryType: args?.type, query: args?.query })
184
192
  return { entries: rows.map((/** @type {any} */ entry) => wireEntry(entry)) }
185
193
  })
186
194
  },
@@ -188,19 +196,19 @@ export function createBlackboardRemoteService(dependencies = {}) {
188
196
  /** Batch content read; unknown keys are values, not errors. Audit reads
189
197
  * through this remote (the panel) never move read counts — counting is
190
198
  * the agent-tool path's reuse evidence, not a page-view metric. */
191
- read(agent, args) {
192
- return payloadWrap('read', () => {
193
- const { boardId, faces } = resolve(agent)
194
- const result = faces.kernel.read(boardId, args?.keys ?? [], { count: false })
199
+ async read(agent, args) {
200
+ return payloadWrap('read', async () => {
201
+ const { boardId, faces } = await resolve(agent)
202
+ const result = await faces.kernel.read(boardId, args?.keys ?? [], { count: false })
195
203
  return { entries: result.found.map((/** @type {any} */ entry) => wireEntry(entry, { content: true })) }
196
204
  })
197
205
  },
198
206
 
199
207
  /** Acquire the one-shot write authority for one key (auto-subscribes on contention; a promoted key refuses explicitly). */
200
- apply(agent, args) {
201
- return payloadWrap('apply', () => {
202
- const { sessionId, boardId, faces } = resolve(agent)
203
- const result = faces.kernel.apply(boardId, { holderId: sessionId, key: args?.key, ttlMs: faces.ttlMs() })
208
+ async apply(agent, args) {
209
+ return payloadWrap('apply', async () => {
210
+ const { sessionId, boardId, faces } = await resolve(agent)
211
+ const result = await faces.kernel.apply(boardId, { holderId: sessionId, key: args?.key, ttlMs: faces.ttlMs() })
204
212
  if (result.status === 'contended') return { acquired: false, holder: result.holder, subscribed: true }
205
213
  if (result.status === 'promoted') return { acquired: false, promoted: true, destination: result.destination }
206
214
  return { acquired: true, token: freshToken(), expiresAt: result.expiresAt }
@@ -208,10 +216,10 @@ export function createBlackboardRemoteService(dependencies = {}) {
208
216
  },
209
217
 
210
218
  /** Create or update one entry under the acting session's live write authority. */
211
- write(agent, args) {
219
+ async write(agent, args) {
212
220
  try {
213
- const { sessionId, boardId, faces } = resolve(agent)
214
- const result = faces.kernel.write(boardId, {
221
+ const { sessionId, boardId, faces } = await resolve(agent)
222
+ const result = await faces.kernel.write(boardId, {
215
223
  holderId: sessionId,
216
224
  key: args?.key,
217
225
  entryType: args?.entryType,
@@ -239,10 +247,10 @@ export function createBlackboardRemoteService(dependencies = {}) {
239
247
  },
240
248
 
241
249
  /** Delete one entry under the acting session's live write authority. */
242
- remove(agent, args) {
250
+ async remove(agent, args) {
243
251
  try {
244
- const { sessionId, boardId, faces } = resolve(agent)
245
- const result = faces.kernel.deleteKey(boardId, { holderId: sessionId, key: args?.key })
252
+ const { sessionId, boardId, faces } = await resolve(agent)
253
+ const result = await faces.kernel.deleteKey(boardId, { holderId: sessionId, key: args?.key })
246
254
  if (result.status === 'missing') return { ok: false, error: `blackboard key "${result.key}" does not exist` }
247
255
  if (result.status === 'promoted') {
248
256
  return { ok: false, error: `entry "${result.key}" is promoted (${result.destination}) and read-only; promoted entries can never be deleted` }
@@ -261,13 +269,13 @@ export function createBlackboardRemoteService(dependencies = {}) {
261
269
  },
262
270
 
263
271
  /** Request the promotion-evaluation brief into the session's main agent (slice 3). Folds failures like the mutations. */
264
- requestPromotion(agent, args) {
272
+ async requestPromotion(agent, args) {
265
273
  try {
266
- const { faces } = resolve(agent)
274
+ const { faces } = await resolve(agent)
267
275
  if (typeof faces.requestPromotion !== 'function') {
268
276
  return { ok: false, error: 'the blackboard bridge does not offer promotion requests' }
269
277
  }
270
- faces.requestPromotion(agent)
278
+ await faces.requestPromotion(agent)
271
279
  return { ok: true }
272
280
  } catch (cause) {
273
281
  const error = cause instanceof BlackboardRemoteError
@@ -278,10 +286,10 @@ export function createBlackboardRemoteService(dependencies = {}) {
278
286
  },
279
287
 
280
288
  /** Mark one entry promoted under the user-adjudicated destination (slice 3); marking is an annotation, not a payload mutation. */
281
- markPromoted(agent, args) {
289
+ async markPromoted(agent, args) {
282
290
  try {
283
- const { boardId, faces } = resolve(agent)
284
- const result = faces.kernel.markPromoted(boardId, { key: args?.key, destination: args?.destination })
291
+ const { boardId, faces } = await resolve(agent)
292
+ const result = await faces.kernel.markPromoted(boardId, { key: args?.key, destination: args?.destination })
285
293
  if (result.status === 'missing') return { ok: false, error: `blackboard key "${result.key}" does not exist` }
286
294
  if (result.status === 'already-promoted') return { ok: true, destination: result.destination, alreadyPromoted: true }
287
295
  return { ok: true, destination: result.destination }
@@ -0,0 +1,238 @@
1
+ // Session-adjacent storage. Never creates Session directories or touches the
2
+ // host's session.lock. Missing logs preserve all sidecars (no automatic GC).
3
+ import * as fs from 'node:fs/promises'
4
+ import { constants } from 'node:fs'
5
+ import { join, resolve, dirname, basename, isAbsolute } from 'node:path'
6
+ import { hostname } from 'node:os'
7
+ import { randomUUID } from 'node:crypto'
8
+ import { zstdDecompressSync } from 'node:zlib'
9
+ import { ENTRY_TYPES, PROMOTION_DESTINATIONS, validateKey, validateSummary } from './kernel.js'
10
+
11
+ export const LOG = /^session\.v([1-9][0-9]*)\.jsonl(?:\.zstd)?$/
12
+ const SIDE = /^session\.v[1-9][0-9]*\.jsonl(?:\.zstd)?_bb$/
13
+ const ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,199}$/
14
+ const LOCK = 'weir-blackboard.lock'
15
+ const uid = () => process.getuid?.()
16
+ const code = error => error?.code
17
+ const pause = ms => new Promise(resolve => setTimeout(resolve, ms))
18
+
19
+ export function sessionId(id) {
20
+ if (typeof id !== 'string' || !ID.test(id)) throw new Error('blackboard: invalid Session identity')
21
+ return id
22
+ }
23
+
24
+ // Recheck every ancestor; realpath alone would silently accept symlink aliases.
25
+ export async function trusted(path, kind = 'file', absent = false, allowLinks = false) {
26
+ const absolute = resolve(path)
27
+ const parent = dirname(absolute)
28
+ if (parent !== absolute) await trusted(parent, 'directory')
29
+ let stat
30
+ try { stat = await fs.lstat(absolute) } catch (error) {
31
+ if (absent && code(error) === 'ENOENT') return false
32
+ throw error
33
+ }
34
+ if (stat.isSymbolicLink() || (kind === 'directory' ? !stat.isDirectory() : !stat.isFile())) throw new Error(`blackboard: untrusted ${kind}: ${absolute}`)
35
+ // System ancestors may be root-owned; Session files/directories must belong
36
+ // to this user (checked by the caller at the session boundary).
37
+ if (kind === 'file' && (!allowLinks && stat.nlink !== 1 || (uid() !== undefined && stat.uid !== uid()))) throw new Error(`blackboard: unsafe file ownership: ${absolute}`)
38
+ return stat
39
+ }
40
+
41
+ export async function locateSession(home, id, expectedCwd) {
42
+ sessionId(id)
43
+ if (typeof home !== 'string' || !home || !home.startsWith('/') && !/^[A-Za-z]:[\\/]/.test(home)) throw new Error('blackboard: profileContext.home unavailable')
44
+ const root = join(home, 'sessions')
45
+ await trusted(root, 'directory')
46
+ const matches = []
47
+ for (const workspace of await fs.readdir(root)) {
48
+ const dir = join(root, workspace, id)
49
+ let stat
50
+ try { stat = await trusted(dir, 'directory') } catch (error) {
51
+ if (code(error) === 'ENOENT') continue
52
+ throw error
53
+ }
54
+ if (uid() !== undefined && stat.uid !== uid()) throw new Error('blackboard: foreign Session directory')
55
+ const logs = (await fs.readdir(dir)).filter(name => LOG.test(name))
56
+ // Highest generation is DSH's canonical selection. Same-version physical
57
+ // encodings are ambiguous: never guess which installation owns the log.
58
+ if (logs.some(name => !Number.isSafeInteger(Number(LOG.exec(name)[1])))) throw new Error('blackboard: unsupported canonical generation number')
59
+ logs.sort((a, b) => Number(LOG.exec(b)[1]) - Number(LOG.exec(a)[1]))
60
+ if (!logs.length) continue
61
+ const name = logs[0]
62
+ if (logs[1] && LOG.exec(logs[1])[1] === LOG.exec(name)[1]) throw new Error('blackboard: ambiguous canonical log')
63
+ const path = join(dir, name)
64
+ await trusted(path)
65
+ const handle = await fs.open(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0))
66
+ let bytes
67
+ try { bytes = await handle.readFile() } finally { await handle.close() }
68
+ let header
69
+ try {
70
+ const text = name.endsWith('.zstd') ? zstdDecompressSync(bytes).toString('utf8') : bytes.toString('utf8')
71
+ header = JSON.parse(text.split('\n')[0])
72
+ } catch { throw new Error('blackboard: unreadable Session header') }
73
+ if (header.type !== 'session' || header.id !== id || typeof header.cwd !== 'string' || !isAbsolute(header.cwd) || header.version !== Number(LOG.exec(name)[1]) || expectedCwd !== undefined && header.cwd !== expectedCwd) throw new Error('blackboard: Session header identity/cwd mismatch')
74
+ matches.push({ id, dir, log: path, file: join(dir, name + '_bb'), header })
75
+ }
76
+ if (matches.length !== 1) throw new Error(`blackboard: ${matches.length ? 'ambiguous Session directories' : 'durable Session log unavailable; sidecars preserved'}`)
77
+ return matches[0]
78
+ }
79
+
80
+ export function decodeRecord(text, id) {
81
+ let record
82
+ try { record = JSON.parse(text) } catch { throw new Error('blackboard: corrupt sidecar') }
83
+ if (!record || record.schemaVersion !== 1 || record.rootSessionId !== id || !Number.isSafeInteger(record.revision) || record.revision < 0 || !Array.isArray(record.entries)) throw new Error('blackboard: unsupported/corrupt sidecar identity or schema')
84
+ const seen = new Set()
85
+ for (const e of record.entries) {
86
+ validateKey(e?.key)
87
+ validateSummary(e.summary)
88
+ if (seen.has(e.key) || !ENTRY_TYPES.includes(e.entryType) || typeof e.content !== 'string' || !e.content.trim() || !['readCount', 'subscribeCount', 'createdAt', 'updatedAt', 'revision'].every(k => Number.isSafeInteger(e[k]) && e[k] >= (k === 'revision' ? 1 : 0)) || e.promoted && (!PROMOTION_DESTINATIONS.includes(e.promoted.destination) || !Number.isSafeInteger(e.promoted.at) || e.promoted.at < 0)) throw new Error('blackboard: invalid durable entry')
89
+ // Explicit field projection: never revive authorization or unknown fields.
90
+ seen.add(e.key)
91
+ }
92
+ return { schemaVersion: 1, rootSessionId: id, revision: record.revision, entries: record.entries.map(e => ({ key: e.key, entryType: e.entryType, summary: e.summary, content: e.content, readCount: e.readCount, subscribeCount: e.subscribeCount, revision: e.revision, createdAt: e.createdAt, updatedAt: e.updatedAt, ...(e.promoted ? { promoted: { destination: e.promoted.destination, at: e.promoted.at } } : {}) })) }
93
+ }
94
+
95
+ // Only ESRCH proves death. A module reload/new nonce in the SAME live PID
96
+ // never grants reclamation. Unknown host/permissions fail closed.
97
+ function dead(owner) {
98
+ if (owner?.host !== hostname() || !Number.isSafeInteger(owner.pid) || owner.pid <= 0) return false
99
+ try { process.kill(owner.pid, 0); return false } catch (error) { return code(error) === 'ESRCH' }
100
+ }
101
+
102
+ const ownerKey = Symbol.for('weir.blackboard.storage.owner.v1')
103
+ const writerToken = globalThis[ownerKey] ??= randomUUID()
104
+
105
+ export function createBlackboardStorage({ home, hook = async (_op, _path) => {}, timeoutMs = 5000 } = {}) {
106
+ const queue = new Map()
107
+ async function safeRead(path) {
108
+ await trusted(path, 'file', false, basename(path).startsWith(LOCK))
109
+ const fd = await fs.open(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0))
110
+ try { return await fd.readFile('utf8') } finally { await fd.close() }
111
+ }
112
+ async function syncDir(dir) {
113
+ await hook('dir-fsync', dir)
114
+ const fd = await fs.open(dir, 'r')
115
+ try { await fd.sync() } finally { await fd.close() }
116
+ }
117
+ async function publish(file, text) {
118
+ await trusted(dirname(file), 'directory')
119
+ await trusted(file, 'file', true)
120
+ const temp = join(dirname(file), `weir-blackboard.${randomUUID()}.tmp`)
121
+ let renamed = false
122
+ try {
123
+ await hook('create', temp)
124
+ const fd = await fs.open(temp, 'wx', 0o600)
125
+ try { await fd.writeFile(text); await hook('file-fsync', temp); await fd.sync() } finally { await fd.close() }
126
+ await hook('rename', file)
127
+ await trusted(file, 'file', true)
128
+ await fs.rename(temp, file)
129
+ renamed = true
130
+ try { await syncDir(dirname(file)) } catch (error) {
131
+ // Rename may have committed. Confirm the authoritative full bytes;
132
+ // this is not a rollback and the token must not become usable twice.
133
+ if (await safeRead(file) !== text) throw error
134
+ }
135
+ } finally {
136
+ if (!renamed) await fs.unlink(temp).catch(() => {})
137
+ }
138
+ }
139
+ async function lock(dir) {
140
+ const path = join(dir, LOCK)
141
+ const recover = path + '.recover'
142
+ const owner = JSON.stringify({ schemaVersion: 1, token: randomUUID(), host: hostname(), pid: process.pid })
143
+ const candidate = path + '.' + randomUUID() + '.candidate'
144
+ const fd = await fs.open(candidate, 'wx', 0o600)
145
+ try { await fd.writeFile(owner); await fd.sync() } finally { await fd.close() }
146
+ const deadline = Date.now() + timeoutMs
147
+ try {
148
+ for (;;) {
149
+ await trusted(path, 'file', true, true)
150
+ try { await fs.link(candidate, path); break } catch (error) { if (code(error) !== 'EEXIST') throw error }
151
+ const previous = await safeRead(path).catch(error => { if (code(error) === 'ENOENT') return null; throw error })
152
+ if (previous === null) continue
153
+ let doc
154
+ try { doc = JSON.parse(previous) } catch { throw new Error('blackboard: unreadable writer lock; manual recovery required') }
155
+ if (doc.schemaVersion !== 1) throw new Error('blackboard: unknown writer lock schema')
156
+ if (dead(doc)) {
157
+ // Recovery gate is never stolen: interruption fails closed and needs
158
+ // offline cleanup. It prevents two stale observers removing a successor.
159
+ await trusted(recover, 'file', true)
160
+ try { await fs.link(candidate, recover) } catch (error) {
161
+ if (code(error) !== 'EEXIST') throw error
162
+ throw new Error('blackboard: recovery already in progress; manual recovery may be required')
163
+ }
164
+ try {
165
+ if (await safeRead(path) === previous && dead(doc)) await fs.unlink(path)
166
+ } finally { if (await safeRead(recover) === owner) await fs.unlink(recover) }
167
+ continue
168
+ }
169
+ if (Date.now() >= deadline) throw new Error('blackboard: writer lock held by a live/unknown process')
170
+ await pause(10)
171
+ }
172
+ } finally { await fs.unlink(candidate) }
173
+ return async () => { if (await safeRead(path) === owner) await fs.unlink(path) }
174
+ }
175
+ async function transact(id, cwd, action) {
176
+ let where = await locateSession(home, id, cwd)
177
+ const release = await lock(where.dir)
178
+ try {
179
+ // Re-resolve under the version-independent lock, before reading candidates.
180
+ where = await locateSession(home, id, cwd)
181
+ const ownerPath = join(where.dir, 'weir-blackboard.writer')
182
+ let owned = false
183
+ if (await trusted(ownerPath, 'file', true)) {
184
+ let owner
185
+ try { owner = JSON.parse(await safeRead(ownerPath)) } catch { throw new Error('blackboard: corrupt writer authority') }
186
+ if (owner.schemaVersion !== 1 || owner.token !== writerToken && !dead(owner)) throw new Error('blackboard: authority belongs to another live/unknown writer')
187
+ owned = owner.token === writerToken
188
+ }
189
+ if (!owned) await publish(ownerPath, JSON.stringify({ schemaVersion: 1, token: writerToken, host: hostname(), pid: process.pid }))
190
+ const records = []
191
+ for (const name of (await fs.readdir(where.dir)).filter(name => SIDE.test(name))) {
192
+ records.push({ path: join(where.dir, name), record: decodeRecord(await safeRead(join(where.dir, name)), id) })
193
+ }
194
+ if (records.some(row => JSON.stringify(row.record) !== JSON.stringify(records[0].record))) throw new Error('blackboard: conflicting sidecars; originals preserved')
195
+ const previous = records[0]?.record ?? { schemaVersion: 1, rootSessionId: id, revision: 0, entries: [] }
196
+ // Migrate the unchanged snapshot first, so a cleanup failure never
197
+ // leaves a newer canonical record beside an older conflicting source.
198
+ if (!records.some(row => row.path === where.file)) await publish(where.file, JSON.stringify(previous) + '\n')
199
+ for (const row of records) if (row.path !== where.file) {
200
+ if (!SIDE.test(basename(row.path)) || dirname(row.path) !== where.dir) throw new Error('blackboard: unsafe migration path')
201
+ if (JSON.stringify(decodeRecord(await safeRead(row.path), id)) !== JSON.stringify(previous)) throw new Error('blackboard: migration source changed')
202
+ await fs.unlink(row.path)
203
+ }
204
+ const result = await action(structuredClone(previous.entries))
205
+ const entries = result.entries
206
+ const changed = JSON.stringify(entries) !== JSON.stringify(previous.entries)
207
+ const next = { ...previous, revision: previous.revision + (changed ? 1 : 0), entries }
208
+ const encoded = JSON.stringify(decodeRecord(JSON.stringify(next), id)) + '\n'
209
+ if (JSON.stringify(decodeRecord(await safeRead(where.file), id)) !== JSON.stringify(previous)) throw new Error('blackboard: revision conflict')
210
+ const current = await locateSession(home, id, cwd)
211
+ if (current.file !== where.file) throw new Error('blackboard: canonical log changed during commit')
212
+ if (changed) await publish(where.file, encoded)
213
+ return result.publish()
214
+ } finally { await release() }
215
+ }
216
+ return {
217
+ locate: (id, cwd) => locateSession(home, id, cwd),
218
+ async releaseWriter(id, cwd) {
219
+ let where
220
+ try { where = await locateSession(home, id, cwd) } catch { return }
221
+ const release = await lock(where.dir)
222
+ try {
223
+ const path = join(where.dir, 'weir-blackboard.writer')
224
+ if (await trusted(path, 'file', true)) {
225
+ const owner = JSON.parse(await safeRead(path))
226
+ if (owner.schemaVersion === 1 && owner.token === writerToken) await fs.unlink(path)
227
+ }
228
+ } finally { await release() }
229
+ },
230
+ transact(id, cwd, action) {
231
+ const previous = queue.get(id) ?? Promise.resolve()
232
+ const next = previous.catch(() => {}).then(() => transact(id, cwd, action))
233
+ queue.set(id, next)
234
+ void next.finally(() => { if (queue.get(id) === next) queue.delete(id) }).catch(() => {})
235
+ return next
236
+ },
237
+ }
238
+ }
@@ -15,32 +15,24 @@
15
15
  // the host root, and registers a hand-written typert contribution
16
16
  // (src-json codecs, zero generated artifacts).
17
17
  //
18
- // Every read resolves its faces from the bridge AT CALL TIME: a non-Weir
19
- // preset or an unmounted bridge surfaces as an explicit typed error, never a
20
- // guessed or empty payload.
18
+ // Each read observes the exact session's current preset and checks the same
19
+ // ownership generation again after the payload resolves.
21
20
  import { openCapabilityStore } from './store/store.js'
22
21
  import { buildReceiptPayload, buildListPayload, buildConditionsPayload, buildPresetsPayload, buildDefaultGetPayload } from './read-payloads.js'
22
+ import { PRESET_SELECTED_EVENT } from './preset-invalidation.js'
23
+ import { createAudit } from '../shared/audit.js'
23
24
 
24
25
  /** The host-root service key the typert gateway resolves (S27: ctx.get from the host root). */
25
26
  export const CAPABILITY_READ_SERVICE_KEY = 'weirCapabilityRead'
26
27
  /** The wire namespace: POST /api/weirCapabilities/<method>, client ctx.remote.weirCapabilities.*. */
27
28
  export const CAPABILITY_READ_NAMESPACE = 'weirCapabilities'
28
- /** The three read methods, each taking exactly one parameter. */
29
+ /** The five read methods, each taking exactly one parameter. */
29
30
  export const CAPABILITY_READ_METHODS = ['receipt', 'list', 'conditions', 'presets', 'defaultGet']
30
31
 
31
- /**
32
- * Typed read-channel failure. `code` is the machine-readable discriminant:
33
- * - 'bridge-absent' — no skill-selection plugin fed the bridge (non-Weir
34
- * preset or unmounted); the client settles its
35
- * explicit unavailable state.
36
- * - 'unknown-session' — the session id never reached the cwd cache (not an
37
- * agent this runtime created).
38
- * - 'payload-failed' — an underlying face threw; the cause is chained.
39
- * - 'channel-unavailable' — the typert registration is absent and could not be re-established.
40
- */
32
+ /** Typed infrastructure/ownership failure, distinct from domain status values. */
41
33
  export class CapabilityReadError extends Error {
42
34
  /**
43
- * @param {'bridge-absent' | 'unknown-session' | 'payload-failed'} code
35
+ * @param {'bridge-absent' | 'owner-ambiguous' | 'owner-unavailable' | 'owner-changed' | 'unknown-session' | 'payload-failed' | 'channel-unavailable'} code
44
36
  * @param {string} message
45
37
  * @param {{ cause?: unknown }} [options]
46
38
  */
@@ -51,87 +43,143 @@ export class CapabilityReadError extends Error {
51
43
  }
52
44
  }
53
45
 
54
- /**
55
- * The bridge: exactly one skill-selection plugin mounts per composition (per
56
- * process), and every consumer is the same bundle module instance — the same
57
- * module-level slot pattern as the selection face and the MCP facade realm
58
- * bridge. Faces:
59
- * provider, inventory(options, previous?), lifecycle,
60
- * mcpManager() — weirMcpManager accessor, read at call time
61
- * profileContext() — host profile identity for the capability store
62
- * sessionCwd(id) — { found: boolean, cwd: string | undefined }
63
- */
64
- let bridgeFaces = null
46
+ /** Explicit per-preset feeds. Overlapping generations are ambiguous, never last-writer-wins. */
47
+ const bridgeFeeds = new Map()
48
+ const READ_PRESETS = new Set(['weir', 'weir-creative'])
65
49
 
66
- /**
67
- * Feed the bridge (skill-selection apply). Returns the unregister the plugin
68
- * disposes with its own lifecycle.
69
- */
70
50
  export function feedCapabilityReadBridge(faces) {
71
- bridgeFaces = faces
72
- return () => { if (bridgeFaces === faces) bridgeFaces = null }
51
+ const presetId = faces?.readPresetId
52
+ if (!READ_PRESETS.has(presetId)) throw new TypeError('capability read feed requires an explicit supported readPresetId')
53
+ const token = { faces }
54
+ const feeds = bridgeFeeds.get(presetId) ?? new Set()
55
+ feeds.add(token)
56
+ bridgeFeeds.set(presetId, feeds)
57
+ return () => {
58
+ feeds.delete(token)
59
+ if (feeds.size === 0) bridgeFeeds.delete(presetId)
60
+ }
73
61
  }
74
62
 
75
- /** Current bridge faces, or null when unmounted. */
76
- export function capabilityReadBridge() {
77
- return bridgeFaces
63
+ /** Feed counts per supported preset, for degraded-read diagnostics (no faces content). */
64
+ function feedCensus() {
65
+ return { weir: bridgeFeeds.get('weir')?.size ?? 0, weirCreative: bridgeFeeds.get('weir-creative')?.size ?? 0 }
78
66
  }
79
67
 
80
- /**
81
- * Create the read service object. Methods resolve options as
82
- * { cwd, scope: { session: { id: sessionId } } } and reuse the shared payload
83
- * builders (byte-parity with the /capabilities verbs). All failures are typed
84
- * CapabilityReadError instances.
85
- *
86
- * @param {object} [dependencies] test seams
87
- * @param {Function} [dependencies.bridge] bridge faces getter (default: the module bridge)
88
- * @param {Function} [dependencies.store] profileContext → opened capability store
89
- */
68
+ /** Return the sole generation for an exact preset; no implicit/default owner. */
69
+ export function capabilityReadBridge(presetId) {
70
+ const feeds = bridgeFeeds.get(presetId)
71
+ return feeds?.size === 1 ? [...feeds][0].faces : null
72
+ }
73
+
74
+ function soleFeed(presetId) {
75
+ const feeds = bridgeFeeds.get(presetId)
76
+ if (!feeds?.size) throw new CapabilityReadError('bridge-absent', `capability read: no feed for preset ${presetId}`)
77
+ if (feeds.size !== 1) throw new CapabilityReadError('owner-ambiguous', `capability read: overlapping feeds for preset ${presetId}`)
78
+ return [...feeds][0]
79
+ }
80
+
81
+ /** Extract the current projected owner and its last committed selection generation. */
82
+ function ownership(observation, sessionId) {
83
+ if (!observation || observation.header?.id !== sessionId) {
84
+ throw new CapabilityReadError('unknown-session', `capability read: unknown session ${JSON.stringify(sessionId)}`)
85
+ }
86
+ const presetId = observation.projections?.values?.agentPreset
87
+ if (typeof presetId !== 'string' || !READ_PRESETS.has(presetId)) {
88
+ throw new CapabilityReadError('owner-unavailable', 'capability read: current preset projection is missing or unsupported')
89
+ }
90
+ const events = observation.events
91
+ if (!Array.isArray(events)) throw new CapabilityReadError('owner-unavailable', 'capability read: session selection history is unavailable')
92
+ const selectionSeq = events.reduce((seq, event) => event?.type === PRESET_SELECTED_EVENT && typeof event.seq === 'number' ? Math.max(seq, event.seq) : seq, -1)
93
+ return { presetId, headerPreset: observation.header.agentPreset ?? null, cwd: observation.header.cwd, selectionSeq }
94
+ }
95
+
96
+ /** Create the host read service. Observations are caller-owned leases, always disposed. */
90
97
  export function createCapabilityReadService(dependencies = {}) {
91
- const bridgeFor = dependencies.bridge ?? capabilityReadBridge
98
+ const bridgeFor = dependencies.bridge ?? soleFeed
92
99
  const storeFor = dependencies.store ?? (profileContext => openCapabilityStore({ profileContext }))
93
- // Self-healing registration (registration-race lesson): the typert
94
- // contribution's lifecycle is tied to this plugin's fiber, and any fiber
95
- // re-mount can leave the gateway's strict definition withdrawn (the
96
- // re-enable races the previous registration's disposal and the duplicate
97
- // rejection is swallowed). Verify on EVERY read and re-register on demand —
98
- // a withdrawn channel recovers on the next Badge refresh instead of dying
99
- // until the next app restart.
100
100
  const ensure = dependencies.ensureRegistered ?? (() => true)
101
- const read = async (sessionId, build) => {
102
- if (!ensure()) throw new CapabilityReadError('channel-unavailable', 'capability read channel is not registered with the gateway')
103
- const faces = bridgeFor()
104
- if (!faces) throw new CapabilityReadError('bridge-absent', 'capability read channel is not offered (non-Weir preset or unmounted bridge)')
105
- const location = typeof faces.sessionCwd === 'function' ? faces.sessionCwd(sessionId) : null
106
- if (!location?.found) throw new CapabilityReadError('unknown-session', `capability read: unknown session ${JSON.stringify(typeof sessionId === 'string' ? sessionId : String(sessionId))}`)
107
- const options = { cwd: location.cwd, scope: { session: { id: sessionId } } }
101
+ const onDegraded = dependencies.onDegraded ?? (() => {})
102
+ const observeSession = dependencies.observeSession ?? (sessionId => dependencies.sessionQuery?.()?.observeSession(sessionId))
103
+ const observe = async sessionId => {
104
+ let lease
108
105
  try {
109
- return await build(faces, options)
106
+ lease = await observeSession(sessionId)
107
+ if (!lease || typeof lease[Symbol.dispose] !== 'function') throw new CapabilityReadError('owner-unavailable', 'capability read: session observation is unavailable')
108
+ return { lease, owner: ownership(lease, sessionId) }
110
109
  } catch (cause) {
110
+ lease?.[Symbol.dispose]?.()
111
111
  if (cause instanceof CapabilityReadError) throw cause
112
- throw new CapabilityReadError('payload-failed', `capability read failed: ${cause instanceof Error ? cause.message : String(cause)}`, { cause })
112
+ throw new CapabilityReadError('unknown-session', `capability read: cannot observe session ${JSON.stringify(sessionId)}`, { cause })
113
+ }
114
+ }
115
+ const read = async (sessionId, method, build) => {
116
+ if (!ensure()) throw new CapabilityReadError('channel-unavailable', 'capability read channel is not registered with the gateway')
117
+ const first = await observe(sessionId)
118
+ try {
119
+ const { presetId, cwd, selectionSeq } = first.owner
120
+ const feed = bridgeFor(presetId)
121
+ if (!feed) throw new CapabilityReadError('bridge-absent', `capability read: no feed for preset ${presetId}`)
122
+ const faces = feed.faces ?? feed
123
+ const options = { cwd, scope: { session: { id: sessionId } } }
124
+ let payload
125
+ try {
126
+ payload = await build(faces, options)
127
+ } catch (cause) {
128
+ if (cause instanceof CapabilityReadError) throw cause
129
+ throw new CapabilityReadError('payload-failed', `capability read failed: ${cause instanceof Error ? cause.message : String(cause)}`, { cause })
130
+ }
131
+ // Degraded-receipt diagnostic: a delivered payload with warnings proves
132
+ // the read reached ONE unambiguous owner, but the wire shape cannot say
133
+ // WHICH owner or why the provider degraded. Record the observed identity,
134
+ // header vs projected preset, feed census and the provider's own status so
135
+ // a live "accepted but unverifiable" report is diagnosable without
136
+ // cookies, session-log writes, or skill names.
137
+ if (Array.isArray(payload?.warnings) && payload.warnings.length > 0) {
138
+ try {
139
+ const status = faces.provider?.status?.(options)
140
+ onDegraded({
141
+ method, sessionId, presetId, headerPreset: first.owner.headerPreset,
142
+ source: first.lease?.source ?? null, selectionSeq, cwd,
143
+ warnings: [...payload.warnings],
144
+ providerError: typeof status?.error === 'string' ? status.error : null,
145
+ providerReason: typeof status?.reason === 'string' ? status.reason : null,
146
+ feeds: feedCensus(),
147
+ })
148
+ } catch { /* diagnostics never break a read */ }
149
+ }
150
+ const second = await observe(sessionId)
151
+ try {
152
+ if (second.owner.presetId !== presetId || second.owner.cwd !== cwd || second.owner.selectionSeq !== selectionSeq || bridgeFor(presetId) !== feed) {
153
+ throw new CapabilityReadError('owner-changed', 'capability read: owner or feed changed during read')
154
+ }
155
+ return payload
156
+ } finally {
157
+ second.lease[Symbol.dispose]()
158
+ }
159
+ } finally {
160
+ first.lease[Symbol.dispose]()
113
161
  }
114
162
  }
115
163
  return {
116
- receipt: sessionId => read(sessionId, (faces, options) => buildReceiptPayload({
164
+ receipt: sessionId => read(sessionId, 'receipt', (faces, options) => buildReceiptPayload({
117
165
  provider: faces.provider,
118
166
  lifecycle: faces.lifecycle,
119
167
  store: storeFor(faces.profileContext?.()),
120
168
  }, options)),
121
- list: sessionId => read(sessionId, (faces, options) => buildListPayload({
169
+ list: sessionId => read(sessionId, 'list', (faces, options) => buildListPayload({
122
170
  inventory: faces.inventory,
123
171
  provider: faces.provider,
124
172
  mcpManager: faces.mcpManager?.(),
125
173
  }, options)),
126
- conditions: sessionId => read(sessionId, () => buildConditionsPayload()),
174
+ conditions: sessionId => read(sessionId, 'conditions', () => buildConditionsPayload()),
127
175
  // Presets view reads (silent-preset-reads): the preset listing and the
128
176
  // workspace-default inspection. Domain statuses ({status:'no-workspace'},
129
177
  // a store-level listing failure) are VALUES the panel categorizes — only
130
178
  // infrastructure failures become CapabilityReadError.
131
- presets: sessionId => read(sessionId, (faces, options) => buildPresetsPayload({
179
+ presets: sessionId => read(sessionId, 'presets', (faces, options) => buildPresetsPayload({
132
180
  store: storeFor(faces.profileContext?.()),
133
181
  }, options)),
134
- defaultGet: sessionId => read(sessionId, (faces, options) => buildDefaultGetPayload({
182
+ defaultGet: sessionId => read(sessionId, 'defaultGet', (faces, options) => buildDefaultGetPayload({
135
183
  store: storeFor(faces.profileContext?.()),
136
184
  }, options)),
137
185
  }
@@ -210,7 +258,12 @@ export function apply(ctx) {
210
258
  }
211
259
  }
212
260
  try {
213
- const service = createCapabilityReadService({ ensureRegistered })
261
+ const audit = createAudit(ctx)
262
+ const onDegraded = facts => {
263
+ warn(`weir capability read degraded: method=${facts.method} session=${facts.sessionId} preset=${facts.presetId} header=${facts.headerPreset} source=${facts.source} warnings=${facts.warnings.join(';')} provider=${facts.providerReason ?? '-'}: ${facts.providerError ?? '-'}`)
264
+ audit({ id: facts.sessionId, header: { cwd: facts.cwd } }, 'capability-read', facts)
265
+ }
266
+ const service = createCapabilityReadService({ ensureRegistered, sessionQuery: () => ctx.get?.('sessionQuery'), onDegraded })
214
267
  // The exact frozen binding validateBinding requires (S27): { service,
215
268
  // serviceKey, namespace } — built by hand, no protocol import.
216
269
  service.typertRemote = Object.freeze({
@@ -227,4 +280,4 @@ export function apply(ctx) {
227
280
  }
228
281
 
229
282
  export const name = 'weir-capability-remote'
230
- export const inject = ['typert']
283
+ export const inject = ['typert', 'sessionQuery']