Holds every write to Ed's questions page to its contract (claude/QUESTIONS-PAGE.md), stamps the coordinator's lastActive, and flags answers left without…

Topic helps a community decide what it wants to talk about — and when. Hosts propose topics they could run a session on; electors signal what they want with weighted ❤️s; everyone shares their availability; and the forum turns the most-wanted topics into a schedule of sessions.
A Newspeak House x Sparkle Bureaucracy production.


Topic is a multi-tenant web app: each forum is an independent workspace with its own members, roles, topics, theme, and settings. The heart of the product is a decision loop:
Around the loop: five visibility levels from fully public to deactivated, per-forum theming (colours, fonts, dark palette, custom role labels), a People page with markdown bios and per-forum person pages, stable topic permalinks, an activity timeline, analytics tables, and an admin add-person flow that pre-creates accounts so a new member's first sign-in lands in a ready-made profile.
docs/PRODUCT.md is the full product tour.
A note on names: the product was built as "Timetable", and code identifiers — packages, database tables, internal routes — keep that name. A "timetable" in code is a forum in the UI. See docs/ARCHITECTURE.md for where the boundary sits.
Prerequisites:
npm install
cp .env.example .env
cp .env.example apps/web/.env.local
npm run db:up
npm run db:migrate
npm run db:seed
# Optional, after setting real Clerk development keys in .env:
npm run clerk:seed-dev-users
npm run dev
Local URLs:
http://localhost:3000http://localhost:4000http://localhost:4000/graphqlnpm run db:seed builds a fully populated sample forum from dev-sample-data.md, including deterministic local dev users. To sign in as one of them, run npm run clerk:seed-dev-users (against a Clerk development instance — the script refuses production keys) and use the OTP code 424242 with any +clerk_test email. Seeding details, including how to map a sample person to a real Clerk account, are in docs/DEPLOYMENT.md.
| Command | Description |
|---|---|
npm run dev | Run API and web together |
npm run dev:api / npm run dev:web | Run one app |
npm run typecheck | Type-check every workspace |
npm run test | Run unit tests |
npm run test:e2e | Run Playwright anonymous browser smoke tests |
npm run lint | Lint every workspace (web's own Next config, then lint:node) |
npm run lint:node | Lint apps/api, packages/*, tests, and scripts with the root eslint.config.mjs |
npm run format / npm run format:check | Prettier write / check (defaults; YAML and Markdown are exempt) |
npm run build | Build all workspaces |
npm run db:generate | Generate a SQL migration from the schema |
npm run db:migrate | Apply migrations |
npm run db:seed | Seed the local dev database from dev-sample-data.md |
npm run clerk:seed-dev-users | Create/update Clerk dev users for the sample people |
npm run db:studio | Open Drizzle Studio |
npm run db:up / npm run db:down | Start or stop local Postgres |
Pull requests must keep the full verification path green (CI enforces it):
npm run build && npm run typecheck && npm run lint && \
npm run format:check && npm run test && npm run test:e2e
plus npm run db:migrate when schema or migrations change. Tests are Vitest (packages/shared, apps/api, apps/web) and one Playwright smoke suite (tests/e2e/); the e2e suite always starts its own web server on port 3100 (override with PLAYWRIGHT_PORT), so it runs alongside a dev stack holding :3000. Known coverage gaps are listed in docs/PRODUCT.md.
hooks/register.ts 173 lines1import type { Register } from 'claude-code'
2import { checkWrite, isPage, PAGE_IDS } from './check'
3
4// page-contract: Ed's questions page (claude/QUESTIONS-PAGE.md in edsaperia/dev-ops), kept by code.
5// 1. Every write to the page is checked against the contract before it runs, and refused with the
6// reasons when it breaks it (2026-09-30 to 10-02: items with kind "decision" or "final", items
7// with no status, times in the future — each hid something from Ed).
8// 2. A coordinator's lastActive is stamped at the end of every turn that did work.
9// 3. Answers of the coordinator's project left without handledAt are named to it, at most hourly.
10// 4. A coordinator other than dev-ops's is told when dev-ops main moves, so it re-reads the rules.
11// 5. A page-comment wake read with ReadNotifications is told whose wake thread it came on, from the
12// page's wake collection (2026-10-05: Topic took its own thread for another project's and sat on
13// Ed's "Merge #387"; every coordinator spends a turn finding out whose each comment is).
14// The session counts as a coordinator once it writes coordinators/<project> on the page, or, after a
15// restart has wiped what the mod knew, once its own session link is found in coordinators/<project>,
16// looked for on any turn that did work, not only one that used the page (2026-10-03: dev-ops and Topic
17// stopped being stamped after a restart; 2026-10-04 to 10-21: admit, five times, whose wakes rarely
18// touch the page).
19
20type Doc = Record<string, unknown>
21type Write = { op: string; collection?: unknown; doc_id?: unknown; data?: unknown; file_path?: unknown }
22
23const HANDLED_GRACE_MS = 10 * 60e3
24const REMIND_EVERY_MS = 60 * 60e3
25const RULES_REPO = 'https://github.com/edsaperia/dev-ops.git'
26
27let project = '' // learned from this session's own write to coordinators/<project>
28let pageUrl = 'https://claude.ai/artifact/' + PAGE_IDS[0] // a write to the page's other link replaces it
29let worked = false // this turn made a tool call of its own
30let inside = false // the mod's own tool calls, which are neither work nor checked twice
31let remindedAt = 0
32let rulesSha = ''
33let lookedAt = 0 // when the mod last looked for this session's own link on the page
34const LOOK_EVERY_MS = 60 * 60e3
35let threads: Record<string, string> = {} // wake thread id → project, from the page's wake collection
36let threadsAt = 0
37const THREADS_EVERY_MS = 60e3 // an unknown thread is looked up again after a minute: a new wake thread is written a moment after its first comment
38
39const iso = (ms: number) => new Date(ms).toISOString().replace(/\.\d{3}Z$/, 'Z')
40
41// The documents an ArtifactData read printed, one JSON object per line between its BEGIN and END marks.
42function docsOf(text: unknown): Array<{ id: string; data: Doc; version: number }> {
43 if (typeof text !== 'string') return []
44 const out: Array<{ id: string; data: Doc; version: number }> = []
45 for (const line of text.split('\n')) {
46 const s = line.trim()
47 if (!s.startsWith('{"id"')) continue
48 try { out.push(JSON.parse(s)) } catch { /* not a document line */ }
49 }
50 return out
51}
52
53export const register: Register = on => {
54 on('tool.call', { tool: 'ArtifactData' }, async ($, e, next) => {
55 if (inside) return next(e)
56 worked = true
57 const a = e as unknown as { action: string; url?: string; collection?: string; doc_id?: string; data?: Doc; file_path?: string; writes?: Write[] }
58 if (!isPage(a.url)) return next(e)
59 if (!pageUrl) pageUrl = a.url as string
60 const now = await $.clock.now()
61 const writes: Write[] = a.action === 'batch' ? (a.writes ?? []) : [{ op: a.action, collection: a.collection, doc_id: a.doc_id, data: a.data, file_path: a.file_path }]
62 const why: string[] = []
63 for (const w of writes) {
64 let data = w.data
65 if (data === undefined && typeof w.file_path === 'string') {
66 try { data = JSON.parse(await $.fs.read(w.file_path)) } catch { data = undefined }
67 }
68 why.push(...checkWrite(w.op, w.collection, w.doc_id, data, now))
69 if (w.collection === 'coordinators' && (w.op === 'set' || w.op === 'update') && typeof w.doc_id === 'string') {
70 project = w.doc_id
71 pageUrl = a.url as string
72 }
73 }
74 if (why.length) {
75 return {
76 deny: `page-contract: this write breaks the questions page's contract (claude/QUESTIONS-PAGE.md in edsaperia/dev-ops), so nothing was written:\n- ${why.join('\n- ')}\nFix the item and write it again.`,
77 }
78 }
79 return next(e)
80 })
81
82 on('tool.call', { tool: 'ReadNotifications' }, async ($, e, next) => {
83 const r = await next(e)
84 const text = typeof r.text === 'string' ? r.text : ''
85 if (inside || !PAGE_IDS.some(id => text.includes(id))) return r
86 const ids = [...new Set([...text.matchAll(/"thread"\s*:\s*"([0-9a-f-]{36})"/g)].map(m => m[1] as string))]
87 if (!ids.length) return r
88 inside = true
89 try {
90 const now = await $.clock.now()
91 if (ids.some(id => !threads[id]) && now - threadsAt > THREADS_EVERY_MS) {
92 threadsAt = now
93 const list = await $.tool.call({ tool: 'ArtifactData', action: 'list', url: pageUrl, collection: 'wake' } as never)
94 const map: Record<string, string> = {}
95 for (const d of docsOf((list as { text?: string }).text)) if (typeof d.data.threadId === 'string') map[d.data.threadId] = d.id
96 if (Object.keys(map).length) threads = map
97 }
98 const lines = ids.map(id => {
99 const p = threads[id]
100 if (!p) return `thread ${id} is not in the page's wake collection yet; a coordinator starting a new wake thread writes it there a moment after its first comment, so ${project ? `re-read wake/${project}` : 'check the collection'} before treating it as not yours`
101 return `thread ${id} is ${p}'s wake thread` + (!project ? '' : p === project ? ': yours, read it' : `: not ${project}'s`)
102 })
103 return { ...r, context: [...(r.context ?? []), `page-contract: page comments in this read, by the page's wake collection: ${lines.join('; ')}.`] } as typeof r
104 } catch { return r } finally {
105 inside = false
106 }
107 })
108
109 on('tool.call', ($, e, next) => {
110 if (!inside) worked = true
111 return next(e)
112 })
113
114 on('turn.start', async ($, e, next) => {
115 worked = false
116 if (project && project !== 'dev-ops') {
117 try {
118 const r = await $.process.run(['git', 'ls-remote', RULES_REPO, 'refs/heads/main'], { timeoutMs: 15000 })
119 const sha = r.exitCode === 0 ? r.stdout.split(/\s/)[0] : ''
120 if (sha && rulesSha && sha !== rulesSha) {
121 await $.session.append({ message: { type: 'user', content: [{ type: 'text', text: `page-contract: edsaperia/dev-ops main moved (${rulesSha.slice(0, 7)} → ${sha.slice(0, 7)}) since this session last looked. Before coordinator work, re-read CONVENTIONS.md and claude/QUESTIONS-PAGE.md from dev-ops main with the GitHub tool, or by a fresh git fetch or clone of dev-ops (never the container's checkout from session start) and follow what they say now.` }] } })
122 }
123 if (sha) rulesSha = sha
124 } catch { /* no network: say nothing */ }
125 }
126 return next(e)
127 })
128
129 on('turn.complete', async ($, e, next) => {
130 const done = await next(e)
131 if (!pageUrl || !worked || (e as { agentId?: string }).agentId) return done
132 inside = true
133 try {
134 const now = await $.clock.now()
135 // 1. A session that has not told the mod its project (a restart wipes it):
136 // find this session's own link among the coordinators, at most hourly.
137 if (!project && now - lookedAt > LOOK_EVERY_MS) {
138 lookedAt = now
139 const mine = String(await $.env.get('CLAUDE_CODE_REMOTE_SESSION_ID') ?? '').replace(/^(cse|session)_/, '')
140 if (mine) {
141 const list = await $.tool.call({ tool: 'ArtifactData', action: 'list', url: pageUrl, collection: 'coordinators' } as never)
142 const hit = docsOf((list as { text?: string }).text).find(d => String(d.data.sessionUrl ?? '').endsWith('session_' + mine))
143 if (hit) project = hit.id
144 }
145 }
146 if (!project) return done
147 // 2. lastActive, pinned to the version just read.
148 const got = await $.tool.call({ tool: 'ArtifactData', action: 'get', url: pageUrl, collection: 'coordinators', doc_id: project } as never)
149 const me = docsOf((got as { text?: string }).text).find(d => d.id === project)
150 if (me) {
151 await $.tool.call({ tool: 'ArtifactData', action: 'update', url: pageUrl, collection: 'coordinators', doc_id: project, data: { lastActive: iso(now) }, if_version: me.version } as never)
152 }
153 // 3. Answers older than the grace period with no handledAt (or one older than the answer).
154 if (now - remindedAt > REMIND_EVERY_MS) {
155 const q = await $.tool.call({ tool: 'ArtifactData', action: 'query', url: pageUrl, collection: 'questions', query: { where: [['project', '==', project], ['status', '==', 'answered']], limit: 1000 } } as never)
156 const late = docsOf((q as { text?: string }).text).filter(d => {
157 const at = Date.parse(String((d.data.answer as Doc | undefined)?.at ?? ''))
158 const handled = Date.parse(String(d.data.handledAt ?? ''))
159 return at && now - at > HANDLED_GRACE_MS && (!handled || handled < at)
160 })
161 if (late.length) {
162 remindedAt = now
163 const ids = late.slice(0, 12).map(d => d.id).join(', ') + (late.length > 12 ? ` and ${late.length - 12} more` : '')
164 await $.session.append({ message: { type: 'user', content: [{ type: 'text', text: `page-contract: ${late.length} of ${project}'s answered items on Ed's page have no handledAt (answered over 10 minutes ago): ${ids}. Set handledAt (real clock, if_version pinned) on each you have acted on; act on any you have not.` }] } })
165 }
166 }
167 } catch { /* bookkeeping never breaks a turn */ } finally {
168 inside = false
169 }
170 return done
171 })
172}
173hooks/check.ts 104 lines1// The questions page's data contract (claude/QUESTIONS-PAGE.md in edsaperia/dev-ops), as code.
2// Pure functions: given a write and the time, the reasons it breaks the contract ([] when it holds).
3
4// The page: its claude.ai link and its artifact id. Writes to any other artifact are not checked.
5export const PAGE_IDS = ['FoSoRQxMVh8cZocFpMP6KW', '77dc0e00-9f35-45ee-af49-0632428ebbf5']
6export const isPage = (url: unknown) => typeof url === 'string' && PAGE_IDS.some(id => url.includes(id))
7
8// A time may run ahead of this host's clock by this much (clock skew), never more.
9const SKEW_MS = 2 * 60e3
10
11type Doc = Record<string, unknown>
12const isObj = (v: unknown): v is Doc => !!v && typeof v === 'object' && !Array.isArray(v)
13const isStr = (v: unknown): v is string => typeof v === 'string'
14const isHttps = (v: unknown) => isStr(v) && /^https:\/\//.test(v)
15
16function time(field: string, v: unknown, now: number, why: string[]) {
17 if (v === undefined) return
18 const t = isStr(v) ? Date.parse(v) : NaN
19 if (Number.isNaN(t)) why.push(`${field} is not an ISO time (write it with the real clock, e.g. \`date -u +%FT%TZ\`)`)
20 else if (t > now + SKEW_MS) why.push(`${field} ${v} is in the future (now is ${new Date(now).toISOString()}); write the real clock, never a rounded-up time`)
21}
22
23function links(field: string, v: unknown, why: string[], needText: boolean) {
24 if (v === undefined) return
25 if (!Array.isArray(v)) { why.push(`${field} must be an array`); return }
26 v.forEach((l, i) => {
27 if (!isObj(l) || !isStr(l.label)) why.push(`${field}[${i}] must be an object with a string label`)
28 else if (needText ? !isStr(l.text) : !isHttps(l.url)) why.push(needText ? `${field}[${i}] needs a string text` : `${field}[${i}].url must start with https://`)
29 else if (needText && l.url !== undefined && !isHttps(l.url)) why.push(`${field}[${i}].url must start with https://`)
30 })
31}
32
33// One item of the questions collection: `whole` for a set (every coordinator field must be there),
34// otherwise an update, where only the fields present are checked.
35export function checkQuestion(d: Doc, now: number, whole: boolean): string[] {
36 const why: string[] = []
37 const kind = d.kind
38 if (kind !== undefined && kind !== 'question' && kind !== 'update' && kind !== 'task')
39 why.push(`kind ${JSON.stringify(kind)} is not "question", "update" or "task" (a decision taken on Ed's behalf is an "update"; a builder's FINAL is an "update")`)
40 if (d.status !== undefined && !['open', 'answered', 'withdrawn'].includes(d.status as string))
41 why.push(`status ${JSON.stringify(d.status)} is not "open", "answered" or "withdrawn"`)
42 if (whole) {
43 if (d.status === undefined) why.push('status is missing: a new item is written with "status": "open", or Ed never sees it')
44 if (!isStr(d.title) || !d.title) why.push('title is missing (a string: the item in one line)')
45 if (!isStr(d.context)) why.push(isStr(d.body) ? 'the text goes in "context", not "body"' : 'context is missing (a string: what Ed needs to answer from his phone)')
46 if (!isStr(d.project) || !d.project) why.push('project is missing')
47 if (!isStr(d.askedBy)) why.push('askedBy is missing (e.g. "draft coordinator (cloud)", "builder (PR #12)")')
48 if (d.asked === undefined) why.push(`asked is missing${d.createdAt !== undefined ? ' ("asked", not "createdAt")' : ''}: write the real clock, now ${new Date(now).toISOString()}`)
49 } else {
50 if (d.title !== undefined && (!isStr(d.title) || !d.title)) why.push('title must be a non-empty string')
51 if (d.context !== undefined && !isStr(d.context)) why.push('context must be a string')
52 }
53 time('asked', d.asked, now, why)
54 time('handledAt', d.handledAt, now, why)
55 const effKind = kind ?? (whole ? 'question' : undefined)
56 if (d.options !== undefined || (whole && effKind === 'question')) {
57 const o = d.options
58 if (!Array.isArray(o)) why.push('options must be an array of {key, label, description}')
59 else {
60 if (effKind === 'question' && o.length === 0) why.push('a question needs options (an OK-only item is kind "update"; a Done-only item is kind "task")')
61 o.forEach((x, i) => {
62 if (!isObj(x) || !isStr(x.key) || !x.key || !isStr(x.label)) why.push(`options[${i}] must be {key, label, description}, not ${JSON.stringify(x)}`)
63 })
64 }
65 }
66 links('links', d.links, why, false)
67 links('copy', d.copy, why, true)
68 return why
69}
70
71// One in-flight item: a set needs what the page draws; times are real.
72export function checkFlight(d: Doc, now: number, whole: boolean): string[] {
73 const why: string[] = []
74 if (whole) {
75 if (!isStr(d.project) || !d.project) why.push('project is missing')
76 if (!isStr(d.title) || !d.title) why.push('title is missing')
77 }
78 if (d.status !== undefined && d.status !== 'active' && d.status !== 'done') why.push(`status ${JSON.stringify(d.status)} is not "active" or "done"`)
79 for (const f of ['startedAt', 'updatedAt']) time(f, d[f], now, why)
80 if (d.expectBy !== undefined && d.expectBy !== null && Number.isNaN(Date.parse(String(d.expectBy)))) why.push('expectBy is not an ISO time')
81 links('links', d.links, why, false)
82 return why
83}
84
85export function checkCoordinator(d: Doc, now: number): string[] {
86 const why: string[] = []
87 time('lastActive', d.lastActive, now, why)
88 if (d.sessionUrl !== undefined && !isHttps(d.sessionUrl)) why.push('sessionUrl must start with https://')
89 return why
90}
91
92// One write as the ArtifactData tool takes it (a set or update; a batch is checked entry by entry).
93export function checkWrite(op: string, collection: unknown, docId: unknown, data: unknown, now: number): string[] {
94 if (op !== 'set' && op !== 'update') return []
95 if (!isObj(data)) return []
96 const whole = op === 'set'
97 const where = `${collection}/${docId}`
98 const why = collection === 'questions' ? checkQuestion(data, now, whole)
99 : collection === 'inflight' ? checkFlight(data, now, whole)
100 : collection === 'coordinators' ? checkCoordinator(data, now)
101 : []
102 return why.map(w => `${where}: ${w}`)
103}
104