Skip to content

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

address review: restore autostash for non-main updaters, add codex sentinel regression tests

Adam Eivyc4e8ab178e0a
diff --git a/server/services/runner.test.js b/server/services/runner.test.js
new file mode 100644
index 0000000000..b83a046720
--- /dev/null
+++ b/server/services/runner.test.js
@@ -0,0 +1,99 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import EventEmitter from 'events';
+
+vi.mock('child_process', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, spawn: vi.fn() };
+});
+
+vi.mock('../lib/fileUtils.js', () => ({
+ ensureDir: vi.fn().mockResolvedValue(undefined),
+}));
+
+vi.mock('fs/promises', () => ({
+ writeFile: vi.fn().mockResolvedValue(undefined),
+ readFile: vi.fn().mockResolvedValue('{}'),
+}));
+
+const { spawn } = await import('child_process');
+const runner = await import('./runner.js');
+const { setAIToolkit, executeCliRun } = runner;
+
+// Minimal toolkit stub that satisfies executeCliRun's expectations
+function fakeToolkit() {
+ return {
+ services: {
+ runner: { _portosActiveRuns: new Map() },
+ errorDetection: null,
+ },
+ };
+}
+
+function makeChild() {
+ const child = new EventEmitter();
+ child.stdout = new EventEmitter();
+ child.stderr = new EventEmitter();
+ child.stdin = { write: vi.fn(), end: vi.fn() };
+ child.kill = vi.fn();
+ child.killed = false;
+ return child;
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ setAIToolkit(fakeToolkit(), { dataDir: '/tmp/test-runner' });
+});
+
+describe('executeCliRun — Codex sentinel suppression', () => {
+ it('omits --model when defaultModel is codex-configured-default', async () => {
+ const child = makeChild();
+ spawn.mockReturnValue(child);
+
+ const provider = {
+ id: 'codex',
+ command: 'codex',
+ args: [],
+ defaultModel: 'codex-configured-default',
+ timeout: 5000,
+ };
+
+ setImmediate(() => {
+ child.stdout.emit('data', Buffer.from('output'));
+ child.emit('close', 0);
+ });
+
+ await executeCliRun('run-1', provider, 'test prompt', '/workspace');
+
+ const [, capturedArgs] = spawn.mock.calls.at(-1);
+ expect(capturedArgs).not.toContain('--model');
+ expect(capturedArgs).not.toContain('codex-configured-default');
+ // Should still have the exec subcommand and stdin marker
+ expect(capturedArgs).toContain('exec');
+ expect(capturedArgs).toContain('-');
+ });
+
+ it('passes --model when a real model name is provided', async () => {
+ const child = makeChild();
+ spawn.mockReturnValue(child);
+
+ const provider = {
+ id: 'codex',
+ command: 'codex',
+ args: [],
+ defaultModel: 'o4-mini',
+ timeout: 5000,
+ };
+
+ setImmediate(() => {
+ child.stdout.emit('data', Buffer.from('output'));
+ child.emit('close', 0);
+ });
+
+ await executeCliRun('run-2', provider, 'test prompt', '/workspace');
+
+ const [, capturedArgs] = spawn.mock.calls.at(-1);
+ const modelIdx = capturedArgs.indexOf('--model');
+ expect(modelIdx).toBeGreaterThanOrEqual(0);
+ expect(capturedArgs[modelIdx + 1]).toBe('o4-mini');
+ });
+});
diff --git a/server/services/writersRoom/evaluator.test.js b/server/services/writersRoom/evaluator.test.js
new file mode 100644
index 0000000000..a560125e7f
--- /dev/null
+++ b/server/services/writersRoom/evaluator.test.js
@@ -0,0 +1,132 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import EventEmitter from 'events';
+
+vi.mock('child_process', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, spawn: vi.fn() };
+});
+
+vi.mock('../../lib/fileUtils.js', () => ({
+ PATHS: { data: '/tmp/wr-eval-test' },
+ atomicWrite: vi.fn().mockResolvedValue(undefined),
+ ensureDir: vi.fn().mockResolvedValue(undefined),
+ safeJSONParse: vi.fn((v) => (typeof v === 'string' ? JSON.parse(v) : v)),
+}));
+
+vi.mock('../providers.js', () => ({
+ getActiveProvider: vi.fn(),
+ getProviderById: vi.fn(),
+}));
+
+vi.mock('../promptService.js', () => ({
+ buildPrompt: vi.fn().mockResolvedValue('test prompt'),
+ getStage: vi.fn().mockReturnValue({ stage: 'writers-room-evaluate', model: null }),
+}));
+
+vi.mock('./local.js', () => ({
+ getWorkWithBody: vi.fn(),
+}));
+
+vi.mock('./characters.js', () => ({
+ listCharacters: vi.fn().mockResolvedValue([]),
+ mergeExtractedCharacters: vi.fn().mockResolvedValue([]),
+}));
+
+vi.mock('./settings.js', () => ({
+ listSettings: vi.fn().mockResolvedValue([]),
+ mergeExtractedSettings: vi.fn().mockResolvedValue([]),
+}));
+
+const { spawn } = await import('child_process');
+const providers = await import('../providers.js');
+const local = await import('./local.js');
+const evaluator = await import('./evaluator.js');
+const { runAnalysis } = evaluator;
+
+// A minimal work manifest + body that satisfies runAnalysis's guard checks
+// (WORK_ID_RE requires wr-work- followed by only hex digits and dashes)
+const FAKE_WORK_ID = 'wr-work-aabbccdd-eeff-1122-3344-556677889900';
+const fakeWorkManifest = {
+ id: FAKE_WORK_ID,
+ title: 'Test Work',
+ kind: 'novel',
+ status: 'drafting',
+ activeDraftVersionId: 'wr-draft-v1',
+ drafts: [{ id: 'wr-draft-v1', wordCount: 10, contentHash: 'abc123' }],
+};
+
+function makeChild(exitCode = 0) {
+ const child = new EventEmitter();
+ child.stdout = new EventEmitter();
+ child.stderr = new EventEmitter();
+ child.stdin = { on: vi.fn(), end: vi.fn() };
+ child.kill = vi.fn();
+ child.killed = false;
+ return child;
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ local.getWorkWithBody.mockResolvedValue({
+ manifest: fakeWorkManifest,
+ body: 'Once upon a time there was a test.',
+ });
+});
+
+describe('evaluator buildCliInvocation — Codex sentinel suppression', () => {
+ it('omits --model when the model is codex-configured-default', async () => {
+ providers.getActiveProvider.mockResolvedValue({
+ id: 'codex',
+ type: 'cli',
+ enabled: true,
+ command: 'codex',
+ args: [],
+ defaultModel: 'codex-configured-default',
+ timeout: 5000,
+ });
+
+ const child = makeChild();
+ spawn.mockReturnValue(child);
+
+ setImmediate(() => {
+ child.stdout.emit('data', Buffer.from(JSON.stringify({ logline: 'a', summary: 'b', themes: [], strengths: [], issues: [], suggestions: [] })));
+ child.emit('close', 0);
+ });
+
+ await runAnalysis(FAKE_WORK_ID, { kind: 'evaluate' });
+
+ const [, capturedArgs] = spawn.mock.calls.at(-1);
+ expect(capturedArgs).not.toContain('--model');
+ expect(capturedArgs).not.toContain('codex-configured-default');
+ // Codex exec + stdin marker must still be present
+ expect(capturedArgs).toContain('exec');
+ expect(capturedArgs).toContain('-');
+ });
+
+ it('passes --model when a real model name is provided', async () => {
+ providers.getActiveProvider.mockResolvedValue({
+ id: 'codex',
+ type: 'cli',
+ enabled: true,
+ command: 'codex',
+ args: [],
+ defaultModel: 'o4-mini',
+ timeout: 5000,
+ });
+
+ const child = makeChild();
+ spawn.mockReturnValue(child);
+
+ setImmediate(() => {
+ child.stdout.emit('data', Buffer.from(JSON.stringify({ logline: 'a', summary: 'b', themes: [], strengths: [], issues: [], suggestions: [] })));
+ child.emit('close', 0);
+ });
+
+ await runAnalysis(FAKE_WORK_ID, { kind: 'evaluate' });
+
+ const [, capturedArgs] = spawn.mock.calls.at(-1);
+ const modelIdx = capturedArgs.indexOf('--model');
+ expect(modelIdx).toBeGreaterThanOrEqual(0);
+ expect(capturedArgs[modelIdx + 1]).toBe('o4-mini');
+ });
+});
diff --git a/update.ps1 b/update.ps1
index 96dbdb34e8..13e635814c 100644
--- a/update.ps1
+++ b/update.ps1
@@ -95,11 +95,30 @@ function Safe-Install {
}
# Pull latest — always switch to main (detached HEAD or feature branch both
-# need to land on main before pulling, or the version won't advance)
+# need to land on main before pulling, or the version won't advance). If the
+# user has uncommitted edits on a non-main branch, stash them first so the
+# checkout doesn't abort or carry edits onto main, then restore on the way back.
Step "git-pull" "running" "Pulling latest changes..."
$headRef = git symbolic-ref -q HEAD 2>$null
$currentBranch = if ($headRef) { $headRef -replace "refs/heads/", "" } else { "" }
+$stashed = $false
if ($currentBranch -ne "main") {
+ $hasChanges = $false
+ git diff --quiet 2>$null
+ if ($LASTEXITCODE -ne 0) { $hasChanges = $true }
+ if (-not $hasChanges) {
+ git diff --cached --quiet 2>$null
+ if ($LASTEXITCODE -ne 0) { $hasChanges = $true }
+ }
+ if (-not $hasChanges) {
+ $untracked = git ls-files --others --exclude-standard
+ if ($untracked) { $hasChanges = $true }
+ }
+ if ($hasChanges) {
+ Write-SafeHost "⚠️ Stashing local changes from '$(if ($currentBranch) { $currentBranch } else { 'detached HEAD' })' before switching to main" -ForegroundColor Yellow
+ Invoke-Logged git stash push -u -m "portos-update-$([int][double]::Parse((Get-Date -UFormat %s)))"
+ if ($LASTEXITCODE -eq 0) { $stashed = $true }
+ }
if (-not $currentBranch) {
$detachedCommit = git rev-parse --short HEAD
Write-SafeHost "⚠️ On detached HEAD (commit $detachedCommit) — switching to main for update" -ForegroundColor Yellow
@@ -111,6 +130,18 @@ if ($currentBranch -ne "main") {
}
Invoke-Logged git pull --rebase --autostash
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+if ($stashed) {
+ if ($currentBranch) {
+ Write-SafeHost "⚠️ Returning to '$currentBranch' and restoring stashed changes" -ForegroundColor Yellow
+ Invoke-Logged git checkout $currentBranch
+ Invoke-Logged git stash pop
+ if ($LASTEXITCODE -ne 0) {
+ Write-SafeHost "⚠️ Could not restore stashed changes — see 'git stash list'" -ForegroundColor Yellow
+ }
+ } else {
+ Write-SafeHost "⚠️ Was on detached HEAD; stashed changes preserved in 'git stash' (run 'git stash pop' manually)" -ForegroundColor Yellow
+ }
+}
Step "git-pull" "done" "Latest changes pulled"
Write-SafeHost ""
diff --git a/update.sh b/update.sh
index 59ac0cb134..95763c18ed 100755
--- a/update.sh
+++ b/update.sh
@@ -60,14 +60,31 @@ safe_install() {
}
# Pull latest — always switch to main (detached HEAD or feature branch both
-# need to land on main before pulling, or the version won't advance)
+# need to land on main before pulling, or the version won't advance). If the
+# user has uncommitted edits on a non-main branch, stash them first so the
+# checkout doesn't abort or carry edits onto main, then restore on the way back.
step "git-pull" "running" "Pulling latest changes..."
current_branch=$(git symbolic-ref -q --short HEAD 2>/dev/null || echo "")
+stashed=0
if [ "$current_branch" != "main" ]; then
+ if ! git diff --quiet || ! git diff --cached --quiet || [ -n "$(git ls-files --others --exclude-standard)" ]; then
+ log "⚠️ Stashing local changes from '${current_branch:-detached HEAD}' before switching to main"
+ if run git stash push -u -m "portos-update-$(date +%s)"; then
+ stashed=1
+ fi
+ fi
log "⚠️ On branch '${current_branch:-detached HEAD}' — switching to main for update"
run git checkout main
fi
run git pull --rebase --autostash
+if [ "$stashed" = "1" ]; then
+ if [ -n "$current_branch" ]; then
+ log "⚠️ Returning to '$current_branch' and restoring stashed changes"
+ run git checkout "$current_branch" && (run git stash pop || log "⚠️ Could not restore stashed changes — see 'git stash list'")
+ else
+ log "⚠️ Was on detached HEAD; stashed changes preserved in 'git stash' (run 'git stash pop' manually)"
+ fi
+fi
step "git-pull" "done" "Latest changes pulled"
log ""