Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 54 additions & 2 deletions src/board/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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
Expand Down
9 changes: 6 additions & 3 deletions src/commands/extract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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<string, unknown[]>)[name])
const proposed = (result as unknown as Record<string, unknown[]>)[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<string, unknown[]>)[name] ?? []) foldChanges.push(`${name}: ${JSON.stringify(item)}`)
Expand Down Expand Up @@ -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<string, unknown> | 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
}
Expand Down
56 changes: 54 additions & 2 deletions src/commands/work.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
rankItem,
readExternalIssues,
readWorkItems,
shortTitle,
stateFor,
summarizeForRecall,
WORK_PRIORITIES,
Expand Down Expand Up @@ -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<string, unknown>[] | null) ?? []) : []
Expand All @@ -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 } : {}),
Expand All @@ -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<string, unknown>[] | 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')
Expand Down
4 changes: 3 additions & 1 deletion src/recall.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}

Expand Down
85 changes: 85 additions & 0 deletions src/requests.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown>[] | 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
}
Loading
Loading