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

fix: keep machine-local clone and intake fields out of synced Brain links (#12489)

[._.]/ Adam Eivy51063c3e9d29
diff --git a/server/lib/README.md b/server/lib/README.md
index 8c58a20727..fc0bc120e8 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -162,6 +162,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `storyBuilderValidation.js` | Unified Story Builder session/step schemas. |
| `telegramValidation.js` | Telegram bot config + test schemas. |
| `terminalReplay.js` | `stripTerminalQueries(text)` — remove response-soliciting terminal sequences (DSR `ESC[6n`, DA, DECRQM, DECRQSS, OSC colour queries) from the re-attach replay buffer a PTY session hands a newly attached client. A TUI emits `ESC[6n` on nearly every render and the 50KB ring buffer stores PTY output verbatim, so replaying it makes the attaching xterm ANSWER every historical query as input — landing cursor-position reports (`56;3R56;3R…`) on the shell prompt the dead TUI left behind, which then echo back into the same buffer and re-flood on every later attach. Applied on the way out, over the joined buffer, so a sequence split across two stored chunks still matches; live output is untouched because a running TUI must still get its replies. Stateful sequences the replay needs (mouse tracking, bracketed paste, alternate screen, SGR) are deliberately preserved — this is NOT `ansiStrip.js`, which removes every sequence to recover plain text. `createTerminalModeTracker()` — `observe(chunk)` follows the same stream’s DEC private modes (alternate screen, mouse tracking and encoding, bracketed paste, DECCKM, cursor visibility) and `preamble()` re-asserts the ones still in force, prepended to the replay: a TUI declares them ONCE at startup, so a session that overflows the 50KB window would otherwise replay as a normal-buffer, mouse-less terminal and become unscrollable. **`createReplayBuffer({ maxBytes })` is the export callers want** — the ring buffer that owns the bytes and applies both corrections to them (`push(chunk)` records and evicts, `render()` returns what an attaching client is handed); `services/shell.js` holds one per PTY session. The two helpers above are its internals, exported for their own direct tests — reach for the buffer rather than re-composing them by hand. |
+| `brainLinkLocalFields.js` | `BRAIN_LINK_MACHINE_LOCAL_FIELDS` / `stripLinkMachineLocalFields(record)` / `mergeIncomingLinkRecord(incoming, existing)` — the Brain link fields (`localPath`, clone state, `repoIntake`, scan/study state) that stay on the machine that wrote them: stripped from synced links, kept from the local copy when a peer record lands. |
| `brainThreads.js` | Brain THREAD rules (#7664) — the pure half of the bullet journal (a *thread* is a tracked open loop, never a message thread): `THREAD_STATUSES` / `THREAD_PRIORITIES` / `THREAD_TERMINAL_STATUSES` / `THREAD_ACTIVE_STATUSES`, `isTerminalThreadStatus`, `isThreadOverdue(thread, now)` (never true once finished), `threadNextLine` (the row's "Waiting on X" / next-action line) and the list comparator `compareThreads` (pinned, soonest-due, most recently touched, id — NaN-safe for two undated threads). `brainValidation.js` builds its enums from the arrays, `routes/brainThreads.js` sorts with the comparator, and `client/src/lib/brainThreads.js` re-exports the whole module so the tab, the widget and the server agree. |
| `humanActions.js` | Scheduled human action steps — the pure half: `humanActionPlanSchema` (a plan of dated steps with explicit `instructions`, ready-to-paste `content` and `links`), `humanActionThreadFields` (a step as the Brain thread it is stored as, tagged `human-action` + `plan:<key>`), `buildHumanActionNotes`, and `humanActionReminderDecision` (fire / arm / nothing for one thread, keyed on `remindedFor`). |
| `threadRefKinds.js` | Brain THREAD ref vocabulary + route table (#7664) — the one `(kind, id)` → label/URL registry in the repo. A *thread* is a tracked topic or commitment (an open loop), never a message thread. `THREAD_REF_KINDS` is the frozen row-per-kind table (brain records, catalog scraps/ingredients, the five app-native creative kinds, goals/apps/messages/CoS tasks, and the external GitHub/GitLab/JIRA/URL kinds); `threadRefUrl(kind, id, context)` builds the deep link and `threadRefLabel(kind)` the chip text, both degrading to `null`/the raw kind for a kind this build does not know so a peer-sourced ref never throws. `isSafeExternalUrl` scheme-guards an external id before it can become an href. Pure (no zod, no db, no services) and re-exported by `client/src/lib/threadRefKinds.js`, which is how `pages/CatalogIngredient.jsx` renders its inbound-ref chips through the same table. Existence/title lookups live in `services/threadRefs.js`; a drift guard fails CI when a kind here has no resolver there. |
diff --git a/server/lib/brainLinkLocalFields.js b/server/lib/brainLinkLocalFields.js
new file mode 100644
index 0000000000..3b7ec1c03c
--- /dev/null
+++ b/server/lib/brainLinkLocalFields.js
@@ -0,0 +1,39 @@
+/**
+ * Brain link fields that describe THIS machine's clone and the actions queued
+ * against it. They steer local execution (clone retry replays `repoIntake`,
+ * scan/pull/study/open-folder act on `localPath`), so a peer must never set them
+ * and they are never shipped to one: another machine's clone path is wrong here,
+ * and a peer-chosen `repoIntake` would run its instructions in a local agent.
+ */
+export const BRAIN_LINK_MACHINE_LOCAL_FIELDS = Object.freeze([
+ 'localPath',
+ 'cloneStatus',
+ 'cloneError',
+ 'cloneInstanceId',
+ 'cloneInterrupted',
+ 'malwareScan',
+ 'repoIntake',
+ 'repoStudy',
+]);
+
+/** Copy of a link record without its machine-local fields. Non-link/non-object input is returned unchanged. */
+export function stripLinkMachineLocalFields(record) {
+ if (!record || typeof record !== 'object' || Array.isArray(record)) return record;
+ const out = { ...record };
+ for (const field of BRAIN_LINK_MACHINE_LOCAL_FIELDS) delete out[field];
+ return out;
+}
+
+/**
+ * The record to store when a peer's link `incoming` lands over `existing`: every
+ * synced field from the peer, every machine-local field from this machine (or
+ * absent when this machine has no live copy).
+ */
+export function mergeIncomingLinkRecord(incoming, existing) {
+ const merged = stripLinkMachineLocalFields(incoming);
+ if (!existing || existing._deleted) return merged;
+ for (const field of BRAIN_LINK_MACHINE_LOCAL_FIELDS) {
+ if (field in existing) merged[field] = existing[field];
+ }
+ return merged;
+}
diff --git a/server/lib/index.js b/server/lib/index.js
index 1c355e49b4..2ef5b7a4c5 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -914,3 +914,4 @@ export * from './eventLoopLagProbe.js';
export * from './persistentMindAttachmentOwnership.js';
export * from './credentialEnvVars.js';
+export * from './brainLinkLocalFields.js';
diff --git a/server/routes/brainLinks.js b/server/routes/brainLinks.js
index 73baf1870e..4f208cb51f 100644
--- a/server/routes/brainLinks.js
+++ b/server/routes/brainLinks.js
@@ -39,7 +39,7 @@ async function requireClonedRepoLink(id) {
if (!link) {
throw new ServerError('Link not found', { status: 404, code: 'NOT_FOUND' });
}
- if (!link.isRepo || link.cloneStatus !== 'cloned' || !link.localPath) {
+ if (!link.isRepo || link.cloneStatus !== 'cloned' || !link.localPath || !repoCloner.isDerivedClonePath(link.url, link.localPath)) {
throw new ServerError('Link is not a cloned repository', { status: 400, code: 'NOT_CLONED' });
}
return link;
@@ -235,7 +235,7 @@ router.post('/links/:id/pull', asyncHandler(async (req, res) => {
throw new ServerError('Link not found', { status: 404, code: 'NOT_FOUND' });
}
- if (!link.isRepo || !link.localPath) {
+ if (!link.isRepo || !link.localPath || !repoCloner.isDerivedClonePath(link.url, link.localPath)) {
throw new ServerError('Link is not a cloned repository', {
status: 400,
code: 'NOT_CLONED'
@@ -256,7 +256,7 @@ router.post('/links/:id/open-folder', asyncHandler(async (req, res) => {
throw new ServerError('Link not found', { status: 404, code: 'NOT_FOUND' });
}
- if (!link.localPath) {
+ if (!link.localPath || !repoCloner.isDerivedClonePath(link.url, link.localPath)) {
throw new ServerError('Link has no local folder', {
status: 400,
code: 'NO_LOCAL_PATH'
diff --git a/server/routes/brainLinks.test.js b/server/routes/brainLinks.test.js
index d748607b52..285546fe5f 100644
--- a/server/routes/brainLinks.test.js
+++ b/server/routes/brainLinks.test.js
@@ -10,6 +10,8 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import express from 'express';
+import { join } from 'path';
+import { PATHS } from '../lib/fileUtils.js';
import { request } from '../lib/testHelper.js';
import { errorMiddleware } from '../lib/errorHandler.js';
@@ -32,9 +34,10 @@ vi.mock('../services/brain.js', () => ({
deleteBucketAndUnlinkChildren: vi.fn(),
}));
-vi.mock('../services/repoCloner.js', () => ({
- pullRepo: vi.fn(),
-}));
+vi.mock('../services/repoCloner.js', async () => {
+ const actual = await vi.importActual('../services/repoCloner.js');
+ return { isDerivedClonePath: actual.isDerivedClonePath, pullRepo: vi.fn() };
+});
vi.mock('../services/cos.js', () => ({ addTask: vi.fn() }));
@@ -217,7 +220,7 @@ describe('POST /api/brain/links/:id/study', () => {
url: 'https://gitlab.com/example-group/example-repo',
isRepo: true,
cloneStatus: 'cloned',
- localPath: '/repos/gitlab.com/example-group/example-repo',
+ localPath: join(PATHS.repos, 'gitlab.com', 'example-group', 'example-repo'),
});
beforeEach(() => {
@@ -247,6 +250,15 @@ describe('POST /api/brain/links/:id/study', () => {
expect(res.body).toMatchObject({ taskId: 'task-1', pulled: { ok: true } });
});
+ it('refuses a recorded localPath that is not the derived clone path for the link URL', async () => {
+ brainService.getLinkById.mockResolvedValue({ ...cloned(), localPath: '/srv/elsewhere/example-repo' });
+
+ const res = await request(app).post('/api/brain/links/repo-link/study').send({});
+
+ expect(res.status).toBe(400);
+ expect(restudyRepoLink).not.toHaveBeenCalled();
+ });
+
it('409s when a study for the repo is already in flight', async () => {
restudyRepoLink.mockResolvedValue({ queued: false, reason: 'duplicate' });
diff --git a/server/routes/hostControlBrainRepoIntake.test.js b/server/routes/hostControlBrainRepoIntake.test.js
index ca00ebcce1..152d5eb733 100644
--- a/server/routes/hostControlBrainRepoIntake.test.js
+++ b/server/routes/hostControlBrainRepoIntake.test.js
@@ -35,7 +35,8 @@ vi.mock('../services/instanceIdentity.js', () => ({
UNKNOWN_INSTANCE_ID: 'unknown',
}));
vi.mock('../services/userActions.js', () => ({ recordUserAction: vi.fn(async () => {}) }));
-vi.mock('../services/repoCloner.js', () => ({
+vi.mock('../services/repoCloner.js', async () => ({
+ isDerivedClonePath: (await vi.importActual('../services/repoCloner.js')).isDerivedClonePath,
cloneRepo: clone.cloneRepo,
pullRepo: vi.fn(),
reapStaleCloneStaging: vi.fn(async () => 0),
diff --git a/server/services/brainReconcile.js b/server/services/brainReconcile.js
index 69b41b346f..b5d2bcc648 100644
--- a/server/services/brainReconcile.js
+++ b/server/services/brainReconcile.js
@@ -29,6 +29,7 @@
*/
import { createHash } from 'crypto';
+import { stripLinkMachineLocalFields } from '../lib/brainLinkLocalFields.js';
import * as brainStorage from './brainStorage.js';
import { brainEvents } from './brainStorage.js';
import * as brainSyncLog from './brainSyncLog.js';
@@ -70,7 +71,9 @@ async function buildRawMap() {
const records = await brainStorage.getRawRecords(type);
const sorted = {};
for (const id of Object.keys(records).sort()) {
- sorted[id] = records[id];
+ // Machine-local link fields are neither shipped nor hashed: each install
+ // holds its own values, so hashing them would never converge.
+ sorted[id] = type === 'links' ? stripLinkMachineLocalFields(records[id]) : records[id];
}
map[type] = sorted;
}
diff --git a/server/services/brainReconcile.test.js b/server/services/brainReconcile.test.js
index caead089aa..e7ee27db05 100644
--- a/server/services/brainReconcile.test.js
+++ b/server/services/brainReconcile.test.js
@@ -33,6 +33,25 @@ beforeEach(() => {
brainEvents.emit('record:changed', { type: 'people', id: 'test-reset' });
});
+describe('machine-local link fields', () => {
+ const synced = { id: 'a', updatedAt: '2026-01-01T00:00:00.000Z', title: 'A', url: 'https://github.com/o/r' };
+ const withLocal = (extra) => ({ links: { a: { ...synced, ...extra } } });
+
+ it('are neither hashed nor shipped in the snapshot', async () => {
+ emptyStores(withLocal({}));
+ const bare = await getBrainChecksum();
+
+ brainEvents.emit('record:changed', { type: 'links', id: 'a' });
+ emptyStores(withLocal({
+ localPath: '/srv/x', cloneStatus: 'cloned', repoIntake: { learn: true, studyContext: 'do X' }, malwareScan: { reportId: 'r' },
+ }));
+ const snapshot = await getBrainSnapshot();
+
+ expect(snapshot.checksum).toBe(bare);
+ expect(snapshot.records.links.a).toEqual(synced);
+ });
+});
+
describe('brainReconcile checksum', () => {
it('reuses the cached checksum when no brain records changed', async () => {
emptyStores({ links: { a: { id: 'a', updatedAt: '2026-01-01T00:00:00.000Z', title: 'A' } } });
diff --git a/server/services/brainStorage.js b/server/services/brainStorage.js
index ba143fd5fe..6e5b89068e 100644
--- a/server/services/brainStorage.js
+++ b/server/services/brainStorage.js
@@ -44,6 +44,7 @@ import { createCollectionStore } from '../lib/collectionStore.js';
import { linkIsRepo, normalizeRepoLinkFields } from '../lib/repoLinkFields.js';
import { supersedingTimestamp } from '../lib/tombstones.js';
import { parseTsMs, compareNewerWins } from '../lib/lwwTimestamp.js';
+import { mergeIncomingLinkRecord } from '../lib/brainLinkLocalFields.js';
const DATA_DIR = PATHS.brain;
@@ -1420,7 +1421,7 @@ export async function applyRemoteRecord(type, id, record, op) {
// tombstone, never as a malformed live record missing `deletedAt`.
await store.saveOneNow(id, record._deleted
? makeTombstone(record.updatedAt, record.originInstanceId ?? existing?.originInstanceId)
- : { ...record });
+ : (type === 'links' ? mergeIncomingLinkRecord(record, existing) : { ...record }));
}
// Still no per-record event (that would echo back to the peer, #1077) —
diff --git a/server/services/brainStorage.test.js b/server/services/brainStorage.test.js
index 0f1deff9ab..6203d3c1e2 100644
--- a/server/services/brainStorage.test.js
+++ b/server/services/brainStorage.test.js
@@ -1232,3 +1232,54 @@ it('keeps latest-ten defaults while allowing complete JSONL catch-up', async ()
expect((await brainStorage.getDigests(Infinity)).at(-1).id).toBe('digest-0');
expect((await brainStorage.getReviews(Infinity)).at(-1).id).toBe('digest-0');
});
+
+describe('machine-local link fields (peer records)', () => {
+ const peerLink = (extra = {}) => ({
+ url: 'https://github.com/example-org/example-repo',
+ title: 'example-org/example-repo',
+ isRepo: true,
+ updatedAt: ISO('2026-06-10T00:00:00Z'),
+ originInstanceId: 'peer-x',
+ ...extra,
+ });
+ const hostile = {
+ localPath: '/peer/chosen/dir',
+ cloneStatus: 'cloned',
+ cloneInstanceId: 'peer-x',
+ repoIntake: { learn: true, studyContext: 'peer instructions', providerId: 'p', targetAppId: 'a' },
+ malwareScan: { reportId: '11111111-1111-4111-8111-111111111111' },
+ repoStudy: { taskId: 't' },
+ };
+
+ it('a new peer link lands without them', async () => {
+ await brainStorage.applyRemoteRecord('links', 'peer-link-new', peerLink(hostile), 'create');
+ brainStorage.invalidateAllCaches();
+ const stored = await brainStorage.getById('links', 'peer-link-new');
+ expect(stored).toMatchObject({ title: 'example-org/example-repo' });
+ for (const field of Object.keys(hostile)) expect(stored).not.toHaveProperty(field);
+ });
+
+ it('a newer peer record updates synced fields but keeps this machine\'s local values', async () => {
+ await brainStorage.upsertWithId('links', 'peer-link-upd', {
+ ...peerLink({ updatedAt: ISO('2026-06-09T00:00:00Z') }),
+ localPath: '/local/clone', cloneStatus: 'cloned', repoIntake: { malwareScan: true },
+ });
+ const res = await brainStorage.applyRemoteRecord(
+ 'links', 'peer-link-upd', peerLink({ title: 'renamed', updatedAt: ISO('2099-01-01T00:00:00Z'), ...hostile }), 'update',
+ );
+ expect(res.applied).toBe(true);
+ brainStorage.invalidateAllCaches();
+ expect(await brainStorage.getById('links', 'peer-link-upd')).toMatchObject({
+ title: 'renamed', localPath: '/local/clone', cloneStatus: 'cloned', repoIntake: { malwareScan: true },
+ });
+ });
+
+ it('never ships them: delta log reads strip legacy entries that carry them', async () => {
+ const before = brainSyncLog.getCurrentSeq();
+ await brainSyncLog.appendChange('create', 'links', 'peer-link-log', peerLink(hostile), 'peer-x');
+ const { changes } = await brainSyncLog.getChangesSince(before, 10);
+ const entry = changes.find((c) => c.id === 'peer-link-log');
+ expect(entry.record.title).toBe('example-org/example-repo');
+ for (const field of Object.keys(hostile)) expect(entry.record).not.toHaveProperty(field);
+ });
+});
diff --git a/server/services/brainSyncLog.js b/server/services/brainSyncLog.js
index 47ab26e31e..033433a757 100644
--- a/server/services/brainSyncLog.js
+++ b/server/services/brainSyncLog.js
@@ -16,6 +16,7 @@ import { join } from 'path';
import { createMutex } from '../lib/asyncMutex.js';
import { appendFileGuarded, ensureDir, safeJSONParse, PATHS, atomicWrite } from '../lib/fileUtils.js';
import { compareNewerWins } from '../lib/lwwTimestamp.js';
+import { stripLinkMachineLocalFields } from '../lib/brainLinkLocalFields.js';
const DATA_DIR = PATHS.brain;
const SYNC_LOG_FILE = join(DATA_DIR, 'sync_log.jsonl');
@@ -345,7 +346,11 @@ export async function getChangesSince(sinceSeq, limit = 100) {
// A line without a numeric seq is unsequenceable — shipping it would set
// the peer's cursor to undefined on the next maxSeq.
if (typeof entry?.seq !== 'number' || entry.seq <= sinceSeq) continue;
- changes.push(entry);
+ // Read-time, so entries logged before links had machine-local fields
+ // (or relayed verbatim from an older peer) never carry them out either.
+ changes.push(entry.type === 'links' && entry.record
+ ? { ...entry, record: stripLinkMachineLocalFields(entry.record) }
+ : entry);
if (changes.length >= limit) break;
}
diff --git a/server/services/repoCloner.js b/server/services/repoCloner.js
index f236c63f75..e2d2aeb363 100644
--- a/server/services/repoCloner.js
+++ b/server/services/repoCloner.js
@@ -9,7 +9,7 @@
import { spawn } from '../lib/childProcess.js';
import { existsSync } from 'fs';
import { access, mkdtemp, readdir, rename, rm } from 'fs/promises';
-import { dirname, join } from 'path';
+import { dirname, join, resolve } from 'path';
import { ensureDir, PATHS } from '../lib/fileUtils.js';
import { MAX_REPO_PATH_DEPTH, REPO_HOSTS, parseRepoUrl, repoCloneUrl } from '../lib/repoUrl.js';
@@ -41,6 +41,18 @@ export function getCloneDir(customDir) {
return customDir || DEFAULT_CLONE_DIR;
}
+/**
+ * True when `localPath` is exactly where cloneRepo puts `url`. Every action
+ * that reads or pulls a recorded clone checks this first: the recorded path is
+ * stored data, so it is only trusted when it equals the path derived from the
+ * link's own URL under the clone directory.
+ */
+export function isDerivedClonePath(url, localPath, customDir) {
+ const parsed = parseRepoUrl(url);
+ if (!parsed || typeof localPath !== 'string' || !localPath) return false;
+ return resolve(localPath) === resolve(join(getCloneDir(customDir), repoSubPath(parsed)));
+}
+
/**
* Ensure clone directory exists
*/
diff --git a/server/services/repoCloner.test.js b/server/services/repoCloner.test.js
index 68a7241775..7d44ca488d 100644
--- a/server/services/repoCloner.test.js
+++ b/server/services/repoCloner.test.js
@@ -19,7 +19,7 @@ vi.mock('../lib/fileUtils.js', () => ({
import { existsSync } from 'fs';
import { access, mkdtemp, readdir, rename, rm } from 'fs/promises';
import { spawn } from '../lib/childProcess.js';
-import { cloneRepo, reapStaleCloneStaging, pullRepo } from './repoCloner.js';
+import { cloneRepo, isDerivedClonePath, reapStaleCloneStaging, pullRepo, getCloneDir } from './repoCloner.js';
const REPOS_DIR = '/repos';
const OWNER_DIR = join(REPOS_DIR, 'acme');
@@ -293,6 +293,20 @@ describe('cloneRepo across hosts', () => {
});
});
+describe('isDerivedClonePath', () => {
+ const root = getCloneDir();
+
+ it('accepts only the path cloneRepo derives for the URL, on flat and namespaced hosts', () => {
+ expect(isDerivedClonePath('https://github.com/acme/widgets', join(root, 'acme', 'widgets'))).toBe(true);
+ expect(isDerivedClonePath('https://gitlab.com/acme/widgets', join(root, 'gitlab.com', 'acme', 'widgets'))).toBe(true);
+ expect(isDerivedClonePath('https://github.com/acme/widgets', join(root, 'acme', 'other'))).toBe(false);
+ expect(isDerivedClonePath('https://github.com/acme/widgets', join(root, 'acme', 'widgets', '..', '..', '..'))).toBe(false);
+ expect(isDerivedClonePath('https://github.com/acme/widgets', '/etc')).toBe(false);
+ expect(isDerivedClonePath('https://example.com/not-a-repo', join(root, 'acme', 'widgets'))).toBe(false);
+ expect(isDerivedClonePath('https://github.com/acme/widgets', null)).toBe(false);
+ });
+});
+
describe('pullRepo', () => {
const localPath = '/local/repo';
diff --git a/server/services/repoIntake.js b/server/services/repoIntake.js
index 3b5a4e83e8..46a1167c48 100644
--- a/server/services/repoIntake.js
+++ b/server/services/repoIntake.js
@@ -29,15 +29,18 @@ import { prepareScanReportDirectory, reportPathForId } from './malwareScanReport
import { resolveTrackerFilingBlock } from '../lib/workTracker.js';
import { GENERIC_REPO_STUDY_LABEL_CONTRACT } from '../lib/dispatchLabels.js';
import { normalizeRepoIntake } from '../lib/repoIntakeActions.js';
-import { pullRepo } from './repoCloner.js';
+import { isDerivedClonePath, pullRepo } from './repoCloner.js';
import { repoLinkLabel as repoLabel } from '../lib/repoLinkFields.js';
/**
* True when the link's recorded clone is readable on disk. Both actions read the
* clone, so neither may queue an agent against a path that was never written or
- * has since been deleted.
+ * has since been deleted. The path must also be the one PortOS derives for the
+ * link's URL, so a `localPath` that did not come from this machine's own clone
+ * (e.g. a synced record) never points an agent at an arbitrary directory.
*/
-const isCloneReadable = (link) => Boolean(link?.localPath) && existsSync(link.localPath);
+const isCloneReadable = (link) =>
+ Boolean(link?.localPath) && isDerivedClonePath(link.url, link.localPath) && existsSync(link.localPath);
/**
* Queue the read-only `/do:scan` malware audit against a cloned link.
diff --git a/server/services/repoIntake.test.js b/server/services/repoIntake.test.js
index 8f34e0124b..2a8ef2de43 100644
--- a/server/services/repoIntake.test.js
+++ b/server/services/repoIntake.test.js
@@ -1,4 +1,6 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { join } from 'path';
+import { PATHS } from '../lib/fileUtils.js';
const addTask = vi.fn();
const getAppById = vi.fn();
@@ -16,7 +18,10 @@ vi.mock('./malwareScanReports.js', () => ({
reportPathForId: (id) => `/scans/${id}.md`,
}));
vi.mock('fs', () => ({ existsSync: (...args) => existsSync(...args) }));
-vi.mock('./repoCloner.js', () => ({ pullRepo: (...args) => pullRepo(...args) }));
+vi.mock('./repoCloner.js', async () => ({
+ isDerivedClonePath: (await vi.importActual('./repoCloner.js')).isDerivedClonePath,
+ pullRepo: (...args) => pullRepo(...args),
+}));
// The REAL workTracker resolution runs — the tracker instructions in the prompt
// are what these tests assert. Only its one shell-out is stubbed; the tracker is
// steered through the app's own `workTracker` setting, as a user would.
@@ -32,7 +37,7 @@ const LINK = {
title: 'example-owner/example-repo',
repoOwner: 'example-owner',
repoName: 'example-repo',
- localPath: '/repos/example-owner/example-repo',
+ localPath: join(PATHS.repos, 'example-owner', 'example-repo'),
};
const APP = { id: 'portos-default', name: 'PortOS', repoPath: '/srv/portos', workTracker: 'github' };
@@ -141,6 +146,17 @@ describe('queueRepoStudy', () => {
expect(addTask.mock.calls[1][0].context).toMatch(/keeps no single feature inventory; build one/);
});
+ it('refuses a clone path that is not the derived path for the link URL (scan and study)', async () => {
+ existsSync.mockReturnValue(true);
+ const foreign = { ...LINK, localPath: '/srv/elsewhere/example-repo' };
+
+ expect(await queueMalwareScan(foreign)).toEqual({ queued: false, reason: 'not-cloned' });
+ expect(await queueRepoStudy(foreign)).toEqual({ queued: false, reason: 'not-cloned' });
+ expect(await restudyRepoLink(foreign)).toEqual({ queued: false, reason: 'not-cloned' });
+ expect(addTask).not.toHaveBeenCalled();
+ expect(pullRepo).not.toHaveBeenCalled();
+ });
+
it('does not masquerade as a scheduled task type', async () => {
await queueRepoStudy(LINK);
expect(addTask.mock.calls[0][0].analysisType).toBeUndefined();