Open-source, local-first social media research agent for Instagram, TikTok, and LinkedIn. Jev routes read-only steps; socai CLI captures cited browser evidence.
JavaScript agent-skillsai-agentsbrowser-agentbrowser-automationdecision-modeldeep-researchinstagramjevlinkedinlocal-firstopen-sourceosintresearch-agentsocaisocial-listeningsocial-mediasocial-media-researchsocmintsystem-onetiktok
feat: checkpoint interrupted research runs
Asklvaac94a0fdaf3
diff --git a/docs/troubleshooting.md b/docs/troubleshooting.mdindex 9895cae..ff2a3c0 100644--- a/docs/troubleshooting.md+++ b/docs/troubleshooting.md@@ -5,7 +5,7 @@ Jev Social directs your Chrome browser through the [socai](https://github.com/so> [!WARNING]> **Data Retention & Privacy Notice**:> - **Archived Runs & Artifacts**: Two distinct storage locations persist data that may survive cancellation or process termination:-> 1. **Jev Social Runs**: Finalized runs persist full evidence, captured cards, and raw `socaiOutputs` stdout text to `${JEV_SOCIAL_HOME:-~/.jev-social}/runs/<id>.json`.+> 1. **Jev Social Runs**: Running, interrupted, and finalized runs persist sanitized evidence cards, action status, timing, and the partial or final report to `${JEV_SOCIAL_HOME:-~/.jev-social}/runs/<id>.json`. Raw CLI stdout, cookies, DOM snapshots, and local filesystem paths are not stored in these checkpoints.> 2. **`socai` Command Artifacts**: The underlying CLI writes tool inputs, outputs, downloaded media, and execution artifacts following the precedence: `SOCAI_RUNS_DIR` environment override $\rightarrow$ configured `runs.dir` (`socai config get runs.dir`) $\rightarrow$ default `~/.socai/runs/`.> - **Locating & Inspecting Effective Stores**:> To inspect your active artifact storage locations without modifying files:@@ -27,7 +27,7 @@ Jev Social directs your Chrome browser through the [socai](https://github.com/so> - Review directory contents (e.g. `ls "$DIR"` or `Get-ChildItem $dir`) before removing any stored data.> - To clear individual runs or prune old artifacts, delete specific target files manually from the verified store directories rather than running unvalidated recursive shell recipes across dynamic or environment-supplied paths.> - Note: configured `runs.dir` paths may use custom directory names; always verify the exact resolved target directory before manual removal.-> - **Review Before Sharing**: Exported `report.md` files and raw run JSON archives preserve access-restricted posts, private account connections, author names, bio/experience data, comments, and direct URLs from your active session. Always review and redact sensitive data before sharing reports or diagnostic files publicly.+> - **Review Before Sharing**: Exported `report.md` files and run checkpoints can still preserve access-restricted post text, private account connections, author names, bio/experience data, comments, and direct URLs from your active session. Always review and redact sensitive data before sharing reports or diagnostic files publicly.---@@ -50,7 +50,7 @@ By default (using `existing` or `managed` Chrome modes without external endpoint| **Browser connection failure** | `socai` cannot connect to Chrome or its DevTools protocol (CDP) endpoint. | Error indicates connection refusal (e.g. `ECONNREFUSED 127.0.0.1:9222`), socket error, or browser launch timeout. | Follow your active connection mode below. Ensure the target Chrome instance is running with remote debugging enabled and accept any remote-debugging permission prompts. Avoid blanket process-killing commands. || **Login-required / challenge gate** | The platform blocked unauthenticated access with a login modal, redirect (e.g. `authwall`), or CAPTCHA. | Status displays a partial result notice with the specific gate reason (for example, `Partial results · The platform requires attention: login_required`). | Open the platform in the specific user-accessible Chrome session or profile selected by `socai` (`existing` or `managed` mode), complete authentication or challenges, and verify browsing before re-running. (If using hosted `remote` mode, switch to `existing` or `managed` mode to authenticate interactively.) || **Valid empty result** | The platform loaded successfully and the search executed cleanly, but returned 0 matching records. | Evidence cards, table, and heading remain hidden. Depending on subsequent decisions, the run can finalize as `partial` (`Partial results · Jev stopped without usable evidence.`), `step_limit` (if max steps are reached), or `decision_failed` (if a subsequent model decision call fails). | The initial search executed cleanly without matching records on the platform. Broaden or rephrase your search query. (If a subsequent decision failed, verify model API connectivity). |-| **Early decision or classification failure** | Jev encountered an error during classification or the very first action decision before any operations ran. | Stream emits an error event immediately without saving a run or generating a report. | Ensure your query is a supported read-only social research goal, specify `--platform` explicitly, or check your OpenRouter key and network connection. |+| **Early decision or classification failure** | Jev encountered an error during classification or the very first action decision before any browser operations ran. | Classification failures emit an error before a run exists. A first action-decision failure saves a failed checkpoint with no captured posts. | Ensure your query is a supported read-only social research goal, specify `--platform` explicitly, or check your OpenRouter key and network connection. || **Mid-run decision failure (`decision_failed`)** | A model decision call failed after one or more actions had already executed. | Status displays `Partial results · <error message>` with status `decision_failed`; collected evidence prior to the failure is preserved. | Check OpenRouter API connectivity, ensure model quota is available, or retry the request. |---diff --git a/package.json b/package.jsonindex e97f2dc..da65a9c 100644--- a/package.json+++ b/package.json@@ -29,7 +29,7 @@"scripts": {"start": "node ./bin/jev-social.js","dev": "node --watch ./bin/jev-social.js serve --no-open",- "check": "node --check ./bin/jev-social.js && node --check ./src/server.js && node --check ./public/app.js && node --check ./public/evidence-preview.js && node --check ./public/report-download.js && node --check ./public/prompts.js",+ "check": "node --check ./bin/jev-social.js && node --check ./src/server.js && node --check ./public/app.js && node --check ./public/evidence-preview.js && node --check ./public/run-route.js && node --check ./public/report-download.js && node --check ./public/prompts.js","test": "node --test"},"engines": {diff --git a/public/app.js b/public/app.jsindex 1cab96c..727a6db 100644--- a/public/app.js+++ b/public/app.js@@ -9,6 +9,7 @@ import {selectSummaryCards,} from "./evidence-preview.js";import { bindPromptButtons } from "./prompts.js";+import { parseRunRoute, resultHash } from "./run-route.js";const $ = (selector) => document.querySelector(selector);const elements = {@@ -37,6 +38,7 @@ let timer;let startedAt = 0;let activeController;let currentRun;+let restorePoll;elements.searchForm.addEventListener("submit", async (event) => {event.preventDefault();@@ -61,13 +63,13 @@ elements.searchForm.addEventListener("submit", async (event) => {if (error.name !== "AbortError") showError(error);} finally {activeController = undefined;- stopTimer();+ if (elements.resultView.classList.contains("is-running")) stopTimer();button.disabled = false;}});$("#back-to-search").addEventListener("click", () => {- if (location.hash === "#results") history.back();+ if (parseRunRoute(location.hash)) history.back();else showSearchView();});elements.downloadReportBtn?.addEventListener("click", () => {@@ -87,11 +89,11 @@ elements.dialog.addEventListener("click", (event) => {});window.addEventListener("popstate", () => {- if (location.hash === "#results") showResultView();+ if (parseRunRoute(location.hash)) void restoreRunFromRoute();else showSearchView();});-void refreshStatus();+void initialize();bindPromptButtons({buttons: document.querySelectorAll(".prompt-example-btn"),queryElement: $("#query"),@@ -100,6 +102,10 @@ bindPromptButtons({function handleStreamEvent(event) {if (event.stage === "result") return;+ if (event.stage === "started" && event.run?.id) {+ history.replaceState({ view: "results", runId: event.run.id }, "", `${location.pathname}${location.search}${resultHash(event.run.id)}`);+ return;+ }if (event.stage === "error") {const error = new Error(event.error?.message || "The social research run failed.");error.code = event.error?.code;@@ -131,8 +137,8 @@ function handleStreamEvent(event) {showActivity(titles[event.stage] || "socai is working", event.message || descriptions[event.stage] || "Research is in progress.");}-function startTimer() {- startedAt = performance.now();+function startTimer(initialMs = 0) {+ startedAt = performance.now() - Math.max(0, Number(initialMs) || 0);clearInterval(timer);updateTimer();timer = setInterval(updateTimer, 100);@@ -152,11 +158,12 @@ function updateTimer() {function showResultView({ push = false } = {}) {elements.searchView.classList.add("hidden");elements.resultView.classList.remove("hidden");- if (push && location.hash !== "#results") history.pushState({ view: "results" }, "", `${location.pathname}${location.search}#results`);+ if (push && !parseRunRoute(location.hash)) history.pushState({ view: "results" }, "", `${location.pathname}${location.search}${resultHash()}`);}function showSearchView() {activeController?.abort();+ clearTimeout(restorePoll);currentRun = undefined;if (elements.downloadReportBtn) {elements.downloadReportBtn.disabled = true;@@ -170,6 +177,42 @@ function showSearchView() {$("#query").focus();}+async function initialize() {+ const status = refreshStatus();+ const restored = parseRunRoute(location.hash) ? restoreRunFromRoute() : Promise.resolve();+ await Promise.all([status, restored]);+}++async function restoreRunFromRoute() {+ const route = parseRunRoute(location.hash);+ if (!route) return;+ const requestedHash = location.hash;+ clearTimeout(restorePoll);+ showResultView();+ try {+ let id = route.id;+ if (!id) {+ const history = await api("/api/runs");+ if (location.hash !== requestedHash) return;+ id = history.runs?.[0]?.id || "";+ }+ if (!id) {+ resetLiveWorkspace();+ $("#result-title").textContent = "No saved research yet";+ return;+ }+ const run = await api(`/api/runs/${encodeURIComponent(id)}`);+ if (location.hash !== requestedHash) return;+ history.replaceState({ view: "results", runId: id }, "", `${location.pathname}${location.search}${resultHash(id)}`);+ renderRun(run);+ if (run.status === "running") {+ restorePoll = setTimeout(() => void restoreRunFromRoute(), 750);+ }+ } catch (error) {+ showError(error);+ }+}+async function refreshStatus() {try {const status = await api("/api/status");@@ -224,9 +267,12 @@ function renderRun(run) {elements.activity.classList.add("hidden");elements.resultView.classList.remove("has-live-evidence", "is-running");elements.reportSection.classList.remove("hidden");- stopTimer(run.elapsedMs);+ if (run.status === "running") startTimer(run.elapsedMs);+ else stopTimer(run.elapsedMs);$("#result-title").textContent = run.request || run.query || "Social results";- $("#run-status").textContent = run.status && run.status !== "completed" ? `Partial results · ${run.stopReason}` : "";+ $("#run-status").textContent = run.status === "running"+ ? "Research in progress · restored from the latest checkpoint"+ : run.status && run.status !== "completed" ? `Partial results · ${run.stopReason}` : "";$("#action-list").replaceChildren(...(run.actions || []).map((step) => element("li", "", `${step.action.label} · ${step.status}`)));$("#action-history").classList.toggle("hidden", !run.actions?.length);diff --git a/public/run-route.js b/public/run-route.jsnew file mode 100644index 0000000..1a71d47--- /dev/null+++ b/public/run-route.js@@ -0,0 +1,12 @@+const RUN_ID = /^[A-Za-z0-9_.-]+$/;++export function parseRunRoute(hash = "") {+ if (hash === "#results") return { view: "results", id: "" };+ const match = hash.match(/^#results\/([^/]+)$/);+ if (!match || !RUN_ID.test(match[1])) return null;+ return { view: "results", id: match[1] };+}++export function resultHash(id = "") {+ return id && RUN_ID.test(id) ? `#results/${id}` : "#results";+}diff --git a/src/app.js b/src/app.jsindex 5bd4965..35ed3ec 100644--- a/src/app.js+++ b/src/app.js@@ -29,85 +29,132 @@ export async function runSearch(const selectedPlatform = classification.platform;const commands = await actionCapabilities({ config, env, platform: selectedPlatform, signal });const searchQuery = extractSearchQuery(request);+ const createdAt = new Date().toISOString();+ const id = `${createdAt.replace(/[-:.TZ]/g, "").slice(0, 14)}-${crypto.randomBytes(3).toString("hex")}`;let items = [];const actions = [];const executions = [];- let status = "step_limit";- let stopReason = `Reached the limit of ${maxSteps} operations before Jev chose to finish.`;+ let status = "running";+ let stopReason = "Research is still in progress.";+ let activeEntry;++ const checkpoint = async () => {+ const publicRequest = publicEvidence(request);+ const publicQuery = publicEvidence(searchQuery);+ const publicItems = publicEvidence(items);+ const publicStopReason = publicEvidence(stopReason);+ const report = evidenceReport({ request: publicRequest, platform: selectedPlatform, items: publicItems, actions, status, stopReason: publicStopReason });+ const run = {+ id, createdAt, updatedAt: new Date().toISOString(), request: publicRequest, query: publicQuery,+ requestedPlatform: platform, platform: selectedPlatform,+ classification: publicEvidence(classification),+ actions: actions.map(({ command: _command, ...entry }) => publicEvidence(entry)),+ status, stopReason: publicStopReason, maxSteps,+ socaiExitCode: executions.at(-1)?.exitCode ?? null,+ socaiElapsedMs: executions.reduce((sum, execution) => sum + execution.elapsedMs, 0),+ jevElapsedMs: classification.elapsedMs + actions.reduce((sum, entry) => sum + (entry.jevElapsedMs || 0), 0),+ elapsedMs: Date.now() - startedAt,+ result: { ok: status === "completed", query: publicQuery, items: publicItems },+ report,+ finalSocaiOutput: report,+ };+ await saveRun(run, env);+ return run;+ };++ await checkpoint();+ onEvent?.({ stage: "started", run: { id, createdAt, query: searchQuery, platform: selectedPlatform, status } });// Every operation, including which exact result to open, is chosen from the// current observation. The model never supplies executable shell or JS.- for (let step = 0; step < maxSteps; step += 1) {- signal?.throwIfAborted();- const candidates = availableActions({ platform: selectedPlatform, query: searchQuery, goal: request, items, history: actions, commands, limit });- onEvent?.({ stage: "planning", message: "Jev is choosing the next operation…", step: step + 1 });- let decision;- try {- decision = await chooseAction({ goal: request, platform: selectedPlatform, actions: candidates, history: actions, items, limit, remainingSteps: maxSteps - step, ...decisionOptions });- } catch (error) {- if (!actions.length || signal?.aborted) throw error;- status = "decision_failed";- stopReason = error.message;- break;- }- const action = decision.action;- const entry = {- step: step + 1, action, confidence: decision.confidence,- model: decision.model, usage: decision.usage, jevElapsedMs: decision.elapsedMs,- status: "selected",- };- if (action.kind === "finish") {- entry.status = "completed";- actions.push(entry);- status = items.length && !actions.some((item) => item.status === "failed") ? "completed" : "partial";- stopReason = items.length ? "Jev chose to finish with the evidence captured so far." : "Jev stopped without usable evidence.";- break;- }- const stage = action.downloadMedia ? "downloading" : action.kind === "search" ? "searching" : "reading";- onEvent?.({ stage, message: action.label, step: step + 1, action: { kind: action.kind, target: action.target, cli: buildActionArgs(action) } });- try {- const execution = await runSocaiAction({- action, config, env, signal,- onProgress: (message) => {- const clean = safeProgress(message);- if (clean) onEvent?.({ stage, message: clean });- },- });- executions.push(execution);- const captured = extractEvidence(execution.data, action);- items = mergeEvidence(items, captured);- const observation = resultObservation(execution.data, captured);- Object.assign(entry, { command: execution.command, elapsedMs: execution.elapsedMs, observation, status: observation.ok ? "completed" : "failed" });- actions.push(entry);- if (captured.length) onEvent?.({ stage: "evidence", items: publicEvidence(items), message: `Captured ${items.length} records.` });- if (observation.blocked) {- status = "blocked";- stopReason = `The platform requires attention: ${observation.reason || observation.status || "login or access check"}.`;+ try {+ for (let step = 0; step < maxSteps; step += 1) {+ signal?.throwIfAborted();+ const candidates = availableActions({ platform: selectedPlatform, query: searchQuery, goal: request, items, history: actions, commands, limit });+ onEvent?.({ stage: "planning", message: "Jev is choosing the next operation…", step: step + 1 });+ let decision;+ try {+ decision = await chooseAction({ goal: request, platform: selectedPlatform, actions: candidates, history: actions, items, limit, remainingSteps: maxSteps - step, ...decisionOptions });+ } catch (error) {+ if (!actions.length || signal?.aborted) throw error;+ status = "decision_failed";+ stopReason = safeProgress(error.message) || "Jev could not choose another safe operation.";break;}- } catch (error) {- signal?.throwIfAborted();- Object.assign(entry, { status: "failed", observation: { ok: false, code: error.code, error: safeProgress(error.message) || "Browser operation failed." } });+ const action = decision.action;+ const entry = {+ step: step + 1, action, confidence: decision.confidence,+ model: decision.model, usage: decision.usage, jevElapsedMs: decision.elapsedMs,+ status: "selected",+ };+ activeEntry = entry;actions.push(entry);- onEvent?.({ stage: "planning", message: "The operation failed. Jev is considering the remaining options." });+ if (action.kind === "finish") {+ entry.status = "completed";+ status = items.length && !actions.some((item) => item.status === "failed") ? "completed" : "partial";+ stopReason = items.length ? "Jev chose to finish with the evidence captured so far." : "Jev stopped without usable evidence.";+ await checkpoint();+ activeEntry = undefined;+ break;+ }+ await checkpoint();+ const stage = action.downloadMedia ? "downloading" : action.kind === "search" ? "searching" : "reading";+ onEvent?.({ stage, message: action.label, step: step + 1, action: { kind: action.kind, target: action.target, cli: buildActionArgs(action) } });+ try {+ const execution = await runSocaiAction({+ action, config, env, signal,+ onProgress: (message) => {+ const clean = safeProgress(message);+ if (clean) onEvent?.({ stage, message: clean });+ },+ });+ executions.push(execution);+ const captured = extractEvidence(execution.data, action);+ items = mergeEvidence(items, captured);+ const observation = resultObservation(execution.data, captured);+ Object.assign(entry, { command: execution.command, elapsedMs: execution.elapsedMs, observation, status: observation.ok ? "completed" : "failed" });+ if (observation.blocked) {+ status = "blocked";+ stopReason = `The platform requires attention: ${observation.reason || observation.status || "login or access check"}.`;+ }+ await checkpoint();+ if (captured.length) onEvent?.({ stage: "evidence", items: publicEvidence(items), message: `Captured ${items.length} records.` });+ activeEntry = undefined;+ if (observation.blocked) break;+ } catch (error) {+ signal?.throwIfAborted();+ Object.assign(entry, { status: "failed", observation: { ok: false, code: error.code, error: safeProgress(error.message) || "Browser operation failed." } });+ await checkpoint();+ activeEntry = undefined;+ onEvent?.({ stage: "planning", message: "The operation failed. Jev is considering the remaining options." });+ }}+ } catch (error) {+ if (signal?.aborted || error?.name === "AbortError") {+ if (activeEntry?.status === "selected") activeEntry.status = "interrupted";+ status = "interrupted";+ stopReason = "The browser stream closed before this run completed.";+ await checkpoint();+ throw error;+ }+ if (activeEntry?.status === "selected") activeEntry.status = "failed";+ status = "failed";+ stopReason = safeProgress(error.message) || "The research run failed before completion.";+ await checkpoint();+ throw error;+ }+ if (status === "running") {+ status = "step_limit";+ stopReason = `Reached the limit of ${maxSteps} operations before Jev chose to finish.`;}- const report = evidenceReport({ request, platform: selectedPlatform, items, actions, status, stopReason });+ const stored = await checkpoint();const run = {- id: `${new Date().toISOString().replace(/[-:.TZ]/g, "").slice(0, 14)}-${crypto.randomBytes(3).toString("hex")}`,- createdAt: new Date().toISOString(), request, query: searchQuery, requestedPlatform: platform,- platform: selectedPlatform, classification, actions, status, stopReason, maxSteps,+ ...stored, classification, actions,command: executions.at(-1)?.command || "", evidenceCommand: executions[0]?.command || "",evidenceCommands: executions.map((execution) => execution.command),- socaiExitCode: executions.at(-1)?.exitCode ?? null,- socaiElapsedMs: executions.reduce((sum, execution) => sum + execution.elapsedMs, 0),- jevElapsedMs: classification.elapsedMs + actions.reduce((sum, entry) => sum + entry.jevElapsedMs, 0),- elapsedMs: Date.now() - startedAt,result: { ok: status === "completed", query: searchQuery, items },- report, finalSocaiOutput: report,socaiOutputs: executions.map((execution) => ({ command: execution.command, elapsedMs: execution.elapsedMs, text: execution.stdout })),};- await saveRun(run, env);onEvent?.({ stage: "complete", status, message: status === "completed" ? "Evidence ready." : `Partial evidence saved. ${stopReason}` });return run;}diff --git a/src/evidence.js b/src/evidence.jsindex 7aabeda..0cc1ec1 100644--- a/src/evidence.js+++ b/src/evidence.js@@ -1,6 +1,8 @@import { sourceUrl, targetKind } from "./actions.js";const record = (value) => value && typeof value === "object" && !Array.isArray(value);+const PRIVATE_EVIDENCE_KEY = /^(?:stdout|stderr|cookie(?:s|_jar|_string)?|dom|dom_state|(?:inner_|outer_)?html|page_source|storage_state|(?:.*_)?headers|authorization|(?:.*_)?token|api_?key|secret|password|raw(?:_.*)?)$/i;+const LOCAL_PATH_KEY = /(?:^|_)(?:local_)?path$|(?:^|_)(?:run|output|artifact)_dir$/i;export function unwrapResult(value) {return record(value?.data) ? value.data : value;@@ -63,18 +65,24 @@ export function resultObservation(raw, captured) {export function publicEvidence(value) {if (Array.isArray(value)) return value.map(publicEvidence).filter((item) => item !== undefined);if (!record(value)) {- if (typeof value === "string" && /^(?:\/Users\/|\/home\/|\/tmp\/|[A-Za-z]:\\)/.test(value)) return undefined;- return value;+ return typeof value === "string" ? redactLocalPaths(value) : value;}const clean = {};for (const [key, child] of Object.entries(value)) {- if (/(?:^|_)(?:local_)?path$|(?:^|_)(?:run|output|artifact)_dir$/i.test(key)) continue;+ if (LOCAL_PATH_KEY.test(key) || PRIVATE_EVIDENCE_KEY.test(key)) continue;const next = publicEvidence(child);if (next !== undefined) clean[key] = next;}return clean;}+function redactLocalPaths(value) {+ return value+ .replace(/file:\/\/\/[^\s"'`<>)\]}]+/gi, "[redacted path]")+ .replace(/\b[A-Za-z]:[\\/][^\s"'`<>)\]}\r\n]+/g, "[redacted path]")+ .replace(/(^|[\s("'`])\/(?:Users|home|tmp|var|private|etc|usr|opt|bin|Windows|Program Files)\/[^\s"'`<>)\]}\r\n]*/gi, "$1[redacted path]");+}+export function evidenceReport({ request, platform, items, actions, status, stopReason }) {const lines = ["# Captured evidence", "", `Request: ${markdown(request)}`, "", `${items.length} records from ${platform}; ${actions.filter((step) => step.command).length} browser operations.`, ""];for (const [index, item] of items.entries()) {diff --git a/src/runs.js b/src/runs.jsindex 1c446ca..304122d 100644--- a/src/runs.js+++ b/src/runs.js@@ -1,19 +1,37 @@-import { mkdir, readFile, readdir, rename, writeFile } from "node:fs/promises";+import crypto from "node:crypto";+import { mkdir, readFile, readdir, rename, unlink, writeFile } from "node:fs/promises";import path from "node:path";import { getHomeDir } from "./config.js";+const writeQueues = new Map();+function runsDir(env = process.env) {return path.join(getHomeDir(env), "runs");}export async function saveRun(run, env = process.env) {+ if (!run?.id || !/^[A-Za-z0-9_.-]+$/.test(run.id)) throw new Error("Run id contains invalid characters.");const directory = runsDir(env);- await mkdir(directory, { recursive: true, mode: 0o700 });const target = path.join(directory, `${run.id}.json`);- const temporary = `${target}.${process.pid}.tmp`;- await writeFile(temporary, `${JSON.stringify(run, null, 2)}\n`, { mode: 0o600 });- await rename(temporary, target);- return target;+ const previous = writeQueues.get(target) || Promise.resolve();+ const operation = previous.catch(() => {}).then(async () => {+ await mkdir(directory, { recursive: true, mode: 0o700 });+ const temporary = `${target}.${process.pid}.${crypto.randomBytes(6).toString("hex")}.tmp`;+ try {+ await writeFile(temporary, `${JSON.stringify(run, null, 2)}\n`, { mode: 0o600 });+ await rename(temporary, target);+ return target;+ } catch (error) {+ await unlink(temporary).catch(() => {});+ throw error;+ }+ });+ writeQueues.set(target, operation);+ try {+ return await operation;+ } finally {+ if (writeQueues.get(target) === operation) writeQueues.delete(target);+ }}export async function listRuns(env = process.env, limit = 30) {@@ -36,8 +54,12 @@ export async function listRuns(env = process.env, limit = 30) {runs.push({id: run.id,createdAt: run.createdAt,+ updatedAt: run.updatedAt,query: run.query,platform: run.platform,+ status: run.status,+ stopReason: run.stopReason,+ elapsedMs: run.elapsedMs,itemCount: countItems(run.result),});} catch {@@ -47,6 +69,39 @@ export async function listRuns(env = process.env, limit = 30) {return runs;}+export async function markInterruptedRuns(env = process.env) {+ let files;+ try {+ files = await readdir(runsDir(env));+ } catch (error) {+ if (error?.code === "ENOENT") return 0;+ throw error;+ }+ let changed = 0;+ for (const name of files.filter((value) => value.endsWith(".json"))) {+ let run;+ try {+ run = JSON.parse(await readFile(path.join(runsDir(env), name), "utf8"));+ } catch {+ continue;+ }+ if (run.status !== "running") continue;+ const stopReason = "The local process stopped before this run completed.";+ const report = String(run.report || "").replace("Research is still in progress.", stopReason);+ await saveRun({+ ...run,+ updatedAt: new Date().toISOString(),+ status: "interrupted",+ stopReason,+ result: { ...(run.result || {}), ok: false },+ report,+ finalSocaiOutput: report,+ }, env);+ changed += 1;+ }+ return changed;+}+export async function readRun(id, env = process.env) {if (!/^[A-Za-z0-9_.-]+$/.test(id)) return null;try {diff --git a/src/server.js b/src/server.jsindex cc7e035..0c9d0c9 100644--- a/src/server.js+++ b/src/server.js@@ -11,7 +11,7 @@ import { getConfigPath, readConfig, resolveApiKey } from "./config.js";import { errorPayload } from "./errors.js";import { loadLocalEnv } from "./env.js";import { saveOnboarding } from "./onboard.js";-import { listRuns, readRun } from "./runs.js";+import { listRuns, markInterruptedRuns, readRun } from "./runs.js";import { probeSocai } from "./socai.js";const PUBLIC_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../public");@@ -20,6 +20,7 @@ const STATIC_FILES = {"/": ["index.html", "text/html; charset=utf-8"],"/app.js": ["app.js", "text/javascript; charset=utf-8"],"/evidence-preview.js": ["evidence-preview.js", "text/javascript; charset=utf-8"],+ "/run-route.js": ["run-route.js", "text/javascript; charset=utf-8"],"/prompts.js": ["prompts.js", "text/javascript; charset=utf-8"],"/styles.css": ["styles.css", "text/css; charset=utf-8"],"/report-download.js": ["report-download.js", "text/javascript; charset=utf-8"],@@ -30,6 +31,7 @@ const STATIC_FILES = {export async function startServer({ port = 8766, open = true, env = process.env } = {}) {await loadLocalEnv(env);+ await markInterruptedRuns(env);const numericPort = Number(port);if (!Number.isInteger(numericPort) || numericPort < 0 || numericPort > 65_535) {throw new Error("port must be an integer between 0 and 65535");diff --git a/test/app.test.js b/test/app.test.jsindex 0a381aa..65fe2e1 100644--- a/test/app.test.js+++ b/test/app.test.js@@ -4,6 +4,7 @@ import os from "node:os";import path from "node:path";import test from "node:test";import { runSearch } from "../src/app.js";+import { listRuns, readRun } from "../src/runs.js";async function fixture() {const directory = await mkdtemp(path.join(os.tmpdir(), "jev-social-actions-"));@@ -29,7 +30,7 @@ else if (command === 'search') {]});} else if (command === 'get-posts') {console.error('run_dir: /tmp/private/run');- result({ok:true,posts:[{ok:true,url:args[3],entity:{caption:'A handmade bowl',thumbnail_url:'https://cdn.example/art.jpg',local_path:'/tmp/private/post.json'},comments:[{text:'Love the glaze'}]}]});+ result({ok:true,posts:[{ok:true,url:args[3],entity:{caption:'A handmade bowl stored at /tmp/private/raw.json',thumbnail_url:'https://cdn.example/art.jpg',local_path:'/tmp/private/post.json',stdout:'raw private output',cookies:[{name:'sid',value:'secret-cookie'}],dom:'<html>private DOM</html>'},comments:[{text:'Love the glaze'}]}]});} else if (command === 'get-videos') {result({ok:true,videos:[{ok:true,locator:args[3],entity:{url:args[3],title:'Selected video',video:args.includes('--download-media')?{local_path:'/tmp/video.mp4'}:{}}}]});} else if (command === 'profile') result({ok:true,profile:{url:args[2],name:'Maker'},posts:[{url:'https://www.instagram.com/p/new/',caption:'New artwork'}]});@@ -155,3 +156,39 @@ test("an invented action never reaches the CLI", async () => {await assert.rejects(runSearch({query:'find art on Instagram'},{env,client:choices('instagram',()=> 'run_shell')}),{code:'INVALID_JEV_RESPONSE'});} finally { await rm(directory,{recursive:true,force:true}); }});++test("an interrupted run checkpoints completed actions and public evidence", async () => {+ const { directory, env } = await fixture();+ const controller = new AbortController();+ const client = choices("instagram", (criteria, step) => {+ if (step === 0) return matching(criteria, /^Search instagram/);+ return matching(criteria, /Open this post.*\/second\//);+ });+ try {+ await assert.rejects(+ runSearch(+ { query: "find handmade art on Instagram" },+ {+ env,+ client,+ signal: controller.signal,+ onEvent: (event) => {+ if (event.stage === "evidence" && event.items.some((item) => item.detail_read)) controller.abort();+ },+ },+ ),+ { name: "AbortError" },+ );+ const history = await listRuns(env);+ assert.equal(history.length, 1);+ assert.equal(history[0].status, "interrupted");+ const checkpoint = await readRun(history[0].id, env);+ assert.equal(checkpoint.status, "interrupted");+ assert.deepEqual(checkpoint.actions.map((entry) => entry.status), ["completed", "completed"]);+ assert.ok(checkpoint.result.items.some((item) => item.detail_read));+ assert.match(checkpoint.report, /handmade bowl/i);+ const serialized = JSON.stringify(checkpoint);+ assert.doesNotMatch(serialized, /\/tmp\/private|local_path|socaiOutputs|stdout|secret-cookie|private DOM/);+ assert.match(serialized, /\[redacted path\]/);+ } finally { await rm(directory, { recursive: true, force: true }); }+});diff --git a/test/run-route.test.js b/test/run-route.test.jsnew file mode 100644index 0000000..48dd0ac--- /dev/null+++ b/test/run-route.test.js@@ -0,0 +1,13 @@+import assert from "node:assert/strict";+import test from "node:test";+import { parseRunRoute, resultHash } from "../public/run-route.js";++test("result routes carry a recoverable run id", () => {+ assert.deepEqual(parseRunRoute("#results/20260922010101-a1b2c3"), {+ view: "results",+ id: "20260922010101-a1b2c3",+ });+ assert.deepEqual(parseRunRoute("#results"), { view: "results", id: "" });+ assert.equal(parseRunRoute("#results/../../etc"), null);+ assert.equal(resultHash("20260922010101-a1b2c3"), "#results/20260922010101-a1b2c3");+});diff --git a/test/runs.test.js b/test/runs.test.jsnew file mode 100644index 0000000..2eb78f3--- /dev/null+++ b/test/runs.test.js@@ -0,0 +1,53 @@+import assert from "node:assert/strict";+import { mkdtemp, rm } from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import test from "node:test";+import { listRuns, markInterruptedRuns, readRun, saveRun } from "../src/runs.js";++test("startup recovery marks stale running checkpoints as interrupted", async () => {+ const directory = await mkdtemp(path.join(os.tmpdir(), "jev-social-runs-"));+ const env = { ...process.env, JEV_SOCIAL_HOME: directory };+ try {+ await saveRun({+ id: "stale-run",+ createdAt: "2026-09-22T00:00:00.000Z",+ status: "running",+ stopReason: "Research is still in progress.",+ result: { ok: false, items: [{ url: "https://example.com/post" }] },+ report: "# Captured evidence\n\nThe run is partial.",+ }, env);+ assert.equal(await markInterruptedRuns(env), 1);+ const recovered = await readRun("stale-run", env);+ assert.equal(recovered.status, "interrupted");+ assert.equal(recovered.result.ok, false);+ assert.match(recovered.stopReason, /process stopped/i);+ assert.equal(await markInterruptedRuns(env), 0);+ } finally { await rm(directory, { recursive: true, force: true }); }+});++test("concurrent checkpoints for one run remain valid JSON", async () => {+ const directory = await mkdtemp(path.join(os.tmpdir(), "jev-social-runs-"));+ const env = { ...process.env, JEV_SOCIAL_HOME: directory };+ try {+ await Promise.all(Array.from({ length: 20 }, (_, sequence) => saveRun({+ id: "shared-run",+ createdAt: "2026-09-22T00:00:00.000Z",+ status: "running",+ sequence,+ result: { items: Array.from({ length: sequence }, (__, index) => ({ id: index })) },+ }, env)));+ const recovered = await readRun("shared-run", env);+ assert.equal(recovered.sequence, 19);+ assert.equal(recovered.result.items.length, 19);+ assert.equal((await listRuns(env)).length, 1);+ } finally { await rm(directory, { recursive: true, force: true }); }+});++test("saveRun rejects ids that could escape the runs directory", async () => {+ const directory = await mkdtemp(path.join(os.tmpdir(), "jev-social-runs-"));+ const env = { ...process.env, JEV_SOCIAL_HOME: directory };+ try {+ await assert.rejects(saveRun({ id: "../outside", result: {} }, env), /invalid characters/i);+ } finally { await rm(directory, { recursive: true, force: true }); }+});