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

detect GitHub repos in Brain capture and offer post-clone scan/study agents

[._.]/ Adam Eivy3ad24d032a68
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index a0be3b4d4d..aef9f90880 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -16,6 +16,7 @@
- **Cursor's agent CLI ships as a provider, in both CLI and TUI flavors.** `cursor-agent` is a harness-capable coding agent, but PortOS had no entry for it — using it meant hand-rolling a custom provider and guessing at its flags. It now ships as `cursor-cli` (headless one-shot) and `cursor-tui` (interactive PTY), mirroring the Codex/Antigravity/Grok/Kimi pairs. Both ship disabled, so nothing changes until you enable them, and once enabled they're selectable anywhere a process provider is — CoS agents, runners, pipeline stages, TUI sessions. The headless path runs `cursor-agent --print` with the prompt on stdin; the TUI path runs the interactive agent. Both inject `--force`, which is doing more work than the name suggests: besides auto-approving tool calls, it clears Cursor's workspace-trust gate, and without it `cursor-agent` prints "Workspace Trust Required" and exits — which in a fresh CoS worktree is every single run. The model list is a 27-entry slice of the account catalog (Composer, Claude, GPT, Gemini families), each id verified against the live binary; the default is Cursor's own `auto` router, so unlike Grok/Kimi/Antigravity no configured-default sentinel was needed. Cursor bakes reasoning effort into the model id (`…-thinking-high`, `…-xhigh`, `…-max`) rather than exposing a flag, so no Effort control is offered for it. Existing installs pick the pair up on restart via migration `231-cursor-providers`. If your account offers a model outside the shipped 27 (the full catalog runs to 177 ids, most of them `-fast` twins), "Refresh Models" pulls the whole list from the binary — see above.
- **X account diagnostics and review-gated compose handoffs.** Comms now has an X page that stores bounded public snapshots, checks profile/search visibility and post reach through the managed browser, captures visible metrics, and routes drafts through Review Hub before opening X for a final manual submission. It does not store X credentials, post automatically, or claim that ordinary low reach proves a shadowban.
+- **Pasting a GitHub repo into Brain capture can now hand it to an agent.** A bare repo URL captured in the Brain has always been saved as a link and cloned in the background, but nothing said so and nothing followed. Both capture boxes (the Quick Capture dashboard widget and the Brain → Inbox form) now recognize a repo URL, name the `owner/repo` that will be cloned, and offer two opt-in checkboxes: **Scan for malware** runs the same read-only static audit as the Links tab's Scan button, ending in a CLEAN / CAUTION / DANGEROUS report you open from the link; **Study for PortOS ideas** queues an agent that reads the clone for implementation ideas worth adopting and files the good ones as issues (or PLAN.md items, whichever tracker this install is configured for). Both preferences stick, so "always scan what I clone" is a one-time tick. The agents only start once the clone actually lands — a failed clone queues nothing — and the study run is clean-room by contract: it never executes anything from the clone, never edits it, reads its LICENSE before proposing anything, and describes techniques in its own words rather than copying code. Re-pasting a repo you already saved re-queues nothing, since there's no new clone to read.
- **Stacker News triage is newest-first and action-oriented.** Each community sync is capped to a configurable newest-item count (30 by default), preserves source timestamps for stable ordering, captures direct image posts for Ollama vision analysis, and gives every newest item explicit reply, zap-handoff, moderation-handoff, and analysis actions behind the existing human review gate.
- **The claim-issue author gate has a "Me + collaborators" setting.** Until now the only way to let an agent work on a teammate's issue was "Any author", which also opens the queue to drive-by issues from strangers — so a repo with any real collaborators had to choose between ignoring their issues and claiming everyone's. The new option trusts you plus every account the forge already grants access to (GitHub collaborators, GitLab project members including group-inherited ones), which is the same set that could push the code anyway. It sits between "Filed by me only" (still the default) and "Any author" in the CoS → Schedule author-filter dropdown, in the per-app override, and in the `/do:next` run drawer, and applies to `claim-issue` and `claim-work` alike. Neither CLI's `--author` flag accepts more than one account, so the gate is applied to the issue listing rather than pushed into the query — both the work detector and the agent prompt resolve the trusted set first, then filter. If that lookup fails (a token without push access can't read the collaborator list), PortOS reports it and retries rather than quietly narrowing back to your own issues or widening to everybody — and because that failure repeats identically on every retry, both the run drawer and the "Run now" toast name the filter and the way out instead of the generic "try again shortly".
@@ -35,9 +36,11 @@
- **Grok and Kimi agents now actually start, and an agent that fails to spawn says why.** Picking the Grok or Kimi provider for a CoS agent produced a task that never opened a shell: the durable agent runner keeps an allowlist of CLI commands it is permitted to spawn, and `grok` and `kimi` were never added to it even though both ship as selectable providers. Both are allowlisted now, and a test keeps that list in step with the shipped provider catalog so the next provider added without an entry fails in CI rather than in a silent agent. The reporting around it was the worse half of the bug: a rejected spawn was logged and dropped, never reaching the agent record. A TUI agent sat in "initializing" for a minute until the zombie sweeper finalized it as "Agent process terminated unexpectedly" — a message that named no cause — and the CLI equivalent was worse still, staying "working" indefinitely because the stale in-memory entry made every cleanup sweep skip it. Both paths now finalize immediately with the runner's actual error, the runner names the offending command instead of returning one opaque "missing or invalid fields", and an agent reaped without ever having recorded a process id is reported as never having started rather than as a crash.
- **The labels on LoRA training dataset images are readable again.** The source chip ("upload", "generated", "sheet crop", "gallery") and the view label ("front three-quarter") were tinted overlays — 20%-opacity color on top of whatever the training image happened to be — so over a bright photo, or under a light theme, the text all but disappeared. They were also pinned to opposite corners of the thumbnail, so a long view label collided with the source chip in a narrow column and the two printed on top of each other. Both chips now carry their own near-opaque plate with light text, and they share one wrapping row so a long label drops to a second line instead of overlapping.
- **The Antigravity code reviewer no longer looks like it isn't installed.** Antigravity's command is `agy`, but every agent prompt named the reviewer by its internal slug, `antigravity` — a command that exists on no machine. A review-loop agent went looking for it, found nothing, concluded there was no reviewer available, reviewed its own work instead, and merged the PR. Prompts now name the actual command, and a reviewer whose command genuinely isn't installed blocks the merge with a note on the PR instead of quietly being replaced by a self-review.
+- **A queued malware scan is now visible on the link that's being scanned.** Clicking Scan in Brain → Links queued the run and toasted, but recorded nothing on the link — so a reload showed no sign of it and the button re-armed, with the second click rejected as a duplicate. A pending scan now shows a "Scan queued" chip, and the "Scan Reports" filter no longer lists links whose report the agent hasn't written yet (clicking through went to a 404).
- **Pull requests opened by a CoS agent under a "merge when CI is green" policy now actually get merged.** The check that watches those PRs only ran when an app's optional "PR Watcher" scheduled task fired — and that task ships disabled, since its default prompt is a review-and-comment agent most setups don't want. So PortOS was queueing green PRs into a list nothing ever read: they sat open indefinitely, and because the retry counter never advanced, the safety net that gives up and notifies you after a few hours never fired either. The watch now runs on the normal CoS cadence, independent of that task.
## Internal
+- **A one-off "read the code and file what you find" agent run no longer has to impersonate a scheduled task type.** PortOS exempts tracker-filing runs from the "did it leave a commit?" success check, because a run that files GitHub issues legitimately leaves the tree clean — but the exemption was keyed on the task carrying a *scheduled* type name. The only way for a hand-queued run to qualify was to claim one, which would also enroll it in the scheduler's per-type consecutive-failure ledger and eventually auto-park (and notify about) a "type" no schedule owns. The gate now also accepts the tracker marker the dispatch already stamps, which one-off runs carry honestly. Alongside it, the four-part "resolve the tracker, render its filing instructions, and derive the two metadata flags from that same answer" step — previously a third hand-copy in each new caller — moved into `lib/workTracker.js` next to the wording table it reads.
- **[issue-3618] Adding a coding-agent provider is now one table row instead of eight coordinated edits.** Teaching PortOS about a new vendor's CLI/TUI meant editing open-coded dispatch branches across five files — argv builders, prompt-delivery rules, TUI posture flags, the command allowlist — and two of those sites (the TUI model-injection paths) had already drifted apart once before being collapsed into a shared helper. A `PROVIDER_VENDORS` registry now holds one row per vendor (claude, codex, antigravity, opencode, grok, kimi, cursor), and every one of those dispatch points reads from it instead of hand-rolling its own if-chain. No vendor's argv-building logic changed — this only relocates dispatch, verified against the full existing test suite plus a byte-for-byte check that the derived command allowlist still matches the prior hand-maintained list exactly.
- **The six provider-seed migrations share one shell instead of six copies of it.** Every migration that ships a new AI provider to already-installed setups (OpenCode Ollama, its TUI sibling, Grok, Cerebras, Kimi, Cursor) repeated the same byte-identical read → validate → add-missing-ids → write body, so any hardening of it was a six-file sweep nobody did — and none of the six had picked up the reserved-key guard (`__proto__` / `constructor` / `prototype`) the split-migration family already applies. They now call a shared `makeProviderSeedMigration` factory that carries that guard, and each migration keeps only its own frozen provider payload, since a migration is the historical record of what it installed. Their duplicated shell tests collapse into one suite against the factory; every payload assertion each migration already made still runs unchanged.
- **Whether a provider can refresh its model list is now the server's answer, not the client's guess.** The "Refresh Models" button used to be gated by a hand-written client-side re-derivation of the server's model-refresh dispatch — a mirror kept in step by a comment, backed by a parity test that transcribed the same dispatch a *second* time (so it only ever proved the mirror matched the test's copy). It drifted, silently, in both directions: too generous showed a button that errored on every click, too stingy hid the feature with no error at all. A gemini provider configured by absolute path was in the second bucket. The server now derives the answer from one per-vendor table and sends it on the providers payload as `canRefreshModels`; the client just reads it. The three keying conventions that had accumulated as prose above each branch (exact command string, path-tolerant command basename, display-name substring — and which of them a TUI provider is allowed to use) are columns in that table now, so adding the next vendor is one row instead of four coordinated edits across two repos' worth of files. The field is computed per response and never stored, so it can't go stale against the dispatch it describes. No shipped provider's button visibility changes; the one behavior that does is that a provider whose *command* is literally `gemini` now refreshes as gemini even if someone named it "Claude Something", which is the same "an exact command beats a display-name substring" rule the dispatch had already grown for cursor and Antigravity.
diff --git a/client/src/components/QuickBrainCapture.jsx b/client/src/components/QuickBrainCapture.jsx
index 3437d44b54..75fd7a3a53 100644
--- a/client/src/components/QuickBrainCapture.jsx
+++ b/client/src/components/QuickBrainCapture.jsx
@@ -3,9 +3,11 @@ import { Link } from 'react-router';
import { ChevronDown, Film, Send, Sliders, Sparkles, X } from 'lucide-react';
import toast from './ui/Toast';
import * as api from '../services/api';
-import { useLocalStorageBool, useYoutubeIngest } from '../hooks';
+import { useLocalStorageBool, useRepoIntake, useYoutubeIngest } from '../hooks';
import { parseBareUrl } from '../lib/bareUrl';
import { INGEST_OPTIONS, defaultIngestOptions, ingestOptionsFromSettings, isYoutubeVideoUrl } from '../lib/youtubeUrl';
+import RepoIntakeOptions from './brain/RepoIntakeOptions';
+import ToggleChip from './ui/ToggleChip';
export default function QuickBrainCapture() {
const [input, setInput] = useState('');
@@ -21,6 +23,9 @@ export default function QuickBrainCapture() {
// A single-video YouTube URL takes a different path entirely (ingest, not
// capture) and unlocks the advanced panel below.
const isYoutube = useMemo(() => isYoutubeVideoUrl(input), [input]);
+ // A bare GitHub repo URL is cloned on capture, which unlocks the two post-clone
+ // agent opt-ins (malware scan / repo study).
+ const repoIntake = useRepoIntake(input);
const [showAdvanced, setShowAdvanced] = useState(false);
const [ingestOpts, setIngestOpts] = useState(defaultIngestOptions);
@@ -87,7 +92,12 @@ export default function QuickBrainCapture() {
// erroring), so this surface doesn't need its own link-vs-thought branch.
// It ignores the sticky Creative flag for a URL; dropping it here too keeps
// the request honest about what will be stored.
- const result = await api.captureBrainThought(text, undefined, undefined, { creative: creative && !isUrl }, { silent: true }).catch(err => {
+ // `intakeFor` re-derives from the submitted text, so a sticky tick can't ride
+ // along on a capture that is no longer a repo URL.
+ const result = await api.captureBrainThought(text, undefined, undefined, {
+ creative: creative && !isUrl,
+ repoIntake: repoIntake.intakeFor(text),
+ }, { silent: true }).catch(err => {
toast.error(err.message || 'Failed to capture');
setInput(prev => prev || text);
return null;
@@ -162,23 +172,14 @@ export default function QuickBrainCapture() {
<div id="quick-brain-advanced" className="mt-3 pt-3 border-t border-port-border space-y-3">
<div className="flex flex-wrap gap-2">
{INGEST_OPTIONS.map(({ key, label, hint }) => (
- <label
+ <ToggleChip
key={key}
- htmlFor={`quick-brain-${key}`}
- title={hint}
- className={`flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg border text-xs cursor-pointer transition-colors ${ingestOpts[key]
- ? 'bg-port-accent/20 text-port-accent border-port-accent/40'
- : 'bg-port-bg text-gray-400 border-port-border hover:text-gray-200'}`}
- >
- <input
- id={`quick-brain-${key}`}
- type="checkbox"
- checked={ingestOpts[key]}
- onChange={() => toggleOption(key)}
- className="accent-port-accent"
- />
- {label}
- </label>
+ id={`quick-brain-${key}`}
+ label={label}
+ hint={hint}
+ checked={ingestOpts[key]}
+ onToggle={() => toggleOption(key)}
+ />
))}
</div>
@@ -212,6 +213,13 @@ export default function QuickBrainCapture() {
</div>
)}
+ <RepoIntakeOptions
+ idPrefix="quick-brain-repo"
+ repo={repoIntake.repo}
+ options={repoIntake.options}
+ onToggle={repoIntake.toggle}
+ />
+
{ingest.active && (
<div className="mt-3 flex items-center gap-2 text-xs text-gray-400">
<Film size={14} className="text-red-400 shrink-0" />
@@ -241,7 +249,7 @@ export default function QuickBrainCapture() {
Will ingest {INGEST_OPTIONS.filter(o => ingestOpts[o.key]).map(o => o.label.toLowerCase()).join(' + ') || 'nothing — pick an option'}
<ChevronDown size={12} className={showAdvanced ? 'rotate-180 transition-transform' : 'transition-transform'} />
</button>
- ) : isUrl ? 'Will save as link' : creative ? 'Will capture as a creative thought' : 'Will capture as thought'}
+ ) : repoIntake.repo ? 'Will save as link and clone the repo' : isUrl ? 'Will save as link' : creative ? 'Will capture as a creative thought' : 'Will capture as thought'}
</p>
)}
</div>
diff --git a/client/src/components/QuickBrainCapture.test.jsx b/client/src/components/QuickBrainCapture.test.jsx
index b0905bea84..3b0dd40e90 100644
--- a/client/src/components/QuickBrainCapture.test.jsx
+++ b/client/src/components/QuickBrainCapture.test.jsx
@@ -102,6 +102,70 @@ describe('QuickBrainCapture', () => {
expect(screen.getByText('Will capture as thought')).toBeInTheDocument();
});
+ describe('GitHub repo intake', () => {
+ const REPO = 'https://github.com/example-owner/example-repo';
+
+ it('offers the post-clone agent options only for a bare repo URL', () => {
+ renderWidget();
+ type('https://example.com/article');
+ expect(screen.queryByLabelText('Scan for malware')).toBeNull();
+
+ type(REPO);
+ expect(screen.getByLabelText('Scan for malware')).toBeInTheDocument();
+ expect(screen.getByLabelText('Study for PortOS ideas')).toBeInTheDocument();
+ expect(screen.getByText(/will be cloned locally/)).toBeInTheDocument();
+ expect(screen.getByText('Will save as link and clone the repo')).toBeInTheDocument();
+ });
+
+ // The server files this as a thought (parseBareUrl rejects prose), so no
+ // clone happens and the options would be a lie.
+ it('hides the options for a repo URL wrapped in prose', () => {
+ renderWidget();
+ type(`worth reading ${REPO}`);
+ expect(screen.queryByLabelText('Scan for malware')).toBeNull();
+ });
+
+ it('hides the options for a non-repo github.com URL', () => {
+ renderWidget();
+ type('https://github.com/settings');
+ expect(screen.queryByLabelText('Scan for malware')).toBeNull();
+ });
+
+ it('sends the ticked actions with the capture', async () => {
+ renderWidget();
+ type(REPO);
+ fireEvent.click(screen.getByLabelText('Study for PortOS ideas'));
+ fireEvent.click(screen.getByLabelText('Capture'));
+
+ await waitFor(() => expect(captureBrainThought).toHaveBeenCalled());
+ expect(captureBrainThought.mock.calls[0][3].repoIntake).toEqual({ malwareScan: false, learn: true });
+ });
+
+ it('remembers the choice across mounts', () => {
+ const { unmount } = renderWidget();
+ type(REPO);
+ fireEvent.click(screen.getByLabelText('Scan for malware'));
+ expect(screen.getByLabelText('Scan for malware').checked).toBe(true);
+ unmount();
+
+ renderWidget();
+ type(REPO);
+ expect(screen.getByLabelText('Scan for malware').checked).toBe(true);
+ });
+
+ // A sticky tick must not ride along on a capture the user retyped into
+ // something the server will never clone.
+ it('omits the intake when the text is no longer a repo URL at submit time', async () => {
+ localStorage.setItem('brain.repoIntake.malwareScan', 'true');
+ renderWidget();
+ type(REPO);
+ submit('call mom');
+
+ await waitFor(() => expect(captureBrainThought).toHaveBeenCalled());
+ expect(captureBrainThought.mock.calls[0][3].repoIntake).toBeUndefined();
+ });
+ });
+
describe('YouTube ingest path', () => {
it('offers ingest options only for a single-video YouTube URL', async () => {
renderWidget();
diff --git a/client/src/components/brain/RepoIntakeOptions.jsx b/client/src/components/brain/RepoIntakeOptions.jsx
new file mode 100644
index 0000000000..efeeb2cccb
--- /dev/null
+++ b/client/src/components/brain/RepoIntakeOptions.jsx
@@ -0,0 +1,68 @@
+import { GitBranch, ShieldCheck, Lightbulb } from 'lucide-react';
+import ToggleChip from '../ui/ToggleChip';
+
+/**
+ * The "this URL is a GitHub repo" affordance shared by both Brain capture boxes
+ * (the Quick Capture dashboard widget and the Inbox capture form).
+ *
+ * Presentational only — the sticky checkbox state and the repo-URL rule live in
+ * `hooks/useRepoIntake.js`, whose `repo` this renders. The keys must stay in
+ * step with the server's `REPO_INTAKE_KEYS`; parity is pinned by
+ * `server/lib/repoIntakeActions.mirror.test.js`.
+ */
+export const REPO_INTAKE_OPTIONS = [
+ {
+ key: 'malwareScan',
+ label: 'Scan for malware',
+ Icon: ShieldCheck,
+ hint: 'Read-only static audit of the clone. Produces a CLEAN / CAUTION / DANGEROUS report you can open from the link.',
+ },
+ {
+ key: 'learn',
+ label: 'Study for PortOS ideas',
+ Icon: Lightbulb,
+ hint: 'An agent reads the clone for implementation ideas worth adopting and files the good ones as issues. Clean-room — it never copies code.',
+ },
+];
+
+/**
+ * @param {object} props
+ * @param {string} props.idPrefix unique per host form — the checkbox ids/labels
+ * must not collide when both capture boxes are mounted on the same page.
+ * @param {{owner: string, repo: string}|null} props.repo parsed repo, or null to
+ * render nothing (the capture isn't a bare repo URL)
+ * @param {{malwareScan: boolean, learn: boolean}} props.options
+ * @param {(key: string) => void} props.onToggle
+ */
+export default function RepoIntakeOptions({ idPrefix, repo, options, onToggle }) {
+ if (!repo) return null;
+
+ return (
+ <div className="mt-3 pt-3 border-t border-port-border space-y-2">
+ <p className="flex items-center gap-1.5 text-xs text-gray-400">
+ <GitBranch size={12} className="text-port-accent shrink-0" />
+ <span>
+ <span className="text-gray-200">{repo.owner}/{repo.repo}</span> will be cloned locally.
+ </span>
+ </p>
+ <div className="flex flex-wrap gap-2">
+ {REPO_INTAKE_OPTIONS.map(({ key, label, hint, Icon }) => (
+ <ToggleChip
+ key={key}
+ id={`${idPrefix}-${key}`}
+ label={label}
+ hint={hint}
+ Icon={Icon}
+ checked={options[key]}
+ onToggle={() => onToggle(key)}
+ />
+ ))}
+ </div>
+ {REPO_INTAKE_OPTIONS.some(({ key }) => options[key]) && (
+ <p className="text-xs text-gray-500">
+ A CoS agent starts once the clone finishes — track it in Chief of Staff.
+ </p>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/brain/tabs/InboxTab.jsx b/client/src/components/brain/tabs/InboxTab.jsx
index 8b9b099efc..388ca39f11 100644
--- a/client/src/components/brain/tabs/InboxTab.jsx
+++ b/client/src/components/brain/tabs/InboxTab.jsx
@@ -33,6 +33,8 @@ import ConfidenceBadge from '../ConfidenceBadge';
import { timeAgo } from '../../../utils/formatters';
import { parseBareUrl } from '../../../lib/bareUrl';
import VoiceCapture from '../VoiceCapture';
+import RepoIntakeOptions from '../RepoIntakeOptions';
+import { useRepoIntake } from '../../../hooks';
// Where a filed entry's "View" button points. A bare-URL capture is filed to the
// links collection (see captureUrlAsLink) and lives in the Links tab; every
@@ -54,6 +56,9 @@ export default function InboxTab({ onRefresh, settings }) {
// when on, captured thoughts are flagged so they can later be batch-sent to the
// creative catalog (vs todos/refs that stay out).
const [creative, setCreative] = useLocalStorageBool('brain.captureCreative', false);
+ // A bare GitHub repo URL is cloned on capture, which unlocks the two post-clone
+ // agent opt-ins (malware scan / repo study) — shared with Quick Capture.
+ const repoIntake = useRepoIntake(inputText);
const [entries, setEntries] = useState([]);
const [loading, setLoading] = useState(true);
const [showNeedsReview, setShowNeedsReview] = useState(true);
@@ -125,7 +130,12 @@ export default function InboxTab({ onRefresh, settings }) {
setInputText('');
setEntries(prev => [optimisticEntry, ...prev]);
- const result = await api.captureBrainThought(text, undefined, undefined, { creative: asCreative }, { silent: true }).catch(err => {
+ // `intakeFor` re-derives from the submitted text, so a sticky tick can't ride
+ // along on a capture that is no longer a repo URL.
+ const result = await api.captureBrainThought(text, undefined, undefined, {
+ creative: asCreative,
+ repoIntake: repoIntake.intakeFor(text),
+ }, { silent: true }).catch(err => {
toast.error(err.message || 'Failed to capture thought');
setEntries(prev => prev.filter(e => e.id !== tempId));
return null;
@@ -343,12 +353,20 @@ export default function InboxTab({ onRefresh, settings }) {
</div>
<p className="mt-2 text-xs text-gray-500">
Capture a thought — type or use the mic. AI will classify and route it automatically.
- {inputIsUrl && <span className="text-cyan-400"> That&rsquo;s a URL — it will be saved to Links.</span>}
+ {inputIsUrl && (repoIntake.repo
+ ? <span className="text-cyan-400"> That&rsquo;s a GitHub repo — it will be saved to Links and cloned.</span>
+ : <span className="text-cyan-400"> That&rsquo;s a URL — it will be saved to Links.</span>)}
{!inputIsUrl && creative && <span className="text-port-accent-2"> Creative mode on — captures are flagged for the Catalog.</span>}
{settings?.confidenceThreshold && (
<span> Confidence threshold: {Math.round(settings.confidenceThreshold * 100)}%</span>
)}
</p>
+ <RepoIntakeOptions
+ idPrefix="inbox-capture-repo"
+ repo={repoIntake.repo}
+ options={repoIntake.options}
+ onToggle={repoIntake.toggle}
+ />
</form>
{/* Creative batch action — appears once any captured note is flagged
diff --git a/client/src/components/brain/tabs/LinksTab.jsx b/client/src/components/brain/tabs/LinksTab.jsx
index 5fb0f799fe..0b6907b718 100644
--- a/client/src/components/brain/tabs/LinksTab.jsx
+++ b/client/src/components/brain/tabs/LinksTab.jsx
@@ -18,6 +18,7 @@ import {
Tag,
ShieldCheck,
Skull,
+ Lightbulb,
Search,
ChevronDown,
ChevronUp,
@@ -35,6 +36,14 @@ import { LINK_DND_TYPE } from '../links/bucketColors';
import { reorderLinksInBucket } from '../links/bucketReorder';
import { normalizeUrl as normalizeUrlShared } from '../../../utils/urlNormalize';
+/**
+ * True once a link has a malware-scan report that can actually be opened. A
+ * capture-time scan is stamped `queued` before the agent runs — it has a
+ * reportId but no file yet, so the "Scan Reports" filter must not offer it.
+ * Legacy records carry no `status` at all and are treated as readable.
+ */
+const hasScanReport = (link) => Boolean(link.malwareScan?.reportId) && link.malwareScan.status !== 'queued';
+
/** Normalize a user-entered URL the way the quick-add form does. */
function normalizeUrl(raw) {
return normalizeUrlShared(raw, { allowGit: true, requireDot: true });
@@ -99,7 +108,7 @@ export default function LinksTab({ onRefresh }) {
// Client-side filter (type / bucket membership) then keyword search.
const matchesFilter = (link) => {
if (filter === 'github') return link.isGitHubRepo;
- if (filter === 'scanned') return Boolean(link.malwareScan?.reportId);
+ if (filter === 'scanned') return hasScanReport(link);
if (filter === 'other') return !link.isGitHubRepo;
if (filter === 'ungrouped') return !link.bucketId;
return true;
@@ -419,7 +428,7 @@ export default function LinksTab({ onRefresh }) {
{[
{ id: 'all', label: 'All', count: links.length },
{ id: 'github', label: 'GitHub Repos', icon: GitBranch, count: links.filter(l => l.isGitHubRepo).length },
- { id: 'scanned', label: 'Scan Reports', icon: FileText, count: links.filter(l => l.malwareScan?.reportId).length },
+ { id: 'scanned', label: 'Scan Reports', icon: FileText, count: links.filter(hasScanReport).length },
{ id: 'other', label: 'Other Links', icon: Link2, count: links.filter(l => !l.isGitHubRepo).length },
{ id: 'ungrouped', label: 'Ungrouped', icon: FolderClosed, count: links.filter(l => !l.bucketId).length }
].map(tab => {
@@ -683,7 +692,15 @@ export default function LinksTab({ onRefresh }) {
</span>
)}
- {link.malwareScan?.reportId && (
+ {/* A capture-time scan is stamped `queued` before the agent runs,
+ so there is no report to open yet — say so instead of linking
+ at a 404. finalizeMalwareScan flips it once the run lands. */}
+ {link.malwareScan?.status === 'queued' ? (
+ <span className="flex items-center gap-1 text-xs text-gray-400" title="Malware scan queued — track it in Chief of Staff">
+ <ShieldCheck size={12} />
+ Scan queued
+ </span>
+ ) : link.malwareScan?.reportId && (
<Link
to={api.brainScanReportPath(link.id)}
className={`flex items-center gap-1 text-xs ${link.malwareScan.verdict === 'DANGEROUS' ? 'text-port-error' : 'text-port-accent'} hover:underline`}
@@ -694,6 +711,17 @@ export default function LinksTab({ onRefresh }) {
</Link>
)}
+ {link.repoStudy?.taskId && (
+ <Link
+ to="/cos/tasks"
+ className="flex items-center gap-1 text-xs text-gray-400 hover:text-port-accent transition-colors"
+ title={`Repo study queued as ${link.repoStudy.taskId} — track it in Chief of Staff`}
+ >
+ <Lightbulb size={12} />
+ Repo study
+ </Link>
+ )}
+
{/* Local path */}
{link.localPath && (
<span className="flex items-center gap-1 text-xs text-gray-500 truncate max-w-[200px]" title={link.localPath}>
diff --git a/client/src/components/ui/ToggleChip.jsx b/client/src/components/ui/ToggleChip.jsx
new file mode 100644
index 0000000000..0fb6e6ba8c
--- /dev/null
+++ b/client/src/components/ui/ToggleChip.jsx
@@ -0,0 +1,28 @@
+/**
+ * A checkbox styled as a pill — the "pick some of these" affordance used by the
+ * Brain capture boxes (YouTube ingest artifacts, GitHub repo intake actions).
+ *
+ * The label wraps the input, so the whole pill is the hit target while
+ * `htmlFor`/`id` still establish the accessible association explicitly.
+ */
+export default function ToggleChip({ id, label, hint, Icon, checked, onToggle }) {
+ return (
+ <label
+ htmlFor={id}
+ title={hint}
+ className={`flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg border text-xs cursor-pointer transition-colors ${checked
+ ? 'bg-port-accent/20 text-port-accent border-port-accent/40'
+ : 'bg-port-bg text-gray-400 border-port-border hover:text-gray-200'}`}
+ >
+ <input
+ id={id}
+ type="checkbox"
+ checked={checked}
+ onChange={onToggle}
+ className="accent-port-accent"
+ />
+ {Icon && <Icon size={12} />}
+ {label}
+ </label>
+ );
+}
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 9491376c36..1fc4c2b0f9 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -172,6 +172,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useSongTraining` | Drives a song training run over one scope (whole song or a sliced section) on top of `useColorMatch`: counts in, walks + grades the scope's score, then folds the finished take into the rolling progress history (`songProgress.recordAttempt`) and surfaces the next aggregate via `onProgress`. Supports looping (auto-restart after a run) and keeps a `lastSummary`. Exposes `{ running, countingIn, noteColors, activeIndex, lastSummary, start, stop }`; cancels pending loop relaunches on stop/unmount. | The Song editor's Training panel. |
| `useSyncIntegrity` | Fetches per-kind integrity diff from every eligible online peer; reduces to worst-case `statusById` + `byPeer` breakdown maps. | Federated media sync integrity UI — badges, drawers, peer breakdown. |
| `useTwinEvaluationSuite` | Shared lifecycle for the three Digital Twin evaluation-suite panels (Values-Alignment, Adversarial-Boundary, Multi-Turn): loads suite + recent history (silenced), runs every selected provider/model in parallel, prepends fresh runs, and handles the stale-persona / partial-failure toast fan-out. `countField` names the suite's pass-count key so history stays generic. Returns `{ items, history, loading, running, results, expanded, setExpanded, run, reload }`. | The Digital Twin `TwinEvaluationSuitePanel` presentation shell — don't re-roll the load/run/history dance per suite. |
+| `useRepoIntake` | The Brain capture boxes' GitHub-repo state: `repo` (the parsed `{owner,repo}` when the ENTIRE capture text is a repo URL — i.e. exactly when the server will clone it), the two sticky post-clone agent opt-ins (`options`/`toggle`, persisted to `localStorage`), and `intakeFor(submittedText)` which re-derives at submit time so a sticky tick can't ride along on a capture retyped into a plain thought. Also exports the pure `capturedGitHubRepo(text)`. | Any capture surface that should offer the malware-scan / repo-study runs. Render with `components/brain/RepoIntakeOptions`; don't re-parse the text in the component. |
| `useRenderJobQueue` | Per-entry render-job queue for the Universe Builder — `pendingByEntryId` (entryId → jobId[]), `pendingHeadByEntryId` (first jobId per entry for single-subscription thumbs), `enqueueEntryJobs` (append variation/canon jobs), `clearPendingForEntry` (shift a jobId out, or drop the entry). | Universe Builder render orchestration. Don't re-roll the per-entry pending-jobs reducer. |
| `useUniverse` | Loads the universe record for a `universeId` with mount/cancel guards; returns `[universe, setUniverse, loading, error]` (setter exposed for optimistic post-mutation updates). | Any surface that loads a linked universe (pipeline stages, etc.) — use instead of re-rolling the getUniverse-on-mount effect. |
| `useUniverseAction` | LLM-driven universe mutation scaffolding. | Universe Builder action UIs. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index 2de2325c91..bc3991ddbf 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -177,6 +177,7 @@ export * from './useGoalDetail.js';
export * from './usePostSession.js';
export * from './useRecordMerge.js';
export * from './useRenderJobQueue.js';
+export * from './useRepoIntake.js';
export * from './useSyncIntegrity.js';
export * from './useTwinEvaluationSuite.js';
export * from './useUniverseNav.js';
diff --git a/client/src/hooks/useRepoIntake.js b/client/src/hooks/useRepoIntake.js
new file mode 100644
index 0000000000..46b4560668
--- /dev/null
+++ b/client/src/hooks/useRepoIntake.js
@@ -0,0 +1,61 @@
+import { useMemo } from 'react';
+import { useLocalStorageBool } from './useLocalStorageBool.js';
+import { parseBareUrl } from '../lib/bareUrl.js';
+import { parseGitHubUrl } from '../lib/githubRepoUrl.js';
+
+/**
+ * The Brain capture boxes' "this URL is a GitHub repo" state.
+ *
+ * A bare GitHub repo URL is always cloned by the server, which unlocks two
+ * opt-in post-clone CoS agent runs (malware scan / repo study). Both preferences
+ * are sticky — same pattern as the Creative toggle — so a user who always wants
+ * a malware scan ticks it once.
+ *
+ * Rendering lives in `components/brain/RepoIntakeOptions.jsx`, which takes the
+ * `repo` this returns rather than re-parsing the text.
+ */
+
+/** localStorage keys, by action. Reordering the UI table must not rebind these. */
+const STORAGE_KEYS = {
+ malwareScan: 'brain.repoIntake.malwareScan',
+ learn: 'brain.repoIntake.learn',
+};
+
+/**
+ * `{ owner, repo }` when a capture's ENTIRE text is a GitHub repo URL — i.e.
+ * exactly when the server will file it to Links and clone it. Composes the two
+ * mirrored rules in the same order `services/brain.js` does (`parseBareUrl` →
+ * `parseGitHubUrl`); checking only the second would light the panel up for
+ * "check out github.com/owner/repo", which the server files as a thought.
+ */
+export function capturedGitHubRepo(text) {
+ const url = parseBareUrl(text);
+ return url ? parseGitHubUrl(url) : null;
+}
+
+/**
+ * @param {string} text the current capture text
+ * @returns {{ repo: object|null, options: object, toggle: (key: string) => void,
+ * intakeFor: (text: string) => object|undefined }}
+ * `repo` is the parsed `{ owner, repo }` (null when the text isn't a bare repo
+ * URL) — both the panel and the host's hint read it, so the text is parsed
+ * once per keystroke rather than once per consumer. `intakeFor(text)` is the
+ * payload to send with a capture: the ticked options when `text` is a repo
+ * URL, else undefined. It re-derives from the SUBMITTED text so a sticky tick
+ * can't ride along on a capture the user retyped into a plain thought.
+ */
+export function useRepoIntake(text) {
+ const [malwareScan, setMalwareScan] = useLocalStorageBool(STORAGE_KEYS.malwareScan, false);
+ const [learn, setLearn] = useLocalStorageBool(STORAGE_KEYS.learn, false);
+
+ const repo = useMemo(() => capturedGitHubRepo(text), [text]);
+ const options = useMemo(() => ({ malwareScan, learn }), [malwareScan, learn]);
+ const setters = { malwareScan: setMalwareScan, learn: setLearn };
+
+ return {
+ repo,
+ options,
+ toggle: (key) => setters[key](v => !v),
+ intakeFor: (submitted) => (capturedGitHubRepo(submitted) ? { ...options } : undefined),
+ };
+}
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 64f140276a..dbb5f325c7 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -98,6 +98,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `downloadBlob.js` | `downloadBlob(data, filename, type?)` — trigger a browser "Save as…" for a Blob / ArrayBuffer / typed array / string, with object-URL + temporary `<a>` cleanup. Use instead of inlining `URL.createObjectURL` + `<a download>`. |
| `extensionErrors.js` | `isExtensionError(payload)` — true when an error report came from a browser extension's injected content script rather than from PortOS, so `clientErrorReporter` can drop it instead of spending its 1/sec throttle slot on an error we can't fix. Client mirror of the authoritative `server/lib/extensionErrors.js` (parity enforced by `server/lib/extensionErrors.mirror.test.js`); the server re-checks, since a long-lived tab can still be running an old bundle. |
| `genUtils.js` | Shared bits between Image Gen and Video Gen pages. |
+| `githubRepoUrl.js` | `parseGitHubUrl(url)` / `isGitHubRepoUrl(url)` — client mirror of the authoritative `server/lib/githubRepoUrl.js` (parity enforced by `server/lib/githubRepoUrl.mirror.test.js`). The Brain capture boxes use it to tell the user a bare repo URL will be cloned and to reveal the post-clone agent options (malware scan / learn-from-repo). |
| `healthProvenance.js` | `PROVENANCE_LEVELS` / `getProvenanceLevel(level)` — the `data-backed`/`inferred`/`experimental`/`speculative` trust taxonomy (label, tone, description, "what would change this?" copy) behind the `ProvenanceChip` source-style chips on MeatSpace / genome / death-clock / longevity views. Pure data; the chip component maps tone→color and id→icon. |
| `joinInfluenceList.js` | Mirror of `joinInfluenceList` in server universe builder. |
| `kanbanColumns.js` | `bucketTickets` / `ticketInColumn` / `columnConfig` / `FALLBACK_COLUMNS` — pure column logic for the Jira Kanban board (`components/KanbanBoard.jsx`). Buckets tickets into resolved workflow columns (by status name, or statusCategory for the fallback board), assigns each column a stable unique `id` (Jira `name` is not unique — same-named columns map to different statuses), appends an orphan column for any unmatched status, and precomputes per-column Tailwind color config (Blocked→red, Review/QA→purple, else by category). |
diff --git a/client/src/lib/githubRepoUrl.js b/client/src/lib/githubRepoUrl.js
new file mode 100644
index 0000000000..8592bb2971
--- /dev/null
+++ b/client/src/lib/githubRepoUrl.js
@@ -0,0 +1,49 @@
+/**
+ * GitHub repository URL parsing — MIRROR of `server/lib/githubRepoUrl.js`
+ * (authoritative there).
+ *
+ * The Brain capture boxes preview what the server will do with a bare URL: a
+ * GitHub repo gets cloned, which unlocks the post-clone agent options (malware
+ * scan / learn-from-repo). A looser client offers those options for a URL the
+ * server files as a plain bookmark; a tighter one hides them for a repo that
+ * will in fact be cloned.
+ *
+ * Port any change from the server copy verbatim; parity is enforced by
+ * `server/lib/githubRepoUrl.mirror.test.js`.
+ */
+
+// SSH remote: [email protected]:owner/repo(.git)
+const SSH_REPO_RE = /^git@github\.com:([^/]+)\/([^/.]+)(?:\.git)?$/i;
+
+// HTTPS or scheme-less: [https://]github.com/owner/repo[.git][/...]
+const HTTPS_REPO_RE = /(?:https?:\/\/)?github\.com\/([^/]+)\/([^/?#]+)/i;
+
+/**
+ * Parse a GitHub URL into `{ owner, repo, isGitHub }`, or null when the URL
+ * isn't a GitHub repository.
+ *
+ * @param {string} url
+ * @returns {{ owner: string, repo: string, isGitHub: true } | null}
+ */
+export function parseGitHubUrl(url) {
+ if (!url) return null;
+ const normalized = String(url).trim();
+
+ const ssh = normalized.match(SSH_REPO_RE);
+ if (ssh) return { owner: ssh[1], repo: ssh[2], isGitHub: true };
+
+ const https = normalized.match(HTTPS_REPO_RE);
+ if (https) return { owner: https[1], repo: https[2].replace(/\.git$/, ''), isGitHub: true };
+
+ return null;
+}
+
+/**
+ * True when the URL points at a GitHub repository.
+ *
+ * @param {string} url
+ * @returns {boolean}
+ */
+export function isGitHubRepoUrl(url) {
+ return parseGitHubUrl(url) !== null;
+}
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index 669d0e2737..647c29ea58 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -72,6 +72,7 @@ export * from './dndTransform.js';
export * from './downloadBlob.js';
export * from './extensionErrors.js';
export * from './genUtils.js';
+export * from './githubRepoUrl.js';
export * from './healthProvenance.js';
export * from './joinInfluenceList.js';
export * from './kanbanColumns.js';
diff --git a/client/src/services/apiBrain.js b/client/src/services/apiBrain.js
index 3b5555e80d..7fde7fbaf1 100644
--- a/client/src/services/apiBrain.js
+++ b/client/src/services/apiBrain.js
@@ -10,9 +10,11 @@ export const updateBrainSettings = (settings, options = {}) => request('/brain/s
});
// Brain - Capture & Inbox
-export const captureBrainThought = (text, providerOverride, modelOverride, { creative } = {}, options = {}) => request('/brain/capture', {
+// `repoIntake` ({ malwareScan, learn }) is the capture box's post-clone agent
+// opt-in; the server ignores it unless the text is a bare GitHub repo URL.
+export const captureBrainThought = (text, providerOverride, modelOverride, { creative, repoIntake } = {}, options = {}) => request('/brain/capture', {
method: 'POST',
- body: JSON.stringify({ text, providerOverride, modelOverride, creative }),
+ body: JSON.stringify({ text, providerOverride, modelOverride, creative, repoIntake }),
...options
});
export const getBrainInbox = (options = {}) => {
diff --git a/server/lib/README.md b/server/lib/README.md
index 8009dca324..a6581c1348 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -184,6 +184,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `gitForge.js` | `parseGitRemote`, `parseGitHubOwnerFromRemote`, `pickGhAccountForOwner`, `detectForgeCli`, `parsePullRequestUrl` — pure GitHub/GitLab remote + PR/MR URL parsers and forge/account selectors used by `git.js`. |
| `gitOutputParsers.js` | `parseStatus`, `parseDiffStat`, `parseBranchVerboseLine`, `parseSubmoduleStatusLine`/`SUBMODULE_STATUS_RE`, `extractAgentSummary` — pure parsers turning git command output into structured data for `git.js`. `extractAgentSummary` anchors on `agentOutputMarkers`' completion marker so a TUI agent's PR body carries its sentinel summary, not the lifecycle telemetry above it. |
| `gitRemote.js` | `getOriginInfo`, `parseGitRemoteUrl`, `UPSTREAM_OWNER`/`UPSTREAM_REPO` — classifies the local `origin` remote vs the upstream atomantic/PortOS repo. Used by the update flow to detect forks. |
+| `githubRepoUrl.js` | `parseGitHubUrl(url)` → `{ owner, repo }` / `isGitHubRepoUrl(url)` — authoritative "is this a clonable GitHub repo URL?" rule, re-exported by `services/githubCloner.js`. Mirrored to `client/src/lib/githubRepoUrl.js` (parity pinned by `githubRepoUrl.mirror.test.js`) so the Brain capture boxes reveal the post-clone agent options for exactly the URLs the server will clone. |
| `killWithEscalation.js` | `killWithEscalation(proc, {label, stillRunning, delayMs=8000})` — shared SIGTERM→grace→SIGKILL cancel-escalation for spawn-based media jobs. Sends SIGTERM, then escalates to SIGKILL after `delayMs` only when `stillRunning()` holds and the child hasn't exited (`exitCode===null && signalCode===null`). The timer is unref'd and the callback is try/catch-wrapped (runs outside the request lifecycle). Converges musicVideo/render, videoTimeline, imageGen local+codex, videoGen, loraTraining, and the yt-dlp track import cancel paths. |
| `processEnv.js` | `stripDebugMallocEnv(env)` / `safeChildProcessEnv(extra)` — drop macOS `Malloc*` debug env vars before spawning a child. Pinokio-launched PortOS exports `MallocStackLogging`/`MallocScribble`/etc. that flood Python subprocess stderr with `can't turn off malloc stack logging` lines; route every Node→Python spawn through this. No-op on Linux/Windows. Also `whichFirst(name)` — first-hit `which`/`where` PATH probe (Malloc-stripped env, 5s timeout) returning the absolute binary path or `null`; the shared discovery probe behind `findYtDlp`/`findFfmpeg`/`detectPython`/voice `which`. |
| `pythonSetup.js` | Python venv / runner setup helpers. |
@@ -325,11 +326,12 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `staticImportGraph.js` | Static ES-module import scanning for structural test guards. `staticImportSpecifiers(file)` → every specifier a file statically imports (verbatim, source order); `staticImportClosure(entry)` → `{files, packages}` for the whole reachable graph; `specifierMatchesPackage(spec, pkg)` matches a package or any subpath. Static imports only — `await import()` is deferred and can't create a load-time cycle or drag a native dep into an init graph. Shared by `agentImportCycles.test.js` (acyclicity) and `sprites/animationTracks.test.js` (the request-validation graph reaches no sharp/ffmpeg). |
| `sseUtils.js` | Per-job SSE stream helpers (imageGen + others) plus `createSseRunner` — the shared batch-runner lifecycle (runs map, terminal-frame replay, cancel, fire-and-forget coordinator) used by the pipeline completeness/analysis/checks runners. |
| `streamBackpressure.js` | `awaitWritableDrain(res)` — park a streaming-response producer on the socket's next `drain` (or `close`) when `res.write()` returned false, so SSE/NDJSON writes stay bounded for a slow reader. Shared by `routes/ask.js` (SSE) and `routes/localLlm.js` (NDJSON). |
+| `repoIntakeActions.js` | `REPO_INTAKE_KEYS` + `normalizeRepoIntake(input)` — the opt-in post-clone agent actions a Brain capture can request for a GitHub repo URL (`malwareScan` → `/do:scan`, `learn` → a `repo-study` review). Pure half of `services/repoIntake.js` (which pulls the CoS task graph), so the link write path and the Zod schemas can import it freely. Normalizes to null when nothing was ticked, so "no intake" is never persisted onto a link. |
| `tombstones.js` | Generic timestamped tombstones (`{ <keyField>, deletedAt }`) that let an otherwise add-only peer merge represent a DELETE, so a record removed on one machine is not resurrected by a peer that still has it (#3530). `normalizeTombstones` / `recordTombstone` / `clearTombstone` / `tombstoneTimestamp` maintain the list; `mergeTombstones` unions it in both directions (newest deletion per key wins) so a delete propagates rather than only defending locally; `isTombstoned(list, key, createdAt)` suppresses a record unless its own creation stamp is strictly NEWER than the deletion; `pruneTombstones(list, records)` drops tombstones a re-created record has superseded (otherwise a stale peer copy keeps reaping it); `supersedingTimestamp(deletedAt)` stamps a re-create that lands in the same millisecond (or behind a skewed peer clock). Comparison goes through `lwwTimestamp.js`, so polarity matches every other sync merge. Key on a field that means the same thing on every machine — locally-minted ids usually do not. `DEFAULT_TOMBSTONE_LIMIT` (200) caps growth. |
| `uploadLimits.js` | Single source of truth for upload size caps — `JSON_BODY_LIMIT`/`JSON_BODY_LIMIT_BYTES` (the express.json limit applied in `index.js`), `MAX_BASE64_UPLOAD_BYTES` derived from it (base64 ×4/3, so a bigger per-route cap is unreachable), `MAX_SCREENSHOT_BYTES`. Mirrored client-side as `JSON_UPLOAD_MAX_FILE_SIZE`. |
| `uuid.js` | `v4()` thin wrapper over `crypto.randomUUID()`. |
| `versionUtils.js` | `compareSemver(a, b)` — semver ordering (-1/0/1) with pre-release precedence and build-metadata stripping. Shared by the self-update checker (`updateChecker.js`) and the local-LLM Ollama update detector (`localLlm.js`). Inputs must be `v`-stripped. |
-| `workTracker.js` | `WORK_TRACKERS`/`CONCRETE_WORK_TRACKERS`/`DEFAULT_WORK_TRACKER`, `workTrackerLabel`, `hostToWorkTracker`, `isGithubHost` (GitHub-family host test — github.com + enterprise github.*; enterprise-aware replacement for the github.com-only `isGithub` gate), `githubRepoSpec(origin)` (host-qualified `HOST/OWNER/REPO` selector for `gh --repo`, or null for a non-GitHub origin — pairs the isGithubHost gate with the selector so prWatcher/branchReconcile/issueReconcile share one "resolvable GitHub repo" definition), `forgeCliForTracker`, `isFileTracker` (true when the tracker records work as repo files — PLAN.md — so an agent's proposal necessarily dirties the worktree; false for github/gitlab/jira), `trackerToClaimTaskType`, `hostFromOriginUrl` (subgroup-tolerant host parse), pure `resolveWorkTracker({configured,host})`, async `resolveAppWorkTracker(app)` — resolves a managed app's autonomous work source (PLAN.md / GitHub / GitLab / JIRA), defaulting `'auto'` to the git origin host. Also owns the `{trackerInstructions}` prompt block shared by the TRACKER-FILING task types (types that read the app read-only and deliver findings as tracker items, not a commit): `TRACKER_FILING_PRESETS` (per-task-type slug prefix / label / body requirements — `reference-watch`, `ux`), `TRACKER_FILING_TASK_TYPES` (derived from the presets, so a gated type always has wording), and `formatTrackerInstructions(tracker, options)` which renders the plan/github/gitlab/jira block (reference-watch is the default option set, so a bare call stays byte-identical for it). Consumed by the `claim-work` router in `cosTaskGenerator.js`, `referenceRepos.js`, and `routes/apps.js`. |
+| `workTracker.js` | `WORK_TRACKERS`/`CONCRETE_WORK_TRACKERS`/`DEFAULT_WORK_TRACKER`, `workTrackerLabel`, `hostToWorkTracker`, `isGithubHost` (GitHub-family host test — github.com + enterprise github.*; enterprise-aware replacement for the github.com-only `isGithub` gate), `githubRepoSpec(origin)` (host-qualified `HOST/OWNER/REPO` selector for `gh --repo`, or null for a non-GitHub origin — pairs the isGithubHost gate with the selector so prWatcher/branchReconcile/issueReconcile share one "resolvable GitHub repo" definition), `forgeCliForTracker`, `isFileTracker` (true when the tracker records work as repo files — PLAN.md — so an agent's proposal necessarily dirties the worktree; false for github/gitlab/jira), `trackerToClaimTaskType`, `hostFromOriginUrl` (subgroup-tolerant host parse), pure `resolveWorkTracker({configured,host})`, async `resolveAppWorkTracker(app)` — resolves a managed app's autonomous work source (PLAN.md / GitHub / GitLab / JIRA), defaulting `'auto'` to the git origin host. Also owns the `{trackerInstructions}` prompt block shared by the TRACKER-FILING task types (types that read the app read-only and deliver findings as tracker items, not a commit): `TRACKER_FILING_PRESETS` (per-task-type slug prefix / label / body requirements — `reference-watch`, `ux`, `repo-study`), `TRACKER_FILING_TASK_TYPES` (derived from the presets, so a gated type always has wording), and `formatTrackerInstructions(tracker, options)` which renders the plan/github/gitlab/jira block (reference-watch is the default option set, so a bare call stays byte-identical for it). Consumed by the `claim-work` router in `cosTaskGenerator.js`, `referenceRepos.js`, and `routes/apps.js`. |
| `workspaceRoots.js` | Shared allow-list for routes that take a caller-supplied filesystem path. `ALLOWED_WORKSPACE_ROOTS` (defaults + `PORTOS_WORKSPACE_ROOTS`, symlink-resolved), `isWithinRoot(resolvedPath, root)` (separator-safe containment), `isWithinAllowedRoots(realPath)`, and `WORKSPACE_ROOTS_CONFIGURED` (true when the operator set the env var — lets a permissive-by-default route like `routes/detect.js` opt into confinement). Used by `routes/commands.js` (always scoped) and `routes/detect.js` (scoped only when configured). |
| `zodCompat.js` | Zod 4 compatibility helpers. `partialWithoutDefaults(objectSchema)` — like `.partial()` but strips inner field defaults first, so a PATCH/update schema doesn't inject (and clobber) the stored values of fields the caller didn't send. Use for any update schema derived from a defaulted base. |
diff --git a/server/lib/brainValidation.js b/server/lib/brainValidation.js
index 35e9b661fa..bcc25742c2 100644
--- a/server/lib/brainValidation.js
+++ b/server/lib/brainValidation.js
@@ -1,5 +1,6 @@
import { z } from 'zod';
-import { partialWithoutDefaults } from './zodCompat.js';
+import { partialWithoutDefaults, optionalBooleanMap } from './zodCompat.js';
+import { REPO_INTAKE_KEYS } from './repoIntakeActions.js';
// Destination enum. `links` is reachable only from the bare-URL capture
// short-circuit (a pasted URL is filed straight to the links collection) — the
@@ -186,6 +187,12 @@ export const reviewRecordSchema = z.object({
// --- Input schemas for API endpoints ---
+// Opt-in post-clone agent actions for a captured GitHub repo URL. Keys derive
+// from REPO_INTAKE_KEYS so the wire contract can't drift from the normalizer
+// that reads it (server/lib/repoIntakeActions.js).
+export const repoIntakeSchema = z.object(optionalBooleanMap(REPO_INTAKE_KEYS));
+const repoIntakeInputSchema = repoIntakeSchema.optional();
+
// Capture input schema
export const captureInputSchema = z.object({
text: z.string().min(1).max(10000),
@@ -194,7 +201,11 @@ export const captureInputSchema = z.object({
// Opt-in flag: the user marked this note as a creative idea at capture time
// (vs a todo/reference). Creative notes are later batch-sendable into the
// creative catalog as ingredients (see catalog brain-bridge ingest).
- creative: z.boolean().optional()
+ creative: z.boolean().optional(),
+ // Post-clone agent actions for a bare GitHub repo URL. Ignored for every other
+ // capture — only a repo URL gets cloned, and only a clone can be scanned or
+ // studied (services/brain.js#createLinkFromUrl).
+ repoIntake: repoIntakeInputSchema
});
// Resolve review input schema
@@ -389,10 +400,19 @@ export const linkRecordSchema = z.object({
malwareScan: z.object({
reportId: z.string().uuid(),
taskId: z.string().optional(),
- status: z.enum(['completed', 'failed']).optional(),
+ // `queued` is stamped when the capture-time checkbox dispatches the scan
+ // right after the clone; finalizeMalwareScan replaces it on completion.
+ status: z.enum(['queued', 'completed', 'failed']).optional(),
verdict: z.enum(['CLEAN', 'CAUTION', 'DANGEROUS']).nullable().optional(),
completedAt: z.string().datetime().optional()
}).optional(),
+ // What the user asked to happen after the clone lands (capture-time checkboxes).
+ repoIntake: repoIntakeSchema.optional(),
+ // The queued `repo-study` run, once dispatched.
+ repoStudy: z.object({
+ taskId: z.string().optional(),
+ queuedAt: z.string().datetime().optional()
+ }).optional(),
// Bucket grouping (nullable = ungrouped)
bucketId: z.string().guid().nullable().optional(),
bucketOrder: z.number().int().optional(),
@@ -410,7 +430,9 @@ export const linkInputSchema = z.object({
tags: z.array(z.string().max(50)).optional(),
bucketId: z.string().guid().nullable().optional(),
bucketOrder: z.number().int().optional(),
- autoClone: z.boolean().optional().default(true)
+ autoClone: z.boolean().optional().default(true),
+ // Post-clone agent actions, same contract as the capture box's checkboxes.
+ repoIntake: repoIntakeInputSchema
});
// Update Link input schema (partial)
diff --git a/server/lib/githubRepoUrl.js b/server/lib/githubRepoUrl.js
new file mode 100644
index 0000000000..013a86e068
--- /dev/null
+++ b/server/lib/githubRepoUrl.js
@@ -0,0 +1,49 @@
+/**
+ * GitHub repository URL parsing — AUTHORITATIVE copy.
+ *
+ * Answers "is this URL a GitHub repo we can clone, and which owner/repo is it?"
+ * Lives in `lib/` (not `services/githubCloner.js`, which re-exports it) because
+ * the Brain capture boxes have to preview the same answer BEFORE submitting: a
+ * capture that is a bare GitHub repo URL gets cloned, and the client only offers
+ * the post-clone agent options (malware scan / learn-from-repo) when it agrees
+ * with the server about what counts as a repo.
+ *
+ * The client mirror is `client/src/lib/githubRepoUrl.js`; parity is enforced by
+ * `server/lib/githubRepoUrl.mirror.test.js`. Port any change to both.
+ */
+
+// SSH remote: [email protected]:owner/repo(.git)
+const SSH_REPO_RE = /^git@github\.com:([^/]+)\/([^/.]+)(?:\.git)?$/i;
+
+// HTTPS or scheme-less: [https://]github.com/owner/repo[.git][/...]
+const HTTPS_REPO_RE = /(?:https?:\/\/)?github\.com\/([^/]+)\/([^/?#]+)/i;
+
+/**
+ * Parse a GitHub URL into `{ owner, repo, isGitHub }`, or null when the URL
+ * isn't a GitHub repository.
+ *
+ * @param {string} url
+ * @returns {{ owner: string, repo: string, isGitHub: true } | null}
+ */
+export function parseGitHubUrl(url) {
+ if (!url) return null;
+ const normalized = String(url).trim();
+
+ const ssh = normalized.match(SSH_REPO_RE);
+ if (ssh) return { owner: ssh[1], repo: ssh[2], isGitHub: true };
+
+ const https = normalized.match(HTTPS_REPO_RE);
+ if (https) return { owner: https[1], repo: https[2].replace(/\.git$/, ''), isGitHub: true };
+
+ return null;
+}
+
+/**
+ * True when the URL points at a GitHub repository.
+ *
+ * @param {string} url
+ * @returns {boolean}
+ */
+export function isGitHubRepoUrl(url) {
+ return parseGitHubUrl(url) !== null;
+}
diff --git a/server/lib/githubRepoUrl.mirror.test.js b/server/lib/githubRepoUrl.mirror.test.js
new file mode 100644
index 0000000000..4f0ae7cde1
--- /dev/null
+++ b/server/lib/githubRepoUrl.mirror.test.js
@@ -0,0 +1,53 @@
+/**
+ * Mirror parity test for server/lib/githubRepoUrl.js ↔ client/src/lib/githubRepoUrl.js
+ *
+ * The server decides whether a captured URL gets cloned; the client previews
+ * that decision by revealing the post-clone agent options (malware scan /
+ * learn-from-repo) only for a repo URL. A drifted client either offers those
+ * options for a link that will never be cloned, or hides them for one that will.
+ *
+ * Comparison strips comments, so the intentionally divergent header commentary
+ * does not fail the test — only logic does.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { readFileSync } from 'fs';
+import { resolve, dirname } from 'path';
+import { fileURLToPath } from 'url';
+import { compareDeclaration } from './mirrorParity.js';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+
+const SERVER_PATH = resolve(__dirname, 'githubRepoUrl.js');
+const CLIENT_PATH = resolve(__dirname, '../../client/src/lib/githubRepoUrl.js');
+
+const MIRRORED_NAMES = [
+ 'SSH_REPO_RE',
+ 'HTTPS_REPO_RE',
+ 'parseGitHubUrl',
+ 'isGitHubRepoUrl',
+];
+
+describe('githubRepoUrl server↔client mirror parity', () => {
+ const serverSrc = readFileSync(SERVER_PATH, 'utf8');
+ const clientSrc = readFileSync(CLIENT_PATH, 'utf8');
+
+ it('both files are non-empty', () => {
+ expect(serverSrc.length).toBeGreaterThan(100);
+ expect(clientSrc.length).toBeGreaterThan(100);
+ });
+
+ for (const name of MIRRORED_NAMES) {
+ it(`${name} is present and identical on both sides (code only)`, () => {
+ const { serverDecl, clientDecl, serverNorm, clientNorm } =
+ compareDeclaration(serverSrc, clientSrc, name);
+
+ expect(serverDecl, `server/lib/githubRepoUrl.js is missing: ${name}`).not.toBeNull();
+ expect(clientDecl, `client/src/lib/githubRepoUrl.js is missing: ${name}`).not.toBeNull();
+ expect(
+ clientNorm,
+ `"${name}" diverged — the server copy is authoritative; port the change verbatim`,
+ ).toBe(serverNorm);
+ });
+ }
+});
diff --git a/server/lib/index.js b/server/lib/index.js
index 97672086f0..83476d3bd8 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -176,6 +176,7 @@ export * from './gitArgs.js';
export * from './gitForge.js';
export * from './gitOutputParsers.js';
export * from './gitRemote.js';
+export * from './githubRepoUrl.js';
export * from './goalFeatureMap.js';
export * from './killWithEscalation.js';
export * from './openFolder.js';
@@ -299,6 +300,7 @@ export * from './staleWhileRevalidate.js';
export * from './staticImportGraph.js';
export * from './streamBackpressure.js';
export * from './sseUtils.js';
+export * from './repoIntakeActions.js';
export * from './tombstones.js';
export * from './uploadLimits.js';
export * from './uuid.js';
diff --git a/server/lib/repoIntakeActions.js b/server/lib/repoIntakeActions.js
new file mode 100644
index 0000000000..0bf3aa4b98
--- /dev/null
+++ b/server/lib/repoIntakeActions.js
@@ -0,0 +1,31 @@
+/**
+ * The opt-in post-clone agent actions a Brain capture can request for a GitHub
+ * repo URL. Pure — the queueing itself lives in `services/repoIntake.js`, which
+ * pulls the whole CoS task graph; this half is safe to import from the link
+ * write path and from the Zod schemas.
+ *
+ * `malwareScan` → the read-only `/do:scan` audit of the clone.
+ * `learn` → a `repo-study` review: read the clone for ideas worth adopting
+ * into PortOS and file them in the work tracker (clean-room).
+ */
+
+import { isPlainObject } from './objects.js';
+
+export const REPO_INTAKE_KEYS = ['malwareScan', 'learn'];
+
+/**
+ * Normalize a client-supplied intake object to `{ malwareScan, learn }` booleans,
+ * or null when nothing was requested.
+ *
+ * Returning null rather than an all-false object matters: it's what keeps
+ * "the user ticked nothing" from being persisted onto every captured link and
+ * from scheduling a no-op intake pass after each clone.
+ *
+ * @param {unknown} input
+ * @returns {{ malwareScan: boolean, learn: boolean } | null}
+ */
+export function normalizeRepoIntake(input) {
+ if (!isPlainObject(input)) return null;
+ const normalized = Object.fromEntries(REPO_INTAKE_KEYS.map(key => [key, input[key] === true]));
+ return REPO_INTAKE_KEYS.some(key => normalized[key]) ? normalized : null;
+}
diff --git a/server/lib/repoIntakeActions.mirror.test.js b/server/lib/repoIntakeActions.mirror.test.js
new file mode 100644
index 0000000000..1f01b666da
--- /dev/null
+++ b/server/lib/repoIntakeActions.mirror.test.js
@@ -0,0 +1,41 @@
+/**
+ * Parity test for the repo-intake action keys: `REPO_INTAKE_KEYS` (server,
+ * authoritative) ↔ `REPO_INTAKE_OPTIONS` (client, the rendered checkbox table).
+ *
+ * These are the wire contract. Drift is silent in both directions: a key added
+ * server-side is simply never offered in either capture box, and a client-only
+ * key is stripped by the Zod schema and ignored by `normalizeRepoIntake` with no
+ * error anywhere. Unlike the githubRepoUrl mirror this compares KEYS, not source
+ * text — the client half legitimately carries labels, hints, and icons the
+ * server has no business knowing about.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { readFileSync } from 'fs';
+import { resolve, dirname } from 'path';
+import { fileURLToPath } from 'url';
+import { REPO_INTAKE_KEYS } from './repoIntakeActions.js';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const CLIENT_PATH = resolve(__dirname, '../../client/src/components/brain/RepoIntakeOptions.jsx');
+
+// The client table is a .jsx module importing lucide-react, so a server-env
+// suite can't import it (see the CI note in CLAUDE.md about server tests pulling
+// client deps). Read the `key:` entries out of the REPO_INTAKE_OPTIONS literal.
+const clientKeys = () => {
+ const src = readFileSync(CLIENT_PATH, 'utf8');
+ const table = src.match(/REPO_INTAKE_OPTIONS\s*=\s*\[([\s\S]*?)\n\];/);
+ if (!table) return null;
+ return [...table[1].matchAll(/^\s*key:\s*'([^']+)'/gm)].map(m => m[1]);
+};
+
+describe('repoIntake action-key parity (server ↔ client)', () => {
+ it('the client table is parseable — a rename must fail here, not silently pass', () => {
+ expect(clientKeys(), `Could not find REPO_INTAKE_OPTIONS in ${CLIENT_PATH}`).not.toBeNull();
+ expect(clientKeys().length).toBeGreaterThan(0);
+ });
+
+ it('offers exactly the actions the server accepts, in the same order', () => {
+ expect(clientKeys()).toEqual([...REPO_INTAKE_KEYS]);
+ });
+});
diff --git a/server/lib/repoIntakeActions.test.js b/server/lib/repoIntakeActions.test.js
new file mode 100644
index 0000000000..88e36474b8
--- /dev/null
+++ b/server/lib/repoIntakeActions.test.js
@@ -0,0 +1,34 @@
+import { describe, it, expect } from 'vitest';
+import { REPO_INTAKE_KEYS, normalizeRepoIntake } from './repoIntakeActions.js';
+
+describe('normalizeRepoIntake', () => {
+ it('returns null when nothing was ticked, so no-intake is never persisted', () => {
+ expect(normalizeRepoIntake(undefined)).toBeNull();
+ expect(normalizeRepoIntake(null)).toBeNull();
+ expect(normalizeRepoIntake({})).toBeNull();
+ expect(normalizeRepoIntake({ malwareScan: false, learn: false })).toBeNull();
+ });
+
+ it('fills every key so a partial payload cannot leave an action undefined', () => {
+ expect(normalizeRepoIntake({ learn: true })).toEqual({ malwareScan: false, learn: true });
+ });
+
+ it('only accepts a literal true — a truthy string does not opt an agent in', () => {
+ expect(normalizeRepoIntake({ malwareScan: 'yes' })).toBeNull();
+ expect(normalizeRepoIntake({ malwareScan: 1 })).toBeNull();
+ });
+
+ it('ignores unknown keys rather than passing them through', () => {
+ expect(normalizeRepoIntake({ learn: true, rmRf: true })).toEqual({ malwareScan: false, learn: true });
+ });
+
+ it('rejects non-objects, including arrays', () => {
+ expect(normalizeRepoIntake([true])).toBeNull();
+ expect(normalizeRepoIntake('malwareScan')).toBeNull();
+ expect(normalizeRepoIntake(true)).toBeNull();
+ });
+
+ it('covers exactly the two documented actions', () => {
+ expect(REPO_INTAKE_KEYS).toEqual(['malwareScan', 'learn']);
+ });
+});
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 1dfe212cdd..73c03e61ad 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -1,6 +1,6 @@
import { z } from 'zod';
import { ServerError } from './errorHandler.js';
-import { partialWithoutDefaults, emptyToUndefined, emptyToNull } from './zodCompat.js';
+import { partialWithoutDefaults, emptyToUndefined, emptyToNull, optionalBooleanMap } from './zodCompat.js';
import { WORK_TRACKERS } from './workTracker.js';
import { SPRITE_ID_PATTERN, SPRITE_RECORD_KINDS } from '../services/sprites/recordsLogic.js';
import { ANCHOR_DIRECTIONS, SPRITE_DIRECTIONS, TURNAROUND_ID } from '../services/sprites/prompts.js';
@@ -57,12 +57,9 @@ export const isSafeRecordId = (id) =>
&& id !== '.' && id !== '..'
&& !id.includes('/') && !id.includes('\\') && !id.includes('\0');
-// Build a sparse-map Zod shape from a string array of boolean-typed keys.
-// Returns the raw record so callers can either spread it (...optionalBooleanMap(KEYS))
-// into a larger object schema or wrap it directly (z.object(optionalBooleanMap(KEYS))).
-// Mirrors the `{ field?: boolean }` shape used for per-field lock maps.
-export const optionalBooleanMap = (keys) =>
- Object.fromEntries(keys.map((k) => [k, z.boolean().optional()]));
+// `optionalBooleanMap` now lives in zodCompat.js (so per-domain schema files can
+// use it without a cycle through this module) — re-exported for deep imports.
+export { optionalBooleanMap };
// =============================================================================
// EXISTING SCHEMAS
diff --git a/server/lib/workTracker.js b/server/lib/workTracker.js
index 34b25300b0..213d2ae814 100644
--- a/server/lib/workTracker.js
+++ b/server/lib/workTracker.js
@@ -190,6 +190,19 @@ export const TRACKER_FILING_PRESETS = {
bodyRequirements: 'the screen/route audited and the date, what the user is trying to do there, why the current design impedes it, a concrete proposed change naming the component file(s) in {appName}, and a `Scope:` of small/medium/large',
planCommitMessage: 'docs(ux): propose <N> UX finding(s)',
},
+ // One-shot study of a repo the user captured into the Brain (services/repoIntake.js),
+ // as opposed to `reference-watch`'s recurring commit-diff review of a repo
+ // configured on the app. Same clean-room contract: propose reimplementation in
+ // the app's OWN code, never copy upstream source.
+ 'repo-study': {
+ slugPrefix: 'repo-study-',
+ label: 'repo-study',
+ issueLabel: 'repo-study',
+ labelDescription: 'Proposed from a study of a captured reference repository',
+ planItemBody: 'From the `repo-study` of <owner/repo> (<today\'s date>). <What the upstream does and why it is worth having, 1–2 sentences.> Fix: <files + functions in {appName}>. <Estimated scope.>',
+ bodyRequirements: 'the provenance (the studied repo\'s owner/repo + its license + today\'s date), the 1–2 sentence rationale for {appName}, the `Fix:` line naming the {appName} files/functions to change, and the estimated scope',
+ planCommitMessage: 'docs(repo-study): propose <N> item(s) from <owner/repo>',
+ },
};
/**
@@ -259,6 +272,41 @@ export function formatTrackerInstructions(tracker, options = {}) {
return blocks[tracker] || blocks.plan;
}
+/**
+ * Resolve the {trackerInstructions} block naming where a tracker-filing task
+ * records what it found, plus the two metadata signals derived from the SAME
+ * resolved tracker so they can never disagree with the instructions the agent
+ * actually got (#3140, #3102):
+ * - `workTracker` — traceability, and the marker that lets a ONE-OFF
+ * tracker-filing run reach `declaresNoCommitCriterion` without masquerading
+ * as a scheduled task type (see taskTypeHooks.js#isTrackerFilingDispatch)
+ * - `worktreeChangesExpected` — the PLAN.md path commits checklist items
+ * (dirty tree); the github/gitlab/jira paths file issues/tickets out of band
+ * and legitimately leave the tree CLEAN.
+ *
+ * A TRACKER-FILING type reads the app read-only and delivers its findings as
+ * items in the app's tracker rather than as a commit. The set is derived from
+ * `TRACKER_FILING_PRESETS`, so a type is gated in exactly when it has wording.
+ *
+ * Returns `{ trackerInstructions: '', workTracker: null }` for every other type.
+ *
+ * Lives here rather than in one of its callers because all three tracker-filing
+ * dispatch paths need the identical four-part resolution: the SCHEDULED types
+ * (cosTaskGenerator.js), the on-commit reference-watch trigger
+ * (referenceRepos.js), and the one-off `repo-study` (repoIntake.js).
+ */
+export async function resolveTrackerFilingBlock(app, taskType) {
+ if (!TRACKER_FILING_TASK_TYPES.has(taskType)) return { trackerInstructions: '', workTracker: null };
+ // Never throws — degrades to the PLAN.md block, which `isFileTracker` then
+ // agrees with, so the flag and the instructions stay consistent.
+ const workTracker = await resolveAppWorkTracker(app).catch(() => ({ resolved: 'plan' }));
+ return {
+ trackerInstructions: formatTrackerInstructions(workTracker.resolved, TRACKER_FILING_PRESETS[taskType]),
+ workTracker: workTracker.resolved,
+ worktreeChangesExpected: isFileTracker(workTracker.resolved),
+ };
+}
+
/**
* The CoS claim task type that ships work from a concrete tracker. The
* claim-work router (cosTaskGenerator) delegates to one of these prompt bodies
diff --git a/server/lib/zodCompat.js b/server/lib/zodCompat.js
index 74792a318b..6544413ac8 100644
--- a/server/lib/zodCompat.js
+++ b/server/lib/zodCompat.js
@@ -77,6 +77,19 @@ export function partialWithoutDefaults(objectSchema) {
*/
export const emptyToUndefined = (v) => (v === '' ? undefined : v);
+/**
+ * Build a sparse-map Zod shape from a string array of boolean-typed keys.
+ * Returns the raw record so callers can either spread it (...optionalBooleanMap(KEYS))
+ * into a larger object schema or wrap it directly (z.object(optionalBooleanMap(KEYS))).
+ * Mirrors the `{ field?: boolean }` shape used for per-field lock maps.
+ *
+ * Lives here (and is re-exported by validation.js for its existing callers) for
+ * the same TDZ-cycle reason as `emptyToUndefined` above: per-domain schema files
+ * like `brainValidation.js` need it and must not import validation.js.
+ */
+export const optionalBooleanMap = (keys) =>
+ Object.fromEntries(keys.map((k) => [k, z.boolean().optional()]));
+
/**
* Preprocess helper: treat an empty-string UI sentinel as an explicit `null`
* (a *clear*), distinct from `emptyToUndefined`'s "not sent". Use this when an
diff --git a/server/routes/brainCapture.js b/server/routes/brainCapture.js
index 9910dc6966..f8bd2b1876 100644
--- a/server/routes/brainCapture.js
+++ b/server/routes/brainCapture.js
@@ -24,8 +24,8 @@ const router = Router();
* Capture a thought, classify it, and store it
*/
router.post('/capture', asyncHandler(async (req, res) => {
- const { text, providerOverride, modelOverride, creative } = validateRequest(captureInputSchema, req.body);
- const result = await brainService.captureThought(text, providerOverride, modelOverride, { creative });
+ const { text, providerOverride, modelOverride, creative, repoIntake } = validateRequest(captureInputSchema, req.body);
+ const result = await brainService.captureThought(text, providerOverride, modelOverride, { creative, repoIntake });
res.json(result);
}));
diff --git a/server/routes/brainLinks.js b/server/routes/brainLinks.js
index 4a8cadea1b..a495878d28 100644
--- a/server/routes/brainLinks.js
+++ b/server/routes/brainLinks.js
@@ -21,9 +21,8 @@ import {
bucketReorderSchema
} from '../lib/brainValidation.js';
import * as githubCloner from '../services/githubCloner.js';
-import * as cos from '../services/cos.js';
-import { randomUUID } from 'crypto';
-import { prepareScanReportDirectory, reportPathForId, getScanReport } from '../services/malwareScanReports.js';
+import { queueMalwareScan } from '../services/repoIntake.js';
+import { getScanReport } from '../services/malwareScanReports.js';
const router = Router();
@@ -241,9 +240,8 @@ router.post('/links/:id/open-folder', asyncHandler(async (req, res) => {
/**
* POST /api/brain/links/:id/scan
* Queue a read-only malware/risk scan (do:scan) against the cloned repo.
- * Creates a CoS user task whose context inlines the do:scan command body
- * with the repo's localPath baked in as SCAN_DIR. The agent writes its
- * markdown report to ~/.claude/scans/.
+ * The task shape lives in services/repoIntake.js so this button and the
+ * capture-time "scan for malware" checkbox queue exactly the same run.
*/
router.post('/links/:id/scan', asyncHandler(async (req, res) => {
const link = await brainService.getLinkById(req.params.id);
@@ -256,51 +254,22 @@ router.post('/links/:id/scan', asyncHandler(async (req, res) => {
code: 'NOT_CLONED'
});
}
- if (!existsSync(link.localPath)) {
- throw new ServerError('Local clone folder does not exist', {
- status: 400,
- code: 'PATH_NOT_FOUND'
- });
- }
- const reportId = randomUUID();
- const reportPath = reportPathForId(reportId);
- await prepareScanReportDirectory();
- const repoLabel = link.title || link.url;
- const description = `Malware scan: ${repoLabel}`;
- // Carry the BARE command (`metadata.slashdoCommand`) rather than inlining the
- // ~65KB expanded body here: the prompt builder renders the right invocation
- // shape once the provider is known AND inlines the body then (a codex host gets
- // a skill, not `/do:scan`). Inlining here also persisted the whole body as one
- // line of TASKS.md, rewritten on every task mutation and shipped in each
- // peer-sync payload. Matches POST /api/cos/tasks/slashdo (#3114).
- const context = `Run the scan workflow against the cloned repository at: \`${link.localPath}\`
-
-Use that path as SCAN_DIR. Adhere to every Operational Invariant in the workflow body — this is a hostile-until-proven-safe audit. End the report with exactly one verdict heading: \`## Verdict: CLEAN\`, \`## Verdict: CAUTION\`, or \`## Verdict: DANGEROUS\`. When complete, summarize the verdict and top findings in your final response.`;
-
- const result = await cos.addTask(
- {
- description,
- context,
- slashdoCommand: 'scan',
- slashdoArgs: `--report-path-allow-anywhere --report-path ${JSON.stringify(reportPath)}`,
- malwareScan: { linkId: link.id, reportId },
- useWorktree: false,
- openPR: false,
- simplify: false,
- reviewLoop: false
- },
- 'user'
- );
- if (result?.duplicate) {
- throw new ServerError('A scan for this repo is already pending or in progress', {
- status: 409,
- code: 'DUPLICATE_TASK'
- });
+ // `not-cloned` here means the recorded localPath is gone from disk — the
+ // service re-checks existence so the background capture path can't queue a
+ // scan against a directory that was deleted after the clone.
+ const result = await queueMalwareScan(link);
+ if (!result.queued) {
+ throw result.reason === 'duplicate'
+ ? new ServerError('A scan for this repo is already pending or in progress', { status: 409, code: 'DUPLICATE_TASK' })
+ : new ServerError('Local clone folder does not exist', { status: 400, code: 'PATH_NOT_FOUND' });
}
+ // Record the pending scan the same way the capture-time path does, so a
+ // reload shows the "Scan queued" chip instead of re-arming the button (whose
+ // second click would 409 as a duplicate).
+ await brainService.updateLink(link.id, result.linkPatch);
- console.log(`🛡️ Queued malware scan: link=${link.id} path=${link.localPath} task=${result.id}`);
- res.json({ message: 'Scan queued', taskId: result.id, linkId: link.id, scanPath: link.localPath });
+ res.json({ message: 'Scan queued', taskId: result.taskId, linkId: link.id, scanPath: link.localPath });
}));
router.get('/links/:id/scan-report', asyncHandler(async (req, res) => {
diff --git a/server/services/brain.js b/server/services/brain.js
index 2d8ffa63b2..b0304a87b6 100644
--- a/server/services/brain.js
+++ b/server/services/brain.js
@@ -21,6 +21,7 @@ import { getDomainBudgetStatus, recordDomainUsage } from './domainUsage.js';
import { deleteMemoryAssets } from './chatgptImport.js';
import * as githubCloner from './githubCloner.js';
import { parseBareUrl } from '../lib/bareUrl.js';
+import { normalizeRepoIntake } from '../lib/repoIntakeActions.js';
import {
classifierOutputSchema,
digestOutputSchema,
@@ -135,7 +136,7 @@ function safeParseJsonResponse(content) {
* Returns immediately after creating the inbox entry.
* AI classification runs in the background and emits a socket event on completion.
*/
-export async function captureThought(text, providerOverride, modelOverride, { creative = false } = {}) {
+export async function captureThought(text, providerOverride, modelOverride, { creative = false, repoIntake = null } = {}) {
// A capture that is nothing but a URL is a bookmark, not a thought: file it
// straight to Links exactly as the Links tab would, and skip the classifier
// LLM call entirely. This outranks the creative flag — a bare URL carries no
@@ -143,7 +144,7 @@ export async function captureThought(text, providerOverride, modelOverride, { cr
// Creative toggle for a URL rather than the two rules disagreeing.
const bareUrl = parseBareUrl(text);
if (bareUrl) {
- return captureUrlAsLink(bareUrl, text);
+ return captureUrlAsLink(bareUrl, text, repoIntake);
}
const meta = await storage.loadMeta();
@@ -211,10 +212,15 @@ export async function captureThought(text, providerOverride, modelOverride, { cr
* inbox entry (so the capture is still auditable from the inbox, showing where
* it went). Re-pasting a URL that's already saved reuses that link instead of
* failing the capture — the inbox entry then points at the existing bookmark.
+ *
+ * `repoIntake` carries the capture box's opt-in post-clone agent actions
+ * (malware scan / repo study). It applies only to a NEW GitHub link: re-pasting
+ * an already-saved URL performs no clone, so there is no fresh clone for the
+ * agents to read and re-queueing them silently would be a surprise.
*/
-async function captureUrlAsLink(url, capturedText) {
+async function captureUrlAsLink(url, capturedText, repoIntake = null) {
const existing = await storage.getLinkByUrl(url);
- const link = existing || await createLinkFromUrl(url);
+ const link = existing || await createLinkFromUrl(url, { repoIntake });
// No `classification` block: nothing classified this — the destination was
// decided by shape, not by a model, so there is no confidence or extraction to
@@ -236,10 +242,25 @@ async function captureUrlAsLink(url, capturedText) {
link,
message: existing
? 'Already saved in Links.'
- : (link.isGitHubRepo ? 'GitHub repo saved to Links!' : 'Saved to Links!')
+ : (link.isGitHubRepo ? repoCaptureMessage(link.repoIntake) : 'Saved to Links!')
};
}
+/**
+ * What a freshly-captured GitHub repo link tells the user will happen next. The
+ * clone is always implied; the agent runs only when they ticked the boxes, and
+ * they only start once the clone lands.
+ */
+function repoCaptureMessage(repoIntake) {
+ const queued = [
+ repoIntake?.malwareScan && 'malware scan',
+ repoIntake?.learn && 'repo study',
+ ].filter(Boolean);
+ return queued.length
+ ? `GitHub repo saved — cloning, then queueing ${queued.join(' + ')}.`
+ : 'GitHub repo saved to Links — cloning now.';
+}
+
/**
* Background AI classification for a captured thought.
* Updates the inbox entry and emits a brain:classified event when done.
@@ -930,18 +951,40 @@ function hostnameFromUrl(url) {
* Clone a GitHub repo in the background, tracking progress on the link record.
* Runs outside the request lifecycle, so every failure is caught and recorded
* on the link rather than left to bubble.
+ *
+ * The opt-in agent actions the user ticked at capture time are read off the
+ * link's own `repoIntake` field, not passed in — so EVERY path that reaches a
+ * successful clone honors them, including the Links tab's Clone/Retry button
+ * after a first clone failed. They dispatch only after the clone SUCCEEDS:
+ * there is nothing on disk to read before that, and a failed clone must not
+ * queue an agent against a path that doesn't exist.
*/
export async function cloneRepoInBackground(linkId, url) {
await storage.updateLink(linkId, { cloneStatus: 'cloning' });
githubCloner.cloneRepo(url)
.then(async (result) => {
- await storage.updateLink(linkId, {
+ const link = await storage.updateLink(linkId, {
localPath: result.localPath,
cloneStatus: 'cloned',
cloneError: null
});
console.log(`✅ Background clone complete: ${linkId}`);
+ // `link` is null when the user deleted the bookmark mid-clone — nothing
+ // left to scan or study. The whole intake is chained off its OWN catch, so
+ // a queueing failure can't rewrite a clone that genuinely succeeded as
+ // `failed` via the outer handler below.
+ if (!link?.repoIntake) return;
+ // Dynamic on purpose, and NOT for boot cost — routes/brainLinks.js already
+ // imports repoIntake.js statically, so the CoS task graph is loaded either
+ // way. It keeps that graph out of *brain.js's own module graph*, which the
+ // heavily-mocked brain.test.js suite instantiates; a static edge drags
+ // cos.js → taskSchedule.js in and the suite dies on an incomplete mock.
+ // Same reason malwareScanReports.js imports brain.js this way.
+ await import('./repoIntake.js')
+ .then(({ runRepoIntake }) => runRepoIntake(link, link.repoIntake))
+ .then(patch => (Object.keys(patch).length ? storage.updateLink(linkId, patch) : null))
+ .catch(err => console.error(`❌ Post-clone intake failed for ${linkId}: ${err.message}`));
})
.catch(async (err) => {
await storage.updateLink(linkId, {
@@ -962,11 +1005,15 @@ export async function cloneRepoInBackground(linkId, url) {
* link) — this always creates.
*/
export async function createLinkFromUrl(url, {
- title, description, linkType, tags, bucketId, bucketOrder, autoClone
+ title, description, linkType, tags, bucketId, bucketOrder, autoClone, repoIntake
} = {}) {
const parsed = githubCloner.parseGitHubUrl(url);
const isGitHubRepo = !!parsed;
const shouldClone = isGitHubRepo && autoClone !== false;
+ // Opt-in post-clone agent actions. Only meaningful when a clone will actually
+ // happen, and persisted on the link so the record says what was asked for even
+ // if the clone is still running.
+ const intake = shouldClone ? normalizeRepoIntake(repoIntake) : null;
// Derive a readable default title: repo slug for GitHub, hostname for plain
// URLs (so quick-added bucket chips read "example.com" instead of the full URL).
@@ -986,6 +1033,7 @@ export async function createLinkFromUrl(url, {
localPath: null,
cloneStatus: shouldClone ? 'pending' : 'none',
cloneError: null,
+ ...(intake ? { repoIntake: intake } : {}),
...(bucketId !== undefined ? { bucketId } : {}),
...(bucketOrder !== undefined ? { bucketOrder } : {})
});
diff --git a/server/services/brain.test.js b/server/services/brain.test.js
index fa20e65251..627e85f442 100644
--- a/server/services/brain.test.js
+++ b/server/services/brain.test.js
@@ -332,6 +332,88 @@ describe('brain service', () => {
expect.objectContaining({ status: 'classifying' })
);
});
+
+ // The post-clone agent opt-ins (malware scan / repo study). The dispatch
+ // itself lives in services/repoIntake.js and is tested there; what matters
+ // here is that a request only survives the capture path when a clone will
+ // actually happen, since the agents read the clone.
+ describe('repoIntake', () => {
+ const asGitHub = () => {
+ githubCloner.parseGitHubUrl.mockReturnValue({ owner: 'acme', repo: 'widgets', isGitHub: true });
+ githubCloner.cloneRepo.mockResolvedValue({ localPath: '/repos/acme/widgets' });
+ };
+
+ it('records the requested actions on a newly captured repo link', async () => {
+ asGitHub();
+ const result = await captureThought('https://github.com/acme/widgets', undefined, undefined, {
+ repoIntake: { malwareScan: true, learn: true },
+ });
+
+ expect(storage.createLink).toHaveBeenCalledWith(expect.objectContaining({
+ repoIntake: { malwareScan: true, learn: true }
+ }));
+ expect(result.message).toMatch(/malware scan \+ repo study/);
+ });
+
+ it('normalizes a partial request so an absent action is explicitly off', async () => {
+ asGitHub();
+ await captureThought('https://github.com/acme/widgets', undefined, undefined, {
+ repoIntake: { learn: true },
+ });
+
+ expect(storage.createLink).toHaveBeenCalledWith(expect.objectContaining({
+ repoIntake: { malwareScan: false, learn: true }
+ }));
+ });
+
+ it('stores nothing when every box is unticked', async () => {
+ asGitHub();
+ await captureThought('https://github.com/acme/widgets', undefined, undefined, {
+ repoIntake: { malwareScan: false, learn: false },
+ });
+
+ expect(storage.createLink).toHaveBeenCalledWith(
+ expect.not.objectContaining({ repoIntake: expect.anything() })
+ );
+ });
+
+ it('drops the request for a non-GitHub URL, which is never cloned', async () => {
+ await captureThought('https://example.com', undefined, undefined, {
+ repoIntake: { malwareScan: true, learn: true },
+ });
+
+ expect(storage.createLink).toHaveBeenCalledWith(
+ expect.not.objectContaining({ repoIntake: expect.anything() })
+ );
+ });
+
+ // The intent is persisted on the link and read back off it, so the Links
+ // tab's Clone/Retry button (which calls cloneRepoInBackground with no
+ // intake argument) honors a request whose first clone failed.
+ it('is stored on the link, not only threaded through the first clone', async () => {
+ asGitHub();
+ await captureThought('https://github.com/acme/widgets', undefined, undefined, {
+ repoIntake: { malwareScan: true, learn: false },
+ });
+
+ const [created] = storage.createLink.mock.calls[0];
+ expect(created.repoIntake).toEqual({ malwareScan: true, learn: false });
+ });
+
+ it('does not re-run agents when a saved repo URL is pasted again', async () => {
+ asGitHub();
+ storage.getLinkByUrl.mockResolvedValue({ id: 'link-existing', isGitHubRepo: true });
+
+ const result = await captureThought('https://github.com/acme/widgets', undefined, undefined, {
+ repoIntake: { malwareScan: true, learn: true },
+ });
+
+ // No new link, so no new clone — and nothing for the agents to read.
+ expect(storage.createLink).not.toHaveBeenCalled();
+ expect(githubCloner.cloneRepo).not.toHaveBeenCalled();
+ expect(result.message).toMatch(/already saved/i);
+ });
+ });
});
// ===========================================================================
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index e9ca1e5293..261d2ea8bd 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -42,7 +42,7 @@ import { getCodeReviewDefaults } from './codeReview.js';
import { isHeldByOther, getClaimOwner } from './cosTaskClaim.js';
import { ensureInstanceId } from './instances.js';
import { PR_COMPLETION_VALUES } from '../lib/prDisposition.js';
-import { resolveAppWorkTracker, isFileTracker, formatTrackerInstructions, TRACKER_FILING_PRESETS, TRACKER_FILING_TASK_TYPES } from '../lib/workTracker.js';
+import { resolveTrackerFilingBlock } from '../lib/workTracker.js';
/**
* Block a task that has exceeded the max spawn limit. Returns true if blocked.
@@ -2326,37 +2326,6 @@ async function resolveIssueReconcileBlock(app, taskType, metadata, taskSchedule)
return { skip: false, block };
}
-/**
- * Resolve the {trackerInstructions} block naming where a tracker-filing task
- * records what it found, plus the two metadata signals derived from the SAME
- * resolved tracker so they can never disagree with the instructions the agent
- * actually got (#3140, #3102):
- * - `workTracker` — traceability
- * - `worktreeChangesExpected` — the PLAN.md path commits checklist items
- * (dirty tree); the github/gitlab/jira paths file issues/tickets out of band
- * and legitimately leave the tree CLEAN.
- *
- * Mirrors `triggerReferenceAnalysis` (referenceRepos.js, the on-commit path)
- * rather than restating its block table — both run `resolveAppWorkTracker` →
- * `formatTrackerInstructions` / `isFileTracker`.
- *
- * A TRACKER-FILING type reads the app read-only and delivers its findings as
- * items in the app's tracker rather than as a commit. The set is derived from
- * `TRACKER_FILING_PRESETS`, so a type is gated in exactly when it has wording.
- *
- * Returns `{ trackerInstructions: '', workTracker: null }` for every other type.
- */
-async function resolveTrackerFilingBlock(app, taskType) {
- if (!TRACKER_FILING_TASK_TYPES.has(taskType)) return { trackerInstructions: '', workTracker: null };
- // Never throws — degrades to the PLAN.md block, same as the on-commit path.
- const workTracker = await resolveAppWorkTracker(app).catch(() => ({ resolved: 'plan' }));
- return {
- trackerInstructions: formatTrackerInstructions(workTracker.resolved, TRACKER_FILING_PRESETS[taskType]),
- workTracker: workTracker.resolved,
- worktreeChangesExpected: isFileTracker(workTracker.resolved),
- };
-}
-
/**
* reference-watch: dynamically build {referenceData} — a Markdown chunk per ref
* configured on the app + commits since lastReviewedSha. The check persists
diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.js
index c7c73c0490..acf1627633 100644
--- a/server/services/cosTaskStore.js
+++ b/server/services/cosTaskStore.js
@@ -404,6 +404,16 @@ export async function addTask(taskData, taskType = 'user', { raw = false, ignore
if (taskData.malwareScan && typeof taskData.malwareScan === 'object' && !Array.isArray(taskData.malwareScan)) {
metadata.malwareScan = taskData.malwareScan;
}
+ // Brain link a `repo-study` run was queued from, so the completed task can be
+ // traced back to the captured repo it studied.
+ if (isPlainObject(taskData.repoStudy)) metadata.repoStudy = taskData.repoStudy;
+ // Which tracker the prompt told the agent to file into (PLAN.md / GitHub /
+ // GitLab / JIRA), mirroring the raw reference-watch dispatch in
+ // referenceRepos.js#triggerReferenceAnalysis. Beyond traceability this is
+ // what marks a ONE-OFF tracker-filing run as such, so it reaches the
+ // no-commit gate without having to masquerade as a scheduled task type —
+ // see taskTypeHooks.js#isTrackerFilingDispatch.
+ if (taskData.workTracker) metadata.workTracker = taskData.workTracker;
if (taskData.jiraTicketId) metadata.jiraTicketId = taskData.jiraTicketId;
if (taskData.jiraTicketUrl) metadata.jiraTicketUrl = taskData.jiraTicketUrl;
if (taskData.screenshots?.length > 0) metadata.screenshots = taskData.screenshots;
diff --git a/server/services/githubCloner.js b/server/services/githubCloner.js
index 9ba06d2a6a..987455d525 100644
--- a/server/services/githubCloner.js
+++ b/server/services/githubCloner.js
@@ -9,53 +9,15 @@ import { spawn } from 'child_process';
import { existsSync } from 'fs';
import { join } from 'path';
import { ensureDir, PATHS } from '../lib/fileUtils.js';
+import { parseGitHubUrl, isGitHubRepoUrl } from '../lib/githubRepoUrl.js';
// Default directory for cloned repos (can be configured in settings)
const DEFAULT_CLONE_DIR = PATHS.repos;
-/**
- * Parse GitHub URL to extract owner and repo name
- * Supports formats:
- * - https://github.com/owner/repo
- * - https://github.com/owner/repo.git
- * - [email protected]:owner/repo.git
- * - github.com/owner/repo
- */
-export function parseGitHubUrl(url) {
- if (!url) return null;
-
- // Normalize URL
- let normalized = url.trim();
-
- // Handle SSH format: [email protected]:owner/repo.git
- const sshMatch = normalized.match(/git@github\.com:([^/]+)\/([^/.]+)(?:\.git)?$/i);
- if (sshMatch) {
- return {
- owner: sshMatch[1],
- repo: sshMatch[2],
- isGitHub: true
- };
- }
-
- // Handle HTTPS format: https://github.com/owner/repo or github.com/owner/repo
- const httpsMatch = normalized.match(/(?:https?:\/\/)?github\.com\/([^/]+)\/([^/?#]+)/i);
- if (httpsMatch) {
- return {
- owner: httpsMatch[1],
- repo: httpsMatch[2].replace(/\.git$/, ''),
- isGitHub: true
- };
- }
-
- return null;
-}
-
-/**
- * Check if a URL is a GitHub repository URL
- */
-export function isGitHubRepoUrl(url) {
- return parseGitHubUrl(url) !== null;
-}
+// The owner/repo parse rule lives in lib/ so the client can mirror it — the
+// Brain capture boxes have to predict "this URL will be cloned" before submit.
+// Re-exported here so existing `githubCloner.parseGitHubUrl` callers keep working.
+export { parseGitHubUrl, isGitHubRepoUrl };
/**
* Get clone directory path
diff --git a/server/services/repoIntake.js b/server/services/repoIntake.js
new file mode 100644
index 0000000000..1e7ee6c2a0
--- /dev/null
+++ b/server/services/repoIntake.js
@@ -0,0 +1,216 @@
+/**
+ * Post-clone intake for a GitHub repo captured into the Brain.
+ *
+ * When a bare GitHub repo URL is captured (Quick Capture / the Inbox capture
+ * box), the link is cloned in the background. The user can tick two opt-in boxes
+ * at capture time to have a CoS agent pick the clone up once it lands:
+ *
+ * - `malwareScan` → the read-only `/do:scan` audit, identical to the Links
+ * tab's per-link Scan button (both go through `queueMalwareScan` here).
+ * - `learn` → a `repo-study` review: read the clone as a source of IDEAS
+ * for PortOS and file the adoptable ones into PortOS's configured work
+ * tracker. Clean-room — propose reimplementation, never copy upstream code.
+ *
+ * Both are queued only AFTER the clone succeeds (there is nothing to read
+ * before that), and only because the user asked for them in the same request —
+ * see the AI Provider Usage Policy in CLAUDE.md.
+ */
+
+import { randomUUID } from 'crypto';
+import { existsSync } from 'fs';
+import * as cos from './cos.js';
+import { getAppById, PORTOS_APP_ID } from './apps.js';
+import { prepareScanReportDirectory, reportPathForId } from './malwareScanReports.js';
+import { resolveTrackerFilingBlock } from '../lib/workTracker.js';
+import { normalizeRepoIntake } from '../lib/repoIntakeActions.js';
+
+/** `owner/repo` when the link carries GitHub metadata, else its display title. */
+const repoLabel = (link) => (
+ link?.gitHubOwner && link?.gitHubRepo
+ ? `${link.gitHubOwner}/${link.gitHubRepo}`
+ : (link?.title || link?.url || 'unknown repo')
+);
+
+/**
+ * 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.
+ */
+const isCloneReadable = (link) => Boolean(link?.localPath) && existsSync(link.localPath);
+
+/**
+ * Queue the read-only `/do:scan` malware audit against a cloned link.
+ *
+ * Shared by the Links tab's Scan button (POST /api/brain/links/:id/scan) and the
+ * capture-time opt-in, so both produce the same task shape, the same report
+ * plumbing, and the same `linkPatch` — the caller applies that patch so the
+ * pending scan is visible on the link from either entry point. Returns
+ * `{ queued: false, reason }` instead of throwing so the background path can log
+ * and move on; the route maps the reason to its status code.
+ *
+ * @returns {Promise<{ queued: boolean, reason?: string, taskId?: string, linkPatch?: object }>}
+ */
+export async function queueMalwareScan(link) {
+ if (!isCloneReadable(link)) return { queued: false, reason: 'not-cloned' };
+
+ const reportId = randomUUID();
+ const reportPath = reportPathForId(reportId);
+ await prepareScanReportDirectory();
+ // Carry the BARE command (`metadata.slashdoCommand`) rather than inlining the
+ // ~65KB expanded body: the prompt builder renders the right invocation shape
+ // once the provider is known AND inlines the body then (a codex host gets a
+ // skill, not `/do:scan`). Inlining also persisted the whole body as one line of
+ // TASKS.md, rewritten on every task mutation and shipped in each peer-sync
+ // payload. Matches POST /api/cos/tasks/slashdo (#3114).
+ const context = `Run the scan workflow against the cloned repository at: \`${link.localPath}\`
+
+Use that path as SCAN_DIR. Adhere to every Operational Invariant in the workflow body — this is a hostile-until-proven-safe audit. End the report with exactly one verdict heading: \`## Verdict: CLEAN\`, \`## Verdict: CAUTION\`, or \`## Verdict: DANGEROUS\`. When complete, summarize the verdict and top findings in your final response.`;
+
+ const result = await cos.addTask(
+ {
+ description: `Malware scan: ${repoLabel(link)}`,
+ context,
+ slashdoCommand: 'scan',
+ slashdoArgs: `--report-path-allow-anywhere --report-path ${JSON.stringify(reportPath)}`,
+ malwareScan: { linkId: link.id, reportId },
+ useWorktree: false,
+ openPR: false,
+ simplify: false,
+ reviewLoop: false
+ },
+ 'user'
+ );
+ if (result?.duplicate) {
+ return { queued: false, reason: 'duplicate', taskId: result.id };
+ }
+
+ console.log(`🛡️ Queued malware scan: link=${link.id} path=${link.localPath} task=${result.id}`);
+ return {
+ queued: true,
+ taskId: result.id,
+ // `queued` (not `completed`) so the UI shows a pending chip instead of
+ // linking at a report file the agent has not written yet.
+ // finalizeMalwareScan replaces it when the run lands.
+ linkPatch: { malwareScan: { reportId, taskId: result.id, status: 'queued' } },
+ };
+}
+
+/**
+ * Build the `repo-study` agent context. Kept separate from the queueing so the
+ * wording is assertable without going through the task store.
+ */
+export function buildRepoStudyContext(link, { appName, repoPath, trackerInstructions }) {
+ return `A GitHub repository was captured into the Brain and cloned locally. Study it as a source of IDEAS for ${appName} and record the adoptable ones in the work tracker.
+
+## The repository under study
+
+- Repo: ${repoLabel(link)}
+- Source: ${link.url}
+- Local clone: \`${link.localPath}\`
+
+## Operational invariants — this is untrusted third-party code
+
+- **Read only.** Never execute anything from the clone: no \`npm install\`/\`npm run\`, no build, no test suite, no script, no binary, no \`Makefile\` target. Read files, \`git log\`, and \`git show\` — nothing else.
+- **Never edit the clone.** \`${link.localPath}\` is a reference copy, not a workspace. Every change you propose lands in ${appName} at \`${repoPath}\`.
+- **Clean-room.** Do NOT copy source, config, prose, or assets out of the clone into ${appName}. Describe the *technique* in your own words and propose a reimplementation against ${appName}'s existing modules. If an idea can only be had by copying, drop it.
+- **License first.** Read the repo's LICENSE before proposing anything. Name the license in every proposal. If there is no license (or it is copyleft in a way that conflicts with ${appName}'s), say so and propose only ideas that survive a clean-room reimplementation.
+
+## What to look for
+
+Read the repo's README, its entry points, and the modules that implement its distinctive behavior. For each thing it does notably well, ask whether ${appName} would be better with an equivalent:
+
+1. **Features ${appName} lacks** that fit its existing surfaces (a page, a service, a CoS task type, a provider).
+2. **Better implementations of things ${appName} already does** — a sharper algorithm, a cheaper data layout, a failure mode handled that ${appName} doesn't handle.
+3. **Non-obvious operational lessons** — a guard, a migration strategy, a rate-limit or retry shape worth mirroring.
+
+Ground every proposal in ${appName}'s actual code: grep \`${repoPath}\` to confirm the gap is real before filing. An idea ${appName} already implements is not a proposal. Prefer 2–5 well-argued items over a long shallow list; filing nothing is a legitimate outcome — say so in your final summary.
+
+## Where to record proposals
+
+${trackerInstructions}
+
+## Final summary
+
+End with: the studied repo, its license, how many proposals you filed (with their slugs/issue numbers), and anything you deliberately rejected and why.`;
+}
+
+/**
+ * Queue the `repo-study` review of a cloned link against PortOS.
+ *
+ * @returns {Promise<{ queued: boolean, reason?: string, taskId?: string, linkPatch?: object }>}
+ */
+export async function queueRepoStudy(link) {
+ if (!isCloneReadable(link)) return { queued: false, reason: 'not-cloned' };
+
+ const app = await getAppById(PORTOS_APP_ID);
+ if (!app?.repoPath) return { queued: false, reason: 'app-not-found' };
+
+ // Same four-part resolution every tracker-filing dispatch runs: the block
+ // telling the agent where to file, the tracker it names, and the
+ // `worktreeChangesExpected` flag derived from that SAME tracker so the two can
+ // never disagree (a github/gitlab/jira run files out of band and leaves the
+ // tree clean; without the flag it is scored `idle-no-changes`, #3102).
+ const { trackerInstructions, workTracker, worktreeChangesExpected } =
+ await resolveTrackerFilingBlock(app, 'repo-study');
+
+ const result = await cos.addTask(
+ {
+ description: `Repo study: ${repoLabel(link)} — what can ${app.name} learn from it?`,
+ context: buildRepoStudyContext(link, {
+ appName: app.name,
+ repoPath: app.repoPath,
+ trackerInstructions: trackerInstructions
+ .replace(/\{appName\}/g, () => app.name)
+ .replace(/\{repoPath\}/g, () => app.repoPath),
+ }),
+ // The deliverable is tracker items, not code — the agent reads PortOS and
+ // the clone, then files. No worktree, no PR, no review loop.
+ useWorktree: false,
+ openPR: false,
+ simplify: false,
+ reviewLoop: false,
+ worktreeChangesExpected,
+ // Also the marker that lets this ONE-OFF run reach the no-commit gate
+ // without pretending to be a scheduled task type — see
+ // taskTypeHooks.js#isTrackerFilingDispatch.
+ workTracker,
+ repoStudy: { linkId: link.id },
+ },
+ 'user'
+ );
+ if (result?.duplicate) {
+ return { queued: false, reason: 'duplicate', taskId: result.id };
+ }
+
+ console.log(`📚 Queued repo study: link=${link.id} repo=${repoLabel(link)} task=${result.id}`);
+ return {
+ queued: true,
+ taskId: result.id,
+ linkPatch: { repoStudy: { taskId: result.id, queuedAt: new Date().toISOString() } },
+ };
+}
+
+const INTAKE_QUEUERS = { malwareScan: queueMalwareScan, learn: queueRepoStudy };
+
+/**
+ * Run the intake actions the user opted into. Called from the background clone
+ * once the clone lands, so it must never throw — a failed queue is logged, not
+ * propagated into the clone path, and one action failing must not take the other
+ * down with it.
+ *
+ * @returns {Promise<object>} merged link patch for whatever was queued (empty
+ * when nothing was requested or everything failed).
+ */
+export async function runRepoIntake(link, intake) {
+ const requested = normalizeRepoIntake(intake);
+ if (!requested) return {};
+
+ let patch = {};
+ for (const [key, queue] of Object.entries(INTAKE_QUEUERS)) {
+ if (!requested[key]) continue;
+ const result = await queue(link).catch(err => ({ queued: false, reason: err.message }));
+ if (result.queued) patch = { ...patch, ...result.linkPatch };
+ else console.error(`❌ Capture-time ${key} not queued for link ${link.id}: ${result.reason}`);
+ }
+ return patch;
+}
diff --git a/server/services/repoIntake.test.js b/server/services/repoIntake.test.js
new file mode 100644
index 0000000000..dde2ee7cb3
--- /dev/null
+++ b/server/services/repoIntake.test.js
@@ -0,0 +1,197 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const addTask = vi.fn();
+const getAppById = vi.fn();
+const readOriginRemoteUrl = vi.fn();
+const existsSync = vi.fn();
+
+vi.mock('./cos.js', () => ({ addTask: (...args) => addTask(...args) }));
+vi.mock('./apps.js', () => ({
+ PORTOS_APP_ID: 'portos-default',
+ getAppById: (...args) => getAppById(...args),
+}));
+vi.mock('./malwareScanReports.js', () => ({
+ prepareScanReportDirectory: vi.fn(async () => {}),
+ reportPathForId: (id) => `/scans/${id}.md`,
+}));
+vi.mock('fs', () => ({ existsSync: (...args) => existsSync(...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.
+vi.mock('../lib/gitRemote.js', () => ({
+ readOriginRemoteUrl: (...args) => readOriginRemoteUrl(...args),
+}));
+
+const { queueMalwareScan, queueRepoStudy, runRepoIntake, buildRepoStudyContext } = await import('./repoIntake.js');
+
+const LINK = {
+ id: 'link-1',
+ url: 'https://github.com/example-owner/example-repo',
+ title: 'example-owner/example-repo',
+ gitHubOwner: 'example-owner',
+ gitHubRepo: 'example-repo',
+ localPath: '/repos/example-owner/example-repo',
+};
+
+const APP = { id: 'portos-default', name: 'PortOS', repoPath: '/srv/portos', workTracker: 'github' };
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ existsSync.mockReturnValue(true);
+ getAppById.mockResolvedValue(APP);
+ readOriginRemoteUrl.mockResolvedValue(null);
+ addTask.mockImplementation(async () => ({ id: 'task-abc' }));
+});
+
+describe('queueMalwareScan', () => {
+ it('queues the bare slashdo command with the clone path as SCAN_DIR', async () => {
+ const result = await queueMalwareScan(LINK);
+
+ expect(result.queued).toBe(true);
+ expect(result.taskId).toBe('task-abc');
+ const [taskData, taskType] = addTask.mock.calls[0];
+ const { reportId } = taskData.malwareScan;
+ expect(taskType).toBe('user');
+ expect(taskData.slashdoCommand).toBe('scan');
+ // The ~65KB command body must NOT be inlined into the task context (#3114).
+ expect(taskData.context).toContain(LINK.localPath);
+ expect(taskData.context.length).toBeLessThan(2000);
+ expect(taskData.slashdoArgs).toContain(`/scans/${reportId}.md`);
+ expect(taskData.malwareScan).toEqual({ linkId: 'link-1', reportId: expect.any(String) });
+ expect(taskData.useWorktree).toBe(false);
+ expect(taskData.openPR).toBe(false);
+ });
+
+ // Both callers (the Links tab's Scan button and the capture-time checkbox)
+ // apply this, so a pending scan is visible on the link from either entry point
+ // instead of the button re-arming into a 409 after a reload.
+ it('returns a link patch stamping the scan as pending, not as a readable report', () => {
+ return queueMalwareScan(LINK).then(result => {
+ expect(result.linkPatch).toEqual({
+ malwareScan: { reportId: expect.any(String), taskId: 'task-abc', status: 'queued' },
+ });
+ });
+ });
+
+ it('refuses when the recorded clone path is gone from disk', async () => {
+ existsSync.mockReturnValue(false);
+ expect(await queueMalwareScan(LINK)).toEqual({ queued: false, reason: 'not-cloned' });
+ expect(addTask).not.toHaveBeenCalled();
+ });
+
+ it('reports a rejected duplicate instead of claiming a fresh queue', async () => {
+ addTask.mockResolvedValue({ id: 'task-existing', duplicate: true });
+ expect(await queueMalwareScan(LINK)).toEqual({ queued: false, reason: 'duplicate', taskId: 'task-existing' });
+ });
+});
+
+describe('queueRepoStudy', () => {
+ it('files into the app\'s resolved tracker and expects no commit on a forge tracker', async () => {
+ const result = await queueRepoStudy(LINK);
+
+ expect(result.queued).toBe(true);
+ expect(result.linkPatch).toEqual({ repoStudy: { taskId: 'task-abc', queuedAt: expect.any(String) } });
+ const [taskData] = addTask.mock.calls[0];
+ expect(taskData.workTracker).toBe('github');
+ // A github-tracker run files issues out of band and leaves the tree clean —
+ // flagging otherwise scores every successful run as `idle-no-changes`.
+ expect(taskData.worktreeChangesExpected).toBe(false);
+ expect(taskData.repoStudy).toEqual({ linkId: 'link-1' });
+ expect(taskData.context).toContain('gh issue create');
+ expect(taskData.context).toContain('repo-study-');
+ });
+
+ // `analysisType` enrolls a task in taskSchedule's per-type consecutive-failure
+ // ledger (agentFinalization.js), which auto-parks and notifies. A hand-queued
+ // repo study has no schedule to park, so it must reach the no-commit gate via
+ // `workTracker` instead — see taskTypeHooks.js#isTrackerFilingDispatch.
+ it('does not masquerade as a scheduled task type', async () => {
+ await queueRepoStudy(LINK);
+ expect(addTask.mock.calls[0][0].analysisType).toBeUndefined();
+ });
+
+ it('expects a commit on a PLAN.md tracker, where proposals dirty the tree', async () => {
+ getAppById.mockResolvedValue({ ...APP, workTracker: 'plan' });
+ await queueRepoStudy(LINK);
+ const [taskData] = addTask.mock.calls[0];
+ expect(taskData.workTracker).toBe('plan');
+ expect(taskData.worktreeChangesExpected).toBe(true);
+ expect(taskData.context).toContain('PLAN.md');
+ });
+
+ it('degrades to the PLAN.md block when the origin lookup fails', async () => {
+ getAppById.mockResolvedValue({ ...APP, workTracker: 'auto' });
+ readOriginRemoteUrl.mockRejectedValue(new Error('not a git repository'));
+ await queueRepoStudy(LINK);
+ const [taskData] = addTask.mock.calls[0];
+ expect(taskData.workTracker).toBe('plan');
+ expect(taskData.context).toContain('PLAN.md');
+ });
+
+ it('expands the tracker block\'s {appName}/{repoPath} placeholders', async () => {
+ getAppById.mockResolvedValue({ ...APP, workTracker: 'plan' });
+ await queueRepoStudy(LINK);
+ const { context } = addTask.mock.calls[0][0];
+ expect(context).not.toMatch(/\{appName\}|\{repoPath\}/);
+ expect(context).toContain('/srv/portos');
+ });
+
+ it('refuses when PortOS has no repo path to file against', async () => {
+ getAppById.mockResolvedValue({ id: 'portos-default', name: 'PortOS' });
+ expect(await queueRepoStudy(LINK)).toEqual({ queued: false, reason: 'app-not-found' });
+ expect(addTask).not.toHaveBeenCalled();
+ });
+});
+
+describe('buildRepoStudyContext', () => {
+ const context = () => buildRepoStudyContext(LINK, {
+ appName: 'PortOS',
+ repoPath: '/srv/portos',
+ trackerInstructions: 'FILE HERE',
+ });
+
+ it('forbids executing or editing the untrusted clone', () => {
+ const body = context();
+ expect(body).toMatch(/Never execute anything from the clone/);
+ expect(body).toMatch(/Never edit the clone/);
+ expect(body).toContain(LINK.localPath);
+ });
+
+ it('states the clean-room and license rules the proposals depend on', () => {
+ const body = context();
+ expect(body).toMatch(/Clean-room/);
+ expect(body).toMatch(/LICENSE/);
+ });
+});
+
+describe('runRepoIntake', () => {
+ it('does nothing when the user ticked nothing', async () => {
+ expect(await runRepoIntake(LINK, { malwareScan: false, learn: false })).toEqual({});
+ expect(addTask).not.toHaveBeenCalled();
+ });
+
+ it('queues only the ticked action and returns its link patch', async () => {
+ const patch = await runRepoIntake(LINK, { learn: true });
+ expect(addTask).toHaveBeenCalledTimes(1);
+ expect(patch.malwareScan).toBeUndefined();
+ expect(patch.repoStudy).toEqual({ taskId: 'task-abc', queuedAt: expect.any(String) });
+ });
+
+ it('stamps a queued scan as `queued`, so the UI does not link at a missing report', async () => {
+ const patch = await runRepoIntake(LINK, { malwareScan: true });
+ expect(patch.malwareScan).toEqual({
+ reportId: expect.any(String),
+ taskId: 'task-abc',
+ status: 'queued',
+ });
+ });
+
+ it('still queues the other action when one throws', async () => {
+ addTask
+ .mockRejectedValueOnce(new Error('task store down'))
+ .mockResolvedValueOnce({ id: 'task-study' });
+ const patch = await runRepoIntake(LINK, { malwareScan: true, learn: true });
+ expect(patch.malwareScan).toBeUndefined();
+ expect(patch.repoStudy).toEqual({ taskId: 'task-study', queuedAt: expect.any(String) });
+ });
+});
diff --git a/server/services/taskTypeHooks.js b/server/services/taskTypeHooks.js
index 0b7e763670..00e72da643 100644
--- a/server/services/taskTypeHooks.js
+++ b/server/services/taskTypeHooks.js
@@ -43,7 +43,7 @@
*/
import { isFalsyMeta, isTruthyMeta } from './agentState.js';
-import { TRACKER_FILING_TASK_TYPES } from '../lib/workTracker.js';
+import { TRACKER_FILING_TASK_TYPES, CONCRETE_WORK_TRACKERS } from '../lib/workTracker.js';
// taskType → () => import('./path/to/hookModule.js'). A module may export either
// or both hooks; a missing export means "no hook of that kind for this type".
@@ -198,14 +198,39 @@ export function declaresNoCommitCriterion(task) {
// SUCCESSFUL run a validation miss and drags that provider/model's learning
// bucket toward 0% — the #2696/#3273 artifact, arriving by a third route.
if (isTruthyMeta(task?.metadata?.discardWorktree)) return true;
- // Resolved the same way isNonCommittingCoordinatorTask (and the learning
- // bucket) resolves it, so a LIVE queue task (`analysisType`) and the archived
- // agent projection (`taskAnalysisType`) agree.
- const type = task?.metadata?.analysisType || task?.metadata?.taskAnalysisType || task?.taskType || null;
- if (!TRACKER_FILING_TASK_TYPES.has(type)) return false;
+ if (!isTrackerFilingDispatch(task)) return false;
return isFalsyMeta(task?.metadata?.worktreeChangesExpected);
}
+/**
+ * Whether this task was dispatched by a TRACKER-FILING path — the gate in front
+ * of the `worktreeChangesExpected` read above (see that doc comment for why the
+ * flag alone is not enough).
+ *
+ * Two shapes qualify, because tracker-filing runs arrive two ways:
+ *
+ * 1. A SCHEDULED type in `TRACKER_FILING_PRESETS` (`reference-watch`, `ux`).
+ * Resolved the same way isNonCommittingCoordinatorTask (and the learning
+ * bucket) resolves it, so a LIVE queue task (`analysisType`) and the
+ * archived agent projection (`taskAnalysisType`) agree.
+ * 2. A one-off task whose dispatch stamped `metadata.workTracker` — the
+ * concrete tracker the `{trackerInstructions}` block told the agent to file
+ * into. Only a tracker-filing dispatch writes it (repoIntake.js's
+ * `repo-study`, referenceRepos.js#triggerReferenceAnalysis), and it is NOT
+ * in cosValidation's per-app `taskMetadata` ALLOWED keys, so unlike
+ * `worktreeChangesExpected` a user cannot set it on an unrelated task type.
+ *
+ * Without (2), a hand-queued tracker-filing run could only reach this gate by
+ * masquerading as a scheduled type — which would also enroll it in
+ * taskSchedule's per-type consecutive-failure ledger (agentFinalization.js) and
+ * auto-park a "type" no schedule owns.
+ */
+function isTrackerFilingDispatch(task) {
+ const type = task?.metadata?.analysisType || task?.metadata?.taskAnalysisType || task?.taskType || null;
+ if (TRACKER_FILING_TASK_TYPES.has(type)) return true;
+ return CONCRETE_WORK_TRACKERS.includes(task?.metadata?.workTracker);
+}
+
/**
* Resolve the pre-agent input hook for a task type, or null if it has none.
* `buildTaskInput({ app, taskType })` → `{ prompt?, providerId?, model?, hookMetadata?, skip? }`
diff --git a/server/services/taskTypeHooks.noCommit.test.js b/server/services/taskTypeHooks.noCommit.test.js
new file mode 100644
index 0000000000..c4bbc723cb
--- /dev/null
+++ b/server/services/taskTypeHooks.noCommit.test.js
@@ -0,0 +1,73 @@
+/**
+ * `declaresNoCommitCriterion` — which tasks are exempt from the
+ * `[task-<id>]` commit success check.
+ *
+ * The exemption drives provider/model learning buckets: a wrongly-included task
+ * scores every SUCCESSFUL run as a validation miss (#2696/#3273), and a wrongly
+ * EXCLUDED one records a run that committed nothing as a pass.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { declaresNoCommitCriterion } from './taskTypeHooks.js';
+
+const task = (metadata) => ({ id: 'task-1', metadata });
+
+describe('declaresNoCommitCriterion', () => {
+ it('holds an ordinary task to the commit check', () => {
+ expect(declaresNoCommitCriterion(task({}))).toBe(false);
+ expect(declaresNoCommitCriterion(task({ analysisType: 'security' }))).toBe(false);
+ });
+
+ it('exempts a discarded worktree, which cannot leave a commit by construction', () => {
+ expect(declaresNoCommitCriterion(task({ discardWorktree: true }))).toBe(true);
+ // Metadata round-trips through TASKS.md as text.
+ expect(declaresNoCommitCriterion(task({ discardWorktree: 'true' }))).toBe(true);
+ });
+
+ describe('tracker-filing runs', () => {
+ it('exempts a SCHEDULED type whose dispatch derived a clean tree', () => {
+ expect(declaresNoCommitCriterion(task({
+ analysisType: 'reference-watch',
+ worktreeChangesExpected: false,
+ }))).toBe(true);
+ });
+
+ it('exempts a ONE-OFF run marked only by its resolved tracker', () => {
+ // repoIntake.js's `repo-study` — no `analysisType`, because that would
+ // enroll it in taskSchedule's per-type failure ledger and auto-park a
+ // "type" no schedule owns.
+ expect(declaresNoCommitCriterion(task({
+ workTracker: 'github',
+ worktreeChangesExpected: false,
+ }))).toBe(true);
+ expect(declaresNoCommitCriterion(task({
+ workTracker: 'jira',
+ worktreeChangesExpected: 'false',
+ }))).toBe(true);
+ });
+
+ it('still holds a PLAN.md-tracker run to the check — it commits its items', () => {
+ expect(declaresNoCommitCriterion(task({
+ workTracker: 'plan',
+ worktreeChangesExpected: true,
+ }))).toBe(false);
+ });
+
+ it('does not exempt on `auto`, which is not a resolved tracker', () => {
+ expect(declaresNoCommitCriterion(task({
+ workTracker: 'auto',
+ worktreeChangesExpected: false,
+ }))).toBe(false);
+ });
+
+ // `worktreeChangesExpected` is a user-settable per-app taskMetadata override
+ // accepted for EVERY task type; setting it there is asking to skip the TUI
+ // clean-tree gate, not to disable success validation.
+ it('does not exempt the flag alone, with no tracker-filing marker', () => {
+ expect(declaresNoCommitCriterion(task({
+ analysisType: 'security',
+ worktreeChangesExpected: false,
+ }))).toBe(false);
+ });
+ });
+});