From c1b1ed6834174c1a3e5e99cb915cd1ca23a121a7 Mon Sep 17 00:00:00 2001 From: Jean-Baptiste Renard Date: Wed, 2 Dec 2026 10:57:37 +0100 Subject: [PATCH 1/3] feat(triggers): confirm a trigger stop with a configured final check A versioned stop trigger may carry finalCheck.notePath. Switchboard then runs the global stopCheckCommand argv twice, --sample-final then --check-final with the sampled evidence, rechecks target, idle state, composer and deadline, and only then stops the session. A refusal, an error, a timeout or a missing command returns its own result reason and requests no stop; a stop without finalCheck keeps its current path. The check's process group is killed at the deadline or on output overflow, and the result waits for its close within a 500 ms grace period. scripts/assert-named-test.cjs runs one named node:test test and fails when no executed test matches, for the acceptance commands of this change. Implemented with Codex, reviewed adversarially until no finding remained. --- .ai/contexts/trigger-watcher.md | 2 +- CHANGELOG.md | 1 + docs/automation.md | 32 +++ eslint.config.js | 2 +- main.js | 15 +- public/setting-defaults.js | 13 +- scripts/assert-named-test.cjs | 56 ++++ src/main/triggers/trigger-actions.js | 78 +++++- src/main/triggers/trigger-context.js | 1 + test/fixtures/assert-named-test-blocked.cjs | 5 + test/fixtures/assert-named-test-overflow.cjs | 10 + test/fixtures/trigger-stop.cjs | 25 +- test/remote-ssh-spawn-sites.test.js | 3 + test/setting-defaults.test.js | 36 +++ test/trigger-actions-schema.test.js | 17 ++ test/trigger-actions-stop.test.js | 271 ++++++++++++++++++- 16 files changed, 559 insertions(+), 8 deletions(-) create mode 100644 scripts/assert-named-test.cjs create mode 100644 test/fixtures/assert-named-test-blocked.cjs create mode 100644 test/fixtures/assert-named-test-overflow.cjs diff --git a/.ai/contexts/trigger-watcher.md b/.ai/contexts/trigger-watcher.md index f9dc3d3b2..f1378a5ac 100644 --- a/.ai/contexts/trigger-watcher.md +++ b/.ai/contexts/trigger-watcher.md @@ -193,7 +193,7 @@ Main-process modules `trigger-watcher.js` and `trigger-context.js` live in | `src/main/triggers/trigger-watcher.js` | The watcher core: directory setup, `fs.watch` listener, idle-wait logic, single + chained trigger processing, submit-with-verify busy-rise/fall polling, input validation, PTY write, result file. | | `src/main/triggers/trigger-name.js` | The new-session name rules: unpaired-surrogate test, `requestedName`/`actualName` result fields, marker naming provenance and its recovery validation (see "Naming a new session"). | | `src/main/triggers/trigger-context.js` | `createTriggerContext({ activeSessions, log, getCliStatus, projectsDir, lifecycle, sessionRequests, statusSources, getLiveDescriptor, resolveSessionId, remote })` — builds the whole `ctx` object out of `main.js`'s session map, including the pinned per-tab delivery binding (`pinDelivery`) and the descriptor fallback lookup (`lookupDeliveryFallback`). | -| `src/main/triggers/trigger-actions.js` | Versioned (`version`/`action`) requests: `validateTrigger`, `resolveProject` (with its transient-conflict retry), the new-session limiter, open/new/stop execution (`createTriggerActions`). | +| `src/main/triggers/trigger-actions.js` | Versioned (`version`/`action`) requests: `validateTrigger`, `resolveProject` (with its transient-conflict retry), the new-session limiter, open/new/stop execution (`createTriggerActions`), and the stop final check: `finalCheck.notePath` on stop, `runStopCheck` running the global `stopCheckCommand` argv in `--sample-final` then `--check-final` mode (contract in `docs/automation.md`). | | `src/main/triggers/trigger-launch.js` | `acquireOpen` (per-id open FIFO) and `validateTriggerOpen`, the main-process launch checks. | | `src/main/triggers/trigger-renderer-bridge.js` | `createTriggerRendererBridge`: the renderer broker for open/new and stop (see "Renderer broker and open lifecycle"). | | `src/main/triggers/session-request-contract.js` | The typed request parser (`parseSessionRequest`, `statusEnvelope`, `openRefusal`). | diff --git a/CHANGELOG.md b/CHANGELOG.md index 2a612b789..98c4c649a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ What changes for you in each release of Switchboard. How to write an entry: [doc ## Unreleased ### New +- A trigger stop can ask for a final check before the session ends: with `"finalCheck":{"notePath":…}` and the new **stopCheckCommand** setting, Switchboard runs that command to confirm the note and the last turn just before stopping, and refuses the stop with `stop check refused`, `failed`, `timed out` or `unavailable` otherwise. Stops without `finalCheck` are unchanged. - Moving a session to the background now asks whether to stop or keep an older job for the same conversation when Switchboard cannot tell if it is still running; Stop checks again before moving, and Cancel quietly keeps that session in the foreground while the rest of the batch continues. Cancellations from Claude and refusals after a choice still show their reason; Keep also checks for live jobs known only from the Agents list. Cancelled questions close, and waiting for a choice does not shorten the move’s confirmation time. (#1295) ### Changed diff --git a/docs/automation.md b/docs/automation.md index 7ed62f64a..f52d007e2 100644 --- a/docs/automation.md +++ b/docs/automation.md @@ -473,6 +473,38 @@ content. Failure returns `note step not finished` with `delivery` diagnostics and leaves the session running. A newly started turn after the note refuses `session busy` instead of terminating it. +A stop request may include `"finalCheck":{"notePath":"/absolute/path/to/note.md"}`. +The field is valid only on stop and contains only `notePath`. The path must be +absolute, at most 4096 characters, and free of control characters. Switchboard +reads the persisted global `stopCheckCommand` setting for this request. Its +default is `null`; configure it as an argv array whose first element is an +absolute executable path, for example +`["/usr/bin/python3","-B","/absolute/path/to/lifecycle_stop.py"]`. +The array accepts at most 32 strings, 4096 characters per string and 8192 +characters in total; control characters are refused. +The configured program must support `--sample-final` and `--check-final`. +Switchboard supplies the session ID, note path, and sampled evidence tokens as +separate arguments. Trigger files cannot supply command arguments. + +```text + --sample-final --session-id --note + --check-final --session-id --note --expected-note-commit --expected-transcript-turn +``` + +After any `before` delivery and the final idle and composer check, Switchboard +samples note and transcript evidence once, verifies it once, then synchronously +rechecks the target, idle status, composer, and deadline before requesting one +stop. A validator refusal returns `stop check refused` with its first stdout +line in `detail`. A nonzero validator error or malformed sample returns +`stop check failed`; an expired deadline returns `stop check timed out`; an +unset or invalid command or a spawn failure returns `stop check unavailable`. +These results do not request a stop and retain any completed `before` delivery +evidence. The check observes the note and transcript before the stop request; +later writes to those files are outside that observation. +On POSIX, an expired or overproducing validator terminates its process group. +On Windows, termination targets the direct child only; descendants may remain +running, but their inherited output streams cannot delay the stop result. + Stop never opens a closed session or stops siblings in a merged row. Remote, scheduled, background/attach and plain-terminal targets remain unsupported. `expectedCwd` is supported for stop and rechecked before termination. `closed` diff --git a/eslint.config.js b/eslint.config.js index 0d01d41fe..2fd30f7d2 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -861,7 +861,7 @@ module.exports = [ // Tests: node:test, Node globals { - files: ['test/**/*.js', 'test/**/*.test.js', 'test/fixtures/trigger-*.cjs', 'test/get-projects-handler.cjs'], + files: ['test/**/*.js', 'test/**/*.test.js', 'test/fixtures/trigger-*.cjs', 'test/fixtures/assert-named-test-blocked.cjs', 'test/fixtures/assert-named-test-overflow.cjs', 'test/get-projects-handler.cjs'], languageOptions: { ecmaVersion: 2024, sourceType: 'commonjs', diff --git a/main.js b/main.js index 229e9adb8..26814fc21 100644 --- a/main.js +++ b/main.js @@ -93,7 +93,7 @@ const { buildScheduleList } = require('./src/main/schedules/schedule-list'); const { migrateSchedulesTabWithinBound } = require('./src/main/schedules/schedules-tab-migration'); const { archivePlanForGroups, validArchiveGroups } = require('./archived-projects'); const { encodeProjectPath } = require('./encode-project-path'); -const { SETTING_DEFAULTS, normalizeBrowserSettings, +const { SETTING_DEFAULTS, normalizeBrowserSettings, validateStopCheckCommand, PROJECT_DELETE_WORKTREE_INSPECTION_TIMEOUT_MS, PROJECT_DELETE_WORKTREE_REMOVE_TIMEOUT_MS } = require('./public/setting-defaults'); const { isSensitivePath, isSensitivePathAsync, isAllowedMemoryPath: _isAllowedMemoryPath, resolveAllowedMemoryPath: _resolveAllowedMemoryPath, isKnownProjectRoot: _isKnownProjectRoot } = require('./src/main/shared/ipc-path-validator'); const { validatePreLaunchCmd } = require('./src/main/terminals/pre-launch-cmd-guard'); @@ -2014,13 +2014,23 @@ async function writeGlobalSettings(write) { } ipcMain.handle('set-setting', async (_event, key, value) => { - if (key === 'global') await writeGlobalSettings(async () => { await setSetting(key, value); return value; }); + if (key === 'global') { + if (value && Object.hasOwn(value, 'stopCheckCommand')) { + const checked = validateStopCheckCommand(value.stopCheckCommand); + if (!checked.ok) throw new TypeError(checked.error); + } + await writeGlobalSettings(async () => { await setSetting(key, value); return value; }); + } else await setSetting(key, value); return { ok: true }; }); ipcMain.handle('merge-global-settings', async (_event, patch, remove) => { if (!patch || typeof patch !== 'object' || Array.isArray(patch)) throw new TypeError('Invalid global settings patch'); + if (Object.hasOwn(patch, 'stopCheckCommand')) { + const checked = validateStopCheckCommand(patch.stopCheckCommand); + if (!checked.ok) throw new TypeError(checked.error); + } const keys = Array.isArray(remove) ? remove.filter(key => typeof key === 'string') : []; await writeGlobalSettings(() => writer.mergeGlobal(patch, keys)); return { ok: true }; @@ -4811,6 +4821,7 @@ if (!app.isPackaged) { try { require('./src/main/triggers/trigger-watcher').start(createTriggerContext({ activeSessions, log, getCliStatus: (id) => cliSessionState.getStatus(id), projectsDir: PROJECTS_DIR, + getStopCheckCommand: () => (getSetting('global') || {}).stopCheckCommand ?? SETTING_DEFAULTS.stopCheckCommand, lifecycle: triggerLifecycleDeps(), sessionRequests: writer, statusSources: { diff --git a/public/setting-defaults.js b/public/setting-defaults.js index 6be7c0715..c99e85146 100644 --- a/public/setting-defaults.js +++ b/public/setting-defaults.js @@ -36,6 +36,7 @@ const SETTING_DEFAULTS = { activityReporting: false, // see .ai/contexts/activitywatch.md logRetentionDays: 14, remoteTriggers: false, + stopCheckCommand: null, remoteHosts: [], remoteRefreshMs: 300000, schedulesTab: true, @@ -93,8 +94,18 @@ function validateCustomArgs(value) { return { ok: true }; } +function validateStopCheckCommand(value) { + if (value === null) return { ok: true }; + if (!Array.isArray(value) || value.length < 1 || value.length > 32) return { ok: false, error: 'stopCheckCommand must be a nonempty argv array (max 32 elements)' }; + if (typeof value[0] !== 'string' || !(typeof module !== 'undefined' && module.require ? module.require('path').isAbsolute(value[0]) + : /^(?:\/|[A-Za-z]:[\\/]|\\\\)/.test(value[0]))) return { ok: false, error: 'stopCheckCommand executable must be an absolute path' }; + if (value.some(arg => typeof arg !== 'string' || arg.length > 4096 || /[\x00-\x1f\x7f-\x9f]/.test(arg)) + || value.reduce((length, arg) => length + arg.length, 0) > 8192) return { ok: false, error: 'stopCheckCommand arguments must be bounded strings without controls' }; + return { ok: true }; +} + if (typeof module !== 'undefined' && module.exports) { - module.exports = { SETTING_DEFAULTS, THEME_CHOICES, CODEX_CHOICES, BROWSER_MODES, normalizeBrowserSettings, validateCustomArgs, + module.exports = { SETTING_DEFAULTS, THEME_CHOICES, CODEX_CHOICES, BROWSER_MODES, normalizeBrowserSettings, validateCustomArgs, validateStopCheckCommand, PROJECT_DELETE_PREVIEW_TIMEOUT_MS, PROJECT_DELETE_DIALOG_TIMEOUT_MS, PROJECT_DELETE_FOLLOWUP_TIMEOUT_MS, PROJECT_DELETE_WORKTREE_INSPECTION_TIMEOUT_MS, PROJECT_DELETE_WORKTREE_REMOVE_TIMEOUT_MS, DIRECTORY_SCAN_MS }; } diff --git a/scripts/assert-named-test.cjs b/scripts/assert-named-test.cjs new file mode 100644 index 000000000..ef5174ba5 --- /dev/null +++ b/scripts/assert-named-test.cjs @@ -0,0 +1,56 @@ +#!/usr/bin/env node +'use strict'; + +const { spawn } = require('node:child_process'); + +const [, , name, file] = process.argv; +if (!name || !file) { + console.error('Usage: assert-named-test.cjs '); + process.exitCode = 2; +} else { + const timeoutMs = Number(process.env.ASSERT_NAMED_TEST_TIMEOUT_MS) || 60000; + const pattern = '^' + name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '$'; + const env = { ...process.env }; + delete env.NODE_TEST_CONTEXT; + const child = spawn(process.execPath, ['--test-reporter=tap', '--test-name-pattern=' + pattern, file], { + stdio: ['ignore', 'pipe', 'pipe'], detached: process.platform !== 'win32', env, + }); + let timedOut = false, overflow = false, size = 0; + const chunks = []; + const kill = () => { + try { if (process.platform !== 'win32') process.kill(-child.pid, 'SIGKILL'); else child.kill('SIGKILL'); } + catch { child.kill('SIGKILL'); } + }; + process.once('SIGTERM', () => { + kill(); + process.exit(143); + }); + const collect = chunk => { + if (overflow) return; + size += chunk.length; + if (size > 1024 * 1024) { + overflow = true; kill(); + child.stdout.destroy(); child.stderr.destroy(); + } else chunks.push(chunk); + }; + child.stdout.on('data', collect); + child.stderr.on('data', collect); + const timer = setTimeout(() => { timedOut = true; kill(); child.stdout.destroy(); child.stderr.destroy(); }, timeoutMs); + let spawnError = ''; + child.on('error', error => { spawnError = error.message; }); + child.on('close', code => { + clearTimeout(timer); + const output = spawnError || (overflow ? '' : Buffer.concat(chunks).toString('utf8')); + const records = output.split(/\r?\n/).filter(line => /^ok \d+ - /.test(line)); + const matched = records.filter(line => line.replace(/^ok \d+ - /, '').replace(/ # SKIP\b.*$/, '') === name); + const skipped = matched.some(line => / # SKIP\b/.test(line)); + const executed = matched.filter(line => !/ # SKIP\b/.test(line)).length; + if (!timedOut && !overflow && code === 0 && executed > 0 && !skipped) { + console.log(`PASS ${name} (${executed} executed, 0 failed)`); + } else { + console.error(`FAIL ${name}${timedOut ? ' timed out' : overflow ? ' output exceeded limit' : ' absent or failed'}`); + if (!timedOut && !overflow) console.error(output.slice(-4000)); + process.exitCode = 1; + } + }); +} diff --git a/src/main/triggers/trigger-actions.js b/src/main/triggers/trigger-actions.js index 1770b2378..79a359339 100644 --- a/src/main/triggers/trigger-actions.js +++ b/src/main/triggers/trigger-actions.js @@ -2,6 +2,8 @@ const nativeFs = require('fs'); const path = require('path'); +const { spawn } = require('child_process'); +const { validateStopCheckCommand } = require('../../../public/setting-defaults'); const { extractVerifiedCwdFromJsonl, resolveWorktreePath } = require('../../../derive-project-path'); const { normalizeProjectPath } = require('../shared/normalize-project-path'); const { projectHiddenMatcher } = require('../../../public/worktree-nesting'); @@ -10,9 +12,49 @@ const naming = require('./trigger-name'); const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; const FILENAME_UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; const UNAVAILABLE = 'session action not implemented in this build'; +const STOP_CHECK_REAP_GRACE_MS = 500; const object = value => value !== null && typeof value === 'object' && !Array.isArray(value); const own = (value, key) => object(value) && Object.hasOwn(value, key); +function runStopCheck(command, args, deadline, now, launch = spawn) { + return new Promise(resolve => { + const remaining = deadline - now(); + if (remaining <= 0) return resolve({ timedOut: true }); + let child; + try { child = launch(command[0], [...command.slice(1), ...args], { shell: false, windowsHide: true, + stdio: ['ignore', 'pipe', 'pipe'], detached: process.platform !== 'win32' }); } + catch (error) { return resolve({ unavailable: true, error: error.message }); } + let stdout = '', stderr = '', timedOut = false, overflow = false, settled = false, aborting = false; + let timer, reapTimer; + const finish = result => { + if (settled) return; + settled = true; clearTimeout(timer); clearTimeout(reapTimer); + resolve({ stdout, stderr, timedOut, overflow, ...result }); + }; + const abort = () => { + if (settled || aborting) return; + aborting = true; clearTimeout(timer); + if (process.platform !== 'win32' && Number.isInteger(child.pid) && child.pid > 0) { + try { process.kill(-child.pid, 'SIGKILL'); } catch { child.kill('SIGKILL'); } + } else child.kill('SIGKILL'); + child.stdout?.destroy?.(); child.stderr?.destroy?.(); + reapTimer = setTimeout(() => finish({ code: null, signal: 'SIGKILL' }), STOP_CHECK_REAP_GRACE_MS); + }; + const append = (key, chunk) => { + if (settled || aborting) return; + const current = key === 'stdout' ? stdout : stderr; + const next = current + chunk.toString('utf8'); + if (key === 'stdout') stdout = next.slice(0, 4096); else stderr = next.slice(0, 4096); + if (Buffer.byteLength(next) > 4096) { overflow = true; abort(); } + }; + child.stdout?.on('data', chunk => append('stdout', chunk)); + child.stderr?.on('data', chunk => append('stderr', chunk)); + timer = setTimeout(() => { timedOut = true; abort(); }, remaining); + child.on('error', error => { if (!aborting) finish({ unavailable: true, error: error.message }); }); + child.on('close', (code, signal) => finish({ code, signal })); + }); +} + function isVersioned(trigger) { return own(trigger, 'version') || own(trigger, 'action'); } @@ -29,13 +71,19 @@ function validateTrigger(trigger, stem, evidence = {}) { const newMode = trigger.action === 'open' && hasNew; const allowed = newMode ? ['version', 'action', 'new', 'prompt', 'timeout_ms'] : trigger.action === 'open' ? ['version', 'action', 'sessionId', 'prompt', 'timeout_ms', 'expectedCwd'] - : ['version', 'action', 'sessionId', 'before', 'timeout_ms', 'expectedCwd']; + : ['version', 'action', 'sessionId', 'before', 'timeout_ms', 'expectedCwd', 'finalCheck']; const unsupported = Object.keys(trigger).filter(key => !allowed.includes(key)); if (newMode && object(trigger.new)) { unsupported.push(...Object.keys(trigger.new).filter(key => !['project', 'name'].includes(key)).map(key => 'new.' + key)); } if (unsupported.length) return 'unsupported field: ' + unsupported.sort()[0]; if (hasId && (typeof trigger.sessionId !== 'string' || !UUID.test(trigger.sessionId))) return 'sessionId must be a UUID'; + if (own(trigger, 'finalCheck')) { + const finalCheck = trigger.finalCheck; + if (!object(finalCheck) || Object.keys(finalCheck).length !== 1 || !own(finalCheck, 'notePath')) return 'finalCheck must contain only notePath'; + if (typeof finalCheck.notePath !== 'string' || !finalCheck.notePath || !path.isAbsolute(finalCheck.notePath) + || finalCheck.notePath.length > 4096 || /[\x00-\x1f\x7f-\x9f]/.test(finalCheck.notePath)) return 'finalCheck.notePath must be an absolute path without controls (max 4096 characters)'; + } if (newMode) { if (!object(trigger.new)) return 'new must be an object'; const { project, name } = trigger.new; @@ -549,6 +597,34 @@ async function executeStop(trigger, execution) { const final = sample(effects.delivery?.final_turn); if (final.remaining > 0) continue; check(before ? 'note step not finished' : 'session input not quiet'); + if (own(trigger, 'finalCheck')) { + let command; + try { command = ctx.getStopCheckCommand?.(); } + catch (error) { reject('stop check unavailable', { detail: String(error.message || error).slice(0, 256) }); } + if (!validateStopCheckCommand(command).ok || command === null || command === undefined) reject('stop check unavailable'); + const common = ['--session-id', id, '--note', trigger.finalCheck.notePath]; + const launch = deps.spawnStopCheck || spawn; + const runCheck = async args => { + const result = await runStopCheck(command, args, deadline, now, launch); + if (result.timedOut) reject('stop check timed out'); + if (result.unavailable) reject('stop check unavailable', { detail: String(result.error || '').slice(0, 256) }); + if (result.overflow) reject('stop check failed', { detail: 'validator output exceeded limit' }); + if (result.code === 1) reject('stop check refused', { detail: (result.stdout || '').split(/\r?\n/, 1)[0].slice(0, 256) }); + if (result.code !== 0 || result.signal) reject('stop check failed', { detail: (result.stderr || result.stdout || result.signal || 'validator failed').split(/\r?\n/, 1)[0].slice(0, 256) }); + return result.stdout; + }; + const sampled = await runCheck(['--sample-final', ...common]); + let tokens; + try { tokens = JSON.parse(sampled.trim()); } catch {} + if (!object(tokens) || Object.keys(tokens).length !== 2 || !/^[0-9a-f]{40}$/.test(tokens.noteCommit) + || !/^[0-9a-f]{64}$/.test(tokens.transcriptTurn)) reject('stop check failed', { detail: 'invalid final check sample' }); + await runCheck(['--check-final', ...common, '--expected-note-commit', tokens.noteCommit, + '--expected-transcript-turn', tokens.transcriptTurn]); + check('stop check timed out'); + const verified = sample(effects.delivery?.final_turn); + if (verified.remaining > 0) reject('session input not quiet'); + check('stop check timed out'); + } let stopped; try { stopped = deps.stop(session, tabKey); } catch (error) { reject('session stop failed', { error: error.message }); } diff --git a/src/main/triggers/trigger-context.js b/src/main/triggers/trigger-context.js index 3c931d2ef..9d0738e11 100644 --- a/src/main/triggers/trigger-context.js +++ b/src/main/triggers/trigger-context.js @@ -101,6 +101,7 @@ function createTriggerContext(deps) { }, }; if (deps.lifecycle) ctx.lifecycle = deps.lifecycle; + if (deps.getStopCheckCommand) ctx.getStopCheckCommand = deps.getStopCheckCommand; ctx.sessionRequests = deps.sessionRequests; ctx.sessionStatus = deps.sessionStatus || createSessionStatus({ activeSessions, ...deps.statusSources, getPtyStart: pid => source.deliveryPtyStart(pid), diff --git a/test/fixtures/assert-named-test-blocked.cjs b/test/fixtures/assert-named-test-blocked.cjs new file mode 100644 index 000000000..665c23303 --- /dev/null +++ b/test/fixtures/assert-named-test-blocked.cjs @@ -0,0 +1,5 @@ +'use strict'; + +const test = require('node:test'); + +test('blocked', () => { setInterval(() => {}, 1000); }); diff --git a/test/fixtures/assert-named-test-overflow.cjs b/test/fixtures/assert-named-test-overflow.cjs new file mode 100644 index 000000000..d098beb0d --- /dev/null +++ b/test/fixtures/assert-named-test-overflow.cjs @@ -0,0 +1,10 @@ +'use strict'; + +const test = require('node:test'); +const fs = require('node:fs'); + +test('overflow', () => { + fs.writeFileSync(process.env.ASSERT_NAMED_TEST_CHILD_PID_FILE, String(process.pid)); + const chunk = Buffer.alloc(65536, 120); + setInterval(() => fs.writeSync(1, chunk), 10); +}); diff --git a/test/fixtures/trigger-stop.cjs b/test/fixtures/trigger-stop.cjs index 86708a912..4fc43cf6f 100644 --- a/test/fixtures/trigger-stop.cjs +++ b/test/fixtures/trigger-stop.cjs @@ -1,5 +1,7 @@ 'use strict'; +const path = require('node:path'); +const { EventEmitter } = require('node:events'); const { createTriggerActions } = require('../../src/main/triggers/trigger-actions'); const { createTriggerContext } = require('../../src/main/triggers/trigger-context'); const { deliverSingle } = require('../../src/main/triggers/trigger-watcher'); @@ -7,6 +9,27 @@ const { createComposerState, noteUserInput } = require('../../src/main/terminals const ID = '01234567-89ab-cdef-0123-456789abcdef'; const STEM = '21234567-89ab-cdef-0123-456789abcdef'; +function checkFixture(f, reply = () => ({ code: 0 })) { + const calls = []; + f.ctx.getStopCheckCommand = () => [process.execPath, path.resolve('lifecycle_stop.py')]; + f.lifecycle.spawnStopCheck = (file, argv, options) => { + calls.push({ file, argv, options }); + const child = new EventEmitter(); + child.stdout = new EventEmitter(); child.stderr = new EventEmitter(); + child.kill = () => { queueMicrotask(() => child.emit('close', null, 'SIGTERM')); return true; }; + queueMicrotask(() => { + const response = reply(calls.length, child, f) || {}; + if (response.hang) return; + if (response.error) { child.emit('error', response.error); return; } + if (response.stdout) child.stdout.emit('data', Buffer.from(response.stdout)); + if (response.stderr) child.stderr.emit('data', Buffer.from(response.stderr)); + child.emit('close', response.code ?? 0, response.signal ?? null); + }); + return child; + }; + return calls; +} + function fixture(t, options = {}) { t.mock.timers.enable({ apis: ['Date', 'setTimeout'], now: 100000 }); const env = { SWITCHBOARD_TRIGGER_QUIET_MS: '50', SWITCHBOARD_BUSY_FALL_SETTLE_MS: '10', @@ -71,4 +94,4 @@ function fixture(t, options = {}) { observed: () => observed, close: () => { allowed = false; }, writer: value => { identity = value; }, proof: value => { proven = value; } }; } -module.exports = { fixture, ID, STEM }; +module.exports = { fixture, checkFixture, ID, STEM }; diff --git a/test/remote-ssh-spawn-sites.test.js b/test/remote-ssh-spawn-sites.test.js index b8aba0778..bff880354 100644 --- a/test/remote-ssh-spawn-sites.test.js +++ b/test/remote-ssh-spawn-sites.test.js @@ -42,6 +42,9 @@ const UNRESOLVED_ALLOWED = { runScheduleCommand: 'the shell of the schedule\'s shell profile, or on Windows the claude that headlessClaudeLaunch resolves on PATH', runClaudeCommand: 'the shell profile running a local claude command (agents, --bg, stop, respawn, rm)', }, + 'src/main/triggers/trigger-actions.js': { + runStopCheck: 'the stopCheckCommand argv from the global setting, an absolute executable the user configured; not a remote transport', + }, 'src/main/shared/run-to-exit.js': { runToExit: 'exported wrapper; its callers are covered by the program-name test below', }, diff --git a/test/setting-defaults.test.js b/test/setting-defaults.test.js index 6461076c7..47c881cee 100644 --- a/test/setting-defaults.test.js +++ b/test/setting-defaults.test.js @@ -98,6 +98,42 @@ function setupPanel(stored = {}, onSave = async () => ({ ok: true })) { // test in this file. const EFFECTIVE_WITH_NOTHING_STORED = { ...SETTING_DEFAULTS }; +test('final check setting', async () => { + const { validateStopCheckCommand } = require('../public/setting-defaults'); + assert.equal(SETTING_DEFAULTS.stopCheckCommand, null); + const valid = [process.execPath, '-B', path.resolve('validator.py')]; + assert.equal(validateStopCheckCommand(valid).ok, true); + assert.equal(validateStopCheckCommand([process.execPath, '']).ok, true); + for (const invalid of [[], ['relative'], ['--help'], + [process.execPath, 'bad\narg'], [process.execPath, 'x'.repeat(4097)], + Array(33).fill(process.execPath), 'command', {}]) { + assert.equal(validateStopCheckCommand(invalid).ok, false, JSON.stringify(invalid).slice(0, 100)); + } + if (process.platform !== 'win32') assert.equal(validateStopCheckCommand(['C:\\validator.exe']).ok, false); + const source = fs.readFileSync(path.join(ROOT, 'main.js'), 'utf8'); + assert.match(source, /getStopCheckCommand: \(\) => \(getSetting\('global'\)/); + const { createTriggerContext } = require('../src/main/triggers/trigger-context'); + const context = createTriggerContext({ activeSessions: new Map(), log: {}, getStopCheckCommand: () => valid }); + assert.deepEqual(context.getStopCheckCommand(), valid); + const begin = source.indexOf("ipcMain.handle('set-setting'"); + const end = source.indexOf("// see .ai/contexts/cli-harnesses.md", begin); + const handlers = new Map(); let stored = {}; + vm.runInNewContext(source.slice(begin, end), { + ipcMain: { handle: (name, handler) => handlers.set(name, handler) }, + validateStopCheckCommand, + writeGlobalSettings: async fn => fn(), + setSetting: async (_key, value) => { stored = value; }, + writer: { mergeGlobal: async patch => { stored = { ...stored, ...patch }; } }, + }); + await handlers.get('set-setting')(null, 'global', { stopCheckCommand: valid }); + assert.deepEqual(stored.stopCheckCommand, valid); + await assert.rejects(handlers.get('set-setting')(null, 'global', { stopCheckCommand: [] })); + await assert.rejects(handlers.get('merge-global-settings')(null, { stopCheckCommand: [] }, [])); + assert.deepEqual(stored.stopCheckCommand, valid); + await handlers.get('merge-global-settings')(null, { stopCheckCommand: null }, []); + assert.equal(stored.stopCheckCommand, null); +}); + test('Browser defaults are shared and the legacy Chrome default is retired', () => { assert.equal(SETTING_DEFAULTS.browserMode, 'off'); assert.equal(Object.hasOwn(SETTING_DEFAULTS, 'chrome'), false); diff --git a/test/trigger-actions-schema.test.js b/test/trigger-actions-schema.test.js index 6202dbb87..eaf8152c8 100644 --- a/test/trigger-actions-schema.test.js +++ b/test/trigger-actions-schema.test.js @@ -14,6 +14,23 @@ const newBase = { version: 1, action: 'open', new: { project: path.resolve('proj const stop = { version: 1, action: 'stop', sessionId: id }; const log = { info() {}, warn() {}, error() {} }; +test('final check schema', async t => { + const valid = { notePath: path.resolve('note.md') }; + const accepted = await runTrigger(t, { ...stop, finalCheck: valid }); + assert.equal(accepted.result.reason, 'session action not implemented in this build'); + for (const finalCheck of [null, {}, { notePath: '' }, { notePath: 'relative.md' }, + { notePath: 'a'.repeat(4097) }, { notePath: path.resolve('note') + '\n' }, + { ...valid, verifyArgv: ['--help'] }, { ...valid, '--help': true }]) { + const { result, effects } = await runTrigger(t, { ...stop, finalCheck }); + assert.match(result.reason, /^finalCheck/); + assert.equal(effects, 0); + } + const { validateTrigger } = require('../src/main/triggers/trigger-actions'); + const open = await runTrigger(t, { ...base, finalCheck: valid }); + assert.equal(open.result.reason, 'unsupported field: finalCheck'); assert.equal(open.effects, 0); + assert.equal(validateTrigger({ ...stop, finalCheck: valid, verifyArgv: ['--help'] }, request), 'unsupported field: verifyArgv'); +}); + async function runTrigger(t, payload, name = request) { const dir = fs.realpathSync.native(fs.mkdtempSync(path.join(os.tmpdir(), 'sb-v1-schema-'))); const previous = process.env.SWITCHBOARD_TRIGGERS_DIR; diff --git a/test/trigger-actions-stop.test.js b/test/trigger-actions-stop.test.js index 75dd063bc..0f7d1dc23 100644 --- a/test/trigger-actions-stop.test.js +++ b/test/trigger-actions-stop.test.js @@ -7,7 +7,276 @@ const path = require('node:path'); const vm = require('node:vm'); const { createRequire } = require('node:module'); const os = require('node:os'); -const { fixture, ID } = require('./fixtures/trigger-stop.cjs'); +const { fixture, checkFixture, ID } = require('./fixtures/trigger-stop.cjs'); + +const NOTE = path.resolve('final-note.md'); +const TOKEN = { noteCommit: 'a'.repeat(40), transcriptTurn: 'b'.repeat(64) }; +test('final check command construction', async t => { + const f = fixture(t); + const calls = checkFixture(f, number => ({ stdout: number === 1 ? JSON.stringify(TOKEN) + '\n' : '' })); + f.start({ finalCheck: { notePath: NOTE } }); await f.flush(); + assert.deepEqual(calls.map(call => [call.file, ...call.argv]), [ + [process.execPath, path.resolve('lifecycle_stop.py'), '--sample-final', '--session-id', ID, '--note', NOTE], + [process.execPath, path.resolve('lifecycle_stop.py'), '--check-final', '--session-id', ID, '--note', NOTE, + '--expected-note-commit', TOKEN.noteCommit, '--expected-transcript-turn', TOKEN.transcriptTurn], + ]); + assert.ok(calls.every(call => call.options.shell === false)); + assert.ok(calls.every(call => call.options.detached === (process.platform !== 'win32'))); + assert.equal(f.kills(), 1); + f.session.exited = true; assert.equal((await f.finish()).outcome, 'closed'); +}); + +test('final check ordering', async t => { + let f; + f = fixture(t, { onObserve: () => f.events.push(['sample']) }); + const saveMarker = f.execution.saveMarker; + f.execution.saveMarker = marker => { f.events.push(['marker', marker.phase]); saveMarker(marker); }; + const calls = checkFixture(f, number => ({ stdout: number === 1 ? JSON.stringify(TOKEN) : '' })); + const spawnCheck = f.lifecycle.spawnStopCheck; + f.lifecycle.spawnStopCheck = (...args) => { f.events.push(['check', calls.length + 1]); return spawnCheck(...args); }; + f.start({ finalCheck: { notePath: NOTE } }); await f.flush(); + const events = f.events.map(event => event[0]); + assert.equal(calls.length, 2); + assert.ok(events.lastIndexOf('sample', events.indexOf('check') - 1) > events.indexOf('marker')); + assert.ok(events.lastIndexOf('sample') > events.lastIndexOf('check')); + assert.ok(events.indexOf('stop') > events.lastIndexOf('sample')); + f.session.exited = true; assert.equal((await f.finish()).outcome, 'closed'); +}); + +test('legacy stop unchanged', async t => { + const f = fixture(t); const calls = checkFixture(f); + f.start(); await f.flush(); + assert.equal(calls.length, 0); assert.equal(f.kills(), 1); + f.session.exited = true; + assert.equal((await f.finish()).outcome, 'closed'); +}); + +test('final check refusal', async t => { + for (const [mode, reason] of [[1, 'note commit changed'], [2, 'transcript turn changed']]) { + const f = fixture(t); + const calls = checkFixture(f, number => number === 1 + ? { code: mode === 1 ? 1 : 0, stdout: mode === 1 ? reason + '\nsecond line' : JSON.stringify(TOKEN) } + : { code: 1, stdout: reason + '\nsecond line' }); + f.start({ finalCheck: { notePath: NOTE } }); const result = await f.finish(); + assert.equal(result.reason, 'stop check refused'); assert.equal(result.detail, reason); + assert.equal(result.outcome, 'refused'); assert.equal(result.uncertain, undefined); + assert.equal(calls.length, mode); assert.equal(f.kills(), 0); + t.mock.timers.reset(); + } +}); + +test('final check refusal keeps before evidence', async t => { + const f = fixture(t, { onEnter: () => setTimeout(() => { f.session._cliBusy = false; f.setStatus('idle'); }, 10) }); + checkFixture(f, number => number === 1 ? { stdout: JSON.stringify(TOKEN) } : { code: 1, stdout: 'note commit changed\n' }); + f.start({ before: 'Save a note', finalCheck: { notePath: NOTE } }); + const result = await f.finish(); + assert.equal(result.reason, 'stop check refused'); assert.equal(result.detail, 'note commit changed'); + assert.equal(result.wrote, true); assert.notEqual(result.submitted, 'no'); + assert.equal(result.delivery?.ok, true); assert.equal(result.uncertain, undefined); + assert.equal(f.kills(), 0); +}); + +test('final check post verification state', async t => { + for (const [change, reason] of [['busy', 'session busy'], ['input', 'session has unsubmitted input'], + ['quiet', 'session input not quiet'], ['target', 'session target changed'], + ['composer', 'session composer unavailable']]) { + const f = fixture(t); + const calls = checkFixture(f, number => { + if (number === 2) { + if (change === 'busy') f.setStatus('busy'); + if (change === 'input') f.input('draft'); + if (change === 'quiet') f.input('x\x7f'); + if (change === 'target') f.session.generation++; + if (change === 'composer') f.session.composerState = null; + } + return { stdout: number === 1 ? JSON.stringify(TOKEN) : '' }; + }); + f.start({ finalCheck: { notePath: NOTE } }); const result = await f.finish(); + assert.equal(result.reason, reason); assert.equal(result.uncertain, undefined); + assert.equal(calls.length, 2); assert.equal(f.kills(), 0); + t.mock.timers.reset(); + } + const late = fixture(t, { timeout: 40 }); + const calls = checkFixture(late, number => { + if (number === 2) t.mock.timers.setTime(late.execution.deadline + 1); + return { stdout: number === 1 ? JSON.stringify(TOKEN) : '' }; + }); + late.start({ finalCheck: { notePath: NOTE } }); + const result = await late.finish(); + assert.equal(result.reason, 'stop check timed out'); + assert.equal(result.uncertain, undefined); + assert.equal(calls.length, 2); + assert.equal(late.kills(), 0); +}); + +test('final check exit error', async t => { + for (const code of [3, 7]) { + const f = fixture(t); + checkFixture(f, number => number === 1 ? { stdout: JSON.stringify(TOKEN) } : { code, stderr: 'validator error\nmore' }); + f.start({ finalCheck: { notePath: NOTE } }); const result = await f.finish(); + assert.equal(result.reason, 'stop check failed'); assert.equal(result.detail, 'validator error'); + assert.equal(result.uncertain, undefined); assert.equal(f.kills(), 0); + t.mock.timers.reset(); + } + const overflow = fixture(t); + checkFixture(overflow, () => ({ code: 1, stdout: 'x'.repeat(5000) })); + overflow.start({ finalCheck: { notePath: NOTE } }); + const result = await overflow.finish(); + assert.equal(result.reason, 'stop check failed'); assert.equal(overflow.kills(), 0); + t.mock.timers.reset(); + const signaled = fixture(t); + checkFixture(signaled, number => number === 1 ? { stdout: JSON.stringify(TOKEN) } : { signal: 'SIGTERM' }); + signaled.start({ finalCheck: { notePath: NOTE } }); + assert.equal((await signaled.finish()).reason, 'stop check failed'); + assert.equal(signaled.kills(), 0); +}); + +test('final check malformed sample', async t => { + const f = fixture(t); const calls = checkFixture(f, () => ({ stdout: JSON.stringify({ noteCommit: TOKEN.noteCommit }) })); + f.start({ finalCheck: { notePath: NOTE } }); const result = await f.finish(); + assert.equal(result.reason, 'stop check failed'); assert.equal(calls.length, 1); assert.equal(f.kills(), 0); +}); + +test('final check timeout', async t => { + const f = fixture(t, { timeout: 40 }); let killed = false; + const calls = checkFixture(f, () => ({ hang: true })); + const spawnCheck = f.lifecycle.spawnStopCheck; + f.lifecycle.spawnStopCheck = (...args) => { + const child = spawnCheck(...args); const kill = child.kill; + child.kill = () => { killed = true; return kill(); }; + return child; + }; + const pending = f.start({ finalCheck: { notePath: NOTE } }); + await f.flush(); await f.tick(40); + const keepAlive = setInterval(() => {}, 1000); + try { + const result = await pending; + assert.equal(result.reason, 'stop check timed out'); assert.equal(result.uncertain, undefined); + assert.equal(calls.length, 1); assert.equal(killed, true); assert.equal(f.kills(), 0); + } finally { clearInterval(keepAlive); } +}); + +test('final check inherited stream deadline', async t => { + const { EventEmitter } = require('node:events'); + const f = fixture(t, { timeout: 40 }); + const groupKills = []; + if (process.platform !== 'win32') t.mock.method(process, 'kill', (...args) => { groupKills.push(args); return true; }); + let child; + f.ctx.getStopCheckCommand = () => [process.execPath, 'validator']; + f.lifecycle.spawnStopCheck = () => { + child = new EventEmitter(); + child.pid = 424242; + child.stdout = Object.assign(new EventEmitter(), { destroy() { this.destroyed = true; } }); + child.stderr = Object.assign(new EventEmitter(), { destroy() { this.destroyed = true; } }); + child.kill = () => { child.killed = true; return true; }; + queueMicrotask(() => child.emit('exit', 0)); + return child; + }; + f.start({ finalCheck: { notePath: NOTE } }); + await f.flush(); await f.tick(40); + assert.equal(f.done(), false, 'the deadline must allow child close before settling'); + await f.tick(499); + assert.equal(f.done(), false, 'the grace period must remain available'); + await f.tick(1); + assert.equal(f.done(), true, 'the grace period must settle without close'); + assert.equal(f.result().reason, 'stop check timed out'); + assert.equal(f.kills(), 0); + assert.deepEqual(f.events.slice(-3).map(event => event[0]), ['result', 'release-mutex', 'release-fifo']); + assert.equal(child.stdout.destroyed, true); + assert.equal(child.stderr.destroyed, true); + if (process.platform !== 'win32') assert.deepEqual(groupKills, [[-424242, 'SIGKILL']]); + else assert.equal(child.killed, true); +}); + +test('final check inherited stream overflow', async t => { + const { EventEmitter } = require('node:events'); + const f = fixture(t); + let child; + f.ctx.getStopCheckCommand = () => [process.execPath, 'validator']; + f.lifecycle.spawnStopCheck = () => { + child = new EventEmitter(); + child.stdout = Object.assign(new EventEmitter(), { destroy() { this.destroyed = true; } }); + child.stderr = Object.assign(new EventEmitter(), { destroy() { this.destroyed = true; } }); + child.kill = () => { child.killed = true; return true; }; + queueMicrotask(() => { child.emit('exit', 0); child.stdout.emit('data', Buffer.alloc(5000, 120)); }); + return child; + }; + f.start({ finalCheck: { notePath: NOTE } }); + await f.flush(); + assert.equal(f.done(), false, 'overflow must allow child close before settling'); + await f.tick(500); + assert.equal(f.done(), true, 'overflow must settle without close after the grace period'); + assert.equal(f.result().reason, 'stop check failed'); + assert.equal(f.kills(), 0); + assert.deepEqual(f.events.slice(-3).map(event => event[0]), ['result', 'release-mutex', 'release-fifo']); + assert.equal(child.stdout.destroyed, true); + assert.equal(child.stderr.destroyed, true); +}); + +test('final check overflow keeps its reason past the deadline', async t => { + const { EventEmitter } = require('node:events'); + const f = fixture(t, { timeout: 40 }); + if (process.platform !== 'win32') t.mock.method(process, 'kill', () => true); + let child; + f.ctx.getStopCheckCommand = () => [process.execPath, 'validator']; + f.lifecycle.spawnStopCheck = () => { + child = new EventEmitter(); + child.pid = 424243; + child.stdout = Object.assign(new EventEmitter(), { destroy() { this.destroyed = true; } }); + child.stderr = Object.assign(new EventEmitter(), { destroy() { this.destroyed = true; } }); + child.kill = () => { child.killed = true; return true; }; + return child; + }; + f.start({ finalCheck: { notePath: NOTE } }); + await f.flush(); await f.tick(20); + child.stdout.emit('data', Buffer.alloc(5000, 120)); + await f.tick(30); + assert.equal(f.done(), false, 'overflow must allow child close before settling'); + await f.tick(500); + assert.equal(f.done(), true, 'overflow must settle without close after the grace period'); + assert.equal(f.result().reason, 'stop check failed'); + assert.equal(f.kills(), 0); +}); + +test('final check reaps child on timeout', async t => { + const { spawn } = require('node:child_process'); + const f = fixture(t, { timeout: 40 }); let pid, closed = false; + f.ctx.getStopCheckCommand = () => [process.execPath, '-e', 'setInterval(() => {}, 1000)', '--']; + f.lifecycle.spawnStopCheck = (file, argv, options) => { + const child = spawn(file, argv, options); + pid = child.pid; + child.once('close', () => { closed = true; }); + return child; + }; + const pending = f.start({ finalCheck: { notePath: NOTE } }); + await f.flush(); await f.tick(40); + const result = await pending; + assert.equal(result.reason, 'stop check timed out'); + assert.ok(pid > 0); + assert.equal(closed, true, 'child close must precede the published result'); + assert.throws(() => process.kill(pid, 0), { code: 'ESRCH' }); + assert.equal(f.kills(), 0); +}); + +test('final check unavailable', async t => { + for (const command of [null, [], ['relative']]) { + const f = fixture(t); const calls = checkFixture(f); + f.ctx.getStopCheckCommand = () => command; + f.start({ finalCheck: { notePath: NOTE } }); const result = await f.finish(); + assert.equal(result.reason, 'stop check unavailable'); assert.equal(calls.length, 0); assert.equal(f.kills(), 0); + t.mock.timers.reset(); + } + const f = fixture(t); checkFixture(f); + f.lifecycle.spawnStopCheck = () => { throw new Error('spawn denied'); }; + f.start({ finalCheck: { notePath: NOTE } }); const result = await f.finish(); + assert.equal(result.reason, 'stop check unavailable'); assert.equal(f.kills(), 0); + t.mock.timers.reset(); + const unreadable = fixture(t); checkFixture(unreadable); + unreadable.ctx.getStopCheckCommand = () => { throw new Error('settings unreadable'); }; + unreadable.start({ finalCheck: { notePath: NOTE } }); + assert.equal((await unreadable.finish()).reason, 'stop check unavailable'); + assert.equal(unreadable.kills(), 0); +}); test('bare stop calls the shared sidebar backend once and reports closed only after pinned exit', async t => { const f = fixture(t); f.start(); await f.flush(); From be85c715ee1162ead300156f330f477990a9dfed Mon Sep 17 00:00:00 2001 From: Jean-Baptiste Renard Date: Wed, 2 Dec 2026 12:50:51 +0100 Subject: [PATCH 2/3] docs(changelog): reference #1405 in the final-check entry --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 98c4c649a..e09cb7890 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ What changes for you in each release of Switchboard. How to write an entry: [doc ## Unreleased ### New -- A trigger stop can ask for a final check before the session ends: with `"finalCheck":{"notePath":…}` and the new **stopCheckCommand** setting, Switchboard runs that command to confirm the note and the last turn just before stopping, and refuses the stop with `stop check refused`, `failed`, `timed out` or `unavailable` otherwise. Stops without `finalCheck` are unchanged. +- A trigger stop can ask for a final check before the session ends: with `"finalCheck":{"notePath":…}` and the new **stopCheckCommand** setting, Switchboard runs that command to confirm the note and the last turn just before stopping, and refuses the stop with `stop check refused`, `failed`, `timed out` or `unavailable` otherwise. Stops without `finalCheck` are unchanged. (#1405) - Moving a session to the background now asks whether to stop or keep an older job for the same conversation when Switchboard cannot tell if it is still running; Stop checks again before moving, and Cancel quietly keeps that session in the foreground while the rest of the batch continues. Cancellations from Claude and refusals after a choice still show their reason; Keep also checks for live jobs known only from the Agents list. Cancelled questions close, and waiting for a choice does not shorten the move’s confirmation time. (#1295) ### Changed From b22dd2385d2e924328ed0a47a500504b8baf9919 Mon Sep 17 00:00:00 2001 From: Jean-Baptiste Renard Date: Wed, 2 Dec 2026 13:12:21 +0100 Subject: [PATCH 3/3] docs(settings): document stopCheckCommand The global setting a stop trigger with finalCheck runs is listed with the settings no field sets, and links to the new "Stop final check" section of the automation guide. --- docs/automation.md | 2 ++ docs/settings.md | 4 ++++ 2 files changed, 6 insertions(+) diff --git a/docs/automation.md b/docs/automation.md index f52d007e2..2f023e14e 100644 --- a/docs/automation.md +++ b/docs/automation.md @@ -473,6 +473,8 @@ content. Failure returns `note step not finished` with `delivery` diagnostics and leaves the session running. A newly started turn after the note refuses `session busy` instead of terminating it. +#### Stop final check + A stop request may include `"finalCheck":{"notePath":"/absolute/path/to/note.md"}`. The field is valid only on stop and contains only `notePath`. The path must be absolute, at most 4096 characters, and free of control characters. Switchboard diff --git a/docs/settings.md b/docs/settings.md index e6a40d9ae..1fecb30b7 100644 --- a/docs/settings.md +++ b/docs/settings.md @@ -251,6 +251,10 @@ explicit action. See [Activity trace](activity-trace.md#deleting-older-log-files **Dangerous Skip** applies to one launch. - `remoteTriggers` (default off): lets a trigger reach a session of an enabled remote host — see [Automation](automation.md#remote-trigger-targets). +- `stopCheckCommand` (default none): the argv array of the command a stop + trigger with `finalCheck` runs to confirm the session's note and last turn + before stopping it; no settings field sets it — see + [Automation](automation.md#stop-final-check). - `lastSeenVersion` (default none): the last version whose **What's new** was shown — see [Changelog](changelog.md#whats-new-in-the-app).