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

fix: classify local delivery ancestry without adopting remote work

[._.]/ Adam Eivyd4a924807a77
diff --git a/server/services/repoCleanupObservation.delivery.test.js b/server/services/repoCleanupObservation.delivery.test.js
new file mode 100644
index 0000000000..82a3cfe00d
--- /dev/null
+++ b/server/services/repoCleanupObservation.delivery.test.js
@@ -0,0 +1,111 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import { materializeGitRepo } from '../lib/gitTestRepo.js';
+import { execGit } from '../lib/execGit.js';
+import { inspectOpenDeliveryRepair } from './repoCleanupObservation.js';
+
+const forge = vi.hoisted(() => ({ view: null, calls: [], afterAncestry: null }));
+vi.mock('./github.js', () => ({ execGh: vi.fn(async () => JSON.stringify(forge.view)) }));
+vi.mock('./forgeExecOptions.js', () => ({ resolveForgeExecOptions: async () => ({}) }));
+vi.mock('../lib/execGit.js', async original => {
+ const actual = await original();
+ return { ...actual, execGit: async (args, cwd, options) => {
+ forge.calls.push({ args, options });
+ const answer = await actual.execGit(args, cwd, options);
+ if (args[0] === 'merge-base' && forge.afterAncestry) {
+ const hook = forge.afterAncestry;
+ forge.afterAncestry = null;
+ await hook();
+ }
+ return answer;
+ } };
+});
+
+describe('open delivery relationship from exact local Git history', () => {
+ let root;
+ let base;
+ let one;
+ let two;
+ let other;
+ const branch = 'fix/work';
+ const inspect = () => inspectOpenDeliveryRepair(root, branch, 'https://github.com/example/repo/pull/7');
+ const commit = async text => {
+ await writeFile(join(root, 'work.txt'), text);
+ await execGit(['add', 'work.txt'], root);
+ await execGit(['commit', '-m', text], root);
+ return (await execGit(['rev-parse', 'HEAD'], root)).stdout.trim();
+ };
+ beforeEach(async () => {
+ root = await mkdtemp(join(tmpdir(), 'portos-delivery-ancestry-'));
+ await materializeGitRepo(root);
+ await execGit(['remote', 'add', 'origin', 'https://github.com/example/repo.git'], root);
+ base = (await execGit(['rev-parse', 'HEAD'], root)).stdout.trim();
+ await execGit(['checkout', '-b', branch], root);
+ one = await commit('local one');
+ two = await commit('local two');
+ await execGit(['checkout', '-b', 'fixture/diverged', base], root);
+ other = await commit('other history');
+ await execGit(['checkout', 'main'], root);
+ forge.view = { number: 7, state: 'OPEN', isDraft: false, isCrossRepository: false,
+ headRefName: branch, headRefOid: two, mergeable: 'MERGEABLE', reviewDecision: '', statusCheckRollup: [] };
+ forge.calls = [];
+ forge.afterAncestry = null;
+ });
+ afterEach(async () => { await rm(root, { recursive: true, force: true, maxRetries: 3 }); });
+
+ it.each(['local-ahead', 'local-behind', 'diverged', 'equal'])('reports %s without changing refs or authorizing delivery', async relation => {
+ const local = relation === 'local-behind' ? one : two;
+ const published = relation === 'local-ahead' ? one : relation === 'diverged' ? other : two;
+ await execGit(['update-ref', `refs/heads/${branch}`, local], root);
+ forge.view.headRefOid = published;
+ // Even failed checks on a mismatching published head cannot authorize
+ // repair of a different local head or overwrite its unpublished commits.
+ forge.view.statusCheckRollup = [{ name: 'CI', conclusion: 'FAILURE' }];
+ const before = (await execGit(['show-ref'], root)).stdout;
+ forge.calls = [];
+ const result = await inspect();
+ expect(result).toMatchObject({ ancestry: { relation, localHead: local, publishedHead: published } });
+ if (relation === 'equal') expect(result).toMatchObject({ actionable: true, headSha: two });
+ else {
+ expect(result.reason).toBe(`delivery-${relation}`);
+ expect(result.actionable).not.toBe(true);
+ expect(result.headSha).toBeUndefined();
+ }
+ expect(forge.calls.some(({ args }) => ['fetch', 'push', 'reset', 'update-ref', 'checkout'].includes(args[0]))).toBe(false);
+ expect((await execGit(['show-ref'], root)).stdout).toBe(before);
+ });
+
+ it('retains unknown for an unavailable published object without fetching it', async () => {
+ forge.view.headRefOid = 'a'.repeat(40);
+ expect(await inspect()).toMatchObject({ reason: 'delivery-head-unverified' });
+ expect(forge.calls.some(({ args }) => args[0] === 'fetch')).toBe(false);
+ expect(forge.calls.filter(({ args }) => ['cat-file', 'merge-base'].includes(args[0])))
+ .toEqual(expect.arrayContaining([expect.objectContaining({ options: expect.objectContaining({
+ env: expect.objectContaining({ GIT_NO_LAZY_FETCH: '1', GIT_NO_REPLACE_OBJECTS: '1' }),
+ }) })]));
+ });
+
+ it('rejects a changed local ref after observing ancestry', async () => {
+ forge.view.headRefOid = one;
+ forge.afterAncestry = () => execGit(['update-ref', `refs/heads/${branch}`, base], root);
+ expect(await inspect()).toMatchObject({ reason: 'delivery-head-unverified' });
+ });
+
+ it('does not infer divergence from a shallow history boundary', async () => {
+ forge.view.headRefOid = other;
+ await writeFile(join(root, '.git', 'shallow'), `${two}\n${other}\n`);
+ const result = await inspect();
+ expect(result).toMatchObject({ reason: 'delivery-head-unverified' });
+ expect(result.ancestry).toBeUndefined();
+ expect(result.headSha).toBeUndefined();
+ });
+
+ it.each(['foreign branch', 'cross-repository', 'no local branch'])('does not adopt %s from PR metadata', async kind => {
+ if (kind === 'foreign branch') forge.view.headRefName = 'fix/another-machine';
+ if (kind === 'cross-repository') forge.view.isCrossRepository = true;
+ if (kind === 'no local branch') await execGit(['update-ref', '-d', `refs/heads/${branch}`], root);
+ expect(await inspect()).toMatchObject({ reason: 'delivery-head-unverified' });
+ });
+});
diff --git a/server/services/repoCleanupObservation.js b/server/services/repoCleanupObservation.js
index bb3fd56de1..63de6e793c 100644
--- a/server/services/repoCleanupObservation.js
+++ b/server/services/repoCleanupObservation.js
@@ -86,6 +86,41 @@ export async function readLocalBranchPresence(repoPath, branch) {
}
+const COMMIT_SHA = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/;
+
+/** Observe only existing local objects. A relationship describes two captured
+ * commits; it never authorizes adopting a PR, fetching, or replacing local work.
+ */
+async function readDeliveryAncestry(repoPath, branch, publishedHead) {
+ if (!isSafeGitRef(branch) || !COMMIT_SHA.test(publishedHead)) return null;
+ const env = { ...process.env, GIT_OPTIONAL_LOCKS: '0', GIT_NO_LAZY_FETCH: '1', GIT_NO_REPLACE_OBJECTS: '1' };
+ const run = args => execGit(args, repoPath, { ignoreExitCode: true, env, timeout: 5000, maxBuffer: 4096 });
+ const ref = `refs/heads/${branch}`;
+ try {
+ if ((await run(['check-ref-format', ref])).exitCode !== 0) return null;
+ const readHead = () => run(['rev-parse', '--verify', `${ref}^{commit}`]);
+ const local = await readHead();
+ const localHead = local.stdout.trim();
+ if (local.exitCode !== 0 || !COMMIT_SHA.test(localHead)) return null;
+ if ((await run(['cat-file', '-e', `${publishedHead}^{commit}`])).exitCode !== 0) return null;
+ let relation = 'equal';
+ if (localHead !== publishedHead) {
+ const publishedBeforeLocal = await run(['merge-base', '--is-ancestor', publishedHead, localHead]);
+ const localBeforePublished = await run(['merge-base', '--is-ancestor', localHead, publishedHead]);
+ if (![0, 1].includes(publishedBeforeLocal.exitCode) || ![0, 1].includes(localBeforePublished.exitCode)) return null;
+ if (publishedBeforeLocal.exitCode === 0 && localBeforePublished.exitCode === 1) relation = 'local-ahead';
+ else if (publishedBeforeLocal.exitCode === 1 && localBeforePublished.exitCode === 0) relation = 'local-behind';
+ else if (publishedBeforeLocal.exitCode === 1 && localBeforePublished.exitCode === 1) {
+ const shallow = await run(['rev-parse', '--is-shallow-repository']);
+ if (shallow.exitCode !== 0 || shallow.stdout.trim() !== 'false') return null;
+ relation = 'diverged';
+ } else return null;
+ }
+ const current = await readHead();
+ return current.exitCode === 0 && current.stdout.trim() === localHead ? { relation, localHead, publishedHead } : null;
+ } catch { return null; }
+}
+
/** A known open PR is not, by itself, a request for cognitive work. */
export async function inspectOpenDeliveryRepair(repoPath, branch, prUrl, { forgeAccount = null } = {}) {
const target = parsePullRequestUrl(prUrl);
@@ -100,15 +135,15 @@ export async function inspectOpenDeliveryRepair(repoPath, branch, prUrl, { forge
const options = await resolveForgeExecOptions(repoPath, { forgeAccount });
const view = JSON.parse(await execGh(['pr', 'view', String(target.number), '--repo', spec,
'--json', 'number,state,isDraft,isCrossRepository,headRefName,headRefOid,mergeable,reviewDecision,statusCheckRollup'], undefined, options));
- const local = await execGit(['rev-parse', '--verify', `refs/heads/${branch}`], repoPath,
- { env: { ...process.env, GIT_OPTIONAL_LOCKS: '0', GIT_NO_LAZY_FETCH: '1' } });
if (view.number !== target.number || view.state !== 'OPEN' || view.isCrossRepository !== false
- || view.headRefName !== branch || !/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(view.headRefOid || '')
- || view.headRefOid !== local.stdout.trim()) return { reason: 'delivery-head-unverified' };
- if (view.isDraft !== false) return { reason: 'delivery-draft-held' };
+ || view.headRefName !== branch || !COMMIT_SHA.test(view.headRefOid || '')) return { reason: 'delivery-head-unverified' };
+ const ancestry = await readDeliveryAncestry(repoPath, branch, view.headRefOid);
+ if (!ancestry) return { reason: 'delivery-head-unverified' };
+ if (ancestry.relation !== 'equal') return { reason: `delivery-${ancestry.relation}`, ancestry };
+ if (view.isDraft !== false) return { reason: 'delivery-draft-held', ancestry };
const failed = (view.statusCheckRollup || []).filter(check => ['FAILURE', 'ERROR', 'TIMED_OUT', 'ACTION_REQUIRED'].includes(check.conclusion || check.state));
const actionable = view.mergeable === 'CONFLICTING' || view.reviewDecision === 'CHANGES_REQUESTED' || failed.length > 0;
- return actionable ? { actionable: true, headSha: view.headRefOid, evidence: { head: view.headRefOid, conflicts: view.mergeable === 'CONFLICTING',
+ return actionable ? { actionable: true, headSha: view.headRefOid, ancestry, evidence: { head: view.headRefOid, conflicts: view.mergeable === 'CONFLICTING',
changesRequested: view.reviewDecision === 'CHANGES_REQUESTED', checks: failed.map(check => ({ name: check.name || check.context, conclusion: check.conclusion || check.state })).sort((a,b) => String(a.name).localeCompare(String(b.name))) } }
- : { headSha: view.headRefOid, reason: 'delivery-ci-or-review-pending' };
+ : { headSha: view.headRefOid, ancestry, reason: 'delivery-ci-or-review-pending' };
}