Skip to content

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

feat: Layered Intelligence http/cmd custom telemetry sources — UI + backend (#2277)

Adam Eivy8ee155122919
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 0cbb7952ee..92cbc420a8 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -163,3 +163,5 @@
- **[issue-2262] Layered Intelligence Loop — deterministic backbone (server slice).** A perpetual, per-managed-app self-improvement loop that runs as an Engine-B autonomous script job (`job-layered-intelligence`, off by default). On its schedule the handler sweeps `getActiveApps()` and, for each app whose `layeredIntelligence.enabled === true` and whose per-app interval has elapsed, runs four layers: GATHER (reads enabled sources — GOALS.md, CoS `learning.json` metrics, HEALTH_REPORT.md, PLAN.md, open tracker issues, plus app-declared `file` custom sources), REASON (`callProviderAISimple` against the active/overridden provider with a JSON-only prompt), DECIDE (deterministic scope-gate + slug/label dedup against live tracker state), and ACT (files exactly ONE issue via the app's resolved work tracker, and optionally pauses the app on a blocking issue). The reasoning model never touches code — it returns structured JSON and every side effect is deterministic handler code, so the "model must not make direct code changes" contract holds by construction. Dedup and pause are fully tracker-derived (a `<!-- lil-slug: … -->` marker + `layered-intelligence` / `layered-intelligence:blocking` labels; closed-issue suppression pinned at 30 days) — the only local state is per-app `lastRunAt` bookkeeping. Meta/self proposal scopes (`loop-meta` / `portos-self`) are double-enforced to PortOS-only so a hallucinated or hand-edited scope can't file against the loop from someone else's app. GitHub (`gh`) and GitLab (`glab`) forge filing + `plan`-tracker PLAN.md append are implemented; ships via the `DEFAULT_JOBS` catalog (merged into existing installs on boot by `applyAdditiveFields`) and the per-app config accessor's default (all sources on; PortOS gets the meta/self scopes) — so no seed file or migration is needed. Off by default; only runs as a user-enabled scheduled automation (no cold-bootstrap LLM calls). (`server/services/layeredIntelligence.js`, `server/services/autonomousJobs/layeredIntelligenceHandler.js`, `server/services/autonomousJobs/scriptHandlers.js`, `server/services/autonomousJobs/defaults.js`, `server/services/apps.js`, `server/lib/validation.js`)
- **[issue-2262] Layered Intelligence Loop — per-app config UI (client slice).** The Edit App drawer gains an "Intelligence" tab that configures the self-improvement loop per managed app: enable/disable, a run-interval preset select (hourly → weekly, with a "Custom" readout for a hand-set cadence), an optional provider/model override (defaults to the active CoS provider), the Layer-1 telemetry source toggles (goals, CoS metrics, health report, PLAN.md, open issues), an add/remove list of repo-relative custom `file` sources, a free-text guidance-rules box, and the allowed-proposal-scope checkboxes — with the `loop-meta` / `portos-self` scopes shown only on the PortOS baseline app (mirroring the server's PORTOS-only gate). The tab reads the effective config from a new read-only `GET /api/apps/:id/layered-intelligence` endpoint (stored partial merged over the shipped defaults + `isPortos` flag) and, on save, PATCHes only the fields that changed against that baseline via a `buildLayeredIntelligenceUpdate` diff — so an unchanged config stays absent and the server's merge-over-stored contract keeps the install forward-compatible with future default changes (persisting the full effective config would freeze it). No migration or seed file is needed: the job ships via the `DEFAULT_JOBS` boot-merge and the per-app config comes from the accessor default (per the design doc in `docs/plans/2026-07-07-layered-intelligence-loop.md`). (`client/src/components/apps/LayeredIntelligenceTab.jsx`, `client/src/components/apps/EditAppDrawer.jsx`, `client/src/services/apiApps.js`, `server/routes/apps.js`)
+
+- **[issue-2277] Layered Intelligence custom sources gain `http` + `cmd` types (full-stack).** The Intelligence tab's custom-source list previously only offered `file` rows even though the design called for three source types — `http`/`cmd` sources could only be set through the API. Each row now has a type selector (File / URL / Command) that swaps in the type-appropriate value field (repo-relative `ref` / `url` / `cmd`) plus an optional `label`, and "Add source" seeds a new file row. The backend backbone the UI needs was also added in the same change (it didn't exist in `main` yet): the Zod schema is now a `type`-discriminated union (`file` keeps the repo-relative-path refine, `http` requires an http(s) URL, `cmd` is a bounded command string, all with an optional label), and `gatherSources` reads the new types via two injectable, degrade-to-omit helpers — `fetchHttpSource` (http(s)-scheme-guarded, 10s-timeout `fetch`, null on non-2xx/throw) and `runShellCommand` (shell-run in the app's repo dir, 15s timeout, null on non-zero exit). A `customSourceKey` helper namespaces the prompt map key by type so a `file` ref and an `http` url that share a string can't collide. Sanitize/diff on the client mirrors all three types + label so a blank/half-typed row still sanitizes away (no over-persist), and a type change clears the stale value field while keeping the label. (`server/lib/validation.js`, `server/services/layeredIntelligence.js`, `client/src/components/apps/LayeredIntelligenceTab.jsx`)
diff --git a/client/src/components/apps/LayeredIntelligenceTab.jsx b/client/src/components/apps/LayeredIntelligenceTab.jsx
index c07d654f92..7d64f840a5 100644
--- a/client/src/components/apps/LayeredIntelligenceTab.jsx
+++ b/client/src/components/apps/LayeredIntelligenceTab.jsx
@@ -47,19 +47,46 @@ function sameScopes(a, b) {
return a.every(s => sb.has(s));
}
-// Sanitize a custom-source list to what actually gets persisted: file-type
-// entries with a trimmed, non-blank ref. Used both to compare against the
-// baseline and to build the emitted value, so a half-typed/blank row that
-// sanitizes away doesn't register as a change (and over-persist the config).
+// The per-row primary value field, keyed by source type. Mirrors the server's
+// discriminated union (server/lib/validation.js `layeredIntelligenceConfigSchema`).
+export const LI_CUSTOM_TYPES = [
+ { type: 'file', valueKey: 'ref', label: 'File', placeholder: 'repo-relative path, e.g. docs/metrics.md' },
+ { type: 'http', valueKey: 'url', label: 'URL', placeholder: 'https://example.com/status.json' },
+ { type: 'cmd', valueKey: 'cmd', label: 'Command', placeholder: 'git log --oneline -20' }
+];
+
+const CUSTOM_TYPE_BY_KEY = Object.fromEntries(LI_CUSTOM_TYPES.map(t => [t.type, t]));
+
+// The value field name for a source type ('ref' | 'url' | 'cmd'), defaulting to
+// the file `ref` for an unknown/legacy type.
+function customValueKey(type) {
+ return (CUSTOM_TYPE_BY_KEY[type] || CUSTOM_TYPE_BY_KEY.file).valueKey;
+}
+
+// Sanitize a custom-source list to what actually gets persisted: a `type`, its
+// trimmed, non-blank primary value, and an optional trimmed label. Used both to
+// compare against the baseline and to build the emitted value, so a half-typed/
+// blank row that sanitizes away doesn't register as a change (over-persist).
function sanitizeCustom(list) {
return (Array.isArray(list) ? list : [])
- .map(s => ({ type: 'file', ref: String(s?.ref || '').trim() }))
- .filter(s => s.ref);
+ .map(s => {
+ const type = CUSTOM_TYPE_BY_KEY[s?.type] ? s.type : 'file';
+ const valueKey = customValueKey(type);
+ const value = String(s?.[valueKey] || '').trim();
+ const label = String(s?.label || '').trim();
+ const out = { type, [valueKey]: value };
+ if (label) out.label = label;
+ return out;
+ })
+ .filter(s => s[customValueKey(s.type)]);
}
function sameCustom(a, b) {
if (a.length !== b.length) return false;
- return a.every((s, i) => s.type === b[i].type && s.ref === b[i].ref);
+ return a.every((s, i) => {
+ const vk = customValueKey(s.type);
+ return s.type === b[i].type && s[vk] === b[i][vk] && (s.label || '') === (b[i].label || '');
+ });
}
/**
@@ -222,40 +249,73 @@ export default function LayeredIntelligenceTab({ li, onChange, providers, isPort
<div>
<div className="flex items-center justify-between mb-2">
- <span className="text-sm text-gray-400">Custom file sources</span>
+ <span className="text-sm text-gray-400">Custom sources</span>
<button
type="button"
onClick={() => setCustom([...custom, { type: 'file', ref: '' }])}
className="flex items-center gap-1 text-xs px-2 py-1 bg-port-accent/20 text-port-accent hover:bg-port-accent/30 rounded"
>
- <Plus size={12} /> Add file
+ <Plus size={12} /> Add source
</button>
</div>
{custom.length === 0 ? (
- <p className="text-xs text-gray-500">No custom sources. Add a repo-relative file (e.g. <code className="text-gray-400">docs/metrics.md</code>) to feed it into the loop&apos;s prompt.</p>
+ <p className="text-xs text-gray-500">No custom sources. Add a repo-relative file (e.g. <code className="text-gray-400">docs/metrics.md</code>), an <code className="text-gray-400">http</code> URL, or a shell command to feed its output into the loop&apos;s prompt.</p>
) : (
- <div className="space-y-2">
- {custom.map((src, i) => (
- <div key={i} className="flex items-center gap-2">
- <input
- type="text"
- value={src.ref || ''}
- onChange={e => setCustom(custom.map((s, j) => j === i ? { ...s, ref: e.target.value } : s))}
- className={INPUT_CLASS}
- placeholder="repo-relative path, e.g. docs/metrics.md"
- aria-label={`Custom file source ${i + 1}`}
- />
- <button
- type="button"
- onClick={() => setCustom(custom.filter((_, j) => j !== i))}
- className="p-2 text-gray-500 hover:text-port-error shrink-0"
- aria-label={`Remove custom source ${i + 1}`}
- >
- <Trash2 size={14} />
- </button>
- </div>
- ))}
- <p className="text-xs text-gray-500">Paths must be repo-relative — no leading <code>/</code> and no <code>..</code> segments.</p>
+ <div className="space-y-3">
+ {custom.map((src, i) => {
+ const type = CUSTOM_TYPE_BY_KEY[src.type] ? src.type : 'file';
+ const meta = CUSTOM_TYPE_BY_KEY[type];
+ const valueKey = meta.valueKey;
+ const setRow = (patch) => setCustom(custom.map((s, j) => j === i ? { ...s, ...patch } : s));
+ return (
+ <div key={i} className="flex items-start gap-2">
+ <div className="flex-1 space-y-1.5">
+ <div className="flex gap-2">
+ <select
+ value={type}
+ onChange={e => {
+ // Switch type: keep only the label; the old value field no longer applies.
+ const next = e.target.value;
+ setCustom(custom.map((s, j) => j === i
+ ? { type: next, [CUSTOM_TYPE_BY_KEY[next].valueKey]: '', ...(s.label ? { label: s.label } : {}) }
+ : s));
+ }}
+ className={`${INPUT_CLASS} w-28 shrink-0`}
+ aria-label={`Custom source ${i + 1} type`}
+ >
+ {LI_CUSTOM_TYPES.map(t => <option key={t.type} value={t.type}>{t.label}</option>)}
+ </select>
+ <input
+ type="text"
+ value={src[valueKey] || ''}
+ onChange={e => setRow({ [valueKey]: e.target.value })}
+ className={INPUT_CLASS}
+ placeholder={meta.placeholder}
+ aria-label={`Custom source ${i + 1} ${meta.label.toLowerCase()}`}
+ />
+ </div>
+ <input
+ type="text"
+ value={src.label || ''}
+ onChange={e => setRow({ label: e.target.value })}
+ className={`${INPUT_CLASS} text-xs`}
+ placeholder="Optional label"
+ maxLength={120}
+ aria-label={`Custom source ${i + 1} label`}
+ />
+ </div>
+ <button
+ type="button"
+ onClick={() => setCustom(custom.filter((_, j) => j !== i))}
+ className="p-2 text-gray-500 hover:text-port-error shrink-0"
+ aria-label={`Remove custom source ${i + 1}`}
+ >
+ <Trash2 size={14} />
+ </button>
+ </div>
+ );
+ })}
+ <p className="text-xs text-gray-500">File paths must be repo-relative — no leading <code>/</code> and no <code>..</code> segments. URLs must be http(s). Commands run in the app&apos;s repo directory.</p>
</div>
)}
</div>
diff --git a/client/src/components/apps/LayeredIntelligenceTab.test.jsx b/client/src/components/apps/LayeredIntelligenceTab.test.jsx
index d42af51455..9781ca08ac 100644
--- a/client/src/components/apps/LayeredIntelligenceTab.test.jsx
+++ b/client/src/components/apps/LayeredIntelligenceTab.test.jsx
@@ -57,6 +57,39 @@ describe('buildLayeredIntelligenceUpdate', () => {
expect(update.sources.custom).toEqual([{ type: 'file', ref: 'docs/x.md' }]);
});
+ it('sanitizes http + cmd sources with optional labels', () => {
+ const update = buildLayeredIntelligenceUpdate(baseline, {
+ ...baseline,
+ sources: { ...baseline.sources, custom: [
+ { type: 'http', url: ' https://x.com/s ', label: ' status ' },
+ { type: 'cmd', cmd: ' git log ' },
+ { type: 'http', url: '' } // blank → dropped
+ ] }
+ });
+ expect(update.sources.custom).toEqual([
+ { type: 'http', url: 'https://x.com/s', label: 'status' },
+ { type: 'cmd', cmd: 'git log' }
+ ]);
+ });
+
+ it('detects a label-only change on an existing custom source', () => {
+ const withHttp = { ...baseline, sources: { ...baseline.sources, custom: [{ type: 'http', url: 'https://x.com/s' }] } };
+ const update = buildLayeredIntelligenceUpdate(withHttp, {
+ ...withHttp,
+ sources: { ...withHttp.sources, custom: [{ type: 'http', url: 'https://x.com/s', label: 'status' }] }
+ });
+ expect(update.sources.custom).toEqual([{ type: 'http', url: 'https://x.com/s', label: 'status' }]);
+ });
+
+ it('detects a type change on a custom source (file → cmd)', () => {
+ const withFile = { ...baseline, sources: { ...baseline.sources, custom: [{ type: 'file', ref: 'docs/x.md' }] } };
+ const update = buildLayeredIntelligenceUpdate(withFile, {
+ ...withFile,
+ sources: { ...withFile.sources, custom: [{ type: 'cmd', cmd: 'git log' }] }
+ });
+ expect(update.sources.custom).toEqual([{ type: 'cmd', cmd: 'git log' }]);
+ });
+
it('ignores a blank custom-source row that sanitizes back to the baseline (no over-persist)', () => {
const withCustom = { ...baseline, sources: { ...baseline.sources, custom: [{ type: 'file', ref: 'docs/x.md' }] } };
// User clicks "Add file" but leaves the new row blank → sanitizes away → no change.
@@ -121,4 +154,39 @@ describe('LayeredIntelligenceTab (render)', () => {
fireEvent.click(screen.getByLabelText(/Enable the self-improvement loop/i));
expect(onChange).toHaveBeenCalledWith({ enabled: true });
});
+
+ it('adds a custom source (defaulting to file) via "Add source"', () => {
+ const onChange = vi.fn();
+ render(<LayeredIntelligenceTab {...props} onChange={onChange} />);
+ fireEvent.click(screen.getByRole('button', { name: /Add source/i }));
+ expect(onChange).toHaveBeenCalledWith({ sources: expect.objectContaining({ custom: [{ type: 'file', ref: '' }] }) });
+ });
+
+ it('renders the type selector and type-appropriate value field for each custom source', () => {
+ const li = {
+ ...baseline,
+ sources: { ...baseline.sources, custom: [
+ { type: 'file', ref: 'docs/x.md' },
+ { type: 'http', url: 'https://x.com/s' },
+ { type: 'cmd', cmd: 'git log' }
+ ] }
+ };
+ render(<LayeredIntelligenceTab {...props} li={li} />);
+ // One type selector per row.
+ expect(screen.getByLabelText(/Custom source 1 type/i)).toHaveValue('file');
+ expect(screen.getByLabelText(/Custom source 2 type/i)).toHaveValue('http');
+ expect(screen.getByLabelText(/Custom source 3 type/i)).toHaveValue('cmd');
+ // Type-appropriate value field is populated.
+ expect(screen.getByLabelText(/Custom source 1 file/i)).toHaveValue('docs/x.md');
+ expect(screen.getByLabelText(/Custom source 2 url/i)).toHaveValue('https://x.com/s');
+ expect(screen.getByLabelText(/Custom source 3 command/i)).toHaveValue('git log');
+ });
+
+ it('switches a row type, clearing the old value field but keeping the label', () => {
+ const onChange = vi.fn();
+ const li = { ...baseline, sources: { ...baseline.sources, custom: [{ type: 'file', ref: 'docs/x.md', label: 'notes' }] } };
+ render(<LayeredIntelligenceTab {...props} li={li} onChange={onChange} />);
+ fireEvent.change(screen.getByLabelText(/Custom source 1 type/i), { target: { value: 'http' } });
+ expect(onChange).toHaveBeenCalledWith({ sources: expect.objectContaining({ custom: [{ type: 'http', url: '', label: 'notes' }] }) });
+ });
});
diff --git a/server/lib/validation.js b/server/lib/validation.js
index a63c097f4f..d0462feb82 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -126,16 +126,34 @@ export const layeredIntelligenceConfigSchema = z.object({
healthReport: z.boolean().optional(),
planMd: z.boolean().optional(),
openIssues: z.boolean().optional(),
- custom: z.array(z.object({
- type: z.enum(['file']),
- // A safe repo-relative path — reject absolute paths and `..` traversal so a
- // custom source can't read files outside the app repo into the LLM prompt.
- // gatherSources also enforces this at read time (defense in depth).
- ref: z.string().min(1).max(500)
- .refine(r => !r.startsWith('/') && !r.split(/[/\\]/).includes('..'), {
- message: 'ref must be a repo-relative path (no leading / and no ".." segments)'
- })
- })).optional()
+ // Custom Layer-1 sources. Discriminated on `type`: a repo-relative `file`,
+ // an `http`(s) URL, or a shell `cmd`. All three carry an optional display
+ // `label`. gatherSources also re-enforces the file confinement + the
+ // http scheme + a cmd timeout at read time (defense in depth).
+ custom: z.array(z.discriminatedUnion('type', [
+ z.object({
+ type: z.literal('file'),
+ // A safe repo-relative path — reject absolute paths and `..` traversal so a
+ // custom source can't read files outside the app repo into the LLM prompt.
+ ref: z.string().min(1).max(500)
+ .refine(r => !r.startsWith('/') && !r.split(/[/\\]/).includes('..'), {
+ message: 'ref must be a repo-relative path (no leading / and no ".." segments)'
+ }),
+ label: z.string().max(120).optional()
+ }),
+ z.object({
+ type: z.literal('http'),
+ // Only http/https — gatherSources rejects any other scheme at read time too.
+ url: z.string().url().max(2000)
+ .refine(u => /^https?:\/\//i.test(u), { message: 'url must be http(s)' }),
+ label: z.string().max(120).optional()
+ }),
+ z.object({
+ type: z.literal('cmd'),
+ cmd: z.string().min(1).max(2000),
+ label: z.string().max(120).optional()
+ })
+ ])).optional()
}).optional(),
rules: z.string().max(8000).optional(),
allowedScopes: z.array(z.enum(LAYERED_INTELLIGENCE_SCOPES)).optional(),
diff --git a/server/services/layeredIntelligence.js b/server/services/layeredIntelligence.js
index 83da94837e..4ee486cd88 100644
--- a/server/services/layeredIntelligence.js
+++ b/server/services/layeredIntelligence.js
@@ -334,19 +334,81 @@ export async function gatherSources(app, config, { cosPath = PATHS.cos } = {}) {
}
}
for (const custom of src.custom || []) {
- if (custom?.type === 'file' && typeof custom.ref === 'string' && repo) {
+ const key = customSourceKey(custom);
+ if (!key) continue;
+ if (custom.type === 'file' && typeof custom.ref === 'string' && repo) {
const safe = await confineToRepo(repo, custom.ref);
if (!safe) {
console.warn(`⚠️ Layered Intelligence: custom source "${custom.ref}" escapes repo — skipped`);
continue;
}
const content = await tryReadFile(safe);
- if (content) out[`custom:${custom.ref}`] = content.slice(0, 8000);
+ if (content) out[key] = content.slice(0, 8000);
+ } else if (custom.type === 'http' && typeof custom.url === 'string') {
+ const content = await fetchHttpSource(custom.url);
+ if (content) out[key] = content.slice(0, 8000);
+ } else if (custom.type === 'cmd' && typeof custom.cmd === 'string') {
+ const content = await runShellCommand(custom.cmd, { cwd: repo });
+ if (content) out[key] = content.slice(0, 8000);
}
}
return out;
}
+/**
+ * Stable map key for a custom source. Namespaced by type so a `file` ref and an
+ * `http` url that share a string can't collide, and so the prompt's source block
+ * labels are self-describing. Returns null for a malformed/unknown source.
+ */
+export function customSourceKey(custom) {
+ if (!custom || typeof custom !== 'object') return null;
+ if (custom.type === 'file' && custom.ref) return `custom:${custom.ref}`;
+ if (custom.type === 'http' && custom.url) return `custom:http:${custom.url}`;
+ if (custom.type === 'cmd' && custom.cmd) return `custom:cmd:${custom.cmd}`;
+ return null;
+}
+
+/**
+ * Fetch an http(s) custom source for the loop's prompt. Deterministic read, no
+ * LLM. Rejects any non-http(s) scheme (defense in depth over the Zod refine),
+ * bounds the request with a 10s timeout, and returns null on any failure so a
+ * dead URL just omits the key rather than throwing. `fetchImpl` is injectable
+ * for tests.
+ */
+export async function fetchHttpSource(url, { timeoutMs = 10_000, fetchImpl = fetch } = {}) {
+ if (typeof url !== 'string' || !/^https?:\/\//i.test(url)) return null;
+ const res = await fetchImpl(url, { signal: AbortSignal.timeout(timeoutMs) }).catch(() => null);
+ if (!res || !res.ok) return null;
+ const text = await res.text().catch(() => null);
+ return text || null;
+}
+
+/**
+ * Run a user-configured shell command for a `cmd` custom source and return its
+ * stdout. Deterministic read, no LLM. Runs the full command string through the
+ * shell (e.g. `git log --oneline -20 | head`), bounded by a wall-clock timeout,
+ * in the app's repo dir. Returns null on non-zero exit / no output so a failing
+ * command just omits the key. `exec` is injectable for tests.
+ */
+export async function runShellCommand(cmd, { cwd, timeoutMs = 15_000, exec = runShell } = {}) {
+ if (typeof cmd !== 'string' || !cmd.trim()) return null;
+ const { code, stdout } = await exec(cmd, { cwd, timeout: timeoutMs });
+ if (code !== 0) return null;
+ return stdout.trim() || null;
+}
+
+/** Run a full command string through the shell, resolving `{ code, stdout, stderr }` (never rejects). */
+function runShell(cmd, options = {}) {
+ return new Promise((resolve) => {
+ const child = spawn(cmd, { shell: true, windowsHide: true, ...options });
+ let stdout = '', stderr = '';
+ child.stdout?.on('data', d => { stdout += d.toString(); });
+ child.stderr?.on('data', d => { stderr += d.toString(); });
+ child.on('close', code => resolve({ code, stdout, stderr }));
+ child.on('error', err => resolve({ code: -1, stdout: '', stderr: err.message }));
+ });
+}
+
/**
* Confine a custom file `ref` to within `repo` so a hostile/hand-edited config
* can't read arbitrary files into the LLM prompt. Returns the safe absolute path,
diff --git a/server/services/layeredIntelligence.test.js b/server/services/layeredIntelligence.test.js
index 04eb668673..3a10151dce 100644
--- a/server/services/layeredIntelligence.test.js
+++ b/server/services/layeredIntelligence.test.js
@@ -21,6 +21,9 @@ import {
extractPlanSlugs,
appendProposalToPlan,
gatherSources,
+ customSourceKey,
+ fetchHttpSource,
+ runShellCommand,
normalizeIssueState,
listForgeIssues,
listBlockingIssues,
@@ -452,6 +455,56 @@ describe('gatherSources custom file confinement', () => {
});
});
+describe('customSourceKey', () => {
+ it('namespaces by type so file/http/cmd never collide', () => {
+ expect(customSourceKey({ type: 'file', ref: 'x' })).toBe('custom:x');
+ expect(customSourceKey({ type: 'http', url: 'https://x' })).toBe('custom:http:https://x');
+ expect(customSourceKey({ type: 'cmd', cmd: 'git log' })).toBe('custom:cmd:git log');
+ });
+ it('returns null for a malformed/blank source', () => {
+ expect(customSourceKey(null)).toBeNull();
+ expect(customSourceKey({ type: 'file' })).toBeNull();
+ expect(customSourceKey({ type: 'nope', ref: 'x' })).toBeNull();
+ });
+});
+
+describe('fetchHttpSource', () => {
+ it('returns body text on a 2xx http(s) response', async () => {
+ const fetchImpl = vi.fn().mockResolvedValue({ ok: true, text: async () => 'remote body' });
+ expect(await fetchHttpSource('https://example.com/x', { fetchImpl })).toBe('remote body');
+ });
+ it('rejects a non-http scheme without calling fetch', async () => {
+ const fetchImpl = vi.fn();
+ expect(await fetchHttpSource('file:///etc/hosts', { fetchImpl })).toBeNull();
+ expect(fetchImpl).not.toHaveBeenCalled();
+ });
+ it('returns null on a non-ok response', async () => {
+ const fetchImpl = vi.fn().mockResolvedValue({ ok: false, text: async () => 'nope' });
+ expect(await fetchHttpSource('https://example.com/x', { fetchImpl })).toBeNull();
+ });
+ it('returns null when fetch throws (dead URL / timeout)', async () => {
+ const fetchImpl = vi.fn().mockRejectedValue(new Error('boom'));
+ expect(await fetchHttpSource('https://example.com/x', { fetchImpl })).toBeNull();
+ });
+});
+
+describe('runShellCommand', () => {
+ it('returns trimmed stdout on exit 0', async () => {
+ const exec = vi.fn().mockResolvedValue({ code: 0, stdout: ' out\n', stderr: '' });
+ expect(await runShellCommand('echo out', { cwd: '/x', exec })).toBe('out');
+ expect(exec).toHaveBeenCalledWith('echo out', expect.objectContaining({ cwd: '/x' }));
+ });
+ it('returns null on non-zero exit', async () => {
+ const exec = vi.fn().mockResolvedValue({ code: 1, stdout: 'partial', stderr: 'err' });
+ expect(await runShellCommand('false', { cwd: '/x', exec })).toBeNull();
+ });
+ it('returns null on empty command without invoking exec', async () => {
+ const exec = vi.fn();
+ expect(await runShellCommand(' ', { cwd: '/x', exec })).toBeNull();
+ expect(exec).not.toHaveBeenCalled();
+ });
+});
+
describe('forge I/O (injected exec)', () => {
it('listForgeIssues parses gh JSON and extracts slugs', async () => {
const exec = vi.fn().mockResolvedValue({