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

feat: track assigned GitHub issues as Brain threads on demand (#7664)

[._.]/ Adam Eivy3038a9a3ffc6
diff --git a/client/src/components/apps/tabs/IssuesTab.jsx b/client/src/components/apps/tabs/IssuesTab.jsx
index 4be9549911..32fa5ff4f9 100644
--- a/client/src/components/apps/tabs/IssuesTab.jsx
+++ b/client/src/components/apps/tabs/IssuesTab.jsx
@@ -21,7 +21,8 @@ import useReviewerModelOptions from '../../../hooks/useReviewerModelOptions';
import { chipColors } from '../../../lib/chipContrast';
import { enabledProcessProviderFilter } from '../../../utils/providers';
import * as api from '../../../services/api';
-import { timeAgo } from '../../../utils/formatters';
+import { timeAgo, formatCount } from '../../../utils/formatters';
+import { useAsyncAction } from '../../../hooks/useAsyncAction';
import AddToThreadButton from '../../threads/AddToThreadButton';
function ClaimReviewOverride({ defaults, overrides, onChange, modelOptions }) {
@@ -230,6 +231,12 @@ function LabelFilterChip({ facet, hidden, onToggle }) {
* offered alongside Claim rather than instead of it.
*/
export default function IssuesTab({ appId, appName }) {
+ const [trackAssigned, trackingAssigned] = useAsyncAction(async () => {
+ const result = await api.syncGithubThreads({ appId }, { silent: true });
+ const summary = `${appName}: ${formatCount(result.created)} threads added, ${formatCount(result.updated)} updated`;
+ if (result.possiblyTruncated) toast(`${summary}. More assigned issues may exist beyond this batch.`, { icon: '⚠️' });
+ else toast.success(summary);
+ });
const searchId = useId();
const filedById = useId();
const overrideContextId = useId();
@@ -587,6 +594,20 @@ export default function IssuesTab({ appId, appName }) {
</button>
</div>
+ {data?.forge === 'github' && (
+ <div className="flex flex-wrap items-center gap-3 text-xs">
+ <button
+ type="button"
+ onClick={trackAssigned}
+ disabled={trackingAssigned || loading}
+ className="px-3 py-1.5 rounded-lg border border-port-border text-port-accent hover:bg-port-accent/10 disabled:opacity-50"
+ >
+ {trackingAssigned ? 'Tracking assigned issues…' : 'Track my assigned issues in Brain'}
+ </button>
+ <Link to="/brain/threads" className="text-port-accent hover:underline">Open Threads</Link>
+ </div>
+ )}
+
{labelFacets.length > 0 && (
<div
role="group"
diff --git a/client/src/components/apps/tabs/IssuesTab.test.jsx b/client/src/components/apps/tabs/IssuesTab.test.jsx
index a67964dc3d..11926911f4 100644
--- a/client/src/components/apps/tabs/IssuesTab.test.jsx
+++ b/client/src/components/apps/tabs/IssuesTab.test.jsx
@@ -28,6 +28,7 @@ vi.mock('../../ThemeContext', () => ({
vi.mock('../../../services/api', () => ({
getAppIssues: vi.fn(),
+ syncGithubThreads: vi.fn(),
createSlashdoTask: vi.fn(),
getProviders: vi.fn(),
getLocalLlmStatus: vi.fn().mockResolvedValue(null),
@@ -913,3 +914,19 @@ describe('IssuesTab replan', () => {
expect(payload.reviewers).toBeUndefined();
});
});
+
+// One click imports the server-selected account's assignments, independent of
+// the visible list filters, and blocks another click until the request settles.
+it('tracks assigned GitHub issues explicitly and links to the resulting Brain list', async () => {
+ api.getAppIssues.mockResolvedValue(okPayload([ISSUE]));
+ let finish;
+ api.syncGithubThreads.mockImplementation(() => new Promise(resolve => { finish = resolve; }));
+ await renderTab();
+ const button = await findEnabledByRole('button', { name: 'Track my assigned issues in Brain' });
+ fireEvent.click(button);
+ expect(api.syncGithubThreads).toHaveBeenCalledWith({ appId: 'app-1' }, { silent: true });
+ expect(button.disabled).toBe(true);
+ expect(screen.getByRole('link', { name: 'Open Threads' }).getAttribute('href')).toBe('/brain/threads');
+ await act(async () => finish({ created: 1, updated: 0, possiblyTruncated: false }));
+ expect(button.disabled).toBe(false);
+});
diff --git a/client/src/services/README.md b/client/src/services/README.md
index 88daec1d7b..40b2a60ca7 100644
--- a/client/src/services/README.md
+++ b/client/src/services/README.md
@@ -73,7 +73,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire
| File | Purpose |
|---|---|
-| `apiBrainThreads.js` | Brain threads — the bullet journal's open loops (`/brain/threads`, Brain `threads` entity; a *thread* is a tracked topic, never a message thread): filtered list (`listThreads({ status, priority, tag, pinned, refKind, q })`), full record with `resolvedRefs` (`getThread`), create / defaults-free PUT / tombstone delete, per-ref attach/detach (`addThreadRef`, `removeThreadRef`), and attach (`attachToThread`). |
+| `apiBrainThreads.js` | Brain threads — the bullet journal's open loops (`/brain/threads`, Brain `threads` entity; a *thread* is a tracked topic, never a message thread): filtered list (`listThreads({ status, priority, tag, pinned, refKind, q })`), full record with `resolvedRefs` (`getThread`), create / defaults-free PUT / tombstone delete, per-ref attach/detach (`addThreadRef`, `removeThreadRef`), attach (`attachToThread`), and explicit assigned GitHub ingestion (`syncGithubThreads({ appId, pinned })`). |
| `apiBrain.js` | Brain (second-brain) search + ingest + edit, plus the federation parity audit (`getBrainParityReports`, `runBrainParityCheck`). |
| `apiMemory.js` | Memory CRUD. |
| `apiNotes.js` | Notes vault. |
diff --git a/client/src/services/apiBrainThreads.js b/client/src/services/apiBrainThreads.js
index 777eee244b..a4bf759289 100644
--- a/client/src/services/apiBrainThreads.js
+++ b/client/src/services/apiBrainThreads.js
@@ -47,3 +47,7 @@ export const removeThreadRef = (id, kind, refId, options) =>
// POST /api/brain/threads/attach — `{ ref, threadId?, title? }` → `{ thread, created }` (200 / 201).
export const attachToThread = (body = {}, options) =>
request('/brain/threads/attach', { method: 'POST', body: JSON.stringify(body), ...options });
+
+// Explicit, on-demand GitHub discovery; no background polling is enabled.
+export const syncGithubThreads = (body, options) =>
+ request('/brain/threads/sync', { method: 'POST', body: JSON.stringify(body), ...options });
diff --git a/docs/API.md b/docs/API.md
index c442ab6528..338461da51 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -419,6 +419,27 @@ Eidoverse — see [OpenWorld](./features/openworld.md).
| GET | `/brain/reconcile/parity` | Last stored parity report per peer (local read, no peer I/O) |
| POST | `/brain/reconcile/parity` | Run the record-level parity audit — body `{ peerId? }`, omitted sweeps every federating peer |
+### Brain Thread Ingestion
+
+A Brain thread is a tracked topic, distinct from a message thread.
+
+`POST /api/brain/threads/sync` accepts `{ "appId": "example-app", "pinned": false }`.
+It explicitly discovers issues assigned to the saved managed app's GitHub account
+and creates threads for observed open issues. The optional `pinned` value applies
+only to new records. Use the install's normal API authentication.
+
+The response contains `observed`, `created`, `updated`, `skipped`, and
+`possiblyTruncated`. The query reads at most 200 assigned open/closed issues;
+`possiblyTruncated: true` means this is not a complete inventory. Missing issues
+never imply closure or unassignment. Only an observed closed issue updates its
+existing thread's `externalState`; the human's status, title, notes, next action,
+priority and detached links remain untouched. Deleted threads stay deleted.
+A failed or malformed tracker response returns 502 without changing threads.
+
+Managed app GitHub Issues tabs expose this action as **Track my assigned issues in Brain**,
+with a link to the Threads list. This endpoint does not enable background polling. GitLab/JIRA sources, scheduling,
+settings controls and source-closed UI prompts are tracked separately in #7664.
+
### Brain Links
| Method | Endpoint | Description |
diff --git a/server/lib/brainValidation.js b/server/lib/brainValidation.js
index 1fab78b7fd..9ddbbc9075 100644
--- a/server/lib/brainValidation.js
+++ b/server/lib/brainValidation.js
@@ -872,6 +872,12 @@ export const threadQuerySchema = z.object({
q: z.string().trim().max(200).optional()
});
+// On-demand discovery of assigned GitHub issues for one saved managed app.
+export const threadSyncInputSchema = z.object({
+ appId: z.string().trim().min(1).max(128),
+ pinned: z.boolean().optional().default(false),
+}).strict();
+
// POST /api/brain/threads/:id/refs — attach one ref to an existing thread.
export const threadRefInputSchema = threadRefSchema;
diff --git a/server/routes/brainThreads.js b/server/routes/brainThreads.js
index fa6576dcdd..e6e34efb41 100644
--- a/server/routes/brainThreads.js
+++ b/server/routes/brainThreads.js
@@ -32,6 +32,7 @@ import {
threadQuerySchema,
threadRefInputSchema,
threadAttachSchema,
+ threadSyncInputSchema,
} from '../lib/brainValidation.js';
import { isTerminalThreadStatus as isTerminal, compareThreads } from '../lib/brainThreads.js';
import { canonicalThreadRefKind } from '../lib/threadRefKinds.js';
@@ -107,6 +108,12 @@ function matchesQuery(thread, q) {
// ATTACH (before /:id routes so 'attach' is never treated as an id)
// =============================================================================
+router.post('/sync', asyncHandler(async (req, res) => {
+ const input = validateRequest(threadSyncInputSchema, req.body);
+ const { syncGithubThreads } = await import('../services/threadSync.js');
+ res.json(await syncGithubThreads(input));
+}));
+
// POST /attach — `{ ref, threadId?, title? }`. Attaches to an existing thread,
// or mints one and attaches, in a single call: the one-click affordance every
// "add this to a thread" button posts, without making the caller choose between
diff --git a/server/routes/brainThreads.test.js b/server/routes/brainThreads.test.js
index 37dad1d099..b646f6e605 100644
--- a/server/routes/brainThreads.test.js
+++ b/server/routes/brainThreads.test.js
@@ -13,6 +13,8 @@ vi.mock('../services/brainStorage.js', () => ({
// The resolver has its own suite (services/threadRefs.test.js) and reaches
// Postgres; here it is a seam so these tests assert the ROUTE's contract.
+vi.mock('../services/threadSync.js', () => ({ syncGithubThreads: vi.fn(async () => ({ created: 1 })) }));
+
vi.mock('../services/threadRefs.js', () => ({ resolveThreadRefs: vi.fn() }));
import * as brainStorage from '../services/brainStorage.js';
@@ -73,6 +75,16 @@ describe('Brain Threads routes', () => {
app = buildApp();
});
+ it('validates explicit sync requests before dispatch and supplies creation defaults', async () => {
+ const { syncGithubThreads } = await import('../services/threadSync.js');
+ expect((await request(app).post('/api/brain/threads/sync').send({ appId: 'example-app', source: {} })).status).toBe(400);
+ expect(syncGithubThreads).not.toHaveBeenCalled();
+ const result = await request(app).post('/api/brain/threads/sync').send({ appId: 'example-app' });
+ expect(result.status).toBe(200);
+ expect(result.body).toEqual({ created: 1 });
+ expect(syncGithubThreads).toHaveBeenCalledWith({ appId: 'example-app', pinned: false });
+ });
+
// ===========================================================================
// CREATE — server-managed fields
// ===========================================================================
diff --git a/server/services/brainStorage.js b/server/services/brainStorage.js
index 80833c3d60..1cb4181833 100644
--- a/server/services/brainStorage.js
+++ b/server/services/brainStorage.js
@@ -561,8 +561,9 @@ export async function updateWith(type, id, fn) {
* pass the FULL desired record (this does not merge unknown fields the way
* `update()` does). `emitEvent:false` lets a caller (e.g. brainJournal) emit its
* own richer, bridge-shaped event instead of the generic one.
+ * createOnly:true returns null for any existing record, including tombstones.
*/
-export async function upsertWithId(type, id, recordData, { emitEvent = true } = {}) {
+export async function upsertWithId(type, id, recordData, { emitEvent = true, createOnly = false } = {}) {
const store = storeFor(type);
// A malformed id can't name a valid per-record dir — mirror the other write
// paths and no-op rather than letting the store's write-queue assertion throw.
@@ -572,6 +573,9 @@ export async function upsertWithId(type, id, recordData, { emitEvent = true } =
const fallbackOrigin = await getInstanceId();
return store.queueRecordWrite(id, async () => {
const existing = await store.loadOne(id);
+ // Ingestion must not overwrite an edit or resurrect a tombstone.
+ // Test presence inside the queue so a peer or local write cannot race.
+ if (createOnly && existing) return null;
const live = existing && !isTombstone(existing) ? existing : null;
const timestamp = now();
const originInstanceId = live?.originInstanceId ?? fallbackOrigin;
diff --git a/server/services/threadSync.js b/server/services/threadSync.js
new file mode 100644
index 0000000000..cfd8262210
--- /dev/null
+++ b/server/services/threadSync.js
@@ -0,0 +1,106 @@
+/**
+ * Discover assigned issues as Brain threads (tracked topics, NOT message threads).
+ * Explicit requests only: this module never schedules work or calls an AI provider.
+ * Missing rows are not evidence of closure: a bounded query can omit unassigned
+ * or older items. Only a positively observed CLOSED issue changes externalState.
+ */
+import { createHash } from 'node:crypto';
+import { z } from 'zod';
+import { ServerError } from '../lib/errorHandler.js';
+import { safeJSONParse } from '../lib/fileUtils.js';
+import { threadInputSchema } from '../lib/brainValidation.js';
+import * as brainStorage from './brainStorage.js';
+
+const LIMIT = 200;
+const inFlight = new Map();
+const issueRowsSchema = z.array(z.object({
+ number: z.number().int().positive(),
+ title: z.string().trim().min(1),
+ state: z.enum(['OPEN', 'CLOSED']),
+}));
+
+function probeFailure() {
+ return new ServerError('Could not read assigned GitHub issues; existing threads were left untouched', {
+ status: 502, code: 'THREAD_SYNC_FAILED',
+ });
+}
+
+async function runSync({ appId, pinned }) {
+ const { getAppById } = await import('./apps.js');
+ const { resolveAppForgeTarget } = await import('../lib/workTracker.js');
+ const { resolveForgeExecOptions } = await import('./forgeExecOptions.js');
+ const { execGh, ensureForgeReachable } = await import('./github.js');
+ const app = await getAppById(appId);
+ if (!app) throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });
+ const { tracker, target } = await resolveAppForgeTarget(app);
+ if (tracker !== 'github' || target?.forge !== 'github') {
+ throw new ServerError('Select an app whose work tracker is GitHub', {
+ status: 400, code: 'UNSUPPORTED_TRACKER',
+ });
+ }
+ const { cwd, env, customEnv } = await resolveForgeExecOptions(app.repoPath, {
+ forgeAccount: app.forgeAccount,
+ });
+ const reachable = await ensureForgeReachable('thread-sync', {
+ hostname: target.apiHost,
+ ...(customEnv ? { env: customEnv } : {}),
+ });
+ if (!reachable.ok) throw probeFailure();
+ const raw = await execGh([
+ 'issue', 'list', '--repo', target.repoSpec, '--assignee', '@me',
+ '--state', 'all', '--limit', String(LIMIT), '--json', 'number,title,state',
+ ], undefined, { cwd, env }).catch(() => null);
+ const parsed = issueRowsSchema.safeParse(safeJSONParse(raw, null));
+ if (!parsed.success) throw probeFailure();
+
+ // Validate the entire probe before the first write. Identity includes the
+ // forge host and full repository name; punctuation cannot cause slug
+ // collisions, and enterprise instances cannot alias github.com.
+ const repoKey = target.repoSpec.toLowerCase();
+ const rows = [...new Map(parsed.data.map(row => [row.number, row])).values()];
+ const result = { observed: rows.length, created: 0, updated: 0, skipped: 0, possiblyTruncated: rows.length === LIMIT };
+ for (const issue of rows) {
+ const key = JSON.stringify([repoKey, issue.number]);
+ const id = `gh-${createHash('sha256').update(key).digest('hex')}`;
+ const ref = {
+ kind: 'github.issue',
+ id: `https://${target.apiHost}/${target.fullName}/issues/${issue.number}`,
+ label: issue.title.slice(0, 300),
+ };
+ const externalState = issue.state === 'OPEN' ? 'open' : 'closed';
+ const source = { kind: ref.kind, key };
+ if (externalState === 'open') {
+ const created = await brainStorage.upsertWithId('threads', id, {
+ ...threadInputSchema.parse({ title: issue.title.slice(0, 200), pinned, refs: [ref] }),
+ source, externalState, closedAt: null,
+ }, { createOnly: true });
+ if (created) {
+ result.created++;
+ continue;
+ }
+ }
+ // Merge inside the store queue. Human fields, unknown peer fields,
+ // detached refs, and tombstones remain untouched.
+ const updated = await brainStorage.updateWith('threads', id, fresh => {
+ if (fresh.source?.kind !== source.kind || fresh.source?.key !== key) return null;
+ const refs = Array.isArray(fresh.refs) ? fresh.refs : [];
+ const changedLabel = refs.some(r => r.kind === ref.kind && r.id === ref.id && r.label !== ref.label);
+ if (fresh.externalState === externalState && !changedLabel) return null;
+ return {
+ externalState,
+ ...(changedLabel ? { refs: refs.map(r => r.kind === ref.kind && r.id === ref.id ? { ...r, label: ref.label } : r) } : {}),
+ };
+ });
+ if (updated) result.updated++;
+ else result.skipped++;
+ }
+ return result;
+}
+
+/** Repeated requests for the same app share one in-flight ingestion. */
+export function syncGithubThreads(input) {
+ if (inFlight.has(input.appId)) return inFlight.get(input.appId);
+ const pending = runSync(input).finally(() => inFlight.delete(input.appId));
+ inFlight.set(input.appId, pending);
+ return pending;
+}
diff --git a/server/services/threadSync.test.js b/server/services/threadSync.test.js
new file mode 100644
index 0000000000..57539248aa
--- /dev/null
+++ b/server/services/threadSync.test.js
@@ -0,0 +1,104 @@
+/** Brain threads are tracked topics, not message threads. */
+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
+import { makePathsProxy, lazyTempDataRoot, cleanupTempDataRoots } from '../lib/mockPathsDataRoot.js';
+vi.mock('../lib/fileUtils.js', async (original) => makePathsProxy(await original(), {
+ dataRoot: () => lazyTempDataRoot('thread-sync-test-'),
+}));
+vi.mock('./instanceIdentity.js', () => ({ getInstanceId: async () => 'example-instance' }));
+const { getAppById, resolveAppForgeTarget, resolveForgeExecOptions, execGh, ensureForgeReachable } = vi.hoisted(() => ({
+ getAppById: vi.fn(), resolveAppForgeTarget: vi.fn(), resolveForgeExecOptions: vi.fn(), execGh: vi.fn(), ensureForgeReachable: vi.fn(),
+}));
+vi.mock('./apps.js', () => ({ getAppById }));
+vi.mock('../lib/workTracker.js', async (original) => ({ ...await original(), resolveAppForgeTarget }));
+vi.mock('./forgeExecOptions.js', () => ({ resolveForgeExecOptions }));
+vi.mock('./github.js', () => ({ execGh, ensureForgeReachable }));
+import * as storage from './brainStorage.js';
+import { syncGithubThreads } from './threadSync.js';
+const sync = (body = { appId: 'example-app' }) => syncGithubThreads(body);
+const issue = { number: 42, title: 'Example issue', state: 'OPEN' };
+let sequence = 0;
+const currentRecord = async () => (await storage.getAll('threads')).find(t => t.source?.key.includes(`repo-${sequence}`));
+beforeEach(() => {
+ vi.clearAllMocks();
+ sequence++;
+ getAppById.mockResolvedValue({ repoPath: '/example/repo', forgeAccount: 'example-account' });
+ resolveAppForgeTarget.mockResolvedValue({ tracker: 'github', target: {
+ forge: 'github', apiHost: 'github.example.com', fullName: `example/repo-${sequence}`,
+ repoSpec: `github.example.com/example/repo-${sequence}`,
+ } });
+ resolveForgeExecOptions.mockResolvedValue({ cwd: '/example/repo', env: { EXAMPLE: 'pinned' }, customEnv: { EXAMPLE: 'pinned' } });
+ ensureForgeReachable.mockResolvedValue({ ok: true });
+ execGh.mockResolvedValue(JSON.stringify([issue]));
+});
+afterAll(cleanupTempDataRoots);
+describe('assigned GitHub issue ingestion through the real store', () => {
+ it('preserves human edits, unknown fields and tombstones across repeat discovery and closure', async () => {
+ expect((await sync({ appId: 'example-app', pinned: true })).created).toBe(1);
+ const record = await currentRecord();
+ expect(record).toMatchObject({ title: issue.title, pinned: true, status: 'open', externalState: 'open' });
+ expect(record.id).toMatch(/^gh-[a-f0-9]{64}$/);
+ expect(execGh).toHaveBeenCalledWith(expect.arrayContaining(['--assignee', '@me', '--repo', `github.example.com/example/repo-${sequence}`]), undefined, { cwd: '/example/repo', env: { EXAMPLE: 'pinned' } });
+ expect(resolveForgeExecOptions).toHaveBeenCalledWith('/example/repo', { forgeAccount: 'example-account' });
+ expect(ensureForgeReachable).toHaveBeenCalledWith('thread-sync', { hostname: 'github.example.com', env: { EXAMPLE: 'pinned' } });
+ await storage.update('threads', record.id, { title: 'My title', status: 'waiting', priority: 'urgent', notes: 'My notes', nextAction: 'Call', futureField: { keep: true } });
+ execGh.mockResolvedValue(JSON.stringify([{ ...issue, title: 'Renamed externally', state: 'CLOSED' }]));
+ expect((await sync())).toMatchObject({ created: 0, updated: 1 });
+ const edited = await storage.getById('threads', record.id);
+ expect(edited).toMatchObject({ title: 'My title', status: 'waiting', priority: 'urgent', notes: 'My notes', nextAction: 'Call', futureField: { keep: true }, externalState: 'closed', closedAt: null, pinned: true });
+ expect(edited.refs[0].label).toBe('Renamed externally');
+ expect((await sync())).toMatchObject({ created: 0, updated: 0 });
+ expect((await storage.getById('threads', record.id)).updatedAt).toBe(edited.updatedAt);
+ await storage.remove('threads', record.id);
+ const tombstone = (await storage.getRawRecords('threads'))[record.id];
+ execGh.mockResolvedValue(JSON.stringify([issue]));
+ expect((await sync()).created).toBe(0);
+ expect(await storage.getById('threads', record.id)).toBeNull();
+ expect((await storage.getRawRecords('threads'))[record.id]).toEqual(tombstone);
+ });
+ it('leaves stored records untouched on failed, malformed, and empty probes', async () => {
+ await sync();
+ const before = await storage.getRawRecords('threads');
+ for (const raw of [null, '{}', JSON.stringify([issue, { number: 99, state: 'OPEN' }]), '[]']) {
+ execGh.mockResolvedValue(raw);
+ if (raw === '[]') await expect(sync()).resolves.toMatchObject({ created: 0 });
+ else await expect(sync()).rejects.toMatchObject({ code: 'THREAD_SYNC_FAILED' });
+ expect(await storage.getRawRecords('threads')).toEqual(before);
+ }
+ execGh.mockRejectedValue(new Error('example transport failure'));
+ await expect(sync()).rejects.toMatchObject({ code: 'THREAD_SYNC_FAILED' });
+ ensureForgeReachable.mockResolvedValue({ ok: false });
+ await expect(sync()).rejects.toMatchObject({ code: 'THREAD_SYNC_FAILED' });
+ expect(await storage.getRawRecords('threads')).toEqual(before);
+ });
+ it('deduplicates runs, separates hosts, and does not create closed issues or restore detached refs', async () => {
+ expect((await sync()).created).toBe(1);
+ expect((await sync()).created).toBe(0);
+ const record = await currentRecord();
+ await storage.update('threads', record.id, { refs: [] });
+ execGh.mockResolvedValue(JSON.stringify([{ ...issue, state: 'CLOSED' }, { ...issue, number: 99, state: 'CLOSED' }]));
+ expect((await sync())).toMatchObject({ created: 0, updated: 1 });
+ expect((await storage.getById('threads', record.id)).refs).toEqual([]);
+ resolveAppForgeTarget.mockResolvedValue({ tracker: 'github', target: { forge: 'github', apiHost: 'github.com', fullName: `example/repo-${sequence}`, repoSpec: `github.com/example/repo-${sequence}` } });
+ execGh.mockResolvedValue(JSON.stringify([issue]));
+ expect((await sync()).created).toBe(1);
+ });
+ it('rejects unsupported apps before calling the forge', async () => {
+ getAppById.mockResolvedValue(null);
+ await expect(sync()).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ getAppById.mockResolvedValue({ repoPath: '/example/repo' });
+ resolveAppForgeTarget.mockResolvedValue({ tracker: 'jira', target: null });
+ await expect(sync()).rejects.toMatchObject({ code: 'UNSUPPORTED_TRACKER' });
+ expect(execGh).not.toHaveBeenCalled();
+ });
+ it('shares an in-flight request and releases the guard after a failure', async () => {
+ let finish;
+ execGh.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
+ const first = syncGithubThreads({ appId: 'example-app' });
+ expect(syncGithubThreads({ appId: 'example-app' })).toBe(first);
+ await vi.waitFor(() => expect(finish).toBeTypeOf('function'));
+ finish(null);
+ await expect(first).rejects.toMatchObject({ code: 'THREAD_SYNC_FAILED' });
+ execGh.mockResolvedValue('[]');
+ await expect(syncGithubThreads({ appId: 'example-app' })).resolves.toMatchObject({ created: 0 });
+ });
+});