Harden workspace sync quarantine and updater recovery (#6)
ForgeFlow quality gate / secret-scan (push) Successful in 8s
ForgeFlow quality gate / quality (push) Failing after 11m39s

This commit was merged in pull request #6.
This commit is contained in:
2026-08-30 00:34:02 +02:00
parent d926007dae
commit a93231d69f
7 changed files with 163 additions and 17 deletions
+71 -2
View File
@@ -167,6 +167,48 @@ class GitService {
return { root, gitDir: path.resolve(result.stdout.trim()) };
}
async writeWorkspaceReviewManifest(repoPath, plan, { backupBranch = null, stash = null } = {}) {
const { root, gitDir } = await this.gitDirectory(repoPath);
const reviewId = String(plan?.id || '').trim();
if (!/^[0-9a-f]{64}$/i.test(reviewId)) throw new Error('Workspace review manifest requires a valid synchronization plan.');
const reviewDirectory = path.join(gitDir, 'forgeflow', 'workspace-reviews');
await fs.mkdir(reviewDirectory, { recursive: true });
const manifestPath = path.join(reviewDirectory, `${reviewId}.json`);
const payload = {
schemaVersion: 1,
kind: 'workspace-sync-quarantine',
id: reviewId,
status: 'pending-codex-review',
createdAt: new Date().toISOString(),
repositoryRoot: root,
branch: plan.branch,
upstream: plan.upstream,
sourceSha: plan.currentSha,
targetSha: plan.targetSha,
recoveryBranch: backupBranch,
stashRef: stash?.ref || null,
stashSha: stash?.sha || null,
files: (plan.localFiles || []).map((file) => ({
path: file.path,
originalPath: file.originalPath || null,
status: file.status,
staged: Boolean(file.staged),
unstaged: Boolean(file.unstaged),
untracked: Boolean(file.untracked)
})),
instructions: [
'Review the recovery branch and quarantine stash with Codex before restoring anything.',
'ForgeFlow recovery branches are local-only and cannot be pushed to Gitea.',
'Restore only files that are still useful; obsolete files can be dropped after review.'
],
manifestPath
};
const temporaryPath = `${manifestPath}.${process.pid}.${crypto.randomUUID()}.tmp`;
await fs.writeFile(temporaryPath, `${JSON.stringify(payload, null, 2)}\n`, { mode: 0o600 });
await fs.rename(temporaryPath, manifestPath);
return payload;
}
isGitLockError(error) {
const message = String(error?.message || error || '');
return /(?:cannot lock ref|Unable to create .*\.lock|another git process)/i.test(message)
@@ -447,6 +489,7 @@ class GitService {
const stamp = new Date().toISOString().replace(/[-:]/g, '').replace(/\..+/, '').replace('T', '-');
let backupBranch = null;
let stash = null;
let review = null;
if (plan.summary.localCommitsToProtect > 0) {
const safeBranch = plan.branch.replace(/[^A-Za-z0-9._-]/g, '-');
backupBranch = `forgeflow/recovery-${safeBranch}-${stamp}-${plan.currentSha.slice(0, 7)}`;
@@ -454,10 +497,13 @@ class GitService {
await run('git', ['branch', backupBranch, 'HEAD'], { cwd: root, timeout: 30_000 });
}
if (plan.summary.localFilesToStash > 0) {
const label = `ForgeFlow workspace sync ${plan.branch} ${stamp}`;
const label = `FORGEFLOW-QUARANTINE:${plan.id} workspace sync ${plan.branch} ${stamp}`;
await run('git', ['stash', 'push', '--include-untracked', '-m', label], { cwd: root, timeout: 120_000 });
stash = (await this.stashList(root))[0] || null;
}
if (backupBranch || stash) {
review = await this.writeWorkspaceReviewManifest(root, plan, { backupBranch, stash });
}
const protectedStatus = await this.status(root);
if (!protectedStatus.clean || protectedStatus.head !== plan.currentSha) {
@@ -486,6 +532,7 @@ class GitService {
status,
backupBranch,
stash,
review,
cleaned: plan.localFiles.filter((file) => file.untracked).map((file) => file.path),
ignoredFilesPreserved: true
};
@@ -718,6 +765,12 @@ class GitService {
const status = await this.status(root);
const branch = status.branch.head;
if (!branch || branch === '(detached)') throw new Error('Cannot push from a detached HEAD.');
if (/^forgeflow\/recovery-/.test(branch)) {
const error = new Error('ForgeFlow recovery branches are local quarantine references and cannot be pushed to Gitea. Review them with Codex and move only approved work onto a normal branch.');
error.code = 'WORKSPACE_RECOVERY_BRANCH_LOCAL_ONLY';
error.recoverable = true;
throw error;
}
const args = status.branch.upstream ? ['push', '--porcelain'] : ['push', '--porcelain', '--set-upstream', 'origin', branch];
const result = await run('git', args, { cwd: root, timeout: 180_000, maxBuffer: 16 * 1024 * 1024 });
return { output: `${result.stdout}\n${result.stderr}`.trim(), status: await this.status(root) };
@@ -804,7 +857,16 @@ class GitService {
const result = await run('git', ['stash', 'list', `--format=${format}`], { cwd: root });
return result.stdout.split('\x1e').map((record) => record.trim()).filter(Boolean).map((record) => {
const [ref, sha, date, subject] = record.split('\x1f');
return { ref, sha, shortSha: sha.slice(0, 7), date, subject };
const quarantine = String(subject || '').match(/FORGEFLOW-QUARANTINE:([0-9a-f]{64})/i);
return {
ref,
sha,
shortSha: sha.slice(0, 7),
date,
subject,
quarantined: Boolean(quarantine),
reviewId: quarantine?.[1] || null
};
});
}
@@ -812,6 +874,13 @@ class GitService {
const root = await this.ensureRepository(repoPath);
const value = String(ref || 'stash@{0}');
if (!/^stash@\{\d+\}$/.test(value)) throw new Error('Invalid stash reference.');
const candidate = (await this.stashList(root)).find((item) => item.ref === value);
if (candidate?.quarantined) {
const error = new Error(`This stash is quarantined for Codex review (${candidate.reviewId}). ForgeFlow will not apply and drop it wholesale; restore only reviewed files manually.`);
error.code = 'WORKSPACE_QUARANTINE_REVIEW_REQUIRED';
error.recoverable = true;
throw error;
}
const result = await run('git', ['stash', 'pop', value], { cwd: root, timeout: 120_000 });
return { output: result.stdout.trim(), status: await this.status(root), stashes: await this.stashList(root) };
}
+3 -2
View File
@@ -161,12 +161,13 @@ Force repair after you have closed all Git tools for this repository?`)
]);
const recovery = [
result.backupBranch ? `recovery branch ${result.backupBranch}` : null,
result.stash ? `stash ${result.stash.ref}` : null,
result.stash ? `quarantine stash ${result.stash.ref}` : null,
result.review ? `Codex review manifest ${result.review.manifestPath}` : null,
].filter(Boolean).join(" and ");
showToast(
"Workspace synchronized with Gitea",
recovery
? `Local work is preserved in ${recovery}. Ignored runtime files were retained.`
? `Local work is quarantined in ${recovery}. Review it before restoring anything; ignored runtime files were retained.`
: `Tracked files now match ${result.plan.upstream}; ignored runtime files were retained.`,
"success",
);
+1 -1
View File
@@ -367,7 +367,7 @@ function renderGitTools(repository) {
? ui.branches.map((branch) => `<div class="tool-row"><div><strong>${escapeHtml(branch.name)}</strong><span>${escapeHtml(branch.shortSha)}${branch.upstream ? ` · ${escapeHtml(branch.upstream)}` : " · unpublished"}</span></div>${branch.current ? '<span class="status-pill success">Current</span>' : `<button class="button" data-action="checkout-branch" data-branch="${attr(branch.name)}">Switch</button>`}</div>`).join("")
: '<div class="empty-state compact"><p>Load branch information.</p></div>';
const stashRows = ui.stashes.length
? ui.stashes.map((stash) => `<div class="tool-row"><div><strong>${escapeHtml(stash.ref)}</strong><span>${escapeHtml(stash.subject)} · ${formatDate(stash.date)}</span></div><button class="button" data-action="pop-stash" data-stash-ref="${attr(stash.ref)}">Apply & drop</button></div>`).join("")
? ui.stashes.map((stash) => `<div class="tool-row"><div><strong>${escapeHtml(stash.ref)}</strong><span>${escapeHtml(stash.subject)} · ${formatDate(stash.date)}</span></div>${stash.quarantined ? `<span class="status-pill warning" title="Workspace review ${attr(stash.reviewId || "")}">Codex review required</span>` : `<button class="button" data-action="pop-stash" data-stash-ref="${attr(stash.ref)}">Apply & drop</button>`}</div>`).join("")
: '<div class="empty-state compact"><p>No stashes, or Git tools have not been loaded.</p></div>';
const recoveryBody = recovery
? `<div class="troubleshooting-summary"><span class="status-pill ${locks.length ? "warning" : "success"}">${locks.length ? `${locks.length} lock${locks.length === 1 ? "" : "s"}` : "No Git locks"}</span><span>${activeProcesses.length ? `${activeProcesses.length} active Git process(es)` : "No matching active Git process detected"}</span></div>${locks.length ? `<div class="tool-list">${locks.map((lock) => `<div class="tool-row"><div><strong>${escapeHtml(lock.name)}</strong><span>${Math.round(lock.ageMs / 1000)}s old · ${escapeHtml(lock.modifiedAt)}</span></div></div>`).join("")}</div>` : ""}${recommendations.length ? `<div class="tool-list recovery-actions">${recommendations.map((item) => `<div class="tool-row"><div><strong>${escapeHtml(item.label)}</strong><span>${item.safe ? "Safe automated action" : item.action ? "Creates a safety branch before changing history" : "Review required"}</span></div>${item.action ? `<button class="button ${item.safe ? "" : "danger"}" data-action="repair-repository-sync" data-strategy="${attr(item.action)}">Run</button>` : ""}</div>`).join("")}</div>` : ""}`