Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat(github): let an agent file an issue for a gap it hit

enesa8376dec0745
diff --git a/src/core/agents/hook-server.ts b/src/core/agents/hook-server.ts
index e82324928..c23386d7e 100644
--- a/src/core/agents/hook-server.ts
+++ b/src/core/agents/hook-server.ts
@@ -230,7 +230,10 @@ export const requiresVerified: ReadonlySet<string> = new Set([
'notify',
'sticky',
'open-project',
- 'settings'
+ 'settings',
+ // Publishes text from this machine to a repository. `legacy` means "we cannot judge this
+ // caller", and an unjudgeable caller must never be the one that files.
+ 'report-issue'
])
/**
@@ -251,10 +254,13 @@ export const OPEN_PROJECT_CONTROL_REFUSAL = 'Project open refused.'
/** Same posture for `settings`: a caller that cannot prove which node it is must not read this
* machine's settings, and must never be the one a settings dialog names as the requester. */
export const SETTINGS_CONTROL_REFUSAL = 'Settings access refused.'
+/** One sentence, names what was refused, no diagnosis — house style for every refusal here. */
+export const REPORT_ISSUE_CONTROL_REFUSAL = 'Issue reporting refused.'
/** The verified-only refusal, worded for the verb that was refused. */
export function verifiedRefusalFor(verb: string): string {
if (verb === 'settings') return SETTINGS_CONTROL_REFUSAL
+ if (verb === 'report-issue') return REPORT_ISSUE_CONTROL_REFUSAL
if (verb === 'sticky') return STICKY_CONTROL_REFUSAL
if (verb === 'open-project') return OPEN_PROJECT_CONTROL_REFUSAL
return MESSAGING_CONTROL_REFUSAL
diff --git a/src/core/agents/messaging-verified-only.test.ts b/src/core/agents/messaging-verified-only.test.ts
index b660ac628..ddd5c5eeb 100644
--- a/src/core/agents/messaging-verified-only.test.ts
+++ b/src/core/agents/messaging-verified-only.test.ts
@@ -137,7 +137,7 @@ describe('where the verbs sit in the routing tables', () => {
}
})
- it('the verified-only set is exactly the messaging verbs plus sticky, open-project and settings', () => {
+ it('the verified-only set is exactly the messaging verbs plus sticky, open-project, settings and report-issue', () => {
// Pins that nothing ELSE ever drifts in: adding a SHIPPED verb here would strand its legacy
// population with no hatch, which is the one thing this set must never be casually grown by.
// `notify` (folded in from #98, Task 5.2) is a messaging verb like the other two — it writes
@@ -149,16 +149,26 @@ describe('where the verbs sit in the routing tables', () => {
// for a forgeable caller would authorize whoever forged it; new verb, so fail-closed from
// day one strands nobody. `settings` (@shared/settings-verb) is here because its `--set` dialog
// names the requesting node and the user's click grants what that node asked for; also new.
+ // `report-issue` (@core/github/report-issue-service) is here because it PUBLISHES text from
+ // this machine to a repository, with no dialog anywhere on the path — `legacy` means "we
+ // cannot judge this caller", and an unjudgeable caller must never be the one that publishes.
+ // New verb, so fail-closed from day one strands no legacy population either.
expect([...requiresVerified].sort()).toEqual([
'notify',
'open-project',
'reply',
+ 'report-issue',
'send',
'settings',
'sticky'
])
})
+ it('the report-issue refusal is its own flat sentence, not the messaging one', () => {
+ expect(verifiedRefusalFor('report-issue')).toBe('Issue reporting refused.')
+ expect(verifiedRefusalFor('report-issue')).not.toBe(MESSAGING_CONTROL_REFUSAL)
+ })
+
it('the settings refusal is its own flat sentence', () => {
expect(verifiedRefusalFor('settings')).toBe('Settings access refused.')
expect(verifiedRefusalFor('settings')).not.toBe(MESSAGING_CONTROL_REFUSAL)
diff --git a/src/core/canvas-control-core.ts b/src/core/canvas-control-core.ts
index cd5912905..61d41670b 100644
--- a/src/core/canvas-control-core.ts
+++ b/src/core/canvas-control-core.ts
@@ -65,6 +65,46 @@ function settingsVerbDocLines(): string[] {
]
}
+/**
+ * The `report-issue` verb's help, with the caps RENDERED from the constants that enforce them
+ * (`report-issue-core.ts`) rather than re-typed — the same discipline as `messagingGuidanceLines`
+ * and `settingsVerbDocLines`. A number typed into prose drifts the day someone tunes the cap, and
+ * an agent that believes a stale limit retries into a refusal it was told would not happen.
+ *
+ * WHEN TO FILE is the load-bearing half of this text, not the flags. An agent that files whenever
+ * anything goes wrong turns a public tracker into its own scratchpad, so the wording names the
+ * three non-cases (own mistake, failing test, broken code) before it names the case.
+ */
+function reportIssueDocLines(): string[] {
+ return [
+ '- `report-issue --kind <code> --title <one line> --body <text> [--dry-run]` — open a GitHub',
+ ' issue in THIS project\'s repository when NODETERM ITSELF could not do something. Off by',
+ ' default: the user switches it on per project, and until then this is refused by name.',
+ ' FILE WHEN the thing you could not do is a gap in the product: a verb refused because this',
+ ' edition does not implement it, a capability that does not exist, a refusal whose reason is',
+ ' "nodeterm cannot do this", something the skill told you to do that has no way to be done.',
+ ' DO NOT FILE for your own mistakes (wrong flags, a bad id, a verb you misread), for a failing',
+ ' test, for code that is broken in the repository you are working on, or for anything the user',
+ ' asked you to do and you simply found hard. Those are your work, not a product gap.',
+ ' ONE ISSUE PER DISTINCT GAP. Do not check first and do not search for duplicates: repeats are',
+ ' recognised automatically by `--kind` plus the title and folded into the existing issue, so',
+ ' filing the same gap again is free and costs nobody a duplicate. Keep `--kind` STABLE for the',
+ ` same gap (it is half the fingerprint) — a code like \`verb-unsupported\` or`,
+ ' `capability-missing`, never a sentence and never something that changes per run.',
+ ` Limits: ${REPORT_CAP_PER_RUN} reports per nodeterm run and ${REPORT_CAP_PER_DAY} per day, per project; past either you are`,
+ ' refused by name and must tell the user instead. Everything you send is redacted (tokens,',
+ ' keys, home directories, ssh addresses, environment values) and shortened before it is',
+ ' published, but write it as if it were public anyway: do not paste credentials, customer',
+ ' names or private hostnames into `--body`, because only recognisable shapes can be stripped.',
+ ' `--dry-run` returns the exact text that would be published without publishing it.',
+ ` Every issue is labelled \`${REPORT_LABEL}\` and says plainly that a machine filed it.`,
+ ' Refusals are terminal unless they say otherwise: `report-disabled` (the user has not turned',
+ ' it on), `report-no-repo` (this project has no GitHub repository — do NOT file it somewhere',
+ ' else), `report-scope-missing` (the token cannot write issues), `report-cap-run` /',
+ ' `report-cap-day`. Server Edition refuses this verb by name.'
+ ]
+}
+
/**
* The `browser` verb's retry guidance, RENDERED from `BROWSER_RETRYABLE` + `BROWSER_OUTCOME_LABEL`
* (`src/core/browser-outcomes.ts`) — same discipline as `messagingGuidanceLines`: the table is the
@@ -160,6 +200,7 @@ export type ControlVerb =
| 'browser'
| 'open-project'
| 'settings'
+ | 'report-issue'
export interface ControlCommand {
verb: ControlVerb
@@ -204,7 +245,12 @@ const VERBS: ControlVerb[] = [
'open-project',
// Read and ask to change the few settings on the allowlist (@shared/settings-verb). Every change
// is confirmed by the user on the desktop; the Server Edition refuses `--set` by name.
- 'settings'
+ 'settings',
+ // File a GitHub issue in the CALLER'S OWN project's repository when nodeterm could not do
+ // something (@core/github/report-issue-service). Off by default per project; there is no
+ // `--project` flag on purpose — reporting into somebody else's repository is not a capability
+ // an agent should be able to reach by naming an id.
+ 'report-issue'
]
/**
@@ -233,6 +279,11 @@ import {
SETTINGS_VERB_KEY_LIST,
parseSettingsRequest
} from '../shared/settings-verb'
+import {
+ REPORT_CAP_PER_DAY,
+ REPORT_CAP_PER_RUN,
+ REPORT_LABEL
+} from './github/report-issue-core'
/** The `--dry-run` paragraph both agent-facing bodies share, rendered from `DRY_RUN_VERBS`. */
function dryRunDocLines(): string[] {
@@ -273,6 +324,12 @@ export function parseControlRequest(
if (v === 'link' && !args.to) return { error: 'link requires --to <id,id>' }
if (v === 'verify' && !args.node) return { error: 'verify requires --node <id>' }
if (v === 'spawn-team' && !args.team) return { error: 'spawn-team requires --team <json>' }
+ // Both halves are required and neither may be guessed: `--kind` is the stable half of the dedupe
+ // fingerprint (a drifting kind files a fresh issue per turn, which is the spam case) and
+ // `--title` is what a maintainer reads in the issue list.
+ if (v === 'report-issue' && !args.kind) return { error: 'report-issue requires --kind <code>' }
+ if (v === 'report-issue' && !args.title) return { error: 'report-issue requires --title <one line>' }
+ if (v === 'report-issue' && !args.body) return { error: 'report-issue requires --body <text>' }
if (v === 'assign' && !args.node) return { error: 'assign requires --node <id>' }
if (v === 'open-worktree' && !args.branch) return { error: 'open-worktree requires --branch <name>' }
if (v === 'close-worktree' && !args.group) return { error: 'close-worktree requires --group <id>' }
@@ -508,6 +565,7 @@ export function buildCanvasControlInstructions(shimPath: string): string {
' never moves the node on the canvas or changes its group. Use it to reflect progress: move a card',
' to your "In Progress"/"Done" column as work advances.',
...settingsVerbDocLines(),
+ ...reportIssueDocLines(),
...browserVerbDocLines(),
'',
...offScreenGuidanceLines(),
@@ -1027,6 +1085,7 @@ Verbs:
its group, or touches the running session. Use it to reflect progress: as a station finishes,
move its card into your "In Progress" / "Done" column so the board tells the real story.
${settingsVerbDocLines().join('\n')}
+${reportIssueDocLines().join('\n')}
${browserVerbDocLines().join('\n')}
${offScreenGuidanceLines().join('\n')}
diff --git a/src/core/github/client.ts b/src/core/github/client.ts
index 25d5e82ab..9896f08c2 100644
--- a/src/core/github/client.ts
+++ b/src/core/github/client.ts
@@ -1,4 +1,5 @@
import type {
+ CreateIssueInput,
GitHubIssue,
GitHubIssueLabel,
GitHubIssueUser,
@@ -220,6 +221,15 @@ export class GitHubIssuesClient {
if (!isoDate(options.since)) throw new GitHubClientError('invalid-request')
query.set('since', options.since)
}
+ if (options.labels !== undefined) {
+ // Label names are `,`-joined by the API, so one containing a comma cannot be expressed here.
+ // Refuse rather than silently query for two labels that do not exist and get an empty page —
+ // which the dedupe lookup would read as "nothing upstream" and answer by filing a duplicate.
+ if (!string(options.labels, 1_000) || !options.labels.trim()) {
+ throw new GitHubClientError('invalid-request')
+ }
+ query.set('labels', options.labels)
+ }
const response = await this.request(`/repos/${repository}/issues?${query}`, {
method: 'GET',
...(options.etag ? { headers: { 'if-none-match': options.etag } } : {})
@@ -279,6 +289,58 @@ export class GitHubIssuesClient {
return decoded
}
+ /**
+ * Open a new issue. Bounds mirror GitHub's own: a 256-character title and a body the report
+ * composer has already clamped far below the API's 65 536.
+ *
+ * A 403 here is the one a caller must not paper over: a token with `issues: read` lists and gets
+ * issues perfectly and fails only at the write, so the feature looks configured right up to the
+ * moment it matters. `request()` already classifies a non-rate-limit 403 as
+ * `insufficient-permission`; the report service turns that code into the sentence naming the
+ * missing scope.
+ */
+ async createIssue(repository: string, input: CreateIssueInput): Promise<GitHubIssue> {
+ safeRepository(repository)
+ if (!string(input.title, 256) || !input.title.trim() || !string(input.body, 60_000) ||
+ (input.labels !== undefined && (!Array.isArray(input.labels) || input.labels.length > 100 ||
+ input.labels.some((label) => !string(label, 50) || !label.trim())))) {
+ throw new GitHubClientError('invalid-request')
+ }
+ const response = await this.request(`/repos/${repository}/issues`, {
+ method: 'POST',
+ body: JSON.stringify({
+ title: input.title,
+ body: input.body,
+ ...(input.labels?.length ? { labels: input.labels } : {})
+ })
+ })
+ const decoded = issueFrom(await this.json(response))
+ if (!decoded) throw new GitHubClientError('malformed-response')
+ return decoded
+ }
+
+ /** Comment on an existing issue. Returns the comment id; the caller only needs "it landed". */
+ async createIssueComment(
+ repository: string,
+ issueNumber: number,
+ body: string
+ ): Promise<{ id: number }> {
+ safeRepository(repository)
+ if (!positiveInteger(issueNumber, Number.MAX_SAFE_INTEGER) || !string(body, 60_000) ||
+ !body.trim()) {
+ throw new GitHubClientError('invalid-request')
+ }
+ const response = await this.request(`/repos/${repository}/issues/${issueNumber}/comments`, {
+ method: 'POST',
+ body: JSON.stringify({ body })
+ })
+ const value = object(await this.json(response))
+ if (!value || !positiveInteger(Number(value.id), Number.MAX_SAFE_INTEGER)) {
+ throw new GitHubClientError('malformed-response')
+ }
+ return { id: Number(value.id) }
+ }
+
async listRepositoryLabels(
repository: string,
options: { page: number; perPage: number; etag?: string }
diff --git a/src/core/github/host.test.ts b/src/core/github/host.test.ts
index fd56452a3..1705410a2 100644
--- a/src/core/github/host.test.ts
+++ b/src/core/github/host.test.ts
@@ -91,7 +91,9 @@ function fixture() {
getIssue: vi.fn(),
updateIssue: vi.fn(),
listRepositoryLabels: vi.fn(),
- createLabel: vi.fn()
+ createLabel: vi.fn(),
+ createIssue: vi.fn(),
+ createIssueComment: vi.fn()
}
const controller = new GitHubHostController({
project: vi.fn(async (id: string) => id === project.id
diff --git a/src/core/github/report-issue-core.test.ts b/src/core/github/report-issue-core.test.ts
new file mode 100644
index 000000000..57e1b1280
--- /dev/null
+++ b/src/core/github/report-issue-core.test.ts
@@ -0,0 +1,168 @@
+import { describe, expect, it } from 'vitest'
+import {
+ REPORT_CAP_PER_DAY,
+ REPORT_CAP_PER_RUN,
+ RECOMMENT_WINDOW_MS,
+ bodyHasMarker,
+ composeReportBody,
+ decideReport,
+ emptyLedger,
+ fingerprintReport,
+ normalizeForFingerprint,
+ recordReport,
+ reportMarker,
+ type ReportLedger
+} from './report-issue-core'
+
+const ENV = { version: '0.3.7', os: 'linux', edition: 'desktop' }
+const GAP = { kind: 'verb-unsupported', title: 'open-worktree is not supported on Server Edition' }
+const NOW = 1_800_000_000_000
+
+const ledgerWith = (over: Partial<ReportLedger> = {}): ReportLedger => ({ ...emptyLedger(), ...over })
+
+describe('the fingerprint is the identity of a GAP, not of a run', () => {
+ it('is stable across machines: paths, ids and numbers do not change it', () => {
+ const a = fingerprintReport({ kind: 'verb-unsupported', title: 'node nt-8813 failed after 42ms' })
+ const b = fingerprintReport({ kind: 'verb-unsupported', title: 'node nt-2211 failed after 7ms' })
+ expect(a).toBe(b)
+ })
+
+ it('separates genuinely different gaps', () => {
+ expect(fingerprintReport(GAP)).not.toBe(
+ fingerprintReport({ kind: 'capability-missing', title: GAP.title })
+ )
+ })
+
+ it('ignores case and whitespace but keeps the words', () => {
+ expect(normalizeForFingerprint(' Open-Worktree FAILED\n')).toBe('open-worktree failed')
+ })
+})
+
+describe('the body says a machine wrote it, and carries the marker', () => {
+ const body = composeReportBody(
+ { ...GAP, detail: 'tried to open a worktree for branch x', agent: 'claude' },
+ ENV,
+ fingerprintReport(GAP)
+ )
+
+ it('never claims a person reported it', () => {
+ expect(body).toContain('Filed automatically by a nodeterm agent')
+ expect(body).toContain('A human has not read this')
+ })
+
+ it('states the version and platform so a fixed gap can be closed at a glance', () => {
+ expect(body).toContain('0.3.7')
+ expect(body).toContain('linux')
+ })
+
+ it('carries a marker the next run can find', () => {
+ expect(bodyHasMarker(body, fingerprintReport(GAP))).toBe(true)
+ expect(bodyHasMarker(body, 'deadbeefdeadbeef')).toBe(false)
+ })
+
+ it('fences pasted output instead of letting it become markdown', () => {
+ const withOutput = composeReportBody({ ...GAP, detail: 'd', excerpt: '# not a heading' }, ENV, 'f')
+ expect(withOutput).toContain('```\n# not a heading\n```')
+ })
+})
+
+describe('dedupe: a gap that already has an issue is never filed twice', () => {
+ const fp = fingerprintReport(GAP)
+
+ it('files the first time', () => {
+ expect(decideReport({ fingerprint: fp, ledger: emptyLedger(), matches: [], filedThisRun: 0, now: NOW }))
+ .toEqual({ action: 'create', fingerprint: fp })
+ })
+
+ it('COMMENTS rather than creating when an open issue already carries the fingerprint', () => {
+ const decision = decideReport({
+ fingerprint: fp, ledger: emptyLedger(), matches: [{ number: 412 }], filedThisRun: 0, now: NOW
+ })
+ expect(decision).toEqual({ action: 'comment', fingerprint: fp, issueNumber: 412 })
+ })
+
+ it('says nothing at all when it already commented inside the window', () => {
+ const ledger = recordReport(emptyLedger(), fp, 412, NOW, false)
+ const decision = decideReport({
+ fingerprint: fp, ledger, matches: [{ number: 412 }], filedThisRun: 0, now: NOW + 60_000
+ })
+ expect(decision.action).toBe('skip')
+ })
+
+ it('speaks again once the window has passed — a gap still live months later is news', () => {
+ const ledger = recordReport(emptyLedger(), fp, 412, NOW, false)
+ const decision = decideReport({
+ fingerprint: fp, ledger, matches: [{ number: 412 }], filedThisRun: 0, now: NOW + RECOMMENT_WINDOW_MS + 1
+ })
+ expect(decision).toEqual({ action: 'comment', fingerprint: fp, issueNumber: 412 })
+ })
+
+ it('does not instantly refile a gap whose issue was just closed as wontfix', () => {
+ // The lookup asks for OPEN issues, so a closed one produces no match. Without this rule a
+ // maintainer closing the issue would be answered by a fresh copy on the next agent turn.
+ const ledger = recordReport(emptyLedger(), fp, 412, NOW, true)
+ const decision = decideReport({
+ fingerprint: fp, ledger, matches: [], filedThisRun: 0, now: NOW + 60_000
+ })
+ expect(decision.action).toBe('skip')
+ })
+})
+
+describe('caps bound how much NEW noise reaches the tracker', () => {
+ const fp = fingerprintReport(GAP)
+
+ it('refuses past the per-run cap, and names the cap so the agent stops', () => {
+ const decision = decideReport({
+ fingerprint: fp, ledger: emptyLedger(), matches: [], filedThisRun: REPORT_CAP_PER_RUN, now: NOW
+ })
+ expect(decision.action).toBe('refuse')
+ expect((decision as { reason: string }).reason).toContain('report-cap-run')
+ expect((decision as { reason: string }).reason).toContain('Do not retry')
+ })
+
+ it('refuses past the rolling-day cap even in a fresh run', () => {
+ const ledger = ledgerWith({ filedAt: Array.from({ length: REPORT_CAP_PER_DAY }, () => NOW - 1_000) })
+ const decision = decideReport({ fingerprint: fp, ledger, matches: [], filedThisRun: 0, now: NOW })
+ expect(decision.action).toBe('refuse')
+ expect((decision as { reason: string }).reason).toContain('report-cap-day')
+ })
+
+ it('lets yesterday’s reports age out of the day cap', () => {
+ const old = NOW - 25 * 60 * 60 * 1_000
+ const ledger = ledgerWith({ filedAt: Array.from({ length: REPORT_CAP_PER_DAY }, () => old) })
+ expect(decideReport({ fingerprint: fp, ledger, matches: [], filedThisRun: 0, now: NOW }).action)
+ .toBe('create')
+ })
+
+ it('a KNOWN gap is still recognised when the caps are exhausted', () => {
+ // Order regression: caps-before-dedupe would spend the run's budget on five recurrences of one
+ // known gap and then go silent on the sixth, genuinely new one.
+ const decision = decideReport({
+ fingerprint: fp,
+ ledger: ledgerWith({ filedAt: Array.from({ length: REPORT_CAP_PER_DAY }, () => NOW) }),
+ matches: [{ number: 412 }],
+ filedThisRun: REPORT_CAP_PER_RUN,
+ now: NOW
+ })
+ expect(decision).toEqual({ action: 'comment', fingerprint: fp, issueNumber: 412 })
+ })
+})
+
+describe('the ledger', () => {
+ it('counts only filings against the day cap, not comments', () => {
+ const commented = recordReport(emptyLedger(), 'a', 1, NOW, false)
+ expect(commented.filedAt).toEqual([])
+ expect(recordReport(commented, 'b', 2, NOW, true).filedAt).toHaveLength(1)
+ })
+
+ it('prunes entries older than a day so the file cannot grow without bound', () => {
+ const ledger = ledgerWith({ filedAt: [NOW - 48 * 60 * 60 * 1_000, NOW - 1_000] })
+ expect(recordReport(ledger, 'a', 1, NOW, true).filedAt).toHaveLength(2)
+ })
+})
+
+describe('the marker', () => {
+ it('is an HTML comment, so it is invisible in the rendered issue', () => {
+ expect(reportMarker('abc')).toBe('<!-- nodeterm-report:v1:abc -->')
+ })
+})
diff --git a/src/core/github/report-issue-core.ts b/src/core/github/report-issue-core.ts
new file mode 100644
index 000000000..b75038f56
--- /dev/null
+++ b/src/core/github/report-issue-core.ts
@@ -0,0 +1,265 @@
+/**
+ * Composing and rate-deciding an agent-filed issue report. Pure: no clock of its own, no network,
+ * no disk — every decision is a function of what it is handed, so the spam rules are testable
+ * without a GitHub account.
+ *
+ * The premise this file is built on: an automatic filer that files twice is not a minor annoyance,
+ * it is the whole risk. Twenty agents across a fleet hitting the same product gap on the same
+ * afternoon is the NORMAL case, not the pathological one — that is exactly what "report what you
+ * could not do" produces — so the default outcome for a repeated gap must be "say nothing", and
+ * filing must be the narrow path.
+ *
+ * Four independent brakes, deliberately redundant because each fails differently:
+ * 1. FINGERPRINT + remote lookup — the same gap from any machine lands on one issue.
+ * 2. A local ledger — survives an app restart, and answers before any network call is made.
+ * 3. A per-run cap — bounds a loop that re-hits the same code path with varying text.
+ * 4. A per-day cap — bounds the fleet case a per-run cap cannot see.
+ */
+import { createHash } from 'node:crypto'
+
+/** Marker version. Bump only if the fingerprint INPUT changes, which re-keys every open report. */
+const MARKER_VERSION = 'v1'
+
+/** How many reports one app run may file into one project before it stops and says so. */
+export const REPORT_CAP_PER_RUN = 5
+
+/** How many reports one project may accumulate in a rolling day, across app runs. */
+export const REPORT_CAP_PER_DAY = 20
+
+/** After commenting "seen again" on an existing report, stay quiet on it for this long. */
+export const RECOMMENT_WINDOW_MS = 24 * 60 * 60 * 1_000
+
+/** The label every auto-filed issue carries, so a maintainer can find, filter and mute them. */
+export const REPORT_LABEL = 'agent-report'
+export const REPORT_LABEL_COLOR = 'b60205'
+export const REPORT_LABEL_DESCRIPTION = 'Filed automatically by a nodeterm agent; not read by a human first.'
+
+export interface ReportEnvironment {
+ /** nodeterm version, e.g. `0.3.7`. */
+ version: string
+ /** `darwin` / `linux` / `win32`. */
+ os: string
+ /** Which surface filed it — desktop, server. */
+ edition: string
+}
+
+export interface ReportInput {
+ /**
+ * The machine-readable class of what could not be done — a refusal code or verb name, NOT free
+ * prose. This is the stable half of the fingerprint: prose varies per agent and per turn, and a
+ * fingerprint over prose alone would file a fresh issue for every rewording of one gap.
+ */
+ kind: string
+ /** One line, the issue title. */
+ title: string
+ /** The agent's own description of what it was trying to do. */
+ detail: string
+ /** Optional pasted machine output. Clamped and redacted by the caller before it arrives here. */
+ excerpt?: string
+ /** Which agent hit it (`claude`, `codex`, …), for the body only — never the fingerprint. */
+ agent?: string
+}
+
+/**
+ * Normalise a message so the same gap fingerprints identically on two machines and in two runs.
+ * Digits, hex runs and quoted spans all carry per-run identity (a node id, a PID, a path, a
+ * timestamp) and are exactly what would otherwise split one gap into a hundred issues.
+ */
+export function normalizeForFingerprint(message: string): string {
+ return message
+ .toLowerCase()
+ // Long hex / base64-ish runs: ids, hashes, tokens' remnants.
+ .replace(/[0-9a-f]{8,}/g, '#')
+ // Any remaining digit run: ports, counts, line numbers, timestamps.
+ .replace(/\d+/g, '#')
+ .replace(/\s+/g, ' ')
+ .trim()
+ .slice(0, 300)
+}
+
+/**
+ * The host-independent identity of a gap. Built from the KIND and the normalised title only —
+ * never the body, the excerpt, the OS, the version or the agent. Two users on two platforms
+ * hitting one product gap must land on one issue, and a version in the fingerprint would file a
+ * fresh copy of every known gap on every release.
+ */
+export function fingerprintReport(input: Pick<ReportInput, 'kind' | 'title'>): string {
+ const basis = `${input.kind.trim().toLowerCase()}\n${normalizeForFingerprint(input.title)}`
+ return createHash('sha256').update(basis).digest('hex').slice(0, 16)
+}
+
+/** The HTML comment carrying the fingerprint. Invisible when rendered, greppable by the next run,
+ * and — because it is in the body rather than a label — it survives label edits by a maintainer. */
+export function reportMarker(fingerprint: string): string {
+ return `<!-- nodeterm-report:${MARKER_VERSION}:${fingerprint} -->`
+}
+
+/** Does this issue body carry this fingerprint? Substring match on the exact marker, so a body
+ * quoting the marker inside a code fence still counts — that is a report of the same gap. */
+export function bodyHasMarker(body: string, fingerprint: string): boolean {
+ return body.includes(reportMarker(fingerprint))
+}
+
+/**
+ * The issue body. Every sentence here is doing a job:
+ * - it says a MACHINE wrote this and no human read it, first, before the reader forms an opinion
+ * about who is asking them for something;
+ * - it says which version and platform, because a gap that is already fixed must be closable at a
+ * glance;
+ * - it carries the marker, which is the only thing that keeps the next thousand runs quiet.
+ *
+ * It must never claim a person reported this, and must never adopt a person's voice ("I tried…").
+ */
+export function composeReportBody(
+ input: ReportInput,
+ env: ReportEnvironment,
+ fingerprint: string
+): string {
+ const lines = [
+ '> **Filed automatically by a nodeterm agent.**',
+ '> A human has not read this. It was written by an agent that could not complete something and',
+ '> was configured to report it. Close it without ceremony if it is wrong, already known, or not',
+ '> a real gap.',
+ '',
+ '### What the agent could not do',
+ '',
+ input.detail.trim() || '_(no detail given)_',
+ ''
+ ]
+ if (input.excerpt?.trim()) {
+ lines.push('### Output', '', '```', input.excerpt.trim(), '```', '')
+ }
+ lines.push(
+ '### Environment',
+ '',
+ `| | |`,
+ `|---|---|`,
+ `| nodeterm | ${env.version} |`,
+ `| platform | ${env.os} |`,
+ `| surface | ${env.edition} |`,
+ `| agent | ${input.agent ?? 'unknown'} |`,
+ `| kind | \`${input.kind}\` |`,
+ '',
+ reportMarker(fingerprint)
+ )
+ return lines.join('\n')
+}
+
+/** The body of the "this happened again" comment. Deliberately tiny — the issue already says
+ * everything; this only adds that it is still live on a later version. */
+export function composeRecurrenceComment(env: ReportEnvironment, fingerprint: string): string {
+ return [
+ `Seen again by a nodeterm agent on ${env.version} (${env.os}, ${env.edition}).`,
+ '',
+ reportMarker(fingerprint)
+ ].join('\n')
+}
+
+/** One project's machine-local report history. Persisted as-is; see `report-ledger.ts`. */
+export interface ReportLedger {
+ /** Per fingerprint: the issue we filed or commented on, and when we last spoke. */
+ seen: Record<string, { issueNumber: number; lastSpokeAt: number }>
+ /** Timestamps of reports filed, for the rolling-day cap. Pruned on write. */
+ filedAt: number[]
+}
+
+export function emptyLedger(): ReportLedger {
+ return { seen: {}, filedAt: [] }
+}
+
+export type ReportDecision =
+ | { action: 'create'; fingerprint: string }
+ | { action: 'comment'; fingerprint: string; issueNumber: number }
+ | { action: 'skip'; fingerprint: string; issueNumber: number; reason: string }
+ | { action: 'refuse'; fingerprint: string; reason: string }
+
+export interface DecideInput {
+ fingerprint: string
+ ledger: ReportLedger
+ /** Open issues already carrying this fingerprint, newest first. Empty = nothing upstream. */
+ matches: Array<{ number: number }>
+ /** Reports this app run has already filed into this project. */
+ filedThisRun: number
+ now: number
+}
+
+/**
+ * The whole rate decision, in one pure function.
+ *
+ * Order matters and is the opposite of the obvious one: DEDUPE IS CHECKED BEFORE THE CAPS. A gap
+ * that already has an issue costs nothing to recognise and must not consume a cap slot — otherwise
+ * five recurrences of one known gap would exhaust the run's budget and silence the sixth, genuinely
+ * new gap. Caps exist to bound how much NEW noise reaches the tracker, not how often we notice an
+ * old thing.
+ */
+export function decideReport(input: DecideInput): ReportDecision {
+ const { fingerprint, ledger, matches, filedThisRun, now } = input
+ const known = ledger.seen[fingerprint]
+ const upstream = matches[0]
+
+ // Already tracked upstream → at most a quiet "seen again", and only outside the window.
+ if (upstream) {
+ const spokeAt = known?.issueNumber === upstream.number ? known.lastSpokeAt : undefined
+ if (spokeAt !== undefined && now - spokeAt < RECOMMENT_WINDOW_MS) {
+ return {
+ action: 'skip',
+ fingerprint,
+ issueNumber: upstream.number,
+ reason: 'already reported and commented recently'
+ }
+ }
+ return { action: 'comment', fingerprint, issueNumber: upstream.number }
+ }
+
+ // Known locally but gone upstream (closed, deleted, or a repo change): treat as new, but only
+ // once the recomment window has passed, so a closed-as-wontfix issue is not instantly refiled on
+ // a loop. A CLOSED issue carries no marker match because the lookup asks for open ones only.
+ if (known && now - known.lastSpokeAt < RECOMMENT_WINDOW_MS) {
+ return {
+ action: 'skip',
+ fingerprint,
+ issueNumber: known.issueNumber,
+ reason: 'reported recently; its issue is no longer open'
+ }
+ }
+
+ if (filedThisRun >= REPORT_CAP_PER_RUN) {
+ return {
+ action: 'refuse',
+ fingerprint,
+ reason:
+ `report-cap-run: this nodeterm run has already filed ${REPORT_CAP_PER_RUN} reports for ` +
+ 'this project, which is the limit. Do not retry; tell the user what you found instead.'
+ }
+ }
+
+ const dayAgo = now - 24 * 60 * 60 * 1_000
+ const today = ledger.filedAt.filter((t) => t > dayAgo).length
+ if (today >= REPORT_CAP_PER_DAY) {
+ return {
+ action: 'refuse',
+ fingerprint,
+ reason:
+ `report-cap-day: ${REPORT_CAP_PER_DAY} reports have been filed for this project in the ` +
+ 'last 24 hours, which is the limit. Do not retry; tell the user what you found instead.'
+ }
+ }
+
+ return { action: 'create', fingerprint }
+}
+
+/** Fold an outcome back into the ledger. Pure; the caller persists the result. Prunes the
+ * rolling-day list here so the file cannot grow without bound. */
+export function recordReport(
+ ledger: ReportLedger,
+ fingerprint: string,
+ issueNumber: number,
+ now: number,
+ filed: boolean
+): ReportLedger {
+ const dayAgo = now - 24 * 60 * 60 * 1_000
+ return {
+ seen: { ...ledger.seen, [fingerprint]: { issueNumber, lastSpokeAt: now } },
+ filedAt: filed ? [...ledger.filedAt.filter((t) => t > dayAgo), now] : ledger.filedAt.filter((t) => t > dayAgo)
+ }
+}
diff --git a/src/core/github/report-issue-service.test.ts b/src/core/github/report-issue-service.test.ts
new file mode 100644
index 000000000..405c168e9
--- /dev/null
+++ b/src/core/github/report-issue-service.test.ts
@@ -0,0 +1,227 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { GitHubClientError } from './client'
+import {
+ reportIssue,
+ resetReportRunCounters,
+ type ReportIssueClient,
+ type ReportIssueDeps
+} from './report-issue-service'
+import {
+ REPORT_CAP_PER_RUN,
+ REPORT_LABEL,
+ composeReportBody,
+ emptyLedger,
+ fingerprintReport,
+ type ReportLedger
+} from './report-issue-core'
+
+const ENV = { version: '0.3.7', os: 'linux', edition: 'desktop' }
+const INPUT = {
+ kind: 'verb-unsupported',
+ title: 'open-worktree is not supported on Server Edition',
+ detail: 'tried to create a worktree for branch feat/x'
+}
+
+function issue(number: number, body: string) {
+ return {
+ id: number, number, title: 't', body, state: 'open' as const, stateReason: null,
+ htmlUrl: `https://github.com/o/r/issues/${number}`, apiUrl: '', labels: [], assignees: [],
+ createdAt: '2026-01-01T00:00:00Z', updatedAt: '2026-01-01T00:00:00Z', locked: false
+ }
+}
+
+function fakeClient(over: Partial<ReportIssueClient> = {}) {
+ const created: Array<{ title: string; body: string; labels?: string[] }> = []
+ const comments: Array<{ issueNumber: number; body: string }> = []
+ const client: ReportIssueClient & { created: typeof created; comments: typeof comments } = {
+ created,
+ comments,
+ listIssues: vi.fn(async () => ({ items: [] })),
+ createIssue: vi.fn(async (_repo: string, input) => {
+ created.push(input)
+ return issue(101, input.body)
+ }),
+ createIssueComment: vi.fn(async (_repo: string, issueNumber: number, body: string) => {
+ comments.push({ issueNumber, body })
+ return { id: 1 }
+ }),
+ listRepositoryLabels: vi.fn(async () => ({ items: [] })),
+ createLabel: vi.fn(async () => ({ id: 1, name: REPORT_LABEL, color: 'b60205', description: null })),
+ ...over
+ } as never
+ return client
+}
+
+function deps(over: Partial<ReportIssueDeps> = {}, client = fakeClient()): ReportIssueDeps & {
+ client: ReturnType<typeof fakeClient>
+ saved: ReportLedger[]
+} {
+ const saved: ReportLedger[] = []
+ return {
+ client,
+ saved,
+ contextForProject: async () => ({ repository: 'owner/repo', client }),
+ granted: () => true,
+ loadLedger: async () => emptyLedger(),
+ saveLedger: async (_id: string, ledger: ReportLedger) => { saved.push(ledger) },
+ env: ENV,
+ ...over
+ } as never
+}
+
+beforeEach(() => resetReportRunCounters())
+
+describe('the consent gate', () => {
+ it('refuses when the project switch is off, and names the switch', async () => {
+ const d = deps({ granted: () => false })
+ const result = await reportIssue(d, { projectId: 'p', input: INPUT })
+ expect(result.ok).toBe(false)
+ expect((result as { message: string }).message).toContain('switched off for this project')
+ expect((result as { message: string }).message).toContain('Settings → Agents')
+ expect(d.client.createIssue).not.toHaveBeenCalled()
+ })
+
+ it('reads the grant per call, so revoking it stops the NEXT report', async () => {
+ let on = true
+ const d = deps({ granted: () => on })
+ expect((await reportIssue(d, { projectId: 'p', input: INPUT })).ok).toBe(true)
+ on = false
+ expect((await reportIssue(d, { projectId: 'p', input: INPUT })).ok).toBe(false)
+ expect(d.client.createIssue).toHaveBeenCalledTimes(1)
+ })
+})
+
+describe('the repository comes from the project, or there is none', () => {
+ it('refuses a project with no repo — and never substitutes another', async () => {
+ const d = deps({
+ contextForProject: async () => { throw new Error('repository-not-found') }
+ })
+ const result = await reportIssue(d, { projectId: 'p', input: INPUT })
+ expect(result.ok).toBe(false)
+ expect((result as { message: string }).message).toContain('no GitHub repository configured')
+ expect((result as { message: string }).message).toContain('do not file it anywhere else')
+ })
+
+ it('names the machine-local approval when that is what is missing', async () => {
+ const d = deps({ contextForProject: async () => { throw new Error('not-approved') } })
+ const result = await reportIssue(d, { projectId: 'p', input: INPUT })
+ expect((result as { message: string }).message).toContain('has not approved GitHub access')
+ })
+})
+
+describe('a read-only token fails only at the write, so it must say so', () => {
+ it('turns a 403 into the missing-scope sentence, not a generic failure', async () => {
+ const client = fakeClient({
+ createIssue: vi.fn(async () => { throw new GitHubClientError('insufficient-permission', 403) })
+ })
+ const result = await reportIssue(deps({}, client), { projectId: 'p', input: INPUT })
+ expect(result.ok).toBe(false)
+ const message = (result as { message: string }).message
+ expect(message).toContain('Issues: read and write')
+ expect(message).toContain('403')
+ expect(message).not.toMatch(/^report-failed/)
+ })
+})
+
+describe('dedupe', () => {
+ it('files the first report, with the marker label', async () => {
+ const d = deps()
+ const result = await reportIssue(d, { projectId: 'p', input: INPUT })
+ expect(result).toMatchObject({ ok: true, action: 'created', issueNumber: 101 })
+ expect(d.client.created[0].labels).toEqual([REPORT_LABEL])
+ })
+
+ it('COMMENTS on the existing issue instead of filing a second', async () => {
+ const fp = fingerprintReport({ kind: INPUT.kind, title: INPUT.title })
+ const existing = composeReportBody({ ...INPUT }, ENV, fp)
+ const client = fakeClient({ listIssues: vi.fn(async () => ({ items: [issue(412, existing)] })) })
+ const d = deps({}, client)
+ const result = await reportIssue(d, { projectId: 'p', input: INPUT })
+ expect(result).toMatchObject({ ok: true, action: 'commented', issueNumber: 412 })
+ expect(client.createIssue).not.toHaveBeenCalled()
+ expect(client.comments[0].body).toContain('Seen again')
+ })
+
+ it('files NOTHING when the dedupe lookup itself failed', async () => {
+ // A failed lookup is not evidence that nothing was reported. Filing anyway on a transient 500
+ // is how one gap becomes twenty issues.
+ const client = fakeClient({
+ listIssues: vi.fn(async () => { throw new GitHubClientError('request-failed', 500) })
+ })
+ const result = await reportIssue(deps({}, client), { projectId: 'p', input: INPUT })
+ expect(result.ok).toBe(false)
+ expect((result as { message: string }).message).toContain('nothing was filed')
+ expect(client.createIssue).not.toHaveBeenCalled()
+ })
+
+ it('fingerprints the REDACTED title, so one gap is one issue across machines', async () => {
+ const a = deps()
+ await reportIssue(a, { projectId: 'p', input: { ...INPUT, title: 'boom in /home/alice/app' } })
+ const b = deps()
+ await reportIssue(b, { projectId: 'p2', input: { ...INPUT, title: 'boom in /Users/bob/app' } })
+ const marker = (body: string) => body.match(/nodeterm-report:v1:([0-9a-f]+)/)?.[1]
+ expect(marker(a.client.created[0].body)).toBe(marker(b.client.created[0].body))
+ })
+})
+
+describe('caps', () => {
+ it('stops filing after the per-run cap and says which cap', async () => {
+ const d = deps()
+ for (let i = 0; i < REPORT_CAP_PER_RUN; i += 1) {
+ await reportIssue(d, { projectId: 'p', input: { ...INPUT, title: `gap number ${i} here` } })
+ }
+ const result = await reportIssue(d, { projectId: 'p', input: { ...INPUT, title: 'one gap too many' } })
+ expect(result.ok).toBe(false)
+ expect((result as { message: string }).message).toContain('report-cap-run')
+ expect(d.client.createIssue).toHaveBeenCalledTimes(REPORT_CAP_PER_RUN)
+ })
+
+ it('counts the cap per project, not per machine', async () => {
+ const d = deps()
+ for (let i = 0; i < REPORT_CAP_PER_RUN; i += 1) {
+ await reportIssue(d, { projectId: 'p', input: { ...INPUT, title: `gap number ${i} here` } })
+ }
+ const other = await reportIssue(d, { projectId: 'other', input: { ...INPUT, title: 'fresh project gap' } })
+ expect(other.ok).toBe(true)
+ })
+})
+
+describe('redaction is applied to what is actually published', () => {
+ it('strips a secret the agent pasted into the detail', async () => {
+ const d = deps()
+ await reportIssue(d, {
+ projectId: 'p',
+ input: { ...INPUT, detail: 'ran with ghp_A1b2C3d4E5f6G7h8I9j0K1l2M3n4O5p6Q7r8 set' }
+ })
+ expect(d.client.created[0].body).not.toContain('ghp_A1b2')
+ expect(d.client.created[0].body).toContain('[redacted]')
+ })
+
+ it('strips the home path out of the TITLE too', async () => {
+ const d = deps()
+ await reportIssue(d, { projectId: 'p', input: { ...INPUT, title: 'crash in /home/jdoe/app.ts' } })
+ expect(d.client.created[0].title).toBe('crash in ~/app.ts')
+ })
+})
+
+describe('dry run', () => {
+ it('returns the exact text that would be published and publishes nothing', async () => {
+ const d = deps()
+ const result = await reportIssue(d, { projectId: 'p', input: INPUT, dryRun: true })
+ expect(result).toMatchObject({ ok: true, action: 'dry-run' })
+ expect((result as { preview: string }).preview).toContain('Filed automatically by a nodeterm agent')
+ expect(d.client.createIssue).not.toHaveBeenCalled()
+ expect(d.client.listIssues).not.toHaveBeenCalled()
+ })
+})
+
+describe('validation lives at the acting layer too', () => {
+ it('refuses a report with no body, even though main never runs parseControlRequest', () => {
+ // The desktop path answers `report-issue` in main and returns before the renderer forward, so
+ // the parser's own `--body` rule is never reached there. Two entry points, one rule.
+ return reportIssue(deps(), { projectId: 'p', input: { ...INPUT, detail: ' ' } }).then((r) => {
+ expect(r.ok).toBe(false)
+ expect((r as { message: string }).message).toContain('--kind, --title and --body')
+ })
+ })
+})
diff --git a/src/core/github/report-issue-service.ts b/src/core/github/report-issue-service.ts
new file mode 100644
index 000000000..4c29d8e2d
--- /dev/null
+++ b/src/core/github/report-issue-service.ts
@@ -0,0 +1,328 @@
+/**
+ * The agent-filed issue report, end to end — in `src/core` so BOTH shells get it (the desktop's
+ * control handler and the Server Edition's call the same function; neither owns a copy).
+ *
+ * Deliberately NOT in the renderer, and deliberately not behind a per-report dialog. The whole
+ * point of the feature is that an agent which hit a product gap at 03:00 reports it instead of
+ * dying in a pane nobody reads, so a dialog per report would defeat it. What replaces the dialog
+ * is a stack of refusals, each of which must pass before anything is published:
+ *
+ * 1. The per-project capability must be GRANTED (`agentIssueReporting`) — default off, and a
+ * switch arriving from a clone grants nothing until this machine's user answers its notice.
+ * 2. The project must have a GitHub repo of its own. There is no fallback repository, ever:
+ * falling back to nodeterm's own tracker would turn every other user's machine into a
+ * firehose aimed at us.
+ * 3. The caller's node identity must be `verified` (enforced upstream, in the hook server).
+ * 4. The text is redacted, clamped, fingerprinted and deduplicated.
+ * 5. Caps bound what survives all of that.
+ *
+ * ── THE RISK THIS FILE CANNOT REMOVE ────────────────────────────────────────────────────────────
+ * `resolveProject` derives the repository from `kanban.github.repository` OR, when unset, from the
+ * project's own git origin. For anyone working ON nodeterm that origin IS nodeterm's repository —
+ * so a contributor who grants this capability files into OUR public tracker, which is correct
+ * (a nodeterm gap belongs there) and also exactly the spam vector. The dedupe fingerprint is what
+ * makes that survivable: one gap, one issue, however many machines hit it. Weakening the dedupe
+ * weakens that, not just this feature.
+ */
+import type {
+ CreateIssueInput,
+ GitHubIssue,
+ IssuePageResult,
+ LabelPageResult,
+ ListIssueOptions,
+ GitHubRepositoryLabel
+} from '../../shared/github-issues'
+import { GitHubClientError } from './client'
+import { redactBody, redactExcerpt, redactReportText } from './report-redact'
+import {
+ REPORT_LABEL,
+ REPORT_LABEL_COLOR,
+ REPORT_LABEL_DESCRIPTION,
+ composeRecurrenceComment,
+ composeReportBody,
+ decideReport,
+ emptyLedger,
+ fingerprintReport,
+ bodyHasMarker,
+ recordReport,
+ type ReportEnvironment,
+ type ReportInput,
+ type ReportLedger
+} from './report-issue-core'
+
+/** How many open auto-reports the dedupe lookup scans. One page, because the lookup runs on every
+ * report and a repository drowning in more than this has a bigger problem than deduplication. */
+const LOOKUP_PAGE_SIZE = 100
+
+/** The client surface this service needs — a subset of `GitHubIssuesClient`, so tests can supply a
+ * fake without standing up HTTP, and so the service cannot quietly start using another endpoint. */
+export interface ReportIssueClient {
+ listIssues(repository: string, options: ListIssueOptions): Promise<IssuePageResult>
+ createIssue(repository: string, input: CreateIssueInput): Promise<GitHubIssue>
+ createIssueComment(repository: string, issueNumber: number, body: string): Promise<{ id: number }>
+ listRepositoryLabels(
+ repository: string,
+ options: { page: number; perPage: number }
+ ): Promise<LabelPageResult>
+ createLabel(
+ repository: string,
+ input: { name: string; color: string; description?: string }
+ ): Promise<GitHubRepositoryLabel>
+}
+
+export interface ReportIssueDeps {
+ /** Project → an authenticated client and the repository it may write to. Throws for every
+ * reason a project might not be reportable; `describeContextError` turns those into sentences. */
+ contextForProject(projectId: string): Promise<{ repository: string; client: ReportIssueClient }>
+ /**
+ * Is the capability granted for this project RIGHT NOW? Read per call, never cached at start —
+ * the same rule browser control and messaging follow, so revoking the switch stops the next
+ * report rather than the one after the restart.
+ */
+ granted(projectId: string): boolean | Promise<boolean>
+ loadLedger(projectId: string): Promise<ReportLedger>
+ saveLedger(projectId: string, ledger: ReportLedger): Promise<void>
+ env: ReportEnvironment
+ now?(): number
+}
+
+export interface ReportIssueRequest {
+ projectId: string
+ input: ReportInput
+ /** Compose and decide, publish nothing, and return the exact text that WOULD be published. */
+ dryRun?: boolean
+}
+
+export type ReportIssueResult =
+ | { ok: true; action: 'created' | 'commented'; issueNumber: number; url?: string; message: string }
+ | { ok: true; action: 'skipped' | 'dry-run'; message: string; preview?: string }
+ | { ok: false; error: string; message: string }
+
+/** Reports filed per project in THIS app run. Module-level on purpose: the per-run cap must not be
+ * resettable by anything an agent can reach, and a restart is a legitimate reset. */
+const filedThisRun = new Map<string, number>()
+
+/** Test seam — the per-run counter is process state, so a test that needs a fresh run says so. */
+export function resetReportRunCounters(): void {
+ filedThisRun.clear()
+}
+
+/**
+ * Turn a failure from `contextForProject` into a sentence an agent can act on. Every one of these
+ * is TERMINAL for this turn: none of them is fixed by retrying, and an agent that retries a
+ * misconfigured project is the loop this whole feature must not become.
+ */
+export function describeContextError(error: unknown): string {
+ const code = error instanceof Error ? error.message : String(error)
+ switch (code) {
+ case 'invalid-configuration':
+ case 'repository-not-found':
+ return (
+ 'report-no-repo: this project has no GitHub repository configured, so there is nowhere to ' +
+ 'file a report. Do not retry, and do not file it anywhere else — tell the user what you ' +
+ 'found and let them decide where it belongs.'
+ )
+ case 'not-approved':
+ return (
+ 'report-repo-not-approved: the user has not approved GitHub access for this project and ' +
+ 'repository on this machine. Do not retry; ask the user to approve it in the project’s ' +
+ 'GitHub settings.'
+ )
+ case 'not-authenticated':
+ case 'invalid-token':
+ return (
+ 'report-not-authenticated: there is no usable GitHub credential on this machine. Do not ' +
+ 'retry; ask the user to sign in under Settings → GitHub.'
+ )
+ case 'project-not-found':
+ return 'report-no-project: that project is not open here. Do not retry.'
+ default:
+ return `report-failed: could not reach GitHub (${code}). Tell the user rather than retrying.`
+ }
+}
+
+/** The one message that must not be generic: a token with `issues: read` does everything up to the
+ * write and fails only here, so "request failed" would send the user hunting the wrong problem. */
+function describeClientError(error: unknown): string {
+ if (error instanceof GitHubClientError) {
+ if (error.code === 'insufficient-permission') {
+ return (
+ 'report-scope-missing: the GitHub token on this machine cannot write issues (HTTP 403). ' +
+ 'It needs the "Issues: read and write" permission on this repository — a read-only token ' +
+ 'lists issues fine and fails only here. Do not retry; tell the user to update the token ' +
+ 'under Settings → GitHub.'
+ )
+ }
+ if (error.code === 'rate-limited') {
+ return 'report-rate-limited: GitHub is rate-limiting this token. Try again later, once.'
+ }
+ }
+ const detail = error instanceof Error ? error.message : String(error)
+ return `report-failed: GitHub rejected the report (${detail}). Do not retry more than once.`
+}
+
+/** Ensure the marker label exists, so every auto-filed issue is filterable and muteable. Failure
+ * is NOT fatal: an unlabelled report still carries its marker and its disclaimer, and refusing to
+ * file because a label could not be created would lose the report over cosmetics. */
+async function ensureLabel(client: ReportIssueClient, repository: string): Promise<boolean> {
+ try {
+ const page = await client.listRepositoryLabels(repository, { page: 1, perPage: LOOKUP_PAGE_SIZE })
+ if (page.items.some((label) => label.name.toLowerCase() === REPORT_LABEL)) return true
+ await client.createLabel(repository, {
+ name: REPORT_LABEL,
+ color: REPORT_LABEL_COLOR,
+ description: REPORT_LABEL_DESCRIPTION
+ })
+ return true
+ } catch {
+ return false
+ }
+}
+
+/**
+ * File (or decline to file) one report.
+ *
+ * Redaction happens BEFORE the fingerprint, not after, and that ordering is load-bearing twice
+ * over: the fingerprint must be host-independent to dedupe across machines, and a title carrying
+ * `/Users/jane` would otherwise fingerprint one gap once per user.
+ */
+export async function reportIssue(
+ deps: ReportIssueDeps,
+ request: ReportIssueRequest
+): Promise<ReportIssueResult> {
+ const now = deps.now?.() ?? Date.now()
+ const { projectId, input } = request
+
+ // Validated HERE and not only in `parseControlRequest`, because the desktop path never reaches
+ // that parser: main answers `report-issue` before the renderer forward, exactly as it does for
+ // `browser`. Two entry points, so the rule lives at the acting layer as well as the parsing one.
+ if (!input.kind.trim() || !input.title.trim() || !input.detail.trim()) {
+ const message =
+ 'report-invalid: a report needs --kind, --title and --body. Do not retry until you have all ' +
+ 'three.'
+ return { ok: false, error: 'report-invalid', message }
+ }
+
+ if (!(await deps.granted(projectId))) {
+ const message =
+ 'report-disabled: filing GitHub issues from an agent is switched off for this project. It ' +
+ 'is the "Let agents file GitHub issues for gaps they hit" switch in Settings → Agents, and ' +
+ 'it is off by default. Do not retry; tell the user what you found instead.'
+ return { ok: false, error: 'report-disabled', message }
+ }
+
+ let repository: string
+ let client: ReportIssueClient
+ try {
+ const context = await deps.contextForProject(projectId)
+ repository = context.repository
+ client = context.client
+ } catch (error) {
+ const message = describeContextError(error)
+ return { ok: false, error: message.split(':')[0], message }
+ }
+
+ // Redact every field independently, then compose, then redact the composition (the second pass
+ // catches anything the composer interpolated around the parts).
+ const title = redactReportText(input.title).text.slice(0, 200)
+ const detail = redactReportText(input.detail).text
+ const excerpt = input.excerpt ? redactExcerpt(input.excerpt).text : undefined
+ const fingerprint = fingerprintReport({ kind: input.kind, title })
+ const body = redactBody(
+ composeReportBody({ ...input, title, detail, ...(excerpt ? { excerpt } : {}) }, deps.env, fingerprint)
+ ).text
+
+ if (request.dryRun) {
+ return {
+ ok: true,
+ action: 'dry-run',
+ message: `Would file into ${repository} as "${title}" (fingerprint ${fingerprint}). Nothing was published.`,
+ preview: body
+ }
+ }
+
+ const ledger = await deps.loadLedger(projectId).catch(() => emptyLedger())
+
+ let matches: Array<{ number: number }> = []
+ try {
+ const page = await client.listIssues(repository, {
+ state: 'open',
+ page: 1,
+ perPage: LOOKUP_PAGE_SIZE,
+ labels: REPORT_LABEL
+ })
+ matches = page.items.filter((issue) => bodyHasMarker(issue.body, fingerprint))
+ } catch (error) {
+ // A failed lookup is NOT evidence that nothing was reported — the same rule the worktree code
+ // states for a failed `git` read. Filing anyway on a transient 500 is how one gap becomes
+ // twenty issues, so this fails CLOSED and the agent is told to try later.
+ const message = describeClientError(error)
+ return {
+ ok: false,
+ error: 'report-lookup-failed',
+ message: `report-lookup-failed: could not check whether this was already reported, so nothing was filed. ${message}`
+ }
+ }
+
+ const decision = decideReport({
+ fingerprint,
+ ledger,
+ matches,
+ filedThisRun: filedThisRun.get(projectId) ?? 0,
+ now
+ })
+
+ if (decision.action === 'refuse') {
+ return { ok: false, error: decision.reason.split(':')[0], message: decision.reason }
+ }
+
+ if (decision.action === 'skip') {
+ return {
+ ok: true,
+ action: 'skipped',
+ message:
+ `Already reported as #${decision.issueNumber} (${decision.reason}). Nothing was filed. ` +
+ 'This is the expected outcome for a known gap — do not retry.'
+ }
+ }
+
+ try {
+ if (decision.action === 'comment') {
+ await client.createIssueComment(
+ repository,
+ decision.issueNumber,
+ composeRecurrenceComment(deps.env, fingerprint)
+ )
+ await deps
+ .saveLedger(projectId, recordReport(ledger, fingerprint, decision.issueNumber, now, false))
+ .catch(() => undefined)
+ return {
+ ok: true,
+ action: 'commented',
+ issueNumber: decision.issueNumber,
+ message: `Already tracked as ${repository}#${decision.issueNumber}; noted that it happened again.`
+ }
+ }
+
+ const labelled = await ensureLabel(client, repository)
+ const issue = await client.createIssue(repository, {
+ title,
+ body,
+ ...(labelled ? { labels: [REPORT_LABEL] } : {})
+ })
+ filedThisRun.set(projectId, (filedThisRun.get(projectId) ?? 0) + 1)
+ await deps
+ .saveLedger(projectId, recordReport(ledger, fingerprint, issue.number, now, true))
+ .catch(() => undefined)
+ return {
+ ok: true,
+ action: 'created',
+ issueNumber: issue.number,
+ url: issue.htmlUrl,
+ message: `Filed ${repository}#${issue.number}: ${issue.htmlUrl}`
+ }
+ } catch (error) {
+ const message = describeClientError(error)
+ return { ok: false, error: message.split(':')[0], message }
+ }
+}
diff --git a/src/core/github/report-ledger.test.ts b/src/core/github/report-ledger.test.ts
new file mode 100644
index 000000000..dd325b102
--- /dev/null
+++ b/src/core/github/report-ledger.test.ts
@@ -0,0 +1,90 @@
+import { promises as fs } from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { ReportLedgerStore } from './report-ledger'
+import { emptyLedger } from './report-issue-core'
+
+let dir: string
+
+beforeEach(async () => {
+ dir = await fs.mkdtemp(path.join(os.tmpdir(), 'nt-report-ledger-'))
+})
+afterEach(async () => {
+ await fs.rm(dir, { recursive: true, force: true })
+})
+
+describe('the ledger round-trips', () => {
+ it('reads back what it wrote', async () => {
+ const store = new ReportLedgerStore(dir)
+ const ledger = { seen: { abc: { issueNumber: 7, lastSpokeAt: 1_700_000 } }, filedAt: [1_700_000] }
+ await store.save('project-1', ledger)
+ expect(await store.load('project-1')).toEqual(ledger)
+ })
+
+ it('keeps projects apart', async () => {
+ const store = new ReportLedgerStore(dir)
+ await store.save('a', { seen: { x: { issueNumber: 1, lastSpokeAt: 1 } }, filedAt: [] })
+ expect(await store.load('b')).toEqual(emptyLedger())
+ })
+})
+
+describe('a project id never becomes a path segment', () => {
+ it('cannot escape the data directory', async () => {
+ // Project ids arrive from .nodeterm/project.json, which is git-shared and hand-editable, so
+ // `../../..` is an id a hostile file can carry. The id is hashed, never joined.
+ const store = new ReportLedgerStore(dir)
+ await store.save('../../../../tmp/nt-escape', { seen: {}, filedAt: [1] })
+ const written = await fs.readdir(path.join(dir, 'agent-reports'))
+ expect(written).toHaveLength(1)
+ expect(written[0]).toMatch(/^[0-9a-f]{32}\.json$/)
+ })
+
+ it('an id containing a path separator still round-trips as itself', async () => {
+ const store = new ReportLedgerStore(dir)
+ const ledger = { seen: { k: { issueNumber: 3, lastSpokeAt: 9 } }, filedAt: [] }
+ await store.save('a/b/c', ledger)
+ expect(await store.load('a/b/c')).toEqual(ledger)
+ })
+})
+
+describe('reads fail open — never refuse to report because a cache was unreadable', () => {
+ it('answers an empty ledger when the file does not exist', async () => {
+ expect(await new ReportLedgerStore(dir).load('missing')).toEqual(emptyLedger())
+ })
+
+ it('answers an empty ledger for corrupt JSON rather than throwing', async () => {
+ const store = new ReportLedgerStore(dir)
+ await store.save('p', { seen: {}, filedAt: [] })
+ const file = path.join(dir, 'agent-reports', (await fs.readdir(path.join(dir, 'agent-reports')))[0])
+ await fs.writeFile(file, '{ this is not json')
+ expect(await store.load('p')).toEqual(emptyLedger())
+ })
+
+ it('drops malformed entries but keeps the sound ones', async () => {
+ const store = new ReportLedgerStore(dir)
+ await store.save('p', { seen: {}, filedAt: [] })
+ const file = path.join(dir, 'agent-reports', (await fs.readdir(path.join(dir, 'agent-reports')))[0])
+ await fs.writeFile(file, JSON.stringify({
+ seen: {
+ good: { issueNumber: 5, lastSpokeAt: 10 },
+ badNumber: { issueNumber: 'nope', lastSpokeAt: 10 },
+ missingClock: { issueNumber: 6 }
+ },
+ filedAt: [1, 'two', 3]
+ }))
+ const loaded = await store.load('p')
+ expect(Object.keys(loaded.seen)).toEqual(['good'])
+ expect(loaded.filedAt).toEqual([1, 3])
+ })
+})
+
+describe('the file is written for this user only', () => {
+ it('is mode 0600 — it records what this machine has published', async () => {
+ const store = new ReportLedgerStore(dir)
+ await store.save('p', { seen: {}, filedAt: [] })
+ const entries = await fs.readdir(path.join(dir, 'agent-reports'))
+ const stat = await fs.stat(path.join(dir, 'agent-reports', entries[0]))
+ expect(stat.mode & 0o777).toBe(0o600)
+ })
+})
diff --git a/src/core/github/report-ledger.ts b/src/core/github/report-ledger.ts
new file mode 100644
index 000000000..d43d080d7
--- /dev/null
+++ b/src/core/github/report-ledger.ts
@@ -0,0 +1,73 @@
+/**
+ * The machine-local record of what has already been reported, per project.
+ *
+ * MACHINE-LOCAL by construction, and that is a rule rather than a convenience: the ledger decides
+ * whether a report is filed, so a git-shared copy would let a cloned repository hand a stranger's
+ * machine a pre-loaded "already reported everything" ledger (silencing every gap) or an empty one
+ * (re-filing all of them). It lives beside the other per-machine stores in the data directory, on
+ * the same precedent as `IndexEntryV3.capabilityAck` and `trigger-arm-store`.
+ *
+ * Reads FAIL OPEN to an empty ledger and writes are best-effort: losing the ledger costs at most
+ * one duplicate comment on an existing issue, because the authoritative dedupe is the fingerprint
+ * marker in the repository itself. Refusing to report because a local cache file was unreadable
+ * would be the worse failure.
+ */
+import { promises as fs } from 'node:fs'
+import { createHash } from 'node:crypto'
+import path from 'node:path'
+import { writeFileAtomic } from '../fs-atomic'
+import { emptyLedger, type ReportLedger } from './report-issue-core'
+
+const DIR = 'agent-reports'
+
+/** A project id is hand-editable and arrives from a shared file, so it never becomes a path
+ * segment directly — `../../etc` is a project id a hostile `project.json` can carry. The hash is
+ * stable, collision-free in practice, and cannot escape the directory. */
+function ledgerFile(dir: string, projectId: string): string {
+ const key = createHash('sha256').update(projectId).digest('hex').slice(0, 32)
+ return path.join(dir, DIR, `${key}.json`)
+}
+
+/** Read one field defensively: the file is JSON on disk and may be truncated, hand-edited, or from
+ * a future version. Anything unexpected reads as "no history", never as a crash. */
+function parseLedger(raw: string): ReportLedger {
+ try {
+ const value = JSON.parse(raw) as Partial<ReportLedger>
+ const seen: ReportLedger['seen'] = {}
+ if (value.seen && typeof value.seen === 'object') {
+ for (const [fingerprint, entry] of Object.entries(value.seen)) {
+ if (!entry || typeof entry !== 'object') continue
+ const { issueNumber, lastSpokeAt } = entry as { issueNumber?: unknown; lastSpokeAt?: unknown }
+ if (typeof issueNumber !== 'number' || !Number.isSafeInteger(issueNumber)) continue
+ if (typeof lastSpokeAt !== 'number' || !Number.isFinite(lastSpokeAt)) continue
+ seen[fingerprint] = { issueNumber, lastSpokeAt }
+ }
+ }
+ const filedAt = Array.isArray(value.filedAt)
+ ? value.filedAt.filter((t): t is number => typeof t === 'number' && Number.isFinite(t))
+ : []
+ return { seen, filedAt }
+ } catch {
+ return emptyLedger()
+ }
+}
+
+export class ReportLedgerStore {
+ constructor(private readonly dataDir: string) {}
+
+ async load(projectId: string): Promise<ReportLedger> {
+ try {
+ return parseLedger(await fs.readFile(ledgerFile(this.dataDir, projectId), 'utf8'))
+ } catch {
+ return emptyLedger()
+ }
+ }
+
+ async save(projectId: string, ledger: ReportLedger): Promise<void> {
+ const target = ledgerFile(this.dataDir, projectId)
+ await fs.mkdir(path.dirname(target), { recursive: true })
+ // Atomic, like every other store here — a torn ledger would be parsed as "nothing reported"
+ // and answer the next gap by filing a duplicate. Never a bare `fs.rename` (fs-atomic.guard).
+ await writeFileAtomic(target, JSON.stringify(ledger), { mode: 0o600 })
+ }
+}
diff --git a/src/core/github/report-redact.test.ts b/src/core/github/report-redact.test.ts
new file mode 100644
index 000000000..7beb2c871
--- /dev/null
+++ b/src/core/github/report-redact.test.ts
@@ -0,0 +1,166 @@
+import { describe, expect, it } from 'vitest'
+import {
+ REDACTED,
+ REPORT_BODY_MAX,
+ redactBody,
+ redactExcerpt,
+ redactReportText
+} from './report-redact'
+
+/** A real-SHAPED credential for every class. None of these is a live secret; each matches the
+ * vendor's documented layout, because a test using `xxx` proves only that `xxx` is caught. */
+const SAMPLES = {
+ githubClassic: 'ghp_A1b2C3d4E5f6G7h8I9j0K1l2M3n4O5p6Q7r8',
+ githubFine: 'github_pat_11ABCDEFG0aBcDeFgHiJkL_mNoPqRsTuVwXyZ0123456789abcdefghij',
+ anthropic: 'sk-ant-api03-AbCdEfGhIjKlMnOpQrStUvWxYz0123456789-_AbCdEf',
+ openai: 'sk-proj-AbCdEfGhIjKlMnOpQrStUvWxYz0123456789',
+ aws: 'AKIAIOSFODNN7EXAMPLE',
+ // Assembled at runtime, not written as one literal: a sample realistic enough to prove the rule
+ // matches is also realistic enough for GitHub's push protection to block the PR that adds it
+ // (it did). The runtime value is identical, so the test loses nothing.
+ slack: ['xoxb', '123456789012', '1234567890123', 'AbCdEfGhIjKlMnOpQrStUvWx'].join('-'),
+ jwt:
+ 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.' +
+ 'eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIn0.' +
+ 'SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'
+}
+
+describe('every class of secret is removed', () => {
+ for (const [label, secret] of Object.entries(SAMPLES)) {
+ it(`removes a ${label} token`, () => {
+ const { text } = redactReportText(`the call failed with ${secret} in the header`)
+ expect(text).not.toContain(secret)
+ expect(text).toContain(REDACTED)
+ })
+ }
+
+ it('removes a PEM private key block whole, body included', () => {
+ const body = 'MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDR2n/EXAMPLEb64'
+ const { text, rules } = redactReportText(
+ `config:\n-----BEGIN RSA PRIVATE KEY-----\n${body}\n-----END RSA PRIVATE KEY-----\ndone`
+ )
+ expect(text).not.toContain(body)
+ expect(text).not.toContain('BEGIN RSA PRIVATE KEY')
+ expect(rules).toContain('private-key')
+ // The surrounding report survives — redaction must not eat the diagnostic.
+ expect(text).toContain('config:')
+ expect(text).toContain('done')
+ })
+
+ it('removes a bearer/authorization credential but keeps the header name', () => {
+ const { text } = redactReportText("curl -H 'authorization: Bearer aGVsbG8td29ybGQtMTIz'")
+ expect(text).not.toContain('aGVsbG8td29ybGQtMTIz')
+ expect(text).toContain('authorization')
+ })
+
+ it('does NOT blank an ordinary English word after the keyword "token"', () => {
+ // `token authentication failed` is a diagnostic sentence, not a credential. A keyword-only
+ // rule redacts `authentication` here and destroys the report's meaning.
+ const { text } = redactReportText('token authentication failed for this request')
+ expect(text).toBe('token authentication failed for this request')
+ })
+})
+
+describe('home directories lose the user, not the path', () => {
+ it.each([
+ ['/home/jdoe/src/app/index.ts', '~/src/app/index.ts'],
+ ['/Users/Jane.Doe/Projects/x.ts', '~/Projects/x.ts'],
+ ['C:\\Users\\jdoe\\src\\app.ts', '~\\src\\app.ts'],
+ ['/root/nodeterm/src/core/x.ts', '~/nodeterm/src/core/x.ts']
+ ])('rewrites %s', (input, expected) => {
+ expect(redactReportText(input).text).toBe(expected)
+ })
+
+ it('takes the whole address when a macOS home IS an e-mail address', () => {
+ // Order regression: home-first would leave `[email protected]` — the employer's domain, published.
+ const { text } = redactReportText('/Users/[email protected]/src/app.ts')
+ expect(text).not.toContain('corp.com')
+ expect(text).not.toContain('jane.doe')
+ })
+})
+
+describe('ssh endpoints and addresses', () => {
+ it.each([
+ 'ssh root@prod-db-01 failed',
+ 'scp build.tar [email protected]:/srv failed',
+ 'contact [email protected] for access'
+ ])('removes the endpoint in %s', (input) => {
+ const { text } = redactReportText(input)
+ expect(text).toContain(REDACTED)
+ expect(text).not.toMatch(/@[A-Za-z0-9]/)
+ })
+})
+
+describe('environment variable values', () => {
+ it('keeps the NAME and drops the value — the name is the diagnostic', () => {
+ const { text } = redactReportText('spawned with DATABASE_URL=postgres://u:p@db/app and PATH=/usr/bin')
+ expect(text).toContain('DATABASE_URL=')
+ expect(text).toContain('PATH=')
+ expect(text).not.toContain('postgres://')
+ expect(text).not.toContain('/usr/bin')
+ })
+
+ it('does not leave the tail of a quoted value behind', () => {
+ const { text } = redactReportText('API_HOST="secret host name"')
+ expect(text).not.toContain('secret host name')
+ expect(text).not.toContain('host name"')
+ })
+
+ it('leaves ordinary prose and short comparisons alone', () => {
+ expect(redactReportText('exit=1 and n=3').text).toBe('exit=1 and n=3')
+ })
+})
+
+describe('caps', () => {
+ it('keeps the TAIL of a long excerpt, where the error is', () => {
+ const noise = 'noise line\n'.repeat(1_000)
+ const { text, truncated } = redactExcerpt(`${noise}FATAL: the actual cause`, 200)
+ expect(truncated).toBe(true)
+ expect(text).toContain('FATAL: the actual cause')
+ expect(text).toContain('omitted')
+ expect(text.length).toBeLessThan(300)
+ })
+
+ it('clamps the excerpt AFTER redacting, so no half-token survives', () => {
+ // Clamp-then-redact keeps the TAIL, which here is most of the token; the cut destroys the
+ // leading word boundary, so the surviving fragment matches no rule and ships.
+ const { text } = redactExcerpt(`${'noise '.repeat(20)}${SAMPLES.githubClassic}`, 40)
+ expect(text).not.toContain(SAMPLES.githubClassic.slice(-20))
+ expect(text).toContain(REDACTED)
+ })
+
+ it('catches a token glued to the end of the preceding word', () => {
+ // A wrapped log column, a concatenated URL or an already-clamped line all produce this, and a
+ // leading `\b` anchor silently matches NOTHING here — the credential ships intact.
+ const { text } = redactReportText(`url=https://github.com/x${SAMPLES.githubClassic}`)
+ expect(text).not.toContain(SAMPLES.githubClassic)
+ })
+
+ it('clamps the assembled body to the published maximum', () => {
+ const { text, truncated } = redactBody('a'.repeat(REPORT_BODY_MAX * 2))
+ expect(truncated).toBe(true)
+ expect(text).toContain('report truncated')
+ expect(text.length).toBeLessThan(REPORT_BODY_MAX + 200)
+ })
+
+ it('redacts the assembled body again, catching a value the caller interpolated', () => {
+ const { text } = redactBody(`## Context\n\nran with ${SAMPLES.aws} set`)
+ expect(text).not.toContain(SAMPLES.aws)
+ })
+})
+
+describe('the result reports what fired, never the secret', () => {
+ it('names the rules that changed the text', () => {
+ const { rules } = redactReportText(`${SAMPLES.githubClassic} at /home/jdoe/x`)
+ expect(rules).toContain('github-token')
+ expect(rules).toContain('home-path')
+ })
+
+ it('reports nothing for clean text and leaves it byte-identical', () => {
+ const clean = 'open-terminal refused: this edition has no session host.'
+ const { text, rules, truncated } = redactReportText(clean)
+ expect(text).toBe(clean)
+ expect(rules).toEqual([])
+ expect(truncated).toBe(false)
+ })
+})
diff --git a/src/core/github/report-redact.ts b/src/core/github/report-redact.ts
new file mode 100644
index 000000000..715c92f40
--- /dev/null
+++ b/src/core/github/report-redact.ts
@@ -0,0 +1,229 @@
+/**
+ * Redaction for agent-filed issue reports — the last thing that runs before text from this
+ * machine is published to a repository we must assume is PUBLIC (ours is).
+ *
+ * The threat is not a hostile agent. It is an ordinary one pasting the thing it was looking at:
+ * a refusal message, a stack trace, the command it ran, the tail of a failing build. Those carry
+ * `/Users/<realname>/`, `root@prod-db-01`, `ANTHROPIC_API_KEY=sk-ant-…` and a bearer header,
+ * routinely, with nobody awake to read the draft.
+ *
+ * WHAT THIS CAN AND CANNOT DO — state it plainly, because the caps and the consent gate are sized
+ * against the second half:
+ * - It catches SHAPED secrets: things with a recognisable prefix, a delimiter, or a known layout.
+ * - It cannot catch SEMANTIC ones. `the acme-bank fraud-scoring worker crashed` is a customer
+ * name, an internal service and a business fact, and no pattern will ever see it. That is why
+ * this file is one layer of several (default-off per-project switch, caps, dedupe, a label and
+ * a body that says a machine wrote it) and never the sole reason publishing is safe.
+ *
+ * Every rule is ordered: multi-line key blocks first (they contain base64 that later rules would
+ * mangle into something unrecognisable), then keyed secrets, then assignments, then paths, then
+ * endpoints. Rules are written without nested quantifiers — this runs on agent-supplied text of
+ * bounded but attacker-influenced length, so a backtracking blowup would be a hang in the hook
+ * server's request path.
+ */
+
+/** What replaced a secret. One token, so a reader of the issue can see redaction happened. */
+export const REDACTED = '[redacted]'
+
+/** The whole body GitHub receives, after the header and footer are added around the report. */
+export const REPORT_BODY_MAX = 8_000
+
+/** A single block of pasted machine output (a log tail, a stack trace) inside one report. */
+export const REPORT_EXCERPT_MAX = 2_000
+
+export interface RedactionResult {
+ text: string
+ /** Which rule names fired, deduplicated and in rule order — surfaced to the agent (and the
+ * dry-run preview) so a human can see WHAT was stripped without seeing the secret. */
+ rules: string[]
+ /** True when the text was shortened by a cap rather than only rewritten. */
+ truncated: boolean
+}
+
+interface Rule {
+ name: string
+ pattern: RegExp
+ replace: string | ((...args: string[]) => string)
+}
+
+/**
+ * Home directories → `~`. The USERNAME is the secret here, not the prefix: `/home/` tells a reader
+ * nothing, `/home/jdoe` names a person. So the segment is replaced and the tail is kept — a report
+ * whose paths all collapsed to `~` would lose the very detail that makes it actionable.
+ *
+ * Runs AFTER the endpoint rule, and the order is load-bearing: a macOS home directory is routinely
+ * the user's e-mail address (`/Users/[email protected]/`). Home-first would eat `/Users/jane.doe`
+ * and leave `[email protected]`, which no later rule matches — publishing the employer's domain. Endpoint
+ * -first takes the whole address, and the `/Users/` prefix that remains names nobody.
+ */
+const HOME_RULES: Rule[] = [
+ {
+ name: 'home-path',
+ // POSIX: /home/<user>, /Users/<user>, and /root (which has no user segment to drop).
+ pattern: /\/(?:home|Users)\/[A-Za-z0-9._-]{1,64}/g,
+ replace: '~'
+ },
+ {
+ name: 'home-path',
+ pattern: /(?<![A-Za-z0-9._-])\/root(?=\/|\b)/g,
+ replace: '~'
+ },
+ {
+ name: 'home-path',
+ // Windows, both separators, drive letter free.
+ pattern: /[A-Za-z]:\\Users\\[A-Za-z0-9._ -]{1,64}/g,
+ replace: '~'
+ }
+]
+
+/**
+ * Keyed secrets. Each entry is a vendor prefix with a documented shape, so the match is anchored
+ * on the prefix rather than on entropy: an entropy heuristic on a 2 KB log tail redacts commit
+ * SHAs, UUIDs and base64 payloads, which is how a redactor turns a useful report into noise.
+ */
+const SECRET_RULES: Rule[] = [
+ {
+ name: 'private-key',
+ // Multi-line, non-greedy, and FIRST: the base64 body inside would otherwise be chewed by the
+ // rules below into fragments that no longer look like a key — which reads as "no secret here".
+ pattern: /-----BEGIN[A-Z ]{0,40}PRIVATE KEY-----[\s\S]{0,8000}?-----END[A-Z ]{0,40}PRIVATE KEY-----/g,
+ replace: `${REDACTED} (private key)`
+ },
+ {
+ name: 'github-token',
+ // Classic PAT / OAuth / server / refresh tokens, and the fine-grained `github_pat_` form.
+ //
+ // NO leading `\b`, deliberately, and this was a caught bug rather than a preference: `\b`
+ // needs a non-word character before `ghp_`, so a token glued to the end of a preceding word —
+ // which is what a clamped log line, a wrapped column or a concatenated URL produces — was not
+ // matched at all. These prefixes carry an underscore and never occur inside an English word,
+ // so the false-positive cost of dropping the anchor is nil and the miss it prevents is a live
+ // credential published to a public repository. Rules whose prefix COULD be a word fragment
+ // (`sk-` inside `disk-…`, `eyJ` inside `keyJ…`) keep their anchor for the opposite reason.
+ pattern: /(?:gh[pousr]_[A-Za-z0-9]{16,255}|github_pat_[A-Za-z0-9_]{20,255})\b/g,
+ replace: REDACTED
+ },
+ {
+ name: 'anthropic-key',
+ pattern: /\bsk-ant-[A-Za-z0-9_-]{16,200}\b/g,
+ replace: REDACTED
+ },
+ {
+ name: 'openai-key',
+ // `sk-` plus a long run. Kept after the Anthropic rule so `sk-ant-…` is named precisely.
+ pattern: /\bsk-[A-Za-z0-9_-]{20,200}\b/g,
+ replace: REDACTED
+ },
+ {
+ name: 'aws-key-id',
+ pattern: /\b(?:AKIA|ASIA|AGPA|AIDA|AROA|ANPA)[0-9A-Z]{16}\b/g,
+ replace: REDACTED
+ },
+ {
+ name: 'slack-token',
+ pattern: /\bxox[abprs]-[A-Za-z0-9-]{10,200}\b/g,
+ replace: REDACTED
+ },
+ {
+ name: 'jwt',
+ // Three base64url segments. Bounded per segment; a JWT is a bearer credential in its own right.
+ pattern: /\beyJ[A-Za-z0-9_-]{10,2000}\.[A-Za-z0-9_-]{10,2000}\.[A-Za-z0-9_-]{10,2000}\b/g,
+ replace: REDACTED
+ },
+ {
+ name: 'bearer-header',
+ // `Authorization: Bearer x`, `-H 'authorization: token x'`, `--header "Bearer x"`.
+ //
+ // The keyword alone is too weak a signal to redact on: `token authentication failed` puts a
+ // 14-character ENGLISH WORD where a credential would be, and blanking it turns a diagnostic
+ // sentence into a mystery. So the candidate must also LOOK like a credential — carry a digit
+ // or one of the separator characters real keys use. A lowercase word never does.
+ pattern: /\b(authorization\s*[:=]\s*|Bearer\s+|token\s+)(['"]?)([A-Za-z0-9._~+/=-]{12,400})/gi,
+ replace: (m: string, lead: string, quote: string, value: string) =>
+ /[0-9._~+/=-]/.test(value) ? `${lead}${quote}${REDACTED}` : m
+ }
+]
+
+/**
+ * `NAME=value` where NAME looks like an environment variable. The NAME is kept: "the report says
+ * DATABASE_URL was set" is exactly the diagnostic detail, and the value is exactly the part that
+ * must not be published.
+ *
+ * Scoped to UPPER_SNAKE names of 4+ characters so ordinary prose (`X=1`, `n=3`) and shell
+ * comparisons survive. A value is consumed up to whitespace, or to the closing quote when quoted —
+ * `FOO="a b c"` must not leave `b c` behind.
+ */
+const ENV_RULE: Rule = {
+ name: 'env-value',
+ pattern: /\b([A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+|[A-Z]{4,})=(?:"[^"\n]{0,400}"|'[^'\n]{0,400}'|[^\s"'][^\s]{0,400})/g,
+ replace: (_m: string, name: string) => `${name}=${REDACTED}`
+}
+
+/**
+ * `user@host` — SSH endpoints and e-mail addresses in one rule, because they are the same shape
+ * and both are things this machine should not publish on the user's behalf. The USER is dropped
+ * and the host kept in the SSH case only when it is not itself a domain; simpler and safer to drop
+ * the whole token, since a bare internal hostname (`prod-db-01`) is also an infrastructure leak.
+ */
+const ENDPOINT_RULE: Rule = {
+ name: 'endpoint',
+ pattern: /(?<![A-Za-z0-9._%+-])[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9](?:[A-Za-z0-9.-]{0,253}[A-Za-z0-9])?/g,
+ replace: REDACTED
+}
+
+const RULES: Rule[] = [...SECRET_RULES, ENV_RULE, ENDPOINT_RULE, ...HOME_RULES]
+
+/**
+ * Apply every rule. Pure, order-fixed, and it reports WHICH classes fired so the caller can tell a
+ * human "3 secrets and a home path were removed" without quoting any of them.
+ */
+export function redactReportText(input: string): RedactionResult {
+ const fired: string[] = []
+ let text = input
+ for (const rule of RULES) {
+ // `replace` with a global regex has no lastIndex hazard (it is reset per call), and each rule
+ // sees the output of the previous one on purpose: a bearer header inside a home path should be
+ // caught by both.
+ const next = text.replace(rule.pattern, rule.replace as never)
+ if (next !== text && !fired.includes(rule.name)) fired.push(rule.name)
+ text = next
+ }
+ return { text, rules: fired, truncated: false }
+}
+
+/**
+ * Clamp a block of pasted machine output and redact it.
+ *
+ * The TAIL is kept, not the head: a stack trace's cause, a build's first error and a CLI's refusal
+ * all land at the end, and a head-clamped 2 KB of a 40 KB log is almost always the part nobody
+ * needed. The elision is marked so a reader knows bytes are missing.
+ */
+export function redactExcerpt(input: string, max = REPORT_EXCERPT_MAX): RedactionResult {
+ const redacted = redactReportText(input)
+ if (redacted.text.length <= max) return redacted
+ // Clamp AFTER redacting: clamping first can cut a token in half and leave a recognisable
+ // fragment of a secret that no rule matches any more.
+ const tail = redacted.text.slice(redacted.text.length - max)
+ return {
+ text: `…[${redacted.text.length - max} earlier characters omitted]\n${tail}`,
+ rules: redacted.rules,
+ truncated: true
+ }
+}
+
+/**
+ * Final gate on the assembled body. Redacts again — the assembled body contains text the caller
+ * built around the excerpt, and a caller that interpolated a raw value must not get past this —
+ * then clamps to `REPORT_BODY_MAX`, keeping the HEAD here because the assembled body leads with
+ * the machine-written context a reader needs first.
+ */
+export function redactBody(input: string, max = REPORT_BODY_MAX): RedactionResult {
+ const redacted = redactReportText(input)
+ if (redacted.text.length <= max) return redacted
+ const head = redacted.text.slice(0, max)
+ return {
+ text: `${head}\n\n…[report truncated at ${max} characters]`,
+ rules: redacted.rules,
+ truncated: true
+ }
+}
diff --git a/src/core/github/service.test.ts b/src/core/github/service.test.ts
index 9445a59c8..18570cf1b 100644
--- a/src/core/github/service.test.ts
+++ b/src/core/github/service.test.ts
@@ -93,6 +93,14 @@ class FixtureClient implements GitHubIssuesClientLike {
this.repositoryLabels.push(label)
return label
}
+
+ // The report path does not run through GitHubIssueService, so these are declaration-only here.
+ // They must still THROW rather than return a fake issue: a test that accidentally reaches them
+ // should fail loudly instead of asserting against a value nothing produced.
+ async createIssue(): Promise<never> { throw new Error('createIssue not used by this fixture') }
+ async createIssueComment(): Promise<never> {
+ throw new Error('createIssueComment not used by this fixture')
+ }
}
function context(client: FixtureClient, over: Partial<GitHubIssueServiceContext> = {}): GitHubIssueServiceContext {
diff --git a/src/core/github/service.ts b/src/core/github/service.ts
index ddc3a3e59..c90fa4022 100644
--- a/src/core/github/service.ts
+++ b/src/core/github/service.ts
@@ -1,4 +1,5 @@
import type {
+ CreateIssueInput,
CreateMappedLabelsResult,
GitHubIssue,
GitHubIssueCardView,
@@ -47,6 +48,11 @@ export interface GitHubIssuesClientLike {
repository: string,
input: { name: string; color: string; description?: string }
): Promise<GitHubRepositoryLabel>
+ /** Agent-filed gap reports (@core/github/report-issue-service). Declared here rather than only
+ * on the concrete client so `contextForProject` hands one caller everything it needs — the
+ * report path must never build a second authenticated client of its own. */
+ createIssue(repository: string, input: CreateIssueInput): Promise<GitHubIssue>
+ createIssueComment(repository: string, issueNumber: number, body: string): Promise<{ id: number }>
}
export interface GitHubIssueProjectContext {
diff --git a/src/core/workspace-files.ts b/src/core/workspace-files.ts
index 3a4105af6..02b037103 100644
--- a/src/core/workspace-files.ts
+++ b/src/core/workspace-files.ts
@@ -151,6 +151,11 @@ export interface ProjectFileV1 {
/** Per-project capability switch (@shared/project-capabilities): agents may message other agent
* nodes in this project. Git-shared like `agentBrowserControl`, read with the same strictness. */
agentMessaging?: boolean
+ /** Per-project capability switch (@shared/project-capabilities): agents may file GitHub issues
+ * for product gaps they hit. Git-shared like the two above, read with the same strictness —
+ * and the only one of the three whose effect leaves this machine, so a stranger's `true` here
+ * buys nothing until this machine's user answers its notice. */
+ agentIssueReporting?: boolean
dinoHighScore?: number
kanban?: ProjectKanban
/**
diff --git a/src/main/canvas-control-core.test.ts b/src/main/canvas-control-core.test.ts
index db7416e50..a7dced2f3 100644
--- a/src/main/canvas-control-core.test.ts
+++ b/src/main/canvas-control-core.test.ts
@@ -16,6 +16,11 @@ import { RETRYABLE } from '../core/agents/agent-message-decide'
import { PROJECT_TARGETABLE_VERBS } from '../core/project-grants'
import { DRY_RUN_VERBS } from '../shared/control-verbs'
import { SETTINGS_VERB_KEYS, SETTINGS_VERB_KEY_LIST } from '../shared/settings-verb'
+import {
+ REPORT_CAP_PER_DAY,
+ REPORT_CAP_PER_RUN,
+ REPORT_LABEL
+} from '../core/github/report-issue-core'
import { STRICT_CONTROL_VERBS } from '../core/agents/node-identity-policy'
import { BROWSER_ACTION_KEYS } from '../core/browser-verb'
import { BROWSER_RETRYABLE, BROWSER_OUTCOME_LABEL } from '../core/browser-outcomes'
@@ -551,6 +556,34 @@ describe('parseControlRequest', () => {
}
})
+ it('both bodies teach WHEN to file a report, with the caps rendered from the real constants', () => {
+ for (const body of [buildCanvasSkillBody('/x/shim.sh'), buildCanvasControlInstructions('/tmp/nodeterm.sh')]) {
+ expect(body).toContain('`report-issue --kind <code> --title <one line> --body <text> [--dry-run]`')
+ // The caps are RENDERED, so tuning either constant without moving the prose reddens here —
+ // an agent that believes a stale limit retries into a refusal it was told would not happen.
+ expect(body).toContain(`${REPORT_CAP_PER_RUN} reports per nodeterm run`)
+ expect(body).toContain(`${REPORT_CAP_PER_DAY} per day`)
+ expect(body).toContain(`\`${REPORT_LABEL}\``)
+ // The load-bearing half is WHEN, not the flags: the three non-cases must be named, or an
+ // agent files its own mistakes into a public tracker.
+ expect(body).toMatch(/DO NOT FILE for your own mistakes/)
+ expect(body).toMatch(/for a failing\s+test/)
+ expect(body).toMatch(/FILE WHEN the thing you could not do is a gap in the product/)
+ // Duplicate suppression is automatic; telling an agent to check first would have it burn a
+ // turn searching and then file anyway when the search came back empty.
+ expect(body).toMatch(/Do not check first and do not search for duplicates/)
+ expect(body).toMatch(/Keep `--kind` STABLE/)
+ // Default-off, and the refusal names are the agent's whole vocabulary for giving up.
+ expect(body).toMatch(/Off by\s+default/)
+ for (const refusal of ['report-disabled', 'report-no-repo', 'report-scope-missing', 'report-cap-run', 'report-cap-day']) {
+ expect(body, `refusal ${refusal} documented`).toContain(`\`${refusal}\``)
+ }
+ // The no-repo refusal must not read as an invitation to find another repository.
+ expect(body).toMatch(/do NOT file it somewhere\s+else/)
+ expect(body).toMatch(/Server Edition refuses this verb by name/)
+ }
+ })
+
it('both bodies document `settings` from the REAL allowlist and state that every change asks', () => {
for (const body of [buildCanvasSkillBody('/x/shim.sh'), buildCanvasControlInstructions('/tmp/nodeterm.sh')]) {
// Walked off the table, so a key added to or dropped from the allowlist reddens here unless
diff --git a/src/main/index.ts b/src/main/index.ts
index 4a01bc7de..96ba5b9db 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -109,7 +109,14 @@ import {
import { generateCommitMessage, generateGroupName, generateTerminalName } from '../core/commit-message'
import { initUpdater } from './updater'
import { fetchCheck } from '../core/check'
-import { hookServer, OPEN_PROJECT_CONTROL_REFUSAL } from '../core/agents/hook-server'
+import {
+ hookServer,
+ OPEN_PROJECT_CONTROL_REFUSAL,
+ REPORT_ISSUE_CONTROL_REFUSAL
+} from '../core/agents/hook-server'
+import { reportIssue } from '../core/github/report-issue-service'
+import { ReportLedgerStore } from '../core/github/report-ledger'
+import { projectCapabilityGrantedFor } from '../shared/project-capability-consent'
import { askpassServer, ensureAskpassScript } from './remote-ssh/ssh-askpass'
import { appSshAgent } from './remote-ssh/ssh-agent'
import {
@@ -1706,6 +1713,9 @@ app.whenReady().then(async () => {
run: runGitHubCliCommand
})
dropGitHubRelayClient = (id) => github.service.dropClient(id)
+ // Machine-local record of what has already been reported, per project — never git-shared, or a
+ // cloned repo could hand this machine a pre-loaded "already reported" ledger.
+ const reportLedger = new ReportLedgerStore(app.getPath('userData'))
registerElectronGitHubControl(
ipcMain,
() => getMainWindow()?.webContents.id,
@@ -3493,6 +3503,77 @@ app.whenReady().then(async () => {
// node inside the save debounce, or an id main never saved): the project gates fail closed.
const projectIdOfNode = (id: string): string | undefined =>
workspaceStore.persistedCanvases().find((c) => c.nodes.some((n) => n.id === id))?.id
+ /**
+ * `report-issue`, answered entirely in MAIN like `browser` and for the same reason: the GitHub
+ * credential, the repository resolution and the network call are all main-side, and the renderer
+ * is the more attackable half. There is deliberately no confirmation dialog — an agent that hits
+ * a product gap while nobody is watching is the case this verb exists for — so the gates below
+ * are the whole of the consent, and each one refuses on its own:
+ *
+ * - node identity must be `verified` (already enforced at the hook-server route; this is the
+ * belt every other verified-only verb in this file also wears);
+ * - the report goes to the CALLER'S OWN project, never a `--project` id. Reporting into
+ * somebody else's repository is not something an agent should reach by naming an id, so the
+ * flag does not exist rather than being gated;
+ * - the per-project capability must be GRANTED — the file bit AND this machine's 'kept'
+ * answer — read per call off the store, exactly as messaging's switch is, so revoking it
+ * stops the next report rather than the one after a restart.
+ */
+ const handleReportIssueVerb = async (
+ nodeId: string,
+ args: Record<string, string>,
+ verified: boolean
+ ): Promise<{ ok: boolean; message?: string; error?: string }> => {
+ const refuse = (error: string) => ({ ok: false, error, message: error })
+ if (!verified) return refuse(REPORT_ISSUE_CONTROL_REFUSAL)
+ const projectId = projectIdOfNode(nodeId)
+ // Unresolved caller ⇒ fail closed, the same rule the project gates above follow: we cannot
+ // name the repository a report belongs to, and guessing one is the failure mode this whole
+ // feature is shaped around.
+ if (!projectId) {
+ return refuse(
+ 'report-no-project: this node is not in a saved project, so there is no repository to ' +
+ 'report to. Do not retry.'
+ )
+ }
+ return reportIssue(
+ {
+ contextForProject: async (id) => {
+ const context = await github.controller.contextForProject(id)
+ return { repository: context.repository, client: context.client }
+ },
+ granted: () =>
+ projectCapabilityGrantedFor(
+ workspaceStore.capabilityProjectFor(projectId),
+ 'agentIssueReporting',
+ settingsStore.get()
+ ),
+ loadLedger: (id) => reportLedger.load(id),
+ saveLedger: (id, ledger) => reportLedger.save(id, ledger),
+ env: { version: app.getVersion(), os: process.platform, edition: 'desktop' }
+ },
+ {
+ projectId,
+ dryRun: dryRunRequested(args),
+ input: {
+ kind: args.kind ?? '',
+ title: args.title ?? '',
+ detail: args.body ?? '',
+ ...(args.output ? { excerpt: args.output } : {}),
+ ...(args.agent ? { agent: args.agent } : {})
+ }
+ }
+ ).then((result) =>
+ result.ok
+ ? {
+ ok: true,
+ message: result.action === 'dry-run' && result.preview
+ ? `${result.message}\n\n${result.preview}`
+ : result.message
+ }
+ : { ok: false, error: result.error, message: result.message }
+ )
+ }
hookServer.setControlHandler(async ({ verb, nodeId, args, verified }) => {
// `--dry-run` (issue #532) is honoured by the spawn verbs only, and this gate runs FIRST —
// before the browser intercept, the open-project gates and the renderer forward — because a
@@ -3507,6 +3588,8 @@ app.whenReady().then(async () => {
// the debugger handle and the CDP allowlist are main-side, and the renderer is the more
// attackable half. Every other verb still round-trips to the renderer below.
if (verb === 'browser') return handleBrowserVerb(nodeId, args, verified)
+ // Answered in MAIN for the same reasons as `browser`; see handleReportIssueVerb.
+ if (verb === 'report-issue') return handleReportIssueVerb(nodeId, args, verified)
// ── `open-project` + `--project` targeting, gated in MAIN before anything is forwarded
// (issue #338 PR 1). The renderer never sees an invalid cwd or an unauthorized `--project`.
// The verb itself is verified-only at the hook-server route (requiresVerified) — by the time
diff --git a/src/shared/control-off-screen.ts b/src/shared/control-off-screen.ts
index 325bab554..4fade3a69 100644
--- a/src/shared/control-off-screen.ts
+++ b/src/shared/control-off-screen.ts
@@ -84,7 +84,11 @@ const STORE_ANSWERED_VERBS: ReadonlySet<string> = new Set([
'open-project',
// Reads settings.json and the projects store, and its dialog is app-global — no canvas at either
// end, and a background agent asking must never travel the user's view (@shared/settings-verb).
- 'settings'
+ 'settings',
+ // Talks to GitHub on behalf of the caller's OWN project. No node at either end and no dialog, so
+ // travelling the user's view would be pure interruption — and the point of the verb is that it
+ // works while nobody is watching.
+ 'report-issue'
])
/**
diff --git a/src/shared/control-verbs.test.ts b/src/shared/control-verbs.test.ts
index 4db4d27ef..8ee22921b 100644
--- a/src/shared/control-verbs.test.ts
+++ b/src/shared/control-verbs.test.ts
@@ -25,9 +25,13 @@ describe('dryRunRequested', () => {
})
describe('DRY_RUN_VERBS', () => {
- it('covers exactly the spawn verbs', () => {
+ it('covers the spawn verbs, plus the one verb whose mutation cannot be undone', () => {
+ // The set was "exactly the spawn verbs" until `report-issue` joined it. The rule it actually
+ // encodes is the asymmetry in the header — easy to call, expensive or impossible to reverse —
+ // and publishing an issue to a repository is the strongest case of that in the whole verb
+ // list: a spawned node can be deleted, a filed issue is already on the internet.
expect([...DRY_RUN_VERBS].sort()).toEqual(
- ['open-agent', 'open-claude', 'open-terminal', 'open-worktree', 'spawn-team'].sort()
+ ['open-agent', 'open-claude', 'open-terminal', 'open-worktree', 'report-issue', 'spawn-team'].sort()
)
})
it('never contains a destructive or read verb', () => {
diff --git a/src/shared/control-verbs.ts b/src/shared/control-verbs.ts
index bf57da465..b6e531fcb 100644
--- a/src/shared/control-verbs.ts
+++ b/src/shared/control-verbs.ts
@@ -85,7 +85,13 @@ export const DRY_RUN_VERBS: ReadonlySet<string> = new Set([
'open-claude',
'open-agent',
'spawn-team',
- 'open-worktree'
+ 'open-worktree',
+ // Not a spawn verb, and the only member that is not — but it fits the asymmetry the set exists
+ // for better than any of them: a report is PUBLISHED, and publishing is the one mutation here
+ // that cannot be undone at all. A dry run returns the exact redacted text that would be filed,
+ // which is also the only way a human can inspect what this project would send before it sends
+ // anything.
+ 'report-issue'
])
/**
diff --git a/src/shared/github-issues.ts b/src/shared/github-issues.ts
index 82b0ca740..65acb1a33 100644
--- a/src/shared/github-issues.ts
+++ b/src/shared/github-issues.ts
@@ -107,6 +107,23 @@ export interface ListIssueOptions {
perPage: number
since?: string
etag?: string
+ /**
+ * Comma-separated label filter, passed straight to the REST list endpoint.
+ *
+ * The dedupe lookup for agent-filed reports uses THIS rather than the search API on purpose:
+ * `/search/issues` is served from an index that lags its writes, so two agents hitting one gap a
+ * minute apart would both search, both miss, and both file — the exact duplicate the fingerprint
+ * exists to prevent. The list endpoint reads the database and is immediately consistent.
+ */
+ labels?: string
+}
+
+/** What `createIssue` needs. `labels` are names, and the caller ensures they exist first —
+ * GitHub creates an unknown label implicitly, with a random colour and no description. */
+export interface CreateIssueInput {
+ title: string
+ body: string
+ labels?: string[]
}
export interface IssuePageResult {
diff --git a/src/shared/project-capabilities.ts b/src/shared/project-capabilities.ts
index 4fb46154a..5acf86e04 100644
--- a/src/shared/project-capabilities.ts
+++ b/src/shared/project-capabilities.ts
@@ -40,11 +40,12 @@
*/
import type { Settings } from './types'
-export type ProjectCapability = 'agentBrowserControl' | 'agentMessaging'
+export type ProjectCapability = 'agentBrowserControl' | 'agentMessaging' | 'agentIssueReporting'
export const PROJECT_CAPABILITIES: readonly ProjectCapability[] = [
'agentBrowserControl',
- 'agentMessaging'
+ 'agentMessaging',
+ 'agentIssueReporting'
] as const
export interface ProjectCapabilityCopy {
@@ -81,6 +82,23 @@ export const PROJECT_CAPABILITY_COPY: Record<ProjectCapability, ProjectCapabilit
cloneWarning:
'This setting is saved in the project file (.nodeterm/project.json), so if you commit it, ' +
'everyone who clones the repo gets it too.'
+ },
+ agentIssueReporting: {
+ label: 'Let agents file GitHub issues for gaps they hit',
+ description:
+ 'When an agent in this project runs into something nodeterm cannot do, it can open an issue ' +
+ 'in THIS project’s GitHub repository by itself — no prompt, and nobody reads the text first. ' +
+ 'That text is written by a machine out of whatever it was looking at: error output, the ' +
+ 'command it ran, file paths, branch and project names. Secrets with a recognisable shape are ' +
+ 'stripped first (tokens, keys, home directories, ssh addresses, environment values) and the ' +
+ 'report is shortened — but ONLY recognisable shapes can be stripped, so a customer name, an ' +
+ 'internal hostname or a private project name inside an error message is published as ' +
+ 'written. Assume the repository is public. Repeats fold into the existing issue, there is a ' +
+ 'daily limit, and every issue is labelled and says plainly that a machine filed it.',
+ cloneWarning:
+ 'This setting is saved in the project file (.nodeterm/project.json), so if you commit it, ' +
+ 'everyone who clones the repo gets it too — and on their machine it publishes their text, to ' +
+ 'whichever repository their copy of the project points at.'
}
}
diff --git a/src/shared/settings-verb.ts b/src/shared/settings-verb.ts
index 3f3b49e6c..634c8217f 100644
--- a/src/shared/settings-verb.ts
+++ b/src/shared/settings-verb.ts
@@ -127,6 +127,12 @@ export const SETTINGS_VERB_FORBIDDEN = new Set<keyof Settings | keyof Project>([
'hookIdentityStrict',
// Browser control — a capability that acts as the user on the web.
'agentBrowserControl',
+ // Issue reporting — the only capability whose effect LEAVES THE MACHINE. An agent that could
+ // switch on its own auto-reporting is a self-granting loop aimed at a public tracker, so this
+ // is never settable from the CLI whatever the allowlist says. (The name pattern below does not
+ // catch it — none of "issue", "report" or "github" is a forbidden name class — so this explicit
+ // entry is the whole fence.)
+ 'agentIssueReporting',
// This machine's consent record for capabilities; writable only by the human's answer.
'capabilityAck',
// Accounts, credentials, model gateway, and anything that decides WHAT COMMAND runs.
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 455abbe71..67d635fd5 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -786,6 +786,12 @@ export interface Project {
* rules as `agentBrowserControl` above — git-shared hostile input, strict `=== true` read,
* never a grant without this machine's recorded 'kept' (`projectCapabilityGrantedFor`). */
agentMessaging?: boolean
+ /** Per-project capability switch: agents may file a GitHub issue in THIS project's repository
+ * when they hit a nodeterm gap. Same rules as the two above — git-shared hostile input, strict
+ * `=== true` read, never a grant without this machine's recorded 'kept'
+ * (`projectCapabilityGrantedFor`). Unlike them, what it grants is PUBLICATION: the text leaves
+ * the machine, so the copy in `PROJECT_CAPABILITY_COPY` says so in as many words. */
+ agentIssueReporting?: boolean
/**
* MACHINE-LOCAL record of what this machine's user ANSWERED for each capability switch —
* 'kept' or 'declined', not a bare bit, because a declined switch whose hostile `true`