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

test: verify ownership recheck response integrity (#11348)

[._.]/ Adam Eivy18e95413fdd4
diff --git a/docs/features/chief-of-staff.md b/docs/features/chief-of-staff.md
index 3af28acd5b..fce505745d 100644
--- a/docs/features/chief-of-staff.md
+++ b/docs/features/chief-of-staff.md
@@ -113,6 +113,37 @@ the worker runs right before its first mutation, because a run can take the
branch after the scan. A refusal, an unreadable registry, or a moved checkout
leaves the branch untouched; a completed or released owner admits recovery.
+### Ownership response investigation (#11348)
+
+The 2026-10-13 reconciliation observation `{"admitted":true}}` could not be
+reproduced at the generated-command/HTTP boundary. The original capture had
+neither HTTP status nor headers, so it does not identify whether the extra
+byte came from the server, transport, or the tool that displayed the output.
+No production producer fix is claimed.
+
+`server/routes/cosAgentRoutes.ownershipResponse.test.js` runs the actual
+generated recheck command through a shell and curl against a loopback Express
+server with the real ownership service. All agents, repository paths, state
+and authorization are synthetic; it never reserves an existing install's
+branch. Status and headers are captured with the exact body bytes. Successful
+admission returns HTTP 200, JSON content type, Content-Length 17, and body hex
+`7b2261646d6974746564223a747275657d` (`{"admitted":true}`). Strict parsing of
+the complete body succeeds, and a subsequent competing claim bind is refused.
+Live-owner, unreadable-registry and unknown-coordinator refusals each return
+one complete JSON document with their service reason and leave state unchanged.
+The synthetic authentication gate's HTTP 401 remains a separate error envelope.
+
+If this recurs, capture the **first** authorized recheck using curl's
+`--dump-header <private-header-file>`, `--output <private-body-file>` and
+`--write-out '%{http_code}'` options, retaining its exit code separately.
+Use a private scratch directory outside the repository; do not enable verbose
+request logging or store the bearer token. Parse the whole body file without
+trimming or extracting a JSON substring. Compare its byte count and hex with
+the tool-displayed output before attributing the fault; headers and bodies
+remain private until redacted. A failed HTTP request, refusal, or malformed
+body leaves the branch untouched. A second request cannot retroactively
+authorize an unreadable first result.
+
## Task File Format
```markdown
diff --git a/server/routes/cosAgentRoutes.ownershipResponse.test.js b/server/routes/cosAgentRoutes.ownershipResponse.test.js
new file mode 100644
index 0000000000..8bb47bb9eb
--- /dev/null
+++ b/server/routes/cosAgentRoutes.ownershipResponse.test.js
@@ -0,0 +1,130 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import express from 'express';
+import { promisify } from 'node:util';
+import { execFile } from '../lib/childProcess.js';
+import { startLoopbackServer, closeLoopbackServer } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+
+const fixture = vi.hoisted(() => ({ state: null, apiBase: '', unreadable: false }));
+vi.mock('../services/cos.js', () => ({}));
+vi.mock('../services/agentOrchestrator.js', () => ({}));
+vi.mock('../services/apps.js', () => ({ getAppById: async () => ({ repoPath: '/synthetic/repo' }) }));
+vi.mock('../services/cosState.js', () => ({
+ withStateLock: (work) => work(),
+ loadState: async () => structuredClone(fixture.state),
+ saveState: async (state) => { fixture.state = structuredClone(state); },
+}));
+vi.mock('../services/cosEvents.js', () => ({ cosEvents: { emit: vi.fn() } }));
+vi.mock('../services/cosAgentLifecycle.js', () => ({
+ getAgents: async () => fixture.unreadable ? null : Object.values(fixture.state.agents),
+}));
+vi.mock('../services/agentState.js', () => ({ getActiveAgentIds: () => [] }));
+vi.mock('../services/worktreeManager.js', async (importOriginal) => ({
+ ...await importOriginal(),
+ listWorktrees: async () => [{ branch: 'refs/heads/claim/issue-101', path: '/synthetic/repo/worktree' }],
+}));
+vi.mock('../services/github.js', () => ({
+ execGh: vi.fn(), ensureForgeReachable: vi.fn(),
+ getIssueDispatchHint: async () => ({ status: 'unavailable', model: null, effort: null }),
+}));
+vi.mock('../lib/networkExposure.js', () => ({ localApiBaseUrl: () => fixture.apiBase }));
+
+import routes from './cosAgentRoutes.js';
+import { formatInFlightForPrompt } from '../services/branchReconcile.js';
+import { updateClaimOwnership } from '../services/cosClaimOwnership.js';
+
+const execute = promisify(execFile);
+const coordinator = 'synthetic-coordinator';
+const branch = 'claim/issue-101';
+let server;
+
+beforeEach(async () => {
+ fixture.unreadable = false;
+ fixture.state = { agents: {
+ [coordinator]: { id: coordinator, status: 'running', workspacePath: '/synthetic/repo', metadata: {} },
+ } };
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ const app = express();
+ // Synthetic authorization only: no real install credential or runtime state.
+ app.use((req, res, next) => req.get('Authorization') === 'Bearer synthetic-test-token'
+ ? next() : res.status(401).json({ error: 'Authentication required', code: 'AUTH_REQUIRED' }));
+ app.use(express.json());
+ app.use('/api/cos', routes);
+ app.use(errorMiddleware);
+ server = await startLoopbackServer(app);
+ fixture.apiBase = `http://127.0.0.1:${server.address().port}`;
+});
+
+afterEach(async () => {
+ if (server) await closeLoopbackServer(server);
+ server = null;
+ vi.restoreAllMocks();
+});
+
+// Exercise the command handed to a coordinator, including shell quoting and
+// curl's output boundary. Split the HTTP header delimiter as bytes; the body
+// is never trimmed, concatenated with diagnostics, or repaired before parsing.
+async function captureRecheck({ token = 'synthetic-test-token', agentId = coordinator } = {}) {
+ const prompt = await formatInFlightForPrompt([
+ { branch, state: 'ABANDONED_WIP', worktreePath: '/synthetic/repo/worktree' },
+ ], { defaultBranch: 'main', actions: {}, appId: 'synthetic-app' });
+ const command = prompt.match(/^- Recheck: `([^\n]+)`$/m)[1].replace('{agentId}', agentId);
+ const { stdout, stderr } = await execute('sh', ['-c', `${command} --dump-header - --max-time 10`], {
+ encoding: 'buffer', timeout: 15000,
+ env: { PATH: process.env.PATH, SYSTEMROOT: process.env.SYSTEMROOT, PORTOS_API_TOKEN: token },
+ });
+ expect(stderr.length).toBe(0);
+ const separator = stdout.indexOf(Buffer.from('\r\n\r\n'));
+ expect(separator).toBeGreaterThan(0);
+ const headerText = stdout.subarray(0, separator).toString('utf8');
+ const body = stdout.subarray(separator + 4);
+ const status = Number(headerText.match(/^HTTP\/\S+ (\d+)/)[1]);
+ expect(headerText).toMatch(/content-type: application\/json/i);
+ expect(Number(headerText.match(/content-length: (\d+)/i)[1])).toBe(body.length);
+ return { status, body, parsed: JSON.parse(body.toString('utf8')) };
+}
+
+describe('generated ownership recheck raw HTTP response (#11348)', () => {
+ it('returns exactly one JSON document and reserves the branch for the registered coordinator', async () => {
+ const capture = await captureRecheck();
+ expect(capture.status).toBe(200);
+ expect(capture.body.toString('hex')).toBe('7b2261646d6974746564223a747275657d');
+ expect(capture.parsed).toEqual({ admitted: true });
+ expect(fixture.state.agents[coordinator].metadata.claimBranches).toEqual([branch]);
+ fixture.state.agents.picker = { id: 'picker', status: 'running', workspacePath: '/synthetic/repo',
+ metadata: { sourceWorkspace: '/synthetic/repo', claimBranch: 'claim/issue-100', claimPicksOwnBranch: false } };
+ expect(await updateClaimOwnership({ action: 'bind', agentId: 'picker', branch }))
+ .toEqual({ bound: false, reason: 'owner-active' });
+ });
+
+ it.each(['claim-owner-active', 'ownership-unreadable', 'owner-unknown'])('preserves the %s refusal as complete JSON without reserving', async (reason) => {
+ if (reason === 'claim-owner-active') {
+ fixture.state.agents.owner = { id: 'owner', status: 'running', metadata: { claimBranches: [branch] } };
+ }
+ if (reason === 'ownership-unreadable') fixture.unreadable = true;
+ const before = structuredClone(fixture.state);
+ const capture = await captureRecheck({ agentId: reason === 'owner-unknown' ? 'unknown' : coordinator });
+ expect(capture.status).toBe(200);
+ expect(capture.body.toString('utf8')).toBe(JSON.stringify({ admitted: false, reason }));
+ expect(capture.parsed).toEqual({ admitted: false, reason });
+ expect(fixture.state).toEqual(before);
+ });
+
+ it('keeps an HTTP authentication error separate from admission and leaves ownership unchanged', async () => {
+ const before = structuredClone(fixture.state);
+ const capture = await captureRecheck({ token: 'invalid-synthetic-token' });
+ expect(capture.status).toBe(401);
+ expect(capture.parsed).toEqual({ error: 'Authentication required', code: 'AUTH_REQUIRED' });
+ expect(fixture.state).toEqual(before);
+ });
+
+ it('serializes route validation errors without granting admission or changing ownership', async () => {
+ const before = structuredClone(fixture.state);
+ const capture = await captureRecheck({ agentId: '' });
+ expect(capture.status).toBe(400);
+ expect(capture.parsed).toMatchObject({ code: 'VALIDATION_ERROR' });
+ expect(capture.parsed.admitted).toBeUndefined();
+ expect(fixture.state).toEqual(before);
+ });
+});