Merge current master and shared chat guidance into Speko UI

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* codex/speko-voice-runtime:
  fix(recovery): surface exhausted review-path repair (#15764)
  fix(slack): link created tasks in default reply guidance (#15579)
  fix(slack): require result and review updates in conversation prompts (#15611)
  Fix idle sleep checks for finished login and wake history (#15761)
  ci: use a Docker Hub mirror for image builds (#15756)
  fix(release): retry incomplete canary dependency publications (#15743)
  fix(release): reuse publisher lockfile for canary smoke (#15712)
This commit is contained in:
DottaandPaperclip committed 2026-10-09 21:11:35 -05:00
commit abdd8b5f9c
27 files changed
+1157 -35

No files matched your search

+4
View File
@@ -183,6 +183,10 @@ jobs:
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
with:
buildkitd-config-inline: |
[registry."docker.io"]
mirrors = ["mirror.gcr.io"]
# Deployment tooling reads these labels from the registry to verify an
# image's schema expectations against a migrator before deploying it,
+27
View File
@@ -224,6 +224,10 @@ jobs:
pnpm install --resolution-only --ignore-scripts --ignore-pnpmfile --no-frozen-lockfile
echo "TOOLS_EPOCH=$(date -u +%G-W%V)" >> "$GITHUB_ENV"
- uses: docker/setup-buildx-action@37fe631027851001ddb9b187196cc803df7f5f0e # v4
with:
buildkitd-config-inline: |
[registry."docker.io"]
mirrors = ["mirror.gcr.io"]
- name: Build the immutable cloud image without registry credentials
uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a # v7
with:
@@ -354,6 +358,7 @@ jobs:
- name: Checkout repository
uses: actions/checkout@v7
with:
ref: ${{ github.sha }}
fetch-depth: 0
- name: Setup pnpm
@@ -373,6 +378,18 @@ jobs:
- name: Install dependencies
run: pnpm install --no-frozen-lockfile
# Master can precede the separate lockfile-refresh PR. Preserve the
# resolution used for this build before release tooling restores the
# tracked lockfile or rewrites workspace versions.
- name: Save canary smoke lockfile
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: canary-smoke-lockfile-${{ github.sha }}
path: pnpm-lock.yaml
if-no-files-found: error
overwrite: true
retention-days: 14
- name: Restore tracked install-time changes
run: git checkout -- pnpm-lock.yaml
@@ -447,6 +464,9 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
ref: ${{ github.sha }}
persist-credentials: false
- name: Setup pnpm
uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6
@@ -458,6 +478,13 @@ jobs:
with:
node-version: 24
# Default download scope is this workflow run, including job reruns.
# A missing artifact fails instead of resolving a different dependency set.
- name: Restore canary smoke lockfile
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
with:
name: canary-smoke-lockfile-${{ github.sha }}
- name: Install test dependencies
run: pnpm install --frozen-lockfile
+5
View File
@@ -715,6 +715,11 @@ a real mention. **Done** finishes setup once webhook verification and required
account linking are complete, whether or not a test message was sent. The
separate strict connection-test API retains its conversation and delivery checks.
New Slack conversations receive default communication guidance that requires a
clickable link to each task the agent creates. Agents use the public task URL
from Paperclip tools or task context and report when a link is unavailable.
Existing conversations keep their original communication guidance snapshot.
### Chat activity pagination and callback diagnostics
The connection Activity tab loads 25 records per page. `GET /api/chat-endpoints/:id/activity?limit=25`
+27
View File
@@ -100,9 +100,22 @@ It:
- publishes the user-facing `paperclipai` package last, so `paperclipai@canary` does not advance before the full package set exists
- verifies that `canary` resolves to the just-published version and that published internal dependencies exist on npm
- installs `paperclipai@canary` into a clean temporary prefix as the final npm gate
- starts the exact published canary through a separate fresh npm install for the onboarding smoke; only npm `ETARGET` install failures retry, up to three attempts within two minutes, before onboarding runs once under the existing five-minute startup deadline
- fails by default if npm leaves `latest` pointing at a canary; use `--allow-canary-latest` only when that state is intentional
- creates a git tag `canary/vYYYY.MDD.P-canary.N`
After publication, the onboarding smoke checks out the same source SHA and
installs its test dependencies from the publisher's resolved lockfile with
`--frozen-lockfile`. The same-run artifact is captured before tracked files are
restored or release versions are rewritten. This lets a source commit use its
current patches and manifests while the separate lockfile-refresh PR is still
pending, without resolving new dependencies in the smoke job. The smoke still installs and tests
the exact published canary version, not a workspace build.
The lockfile artifact is retained for 14 days. A publisher-job rerun replaces its
source-named artifact; a smoke-only rerun uses the existing artifact. A missing
artifact fails the job rather than falling back to a different dependency set.
Users install canaries with:
```bash
@@ -291,6 +304,20 @@ suppresses push-triggered workflow runs for those pushes. The release jobs
therefore dispatch `docker.yml` explicitly at the new tag ref; the tag
mapping keys off `github.ref` either way.
The Docker build matrix and the release preview image builder configure
BuildKit to check `mirror.gcr.io` for Docker Hub images first. This covers
both the Dockerfile frontend and base images. BuildKit keeps Docker Hub as
the fallback when the cache has no usable copy. The image references,
build arguments, GHCR publication, and release gates stay the same.
This is an availability improvement, not an outage guarantee. Google can
evict cached images, and mutable tags can lag upstream changes or deletions.
Matching manifests at one point does not guarantee later tag freshness or
blob availability. The initial `moby/buildkit` bootstrap still uses the host
Docker daemon and can fail on Docker Hub before this configuration takes
effect. See the [BuildKit mirror configuration](https://docs.docker.com/build/ci/github-actions/configure-builder/#registry-mirror)
and [Google cache limits](https://docs.cloud.google.com/artifact-registry/docs/pull-cached-dockerhub-images).
## Local Commands
### Preview a canary locally
+2
View File
@@ -682,6 +682,8 @@ Agent-assigned `in_review` with no typed participant is only healthy when one of
An `in_review` issue is stalled when it has no typed participant, no pending interaction or approval, no user owner, no active monitor, no active run, no queued wake, and no explicit recovery action. Paperclip should surface that state as recovery work rather than silently completing the issue or leaving blocker chains parked indefinitely.
When a maintained review path is consumed, Paperclip queues one normal-model repair wake per consumed-path fingerprint. If an external check is still pending, that repair must persist a new one-shot issue monitor and report its scheduled check time; a promise to check later does not schedule a wake. If the repair also finishes without a maintained path, Paperclip atomically rechecks the issue's current owner and review paths, then blocks it with a board-owned recovery action and an inline notice linking the repair run. The original assignee is preserved. A new maintained path or a newer run prevents stale finalization from escalating the issue. The stranded-issue sweep retries this same disposition from the saved terminal repair run if a restart or transaction failure prevented finalization. A due or claimed monitor whose bounds remain valid is preserved for monitor dispatch while its owner permits on-demand wakes; passing its due time does not consume it. Disabling those wakes cannot let an overdue monitor hide an exhausted repair indefinitely. Exhaustion never queues another automatic repair wake.
When an execution-policy review stage has a pending agent participant, the participant's run is part of the review path only while it is live or queued. If that participant run reaches a terminal state while `executionState.status` remains `pending`, no decision has been recorded. After a successful run with no review decision, Paperclip should queue one bounded normal-model recovery wake for the same participant when the agent is invokable and no other review path exists. A failed participant instead follows the provider-continuity rules below: local conversational adapters can start a bounded continuation turn, while native sessions use validated resume/replacement. Other adapters retain their action-recovery gates. The original assignee stays unchanged. If that recovery run also finishes while the stage remains pending, or the participant cannot be invoked, Paperclip must move the source issue to an explicit blocked/recovery path instead of leaving `in_review` to drift silently.
### Issue monitors
+9
View File
@@ -120,6 +120,15 @@ block sleep even when their watched issue is complete and no review has started.
Missing migrations, malformed configuration and database errors produce unknown
without exposing SQL or tenant data.
Finished login-session history permits sleep only after its promotion claim is
cleared and any retained provider reference has a matching released or expired
lease with successful cleanup and a release timestamp in the same company and
environment. Missing cleanup evidence, `cleanup_pending`, and live login flows
remain blockers. A finished coalesced wake is history only when its exact
company/agent's linked run has finished without retry or accounting debt.
Image-setup history still blocks: promotion can succeed before teardown is
confirmed, so a terminal label does not prove that its provider resource is gone.
Every enabled plugin blocks sleep. A version label does not prove that arbitrary
worker code has no background activity. No plugin approval or configuration
bypass is supported. Scheduled and externally triggered work needs a durable
+1 -1
View File
@@ -61,7 +61,7 @@
"smoke:posthog-live": "node scripts/smoke/posthog-live.mjs",
"smoke:pipelines-tutorial": "./scripts/smoke/pipelines-tutorial-smoke.sh",
"smoke:terminal-bench-loop-skill": "node scripts/smoke/terminal-bench-loop-skill-smoke.mjs",
"test:release-registry": "node --test scripts/__tests__/cursor-public-install-sandbox.test.mjs scripts/__tests__/grok-public-install-sandbox.test.mjs scripts/__tests__/retain-runner-qualification-packages.test.mjs scripts/verify-release-registry-state.test.mjs scripts/release-package-map.test.mjs scripts/check-release-package-bootstrap.test.mjs scripts/check-no-git-push.test.mjs scripts/release-lib.test.mjs scripts/release-registry-versions.test.mjs scripts/link-plugin-dev-sdk.test.js scripts/acpx-patch-packaging.test.mjs scripts/service-onboard-smoke.test.mjs scripts/docker-onboard-smoke.test.mjs scripts/preview-artifacts.test.mjs scripts/cloud-migrator-artifacts.test.mjs",
"test:release-registry": "node --test scripts/__tests__/canary-startup-playwright.test.mjs scripts/__tests__/cursor-public-install-sandbox.test.mjs scripts/__tests__/grok-public-install-sandbox.test.mjs scripts/__tests__/retain-runner-qualification-packages.test.mjs scripts/verify-release-registry-state.test.mjs scripts/release-package-map.test.mjs scripts/check-release-package-bootstrap.test.mjs scripts/check-no-git-push.test.mjs scripts/release-lib.test.mjs scripts/release-registry-versions.test.mjs scripts/link-plugin-dev-sdk.test.js scripts/acpx-patch-packaging.test.mjs scripts/service-onboard-smoke.test.mjs scripts/docker-onboard-smoke.test.mjs scripts/preview-artifacts.test.mjs scripts/cloud-migrator-artifacts.test.mjs",
"storybook-visual:baseline": "node scripts/storybook-visual-baseline.mjs",
"test:storybook-visual": "node scripts/storybook-visual-baseline.mjs download && node scripts/storybook-visual-baseline.mjs verify && pnpm build-storybook && npx playwright test --config tests/storybook-visual/playwright.config.ts",
"test:storybook-visual:update": "node scripts/storybook-visual-baseline.mjs download && pnpm build-storybook && npx playwright test --config tests/storybook-visual/playwright.config.ts --update-snapshots && node scripts/storybook-visual-baseline.mjs pack",
@@ -0,0 +1,114 @@
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync } from "node:fs";
import os from "node:os";
import net from "node:net";
import path from "node:path";
import { fileURLToPath } from "node:url";
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..");
// Exercise the real startup helper and child-process boundary without registry
// traffic. The npm fixture installs a real executable into its isolated prefix.
export async function canaryStartup({ mode, onboard = "success", budget = 5000, delay = 5, cancelAtKind, playwright = false }) {
const root = mkdtempSync(path.join(os.tmpdir(), "canary-startup-test-"));
const calls = path.join(root, "calls.jsonl");
const fixtureBin = path.join(root, "bin");
mkdirSync(fixtureBin);
const npmFixture = path.join(fixtureBin, "npm");
const port = await new Promise((resolve, reject) => {
const server = net.createServer();
server.on("error", reject);
server.listen(0, "127.0.0.1", () => { const port = server.address().port; server.close(() => resolve(port)); });
});
const cli = `#!/usr/bin/env node
const { appendFileSync } = require("node:fs");
appendFileSync(process.env.FIXTURE_CALLS, JSON.stringify({kind:"onboard", pid:process.pid, args:process.argv.slice(2)}) + "\\n");
if (process.env.FIXTURE_ONBOARD === "fail") { console.error("npm error code ETARGET"); process.exit(17); }
if (process.env.FIXTURE_ONBOARD === "hang") { setTimeout(() => {}, 10000); }
if (process.env.FIXTURE_ONBOARD === "serve") {
const { spawn } = require("node:child_process");
const child = spawn(process.execPath, ["-e", "process.on('SIGTERM',()=>{}); setTimeout(()=>process.exit(0),10000)"], {stdio:"ignore"});
appendFileSync(process.env.FIXTURE_CALLS, JSON.stringify({kind:"descendant", pid:child.pid}) + "\\n");
process.on("SIGTERM", () => {});
setTimeout(() => process.exit(0), 10000);
require("node:http").createServer((req,res) => {res.end("ok");}).listen(Number(process.env.FIXTURE_PORT), "127.0.0.1");
}
`;
writeFileSync(npmFixture, `#!/usr/bin/env node
const fs = require("node:fs");
const path = require("node:path");
const args = process.argv.slice(2);
const entries = fs.existsSync(process.env.FIXTURE_CALLS) ? fs.readFileSync(process.env.FIXTURE_CALLS, "utf8").trim().split("\\n").filter(Boolean).map(JSON.parse) : [];
const attempt = entries.filter(e => e.kind === "npm").length + 1;
fs.appendFileSync(process.env.FIXTURE_CALLS, JSON.stringify({kind:"npm", pid:process.pid, args, cache:process.env.npm_config_cache}) + "\\n");
const mode = process.env.FIXTURE_MODE;
if (mode === "hang") { setTimeout(() => {}, 10000); }
else if (mode === "permanent" || (mode === "recover" && attempt === 1)) { console.error("npm error code ETARGET"); process.exit(1); }
else if (mode === "auth") { console.error("npm error code E401"); process.exit(1); }
else if (mode === "mixed") { console.error("npm error code ETARGET\\nnpm error code E401"); process.exit(1); }
else if (mode === "network") { console.error("npm error code ECONNRESET"); process.exit(1); }
else {
const prefix = args[args.indexOf("--prefix") + 1];
const bin = path.join(prefix, "node_modules", ".bin");
fs.mkdirSync(bin, {recursive:true});
fs.writeFileSync(path.join(bin, "paperclipai"), ${JSON.stringify(cli).replaceAll('$','\$')});
fs.chmodSync(path.join(bin, "paperclipai"), 0o755);
}
`);
chmodSync(npmFixture, 0o755);
const helper = new URL("../../tests/canary-onboarding/start-published-canary.mjs", import.meta.url).href;
const driver = path.join(root, "driver.mjs");
writeFileSync(driver, `import { startPublishedCanary } from ${JSON.stringify(helper)};
try { await startPublishedCanary({version:"2026.1009.0-canary.1", workspace:${JSON.stringify(root)}, dataDir:${JSON.stringify(path.join(root,"data"))}, installBudgetMs:${budget}, retryDelayMs:${delay}}); }
catch (error) { console.error(error.message); process.exitCode = 1; }
`);
const playwrightConfig = path.join(root, "playwright.config.mjs");
if (playwright) {
const originalConfig = path.join(repoRoot, "tests/canary-onboarding/playwright.config.ts");
const testApi = new URL("../../node_modules/@playwright/test/index.mjs", import.meta.url).href;
writeFileSync(path.join(root,"fixture.spec.mjs"), `import { test } from ${JSON.stringify(testApi)}; test("fixture", async()=>{});`);
writeFileSync(playwrightConfig, `import original from ${JSON.stringify(originalConfig)};
export default {...original, testDir:${JSON.stringify(root)}, testMatch:"fixture.spec.mjs", reporter:"list", projects:[{name:"fixture"}], webServer:{...original.webServer, timeout:${mode === "hang" ? 2500 : 300000}}};`);
}
const started = Date.now();
try {
const result = await new Promise((resolve, reject) => {
const child = spawn(process.execPath, playwright
? [path.join(repoRoot, "node_modules/@playwright/test/cli.js"), "test", "--config", playwrightConfig]
: cancelAtKind
? [fileURLToPath(helper), "2026.1009.0-canary.1", root, path.join(root, "data")]
: [driver], { cwd: repoRoot, env: {
...process.env, PATH: fixtureBin + path.delimiter + process.env.PATH,
FIXTURE_MODE: mode, FIXTURE_ONBOARD: onboard, FIXTURE_CALLS: calls, FIXTURE_PORT: String(port),
PAPERCLIPAI_VERSION: "2026.1009.0-canary.1", PAPERCLIP_CANARY_SMOKE_BASE_URL: `http://127.0.0.1:${port}`, PAPERCLIP_CANARY_SMOKE_SERVER_LOG: path.join(root,"server.log"),
npm_config_cache: path.join(root, "fresh-cache"),
}, stdio: ["ignore", "pipe", "pipe"] });
let output = "";
const cancellation = cancelAtKind && setInterval(() => {
if (!existsSync(calls)) return;
const rows = readFileSync(calls, "utf8").trim().split("\n").filter(Boolean).map(JSON.parse);
if (rows.some(row => row.kind === cancelAtKind)) {
clearInterval(cancellation);
child.kill("SIGTERM");
}
}, 10);
child.stdout.on("data", (data) => { output += data; });
child.stderr.on("data", (data) => { output += data; });
child.on("error", reject);
child.on("close", (code) => { clearInterval(cancellation); resolve({code, output}); });
});
if (playwright && existsSync(path.join(root,"server.log"))) result.output += readFileSync(path.join(root,"server.log"), "utf8");
const records = existsSync(calls) ? readFileSync(calls,"utf8").trim().split("\n").filter(Boolean).map(JSON.parse) : [];
const prefixes = records.filter(call => call.kind === "npm").map(call => call.args[call.args.indexOf("--prefix") + 1]);
if (playwright) {
const deadline = Date.now() + 2000;
while (prefixes.some(prefix => existsSync(prefix)) && Date.now() < deadline) {
await new Promise(resolve => setTimeout(resolve, 20));
}
}
assert.deepEqual(prefixes.filter(prefix => existsSync(prefix)), [], "helper-owned install prefixes must be removed");
return { ...result, elapsed: Date.now()-started, calls: records };
} finally { rmSync(root, {recursive:true, force:true}); }
}
@@ -0,0 +1,29 @@
import assert from "node:assert/strict";
import test from "node:test";
import { canaryStartup } from "./canary-startup-fixture.mjs";
test("actual Playwright teardown stops the CLI and descendants that ignore SIGTERM", async () => {
const result = await canaryStartup({ mode: "success", onboard: "serve", playwright: true });
assert.equal(result.code, 0, result.output);
assert.equal(result.calls.filter(call => call.kind === "onboard").length, 1);
const processes = result.calls.filter(call => ["onboard", "descendant"].includes(call.kind));
assert.equal(processes.length, 2);
for (const call of processes) {
const deadline = Date.now() + 2000;
while (Date.now() < deadline) {
try { process.kill(call.pid, 0); } catch (error) { if (error.code === "ESRCH") break; throw error; }
await new Promise(resolve => setTimeout(resolve, 20));
}
assert.throws(() => process.kill(call.pid, 0), {code:"ESRCH"}, `fixture ${call.kind} outlived bounded teardown`);
}
});
test("actual Playwright startup timeout cancels a detached npm install", async () => {
const result = await canaryStartup({ mode: "hang", playwright: true });
assert.equal(result.code, 1);
const installs = result.calls.filter(call => call.kind === "npm");
assert.equal(installs.length, 1, result.output);
assert.equal(result.calls.filter(call => call.kind === "onboard").length, 0);
assert.throws(() => process.kill(installs[0].pid,0), {code:"ESRCH"});
assert.ok(result.elapsed < 10000, `startup timeout did not stop npm: ${result.elapsed}ms`);
});
@@ -1,9 +1,11 @@
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import { existsSync, readdirSync, readFileSync } from "node:fs";
import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import test from "node:test";
import { canaryStartup } from "./canary-startup-fixture.mjs";
const repoRoot = path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
@@ -15,6 +17,45 @@ function readWorkflow(name) {
return readFileSync(path.join(repoRoot, ".github/workflows", name), "utf8");
}
test("Docker Hub mirrors apply to both image builders without widening publication access", () => {
const dockerWorkflow = readWorkflow("docker.yml");
const releaseWorkflow = readWorkflow("release.yml");
const docker = dockerWorkflow.split(" build-and-push:\n")[1].split("\n merge-and-push:")[0];
const preview = releaseWorkflow.split(" image_preview:\n")[1].split("\n publish_image_preview:")[0];
for (const job of [docker, preview]) {
const steps = job.split(/\n(?= - )/);
const builder = steps.find((step) => /uses: docker\/setup-buildx-action@/.test(step));
const build = steps.find((step) => /uses: docker\/build-push-action@/.test(step));
assert.ok(builder && build, "the mirror must configure the builder that runs the image build");
assert.ok(steps.indexOf(builder) < steps.indexOf(build));
const config = builder.match(/buildkitd-config-inline: \|\n((?: {12,}[^\n]*(?:\n|$))+)/)?.[1];
assert.ok(config, "configure the BuildKit container, not only the host Docker daemon");
assert.deepEqual([...config.matchAll(/^\s*\[registry\."([^"]+)"\]/gm)].map((match) => match[1]), ["docker.io"],
"GHCR publishing and cache traffic must not use the pull mirror");
const mirrors = config.match(/^\s*mirrors = (\[[^\n]+\])$/m)?.[1];
assert.ok(mirrors);
assert.deepEqual(JSON.parse(mirrors), ["mirror.gcr.io"]);
assert.doesNotMatch(config, /^\s*(?:http|insecure|ca|keypair)\s*=/m,
"keep verified HTTPS and anonymous public-image pulls");
assert.doesNotMatch(builder, /driver-opts:|buildkitd-flags:|secrets\./,
"do not change bootstrap images, entitlements, or credentials");
}
assert.match(docker, /platform: linux\/amd64/);
assert.match(docker, /platform: linux\/arm64/);
assert.match(docker, /permissions:\n\s+contents: read\n\s+packages: write/);
assert.match(docker, /outputs: type=image,name=ghcr\.io\/\$\{\{ github\.repository \}\},push-by-digest=true,name-canonical=true,push=true/);
assert.match(docker, /cache-to: type=registry,ref=ghcr\.io\/\$\{\{ github\.repository \}\}:buildcache-\$\{\{ matrix\.arch \}\},mode=max/);
assert.match(preview, /permissions:\n\s+contents: read\n\s+steps:/);
assert.match(preview, /platforms: linux\/amd64\n\s+push: false/);
assert.match(preview, /outputs: type=docker,dest=\$\{\{ runner\.temp \}\}\/preview-image\.tar/);
assert.doesNotMatch(preview, /docker\/login-action|secrets\.|packages: write|id-token: write/);
assert.match(releaseWorkflow, /publish_image_preview:\n[\s\S]*?needs: \[plan_preview, image_preview\]/);
assert.doesNotMatch(dockerWorkflow.split(" merge-and-push:\n")[1], /buildkitd-config-inline/,
"the registry-only manifest merge does not need a Docker Hub mirror");
});
test("chaos verification isolates callers that verify the same source commit", () => {
const chaosWorkflow = readWorkflow("runner-chaos-evals.yml");
const group = chaosWorkflow.match(/^ group: (.+)$/m)?.[1];
@@ -170,6 +211,99 @@ test("published canaries are gated by the exact-version onboarding browser smoke
assert.match(releaseWorkflow, /tests\/canary-onboarding\/playwright-report/);
});
test("canary smoke consumes its publisher's source-bound lockfile before frozen installation", () => {
const workflow = readWorkflow("release.yml");
const publish = workflow.split(" publish_canary:\n")[1].split(" smoke_canary_onboarding:\n")[0];
const smoke = workflow.split(" smoke_canary_onboarding:\n")[1].split(" # ----- Nightly lane")[0];
for (const job of [publish, smoke]) {
assert.match(job, /name: Checkout repository\n\s+uses: actions\/checkout@[^\n]+\n\s+with:\n\s+ref: \$\{\{ github\.sha \}\}/);
assert.match(job, /name: canary-smoke-lockfile-\$\{\{ github\.sha \}\}/);
assert.match(job, /version: 9\.15\.4/);
}
assert.match(publish, /name: Save canary smoke lockfile\n\s+uses: actions\/upload-artifact@[0-9a-f]{40} # v4\n\s+with:\n\s+name: canary-smoke-lockfile-\$\{\{ github\.sha \}\}\n\s+path: pnpm-lock\.yaml\n\s+if-no-files-found: error\n\s+overwrite: true\n\s+retention-days: 14/);
assert.ok(publish.indexOf("name: Install dependencies") < publish.indexOf("name: Save canary smoke lockfile"));
assert.ok(publish.indexOf("name: Save canary smoke lockfile") < publish.indexOf("name: Restore tracked install-time changes"));
assert.ok(publish.indexOf("name: Restore tracked install-time changes") < publish.indexOf("name: Publish canary"));
assert.match(smoke, /name: Restore canary smoke lockfile\n\s+uses: actions\/download-artifact@[0-9a-f]{40} # v4\n\s+with:\n\s+name: canary-smoke-lockfile-\$\{\{ github\.sha \}\}/);
assert.ok(smoke.indexOf("name: Restore canary smoke lockfile") < smoke.indexOf("name: Install test dependencies"));
assert.doesNotMatch(smoke, /run-id:|github-token:|repository:|continue-on-error|--no-frozen-lockfile/);
});
for (const drift of ["patch", "manifest"]) {
test(`a publisher lockfile lets a fresh smoke install retain validation after ${drift} drift`, (t) => {
const root = mkdtempSync(path.join(os.tmpdir(), "canary-smoke-lockfile-test-"));
t.after(() => rmSync(root, { recursive: true, force: true }));
const source = path.join(root, "package");
mkdirSync(source);
writeFileSync(path.join(source, "package.json"), JSON.stringify({ name: "smoke-fixture-dependency", version: "1.0.0" }));
writeFileSync(path.join(source, "index.js"), 'module.exports = "original";\n');
const pack = spawnSync("npm", ["pack", "--ignore-scripts", "--pack-destination", root], { cwd: source, encoding: "utf8" });
assert.equal(pack.status, 0, pack.stderr);
const manifest = {
name: "canary-smoke-fixture", private: true,
packageManager: "pnpm@9.15.4",
dependencies: { "smoke-fixture-dependency": "file:smoke-fixture-dependency-1.0.0.tgz" },
pnpm: { patchedDependencies: { "smoke-fixture-dependency@1.0.0": "fixture.patch" } },
};
writeFileSync(path.join(root, "package.json"), JSON.stringify(manifest));
writeFileSync(path.join(root, "pnpm-workspace.yaml"), "packages: []\n");
const patch = (value) => writeFileSync(path.join(root, "fixture.patch"), [
"diff --git a/index.js b/index.js", "index 1111111..2222222 100644",
"--- a/index.js", "+++ b/index.js", "@@ -1 +1 @@",
'-module.exports = "original";', `+module.exports = "${value}";`, "",
].join("\n"));
const workflow = readWorkflow("release.yml");
const publish = workflow.split(" publish_canary:\n")[1].split(" smoke_canary_onboarding:\n")[0];
const smoke = workflow.split(" smoke_canary_onboarding:\n")[1].split(" # ----- Nightly lane")[0];
const installArgs = (name) => {
const job = name === "Install dependencies" ? publish : smoke;
const command = job.match(new RegExp(`name: ${name}\\n\\s+run: (pnpm install[^\\n]+)`))?.[1];
assert.ok(command, `missing ${name}`);
return [...command.split(" ").slice(1), "--offline", "--ignore-scripts"];
};
const install = (args) => spawnSync("pnpm", args, {
cwd: root, encoding: "utf8", env: { ...process.env, CI: "true" },
});
const success = (result) => assert.equal(result.status, 0, `${result.stdout}\n${result.stderr}`);
patch(drift === "patch" ? "old-patch" : "published-patch");
success(install(installArgs("Install dependencies")));
const staleLock = readFileSync(path.join(root, "pnpm-lock.yaml"));
if (drift === "patch") {
patch("published-patch");
} else {
copyFileSync(path.join(root, "smoke-fixture-dependency-1.0.0.tgz"), path.join(root, "updated-dependency.tgz"));
manifest.dependencies["smoke-fixture-dependency"] = "file:updated-dependency.tgz";
writeFileSync(path.join(root, "package.json"), JSON.stringify(manifest));
}
const before = install(installArgs("Install test dependencies"));
assert.notEqual(before.status, 0);
assert.match(before.stdout + before.stderr, drift === "patch" ? /ERR_PNPM_LOCKFILE_CONFIG_MISMATCH/ : /ERR_PNPM_OUTDATED_LOCKFILE/);
// Capture the publisher's resolution, then reproduce its tracked-file restore
// and a fresh smoke runner with no installed workspace dependencies.
success(install(installArgs("Install dependencies")));
const artifact = path.join(root, "publisher-lock.yaml");
if (publish.includes("name: Save canary smoke lockfile")) {
copyFileSync(path.join(root, "pnpm-lock.yaml"), artifact);
}
writeFileSync(path.join(root, "pnpm-lock.yaml"), staleLock);
rmSync(path.join(root, "node_modules"), { recursive: true, force: true });
if (smoke.includes("name: Restore canary smoke lockfile")) {
copyFileSync(artifact, path.join(root, "pnpm-lock.yaml"));
}
success(install(installArgs("Install test dependencies")));
assert.equal(readFileSync(path.join(root, "node_modules/smoke-fixture-dependency/index.js"), "utf8"), 'module.exports = "published-patch";\n');
assert.deepEqual(readFileSync(path.join(root, "pnpm-lock.yaml")), readFileSync(artifact));
// A lockfile from the wrong source still fails closed; restoring an artifact
// must not disable hash validation or resolve another version in the smoke job.
patch("different-source");
const wrongSource = install(installArgs("Install test dependencies"));
assert.notEqual(wrongSource.status, 0);
assert.match(wrongSource.stdout + wrongSource.stderr, /ERR_PNPM_LOCKFILE_CONFIG_MISMATCH/);
});
}
test("every lane's tag push degrades to recovery instructions when rejected", () => {
const releaseWorkflow = readWorkflow("release.yml");
@@ -480,3 +614,94 @@ test("direct protocol concurrency override only lowers the configured ceiling",
if (expected !== null) assert.equal(result.stdout, expected);
}
});
test("canary startup refreshes an incomplete dependency publication, then onboards once", async () => {
const result = await canaryStartup({ mode: "recover" });
assert.equal(result.code, 0, result.output);
const installs = result.calls.filter(call => call.kind === "npm");
const onboarding = result.calls.filter(call => call.kind === "onboard");
assert.equal(installs.length, 2);
assert.equal(onboarding.length, 1);
for (const call of installs) {
assert.equal(call.args[0], "install");
assert.ok(call.args.includes("paperclipai@2026.1009.0-canary.1"));
assert.ok(call.args.includes("--no-package-lock"));
assert.ok(call.args.includes("--no-save"));
}
assert.ok(!installs[0].args.includes("--prefer-online"));
assert.ok(installs[1].args.includes("--prefer-online"));
assert.notEqual(installs[0].args[2], installs[1].args[2]);
assert.equal(installs[0].cache, installs[1].cache);
assert.deepEqual(onboarding[0].args.slice(0, 3), ["onboard", "--yes", "--data-dir"]);
});
test("permanent missing versions stop after three attempts without onboarding", async () => {
const result = await canaryStartup({ mode: "permanent" });
assert.equal(result.code, 1);
assert.equal(result.calls.filter(call => call.kind === "npm").length, 3);
assert.equal(result.calls.filter(call => call.kind === "onboard").length, 0);
assert.match(result.output, /installation failed.*onboarding was not started/);
});
test("npm failures other than ETARGET fail immediately without onboarding", async () => {
const result = await canaryStartup({ mode: "auth" });
assert.equal(result.code, 1);
assert.equal(result.calls.length, 1);
assert.match(result.output, /E401/);
});
test("onboarding failures are never retried, even when they mention ETARGET", async () => {
const result = await canaryStartup({ mode: "success", onboard: "fail" });
assert.equal(result.code, 1);
assert.equal(result.calls.filter(call => call.kind === "npm").length, 1);
assert.equal(result.calls.filter(call => call.kind === "onboard").length, 1);
assert.match(result.output, /onboarding failed \(exit 17\)/);
});
test("a hanging npm install is stopped within the shared acquisition budget", async () => {
const result = await canaryStartup({ mode: "hang", budget: 1000 });
assert.equal(result.code, 1);
assert.equal(result.calls.filter(call => call.kind === "npm").length, 1);
assert.equal(result.calls.filter(call => call.kind === "onboard").length, 0);
assert.ok(result.elapsed < 4000, `install exceeded bounded cancellation: ${result.elapsed}ms`);
assert.match(result.output, /exceeded its startup budget/);
});
test("backoff consumes the shared budget and does not begin another install after expiry", async () => {
const result = await canaryStartup({ mode: "permanent", budget: 1000, delay: 5000 });
assert.equal(result.code, 1);
assert.equal(result.calls.length, 1);
assert.match(result.output, /exceeded its startup budget/);
});
test("Playwright cancellation stops an onboarding process without replay", async () => {
const result = await canaryStartup({ mode: "success", onboard: "hang", cancelAtKind: "onboard" });
assert.equal(result.code, 1);
assert.equal(result.calls.filter(call => call.kind === "npm").length, 1);
const onboarding = result.calls.filter(call => call.kind === "onboard");
assert.equal(onboarding.length, 1);
assert.throws(() => process.kill(onboarding[0].pid, 0), {code:"ESRCH"});
assert.match(result.output, /stopped by SIGTERM/);
assert.ok(result.elapsed < 2500, `onboarding cancellation took ${result.elapsed}ms`);
});
test("canary install retries retain the existing overall Playwright startup deadline", async () => {
const { INSTALL_BUDGET_MS } = await import("../../tests/canary-onboarding/start-published-canary.mjs");
const config = readFileSync(path.join(repoRoot, "tests/canary-onboarding/playwright.config.ts"), "utf8");
assert.equal(INSTALL_BUDGET_MS, 120_000);
assert.match(config, /timeout: 300_000/);
assert.match(config, /start-published-canary\.mjs/);
assert.match(config, /reuseExistingServer: false/);
});
test("nested ETARGET output does not retry a final authentication or network failure", async () => {
for (const mode of ["mixed", "network"]) {
const result = await canaryStartup({ mode });
assert.equal(result.code, 1);
assert.equal(result.calls.length, 1);
}
});
@@ -301,6 +301,11 @@ describe("buildPaperclipTaskMarkdown", () => {
externalChatProvider: "slack", nativeRunner, includeDescription,
});
expect(markdown).toContain("Interactive questions in Slack:");
expect(markdown).toContain("When you have results, update the user in the originating Slack");
expect(markdown).toContain("When the user needs to review a plan, approve an action, or review a result");
expect(markdown).toContain("create the required human-input or approval interaction before you yield");
expect(markdown).toContain("Saving a plan or setting a task to in_review alone does not ask the user to review it");
expect(markdown).toContain("do not continue gated work until the required approval is recorded");
expect(markdown).toContain("ask_user_questions");
expect(markdown).toContain("single_select");
expect(markdown).toContain("resumes this task after the answer");
@@ -1,5 +1,5 @@
import { randomUUID } from "node:crypto";
import { and, eq } from "drizzle-orm";
import { and, eq, sql } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import {
activityLog,
@@ -70,6 +70,7 @@ vi.mock("../adapters/index.ts", async () => {
import { heartbeatService } from "../services/heartbeat.ts";
import { attentionService } from "../services/attention.ts";
import { issueService } from "../services/issues.ts";
import { escalateExhaustedIssueReviewPathRecovery } from "../services/recovery/review-path-recovery-escalation.ts";
import { runningProcesses } from "../adapters/index.ts";
import {
buildIssueBlockersResolvedWakeStateKey,
@@ -342,7 +343,7 @@ describeEmbeddedPostgres("heartbeat resolved dependency wake reconciliation", ()
return { companyId, agentId, blockedIssueId, blockerIssueId, executionWorkspaceId };
}
it("runs exactly one bounded review-path recovery before surfacing a stalled decision", async () => {
it.each(["pathless", "monitor"] as const)("runs exactly one bounded review-path recovery with %s disposition", async (disposition) => {
const companyId = randomUUID();
const agentId = randomUUID();
const issueId = randomUUID();
@@ -368,7 +369,7 @@ describeEmbeddedPostgres("heartbeat resolved dependency wake reconciliation", ()
await db.insert(issues).values({
id: issueId,
companyId,
title: "PAP-14994 fingerprint",
title: "External build follow-up",
status: "in_review",
priority: "medium",
assigneeAgentId: agentId,
@@ -377,6 +378,16 @@ describeEmbeddedPostgres("heartbeat resolved dependency wake reconciliation", ()
identifier: `${issuePrefix}-1`,
});
if (disposition === "monitor") {
const execute = mockAdapterExecute.getMockImplementation()!;
mockAdapterExecute.mockImplementationOnce(execute).mockImplementationOnce(async () => {
await issueService(db).update(issueId, {
monitorNextCheckAt: new Date(Date.now() + 60_000), monitorNotes: "Check external build",
});
return execute();
});
}
const heartbeat = heartbeatService(db);
const followUpRun = await heartbeat.wakeup(agentId, {
source: "automation",
@@ -420,19 +431,195 @@ describeEmbeddedPostgres("heartbeat resolved dependency wake reconciliation", ()
}),
});
const attention = await issueService(db)
.listReviewAttention(companyId, [{ id: issueId, companyId, status: "in_review" }]);
expect(attention.get(issueId)).toMatchObject({ state: "stalled", paths: [] });
const issue = await db.select().from(issues).where(eq(issues.id, issueId)).then((rows) => rows[0]);
if (disposition === "monitor") {
expect(issue).toMatchObject({ status: "in_review", assigneeAgentId: agentId, monitorNextCheckAt: expect.any(Date) });
expect(await db.select().from(issueRecoveryActions)).toHaveLength(0);
expect(await db.select().from(issueComments)).toHaveLength(0);
const attention = await issueService(db).listReviewAttention(companyId, [issue]);
expect(attention.get(issueId)).toMatchObject({ state: "covered", paths: expect.arrayContaining([expect.objectContaining({ kind: "monitor" })]) });
return;
}
expect(issue).toMatchObject({ status: "blocked", assigneeAgentId: agentId });
const actions = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, issueId));
expect(actions).toHaveLength(1);
expect(actions[0]).toMatchObject({
ownerType: "board", ownerAgentId: null, ownerUserId: null,
returnOwnerAgentId: agentId, cause: "issue_review_path_lost", attemptCount: 1, maxAttempts: 1,
});
const notices = await db.select().from(issueComments).where(eq(issueComments.issueId, issueId));
expect(notices).toHaveLength(1);
expect(notices[0]).toMatchObject({ authorType: "system", presentation: expect.objectContaining({ title: "No follow-up scheduled" }) });
const recoveryRun = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, recoveryWakes[0].runId!)).then((rows) => rows[0]);
// Replayed finalization must not duplicate the notice, action, or wake.
expect(await escalateExhaustedIssueReviewPathRecovery(db, { run: recoveryRun, issueId })).toBeNull();
expect(await db.select().from(issueRecoveryActions)).toHaveLength(1);
expect(await db.select().from(issueComments)).toHaveLength(1);
expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.reason, "issue_review_path_lost"))).toHaveLength(1);
const feed = await attentionService(db).list(companyId, { userId: "responsible-user" });
expect(feed.items.find((item) => item.subject.id === issueId)).toMatchObject({
sourceKind: "review",
expect(feed.items.find((item) => item.subject.id === actions[0].id)).toMatchObject({
sourceKind: "recovery_action",
relatedIssue: expect.objectContaining({ id: issueId }),
decisionVerbs: expect.arrayContaining([
expect.objectContaining({ id: "choose_review_path", label: "Choose review path" }),
expect.objectContaining({ id: "resolve", label: "Resolve" }),
]),
});
});
it.each(["monitor", "completed", "reassigned", "newer_run", "other_company"] as const)(
"does not escalate a stale review recovery after %s",
async (change) => {
const companyId = randomUUID();
const agentId = randomUUID();
const issueId = randomUUID();
await db.insert(companies).values({ id: companyId, name: "Review Co", issuePrefix: `R${companyId.slice(0, 6)}` });
await db.insert(agents).values({ id: agentId, companyId, name: "Reviewer", role: "engineer", adapterType: "codex_local" });
await db.insert(issues).values({ id: issueId, companyId, title: "Async review", status: "in_review", assigneeAgentId: agentId });
const [run] = await db.insert(heartbeatRuns).values({
companyId, agentId, status: "succeeded", issueId,
createdAt: new Date(Date.now() - 60_000),
contextSnapshot: { issueId, wakeReason: "issue_review_path_lost", reviewPathRecoveryAttempt: 1 },
}).returning();
if (change === "monitor") {
await issueService(db).update(issueId, { monitorNextCheckAt: new Date(Date.now() + 60_000), monitorNotes: "Check build" });
} else if (change === "completed") {
await issueService(db).update(issueId, { status: "done" });
} else if (change === "reassigned") {
const nextAgentId = randomUUID();
await db.insert(agents).values({ id: nextAgentId, companyId, name: "New reviewer", role: "engineer", adapterType: "codex_local" });
await issueService(db).update(issueId, { assigneeAgentId: nextAgentId });
} else if (change === "newer_run") {
await db.insert(heartbeatRuns).values({ companyId, agentId, issueId, status: "succeeded", contextSnapshot: { issueId } });
}
expect(await escalateExhaustedIssueReviewPathRecovery(db, {
run: change === "other_company" ? { ...run, companyId: randomUUID() } : run,
issueId,
})).toBeNull();
expect(await db.select().from(issueRecoveryActions)).toHaveLength(0);
expect(await db.select().from(issueComments)).toHaveLength(0);
const current = await db.select().from(issues).where(eq(issues.id, issueId)).then((rows) => rows[0]);
expect(current.status).toBe(change === "completed" ? "done" : "in_review");
if (change === "monitor") expect(current.monitorNextCheckAt).not.toBeNull();
},
);
it("serializes concurrent finalization of a failed review repair", async () => {
const companyId = randomUUID();
const agentId = randomUUID();
const issueId = randomUUID();
await db.insert(companies).values({ id: companyId, name: "Review Co", issuePrefix: `R${companyId.slice(0, 6)}` });
await db.insert(agents).values({ id: agentId, companyId, name: "Reviewer", role: "engineer", adapterType: "codex_local" });
await db.insert(issues).values({ id: issueId, companyId, title: "Failed review repair", status: "in_review", assigneeAgentId: agentId });
const [run] = await db.insert(heartbeatRuns).values({
companyId, agentId, issueId, status: "failed",
contextSnapshot: { issueId, wakeReason: "issue_review_path_lost", reviewPathRecoveryAttempt: 1 },
}).returning();
const results = await Promise.all([
escalateExhaustedIssueReviewPathRecovery(db, { run, issueId }),
escalateExhaustedIssueReviewPathRecovery(db, { run, issueId }),
]);
expect(results.filter(Boolean)).toHaveLength(1);
expect(await db.select().from(issueRecoveryActions)).toHaveLength(1);
expect(await db.select().from(issueComments)).toHaveLength(1);
expect(await db.select().from(agentWakeupRequests)).toHaveLength(0);
expect(await db.select().from(activityLog).where(eq(activityLog.action, "issue.review_path_recovery_exhausted"))).toHaveLength(1);
});
it.each(["restart", "transaction_failure", "due_monitor", "claimed_monitor", "expired_monitor", "exhausted_monitor", "disabled_monitor"] as const)("reconciles a committed review repair after %s with a one-connection pool", async (gap) => {
const companyId = randomUUID();
const agentId = randomUUID();
const issueId = randomUUID();
const wakeId = randomUUID();
await db.insert(companies).values({ id: companyId, name: "Review Co", issuePrefix: `R${companyId.slice(0, 6)}`, defaultResponsibleUserId: "responsible-user" });
await db.insert(agents).values({ id: agentId, companyId, name: "Reviewer", role: "engineer", adapterType: "codex_local", runtimeConfig: { heartbeat: { wakeOnDemand: true, maxConcurrentRuns: 1 } } });
await db.insert(issues).values({ id: issueId, companyId, title: "Repair finalized before restart", status: "in_review", assigneeAgentId: agentId, responsibleUserId: "responsible-user" });
await db.insert(agentWakeupRequests).values({
id: wakeId, companyId, agentId, source: "automation", status: "completed",
reason: "issue_review_path_lost", payload: { issueId, reviewPathRecoveryAttempt: 1 },
});
const [repairRun] = await db.insert(heartbeatRuns).values({
companyId, agentId, issueId, status: "succeeded", wakeupRequestId: wakeId, finishedAt: new Date(),
contextSnapshot: { issueId, wakeReason: "issue_review_path_lost", reviewPathRecoveryAttempt: 1 },
}).returning();
const dueAt = new Date(Date.now() - 60_000);
if (gap.endsWith("monitor")) {
const monitored = await issueService(db).update(issueId, {
monitorNextCheckAt: dueAt, monitorNotes: "Check external build",
executionPolicy: { monitor: {
nextCheckAt: dueAt.toISOString(), notes: "Check external build", scheduledBy: "assignee",
kind: "external_service", serviceName: "github_checks",
...(gap === "disabled_monitor" ? {} : { timeoutAt: new Date(Date.now() + 60_000).toISOString(), maxAttempts: 3 }),
} },
});
if (gap === "disabled_monitor") {
// A policy change after saving an unbounded check must not hide the
// spent repair forever: dispatch cannot accept its on-demand wake.
await db.update(agents).set({ runtimeConfig: { heartbeat: { wakeOnDemand: false } } }).where(eq(agents.id, agentId));
} else if (gap === "claimed_monitor") {
await db.update(issues).set({ monitorWakeRequestedAt: new Date() }).where(eq(issues.id, issueId));
} else if (gap === "expired_monitor" || gap === "exhausted_monitor") {
const policy = monitored!.executionPolicy as { monitor: Record<string, unknown> };
await db.update(issues).set({
executionPolicy: { ...policy, monitor: { ...policy.monitor, ...(gap === "expired_monitor" ? { timeoutAt: new Date(Date.now() - 1_000).toISOString() } : { maxAttempts: 1 }) } },
...(gap === "exhausted_monitor" ? { monitorAttemptCount: 1 } : {}),
}).where(eq(issues.id, issueId));
}
}
// Only the terminal run and completed wake were persisted before the crash.
// A new service must restore the missing action without invoking the agent.
const singleConnectionDb = createDb(tempDb!.connectionString, { maxConnections: 1 });
try {
if (gap === "transaction_failure") {
await db.execute(sql`alter table issue_comments add constraint review_repair_notice_test check (false) not valid`);
try {
await expect(escalateExhaustedIssueReviewPathRecovery(singleConnectionDb, { run: repairRun, issueId })).rejects.toThrow();
} finally {
await db.execute(sql`alter table issue_comments drop constraint review_repair_notice_test`);
}
expect(await db.select().from(issueRecoveryActions)).toHaveLength(0);
expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0].status).toBe("in_review");
}
const recovery = heartbeatService(singleConnectionDb);
const result = await recovery.reconcileStrandedAssignedIssues();
if (gap === "due_monitor" || gap === "claimed_monitor") {
expect(result.escalated).toBe(0);
expect(await db.select().from(issueRecoveryActions)).toHaveLength(0);
expect(await db.select().from(issueComments)).toHaveLength(0);
const current = (await db.select().from(issues).where(eq(issues.id, issueId)))[0];
expect(current).toMatchObject({ status: "in_review", monitorNextCheckAt: dueAt });
// A claim left by a crashed dispatcher can be reclaimed after its lease.
if (gap === "claimed_monitor") {
await db.update(issues).set({ monitorWakeRequestedAt: new Date(Date.now() - 6 * 60_000) }).where(eq(issues.id, issueId));
}
const execute = mockAdapterExecute.getMockImplementation()!;
mockAdapterExecute.mockImplementationOnce(async () => {
await issueService(db).update(issueId, { status: "done" });
return execute();
});
const dispatcher = heartbeatService(db, { runtimeEnv: {} });
await dispatcher.tickTimers();
await dispatcher.drainActiveRunExecutions();
const wakes = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.reason, "issue_monitor_due"));
expect(wakes).toHaveLength(1);
expect(mockAdapterExecute).toHaveBeenCalledOnce();
expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0]).toMatchObject({ status: "done", monitorNextCheckAt: null });
return;
}
expect(result).toMatchObject({ escalated: 1, issueIds: [issueId] });
expect(await db.select().from(issueRecoveryActions)).toHaveLength(1);
expect(await db.select().from(issueComments)).toHaveLength(1);
const second = await recovery.reconcileStrandedAssignedIssues();
expect(second.escalated).toBe(0);
expect(await db.select().from(agentWakeupRequests)).toHaveLength(1);
expect(mockAdapterExecute).not.toHaveBeenCalled();
expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0]).toMatchObject({ status: "blocked", assigneeAgentId: agentId });
} finally {
await singleConnectionDb.$client.end({ timeout: 1 });
}
});
it("keeps resolved dependency wake reconciliation active", async () => {
const { companyId, agentId, blockedIssueId, blockerIssueId } =
await seedResolvedDependencyBackstopFixture({ workspaceState: "none" });
+128 -1
View File
@@ -178,7 +178,7 @@ if (!support.supported) console.warn(`Skipping idle sleep Postgres tests: ${supp
const companyId = randomUUID();
const agentId = randomUUID();
const runId = randomUUID();
await db.insert(companies).values({ id: companyId, name: "Idle test", issuePrefix: "IDLE" });
await db.insert(companies).values({ id: companyId, name: "Idle test", issuePrefix: `T${companyId.slice(0, 6).toUpperCase()}` });
await db.insert(agents).values({ id: agentId, companyId, name: "On-demand agent", role: "engineer", status: "idle", adapterType: "process" });
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, invocationSource: "on_demand", status: "succeeded" });
return { companyId, agentId, runId };
@@ -246,6 +246,44 @@ if (!support.supported) console.warn(`Skipping idle sleep Postgres tests: ${supp
expect(await read()).toEqual(present);
});
it("allows consumed coalesced wakes only after their linked run finishes", async () => {
const { companyId, agentId, runId } = await seed();
await db.update(heartbeatRuns).set({ status: "running" }).where(eq(heartbeatRuns.id, runId));
await db.insert(agentWakeupRequests).values({
companyId, agentId, source: "assignment", status: "coalesced", runId, finishedAt: new Date(now),
});
expect(await read()).toEqual(present);
await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date(now) })
.where(eq(heartbeatRuns.id, runId));
expect(await read()).toEqual(none);
});
it.each(["unfinished", "missing_run", "wrong_company", "wrong_agent", "unfinished_run", "retry", "accounting"])(
"keeps a coalesced wake awake with %s evidence", async kind => {
const { companyId, agentId, runId } = await seed();
await db.update(heartbeatRuns).set({ finishedAt: new Date(now) }).where(eq(heartbeatRuns.id, runId));
let linkedRunId = runId;
if (kind === "missing_run") linkedRunId = randomUUID();
if (kind === "wrong_company") {
linkedRunId = (await seed()).runId;
await db.update(heartbeatRuns).set({ finishedAt: new Date(now) }).where(eq(heartbeatRuns.id, linkedRunId));
}
if (kind === "wrong_agent") {
const otherAgentId = randomUUID();
await db.insert(agents).values({ id: otherAgentId, companyId, name: "Other agent", role: "engineer", status: "idle", adapterType: "process" });
await db.update(heartbeatRuns).set({ agentId: otherAgentId }).where(eq(heartbeatRuns.id, runId));
}
if (kind === "unfinished_run") await db.update(heartbeatRuns).set({ finishedAt: null }).where(eq(heartbeatRuns.id, runId));
if (kind === "retry") await db.update(heartbeatRuns).set({ scheduledRetryAt: new Date(now + 1000) }).where(eq(heartbeatRuns.id, runId));
if (kind === "accounting") await db.update(heartbeatRuns).set({ costAccountingPending: true }).where(eq(heartbeatRuns.id, runId));
await db.insert(agentWakeupRequests).values({
companyId, agentId, source: "assignment", status: "coalesced", runId: linkedRunId,
finishedAt: kind === "unfinished" ? null : new Date(now),
});
expect(await read()).toEqual(present);
},
);
it("blocks an active routine without waiting for its next due time", async () => {
const { companyId } = await seed();
await db.insert(routines).values({ companyId, title: "Tomorrow", status: "active" });
@@ -268,6 +306,95 @@ if (!support.supported) console.warn(`Skipping idle sleep Postgres tests: ${supp
expect(await read()).toEqual(present);
});
async function seedFinishedLogin() {
const { companyId } = await seed();
const [environment] = await db.insert(environments).values({ name: "Finished login fixture" }).returning();
const [lease] = await db.insert(environmentLeases).values({
companyId, environmentId: environment!.id, providerLeaseId: "fixture-login-resource",
status: "released", cleanupStatus: "success", releasedAt: new Date(now),
}).returning();
const [session] = await db.insert(adapterAuthSessions).values({
companyId, environmentId: environment!.id, adapterType: "codex_local",
startedByUserId: "fixture-user", publicSessionId: "finished-fixture-session",
status: "authenticated", finishedAt: new Date(now), providerLeaseId: lease!.providerLeaseId,
}).returning();
return { companyId, environment: environment!, lease: lease!, session: session! };
}
it.each(["authenticated", "completed", "failed", "timed_out", "cancelled"] as const)(
"permits finished %s login history after confirmed provider cleanup", async status => {
const { session } = await seedFinishedLogin();
await db.update(adapterAuthSessions).set({ status }).where(eq(adapterAuthSessions.id, session.id));
expect(await read()).toEqual(none);
},
);
it.each(["canonical", "uppercase"])("accepts a %s cleanup reference to the internal lease id", async format => {
const { session, lease } = await seedFinishedLogin();
await db.update(adapterAuthSessions).set({ providerLeaseId: format === "uppercase" ? lease.id.toUpperCase() : lease.id })
.where(eq(adapterAuthSessions.id, session.id));
expect(await read()).toEqual(none);
});
it.each(["fixture-provider-id", "00000000-0000-0000-0000-00000000000z", randomUUID()])(
"accepts cleaned external provider reference %s without an unsafe UUID cast", async providerLeaseId => {
const { session, lease } = await seedFinishedLogin();
await db.update(environmentLeases).set({ providerLeaseId }).where(eq(environmentLeases.id, lease.id));
await db.update(adapterAuthSessions).set({ providerLeaseId }).where(eq(adapterAuthSessions.id, session.id));
expect(await read()).toEqual(none);
},
);
it("keeps a UUID-shaped external reference awake when an internal lease conflicts", async () => {
const { companyId, environment, session, lease } = await seedFinishedLogin();
const conflictingId = randomUUID();
await db.update(environmentLeases).set({ providerLeaseId: conflictingId }).where(eq(environmentLeases.id, lease.id));
await db.update(adapterAuthSessions).set({ providerLeaseId: conflictingId }).where(eq(adapterAuthSessions.id, session.id));
await db.insert(environmentLeases).values({
id: conflictingId, companyId, environmentId: environment.id,
status: "released", cleanupStatus: "failed", releasedAt: new Date(now),
});
expect(await read()).toEqual(present);
await db.update(environmentLeases).set({ cleanupStatus: "success" }).where(eq(environmentLeases.id, conflictingId));
expect(await read()).toEqual(none);
});
it("permits terminal login history without a provider resource", async () => {
const { session } = await seedFinishedLogin();
await db.update(adapterAuthSessions).set({ providerLeaseId: null }).where(eq(adapterAuthSessions.id, session.id));
expect(await read()).toEqual(none);
});
it.each(["cleanup_pending", "starting", "promoting", "awaiting_code", "submitting", "stored"] as const)(
"retains %s login work even with an old successful cleanup receipt", async status => {
const { session } = await seedFinishedLogin();
await db.update(adapterAuthSessions).set({ status }).where(eq(adapterAuthSessions.id, session.id));
expect(await read()).toEqual(present);
},
);
it.each(["unfinished", "promotion_claim", "missing_lease", "wrong_company", "wrong_environment", "cleanup_failed", "cleanup_unknown", "unreleased", "conflicting_lease"])(
"retains terminal login history with %s cleanup evidence", async kind => {
const { companyId, session, lease, environment } = await seedFinishedLogin();
if (kind === "unfinished") await db.update(adapterAuthSessions).set({ finishedAt: null }).where(eq(adapterAuthSessions.id, session.id));
if (kind === "promotion_claim") await db.update(adapterAuthSessions).set({ promotionExpiresAt: new Date(now + 1000) }).where(eq(adapterAuthSessions.id, session.id));
if (kind === "missing_lease") await db.delete(environmentLeases).where(eq(environmentLeases.id, lease.id));
if (kind === "wrong_company") await db.update(environmentLeases).set({ companyId: (await seed()).companyId }).where(eq(environmentLeases.id, lease.id));
if (kind === "wrong_environment") {
const [other] = await db.insert(environments).values({ name: "Other environment", driver: "sandbox" }).returning();
await db.update(environmentLeases).set({ environmentId: other!.id }).where(eq(environmentLeases.id, lease.id));
}
if (kind === "cleanup_failed") await db.update(environmentLeases).set({ cleanupStatus: "failed" }).where(eq(environmentLeases.id, lease.id));
if (kind === "cleanup_unknown") await db.update(environmentLeases).set({ cleanupStatus: null }).where(eq(environmentLeases.id, lease.id));
if (kind === "unreleased") await db.update(environmentLeases).set({ releasedAt: null }).where(eq(environmentLeases.id, lease.id));
if (kind === "conflicting_lease") await db.insert(environmentLeases).values({
companyId, environmentId: environment.id, providerLeaseId: lease.providerLeaseId,
status: "released", cleanupStatus: "failed", releasedAt: new Date(now),
});
expect(await read()).toEqual(present);
},
);
it("reports a pending secret proposal with future expiry", async () => {
const { companyId, agentId, runId } = await seed();
await db.insert(companySecretProposals).values({
@@ -3,6 +3,15 @@ import { CHAT_PROVIDERS, updateChatEndpointSchema } from "@paperclipai/shared";
import { buildChatCommunicationGuidance } from "./chat-communication-guidance.js";
describe("initial medium communication guidance", () => {
it.each([true, false])("requires result and review updates in Slack (direct=%s)", (isDirectMessage) => {
const guidance = buildChatCommunicationGuidance({ provider: "slack", isDirectMessage });
expect(guidance).toContain("When you have results, update the user in the originating Slack");
expect(guidance).toContain("Put this update in your final response");
expect(guidance).toContain("When the user needs to review a plan, approve an action, or review a result");
expect(guidance).toContain("create the required human-input or approval interaction before you yield");
expect(guidance).toContain("do not continue gated work until the required approval is recorded");
});
it("guides Slack presentation while retaining ordinary agent tools and explicit output requests", () => {
const guidance = buildChatCommunicationGuidance({ provider: "slack", isDirectMessage: false, communicationInstructions: "Use customer-facing names." });
expect(guidance).toContain("shared channel thread");
@@ -24,6 +33,15 @@ describe("initial medium communication guidance", () => {
expect(guidance).toContain("Protected approvals must be completed in Paperclip");
});
it.each([false, true])("requires public links for created Slack tasks (DM: %s)", (isDirectMessage) => {
const guidance = buildChatCommunicationGuidance({ provider: "slack", isDirectMessage });
expect(guidance).toContain("include a clickable link to each created task");
expect(guidance).toContain("task identifier or title as the link text");
expect(guidance).toContain("public task URL returned by Paperclip tools or supplied in task context");
expect(guidance).toContain("never guess a URL");
expect(guidance).toContain("If no public task URL is available, say that the link is unavailable");
});
it.each(CHAT_PROVIDERS.filter((provider) => provider !== "slack" && provider !== "speko"))("leaves %s unchanged", (provider) => {
expect(buildChatCommunicationGuidance({ provider, isDirectMessage: false, communicationInstructions: "Ignored" })).toBeNull();
});
@@ -1,5 +1,6 @@
import { SPEKO_COMMUNICATION_GUIDANCE } from "./voice/speko-skill.js";
import type { ChatProvider } from "@paperclipai/shared";
import { slackTaskUpdateGuidance } from "./connectors/slack/task-update-guidance.js";
// Presentation guidance only. Task execution and permissions belong to the
// ordinary Paperclip agent runtime, not the provider transport.
@@ -7,8 +8,10 @@ const providerGuidance: Partial<Record<ChatProvider, string>> = {
speko: SPEKO_COMMUNICATION_GUIDANCE,
slack: [
"This task began in Slack. Write replies for the person talking with you there.",
...slackTaskUpdateGuidance,
"Lead with the answer or outcome. Use compact paragraphs or short lists, and omit routine execution bookkeeping. Honor requests for more detail or exact output over default brevity.",
"Put small answers directly in the message. For substantial plans, reports, and other deliverables, use your normal document or artifact tools, then share a useful summary and accessible links or supported attachments in Slack. Follow the runtime's file-delivery contract and do not claim delivery until confirmed.",
"When you create tasks, include a clickable link to each created task in your reply. Use the task identifier or title as the link text, not a bare task ID. Use the public task URL returned by Paperclip tools or supplied in task context; never guess a URL or use a localhost, API, or sandbox address. If no public task URL is available, say that the link is unavailable.",
"Ask useful questions through the existing human-input tools. Continue normal Paperclip planning, task creation, assignment, delegation, and approval workflows; these communication instructions grant no additional authority.",
].join("\n\n"),
};
@@ -1,4 +1,5 @@
import { slackAppConfigurationSchema } from "@paperclipai/shared";
import { slackTaskUpdateGuidance } from "./task-update-guidance.js";
// Per-turn routing guidance, including resumed CLI sessions. This describes
// existing capabilities; it never grants tools or overrides action policies.
@@ -7,6 +8,7 @@ export function slackChatAgentGuidance(nativeRunner: boolean, savedCommand?: str
return [
"",
"Slack replies and actions:",
...slackTaskUpdateGuidance,
"Paperclip delivers your final response to the originating Slack conversation. Use assigned Slack action tools for an explicitly requested post, edit, reaction, pin, bookmark, canvas, list, or channel operation. Do not post a second copy of your ordinary reply with slack_post_message.",
"For a requested file in this conversation, follow the external-chat file-delivery contract below. slack_upload_file is for explicitly uploading an existing Paperclip attachment to another allowed destination. Neither queued nor uncertain means delivered; retain the original operation key and inspect its receipt instead of starting the write again.",
"Use only the tools assigned to this run and honor their action policies. Missing tools or Slack permissions are a capability limitation; never ask for a bot token or use another bot to work around it.",
@@ -0,0 +1,5 @@
// Shared by initial conversation guidance and every later Slack turn.
export const slackTaskUpdateGuidance = [
"When you have results, update the user in the originating Slack channel thread or direct conversation. Include the outcome and accessible links or supported attachments. Do not leave results only in a Paperclip task, document, or work product. Put this update in your final response so Paperclip can deliver it; do not send a duplicate with slack_post_message.",
"When the user needs to review a plan, approve an action, or review a result, notify them in the same Slack conversation. State what needs review, include the saved review link when available, and explain the action they must take. Follow the normal workflow to save the artifact and create the required human-input or approval interaction before you yield. Saving a plan or setting a task to in_review alone does not ask the user to review it. Do not claim notification or delivery without a successful receipt, and do not continue gated work until the required approval is recorded.",
];
@@ -150,6 +150,7 @@ import {
reviewPathConsumedRefFromRun,
} from "../recovery/review-path-recovery.js";
import { resolveRequiredSuccessfulRunHandoffOnValidPath } from "../successful-run-handoff-state.js";
import { escalateExhaustedIssueReviewPathRecovery } from "../recovery/review-path-recovery-escalation.js";
import {
redactCurrentUserText,
redactCurrentUserValue,
@@ -1987,6 +1988,10 @@ export function createHeartbeatLifecycle(db: Db, dependencies: HeartbeatLifecycl
reviewAttention,
existingWake: Boolean(existingWake),
});
if (decision.kind === "exhausted") {
await escalateExhaustedIssueReviewPathRecovery(db, { run, issueId: issue.id });
return;
}
if (decision.kind !== "enqueue") return;
const recoveryRun = await enqueueWakeup(issue.assigneeAgentId, {
+34 -3
View File
@@ -45,8 +45,16 @@ const WORK_CHECKS = [
`SELECT 1 FROM agent_api_keys WHERE revoked_at IS NULL`,
`SELECT 1 FROM board_api_keys WHERE revoked_at IS NULL
AND (expires_at IS NULL OR expires_at > now())`,
`SELECT 1 FROM agent_wakeup_requests WHERE
status NOT IN ('completed', 'failed', 'cancelled', 'skipped', 'timed_out')`,
// Coalescing consumes a request into another run. Retain it as work until
// both the request and that exact company/agent's run have finished.
`SELECT 1 FROM agent_wakeup_requests w WHERE
w.status NOT IN ('completed', 'failed', 'cancelled', 'skipped', 'timed_out', 'coalesced')
OR (w.status = 'coalesced' AND (w.finished_at IS NULL OR NOT EXISTS (
SELECT 1 FROM heartbeat_runs r WHERE r.id = w.run_id
AND r.company_id = w.company_id AND r.agent_id = w.agent_id
AND r.status IN ('succeeded', 'failed', 'cancelled', 'timed_out', 'interrupted')
AND r.finished_at IS NOT NULL AND r.scheduled_retry_at IS NULL
AND r.cost_accounting_pending = false)))`,
`SELECT 1 FROM issues WHERE status NOT IN ('done', 'cancelled')`,
// A completed issue can still need its first watchdog review, including a
// retry after immediate evaluation failed before creating a review/run.
@@ -62,6 +70,29 @@ const WORK_CHECKS = [
`SELECT 1 FROM issue_recovery_actions WHERE status NOT IN ('resolved', 'cancelled')`,
`SELECT 1 FROM status_cards WHERE archived_at IS NULL`,
`SELECT 1 FROM external_objects WHERE NOT is_terminal OR next_refresh_at IS NOT NULL`,
// Login history keeps its provider reference after teardown. A terminal
// label alone is insufficient: require a finished, unclaimed session and
// positive cleanup evidence for its resource in the same company/environment.
// Cast only UUID-shaped session references, leaving both lease indexes usable.
`SELECT 1 FROM adapter_auth_sessions s WHERE
s.status NOT IN ('authenticated', 'completed', 'failed', 'timed_out', 'cancelled')
OR s.finished_at IS NULL OR s.promotion_expires_at IS NOT NULL
OR (s.provider_lease_id IS NOT NULL AND NOT EXISTS (
SELECT 1 FROM environment_leases l WHERE l.company_id = s.company_id
AND l.environment_id = s.environment_id
AND (l.provider_lease_id = s.provider_lease_id OR l.id = CASE
WHEN s.provider_lease_id ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'
THEN s.provider_lease_id::uuid END)
AND l.status IN ('released', 'expired') AND l.cleanup_status = 'success'
AND l.released_at IS NOT NULL))
OR (s.provider_lease_id IS NOT NULL AND EXISTS (
SELECT 1 FROM environment_leases l WHERE l.company_id = s.company_id
AND l.environment_id = s.environment_id
AND (l.provider_lease_id = s.provider_lease_id OR l.id = CASE
WHEN s.provider_lease_id ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'
THEN s.provider_lease_id::uuid END)
AND (l.status IN ('released', 'expired') AND l.cleanup_status = 'success'
AND l.released_at IS NOT NULL) IS NOT TRUE))`,
// These less common work sources fail closed on any retained state. Their
// terminal-state exceptions can be added with tests for the owning service.
...[
@@ -73,7 +104,7 @@ const WORK_CHECKS = [
"native_run_finalizations", "company_transfer_runs", "decisions", "decision_effect_executions",
"decision_archive_notification_outbox", "browser_use_sessions", "browser_use_runs",
"browser_use_browsers", "environment_custom_image_setup_sessions", "feedback_exports",
"adapter_auth_sessions", "company_secret_proposals", "execution_workspaces",
"company_secret_proposals", "execution_workspaces",
"mcp_oauth_grants", "mcp_mutation_receipts", "mcp_event_subscriptions",
"mcp_event_deliveries", "mcp_attachment_uploads", "dot_agent_bindings",
"dot_runner_assignments", "dot_runner_operations", "dot_mailbox_items",
@@ -194,10 +194,11 @@ function monitorFromIssue(issue: IssueLivenessIssueInput) {
return { policyMonitor, stateMonitor };
}
export function hasScheduledIssueMonitorPath(issue: IssueLivenessIssueInput, now: Date | string | number) {
/** A saved, unconsumed check remains dispatchable when its due time passes. */
export function hasUnconsumedIssueMonitorPath(issue: IssueLivenessIssueInput, now: Date | string | number) {
const nowMs = typeof now === "number" ? now : readDateMs(now) ?? Date.now();
const nextCheckAtMs = readDateMs(issue.monitorNextCheckAt);
if (nextCheckAtMs === null || nextCheckAtMs <= nowMs) return false;
if (nextCheckAtMs === null) return false;
const { policyMonitor, stateMonitor } = monitorFromIssue(issue);
const timeoutAtMs = readDateMs(policyMonitor?.timeoutAt ?? stateMonitor?.timeoutAt);
@@ -211,6 +212,12 @@ export function hasScheduledIssueMonitorPath(issue: IssueLivenessIssueInput, now
return true;
}
export function hasScheduledIssueMonitorPath(issue: IssueLivenessIssueInput, now: Date | string | number) {
const nowMs = typeof now === "number" ? now : readDateMs(now) ?? Date.now();
const nextCheckAtMs = readDateMs(issue.monitorNextCheckAt);
return nextCheckAtMs !== null && nextCheckAtMs > nowMs && hasUnconsumedIssueMonitorPath(issue, nowMs);
}
export function classifyIssueReviewPaths(
input: IssueGraphLivenessInput,
issue: IssueLivenessIssueInput,
@@ -0,0 +1,134 @@
import { and, desc, eq, getTableColumns, or, sql } from "drizzle-orm";
import { agents, heartbeatRuns, issues, type Db } from "@paperclipai/db";
import { isWaitingConversation } from "../agent-conversations.js";
import { logActivity, publishActivity, type ActivityPublication } from "../activity-log.js";
import { issueRecoveryActionService } from "../issue-recovery-actions.js";
import { externalConversationStateSql } from "../slack-conversation-state.js";
import { isHeartbeatWakeOnDemandEnabled } from "../heartbeat-policy.js";
import {
executeIssuePostCommitActions,
issueService,
TERMINAL_HEARTBEAT_RUN_STATUSES,
type IssuePostCommitAction,
} from "../issues.js";
import {
buildIssueReviewPathLostIdempotencyKey,
decideIssueReviewPathRecovery,
ISSUE_REVIEW_PATH_LOST_WAKE_REASON,
reviewPathConsumedRefFromRun,
} from "./review-path-recovery.js";
import { buildStrandedRecoveryEscalationNotice } from "./stranded-notice.js";
import { hasUnconsumedIssueMonitorPath } from "./issue-graph-liveness.js";
/** A spent repair wake must leave an operator action, never another automatic wake. */
export async function escalateExhaustedIssueReviewPathRecovery(
db: Db,
input: { run: typeof heartbeatRuns.$inferSelect; issueId: string },
) {
const { run, issueId } = input;
const publications: ActivityPublication[] = [];
const postCommitActions: IssuePostCommitAction[] = [];
const action = await db.transaction(async (tx) => {
// Services must use the transaction connection for implicit settings reads
// too; borrowing the outer pool deadlocks when its only connection is held.
const issuesSvc = issueService(tx as unknown as Db);
// Share the issue fence with ownership, monitor, and interaction updates.
// Re-read the disposition under the lock rather than blocking a repaired task.
const issue = await tx.select({ ...getTableColumns(issues), externalConversationState: externalConversationStateSql() }).from(issues)
.where(and(eq(issues.companyId, run.companyId), eq(issues.id, issueId)))
.for("update").then((rows) => rows[0] ?? null);
if (!issue || issue.status !== "in_review" || issue.assigneeAgentId !== run.agentId
|| issue.assigneeUserId || isWaitingConversation(issue)
|| issue.externalConversationState === "waiting") return null;
// Startup recovery precedes monitor ticks. Preserve a due or claimed check
// only while the owner still allows the on-demand wake used by dispatch.
// Otherwise the dispatcher leaves it overdue indefinitely without consuming it.
if (hasUnconsumedIssueMonitorPath(issue, new Date())) {
const owner = await tx.select({ runtimeConfig: agents.runtimeConfig }).from(agents)
.where(and(eq(agents.companyId, run.companyId), eq(agents.id, issue.assigneeAgentId)))
.then((rows) => rows[0] ?? null);
if (owner && isHeartbeatWakeOnDemandEnabled(owner)) return null;
}
const attention = (await issuesSvc.listReviewAttention(run.companyId, [issue], tx)).get(issueId);
if (!attention || decideIssueReviewPathRecovery({
issueId,
sourceRunId: run.id,
assigneeAgentId: issue.assigneeAgentId,
contextSnapshot: run.contextSnapshot,
reviewAttention: attention,
existingWake: false,
}).kind !== "exhausted") return null;
const latestRun = await tx.select({ id: heartbeatRuns.id }).from(heartbeatRuns)
.where(and(eq(heartbeatRuns.companyId, run.companyId), or(
eq(heartbeatRuns.issueId, issueId),
eq(heartbeatRuns.nativeIssueId, issueId),
sql`coalesce(${heartbeatRuns.contextSnapshot}->>'issueId', ${heartbeatRuns.contextSnapshot}->>'taskId') = ${issueId}`,
)))
.orderBy(desc(heartbeatRuns.createdAt), desc(heartbeatRuns.id)).limit(1)
.then((rows) => rows[0] ?? null);
if (latestRun?.id !== run.id || !TERMINAL_HEARTBEAT_RUN_STATUSES.has(run.status)) return null;
const consumedPathRef = reviewPathConsumedRefFromRun({
runId: run.id, issueId, contextSnapshot: run.contextSnapshot,
});
const nextAction = "Inspect the run, then restore a scheduled check or review path, retry the original assignee, or record an intentional resolution.";
const recoveryAction = await issueRecoveryActionService(tx as unknown as Db).upsertSourceScoped({
companyId: run.companyId,
sourceIssueId: issueId,
kind: "missing_disposition",
ownerType: "board",
previousOwnerAgentId: run.agentId,
returnOwnerAgentId: run.agentId,
cause: ISSUE_REVIEW_PATH_LOST_WAKE_REASON,
fingerprint: buildIssueReviewPathLostIdempotencyKey({ issueId, consumedPathRef }),
evidence: {
correctiveRunId: run.id,
consumedPathRef,
previousStatus: "in_review",
recoveryAttempt: 1,
maxRecoveryAttempts: 1,
},
nextAction,
wakePolicy: { type: "board_escalation", preservesSourceAssignee: true },
attemptCount: 1,
maxAttempts: 1,
lastAttemptAt: run.finishedAt ?? new Date(),
});
await issuesSvc.update(issueId, {
status: "blocked", companyGuard: run.companyId,
}, tx, publications, postCommitActions);
const notice = buildStrandedRecoveryEscalationNotice({
seed: {
title: "No follow-up scheduled",
tone: "danger",
body: "The automatic review-path repair finished without saving a scheduled check, reviewer, approval, or other maintained path. Paperclip has blocked this task for a board decision; no further automatic follow-up is scheduled.",
nextAction,
},
recoveryCause: ISSUE_REVIEW_PATH_LOST_WAKE_REASON,
recoveryActionId: recoveryAction.id,
recoveryOwner: null,
sourceRun: { id: run.id, agentId: run.agentId, status: run.status },
});
const comment = await issuesSvc.addComment(issueId, notice.body, {}, {
authorType: "system", presentation: notice.presentation, metadata: notice.metadata,
}, tx);
await logActivity(tx as unknown as Db, {
companyId: run.companyId,
actorType: "system",
actorId: "heartbeat",
agentId: run.agentId,
runId: run.id,
action: "issue.review_path_recovery_exhausted",
entityType: "issue",
entityId: issueId,
details: { recoveryActionId: recoveryAction.id, commentId: comment.id, consumedPathRef, recoveryAttempt: 1, maxRecoveryAttempts: 1 },
}, publications);
return recoveryAction;
});
for (const publication of publications) publishActivity(publication);
await executeIssuePostCommitActions(db, postCommitActions);
return action;
}
@@ -139,20 +139,20 @@ describe("review-path recovery", () => {
},
);
it("does not requeue when the bounded recovery run also ends pathless", () => {
it.each([
{ wakeReason: ISSUE_REVIEW_PATH_LOST_WAKE_REASON },
{ reviewPathRecoveryAttempt: 1 },
])("requires escalation when the bounded recovery run also ends pathless (%j)", (contextSnapshot) => {
const decision = decideIssueReviewPathRecovery({
issueId: "issue-1",
sourceRunId: "run-2",
assigneeAgentId: "agent-1",
contextSnapshot: {
wakeReason: ISSUE_REVIEW_PATH_LOST_WAKE_REASON,
reviewPathRecoveryAttempt: 1,
},
contextSnapshot,
reviewAttention: stalled,
existingWake: false,
});
expect(decision).toEqual({ kind: "skip", reason: "bounded review-path recovery already ran" });
expect(decision).toEqual({ kind: "exhausted" });
});
it("never wakes a healthy review", () => {
@@ -6,13 +6,18 @@ import { withRecoveryContext } from "./status-only-context.js";
export const ISSUE_REVIEW_PATH_LOST_WAKE_REASON = "issue_review_path_lost";
export const REVIEW_PATH_RECOVERY_INSTRUCTION =
"This issue is still in review but its last maintained review path was consumed. Restore a reviewer, interaction, approval, monitor, or other durable waiting path, or choose an explicit disposition. This is the only automatic review-path recovery wake for this fingerprint.";
"This issue is still in review but its last maintained review path was consumed. Restore a reviewer, interaction, approval, monitor, or other durable waiting path, or choose an explicit disposition. If an async check is still pending, persist a one-shot issue monitor before ending this run and report its scheduled check time. A promise to check later or a background watcher is not a maintained review path. This is the only automatic review-path recovery wake for this fingerprint; ending without a maintained path will require a board decision.";
const REVIEW_PATH_RECOVERY_IDEMPOTENCY_INDEX = "agent_wakeup_requests_review_path_recovery_idempotency_uq";
function readNonEmptyString(value: unknown) {
return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
}
export function isIssueReviewPathRecoveryRun(contextSnapshot: Record<string, unknown> | null | undefined) {
return readNonEmptyString(contextSnapshot?.wakeReason) === ISSUE_REVIEW_PATH_LOST_WAKE_REASON
|| contextSnapshot?.reviewPathRecoveryAttempt === 1;
}
export function reviewPathConsumedRefFromRun(input: {
runId: string;
issueId: string;
@@ -68,6 +73,7 @@ export type IssueReviewPathRecoveryDecision =
payload: Record<string, unknown>;
contextSnapshot: Record<string, unknown>;
}
| { kind: "exhausted" }
| { kind: "skip"; reason: string };
export function decideIssueReviewPathRecovery(input: {
@@ -84,11 +90,8 @@ export function decideIssueReviewPathRecovery(input: {
}
const context = input.contextSnapshot ?? {};
if (
readNonEmptyString(context.wakeReason) === ISSUE_REVIEW_PATH_LOST_WAKE_REASON
|| context.reviewPathRecoveryAttempt === 1
) {
return { kind: "skip", reason: "bounded review-path recovery already ran" };
if (isIssueReviewPathRecoveryRun(context)) {
return { kind: "exhausted" };
}
const consumedPathRef = reviewPathConsumedRefFromRun({
+17
View File
@@ -4,6 +4,8 @@ import { hasCommittedNativePlanWait } from "../native-runtime/native-plan-wait.j
import { isNativeWorkspaceExportRepairCause } from "@paperclipai/shared";
import { settleSlackConversation } from "../slack-conversation-lifecycle.js";
import { externalConversationStateSql } from "../slack-conversation-state.js";
import { isIssueReviewPathRecoveryRun } from "./review-path-recovery.js";
import { escalateExhaustedIssueReviewPathRecovery } from "./review-path-recovery-escalation.js";
import { executionRetryAccounting } from "../execution-recovery-attempt.js";
import { isExplicitContinuationRetryClaim } from "../explicit-continuation-retry-claim.js";
import {
@@ -4472,6 +4474,21 @@ export function recoveryService(
}
let latestRun = await getLatestIssueRun(issue.companyId, issue.id);
// Terminal run/wake rows survive a restart even if finalization never
// reached the escalation transaction. Retry that idempotent disposition
// before the participant-only review branch can skip pathless reviews.
if (issue.status === "in_review" && latestRun
&& isTerminalIssueRun(latestRun)
&& isIssueReviewPathRecoveryRun(latestRun.contextSnapshot)) {
const [repairRun] = await db.select().from(heartbeatRuns).where(and(
eq(heartbeatRuns.companyId, issue.companyId), eq(heartbeatRuns.id, latestRun.id),
));
if (repairRun && await escalateExhaustedIssueReviewPathRecovery(db, { run: repairRun, issueId: issue.id })) {
result.escalated += 1;
result.issueIds.push(issue.id);
continue;
}
}
// A native chat can finish between the earlier settlement read and this
// fresh run read, before its response is materialized. Its trusted
// finalizer owns that settlement; generic productive-work recovery must
+10
View File
@@ -80,3 +80,13 @@ On a Slack-linked task, human messages sent from Paperclip and your final respon
are mirrored into its Slack thread. Do not manually send the same final response
again. Ordinary tasks and routines have no automatic Slack destination: perform the
requested Slack send explicitly and report whether delivery was confirmed.
On a Slack-linked task, when results are ready, include the outcome and accessible
deliverable links or supported attachments in your final response to the originating
Slack conversation.
Do not leave the result only on the Paperclip task. When the user must review a
plan, approve an action, or review a result, save the artifact and create the
required review interaction through the normal Paperclip workflow. Tell the user
what needs review and what action to take in the same Slack conversation. A saved
plan or an `in_review` status alone is not a review request. Keep approval gates
in place and do not claim delivery without a successful receipt.
+5 -6
View File
@@ -34,12 +34,10 @@ function shellQuote(value: string): string {
}
const command = [
"npx",
"--yes",
shellQuote(`paperclipai@${canaryVersion}`),
"onboard",
"--yes",
"--data-dir",
shellQuote(process.execPath),
shellQuote(path.resolve("tests/canary-onboarding/start-published-canary.mjs")),
shellQuote(canaryVersion),
shellQuote(workspace),
shellQuote(dataDir),
">",
shellQuote(serverLog),
@@ -76,6 +74,7 @@ export default defineConfig({
command,
url: `${baseUrl}/api/health`,
reuseExistingServer: false,
gracefulShutdown: { signal: "SIGTERM", timeout: 5_000 },
timeout: 300_000,
env: {
...process.env,
@@ -0,0 +1,127 @@
import { spawn } from "node:child_process";
import { mkdtemp, rm } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
// Leave three minutes for onboarding inside Playwright's existing five-minute
// startup deadline. This budget includes every install attempt and backoff.
export const INSTALL_BUDGET_MS = 120_000;
const MAX_INSTALL_ATTEMPTS = 3;
const STDERR_TAIL_CHARS = 64 * 1024;
function run(command, args, { env, signal, captureStderr = false }) {
return new Promise((resolve, reject) => {
signal.throwIfAborted();
const grouped = process.platform !== "win32";
const child = spawn(command, args, {
env, detached: grouped, stdio: ["ignore", "inherit", captureStderr ? "pipe" : "inherit"],
});
let stderr = "";
let stopping;
const kill = (kind) => {
try {
if (grouped) process.kill(-child.pid, kind);
else child.kill(kind);
} catch (error) {
if (error.code !== "ESRCH") throw error;
}
};
const stop = () => {
if (stopping || !child.pid) return;
kill("SIGTERM");
// Also stop any lifecycle-script children even if npm exits first.
stopping = new Promise((done) => setTimeout(() => { kill("SIGKILL"); done(); }, 500));
};
signal.addEventListener("abort", stop, { once: true });
child.stderr?.on("data", (chunk) => {
process.stderr.write(chunk);
stderr = (stderr + chunk.toString()).slice(-STDERR_TAIL_CHARS);
});
child.on("error", reject);
child.on("close", async (code, exitSignal) => {
signal.removeEventListener("abort", stop);
await stopping;
if (signal.aborted) reject(signal.reason);
else resolve({ code, signal: exitSignal, stderr });
});
});
}
function delay(ms, signal) {
return new Promise((resolve, reject) => {
signal.throwIfAborted();
const timer = setTimeout(() => {
signal.removeEventListener("abort", stop);
resolve();
}, ms);
const stop = () => { clearTimeout(timer); reject(signal.reason); };
signal.addEventListener("abort", stop, { once: true });
});
}
export async function startPublishedCanary({
version, workspace, dataDir, env = process.env,
installBudgetMs = INSTALL_BUDGET_MS, retryDelayMs = 10_000,
signal = new AbortController().signal,
}) {
if (!version || !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(version)) {
throw new Error("An exact published Paperclip version is required");
}
let prefix;
try {
const budget = new AbortController();
const timer = setTimeout(() => budget.abort(new Error("Canary npm installation exceeded its startup budget")), installBudgetMs);
const installSignal = AbortSignal.any([signal, budget.signal]);
try {
for (let attempt = 1; attempt <= MAX_INSTALL_ATTEMPTS; attempt++) {
installSignal.throwIfAborted();
// Every attempt gets a clean prefix. The fresh per-smoke npm cache still
// retains downloaded tarballs, but --prefer-online refreshes metadata.
prefix = await mkdtemp(path.join(workspace, "npm-install-"));
const result = await run(process.platform === "win32" ? "npm.cmd" : "npm", [
"install", "--prefix", prefix, "--no-save", "--no-package-lock", "--no-audit", "--no-fund",
...(attempt > 1 ? ["--prefer-online"] : []), `paperclipai@${version}`,
], { env, signal: installSignal, captureStderr: true });
if (result.code === 0) break;
const codes = [...result.stderr.matchAll(/^npm (?:error|ERR!) code ([A-Z0-9_]+)\r?$/gm)];
const missingVersion = codes.at(-1)?.[1] === "ETARGET";
if (!missingVersion || result.signal || attempt === MAX_INSTALL_ATTEMPTS) {
throw new Error(`Canary npm installation failed (exit ${result.code ?? result.signal}); onboarding was not started`);
}
await rm(prefix, { recursive: true, force: true });
prefix = undefined;
process.stderr.write(`Canary dependency publication is incomplete; retrying npm installation (${attempt}/${MAX_INSTALL_ATTEMPTS})\n`);
await delay(retryDelayMs * attempt, installSignal);
}
} finally {
clearTimeout(timer);
}
signal.throwIfAborted();
// Start the installed CLI exactly once. Its own failures must never trigger
// another onboarding run or another dependency-install attempt.
const result = await run(path.join(prefix, "node_modules", ".bin", process.platform === "win32" ? "paperclipai.cmd" : "paperclipai"),
["onboard", "--yes", "--data-dir", dataDir], { env, signal });
if (result.code !== 0) throw new Error(`Canary onboarding failed (exit ${result.code ?? result.signal})`);
} finally {
if (prefix) await rm(prefix, { recursive: true, force: true });
}
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const [version, workspace, dataDir] = process.argv.slice(2);
const cancellation = new AbortController();
const stop = (kind) => cancellation.abort(new Error(`Canary startup stopped by ${kind}`));
const interrupt = () => stop("SIGINT");
const terminate = () => stop("SIGTERM");
process.on("SIGINT", interrupt);
process.on("SIGTERM", terminate);
try {
await startPublishedCanary({ version, workspace, dataDir, signal: cancellation.signal });
} catch (error) {
console.error(error.message);
process.exitCode = 1;
} finally {
process.removeListener("SIGINT", interrupt);
process.removeListener("SIGTERM", terminate);
}
}