diff --git a/src/board/http.ts b/src/board/http.ts index a1af027..571732e 100644 --- a/src/board/http.ts +++ b/src/board/http.ts @@ -8,9 +8,10 @@ import { gitShow } from '../bare.js' import { blobStoreFromEnv, MAX_ATTACHMENT_BYTES, TooLarge, writeHashed, type BlobStore } from '../blobs.js' import { addComment, ticketThread } from '../comments.js' import { workAdd, workMove, workSet } from '../commands/project.js' -import { statusBeforeArchive, workRank, type WorkWriteOptions } from '../commands/work.js' +import { statusBeforeArchive, workPromote, workPromoteMany, workRank, type WorkWriteOptions } from '../commands/work.js' +import { requestsSet, REQUESTS_FILE } from '../requests.js' import { serializeFor } from '../queue.js' -import { findItem, labelCounts, summarizeForRecall, WORK_PRIORITIES, WORK_STATUSES, type LoreWorkItem, type RankTarget } from '../work.js' +import { findItem, labelCounts, parseRequests, requestRows, summarizeForRecall, WORK_PRIORITIES, WORK_STATUSES, type LoreWorkItem, type RankTarget } from '../work.js' import { assigneeResolver, assigneeOptions, bareProject, bareProjects, bareWorkItems, boardRole, type BoardRole } from './access.js' import type { LoreConfig } from '../config.js' import { boardSecret, CodeStore, cookieHeader, normalizeEmail, RateLimiter, readCookie, SessionSigner, type Session } from './auth.js' @@ -271,6 +272,57 @@ export function createBoardHandler(opts: BoardOptions): BoardHandler { return send(res, 200, { projects }), true } + // Client requests the fold recorded, with the ticket tracking each one (if any); + // a member can turn one into a ticket. + const reqRoute = /^\/p\/([\w.-]+)\/requests(?:\/([\w.-]+)\/promote)?$/.exec(route) + if (reqRoute) { + const [, context, id] = reqRoute + const project = bareProject(opts.repos, context) + const role = project ? boardRole(project.config, email, admins) : undefined + if (!project || !role) return send(res, 404, { error: 'no such board' }), true + const bare = join(opts.repos, `${context}.git`) + const rows = () => requestRows(parseRequests(gitShow(bare, 'context/derived/requests.yaml', true)), bareWorkItems(opts.repos, project).items) + if (!id && method === 'GET') { + return send(res, 200, { context, project: project.config.project, client: project.config.client?.name, role, archived: project.config.lifecycle === 'archived', requests: rows() }), true + } + if (id && method === 'POST') { + if (role !== 'member') return send(res, 403, { error: 'you can view this board but not change it' }), true + const body = await readBody(req) + const item = await serializeFor(context)(async () => + workPromote(cwd, id, { title: str(body.title), priority: str(body.priority) as never, reason: 'made a ticket from the requests list' }, { context, via: 'web', actor: email, operationId: randomUUID() }), + ) + return send(res, 201, { item, request: rows().find((r) => r.id === id) }), true + } + return send(res, 404, { error: 'not found' }), true + } + // Several requests at once: make tickets, archive, delete, or put back. + const bulkRoute = /^\/p\/([\w.-]+)\/requests-bulk$/.exec(route) + if (bulkRoute && method === 'POST') { + const context = bulkRoute[1] + const project = bareProject(opts.repos, context) + const role = project ? boardRole(project.config, email, admins) : undefined + if (!project || !role) return send(res, 404, { error: 'no such board' }), true + if (role !== 'member') return send(res, 403, { error: 'you can view this board but not change it' }), true + const body = await readBody(req) + const ids = strList(body.ids) ?? [] + const action = str(body.action) + if (ids.length === 0 || ids.length > 500) return send(res, 400, { error: 'select between 1 and 500 requests' }), true + const w: WorkWriteOptions = { context, via: 'web', actor: email, operationId: randomUUID() } + const done = await serializeFor(context)(async () => { + if (action === 'ticket') { + const r = await workPromoteMany(cwd, ids, { reason: 'made a ticket from the requests list' }, w) + return { tickets: r.created.map((i) => i.key), changed: r.created.map((i) => i.request!), skipped: r.skipped } + } + if (action === 'archive' || action === 'delete' || action === 'restore') { + const r = requestsSet(cwd, ids, action, w) + return { tickets: [], changed: r.changed, skipped: r.unchanged } + } + throw new Error('action must be ticket, archive, delete or restore') + }) + const bare = join(opts.repos, `${context}.git`) + return send(res, 200, { ...done, requests: requestRows(parseRequests(gitShow(bare, REQUESTS_FILE, true)), bareWorkItems(opts.repos, project).items) }), true + } + const fileRoute = /^\/p\/([\w.-]+)\/files\/([a-f0-9]{64})$/.exec(route) const m = fileRoute ? null : /^\/p\/([\w.-]+)(?:\/items(?:\/([\w.-]+)(?:\/(move|rank|thread|comments|files|detach))?)?)?$/.exec(route) if (!m && !fileRoute) return send(res, 404, { error: 'not found' }), true diff --git a/src/commands/extract.ts b/src/commands/extract.ts index cf7890f..d3afdaf 100644 --- a/src/commands/extract.ts +++ b/src/commands/extract.ts @@ -10,6 +10,7 @@ import { parse, stringify } from 'yaml' import { loadConfig } from '../config.js' import { describeSows, readSows, summarizeSow } from '../sow.js' import { appendAudit } from '../audit.js' +import { isHumanClosed, reidAroundClosed } from '../requests.js' import { applyFoldChanges, applyFoldCreations, describeWorkForPrompt, liveLabels, describeWorkHistory, readExternalIssues, readWorkItems, workPrefix, writeWorkItems, type WorkChangeProposal, type WorkCreateProposal } from '../work.js' import { loadState, updateState } from '../state.js' import { fallbackApiKey, withCliFallback } from '../llm-fallback.js' @@ -288,14 +289,16 @@ export async function extract(root: string, opts: { report?: boolean; review?: b const inUse = liveLabels(workItems) const workNote = `\n\n# Tracked work (lore tracker ${prefix}: key | rank | status | priority | assignee | labels | title | external tracker state)\n${workItems.length ? describeWorkForPrompt(workItems, today) : '(no tickets yet)'}\n\n# Labels in use (the only labels a new ticket may carry)\n${inUse.length ? inUse.join(', ') : '(none yet — leave labels empty)'}` const user = `Today is ${today}.${clientNote}${commitments}${workNote}${groupNote}\n\n# Current artifacts\n${Object.entries(artifacts) - .map(([name, items]) => `## ${name}\n${stringify(items)}`) + // Requests a person archived or deleted are theirs: the fold neither sees nor reopens them. + .map(([name, items]) => `## ${name}\n${stringify(name === 'requests' ? items.filter((i) => !isHumanClosed(i)) : items)}`) .join('\n')}\n\n# Pinned facts\n${pins}\n\n# New material\n${batches[i].text}` const result = await withRetry(() => onBackend(() => cliFold(model, user), () => sdkFold(model, user)), 2, (attempt, err) => console.warn(` ⚠ batch ${i + 1} attempt ${attempt} failed (${err instanceof Error ? err.message : err}) — retrying`), ) const changes: string[] = [] for (const name of wantArtifacts) { - const merged = acceptFold(name, artifacts[name], (result as unknown as Record)[name]) + const proposed = (result as unknown as Record)[name] + const merged = acceptFold(name, artifacts[name], name === 'requests' ? reidAroundClosed(artifacts[name], proposed) : proposed) if (merged.rejected) console.warn(` ⚠ ${name}: model ${merged.rejected}`) if (merged.added || merged.updated) changes.push(`${name} +${merged.added}/~${merged.updated}`) for (const item of (result as unknown as Record)[name] ?? []) foldChanges.push(`${name}: ${JSON.stringify(item)}`) @@ -809,7 +812,7 @@ function readYamlList(root: string, rel: string): unknown[] { export function reportArtifacts(name: string, items: unknown[], weekAgo: string): unknown[] { const monthAgo = new Date(Date.parse(weekAgo) - 23 * 86_400_000).toISOString().slice(0, 10) const field = (item: unknown, key: string) => String((item as Record | null)?.[key] ?? '') - if (name === 'requests') return items.filter((i) => !['done', 'stale'].includes(field(i, 'status')) || field(i, 'date') >= weekAgo) + if (name === 'requests') return items.filter((i) => !isHumanClosed(i) && (!['done', 'stale'].includes(field(i, 'status')) || field(i, 'date') >= weekAgo)) if (name === 'decisions') return items.filter((i) => field(i, 'date') >= monthAgo) return items } diff --git a/src/commands/work.ts b/src/commands/work.ts index a9d87b4..7fb037a 100644 --- a/src/commands/work.ts +++ b/src/commands/work.ts @@ -16,6 +16,7 @@ import { rankItem, readExternalIssues, readWorkItems, + shortTitle, stateFor, summarizeForRecall, WORK_PRIORITIES, @@ -246,7 +247,7 @@ export function workAdd(cwd: string, input: WorkAddInput, opts: WorkWriteOptions } /** Turn a derived request (req-0007) into a tracked item, keeping its evidence. */ -export function workPromote(cwd: string, requestId: string, input: { title?: string; priority?: WorkPriority; reason?: string } = {}, opts: WorkWriteOptions = {}): LoreWorkItem { +export function workPromote(cwd: string, requestId: string, input: { title?: string; description?: string; priority?: WorkPriority; reason?: string } = {}, opts: WorkWriteOptions = {}): LoreWorkItem { const ctx = resolveContext(cwd, opts) const path = join(ctx.root, 'context/derived/requests.yaml') const requests = existsSync(path) ? ((parse(readFileSync(path, 'utf8')) as Record[] | null) ?? []) : [] @@ -257,9 +258,14 @@ export function workPromote(cwd: string, requestId: string, input: { title?: str const already = items.find((i) => i.request === req.id) if (already) throw new Error(`work promote: ${req.id} is already tracked as ${already.key}`) const source = typeof req.source === 'string' ? req.source : undefined + // A long ask becomes a short title, with the ask itself kept as the ticket's body. + const asked = String(req.request ?? req.id).replace(/\s+/g, ' ').trim() + const title = input.title?.trim() || shortTitle(asked) + const description = input.description?.trim() || (title === asked ? undefined : `${asked}${req.requested_by ? `\n\nAsked by ${req.requested_by}${req.date ? ` on ${String(req.date).slice(0, 10)}` : ''}.` : ''}`) const item: LoreWorkItem = { key: nextKey(items, prefix), - title: input.title?.trim() || String(req.request ?? req.id), + title, + ...(description ? { description } : {}), status: 'todo', state: 'open', ...(priority ? { priority } : {}), @@ -284,6 +290,52 @@ export function workPromote(cwd: string, requestId: string, input: { title?: str }) } +/** + * Turn several derived requests into tickets in one write. Requests already + * tracked are skipped, not errors, so a selection that includes some is fine. + */ +export async function workPromoteMany(cwd: string, requestIds: string[], input: { reason?: string } = {}, opts: WorkWriteOptions = {}): Promise<{ created: LoreWorkItem[]; skipped: string[] }> { + const wanted = [...new Set(requestIds.map((i) => i.trim()).filter(Boolean))] + if (wanted.length === 0) throw new Error('work promote: give at least one request id') + const created: LoreWorkItem[] = [] + const skipped: string[] = [] + await mutateBatch(cwd, opts, 'work item change', async (items, prefix, actor, at, ctx) => { + const path = join(ctx.root, 'context/derived/requests.yaml') + const requests = existsSync(path) ? ((parse(readFileSync(path, 'utf8')) as Record[] | null) ?? []) : [] + const missing = wanted.filter((id) => !requests.some((r) => r.id === id)) + if (missing.length) throw new Error(`work promote: no derived request ${missing.join(', ')} — nothing changed`) + for (const id of wanted) { + const req = requests.find((r) => r.id === id)! + const already = items.find((i) => i.request === id) + if (already) { + skipped.push(`${id} is already ${already.key}`) + continue + } + const source = typeof req.source === 'string' ? req.source : undefined + const asked = String(req.request ?? id).replace(/\s+/g, ' ').trim() + const title = shortTitle(asked) + const description = title === asked ? undefined : `${asked}${req.requested_by ? `\n\nAsked by ${req.requested_by}${req.date ? ` on ${String(req.date).slice(0, 10)}` : ''}.` : ''}` + const item: LoreWorkItem = { + key: nextKey(items, prefix), + title, + ...(description ? { description } : {}), + status: 'todo', + state: 'open', + labels: [], + request: id, + sources: source ? [source] : [], + created: at.slice(0, 10), + updated: at.slice(0, 10), + history: [{ id: randomUUID(), at, by: actor, via: opts.via ?? 'cli', change: { created: true }, reason: input.reason?.trim() || `promoted from ${id}${req.requested_by ? ` (asked by ${req.requested_by}${req.date ? `, ${req.date}` : ''})` : ''}`, ...(source ? { sources: [source] } : {}) }], + } + items.push(item) + created.push(item) + } + return { touched: created.map((i) => ({ key: i.key })), message: `promote ${created.length > 8 ? `${created.length} requests` : created.map((i) => `${i.request} → ${i.key}`).join(', ')}` } + }) + return { created, skipped } +} + export function workMove(cwd: string, key: string, status: string, input: ChangeInput, opts: WorkWriteOptions = {}): LoreWorkItem { const to = requireStatus(status)! const reason = requireReason(input, 'move') diff --git a/src/recall.ts b/src/recall.ts index 92b2d9a..5d7bbef 100644 --- a/src/recall.ts +++ b/src/recall.ts @@ -92,7 +92,9 @@ export function recallData( if (!/\.ya?ml$/.test(entry)) continue const name = entry.replace(/\.ya?ml$/, '') if (category && name !== category) continue - derived[name] = parse(readFileSync(join(derivedDir, entry), 'utf8')) + const value = parse(readFileSync(join(derivedDir, entry), 'utf8')) as unknown + // A request a person deleted is gone for every reader; only its record remains. + derived[name] = name === 'requests' && Array.isArray(value) ? value.filter((r) => (r as { status?: unknown } | null)?.status !== 'deleted') : value } } diff --git a/src/requests.ts b/src/requests.ts new file mode 100644 index 0000000..6a9a2f2 --- /dev/null +++ b/src/requests.ts @@ -0,0 +1,85 @@ +import { existsSync, readFileSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' +import { parse, stringify } from 'yaml' +import { appendAudit } from './audit.js' +import { commitWork, type WorkWriteOptions } from './commands/work.js' +import { resolveContext } from './context.js' +import { authorizeWrite } from './write.js' + +export const REQUESTS_FILE = 'context/derived/requests.yaml' + +/** + * Requests are derived by the fold, with one exception: a person may put a + * request aside. `archived` hides it until someone asks to see it; `deleted` + * hides it for good (the record stays, so its id is never handed to a new + * request and the change can be undone). The fold neither sees nor changes + * a request in either state. + */ +export const HUMAN_CLOSED = ['archived', 'deleted'] as const +export type RequestAction = 'archive' | 'delete' | 'restore' + +export function isHumanClosed(item: unknown): boolean { + return (HUMAN_CLOSED as readonly string[]).includes(String((item as { status?: unknown } | null)?.status ?? '')) +} + +const idNumber = (id: unknown): number => Number(/(\d+)$/.exec(String(id ?? ''))?.[1] ?? 0) + +/** + * The fold cannot see requests a person closed, so it may hand one of their + * ids to a new request. Give any such proposal the next free id instead, so + * it lands as the new request it is and the closed one stays closed. + */ +export function reidAroundClosed(previous: unknown[], proposed: unknown[] | undefined): unknown[] | undefined { + if (!Array.isArray(proposed)) return proposed + const closed = new Set(previous.filter(isHumanClosed).map((i) => String((i as { id?: unknown }).id))) + if (closed.size === 0) return proposed + let next = Math.max(0, ...[...previous, ...proposed].map((i) => idNumber((i as { id?: unknown } | null)?.id))) + return proposed.map((item) => { + const id = (item as { id?: unknown } | null)?.id + if (typeof id !== 'string' || !closed.has(id)) return item + return { ...(item as object), id: `req-${String(++next).padStart(4, '0')}` } + }) +} + +export interface RequestsSetResult { + changed: string[] + unchanged: string[] +} + +/** + * Archive, delete or restore requests: one write, one commit. `restore` + * returns a request to `open`; the next fold re-reads it and may mark it + * done or stale from what it knows. Every id must exist or nothing is written. + */ +export function requestsSet(cwd: string, ids: string[], action: RequestAction, opts: WorkWriteOptions = {}): RequestsSetResult { + const wanted = [...new Set(ids.map((i) => i.trim()).filter(Boolean))] + if (wanted.length === 0) throw new Error('requests: give at least one request id') + const ctx = resolveContext(cwd, opts) + const via = opts.via ?? 'cli' + const actor = authorizeWrite(ctx, opts, 'request change') + const at = opts.at ?? new Date().toISOString() + const path = join(ctx.root, REQUESTS_FILE) + const text = existsSync(path) ? readFileSync(path, 'utf8') : '' + const header = /^(#.*\n)+/.exec(text)?.[0] ?? '# Derived by `lore extract` — regenerable; do not hand-edit.\n' + const list = (parse(text) as Record[] | null) ?? [] + const missing = wanted.filter((id) => !list.some((r) => r.id === id)) + if (missing.length) throw new Error(`requests: no request ${missing.join(', ')} — nothing changed`) + const to = action === 'archive' ? 'archived' : action === 'delete' ? 'deleted' : 'open' + const result: RequestsSetResult = { changed: [], unchanged: [] } + for (const r of list) { + if (!wanted.includes(String(r.id))) continue + // Restoring only applies to what a person closed; a request the fold marked done or stale stays as it is. + if (r.status === to || (action === 'restore' && !isHumanClosed(r))) { + result.unchanged.push(String(r.id)) + continue + } + r.status = to + result.changed.push(String(r.id)) + } + if (result.changed.length === 0) return result + writeFileSync(path, header + stringify(list)) + for (const id of result.changed) appendAudit(ctx.root, { at, action: 'work', actor, via, id }) + const listed = result.changed.length > 8 ? `${result.changed.length} requests` : result.changed.join(', ') + commitWork(ctx, REQUESTS_FILE, `lore: requests ${action} ${listed}`) + return result +} diff --git a/src/work.ts b/src/work.ts index 10714fb..d73c07d 100644 --- a/src/work.ts +++ b/src/work.ts @@ -452,6 +452,60 @@ export function lastHumanChange(item: LoreWorkItem, field: string): string | und return at } +/** One entry of `context/derived/requests.yaml`: something the client asked for, as the fold recorded it. */ +export interface DerivedRequest { + id: string + request: string + requested_by?: string + date?: string + status?: string + source?: string +} + +export function parseRequests(text: string): DerivedRequest[] { + if (!text.trim()) return [] + const parsed = parse(text.replace(/^(#.*\n)+/, '')) as unknown + if (!Array.isArray(parsed)) return [] + return parsed + .filter((r): r is Record => Boolean(r) && typeof r === 'object' && typeof (r as Record).id === 'string') + .filter((r) => r.status !== 'deleted') + .map((r) => ({ + id: String(r.id), + request: String(r.request ?? r.id).replace(/\s+/g, ' ').trim(), + ...(r.requested_by ? { requested_by: String(r.requested_by) } : {}), + ...(r.date ? { date: String(r.date).slice(0, 10) } : {}), + ...(r.status ? { status: String(r.status) } : {}), + ...(typeof r.source === 'string' ? { source: r.source } : {}), + })) +} + +/** A request with the ticket that tracks it, or the open ticket that reads like it. */ +export interface RequestRow extends DerivedRequest { + /** The ticket promoted from this request. */ + ticket?: string + /** An open ticket whose title reads like this request — probably the same work under other words. */ + similar?: string +} + +export function requestRows(requests: DerivedRequest[], items: Pick[]): RequestRow[] { + const byRequest = new Map(items.filter((i) => i.request).map((i) => [i.request!, i.key])) + return requests.map((r) => { + const ticket = byRequest.get(r.id) + const similar = ticket ? undefined : items.find((i) => i.state === 'open' && titleSimilarity(i.title, shortTitle(r.request)) >= 0.7)?.key + return { ...r, ...(ticket ? { ticket } : {}), ...(similar ? { similar } : {}) } + }) +} + +/** A ticket title from a longer ask: the whole text when short, else its first sentence, else a cut at a word. */ +export function shortTitle(text: string, max = 90): string { + const clean = text.replace(/\s+/g, ' ').trim() + if (clean.length <= max) return clean + const sentence = /^(.{20,}?[.!?])\s/.exec(clean)?.[1] + if (sentence && sentence.length <= max) return sentence.replace(/[.!?]$/, '') + const cut = clean.slice(0, max - 1) + return `${cut.slice(0, Math.max(cut.lastIndexOf(' '), 40)).replace(/[\s,;:(–—-]+$/, '')}…` +} + export function summarizeForRecall(item: LoreWorkItem): WorkItemSummary { const { history: hist, ...rest } = item const history = Array.isArray(hist) ? hist : [] diff --git a/test/board.test.ts b/test/board.test.ts index 45b67ae..bbf246e 100644 --- a/test/board.test.ts +++ b/test/board.test.ts @@ -575,3 +575,76 @@ test('board assignees: a photo-only profile reuses a known contact and canonical const after = await api('/p/lore-identity-board', { cookie }) assert.deepEqual(after.body.assignees, ['Cory Schadt']) }) + +test('board requests: lists what the client asked for with its ticket, and a member turns one into a ticket', async () => { + const long = 'Add a skip button to the profile step of onboarding so new members who are in a hurry can finish signing up and fill the rest in later from their settings page' + pushContext( + 'lore-reqs', + { project: 'reqs', client: { name: 'Reqs', domains: ['acme.com'] }, sources: {}, board: { enabled: true, members: ['jane@acme.com'], viewers: ['@viewers.io'] } }, + { + 'context/work/lore/REQ.yaml': `- key: REQ-1\n title: Checkout copy\n status: todo\n state: open\n request: req-0001\n labels: []\n sources: []\n created: 2026-08-04\n updated: 2026-08-04\n history: []\n- key: REQ-2\n title: Black Friday landing page\n status: in_progress\n state: open\n labels: []\n sources: []\n created: 2026-08-04\n updated: 2026-08-04\n history: []\n`, + 'context/derived/requests.yaml': `# Derived\n- id: req-0001\n request: New checkout copy\n requested_by: Priya Patel (client)\n date: 2026-09-01\n status: in_progress\n source: https://slack.com/archives/C1/p1\n- id: req-0002\n request: ${long}\n requested_by: Priya Patel (client)\n date: 2026-09-10\n status: open\n- id: req-0003\n request: Black Friday landing page\n date: 2026-09-11\n status: open\n`, + }, + ) + const member = await signIn('jane@acme.com') + const viewer = await signIn('sam@viewers.io') + + const list = await api('/p/lore-reqs/requests', { cookie: viewer }) + assert.equal(list.status, 200) + assert.deepEqual( + list.body.requests.map((r: any) => [r.id, r.ticket ?? null, r.similar ?? null]), + [['req-0001', 'REQ-1', null], ['req-0002', null, null], ['req-0003', null, 'REQ-2']], + 'a request knows its ticket, and one that reads like an open ticket says so', + ) + assert.equal((await api('/p/lore-reqs/requests', {})).status, 401) + assert.equal((await api('/p/lore-reqs/requests/req-0002/promote', { cookie: viewer, body: {} })).status, 403) + + const made = await api('/p/lore-reqs/requests/req-0002/promote', { cookie: member, body: {} }) + assert.equal(made.status, 201, JSON.stringify(made.body)) + assert.equal(made.body.item.key, 'REQ-3') + assert.equal(made.body.item.request, 'req-0002') + assert.equal(made.body.item.title.length <= 90, true, made.body.item.title) + assert.match(made.body.item.description, /fill the rest in later from their settings page\n\nAsked by Priya Patel \(client\) on 2026-09-10\.$/) + assert.equal(made.body.request.ticket, 'REQ-3') + + const twice = await api('/p/lore-reqs/requests/req-0002/promote', { cookie: member, body: {} }) + assert.equal(twice.status, 400) + assert.match(twice.body.error, /already tracked as REQ-3/) + assert.equal((await api('/p/lore-reqs/requests/req-9999/promote', { cookie: member, body: {} })).status, 400) +}) + +test('board requests: several at once — make tickets, archive, delete, and put back', async () => { + const req = (n: number, text: string, status = 'open') => `- id: req-000${n}\n request: ${text}\n date: 2026-09-0${n}\n status: ${status}\n` + pushContext( + 'lore-bulk', + { project: 'bulk', client: { name: 'Bulk', domains: ['acme.com'] }, sources: {}, board: { enabled: true, members: ['jane@acme.com'], viewers: ['@viewers.io'] } }, + { 'context/derived/requests.yaml': `# Derived\n${req(1, 'Export members to CSV')}${req(2, 'Dark mode')}${req(3, 'Weekly digest email')}${req(4, 'Referral codes')}${req(5, 'Old idea', 'stale')}` }, + ) + const member = await signIn('jane@acme.com') + const viewer = await signIn('sam@viewers.io') + const bulk = (cookie: string, ids: string[], action: string) => api('/p/lore-bulk/requests-bulk', { cookie, body: { ids, action } }) + const state = (rows: any[]) => Object.fromEntries(rows.map((r) => [r.id, r.ticket ?? r.status])) + + assert.equal((await bulk(viewer, ['req-0001'], 'archive')).status, 403) + assert.equal((await bulk(member, [], 'archive')).status, 400) + assert.equal((await bulk(member, ['req-0001'], 'explode')).status, 400) + assert.equal((await bulk(member, ['req-0001', 'req-0099'], 'archive')).status, 400, 'an unknown id changes nothing') + + const tickets = await bulk(member, ['req-0001', 'req-0002'], 'ticket') + assert.equal(tickets.status, 200, JSON.stringify(tickets.body)) + assert.deepEqual(tickets.body.tickets, ['BUL-1', 'BUL-2']) + const again = await bulk(member, ['req-0002', 'req-0003'], 'ticket') + assert.deepEqual([again.body.tickets, again.body.skipped], [['BUL-3'], ['req-0002 is already BUL-2']]) + + const archived = await bulk(member, ['req-0004', 'req-0005'], 'archive') + assert.deepEqual(archived.body.changed, ['req-0004', 'req-0005']) + assert.deepEqual(state(archived.body.requests), { 'req-0001': 'BUL-1', 'req-0002': 'BUL-2', 'req-0003': 'BUL-3', 'req-0004': 'archived', 'req-0005': 'archived' }) + + const deleted = await bulk(member, ['req-0005'], 'delete') + assert.deepEqual(Object.keys(state(deleted.body.requests)), ['req-0001', 'req-0002', 'req-0003', 'req-0004'], 'a deleted request leaves every list') + assert.match(git(join(bares, 'lore-bulk.git'), 'show', 'HEAD:context/derived/requests.yaml'), /id: req-0005\n {2}request: Old idea\n {2}date: 2026-09-05\n {2}status: deleted/, 'its record stays, so the id is never reused') + + const back = await bulk(member, ['req-0004', 'req-0005', 'req-0001'], 'restore') + assert.deepEqual([back.body.changed, back.body.skipped], [['req-0004', 'req-0005'], ['req-0001']]) + assert.equal(state(back.body.requests)['req-0005'], 'open') +}) diff --git a/test/requests.test.ts b/test/requests.test.ts new file mode 100644 index 0000000..802d257 --- /dev/null +++ b/test/requests.test.ts @@ -0,0 +1,27 @@ +import assert from 'node:assert/strict' +import { test } from 'node:test' +import { acceptFold } from '../src/commands/extract.js' +import { reidAroundClosed } from '../src/requests.js' + +test('fold: a request a person archived or deleted keeps its record, and a new request never takes its id', () => { + const previous = [ + { id: 'req-0001', request: 'Export members', status: 'open' }, + { id: 'req-0002', request: 'Dark mode', status: 'archived' }, + { id: 'req-0003', request: 'Old idea', status: 'deleted' }, + ] + // The fold was shown only req-0001, so it numbers its new requests from req-0002. + const proposed = [ + { id: 'req-0001', request: 'Export members', status: 'done' }, + { id: 'req-0002', request: 'Referral codes', status: 'open' }, + { id: 'req-0003', request: 'Weekly digest', status: 'open' }, + ] + const merged = acceptFold('requests', previous, reidAroundClosed(previous, proposed)) + assert.deepEqual(merged.items, [ + { id: 'req-0001', request: 'Export members', status: 'done' }, + { id: 'req-0002', request: 'Dark mode', status: 'archived' }, + { id: 'req-0003', request: 'Old idea', status: 'deleted' }, + { id: 'req-0004', request: 'Referral codes', status: 'open' }, + { id: 'req-0005', request: 'Weekly digest', status: 'open' }, + ]) + assert.deepEqual(reidAroundClosed([{ id: 'req-0001', status: 'open' }], proposed), proposed, 'with nothing closed, ids pass through') +}) diff --git a/web/src/BoardPage.tsx b/web/src/BoardPage.tsx index 2a62bde..db1e0e9 100644 --- a/web/src/BoardPage.tsx +++ b/web/src/BoardPage.tsx @@ -6,6 +6,7 @@ import { ItemDrawer } from './ItemDrawer' import { KanbanView } from './KanbanView' import { ListView } from './ListView' import { NewItemModal } from './NewItemModal' +import { RequestsView } from './RequestsView' import { celebrateTicket, ticketElement } from './celebrate' import { AvatarStack } from './people' import { boardRoute, href, navigate, type Filters, type Route } from './router' @@ -172,7 +173,7 @@ export function BoardPage({ route, onUnauthorized }: { route: BoardRoute; onUnau {board.archived && ' · archived (read-only)'}

- navigate({ ...route, view: k as 'list' | 'kanban' }, true)}> + navigate({ ...route, view: k as 'list' | 'kanban' | 'requests' }, true)}> @@ -183,6 +184,10 @@ export function BoardPage({ route, onUnauthorized }: { route: BoardRoute; onUnau List + + Requests + + @@ -198,12 +203,12 @@ export function BoardPage({ route, onUnauthorized }: { route: BoardRoute; onUnau setFilters((f) => ({ ...f, q }))} className="w-full sm:w-72"> - + - setFilters((f) => ({ ...f, labels }))} /> - setFilters((f) => ({ ...f, assignees }))} withNone /> + {route.view !== 'requests' && setFilters((f) => ({ ...f, labels }))} />} + {route.view !== 'requests' && setFilters((f) => ({ ...f, assignees }))} withNone />} {(filters.labels.length > 0 || filters.assignees.length > 0 || filters.q) && ( + + void bulk(k as 'ticket' | 'archive' | 'delete' | 'restore')} disabledKeys={picked.some((r) => r.status === 'archived') ? [] : ['restore']}> + + + + + + + + + + + + + + + + )} + + + + + + Show ticketed, done, stale & archived + + + + + + + + + {canEdit && ( + + 0 && !allPicked} onChange={(on) => setSelected(on ? new Set(rows.map((r) => r.id)) : new Set())}> + + + + + + + + )} + Request + Asked by + Date + Status + Ticket + +
{requests.length ? 'No requests waiting for a ticket.' : 'No client requests recorded yet.'}
}> + {rows.map((r) => ( + + {canEdit && ( + + toggle(r.id, on)}> + + + + + + + + )} + +
+ + {r.request} + + + {r.id} + {r.source && /^https?:\/\//.test(r.source) && ( + + where it was asked + + + )} + +
+
+ {r.requested_by ?? —} + {r.date ?? '—'} + + + {STATUS_LABEL[r.status ?? ''] ?? r.status ?? '—'} + + + + {r.ticket ? ( + + ) : ( +
+ {canEdit && r.status !== 'done' && r.status !== 'archived' && ( + + )} + {r.similar && ( + + )} +
+ )} +
+
+ ))} +
+
+
+
+ + ) +} diff --git a/web/src/api.ts b/web/src/api.ts index 2c30582..48ded03 100644 --- a/web/src/api.ts +++ b/web/src/api.ts @@ -87,6 +87,20 @@ export interface BoardPerson { role: Role } +/** Something the client asked for, as lore recorded it from the conversation. */ +export interface ClientRequest { + id: string + request: string + requested_by?: string + date?: string + status?: string + source?: string + /** The ticket made from this request. */ + ticket?: string + /** An open ticket that reads like this request. */ + similar?: string +} + export interface Board { context: string project: string @@ -250,6 +264,10 @@ export const api = { connections: () => call<{ connections: Connection[] }>('/oauth/connections'), revokeConnection: (id: string) => call<{ ok: true }>(`/oauth/connections/${enc(id)}/revoke`, { body: {} }), board: (context: string) => call(`/p/${enc(context)}`), + requests: (context: string) => call<{ requests: ClientRequest[]; role: Role; archived: boolean }>(`/p/${enc(context)}/requests`), + requestsBulk: (context: string, ids: string[], action: 'ticket' | 'archive' | 'delete' | 'restore') => + call<{ tickets: string[]; changed: string[]; skipped: string[]; requests: ClientRequest[] }>(`/p/${enc(context)}/requests-bulk`, { body: { ids, action } }), + promote: (context: string, id: string) => call<{ item: Item; request?: ClientRequest }>(`/p/${enc(context)}/requests/${enc(id)}/promote`, { body: {} }), item: (context: string, key: string) => call<{ item: Item }>(`/p/${enc(context)}/items/${enc(key)}`), add: (context: string, fields: Partial>) => call<{ item: Item }>(`/p/${enc(context)}/items`, { body: fields }), diff --git a/web/src/router.ts b/web/src/router.ts index 3162c41..413887b 100644 --- a/web/src/router.ts +++ b/web/src/router.ts @@ -1,7 +1,8 @@ import { useEffect, useState } from 'react' // A small router under /board: "/" (projects), "/host" (host status, admins) -// and "/p/". Everything a person would bookmark — the view, the +// "/p/" (the board) and "/p//requests" (client requests +// not yet ticketed). Everything a person would bookmark — the view, the // open ticket, the filters — lives in the query string. const BASE = '/board' @@ -11,7 +12,7 @@ export interface Filters { labels: string[] /** Any of these assignees, "none" meaning unassigned (empty: any). */ assignees: string[] - /** List view: include done and archived. */ + /** List view: include done and archived. Requests view: include tracked, done and stale. */ closed: boolean /** Board view: show the Archived column. */ archived: boolean @@ -26,7 +27,7 @@ export type Route = | { name: 'profile' } | { name: 'help' } | { name: 'authorize'; request: string } - | { name: 'board'; context: string; view: 'list' | 'kanban'; item?: string; filters: Filters } + | { name: 'board'; context: string; view: 'list' | 'kanban' | 'requests'; item?: string; filters: Filters } export function parseRoute(loc: Location = window.location): Route { const path = loc.pathname.startsWith(BASE) ? loc.pathname.slice(BASE.length) : loc.pathname @@ -35,13 +36,13 @@ export function parseRoute(loc: Location = window.location): Route { if (/^\/profile\/?$/.test(path)) return { name: 'profile' } if (/^\/help\/?$/.test(path)) return { name: 'help' } if (/^\/authorize\/?$/.test(path)) return { name: 'authorize', request: new URLSearchParams(loc.search).get('request') ?? '' } - const m = /^\/p\/([\w.-]+)\/?$/.exec(path) + const m = /^\/p\/([\w.-]+)(\/requests)?\/?$/.exec(path) if (!m) return { name: 'projects' } const q = new URLSearchParams(loc.search) return { name: 'board', context: m[1], - view: q.get('view') === 'list' ? 'list' : 'kanban', + view: m[2] ? 'requests' : q.get('view') === 'list' ? 'list' : 'kanban', item: q.get('item') ?? undefined, filters: { q: q.get('q') ?? '', labels: q.getAll('label'), assignees: q.getAll('assignee'), closed: q.get('closed') === '1', archived: q.get('archived') === '1' }, } @@ -64,7 +65,7 @@ export function href(route: Route): string { if (f.archived) q.set('archived', '1') if (route.item) q.set('item', route.item) const qs = q.toString() - return `${BASE}/p/${route.context}${qs ? `?${qs}` : ''}` + return `${BASE}/p/${route.context}${route.view === 'requests' ? '/requests' : ''}${qs ? `?${qs}` : ''}` } export function boardRoute(context: string): Route {