fix: adversarial round — the P0 finalize fail-safe and 12 hardened findings

Three adversarial passes (Claude fresh-context, Codex chaos, Codex structured
with P1 gate) on the full wave diff. Multi-source findings, all fixed:

- P0: finalize_queue is now explicit-delete-only — a record is unlinked ONLY
  when classification proves it staged or dropped; a classifier crash, a
  missing class file, or a malformed pulled .brain-privacy-map.json (which
  previously nuked the whole snapshotted queue, remotely triggerable) now
  retains everything, warns, and re-drains next run. load_privacy_map treats
  corrupt maps as retain-all, never as empty.
- next-version cannot silently drop a live claim: unreadable advertised refs
  get a targeted --depth=1 fetch + retry; still-unreadable claims surface as
  UNKNOWN warnings instead of duplicate-version silence.
- session-update lock: ownership-checked EXIT trap (a TTL-reclaimed holder
  can no longer delete the new holder's lock) + a 5-min background heartbeat
  so a legitimately-slow pull/setup is never reclaimed while alive.
- ensure-event collapses ALL same-(event,source) duplicates to one canonical
  entry; unique per-process tmp path; setup call sites surface (not swallow)
  the hardened refusals.
- memory-ingest: --limit counts only policy-permitted pages (denied records
  no longer starve permitted ones); --probe applies the same policy filter as
  --bulk (skipped_policy_* fields on the report).
- version-bump repair accepts a genuine literal 0.0.0.0 VERSION file.
- slug heal restricted to the stray-.git shape — package.json-anchored
  wrapper roots keep their legit sticky identity (#2212 preserved).
- brain-sync: idle fast path sees leftover .migrating records; unparseable
  spool records quarantine instead of warning forever; migration comment
  stops overclaiming the transition-window race.
- CDP throttling justifications document override persistence (callers own
  restoration), pinned in the allowlist test.

Deferred with record: deny retroactivity for already-ingested pages (P2 TODO,
same semantics as the code-import gate); legacy-migration tail race
(transition-window, requires pre-spool writers).

288 pass / 0 fail across the 10 touched suites.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Garry Tan
2026-08-17 14:13:50 -07:00
co-authored by Claude Fable 5
parent b7d44c45b4
commit fd0dbdeea2
20 changed files with 789 additions and 99 deletions
+99 -37
View File
@@ -140,8 +140,10 @@ spool_has_records() {
# os.replace, one file per line). Reads the file TWICE before unlinking: a
# pre-rename writer can still append through its already-open fd after our
# rename, and those appends land in the renamed file — the second pass
# catches them (the tail race the shared-file design could never close).
# Unparseable lines migrate as-is; finalize_queue keeps + warns on them.
# NARROWS the tail-race window (transition-only: it applies to pre-spool
# writers, and a writer that appends after the second read but before the
# unlink can still lose that line; spool-native writers are immune).
# Unparseable lines migrate as-is; finalize_queue quarantines + warns on them.
convert_legacy_file() {
local legacy="$1"
python3 - "$legacy" "$QUEUE_DIR" <<'PYEOF' 2>/dev/null || true
@@ -244,16 +246,29 @@ def load_lines(path):
return []
def load_privacy_map(path):
# Returns (entries, corrupt). Non-dict entries are filtered out
# defensively — the map may be PULLED from the artifacts remote, so a
# malformed entry like ["bad"] is remotely triggerable and used to raise
# mid-classification (after the snapshot manifest was written), which the
# old finalize turned into a full queue wipe. Any malformed shape also
# marks the map CORRUPT: privacy classification cannot be trusted, so the
# caller holds every queued record instead of guessing (a corrupt privacy
# map silently treated as empty would over-share behavioral data).
try:
with open(path) as f:
data = json.load(f)
# Expected: [{"pattern": "glob", "class": "artifact" | "behavioral"}]
return data if isinstance(data, list) else []
except (FileNotFoundError, json.JSONDecodeError):
return []
except FileNotFoundError:
return [], False
except json.JSONDecodeError:
return [], True
if not isinstance(data, list):
return [], True
# Expected: [{"pattern": "glob", "class": "artifact" | "behavioral"}]
entries = [e for e in data if isinstance(e, dict)]
return entries, len(entries) != len(data)
allowlist_globs = load_lines(allowlist_path)
privacy_map = load_privacy_map(privacy_path)
privacy_map, privacy_corrupt = load_privacy_map(privacy_path)
# Normalize skip entries to the POSIX form queued paths use, so a backslash
# entry in .brain-skip.txt still matches on Windows. The drain is the safety
# boundary that actually stages files, so it must normalize identically to
@@ -318,6 +333,14 @@ def mode_allows(cls, mode):
final = []
classified = {"retained": [], "dropped": {"skipped": [], "invalid": [], "unmatched": [], "missing": []}}
if privacy_corrupt:
# Fail-safe: with an untrustworthy privacy map, stage NOTHING and drop
# NOTHING — retain every queued record until the map is fixed. The next
# drain re-classifies from scratch.
print("BRAIN_SYNC: warning: privacy map at " + privacy_path +
" is malformed — holding all queued records until it is fixed", file=sys.stderr)
classified["retained"] = sorted(queue_paths)
queue_paths = set()
for p in sorted(queue_paths):
if p in skip_lines:
classified["dropped"]["skipped"].append(p)
@@ -353,25 +376,34 @@ PYEOF
}
# Finalize the drain: delete exactly the spool record files this drain
# consumed (per the snapshot manifest), keeping retained (privacy/mode-held)
# and unparseable records queued. The predecessor (a shared-file queue
# rewrite) had a lockless-append race between its live re-read and the
# os.replace; with one file per record that race class is structurally gone —
# a concurrent enqueue is a separate file the snapshot never listed, so
# finalize cannot touch it. Crash semantics are at-least-once: a drain that
# dies before finalize leaves its spool files in place and the next run
# re-drains them; downstream content-hash dedup absorbs the duplicates.
# Dropped-path detail goes to a 0600 sidecar so the status line can stay
# content-free (counts only).
# consumed (per the snapshot manifest) AND positively classified. Deletion is
# EXPLICIT-DELETE-ONLY: a record is unlinked only when its path appears in
# (staged paths classified dropped). The old polarity ("delete unless
# retained") turned a missing/unparseable classification into retained=∅ and
# wiped every snapshotted record — remotely triggerable via a malformed
# pulled privacy map that raised AFTER the manifest write. Now a
# missing/unparseable class_file or paths_file deletes NOTHING (warn +
# return), and a path the classification never mentions stays queued.
# The predecessor (a shared-file queue rewrite) had a lockless-append race
# between its live re-read and the os.replace; with one file per record that
# race class is structurally gone — a concurrent enqueue is a separate file
# the snapshot never listed, so finalize cannot touch it. Crash semantics are
# at-least-once: a drain that dies before finalize leaves its spool files in
# place and the next run re-drains them; downstream content-hash dedup
# absorbs the duplicates. Unparseable records move to $QUEUE_DIR/quarantine/
# (never deleted) so they stop re-warning at every boundary. Dropped-path
# detail goes to a 0600 sidecar so the status line can stay content-free
# (counts only).
finalize_queue() {
local snapshot_file="$1" # spool filenames this drain consumed, one per line
local class_file="$2" # classification JSON from compute_paths_to_stage
local paths_file="$3" # staged paths (compute_paths_to_stage stdout), one per line
# Fail-open by design (a failed finalize self-corrects next run: re-stage →
# nothing-to-commit), but say so — a silent failure here would let the
# subsequent "ok/idle" status claim a drain that did not happen.
python3 - "$QUEUE_DIR" "$snapshot_file" "$class_file" "$GSTACK_HOME/.brain-sync-drops.json" <<'PYEOF' || echo "BRAIN_SYNC: warning: queue finalize failed — entries retained; next run re-drains" >&2
python3 - "$QUEUE_DIR" "$snapshot_file" "$class_file" "$paths_file" "$GSTACK_HOME/.brain-sync-drops.json" <<'PYEOF' || echo "BRAIN_SYNC: warning: queue finalize failed — entries retained; next run re-drains" >&2
import json, os, sys, time
spool_dir, snapshot_file, class_file, drops_file = sys.argv[1:5]
spool_dir, snapshot_file, class_file, paths_file, drops_file = sys.argv[1:6]
def lines(path):
try:
@@ -380,15 +412,26 @@ def lines(path):
except FileNotFoundError:
return []
# Explicit-delete-only inputs. Either input unreadable → delete NOTHING.
try:
with open(class_file) as f:
classified = json.load(f)
if not isinstance(classified, dict):
raise ValueError("classification is not an object")
except Exception:
classified = {"retained": [], "dropped": {}}
retained = set(classified.get("retained", []))
print("BRAIN_SYNC: warning: classification unreadable — no queue records deleted; next run re-drains", file=sys.stderr)
sys.exit(0)
try:
with open(paths_file) as f:
staged = {l.strip() for l in f if l.strip()}
except Exception:
print("BRAIN_SYNC: warning: staged-paths file unreadable — no queue records deleted; next run re-drains", file=sys.stderr)
sys.exit(0)
dropped = set()
for group in (classified.get("dropped", {}) or {}).values():
dropped.update(group)
deletable = staged | dropped
unparseable = 0
for name in lines(snapshot_file):
@@ -404,16 +447,24 @@ for name in lines(snapshot_file):
except Exception:
pass
if not isinstance(p, str):
unparseable += 1 # keep — never destroy what we can't read
# Never destroy what we can't read — but don't leave it re-warning at
# every boundary either: move it aside for inspection.
unparseable += 1
try:
qdir = os.path.join(spool_dir, "quarantine")
os.makedirs(qdir, exist_ok=True)
os.replace(full, os.path.join(qdir, name))
except OSError:
pass # quarantine move failed — leave in place; next run retries
continue
if p in retained:
continue # stays queued: syncs under a higher mode
if p not in deletable:
continue # retained / unclassified: stays queued (explicit-delete-only)
try:
os.unlink(full) # staged or dropped: fully processed
except FileNotFoundError:
pass
if unparseable:
print(f"BRAIN_SYNC: {unparseable} unparseable spool record(s) held (inspect {spool_dir})", file=sys.stderr)
print(f"BRAIN_SYNC: {unparseable} unparseable spool record(s) moved to quarantine (inspect {os.path.join(spool_dir, 'quarantine')})", file=sys.stderr)
if dropped:
fd = os.open(drops_file, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
@@ -573,11 +624,13 @@ subcmd_once() {
# nothing to classify, retain, or drop, and a record created after this
# check simply waits for the next boundary. The legacy file is checked too:
# an OLD writer may have recreated it after the migration above (it gets
# migrated next run, but the depth is honest now). (The detector above
# already ran: its whole point is re-pushing stranded commits when the
# queue is empty.) The lock-release trap installed at acquisition covers
# this exit.
if ! spool_has_records && [ ! -s "$QUEUE" ]; then
# migrated next run, but the depth is honest now) — and so is a leftover
# .migrating file: if its conversion failed above (e.g. python3 missing),
# records are still pending, so "idle" would be dishonest. (The detector
# above already ran: its whole point is re-pushing stranded commits when
# the queue is empty.) The lock-release trap installed at acquisition
# covers this exit.
if ! spool_has_records && [ ! -s "$QUEUE" ] && [ ! -s "$QUEUE.migrating" ]; then
write_status "idle" "queue empty"
exit 0
fi
@@ -589,11 +642,20 @@ subcmd_once() {
# Single trap covers all: lock cleanup AND tempfile cleanup.
trap 'rm -f "$paths_file" "$class_file" "$snapshot_file" 2>/dev/null; rm -rf "$lock_dir" 2>/dev/null || true' EXIT INT TERM
compute_paths_to_stage "$mode" "$class_file" "$snapshot_file" > "$paths_file"
# Fail-safe (G1): a classifier that dies mid-run (ENOSPC/OOM/SIGKILL, or a
# shape the defensive filters don't cover) may have already written the
# snapshot manifest but no classification. Finalizing on that state is what
# used to wipe the queue — so on a nonzero exit, warn loudly, do NOT call
# finalize_queue, and leave everything queued for the next drain.
if ! compute_paths_to_stage "$mode" "$class_file" "$snapshot_file" > "$paths_file"; then
echo "BRAIN_SYNC: warning: queue classification failed — no records consumed; next run re-drains" >&2
write_status "error" "classification failed; queue preserved (next run retries)"
exit 0
fi
if [ ! -s "$paths_file" ]; then
# Nothing stageable. Finalize the snapshot (retained entries survive;
# classified drops removed; records created after the snapshot untouched).
finalize_queue "$snapshot_file" "$class_file"
finalize_queue "$snapshot_file" "$class_file" "$paths_file"
local summary
summary=$(queue_summary "$class_file")
write_status "idle" "no stageable changes${summary:+ ($summary)}"
@@ -645,7 +707,7 @@ subcmd_once() {
commit -q -m "$msg" 2>/dev/null || {
# Nothing to commit (e.g. all files already committed). The drained
# records leave the spool; retained + post-snapshot records survive.
finalize_queue "$snapshot_file" "$class_file"
finalize_queue "$snapshot_file" "$class_file" "$paths_file"
write_status "idle" "queue drained but no new changes to commit"
exit 0
}
@@ -662,7 +724,7 @@ subcmd_once() {
# Drained records leave the spool — they live in the local commit, which
# the run-start detector re-pushes next time (#2549). Retained +
# post-snapshot records survive the finalize.
finalize_queue "$snapshot_file" "$class_file"
finalize_queue "$snapshot_file" "$class_file" "$paths_file"
exit 0
fi
@@ -676,7 +738,7 @@ subcmd_once() {
if git -C "$GSTACK_HOME" merge --no-edit "origin/$branch" >/dev/null 2>&1; then
if GSTACK_HOME="$GSTACK_HOME" _receipted_git closed brain-sync "$push_host" curated-memory-git-push "artifacts_sync_mode!=off" \
bash -c 'git -C "$1" push origin HEAD 2>/dev/null' _ "$GSTACK_HOME"; then
finalize_queue "$snapshot_file" "$class_file"
finalize_queue "$snapshot_file" "$class_file" "$paths_file"
date -u +%Y-%m-%dT%H:%M:%SZ > "$LAST_PUSH_FILE"
write_status "ok" "pushed $n file(s) after rebase"
exit 0
@@ -685,12 +747,12 @@ subcmd_once() {
fi
# Commit exists locally; the run-start detector re-pushes it next time.
write_status "push_failed" "push failed: $(printf '%s' "$push_err" | head -1); commit retained locally, will retry next run"
finalize_queue "$snapshot_file" "$class_file"
finalize_queue "$snapshot_file" "$class_file" "$paths_file"
exit 0
}
# Success: drained records leave the spool (retained + post-snapshot survive).
finalize_queue "$snapshot_file" "$class_file"
finalize_queue "$snapshot_file" "$class_file" "$paths_file"
date -u +%Y-%m-%dT%H:%M:%SZ > "$LAST_PUSH_FILE"
write_status "ok" "pushed $n file(s)"
exit 0
+86 -18
View File
@@ -143,6 +143,13 @@ interface ProbeReport {
updated_count: number;
unchanged_count: number;
skipped_unattributed: number;
/**
* #2392 parity: transcripts whose remote's trust tier is `deny` /
* `read-only`. Probe applies the SAME per-remote policy filter --bulk
* applies, so its ingestible counts match what --bulk would write.
*/
skipped_policy_deny: number;
skipped_policy_readonly: number;
estimate_minutes: number;
}
@@ -1079,9 +1086,10 @@ export function readNewFailures(
/**
* The ONE attribution gate (#2394): a transcript is attributable iff its cwd
* resolves to a git remote. Both probeMode (via transcriptIsAttributable) and
* preparePages route through THIS function, so the two stages' post-attribution
* counts are structurally identical — the parity the probe report promises.
* resolves to a git remote. Both probeMode (via transcriptCwdFromPrefix +
* resolveGitRemote — the same memoized resolver) and preparePages route
* through THIS logic, so the two stages' post-attribution counts are
* structurally identical — the parity the probe report promises.
*/
function sessionIsAttributable(cwd: string | undefined | null): boolean {
if (!cwd) return false;
@@ -1096,12 +1104,12 @@ function sessionIsAttributable(cwd: string | undefined | null): boolean {
const TRANSCRIPT_PROBE_MAX_BYTES = 256 * 1024;
/**
* Lightweight attribution check: does a transcript have a resolvable git
* remote for its cwd? Reads a BOUNDED prefix (first 256KB, never the whole
* file — plan C7: the probe must stay a cheap parse on multi-MB transcripts),
* extracts the cwd with EXACTLY parseTranscriptJsonl's rules, and calls
* resolveGitRemote. Avoids the full parse (body rendering, message counting)
* because probe only needs the yes/no answer.
* Lightweight cwd extraction for the probe: reads a BOUNDED prefix (first
* 256KB, never the whole file — plan C7: the probe must stay a cheap parse on
* multi-MB transcripts) and extracts the cwd with EXACTLY
* parseTranscriptJsonl's rules. The caller resolves attribution/policy via
* resolveGitRemote (memoized). Avoids the full parse (body rendering, message
* counting) because probe only needs the cwd.
*
* Extraction MIRRORS parseTranscriptJsonl (the single source of truth for
* cwd semantics — keep the two in lockstep):
@@ -1117,7 +1125,7 @@ const TRANSCRIPT_PROBE_MAX_BYTES = 256 * 1024;
* Non-transcript types (artifacts) always pass — the attribution filter in
* preparePages only applies to transcripts (#2394).
*/
function transcriptIsAttributable(path: string): boolean {
function transcriptCwdFromPrefix(path: string): string {
let raw: string;
try {
const fd = openSync(path, "r");
@@ -1129,10 +1137,10 @@ function transcriptIsAttributable(path: string): boolean {
closeSync(fd);
}
} catch {
return false;
return "";
}
const lines = raw.split("\n").filter((l) => l.trim().length > 0);
if (lines.length === 0) return false;
if (lines.length === 0) return "";
let cwd = "";
let sawFirstParseable = false;
@@ -1159,8 +1167,7 @@ function transcriptIsAttributable(path: string): boolean {
break;
}
}
if (!cwd) return false;
return sessionIsAttributable(cwd);
return cwd;
}
async function probeMode(args: CliArgs): Promise<ProbeReport> {
@@ -1184,17 +1191,55 @@ async function probeMode(args: CliArgs): Promise<ProbeReport> {
let updatedCount = 0;
let unchangedCount = 0;
let skippedUnattributed = 0;
let skippedPolicyDeny = 0;
let skippedPolicyReadonly = 0;
// Two-phase walk (#2392 parity): collect candidates first (remembering each
// transcript's resolved remote), THEN apply the same per-remote policy
// filter --bulk applies via one repoPolicyTierBatch spawn. Counting during
// the walk would report policy-denied transcripts as ingestible — probe's
// numbers must match what --bulk would actually write.
const candidates: Array<{ path: string; type: MemoryType; remote: string }> = [];
for (const { path, type } of walkAllSources(ctx)) {
// Apply the same attribution filter preparePages uses (#2394):
// skip transcripts with no resolvable git remote unless --include-unattributed.
if (type === "transcript" && !args.includeUnattributed) {
if (!transcriptIsAttributable(path)) {
let remote = "";
if (type === "transcript") {
const cwd = transcriptCwdFromPrefix(path);
remote = cwd ? resolveGitRemote(cwd) : "";
if (!args.includeUnattributed && remote === "") {
skippedUnattributed++;
continue;
}
}
candidates.push({ path, type, remote });
}
// Batch policy check — same hasRepoPolicyStore fast path as preparePages:
// no store on disk → zero policy work. Only transcripts with a resolved
// remote are policy-filtered; artifacts never are (#2392). A missing or
// errored verdict counts as "none" here — probe is read-only and must not
// hard-fail the way the write path does.
if (hasRepoPolicyStore()) {
const remotes = [...new Set(candidates.filter((c) => c.type === "transcript" && c.remote).map((c) => c.remote))];
if (remotes.length > 0) {
const verdicts = repoPolicyTierBatch(remotes);
for (let i = candidates.length - 1; i >= 0; i--) {
const c = candidates[i];
if (c.type !== "transcript" || !c.remote) continue;
const tier = verdicts.get(c.remote)?.tier ?? "none";
if (tier === "deny") {
skippedPolicyDeny++;
candidates.splice(i, 1);
} else if (tier === "read-only") {
skippedPolicyReadonly++;
candidates.splice(i, 1);
}
}
}
}
for (const { path, type } of candidates) {
totalFiles++;
let size = 0;
try {
@@ -1224,6 +1269,8 @@ async function probeMode(args: CliArgs): Promise<ProbeReport> {
updated_count: updatedCount,
unchanged_count: unchangedCount,
skipped_unattributed: skippedUnattributed,
skipped_policy_deny: skippedPolicyDeny,
skipped_policy_readonly: skippedPolicyReadonly,
estimate_minutes: estimateMinutes,
};
}
@@ -1277,8 +1324,16 @@ function preparePages(
let parseFailed = 0;
let partialPages = 0;
// --limit semantics: "stop after N pages WRITTEN" = N policy-eligible pages.
// When a per-remote policy store exists, eligibility is only known after the
// batch policy check below, so the walk must not stop early — a denied-first
// corpus would otherwise consume the limit and starve permitted pages. With
// no store on disk, every prepared page is eligible and the in-loop break
// keeps --limit cheap.
const policyStoreExists = hasRepoPolicyStore();
for (const { path, type } of walkAllSources(ctx)) {
if (args.limit !== null && prepared.length >= args.limit) break;
if (args.limit !== null && !policyStoreExists && prepared.length >= args.limit) break;
if (args.mode === "incremental" && !fileChangedSinceState(path, state)) {
skippedDedup++;
@@ -1354,7 +1409,7 @@ function preparePages(
let skippedPolicyReadonly = 0;
let skippedPolicyDeny = 0;
let policyError: string | undefined;
if (hasRepoPolicyStore()) {
if (policyStoreExists) {
const remotes = [
...new Set(
prepared
@@ -1399,6 +1454,13 @@ function preparePages(
}
}
// --limit applies AFTER policy filtering, over permitted pages only. In the
// no-store fast path the walk already stopped at the limit, so this slice
// is a no-op there.
if (args.limit !== null && finalPrepared.length > args.limit) {
finalPrepared = finalPrepared.slice(0, args.limit);
}
return {
prepared: finalPrepared,
skippedSecret,
@@ -2282,6 +2344,12 @@ function printProbeReport(r: ProbeReport, json: boolean): void {
if (r.skipped_unattributed > 0) {
console.log(`Skipped (unattributed): ${r.skipped_unattributed} (no git remote; use --include-unattributed to include)`);
}
if (r.skipped_policy_deny > 0) {
console.log(`Skipped (policy deny): ${r.skipped_policy_deny} (remote tier is deny; change with: gstack-gbrain-repo-policy set <remote> read-write)`);
}
if (r.skipped_policy_readonly > 0) {
console.log(`Skipped (policy read-only): ${r.skipped_policy_readonly} (remote tier is read-only; transcript ingest writes pages)`);
}
console.log("By type:");
for (const [t, v] of Object.entries(r.by_type)) {
if (v.count > 0) {
+39
View File
@@ -552,6 +552,45 @@ function fetchGitClaimed(
// read from the local remote-tracking ref.
show = runCommand("git", ["show", `refs/remotes/origin/${branch}:${versionPath}`]);
}
if (!show.ok && sha) {
// ls-remote advertises SHAs without objects: a branch pushed after our
// last fetch has NO local object, so both reads above fail. The old
// `continue` here silently dropped a LIVE claim — the exact duplicate-
// allocation this fallback exists to prevent. Distinguish "object
// missing" from "branch has no VERSION file" before deciding.
const haveObject = runCommand("git", ["cat-file", "-e", sha]);
if (haveObject.ok) {
// Object is local and the path read still failed → the branch simply
// carries no version file. Genuinely not a claim; skip quietly.
continue;
}
// Fetch just this ref shallowly (no prompts, no tags, bounded) and
// retry reading VERSION from the now-local object (or FETCH_HEAD).
const fetch = spawnSync(
"git",
["fetch", "origin", `refs/heads/${branch}`, "--depth=1", "--no-tags"],
{ encoding: "utf8", timeout: 10000, env: { ...process.env, GIT_TERMINAL_PROMPT: "0" } },
);
if (fetch.status === 0 && !fetch.error) {
show = runCommand("git", ["show", `${sha}:${versionPath}`]);
if (!show.ok) show = runCommand("git", ["show", `FETCH_HEAD:${versionPath}`]);
if (!show.ok && runCommand("git", ["cat-file", "-e", sha]).ok) {
// Fetched and the object exists but the path doesn't → no VERSION
// file on this branch. Not a claim.
continue;
}
}
if (!show.ok) {
// STILL unreadable — never skip silently. Surface it as an UNKNOWN
// claim so the caller knows the allocation may be unsafe.
warnings.push(
`origin/${branch}: VERSION unreadable even after a targeted fetch — ` +
`counted as an UNKNOWN claim; allocation may collide with this branch. ` +
`Run \`git fetch origin ${branch}\` and re-run to verify.`,
);
continue;
}
}
if (!show.ok) continue;
const raw = extractVersion(show.stdout, versionPath);
if (!raw || !parseVersion(raw)) continue;
+19 -4
View File
@@ -106,11 +106,26 @@ fi
# Write the HOLDER's PID for stale lock detection (see #2613 note above;
# macOS ships bash 3.2 with no BASHPID — the sh child's $PPID IS this
# subshell, so the fallback is exact there).
echo "${BASHPID:-$(sh -c 'echo $PPID')}" > "$LOCK_DIR/pid" 2>/dev/null
# subshell, so the fallback is exact there). MYPID is captured once at
# write time so the trap below can prove ownership before removing.
MYPID="${BASHPID:-$(sh -c 'echo $PPID')}"
echo "$MYPID" > "$LOCK_DIR/pid" 2>/dev/null
# Clean up lock on exit
trap 'rm -rf "$LOCK_DIR" 2>/dev/null' EXIT
# In-flight heartbeat: the step-boundary touches below only fire AFTER the
# pull / setup return, so a legitimately-slow step (cold clone, huge setup)
# older than the TTL got reclaimed while ALIVE. This background loop
# freshens the pidfile mtime every 5 minutes for as long as we still own
# the lock (ownership re-checked each beat: if another updater reclaimed
# and wrote its own pid, the loop exits instead of touching THEIR file).
( while :; do sleep 300; [ "$(cat "$LOCK_DIR/pid" 2>/dev/null)" = "$MYPID" ] || exit 0; touch "$LOCK_DIR/pid" 2>/dev/null; done ) &
HB_PID=$!
# Clean up lock on exit — ownership-checked: after a TTL reclaim by another
# updater, $LOCK_DIR belongs to the NEW holder, and an unconditional rm -rf
# here would delete the live holder's lock (cascading reclaims). Remove the
# lock ONLY while $LOCK_DIR/pid still contains MYPID; always stop the
# heartbeat.
trap 'kill "$HB_PID" 2>/dev/null; [ "$(cat "$LOCK_DIR/pid" 2>/dev/null)" = "$MYPID" ] && rm -rf "$LOCK_DIR" 2>/dev/null' EXIT
# ── Pull latest ──
OLD_HEAD=$(git -C "$GSTACK_DIR" rev-parse HEAD 2>/dev/null)
+23 -5
View File
@@ -104,7 +104,7 @@ case "$ACTION" in
hooks: [{ type: "command", command: hookCmd }]
});
}
const tmp = settingsPath + ".tmp";
const tmp = settingsPath + ".tmp." + process.pid; // per-process: parallel writers must not share a tmp
fs.writeFileSync(tmp, JSON.stringify(settings, null, 2) + "\n");
fs.renameSync(tmp, settingsPath);
'
@@ -130,7 +130,7 @@ case "$ACTION" in
if (settings.hooks.SessionStart.length === 0) delete settings.hooks.SessionStart;
if (Object.keys(settings.hooks).length === 0) delete settings.hooks;
}
const tmp = settingsPath + ".tmp";
const tmp = settingsPath + ".tmp." + process.pid; // per-process: parallel writers must not share a tmp
fs.writeFileSync(tmp, JSON.stringify(settings, null, 2) + "\n");
fs.renameSync(tmp, settingsPath);
' 2>/dev/null
@@ -218,7 +218,19 @@ case "$ACTION" in
return sameMatcher && sameCommand;
};
let existing = settings.hooks[event].find(matchesEntry);
// Collect ALL matches, not just the first: pre-existing installs can
// carry two entries with the same (event, _gstack_source) from the old
// matcher-keyed dedup. `.find()` updated only the first and left the
// stale twin running forever. Keep ONE canonical entry (the first),
// remove the rest in the same atomic write.
const matched = settings.hooks[event].filter(matchesEntry);
let existing = matched.length > 0 ? matched[0] : undefined;
let collapsed = 0;
if (matched.length > 1) {
const extras = new Set(matched.slice(1));
settings.hooks[event] = settings.hooks[event].filter((e) => !extras.has(e));
collapsed = matched.length - 1;
}
const hookEntry = { type: "command", command: cmd };
if (timeoutRaw) {
const n = Number(timeoutRaw);
@@ -270,7 +282,10 @@ case "$ACTION" in
// Atomic tmp+rename: the settings file is either the old JSON (with
// the old single registration) or the new JSON (with the replaced
// one) — a failed update can never leave zero or two registrations.
const tmp = settingsPath + ".tmp";
// Per-process tmp suffix: a fixed settings.json.tmp let two parallel
// writers consume one another. (No apostrophes here: this JS lives
// inside a bash single-quoted string.)
const tmp = settingsPath + ".tmp." + process.pid;
fs.writeFileSync(tmp, after + "\n");
fs.renameSync(tmp, settingsPath);
} catch (e) {
@@ -280,6 +295,9 @@ case "$ACTION" in
console.error("error: could not update " + settingsPath + ": " + (e && e.message ? e.message : e));
process.exit(1);
}
if (collapsed > 0) {
console.error("collapsed " + collapsed + " duplicate (event, source) hook entr" + (collapsed === 1 ? "y" : "ies") + " for " + event + " (source: " + source + ")");
}
if (ensure && existing) {
console.log("OK: " + event + " hook re-pointed (source: " + source + ")");
} else {
@@ -318,7 +336,7 @@ case "$ACTION" in
if (settings.hooks[event].length === 0) delete settings.hooks[event];
}
if (Object.keys(settings.hooks).length === 0) delete settings.hooks;
const tmp = settingsPath + ".tmp";
const tmp = settingsPath + ".tmp." + process.pid; // per-process: parallel writers must not share a tmp
fs.writeFileSync(tmp, JSON.stringify(settings, null, 2) + "\n");
fs.renameSync(tmp, settingsPath);
console.log("OK: removed " + removed + " hook entry/entries tagged source=" + source);
+13 -8
View File
@@ -188,12 +188,16 @@ _resolve_remote() {
# - Old-bug shape (#1125): the pre-walk-up resolver cached basename(pwd)
# for a SUBDIRECTORY of the real project — cached == pwd basename while
# the walk-up says pwd is NOT the project root.
# - Degraded-ancestor shape (2026-08-17): the pre-remote-first resolver
# cached basename(PROJECT_ROOT) for a marker-only ancestor (stray
# ~/.git) that is NOT the remote-bearing repo — cached == the marker
# root's basename while a remote-bearing repo BELOW it exists. Legit
# #2212 stickiness is safe: there the repo that adopted the remote IS
# the marker root (REMOTE_ROOT == PROJECT_ROOT), so the heal never fires.
# - Degraded-ancestor shape (2026-08-17), STRAY-REPO shape ONLY: the
# pre-remote-first resolver cached basename(PROJECT_ROOT) for an
# ancestor anchored by a .git entry whose origin does NOT resolve (the
# stray empty ~/.git live bug) while a remote-bearing repo BELOW it
# exists. A marker root anchored by package.json / pyproject etc. with
# NO .git is legit #2212 sticky identity (a monorepo wrapper that used
# gstack before its inner dir grew a remote) and must NOT be healed.
# Legit remote-adopting stickiness is safe too: there the repo that
# adopted the remote IS the marker root (REMOTE_ROOT == PROJECT_ROOT),
# so the heal never fires.
if [[ -z "$SLUG" && -f "$CACHE_FILE" ]]; then
_CACHED=$(cat "$CACHE_FILE" 2>/dev/null | tr -cd 'a-zA-Z0-9._-')
if [[ -n "$_CACHED" ]]; then
@@ -204,9 +208,10 @@ if [[ -z "$SLUG" && -f "$CACHE_FILE" ]]; then
fi
if [[ "$_CACHED" == "$_PWD_BASE" && -n "$PROJECT_ROOT" && "$PROJECT_ROOT" != "$PROJECT_DIR" ]]; then
: # old-bug shape — recompute below and self-heal the cache
elif [[ -n "$PROJECT_ROOT" && "$_CACHED" == "$_ROOT_BASE" ]] \
elif [[ -n "$PROJECT_ROOT" && "$_CACHED" == "$_ROOT_BASE" && -e "$PROJECT_ROOT/.git" ]] \
&& ! git -C "$PROJECT_ROOT" remote get-url origin >/dev/null 2>&1 \
&& { _resolve_remote; [[ -n "$REMOTE_URL" && "$REMOTE_ROOT" != "$PROJECT_ROOT" ]]; }; then
: # degraded-ancestor shape — recompute below and self-heal the cache
: # degraded-ancestor (stray-repo) shape — recompute below and self-heal the cache
else
SLUG="$_CACHED"
fi
+18 -6
View File
@@ -463,13 +463,25 @@ function cmdRepair(args: string[], cwd: string): void {
const current = readVersionFile(versionPath, versionRel);
// Guard against readVersionFile folding "file exists but is empty / unparsable"
// into DEFAULT ("0.0.0.0") — same data-corruption pathway as file-missing (#2600).
// A fabricated version must never propagate into package.json.
// A fabricated version must never propagate into package.json. But DEFAULT is
// ambiguous: a VERSION file that GENUINELY reads "0.0.0.0" (a brand-new repo)
// is a legitimate version, not the sentinel. Disambiguate on the raw bytes:
// if the trimmed file content itself matches the version shape, proceed with
// the repair; reject only when the raw content is empty or unparseable.
if (current === DEFAULT) {
fail(
`VERSION file at ${versionRel} is empty or contains no parsable version. ` +
"Cannot repair package.json with a fabricated version.",
2,
);
let rawTrimmed = "";
try {
rawTrimmed = readFileSync(versionPath, "utf-8").trim();
} catch {
rawTrimmed = "";
}
if (!VERSION_RE.test(rawTrimmed)) {
fail(
`VERSION file at ${versionRel} is empty or contains no parsable version. ` +
"Cannot repair package.json with a fabricated version.",
2,
);
}
}
if (!VERSION_RE.test(current)) {
fail(