feat: record_directive — the PM's ledger in pm-state (P4, completes Reginald)
The last agent tool. When the PM states standing intent ("pilots come first"),
Reginald logs it verbatim to an append-only JSONL ledger in the pm-state repo —
a directive is intent; its effects still land through propose_change. This
completes Reginald's tool surface: query_project · propose_change · capture_work
· record_directive.
core (@commitea/core):
- directives/record-directive-v0: schema (kind/quote/target/params/rationale +
id/ts/status), serialize/parseDirectiveLog (ts-ordered, seq computed on read,
corrupt lines skipped), appendDirective (concatenation merge), toDirectiveInput.
- RECORD_DIRECTIVE_TOOL + system prompt update ("log standing intent; never claim
a change is applied").
- gitea client: getFile/putFile (contents API, base64-agnostic) for the pm-state repo.
app:
- main: a pm-state client (same token, `commitea-pm-state` repo — the purity
split, D4); appendDirectiveEntry (read→append→write, id/ts stamped here),
readDirectives. model:chat executes record_directive; pmstate:directives reads
the ledger. Degrades cleanly when the pm-state repo is absent.
- Directives screen shows the real ledger when present, the fixture demo otherwise.
Note: the pm-state repo isn't created yet — my token lacks write:user (repo
creation). Create `commitea-pm-state` (private) to activate the live path; all the
code + tests are in place. Override with COMMITEA_PMSTATE_REPO.
Verified: 116 core tests green (8 directive + 2 contents-API added), desktop
typecheck clean, 14 fixture e2e green. Gated live test: the real gemma-4-26b calls
record_directive for "pilots come first" (logs intent, doesn't claim to apply it);
the append/read + POST/PUT contents paths are unit-tested.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -6,18 +6,24 @@
|
||||
* properly later.
|
||||
*/
|
||||
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { dirname, join } from 'node:path'
|
||||
|
||||
import {
|
||||
appendDirective,
|
||||
createGiteaClient,
|
||||
type DirectiveEntry,
|
||||
type GiteaClient,
|
||||
type GiteaConfig,
|
||||
type GiteaLabel,
|
||||
type IssueChange,
|
||||
type LifecycleEvent,
|
||||
makeDirectiveEntry,
|
||||
parseDirectiveLog,
|
||||
planIssueChange,
|
||||
type ProjectSnapshot,
|
||||
type DirectiveInput,
|
||||
} from '@commitea/core'
|
||||
import { ipcMain } from 'electron'
|
||||
|
||||
@@ -62,6 +68,45 @@ export function getGiteaClient(): GiteaClient | null {
|
||||
return sharedClient
|
||||
}
|
||||
|
||||
// The pm-state repo holds machine-derived state (the directive ledger). Same
|
||||
// token/host as the work repo, a different repo (the purity split, decisions D4).
|
||||
let pmStateClient: GiteaClient | null | undefined
|
||||
export function getPmStateClient(): GiteaClient | null {
|
||||
if (pmStateClient === undefined) {
|
||||
const config = resolveConfig()
|
||||
pmStateClient = config
|
||||
? createGiteaClient({ ...config, repo: process.env.COMMITEA_PMSTATE_REPO ?? 'commitea-pm-state' }, fetch)
|
||||
: null
|
||||
}
|
||||
return pmStateClient
|
||||
}
|
||||
|
||||
const DIRECTIVE_LOG_PATH = 'directives/log.jsonl'
|
||||
|
||||
async function readDirectiveLog(client: GiteaClient): Promise<{ text: string; sha: string | null }> {
|
||||
const file = await client.getFile(DIRECTIVE_LOG_PATH)
|
||||
if (!file) return { text: '', sha: null }
|
||||
return { text: Buffer.from(file.contentBase64, 'base64').toString('utf8'), sha: file.sha }
|
||||
}
|
||||
|
||||
/** Record a directive: read the ledger, append, write it back (concatenation merge). */
|
||||
export async function appendDirectiveEntry(client: GiteaClient, input: DirectiveInput): Promise<DirectiveEntry> {
|
||||
const entry = makeDirectiveEntry(input, randomUUID(), new Date().toISOString())
|
||||
const { text, sha } = await readDirectiveLog(client)
|
||||
const next = appendDirective(text, entry)
|
||||
await client.putFile(DIRECTIVE_LOG_PATH, {
|
||||
contentBase64: Buffer.from(next, 'utf8').toString('base64'),
|
||||
message: `directive: ${entry.kind}`,
|
||||
sha: sha ?? undefined,
|
||||
})
|
||||
return entry
|
||||
}
|
||||
|
||||
export async function readDirectives(client: GiteaClient) {
|
||||
const { text } = await readDirectiveLog(client)
|
||||
return parseDirectiveLog(text)
|
||||
}
|
||||
|
||||
/** Full reconcile: issues + milestones + native deps + lifecycle timelines. */
|
||||
export async function reconcileSnapshot(
|
||||
client: GiteaClient,
|
||||
@@ -141,4 +186,15 @@ export function registerGiteaIpc(): void {
|
||||
return { ok: true as const, created }
|
||||
},
|
||||
)
|
||||
|
||||
// Read the directive ledger from the pm-state repo (for the Directives screen).
|
||||
ipcMain.handle('pmstate:directives', async () => {
|
||||
const pm = getPmStateClient()
|
||||
if (!pm) return { ok: false as const, reason: 'unconfigured' as const }
|
||||
try {
|
||||
return { ok: true as const, directives: await readDirectives(pm) }
|
||||
} catch (e) {
|
||||
return { ok: false as const, reason: 'error' as const, message: e instanceof Error ? e.message : String(e) }
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -22,10 +22,11 @@ import {
|
||||
REGINALD_SYSTEM,
|
||||
REGINALD_TOOLS,
|
||||
runAgentTurn,
|
||||
toDirectiveInput,
|
||||
} from '@commitea/core'
|
||||
import { ipcMain } from 'electron'
|
||||
|
||||
import { getGiteaClient, reconcileSnapshot } from './gitea.js'
|
||||
import { appendDirectiveEntry, getGiteaClient, getPmStateClient, reconcileSnapshot } from './gitea.js'
|
||||
|
||||
/** Small local model for prose + the read tool; big model reserved for later decomposition. */
|
||||
function resolveModelRouter(): ModelRouter | null {
|
||||
@@ -106,6 +107,16 @@ export function registerModelIpc(): void {
|
||||
? { proposed: built.map((p) => ({ issue: a.issue, diff: describeChange(p.plan) })) }
|
||||
: { proposed: [], note: 'no change — already at that value' }
|
||||
}
|
||||
if (name === 'record_directive') {
|
||||
const pm = getPmStateClient()
|
||||
if (!pm) return { error: 'pm-state is not configured' }
|
||||
try {
|
||||
const entry = await appendDirectiveEntry(pm, toDirectiveInput(args))
|
||||
return { recorded: { kind: entry.kind, quote: entry.quote } }
|
||||
} catch (e) {
|
||||
return { error: `could not record — is the pm-state repo created? (${e instanceof Error ? e.message : e})` }
|
||||
}
|
||||
}
|
||||
return { error: `unknown tool: ${name}` }
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,10 @@ const api = {
|
||||
/** File a set of captured issues with their est/* + p/* labels. */
|
||||
createIssues: (issues: unknown) => ipcRenderer.invoke('gitea:createIssues', issues),
|
||||
},
|
||||
pmstate: {
|
||||
/** Read the directive ledger from the pm-state repo. */
|
||||
directives: () => ipcRenderer.invoke('pmstate:directives'),
|
||||
},
|
||||
model: {
|
||||
/** Whether a model endpoint is configured (else the UI keeps the scripted Reginald). */
|
||||
status: () => ipcRenderer.invoke('model:status'),
|
||||
|
||||
@@ -8,6 +8,35 @@ export function DirectivesScreen() {
|
||||
const [pending, setPending] = React.useState<DirectivePending | null>(DIRECTIVES.pending)
|
||||
const [entries, setEntries] = React.useState<DirectiveEntry[]>(DIRECTIVES.entries)
|
||||
|
||||
// Real ledger from the pm-state repo, when it exists — else the fixture demo.
|
||||
React.useEffect(() => {
|
||||
let alive = true
|
||||
window.commitea.pmstate
|
||||
.directives()
|
||||
.then((r) => {
|
||||
if (!alive || !r.ok || r.directives.length === 0) return
|
||||
setPending(null)
|
||||
setEntries(
|
||||
r.directives
|
||||
.slice()
|
||||
.reverse()
|
||||
.map((d) => ({
|
||||
seq: d.seq,
|
||||
who: 'You',
|
||||
when: new Date(d.ts).toLocaleDateString(),
|
||||
what: d.quote,
|
||||
why: d.rationale ?? '',
|
||||
status: d.status === 'accepted' ? 'applied' : d.status === 'withdrawn' ? 'withdrawn' : 'superseded',
|
||||
consequence: '',
|
||||
})),
|
||||
)
|
||||
})
|
||||
.catch(() => {})
|
||||
return () => {
|
||||
alive = false
|
||||
}
|
||||
}, [])
|
||||
|
||||
const resolve = (status: string) => {
|
||||
setEntries((e) => [{
|
||||
seq: pending!.seq, who: pending!.who, when: pending!.when, what: pending!.what, why: 'pilot demo on the 14th',
|
||||
|
||||
12
apps/desktop/src/renderer/src/global.d.ts
vendored
12
apps/desktop/src/renderer/src/global.d.ts
vendored
@@ -4,6 +4,7 @@ import type {
|
||||
ChatMessage,
|
||||
CaptureProposal,
|
||||
DependencyEdge,
|
||||
DirectiveRecord,
|
||||
GiteaIssue,
|
||||
GiteaMilestone,
|
||||
IssueChange,
|
||||
@@ -55,12 +56,23 @@ export interface ModelBridge {
|
||||
capture(braindump: string): Promise<CaptureResult>
|
||||
}
|
||||
|
||||
/** The result of reading the directive ledger. */
|
||||
export type DirectivesResult =
|
||||
| { ok: false; reason: 'unconfigured' | 'error'; message?: string }
|
||||
| { ok: true; directives: DirectiveRecord[] }
|
||||
|
||||
/** The pm-state bridge (machine-derived state) exposed by the preload over IPC. */
|
||||
export interface PmStateBridge {
|
||||
directives(): Promise<DirectivesResult>
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
commitea: {
|
||||
platform: string
|
||||
gitea: GiteaBridge
|
||||
model: ModelBridge
|
||||
pmstate: PmStateBridge
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { beforeAll, describe, expect, it } from 'vitest'
|
||||
|
||||
import { extractLabelFacts } from '../labels/label-schema.js'
|
||||
import type { FetchLike, GiteaIssue } from '../gitea/types.js'
|
||||
@@ -10,11 +10,22 @@ import { buildProjectView, type ProjectSnapshot } from './query-project.js'
|
||||
/**
|
||||
* Opt-in (COMMITEA_MODEL_LIVE=1). Drives the real chat client + agent loop
|
||||
* against a local OpenAI-compatible server (LM Studio on :1234 by default),
|
||||
* proving the model calls query_project and narrates the real result.
|
||||
* proving the model calls the tools and narrates the real result. The model is
|
||||
* whatever is loaded (via LM Studio's native API), so it never JIT-swaps.
|
||||
*/
|
||||
const LIVE = !!process.env.COMMITEA_MODEL_LIVE
|
||||
const BASE = process.env.COMMITEA_MODEL_URL ?? 'http://localhost:1234/v1'
|
||||
const MODEL = process.env.COMMITEA_MODEL_SMALL ?? 'google/gemma-4-e4b'
|
||||
let MODEL = process.env.COMMITEA_MODEL_SMALL ?? ''
|
||||
|
||||
beforeAll(async () => {
|
||||
if (!LIVE || MODEL) return
|
||||
const root = BASE.replace(/\/v1\/?$/, '')
|
||||
const loaded = await fetch(`${root}/api/v0/models`)
|
||||
.then((r) => (r.ok ? (r.json() as Promise<{ data?: { id: string; state?: string; type?: string }[] }>) : null))
|
||||
.then((d) => d?.data?.find((m) => m.state === 'loaded' && m.type !== 'embeddings')?.id)
|
||||
.catch(() => undefined)
|
||||
MODEL = loaded ?? 'google/gemma-4-e4b'
|
||||
})
|
||||
|
||||
function issue(over: Partial<GiteaIssue>): GiteaIssue {
|
||||
const labels = over.labels ?? []
|
||||
@@ -59,4 +70,34 @@ describe('agent loop (live model)', () => {
|
||||
},
|
||||
60_000,
|
||||
)
|
||||
|
||||
it.skipIf(!LIVE)(
|
||||
'records a standing instruction via record_directive',
|
||||
async () => {
|
||||
const client = createChatClient({ baseUrl: BASE, model: MODEL }, globalThis.fetch as unknown as FetchLike)
|
||||
const recorded: unknown[] = []
|
||||
const turn = await runAgentTurn({
|
||||
complete: (m, t) => client.complete(m, t),
|
||||
messages: [
|
||||
{ role: 'system', content: REGINALD_SYSTEM },
|
||||
{ role: 'user', content: 'Log this standing directive: pilots come first, everything else waits.' },
|
||||
],
|
||||
tools: REGINALD_TOOLS,
|
||||
execute: async (name, args) => {
|
||||
if (name === 'record_directive') {
|
||||
recorded.push(args)
|
||||
return { recorded: { kind: (args as { kind?: string }).kind ?? 'note' } }
|
||||
}
|
||||
return name === 'query_project'
|
||||
? buildProjectView((args as { view: any }).view, (args as any).filters, SNAP, new Date())
|
||||
: { error: `unknown tool ${name}` }
|
||||
},
|
||||
})
|
||||
|
||||
// the model logged the directive rather than trying to apply it
|
||||
expect(turn.steps.some((s) => s.tool === 'record_directive')).toBe(true)
|
||||
expect(recorded.length).toBeGreaterThan(0)
|
||||
},
|
||||
60_000,
|
||||
)
|
||||
})
|
||||
|
||||
@@ -52,13 +52,40 @@ export const PROPOSE_CHANGE_TOOL: ToolDecl = {
|
||||
},
|
||||
}
|
||||
|
||||
export const REGINALD_TOOLS: ToolDecl[] = [QUERY_PROJECT_TOOL, PROPOSE_CHANGE_TOOL]
|
||||
export const RECORD_DIRECTIVE_TOOL: ToolDecl = {
|
||||
name: 'record_directive',
|
||||
description:
|
||||
'Log a standing instruction from the PM to the durable directive ledger — a reprioritization, ' +
|
||||
'a re-estimate policy, a deadline, a scope or capacity call, or a plain note. Use it when the user ' +
|
||||
'states intent that should persist ("pilots come first", "freeze scope for beta"). This records the ' +
|
||||
'intent verbatim; the actual issue edits still go through propose_change.',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
kind: { type: 'string', enum: ['reprioritize', 'reestimate', 'set-deadline', 'scope', 'capacity', 'note'] },
|
||||
quote: { type: 'string', description: "the PM's own words, stored verbatim" },
|
||||
target: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
issue: { type: 'number' },
|
||||
milestone: { type: 'number' },
|
||||
member: { type: 'string' },
|
||||
},
|
||||
},
|
||||
rationale: { type: 'string', description: 'why (optional)' },
|
||||
},
|
||||
required: ['kind', 'quote'],
|
||||
},
|
||||
}
|
||||
|
||||
export const REGINALD_TOOLS: ToolDecl[] = [QUERY_PROJECT_TOOL, PROPOSE_CHANGE_TOOL, RECORD_DIRECTIVE_TOOL]
|
||||
|
||||
export const REGINALD_SYSTEM = [
|
||||
'You are Reginald, the calm, dry project manager inside CommiTea — a tool that runs projects on Gitea.',
|
||||
'Call query_project to ground every answer in the real project; never invent issues, numbers, or dates.',
|
||||
'The scheduler and forecasts are deterministic code — report their output, do not recompute it.',
|
||||
'To change an estimate or priority, call propose_change — it shows the human a diff to approve.',
|
||||
'When the PM states standing intent ("pilots first", "freeze scope"), call record_directive to log it.',
|
||||
'Never claim a change is applied; you propose, the human approves. Forecasts are ranges, never single dates.',
|
||||
'Refer to issues as #<number>. Be brief and plain — a sentence or two. No preamble, no bullet dumps.',
|
||||
].join(' ')
|
||||
|
||||
66
packages/core/src/directives/record-directive-v0.test.ts
Normal file
66
packages/core/src/directives/record-directive-v0.test.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import {
|
||||
appendDirective,
|
||||
makeDirectiveEntry,
|
||||
parseDirectiveLog,
|
||||
serializeDirective,
|
||||
toDirectiveInput,
|
||||
} from './record-directive-v0.js'
|
||||
|
||||
describe('toDirectiveInput', () => {
|
||||
it('keeps a valid kind + target and drops an empty target', () => {
|
||||
const input = toDirectiveInput({ kind: 'reprioritize', quote: 'pilots first', target: { issue: 87 }, rationale: 'blocked' })
|
||||
expect(input).toEqual({ kind: 'reprioritize', quote: 'pilots first', target: { issue: 87 }, params: undefined, rationale: 'blocked' })
|
||||
expect(toDirectiveInput({ kind: 'note', quote: 'x', target: {} }).target).toBeUndefined()
|
||||
})
|
||||
|
||||
it('falls back to note for an unknown kind', () => {
|
||||
expect(toDirectiveInput({ kind: 'nonsense', quote: 'hmm' }).kind).toBe('note')
|
||||
})
|
||||
})
|
||||
|
||||
describe('serialize + parse round-trip', () => {
|
||||
const entry = makeDirectiveEntry(
|
||||
{ kind: 'reprioritize', quote: 'pilots come first', target: { issue: 87 } },
|
||||
'id-1',
|
||||
'2026-02-01T09:00:00Z',
|
||||
)
|
||||
|
||||
it('serializes to one JSON line', () => {
|
||||
const line = serializeDirective(entry)
|
||||
expect(line).not.toContain('\n')
|
||||
expect(JSON.parse(line)).toMatchObject({ id: 'id-1', kind: 'reprioritize', status: 'accepted' })
|
||||
})
|
||||
|
||||
it('parses a log, orders by ts, and assigns a 1-based seq', () => {
|
||||
const a = serializeDirective(makeDirectiveEntry({ kind: 'note', quote: 'later' }, 'b', '2026-02-02T00:00:00Z'))
|
||||
const b = serializeDirective(makeDirectiveEntry({ kind: 'note', quote: 'earlier' }, 'a', '2026-02-01T00:00:00Z'))
|
||||
const records = parseDirectiveLog(`${a}\n${b}\n`)
|
||||
expect(records.map((r) => r.quote)).toEqual(['earlier', 'later'])
|
||||
expect(records.map((r) => r.seq)).toEqual([1, 2])
|
||||
})
|
||||
|
||||
it('skips blank and corrupt lines without losing the rest', () => {
|
||||
const good = serializeDirective(entry)
|
||||
const records = parseDirectiveLog(`\n{not json\n${good}\n\n`)
|
||||
expect(records).toHaveLength(1)
|
||||
expect(records[0].id).toBe('id-1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('appendDirective', () => {
|
||||
it('concatenates a newline-terminated entry, normalizing a missing trailing newline', () => {
|
||||
const e1 = makeDirectiveEntry({ kind: 'note', quote: 'one' }, 'i1', '2026-01-01T00:00:00Z')
|
||||
const e2 = makeDirectiveEntry({ kind: 'note', quote: 'two' }, 'i2', '2026-01-02T00:00:00Z')
|
||||
let log = appendDirective('', e1)
|
||||
log = appendDirective(log, e2)
|
||||
expect(parseDirectiveLog(log).map((r) => r.quote)).toEqual(['one', 'two'])
|
||||
expect(log.endsWith('\n')).toBe(true)
|
||||
})
|
||||
|
||||
it('handles existing text without a trailing newline', () => {
|
||||
const e = makeDirectiveEntry({ kind: 'note', quote: 'x' }, 'i', '2026-01-01T00:00:00Z')
|
||||
expect(appendDirective('{"id":"prev","ts":"2025-01-01T00:00:00Z"}', e).split('\n').filter(Boolean)).toHaveLength(2)
|
||||
})
|
||||
})
|
||||
106
packages/core/src/directives/record-directive-v0.ts
Normal file
106
packages/core/src/directives/record-directive-v0.ts
Normal file
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* record_directive — the PM's standing instructions ("pilots come first"),
|
||||
* appended to an append-only JSONL ledger in the pm-state repo (decisions.md D4,
|
||||
* pm-state.md). A directive is *intent*: it's logged verbatim; its effects land
|
||||
* later through apply_changes. Merge is concatenation — order derives from `ts`
|
||||
* at read time, so two writers never conflict. `seq` is a display ordinal
|
||||
* computed on read, never stored. This module is pure serialize/parse; the
|
||||
* append (read → concat → write) is the bridge's job.
|
||||
*/
|
||||
|
||||
export type DirectiveKind = 'reprioritize' | 'reestimate' | 'set-deadline' | 'scope' | 'capacity' | 'note'
|
||||
|
||||
export type DirectiveStatus = 'proposed' | 'accepted' | 'amended' | 'withdrawn'
|
||||
|
||||
export interface DirectiveTarget {
|
||||
issue?: number
|
||||
milestone?: number
|
||||
member?: string
|
||||
}
|
||||
|
||||
/** What the record_directive tool captures. */
|
||||
export interface DirectiveInput {
|
||||
kind: DirectiveKind
|
||||
/** Verbatim PM words, shown in the ledger. */
|
||||
quote: string
|
||||
target?: DirectiveTarget
|
||||
/** Structured effect the scheduler applies, e.g. { priority: 1 }. */
|
||||
params?: Record<string, unknown>
|
||||
rationale?: string
|
||||
}
|
||||
|
||||
/** A ledger entry — an input plus its durable id/ts/status. */
|
||||
export interface DirectiveEntry extends DirectiveInput {
|
||||
id: string
|
||||
ts: string
|
||||
status: DirectiveStatus
|
||||
}
|
||||
|
||||
/** A ledger entry as read back, with a computed display ordinal. */
|
||||
export interface DirectiveRecord extends DirectiveEntry {
|
||||
seq: number
|
||||
}
|
||||
|
||||
const DIRECTIVE_KINDS: readonly DirectiveKind[] = [
|
||||
'reprioritize',
|
||||
'reestimate',
|
||||
'set-deadline',
|
||||
'scope',
|
||||
'capacity',
|
||||
'note',
|
||||
]
|
||||
|
||||
/** Normalize a raw tool payload into a DirectiveInput (unknown kind → note). */
|
||||
export function toDirectiveInput(raw: unknown): DirectiveInput {
|
||||
const r = (raw ?? {}) as Record<string, unknown>
|
||||
const kind = DIRECTIVE_KINDS.includes(r.kind as DirectiveKind) ? (r.kind as DirectiveKind) : 'note'
|
||||
const target = (r.target ?? undefined) as DirectiveTarget | undefined
|
||||
return {
|
||||
kind,
|
||||
quote: typeof r.quote === 'string' ? r.quote : '',
|
||||
target: target && (target.issue || target.milestone || target.member) ? target : undefined,
|
||||
params: (r.params && typeof r.params === 'object' ? (r.params as Record<string, unknown>) : undefined),
|
||||
rationale: typeof r.rationale === 'string' ? r.rationale : undefined,
|
||||
}
|
||||
}
|
||||
|
||||
/** Build a full entry from an input + externally-supplied id/ts (Date/uuid live in the caller). */
|
||||
export function makeDirectiveEntry(
|
||||
input: DirectiveInput,
|
||||
id: string,
|
||||
ts: string,
|
||||
status: DirectiveStatus = 'accepted',
|
||||
): DirectiveEntry {
|
||||
return { ...input, id, ts, status }
|
||||
}
|
||||
|
||||
/** One JSONL line (no trailing newline — the caller joins). */
|
||||
export function serializeDirective(entry: DirectiveEntry): string {
|
||||
return JSON.stringify(entry)
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a JSONL log into records ordered by `ts` (then id for stability), with a
|
||||
* 1-based `seq` assigned on read. Blank/corrupt lines are skipped, not fatal.
|
||||
*/
|
||||
export function parseDirectiveLog(text: string): DirectiveRecord[] {
|
||||
const entries: DirectiveEntry[] = []
|
||||
for (const line of text.split('\n')) {
|
||||
const trimmed = line.trim()
|
||||
if (!trimmed) continue
|
||||
try {
|
||||
const e = JSON.parse(trimmed) as DirectiveEntry
|
||||
if (e && typeof e.id === 'string' && typeof e.ts === 'string') entries.push(e)
|
||||
} catch {
|
||||
// skip a corrupt line rather than lose the whole ledger
|
||||
}
|
||||
}
|
||||
entries.sort((a, b) => (a.ts === b.ts ? a.id.localeCompare(b.id) : a.ts.localeCompare(b.ts)))
|
||||
return entries.map((e, i) => ({ ...e, seq: i + 1 }))
|
||||
}
|
||||
|
||||
/** Append a serialized entry to existing log text (concatenation merge). */
|
||||
export function appendDirective(existing: string, entry: DirectiveEntry): string {
|
||||
const base = existing.endsWith('\n') || existing === '' ? existing : existing + '\n'
|
||||
return `${base}${serializeDirective(entry)}\n`
|
||||
}
|
||||
@@ -146,6 +146,28 @@ describe('createGiteaClient.getIssue', () => {
|
||||
])
|
||||
})
|
||||
|
||||
it('getFile returns null on 404 and content+sha on hit', async () => {
|
||||
const miss = stubFetch('nope', 404)
|
||||
expect(await createGiteaClient(CONFIG, miss.fetch).getFile('directives/log.jsonl')).toBeNull()
|
||||
|
||||
const hit = stubFetch({ content: 'aGVsbG8=\n', sha: 'abc123' })
|
||||
const file = await createGiteaClient(CONFIG, hit.fetch).getFile('directives/log.jsonl')
|
||||
expect(file).toEqual({ contentBase64: 'aGVsbG8=', sha: 'abc123' })
|
||||
expect(hit.calls[0].url).toContain('/contents/directives/log.jsonl')
|
||||
})
|
||||
|
||||
it('putFile POSTs to create and PUTs to update (with sha)', async () => {
|
||||
const create = stubFetch({}, 201)
|
||||
await createGiteaClient(CONFIG, create.fetch).putFile('directives/log.jsonl', { contentBase64: 'eA==', message: 'seed' })
|
||||
expect(create.calls[0].init?.method).toBe('POST')
|
||||
expect(JSON.parse(create.calls[0].init?.body ?? '{}')).toEqual({ content: 'eA==', message: 'seed' })
|
||||
|
||||
const update = stubFetch({}, 200)
|
||||
await createGiteaClient(CONFIG, update.fetch).putFile('directives/log.jsonl', { contentBase64: 'eQ==', message: 'append', sha: 's1' })
|
||||
expect(update.calls[0].init?.method).toBe('PUT')
|
||||
expect(JSON.parse(update.calls[0].init?.body ?? '{}')).toEqual({ content: 'eQ==', message: 'append', sha: 's1' })
|
||||
})
|
||||
|
||||
it('createIssue POSTs title/body/labels and returns a normalized issue', async () => {
|
||||
const created = { ...RAW_ISSUE, number: 44, title: 'Retry token refresh', labels: [{ name: 'est/2d' }, { name: 'p/2' }] }
|
||||
const { fetch, calls } = stubFetch(created, 201)
|
||||
|
||||
@@ -105,6 +105,10 @@ export interface GiteaClient {
|
||||
setIssueLabels(index: number, labelIds: number[]): Promise<void>
|
||||
/** Open a new issue with a title, optional body, and label ids. Write. */
|
||||
createIssue(input: { title: string; body?: string; labelIds?: number[] }): Promise<GiteaIssue>
|
||||
/** Read a repo file's base64 content + blob sha; null if it (or the repo) is absent. */
|
||||
getFile(path: string): Promise<{ contentBase64: string; sha: string } | null>
|
||||
/** Create or update a repo file with base64 content (pass `sha` to update). Write. */
|
||||
putFile(path: string, input: { contentBase64: string; message: string; sha?: string }): Promise<void>
|
||||
}
|
||||
|
||||
/** Map raw gitea issue JSON to the normalized domain shape. Pure. */
|
||||
@@ -232,5 +236,25 @@ export function createGiteaClient(config: GiteaConfig, fetchImpl: FetchLike): Gi
|
||||
})) as RawIssue
|
||||
return normalizeIssue(raw)
|
||||
},
|
||||
|
||||
async getFile(path) {
|
||||
const res = await fetchImpl(`${repoBase}/contents/${path}`, {
|
||||
headers: { Authorization: `token ${config.token}`, Accept: 'application/json' },
|
||||
})
|
||||
if (res.status === 404) return null
|
||||
if (!res.ok) {
|
||||
const body = await res.text().catch(() => '')
|
||||
throw new GiteaApiError(res.status, `GET contents/${path} failed (${res.status})`, body)
|
||||
}
|
||||
const json = (await res.json()) as { content?: string; sha: string }
|
||||
return { contentBase64: (json.content ?? '').replace(/\n/g, ''), sha: json.sha }
|
||||
},
|
||||
|
||||
async putFile(path, input) {
|
||||
await request(`/contents/${path}`, {
|
||||
method: input.sha ? 'PUT' : 'POST',
|
||||
body: { content: input.contentBase64, message: input.message, ...(input.sha ? { sha: input.sha } : {}) },
|
||||
})
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,8 +85,30 @@ export { pickModel } from './agent/model-router.js'
|
||||
export type { ModelRouter, TaskKind } from './agent/model-router.js'
|
||||
export { runAgentTurn } from './agent/agent-loop.js'
|
||||
export type { AgentStep, AgentTurn, ToolExecutor } from './agent/agent-loop.js'
|
||||
export { PROPOSE_CHANGE_TOOL, QUERY_PROJECT_TOOL, REGINALD_SYSTEM, REGINALD_TOOLS } from './agent/agent-tools.js'
|
||||
export {
|
||||
PROPOSE_CHANGE_TOOL,
|
||||
QUERY_PROJECT_TOOL,
|
||||
RECORD_DIRECTIVE_TOOL,
|
||||
REGINALD_SYSTEM,
|
||||
REGINALD_TOOLS,
|
||||
} from './agent/agent-tools.js'
|
||||
export { buildProjectView } from './agent/query-project.js'
|
||||
export type { ProjectSnapshot, ProjectView, QueryFilters } from './agent/query-project.js'
|
||||
export { CAPTURE_SYSTEM, captureWork, parseCaptureArgs, PROPOSE_ISSUES_TOOL } from './agent/capture-work.js'
|
||||
export type { CaptureProposal, ProposedIssue } from './agent/capture-work.js'
|
||||
|
||||
export {
|
||||
appendDirective,
|
||||
makeDirectiveEntry,
|
||||
parseDirectiveLog,
|
||||
serializeDirective,
|
||||
toDirectiveInput,
|
||||
} from './directives/record-directive-v0.js'
|
||||
export type {
|
||||
DirectiveEntry,
|
||||
DirectiveInput,
|
||||
DirectiveKind,
|
||||
DirectiveRecord,
|
||||
DirectiveStatus,
|
||||
DirectiveTarget,
|
||||
} from './directives/record-directive-v0.js'
|
||||
|
||||
Reference in New Issue
Block a user