Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

refactor: extract the shared exec half of the three forge-issue filers into appIssues.js (#7687)

[._.]/ Adam Eivydb4d6728b344
diff --git a/server/services/appIssues.js b/server/services/appIssues.js
index a4cb3d2d3c..f92bb2a566 100644
--- a/server/services/appIssues.js
+++ b/server/services/appIssues.js
@@ -30,7 +30,10 @@ import { resolveAppForgeTarget } from '../lib/workTracker.js';
import { safeJSONParse } from '../lib/fileUtils.js';
import { CONTRIBUTOR_LABELS } from '../lib/dispatchLabels.js';
import { withGlabJson } from '../lib/glabArgs.js';
-import { ServerError } from '../lib/errorHandler.js';
+import { ServerError, boundedErrorMessage } from '../lib/errorHandler.js';
+import { forgeIssueCreateArgs, forgeLabelCreateArgs, parseCreatedForgeIssue } from '../lib/forgeIssueCli.js';
+import { scrubHomePath } from '../lib/homePath.js';
+import { scrubSecretTokens } from '../lib/secretText.js';
// Single-user repos never realistically exceed this; `glab` caps a page at 100.
const GH_LIST_LIMIT = 200;
@@ -316,3 +319,128 @@ export async function prepareAppIssueClaim(app, issueNumber, tracker) {
throw new ServerError('Contributor labels remain on the issue; claim was not queued', { status: 502, code: 'CLAIM_LABELS_REMAIN' });
}
}
+
+/**
+ * The last thing that happens to a title/body before any filer's issue reaches
+ * a forge. A filed issue is world-readable the moment it lands, so the strip
+ * has to be enforced mechanically rather than trusted to each caller's own
+ * copy (#7687 — three filers had re-implemented this, and only two called it).
+ * `scrubHomePath` collapses the running user's home prefix (which embeds the OS
+ * username in `/Users/<name>/…`); `scrubSecretTokens` replaces credential-shaped
+ * substrings. Neither is a content filter — deciding whether a sentence names a
+ * private record is not mechanically decidable, so that stays a prompt
+ * instruction for the callers that reach an LLM. Both helpers pass a non-string
+ * through untouched.
+ *
+ * Exported (not just used internally by `fileForgeIssue`) because a filer that
+ * needs to scrub text for a NON-forge tracker in the same request — JIRA,
+ * today — still needs one shared definition to call.
+ */
+export const scrubForgeIssueText = (value) => scrubSecretTokens(scrubHomePath(value));
+
+/**
+ * Refuse to proceed against an unreachable GitHub forge, in the `{ ok, error }`
+ * shape every filer already returns on refusal. GitLab has no equivalently
+ * cheap reachability probe (`ensureForgeReachable` is gh-specific), so a
+ * non-`gh` cli is always reported reachable. One definition instead of the
+ * two near-duplicate inline blocks `persistentMindIssueCapability.js` and
+ * `goalFidelityFollowUp.js` each carried, plus the probe `forgeFiler.js` never
+ * had at all (#7687).
+ */
+export async function probeForgeReachability({ cli, hostname, env = null, label }) {
+ if (cli !== 'gh' || !hostname) return { ok: true };
+ const forge = await ensureForgeReachable(label, { hostname, ...(env ? { env } : {}) });
+ if (forge.ok) return { ok: true };
+ return { ok: false, error: `GitHub is not reachable (${forge.status}); ${forge.remedy || 'check `gh auth status`'}` };
+}
+
+/**
+ * Adapt `execGh`/`execGlab` (this module's own spawn primitives) to the
+ * `(cli, args, { cwd, env }) => { code, stdout, stderr }` shape the Layered
+ * Intelligence loop's `runCli` already uses and never rejects — so
+ * `fileForgeIssue` reads one result shape regardless of which CLI answered,
+ * and a caller that already has an injectable exec (`runCli`, or a test
+ * double shaped like it) can pass it straight through instead.
+ */
+async function execForgeIssueCli(cli, args, { cwd = undefined, env = undefined } = {}) {
+ const run = cli === 'glab'
+ ? execGlab(args, cwd, undefined, { env, rejectOnError: true })
+ : execGh(args, undefined, { cwd, env });
+ return run.then(
+ (stdout) => ({ code: 0, stdout: stdout || '', stderr: '' }),
+ (error) => ({ code: 1, stdout: '', stderr: error?.message || String(error) }),
+ );
+}
+
+/**
+ * Create every label an issue is about to carry, before the issue itself.
+ * Both CLIs 422 the whole `issue create` on an undefined label, so this always
+ * runs first. One label-failure policy for every filer (#7687): an "already
+ * exists" reply is expected and fine (label creation is otherwise idempotent),
+ * anything else aborts the file — a permission or auth problem should surface
+ * now rather than let the caller proceed to a create that is doomed anyway (or,
+ * worse, silently ships without the label a caller assumed would exist).
+ * Returns the first hard-failure message, or `null` when every label is ready.
+ */
+async function ensureForgeIssueLabels({ cli, exec, cwd, env, repo, labels }) {
+ const results = await Promise.all(labels.map(async (spec) => {
+ const { code, stdout, stderr } = await exec(cli, forgeLabelCreateArgs(cli, spec, { repo }), { cwd, env });
+ if (code === 0) return null;
+ if (/already exists/i.test(`${stderr || ''}\n${stdout || ''}`)) return null;
+ return boundedErrorMessage(new Error(stderr || `${cli} label create failed for "${spec.name}"`), `Could not create label "${spec.name}"`);
+ }));
+ return results.find(Boolean) || null;
+}
+
+/**
+ * File one issue on a forge — the exec half every filer needs (#7687): probe
+ * reachability, ensure each label exists, create the issue, and parse its
+ * number/url back out — scrubbing the title/body by construction rather than
+ * trusting each caller to remember to.
+ *
+ * Primitive-first on purpose rather than `{ app, target }`: `forgeFiler.js`
+ * (the Layered Intelligence loop) never resolved either shape — it only ever
+ * had `cli`/`cwd`/`env` and its own injectable `exec` — so this accepts what
+ * every caller already has instead of forcing one caller's resolution shape
+ * onto the other two. `persistentMindIssueCapability.js` and
+ * `goalFidelityFollowUp.js` keep their own early reachability probe (via the
+ * same `probeForgeReachability` this uses) ahead of their pre-file duplicate
+ * check — an unreachable forge should short-circuit before that read, not
+ * after — so they omit `hostname` here to avoid probing twice.
+ *
+ * @param {object} args
+ * @param {'gh'|'glab'} args.cli
+ * @param {string} [args.cwd] - spawn cwd/env context for `gh` (irrelevant once `repo` is set)
+ * @param {object} [args.env]
+ * @param {string|null} [args.repo] - `gh --repo` selector; unused for `glab`, which resolves from cwd
+ * @param {string|null} [args.repoPath] - repo checkout root `glab` must run in; falls back to `cwd`
+ * @param {string|null} [args.hostname] - github API host to probe; omit to skip the probe (already done, or non-github)
+ * @param {string} args.title
+ * @param {string} args.body
+ * @param {{name:string, color:string, description:string}[]} [args.labels] - applied to the issue AND created first
+ * @param {(cli:string, args:string[], opts:object) => Promise<{code:number, stdout:string, stderr:string}>} [args.exec]
+ * @returns {Promise<{ok:true, number:number|null, url:string}|{ok:false, error:string}>}
+ */
+export async function fileForgeIssue({
+ cli, cwd = undefined, env = undefined, repo = null, repoPath = null,
+ hostname = null, title, body, labels = [], exec = execForgeIssueCli,
+} = {}) {
+ const probe = await probeForgeReachability({ cli, hostname, env, label: 'file-forge-issue' });
+ if (!probe.ok) return { ok: false, error: probe.error };
+
+ const execCwd = cli === 'glab' ? (repoPath ?? cwd) : cwd;
+ const labelError = await ensureForgeIssueLabels({ cli, exec, cwd: execCwd, env, repo, labels });
+ if (labelError) return { ok: false, error: labelError };
+
+ const args = forgeIssueCreateArgs(cli, {
+ title: scrubForgeIssueText(title),
+ body: scrubForgeIssueText(body),
+ labels: labels.map((spec) => spec.name),
+ repo: cli === 'glab' ? null : repo,
+ });
+ const { code, stdout, stderr } = await exec(cli, args, { cwd: execCwd, env });
+ if (code !== 0) {
+ return { ok: false, error: boundedErrorMessage(new Error(stderr || `${cli} exited with code ${code}`), 'Issue creation failed') };
+ }
+ return { ok: true, ...parseCreatedForgeIssue(stdout) };
+}
diff --git a/server/services/appIssues.test.js b/server/services/appIssues.test.js
index 6cdba7ffb4..780332e9be 100644
--- a/server/services/appIssues.test.js
+++ b/server/services/appIssues.test.js
@@ -22,7 +22,8 @@ vi.mock('../lib/fileUtils.js', () => ({
safeJSONParse: (raw, fallback) => { try { return JSON.parse(raw); } catch { return fallback; } },
}));
-import { listAppIssues, prepareAppIssueClaim } from './appIssues.js';
+import { homedir } from 'os';
+import { fileForgeIssue, listAppIssues, prepareAppIssueClaim, probeForgeReachability, scrubForgeIssueText } from './appIssues.js';
import { execGh } from './github.js';
import { execGlab, execGlabJson } from './gitlab.js';
import { getOriginInfo, readOriginRemoteUrl } from '../lib/gitRemote.js';
@@ -464,3 +465,113 @@ describe('prepareAppIssueClaim', () => {
);
});
});
+
+// #7687 — the exec half every forge filer needs: probe, create labels, create
+// the issue, and scrub the title/body by construction so no caller can forget.
+describe('fileForgeIssue', () => {
+ const LABELS = [{ name: 'plan', color: '0E8A16', description: 'Claimable backlog item' }];
+
+ it('creates every label before the issue, then returns its parsed number/url', async () => {
+ execGh.mockResolvedValueOnce('').mockResolvedValueOnce('https://github.com/acme/widget/issues/9\n');
+ const result = await fileForgeIssue({ cli: 'gh', repo: 'github.com/acme/widget', title: 'T', body: 'B', labels: LABELS });
+
+ expect(result).toEqual({ ok: true, number: 9, url: 'https://github.com/acme/widget/issues/9' });
+ expect(execGh.mock.calls[0][0]).toEqual(['label', 'create', 'plan', '--repo', 'github.com/acme/widget', '--color', '0E8A16', '--description', 'Claimable backlog item']);
+ expect(execGh.mock.calls[1][0]).toEqual(['issue', 'create', '--repo', 'github.com/acme/widget', '--title', 'T', '--body', 'B', '--label', 'plan']);
+ });
+
+ it('tolerates a label that already exists', async () => {
+ execGh.mockRejectedValueOnce(new Error('label with this name already exists'))
+ .mockResolvedValueOnce('https://github.com/acme/widget/issues/9');
+ const result = await fileForgeIssue({ cli: 'gh', title: 'T', body: 'B', labels: LABELS });
+ expect(result.ok).toBe(true);
+ });
+
+ it('aborts on a real label-create failure without attempting the issue create', async () => {
+ execGh.mockRejectedValueOnce(new Error('HTTP 403: Resource not accessible'));
+ const result = await fileForgeIssue({ cli: 'gh', title: 'T', body: 'B', labels: LABELS });
+ expect(result).toMatchObject({ ok: false, error: expect.stringContaining('HTTP 403') });
+ expect(execGh).toHaveBeenCalledTimes(1);
+ });
+
+ it('reports a bounded error on a failed create rather than claiming success', async () => {
+ execGh.mockResolvedValueOnce('').mockRejectedValueOnce(new Error('GraphQL: Resource not accessible'));
+ const result = await fileForgeIssue({ cli: 'gh', title: 'T', body: 'B', labels: LABELS });
+ expect(result).toMatchObject({ ok: false, error: expect.stringContaining('Resource not accessible') });
+ });
+
+ it('probes reachability first when a hostname is given, before any label or issue call', async () => {
+ ensureForgeReachableMock.mockResolvedValue({ ok: false, status: 'unauthenticated', remedy: 'run `gh auth login`' });
+ const result = await fileForgeIssue({ cli: 'gh', hostname: 'github.com', title: 'T', body: 'B', labels: LABELS });
+ expect(result).toMatchObject({ ok: false, error: expect.stringContaining('gh auth login') });
+ expect(execGh).not.toHaveBeenCalled();
+ });
+
+ it('skips the probe with no hostname — a caller that already probed', async () => {
+ ensureForgeReachableMock.mockResolvedValue({ ok: false, status: 'unauthenticated' });
+ execGh.mockResolvedValueOnce('').mockResolvedValueOnce('https://github.com/acme/widget/issues/1');
+ const result = await fileForgeIssue({ cli: 'gh', title: 'T', body: 'B', labels: LABELS });
+ expect(result.ok).toBe(true);
+ expect(ensureForgeReachableMock).not.toHaveBeenCalled();
+ });
+
+ it('never probes a glab filer — ensureForgeReachable is gh-only', async () => {
+ execGlab.mockResolvedValueOnce('').mockResolvedValueOnce('https://gitlab.com/group/proj/-/issues/1');
+ const result = await fileForgeIssue({ cli: 'glab', hostname: 'gitlab.com', repoPath: '/repo', title: 'T', body: 'B', labels: LABELS });
+ expect(result.ok).toBe(true);
+ expect(ensureForgeReachableMock).not.toHaveBeenCalled();
+ });
+
+ it('creates through glab in the given repo checkout, joining labels with a comma', async () => {
+ execGlab.mockResolvedValueOnce('').mockResolvedValueOnce('https://gitlab.com/group/proj/-/issues/4');
+ await fileForgeIssue({ cli: 'glab', repoPath: '/repo', title: 'T', body: 'B', labels: LABELS });
+ expect(execGlab).toHaveBeenNthCalledWith(2, ['issue', 'create', '--title', 'T', '--description', 'B', '--label', 'plan'], '/repo', undefined, { env: undefined, rejectOnError: true });
+ });
+
+ // #7687 — a filer that never called its own scrub (the Layered Intelligence
+ // loop's `fileProposalToForge`) is protected the same as one that did, since
+ // the strip is enforced here rather than trusted to each caller's memory.
+ it('strips the home-directory prefix and credential-shaped tokens from the title and body', async () => {
+ const home = homedir();
+ execGh.mockResolvedValueOnce('').mockResolvedValueOnce('https://github.com/acme/widget/issues/1');
+ await fileForgeIssue({
+ cli: 'gh', labels: LABELS,
+ title: `Sync fails under ${home}/work/demo`,
+ body: `Retries with ghp_${'A'.repeat(36)} and dies.\nSee ${home}/logs/sync.log.`,
+ });
+ const createArgs = execGh.mock.calls[1][0];
+ const title = createArgs[createArgs.indexOf('--title') + 1];
+ const body = createArgs[createArgs.indexOf('--body') + 1];
+ expect(title).toBe('Sync fails under ~/work/demo');
+ expect(title).not.toContain(home);
+ expect(body).toContain('[REDACTED]');
+ expect(body).not.toContain('ghp_');
+ expect(body).not.toContain(home);
+ });
+});
+
+describe('probeForgeReachability', () => {
+ it('is a no-op for a non-github cli or a missing hostname', async () => {
+ expect(await probeForgeReachability({ cli: 'glab', hostname: 'gitlab.com', label: 'x' })).toEqual({ ok: true });
+ expect(await probeForgeReachability({ cli: 'gh', hostname: null, label: 'x' })).toEqual({ ok: true });
+ expect(ensureForgeReachableMock).not.toHaveBeenCalled();
+ });
+
+ it('formats an unreachable github as a refusal naming the status and remedy', async () => {
+ ensureForgeReachableMock.mockResolvedValue({ ok: false, status: 'offline', remedy: 'check the network' });
+ expect(await probeForgeReachability({ cli: 'gh', hostname: 'github.com', label: 'x' }))
+ .toEqual({ ok: false, error: 'GitHub is not reachable (offline); check the network' });
+ });
+});
+
+describe('scrubForgeIssueText', () => {
+ it('passes a non-string through untouched', () => {
+ expect(scrubForgeIssueText(undefined)).toBeUndefined();
+ expect(scrubForgeIssueText(null)).toBeNull();
+ });
+
+ it('leaves ordinary prose and repo-relative paths untouched', () => {
+ const body = 'server/services/sync.js drops job 4f2a on retry.';
+ expect(scrubForgeIssueText(body)).toBe(body);
+ });
+});
diff --git a/server/services/goalFidelityFollowUp.js b/server/services/goalFidelityFollowUp.js
index 83483e44ef..8dc2651cbf 100644
--- a/server/services/goalFidelityFollowUp.js
+++ b/server/services/goalFidelityFollowUp.js
@@ -43,18 +43,16 @@
* is decided, records what happened, and proceeds either way.
*/
-import { execGh, ensureForgeReachable } from './github.js';
-import { execGlab, execGlabJson } from './gitlab.js';
+import { execGh } from './github.js';
+import { execGlabJson } from './gitlab.js';
import { resolveForgeExecOptions } from './forgeExecOptions.js';
import { PORTOS_APP_ID, getAppById } from './apps.js';
import { getSettings } from './settings.js';
import { fileInvestigationTask } from './investigationTaskProducer.js';
+import { fileForgeIssue, probeForgeReachability, scrubForgeIssueText } from './appIssues.js';
import { forgeCliForTracker, resolveAppForgeTarget } from '../lib/workTracker.js';
-import { forgeIssueCreateArgs, forgeLabelCreateArgs, parseCreatedForgeIssue } from '../lib/forgeIssueCli.js';
import { safeJSONParse } from '../lib/fileUtils.js';
import { boundedErrorMessage } from '../lib/errorHandler.js';
-import { scrubHomePath } from '../lib/homePath.js';
-import { scrubSecretTokens } from '../lib/secretText.js';
import {
GOAL_FIDELITY_ISSUE_LABEL,
GOAL_FIDELITY_ISSUE_LABEL_SPEC,
@@ -79,22 +77,6 @@ const PAGE_LIMIT = 100;
*/
const SCAN_LIMIT = 1_000;
-/**
- * The last thing that happens to a title/body before a tracker sees it.
- *
- * Same enforcement as the persistent mind's filer, for the same reason: a filed
- * issue is world-readable the moment it lands, and the free text here is
- * model-authored prose derived from an untrusted diff. `scrubHomePath` collapses
- * the running user's home prefix (which embeds the OS username in
- * `/Users/<name>/…`); `scrubSecretTokens` replaces credential-shaped substrings.
- * Applied to the TITLE too — it is as public as the body.
- *
- * Deliberately NOT applied to the fingerprint marker's own text: it is derived
- * from a slug of the task's first line and carries no path or credential shape,
- * and a scrub that rewrote it would break the dedup it exists to serve.
- */
-const scrubForgeText = (value) => scrubSecretTokens(scrubHomePath(value));
-
/**
* The managed-app record whose tracker this finding belongs on.
*
@@ -213,31 +195,15 @@ async function listFiledIssues({ app, target, tracker, exec }) {
}));
}
-/**
- * Create the marker label, then the issue.
- *
- * The label create is idempotent and its failure is swallowed — both CLIs fail
- * the whole `issue create` with a 422 on an undefined label, so a label we
- * could not create resurfaces as the create's own error if it mattered.
- */
-async function createForgeIssue({ app, target, tracker, exec, title, body }) {
+/** Create the marker label, then the issue — the exec half shared by every forge filer (#7687). */
+function createForgeIssue({ app, target, tracker, exec, title, body }) {
const cli = forgeCliForTracker(tracker);
- const spec = { name: GOAL_FIDELITY_ISSUE_LABEL, ...GOAL_FIDELITY_ISSUE_LABEL_SPEC };
- await (cli === 'glab'
- ? execGlab(forgeLabelCreateArgs(cli, spec), app.repoPath)
- : execGh(forgeLabelCreateArgs(cli, spec, { repo: target.repoSpec }), undefined, { cwd: exec.cwd, env: exec.env })
- ).catch(() => null);
-
- const args = forgeIssueCreateArgs(cli, {
- title, body, labels: [GOAL_FIDELITY_ISSUE_LABEL], repo: cli === 'glab' ? null : target.repoSpec,
+ return fileForgeIssue({
+ cli, cwd: exec.cwd, env: exec.env, repoPath: app.repoPath,
+ repo: cli === 'glab' ? null : target.repoSpec,
+ title, body,
+ labels: [{ name: GOAL_FIDELITY_ISSUE_LABEL, ...GOAL_FIDELITY_ISSUE_LABEL_SPEC }],
});
- return (cli === 'glab'
- ? execGlab(args, app.repoPath, undefined, { rejectOnError: true })
- : execGh(args, undefined, { cwd: exec.cwd, env: exec.env })
- ).then(
- (stdout) => ({ ok: true, ...parseCreatedForgeIssue(stdout) }),
- (error) => ({ ok: false, error: boundedErrorMessage(error, 'Issue creation failed') }),
- );
}
/**
@@ -306,14 +272,14 @@ async function fileFollowUpIssue({ task, review, fingerprint }) {
const exec = tracker === 'jira' ? null : await resolveForgeContext(app, tracker);
// The reachability probe runs before anything is read or created: on an
// unreachable forge this is one failing call instead of a list and a label
- // create that each have to time out first.
- if (tracker === 'github') {
- const forge = await ensureForgeReachable('goal-fidelity-followup', {
- hostname: target.apiHost,
- ...(exec.customEnv ? { env: exec.customEnv } : {}),
- });
- if (!forge.ok) return { issue: null, error: `GitHub is not reachable (${forge.status}); nothing was filed` };
- }
+ // create that each have to time out first. Kept ahead of the duplicate read
+ // below rather than folded into `fileForgeIssue`'s own probe, for the same
+ // reason `persistentMindIssueCapability.js` keeps its own early probe.
+ const probe = await probeForgeReachability({
+ cli: forgeCliForTracker(tracker), hostname: target?.apiHost, env: exec?.customEnv,
+ label: 'goal-fidelity-followup',
+ });
+ if (!probe.ok) return { issue: null, error: probe.error };
// Read before writing. A failed read must NOT read as "nothing is tracked" —
// that is exactly how a transient CLI blip files the same issue twice — so an
@@ -331,14 +297,16 @@ async function fileFollowUpIssue({ task, review, fingerprint }) {
}
const { title, body } = buildGoalFidelityIssue({ task, review, fingerprint });
- // Scrubbed on the way to the tracker: a filed issue is world-readable the
- // moment it lands, and this text is model-authored prose derived from an
- // untrusted diff. The marker itself is a slug of the task's first line and
- // carries no path or credential shape, so the scrub leaves it intact — which
- // it must, or the issue it files could never dedupe against itself.
+ // The forge path is scrubbed by `fileForgeIssue` itself, by construction —
+ // JIRA doesn't go through it, so it scrubs explicitly here. A filed issue is
+ // world-readable the moment it lands, and this text is model-authored prose
+ // derived from an untrusted diff. The marker itself is a slug of the task's
+ // first line and carries no path or credential shape, so the scrub leaves it
+ // intact — which it must, or the issue it files could never dedupe against
+ // itself.
const created = tracker === 'jira'
- ? await createJiraIssue({ app, title: scrubForgeText(title), body: scrubForgeText(body) })
- : await createForgeIssue({ app, target, tracker, exec, title: scrubForgeText(title), body: scrubForgeText(body) });
+ ? await createJiraIssue({ app, title: scrubForgeIssueText(title), body: scrubForgeIssueText(body) })
+ : await createForgeIssue({ app, target, tracker, exec, title, body });
if (!created.ok) return { issue: null, error: created.error };
return { issue: { number: created.number, url: created.url, duplicate: false }, error: null };
}
diff --git a/server/services/goalFidelityFollowUp.test.js b/server/services/goalFidelityFollowUp.test.js
index 1a043fa326..5ce6a85458 100644
--- a/server/services/goalFidelityFollowUp.test.js
+++ b/server/services/goalFidelityFollowUp.test.js
@@ -12,6 +12,7 @@
*/
import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { homedir } from 'os';
const execGh = vi.fn();
const execGlab = vi.fn();
@@ -131,6 +132,34 @@ describe('runGoalFidelityFollowUp — GitHub', () => {
expect(createArgs[createArgs.indexOf('--body') + 1]).toContain(MARKER);
});
+ // #7687 — the forge path no longer scrubs at the call site; it is enforced
+ // by `fileForgeIssue` itself, by construction, so this caller can't forget.
+ it('strips a home-directory prefix and a credential-shaped token from the filed title and body', async () => {
+ settings({ fileIssue: true });
+ const home = homedir();
+ execGh
+ .mockResolvedValueOnce(ghRows([]))
+ .mockResolvedValueOnce('')
+ .mockResolvedValueOnce('https://github.com/acme/comics/issues/50');
+ const result = await runGoalFidelityFollowUp({
+ agentId: 'agent-1',
+ task: { ...TASK, description: `Fix the sync poller under ${home}/work/demo` },
+ review: { ...REVIEW, evidence: `Retried with ghp_${'A'.repeat(36)} and gave up.` },
+ });
+ expect(result.issue).toMatchObject({ number: 50, duplicate: false });
+ const createArgs = execGh.mock.calls.at(-1)[0];
+ const title = createArgs[createArgs.indexOf('--title') + 1];
+ const body = createArgs[createArgs.indexOf('--body') + 1];
+ expect(title).not.toContain(home);
+ expect(title).toContain('~/work/demo');
+ expect(body).not.toContain(home);
+ expect(body).not.toContain('ghp_');
+ expect(body).toContain('[REDACTED]');
+ // The dedup marker survives — the scrub must not touch it, or the issue it
+ // files could never dedupe against itself.
+ expect(body).toContain(goalFidelityIssueMarker(goalFidelityFingerprint({ ...TASK, description: `Fix the sync poller under ${home}/work/demo` })));
+ });
+
// The dedup lists by LABEL across every STATE rather than by full-text
// search: a label is a direct field filter with no index lag, and the lag
// window is exactly when a scheduled task re-runs.
diff --git a/server/services/layeredIntelligence.test.js b/server/services/layeredIntelligence.test.js
index e9a23e5451..02a452f2cb 100644
--- a/server/services/layeredIntelligence.test.js
+++ b/server/services/layeredIntelligence.test.js
@@ -1,6 +1,6 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { mkdtemp, readFile, writeFile, rm } from 'fs/promises';
-import { tmpdir } from 'os';
+import { tmpdir, homedir } from 'os';
import { join } from 'path';
import { extractTaskType } from './taskLearning/store.js';
import {
@@ -2908,6 +2908,32 @@ describe('forge I/O (injected exec)', () => {
expect(createCall).toContain(LI_LABEL);
});
+ // #7687 — the Layered Intelligence loop's own proposal text (LLM-authored,
+ // derived from an untrusted diff) never scrubbed before this filer moved
+ // onto the shared `fileForgeIssue` wrapper, which scrubs by construction.
+ it('strips a home-directory prefix and a credential-shaped token from the filed title and body', async () => {
+ const home = homedir();
+ const exec = vi.fn().mockResolvedValue({ code: 0, stdout: 'https://github.com/o/r/issues/9\n' });
+ const res = await fileProposalToForge({
+ cli: 'gh', cwd: '/x',
+ title: `Sync fails under ${home}/work/demo`,
+ body: `Retried with ghp_${'A'.repeat(36)} and gave up.`,
+ slug: 's', model: 'light', effort: 'low', exec,
+ });
+ expect(res.success).toBe(true);
+ const createCall = exec.mock.calls.find((c) => c[1][0] === 'issue')[1];
+ const title = createCall[createCall.indexOf('--title') + 1];
+ const body = createCall[createCall.indexOf('--body') + 1];
+ expect(title).not.toContain(home);
+ expect(title).toContain('~/work/demo');
+ expect(body).not.toContain(home);
+ expect(body).not.toContain('ghp_');
+ expect(body).toContain('[REDACTED]');
+ // The slug marker survives the scrub — it carries no path or credential
+ // shape, and rewriting it would break the dedup it exists to serve.
+ expect(body).toContain(slugMarker('s'));
+ });
+
it('fileProposalToForge creates and applies independent dispatch + contributor labels', async () => {
const exec = vi.fn().mockResolvedValue({ code: 0, stdout: 'https://github.com/o/r/issues/9\n' });
const res = await fileProposalToForge({
diff --git a/server/services/layeredIntelligence/forgeFiler.js b/server/services/layeredIntelligence/forgeFiler.js
index 54c401e84a..6d881935d7 100644
--- a/server/services/layeredIntelligence/forgeFiler.js
+++ b/server/services/layeredIntelligence/forgeFiler.js
@@ -12,7 +12,8 @@ import { LI_LABEL, LI_BLOCKING_LABEL } from './constants.js';
import { slugMarker, extractSlugFromBody } from './dedup.js';
import { runCli } from './runCli.js';
import { withGlabJson } from '../../lib/glabArgs.js';
-import { forgeIssueCreateArgs, forgeLabelCreateArgs, parseCreatedForgeIssue } from '../../lib/forgeIssueCli.js';
+import { forgeLabelCreateArgs } from '../../lib/forgeIssueCli.js';
+import { fileForgeIssue } from '../appIssues.js';
export { normalizeIssueState };
@@ -245,14 +246,14 @@ export async function ensureForgeLabels({ cli, cwd, env, extraLabels = [], exec
}
/**
- * File ONE proposal issue on a forge (gh/glab). Ensures labels first, embeds the
- * slug marker in the body, and returns `{ success, number, url }`. The issue
- * number is parsed from the created URL's trailing digits. Required dispatch
- * hints are validated before filing; contributor labels remain optional — never
- * derived from `complexity`. `planner` is the identity of
- * the model that REASONED this proposal (PortOS knows it; the reasoner is never
- * asked to name itself), applied as `planner:<model>` (`planner::<model>` on GitLab) and lazily created by
- * `ensureForgeLabels` like every other extra.
+ * File ONE proposal issue on a forge (gh/glab) — through the exec half every
+ * forge filer shares (`fileForgeIssue`, #7687): create each label, embed the
+ * slug marker in the body, create the issue, and parse `{ success, number,
+ * url }` from the result. Required dispatch hints are validated before filing;
+ * contributor labels remain optional — never derived from `complexity`.
+ * `planner` is the identity of the model that REASONED this proposal (PortOS
+ * knows it; the reasoner is never asked to name itself), applied as
+ * `planner:<model>` (`planner::<model>` on GitLab).
*/
export async function fileProposalToForge({
cli, cwd, env, title, body, slug, model, effort, goodFirstIssue, helpWanted, planner, exec = runCli
@@ -260,13 +261,12 @@ export async function fileProposalToForge({
if (!isDispatchModel(model) || !isDispatchEffort(effort)) {
return { success: false, error: 'Issue filing requires valid model and effort dispatch labels; investigate and supply both before retrying' };
}
- const extras = forgeIssueLabels({ model, effort, goodFirstIssue, helpWanted, planner, cli });
- await ensureForgeLabels({ cli, cwd, env, extraLabels: extras, exec });
- const fullBody = `${body}\n\n${slugMarker(slug)}`;
- const args = forgeIssueCreateArgs(cli, { title, body: fullBody, labels: [LI_LABEL, ...extras] });
- const { code, stdout, stderr } = await exec(cli, args, { cwd, env });
- if (code !== 0) return { success: false, error: stderr || `${cli} exited with code ${code}` };
- return { success: true, ...parseCreatedForgeIssue(stdout) };
+ const names = [LI_LABEL, ...forgeIssueLabels({ model, effort, goodFirstIssue, helpWanted, planner, cli })];
+ const labels = names.map((name) => dispatchLabelSpec(name, { cli }) || { name, color: '1d76db', description: 'Filed by the Layered Intelligence loop' });
+ const result = await fileForgeIssue({ cli, cwd, env, title, body: `${body}\n\n${slugMarker(slug)}`, labels, exec });
+ return result.ok
+ ? { success: true, number: result.number, url: result.url }
+ : { success: false, error: result.error };
}
/**
@@ -276,9 +276,10 @@ export async function fileProposalToForge({
* `gh issue edit --add-label` and `glab issue update --label` fail the WHOLE
* call with a 422 when the repo has never defined the named label, and this is
* the only path that applies `LI_BLOCKING_LABEL` — so on any install where the
- * Layered Intelligence loop has not yet FILED an issue (the other caller of
- * `ensureForgeLabels`), the very first pause would fail. Existing labels are
- * accepted there, while other creation failures are surfaced.
+ * Layered Intelligence loop has not yet FILED an issue (`fileForgeIssue` covers
+ * the issue-filing labels via the shared exec-half wrapper), the very first
+ * pause would fail. Existing labels are accepted there, while other creation
+ * failures are surfaced.
*/
export async function applyBlockingLabel({ cli, cwd, env, number, exec = runCli } = {}) {
if (!Number.isInteger(number)) return { success: false, error: 'no issue number' };
diff --git a/server/services/persistentMindIssueCapability.js b/server/services/persistentMindIssueCapability.js
index c746027598..9521537a99 100644
--- a/server/services/persistentMindIssueCapability.js
+++ b/server/services/persistentMindIssueCapability.js
@@ -15,10 +15,8 @@
* a claim would read from.
*/
-import { execGh, ensureForgeReachable } from './github.js';
-import { execGlab } from './gitlab.js';
import { loadState } from './cosState.js';
-import { listAppIssues } from './appIssues.js';
+import { fileForgeIssue, listAppIssues, probeForgeReachability, scrubForgeIssueText } from './appIssues.js';
import { readPersistentMindManagedApps } from './persistentMindManagedApps.js';
import { normalizePersistentMindCapabilities } from '../lib/persistentMindCapabilities.js';
import { normalizePersistentMindProfile } from '../lib/persistentMindProfile.js';
@@ -26,12 +24,8 @@ import {
DISPATCH_EFFORT_LEVELS, DISPATCH_MODEL_TIERS,
dispatchLabelSpec, forgeIssueLabels, resolvePlannerId,
} from '../lib/dispatchLabels.js';
-import { forgeIssueCreateArgs, forgeLabelCreateArgs, parseCreatedForgeIssue } from '../lib/forgeIssueCli.js';
import { forgeCliForTracker } from '../lib/workTracker.js';
import { boundedByJsonChars } from '../lib/objects.js';
-import { boundedErrorMessage } from '../lib/errorHandler.js';
-import { scrubHomePath } from '../lib/homePath.js';
-import { scrubSecretTokens } from '../lib/secretText.js';
import {
PERSISTENT_MIND_ISSUE_EXTRA_LABEL_SPECS,
PERSISTENT_MIND_ISSUE_CATEGORY_LABELS,
@@ -42,28 +36,6 @@ import {
const MAX_CATALOG_PROMPT_CHARS = 2_000;
-/**
- * The last thing that happens to a title/body before `gh`/`glab` sees it.
- *
- * The capability's Settings guardrail asserts that no repository paths or
- * credentials ride along, and a filed issue is world-readable the moment it
- * lands — so the assertion has to be ENFORCED here rather than trusted to the
- * prompt above. Both halves are mechanically decidable and already have one
- * definition in the tree: `scrubHomePath` collapses the running user's home
- * prefix (which is what embeds the OS username in `/Users/<name>/…`), and
- * `scrubSecretTokens` replaces credential-SHAPED substrings. Neither is a
- * content filter — "no private records" stays a prompt instruction, because no
- * regex can decide whether a sentence of the mind's own prose is one, and the
- * guardrail text now says exactly that rather than promising more.
- *
- * Applied to the TITLE as well as the body: the title is what a duplicate check
- * on any other machine reads back, and a leaked path there is just as public.
- *
- * Both helpers pass a non-string through untouched, so this adds no coercion of
- * its own — the tool schema already requires both fields to be strings.
- */
-const scrubForgeText = (value) => scrubSecretTokens(scrubHomePath(value));
-
const labelSpec = (name, cli) => dispatchLabelSpec(name, { cli })
|| (PERSISTENT_MIND_ISSUE_EXTRA_LABEL_SPECS[name]
? { name, ...PERSISTENT_MIND_ISSUE_EXTRA_LABEL_SPECS[name] }
@@ -167,51 +139,19 @@ export async function listPersistentMindIssues(args) {
};
}
-/**
- * Create the labels this issue needs before creating the issue. Both CLIs fail
- * the whole `issue create` with a 422 when a named label does not exist, and
- * creation is idempotent, so this always runs first. The calls are independent
- * and every failure is swallowed — a label we could not create resurfaces as
- * the create's own error if it actually mattered — so they run concurrently
- * rather than adding a serial spawn per label to every file.
- */
-const ensureLabels = async ({ app, names }) => {
- const cli = forgeCliForTracker(app.forge);
- await Promise.all(names.map((name) => {
- const spec = labelSpec(name, cli);
- if (!spec) return null;
- return (cli === 'glab'
- ? execGlab(forgeLabelCreateArgs(cli, spec), app.repoPath)
- : execGh(forgeLabelCreateArgs(cli, spec, { repo: app.repoSpec }))).catch(() => null);
- }));
-};
-
-const createIssue = ({ app, title, body, labels }) => {
- const cli = forgeCliForTracker(app.forge);
- const args = forgeIssueCreateArgs(cli, {
- title, body, labels, repo: cli === 'glab' ? null : app.repoSpec,
- });
- const run = cli === 'glab'
- ? execGlab(args, app.repoPath, undefined, { rejectOnError: true })
- : execGh(args);
- return run.then(
- (stdout) => ({ ok: true, ...parseCreatedForgeIssue(stdout) }),
- (error) => ({ ok: false, error: boundedErrorMessage(error, 'Issue creation failed') }),
- );
-};
-
/** File one issue on the app's tracker. */
export async function filePersistentMindIssue(args) {
const { app, root, error } = await resolveTarget(args.appId);
if (error) return { ok: false, error };
+ const cli = forgeCliForTracker(app.forge);
// The reachability probe runs before anything is created: on an unreachable
// forge this is one failing call instead of a whole label fan-out that each
- // has to time out first.
- if (app.forge === 'github') {
- const forge = await ensureForgeReachable('mind-issue-file', { hostname: app.apiHost });
- if (!forge.ok) return { ok: false, error: `GitHub is not reachable (${forge.status}); ${forge.remedy || 'check `gh auth status`'}` };
- }
+ // has to time out first. Kept ahead of the duplicate read below rather than
+ // folded into `fileForgeIssue`'s own probe — an unreachable forge should
+ // short-circuit before that read runs at all, not after.
+ const probe = await probeForgeReachability({ cli, hostname: app.apiHost, label: 'mind-issue-file' });
+ if (!probe.ok) return { ok: false, error: probe.error };
// Duplicate guard. A failed read must NOT read as "nothing is tracked" — that
// is exactly how a transient `gh` blip files the same issue twice — so an
@@ -223,8 +163,8 @@ export async function filePersistentMindIssue(args) {
// Scrubbed BEFORE the duplicate check, not just before the create: the title
// that dedupes has to be the title that gets filed, or an issue whose only
// leaked path was in its title would re-file itself on every wake.
- const title = scrubForgeText(args.title);
- const body = scrubForgeText(args.body);
+ const title = scrubForgeIssueText(args.title);
+ const body = scrubForgeIssueText(args.body);
// An all-punctuation title normalizes to the empty string, which would match
// every other such title — only a title with real content can dedupe.
@@ -242,7 +182,7 @@ export async function filePersistentMindIssue(args) {
const labels = [
PERSISTENT_MIND_ISSUE_LABEL,
...forgeIssueLabels({
- cli: forgeCliForTracker(app.forge),
+ cli,
model: args.model,
effort: args.effort,
// The planner axis records who WROTE the plan — this mind's own model —
@@ -251,9 +191,12 @@ export async function filePersistentMindIssue(args) {
}),
...(args.labels || []),
].filter((name, index, all) => all.indexOf(name) === index);
- await ensureLabels({ app, names: labels });
- const created = await createIssue({ app, title, body, labels });
+ const created = await fileForgeIssue({
+ cli, title, body, repoPath: app.repoPath,
+ repo: cli === 'glab' ? null : app.repoSpec,
+ labels: labels.map((name) => labelSpec(name, cli)).filter(Boolean),
+ });
if (!created.ok) return created;
return {
ok: true,
diff --git a/server/services/persistentMindIssueCapability.test.js b/server/services/persistentMindIssueCapability.test.js
index 3d26b5c44a..d896c3d259 100644
--- a/server/services/persistentMindIssueCapability.test.js
+++ b/server/services/persistentMindIssueCapability.test.js
@@ -13,7 +13,14 @@ const mocks = vi.hoisted(() => ({
vi.mock('./cosState.js', () => ({ loadState: vi.fn(async () => mocks.root) }));
vi.mock('./apps.js', () => ({ getActiveApps: vi.fn(async () => mocks.apps) }));
-vi.mock('./appIssues.js', () => ({ listAppIssues: (...args) => mocks.listAppIssues(...args) }));
+// Only `listAppIssues` is doubled — `fileForgeIssue`/`probeForgeReachability`/
+// `scrubForgeIssueText` are the shared exec-half wrapper under test here too
+// (via persistentMindIssueCapability.js's real call into it), and run for
+// real against the doubled `./github.js`/`./gitlab.js` primitives below.
+vi.mock('./appIssues.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ listAppIssues: (...args) => mocks.listAppIssues(...args),
+}));
// `resolveAppForgeTarget` is doubled; `forgeCliForTracker` is a pure mapper the
// code under test relies on for real (it decides the forge's label separator),
// so it passes through rather than being stubbed into a second definition.