Skip to content

Commit 53c1d1a

Browse files
donjor-agent[bot]rsi-pr-agent
authored andcommitted
fix(fork-sync): hook guard, hook re-apply, and fold check each drop a manual repair (#1782)
* fix(fork-sync): hook guard, hook re-apply, and fold check each drop a manual repair The guard reads markers from the committed file, re-apply shifts a hook with its re-indented anchor, and a stopped fold names the commit to retarget to. Fork-Domain: fork-meta Fork-Tier: bugfix Fork-Upstreamable: no * fix(fork-sync): type the hook guard input once; trust committed spans, template literals, and unterminated lines Fork-Domain: fork-meta Fork-Tier: bugfix Fork-Upstreamable: no * fix(fork-sync): any backtick or line continuation keeps a multi-line hook verbatim Squashes: - 73d431d fix(fork-sync): hook guard, hook re-apply, and fold check each drop a manual repair (#1782) (#1782) - 2750cd1 fixup! fix(fork-sync): hook guard, hook re-apply, and fold check each drop a manual repair (#1782) (#1782) Fork-Domain: fork-meta Fork-Tier: bugfix Fork-Upstreamable: no
1 parent 179b030 commit 53c1d1a

9 files changed

Lines changed: 280 additions & 73 deletions

‎docs/fork/operations/fork-sync.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ Conflict resolution is machine-owned, in this order.
9494
| 5 | Anything left is a `manual` row and stops the run |
9595

9696
Only upstream moved: upstream's text stands.
97-
A marked fork hook goes back in verbatim.
97+
A marked fork hook goes back in verbatim, shifted only when upstream re-indented its anchor.
9898
There is no "upstream superseded this" rule: retirement is a traced verdict written in [fork-delta](../internals/fork-delta.md), never a merge rule.
9999

100100
## Block lifecycle

‎scripts/fork-fixup-fold.test.ts‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -157,17 +157,18 @@ it("refuses a fixup that only folds at the tip, naming fixup and owner", () => {
157157
try {
158158
git(root, ["init", "--quiet", "--initial-branch", "main"]);
159159
identity(root);
160-
commit(root, "upstream base", { "file.txt": "a\ntail\n" });
160+
commit(root, "upstream base", { "file.txt": "a\ntail" });
161161
git(root, ["update-ref", "refs/remotes/upstream/main", "main"]);
162162
const base = git(root, ["rev-parse", "main"]);
163-
commit(root, "owner edit", { "file.txt": "b\ntail\n" });
164-
commit(root, "later edit", { "file.txt": "c\ntail\n" });
165-
// The fixup edit builds on the later commit's content, so it applies at
166-
// the tip and nowhere near its owner: the proof must stop there.
167-
commit(root, "fixup! owner edit", { "file.txt": "c!\ntail\n" });
163+
commit(root, "owner edit", { "file.txt": "b\ntail" });
164+
commit(root, "later edit", { "file.txt": "b\nTAIL" });
165+
// The fixup's context is the later commit's unterminated final line, so it
166+
// applies at the tip and nowhere near its owner: the proof must stop there.
167+
commit(root, "fixup! owner edit", { "file.txt": "b!\nTAIL" });
168168
const [failure] = fixupFoldFailures(root, base, "HEAD");
169169
assert.ok(failure?.includes('fixup "fixup! owner edit"'), failure);
170170
assert.ok(failure?.includes('owner "owner edit"'), failure);
171+
assert.ok(failure?.includes('name "later edit"'), failure);
171172
// The live checkout is untouched: the tip stands and the replay worktree is gone.
172173
assert.strictEqual(git(root, ["rev-parse", "HEAD"]), git(root, ["rev-parse", "main"]));
173174
assert.strictEqual(worktreeCount(root), 1);

‎scripts/fork-fixup-fold.ts‎

Lines changed: 62 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,57 @@ const hydrateStack = (git: SystemGit, base: string, head: string): void => {
9797
throw new Error(`could not fetch the stack's blobs from ${promisor}: ${fetch.stderr.trim()}`);
9898
};
9999

100+
/** Git's default diff context: a fold applies only while these lines around each edit match. */
101+
const FOLD_CONTEXT = 3;
102+
103+
/**
104+
* The newest stack commit that shaped the lines a fixup edits or the context
105+
* around them, when that is not the fixup's owner. Those lines did not exist
106+
* yet at the owner, which is why the fold stopped; naming that commit instead
107+
* folds. Blame stops at `base`, so upstream history is never walked.
108+
*/
109+
const retargetFor = (
110+
git: SystemGit,
111+
base: string,
112+
fixup: string,
113+
owner: string,
114+
stack: ReadonlyArray<SubjectCommit>,
115+
): string | undefined => {
116+
const order = new Map(stack.map((commit, index) => [commit.sha, index]));
117+
let newest = order.get(owner) ?? -1;
118+
let path = "";
119+
for (const line of git
120+
.run(["-c", "core.quotePath=false", "diff", "--unified=0", `${fixup}^`, fixup])
121+
.split("\n")) {
122+
if (line.startsWith("--- ")) path = line.startsWith("--- a/") ? line.slice(6) : "";
123+
const hunk = /^@@ -(\d+)(?:,(\d+))? /.exec(line);
124+
if (hunk === null || path === "") continue;
125+
const start = Number(hunk[1]);
126+
const count = Number(hunk[2] ?? 1);
127+
const blob = git.run(["cat-file", "-p", `${fixup}^:${path}`]);
128+
// A final line without a newline is still a line blame can name.
129+
const length = blob === "" ? 0 : blob.split("\n").length - (blob.endsWith("\n") ? 1 : 0);
130+
const from = Math.max(1, start - FOLD_CONTEXT + (count === 0 ? 1 : 0));
131+
const to = Math.min(length, start + Math.max(count, 1) - 1 + FOLD_CONTEXT);
132+
if (from > to) continue;
133+
const blame = git.run([
134+
"blame",
135+
"--porcelain",
136+
"-L",
137+
`${from},${to}`,
138+
`${base}..${fixup}^`,
139+
"--",
140+
path,
141+
]);
142+
for (const [, sha = ""] of blame.matchAll(/^([0-9a-f]{40}) \d+ \d+/gm)) {
143+
const index = order.get(sha) ?? -1;
144+
if (index > newest && !(stack[index]?.subject ?? "").startsWith(FIXUP_PREFIX)) newest = index;
145+
}
146+
}
147+
const target = stack[newest];
148+
return target === undefined || target.sha === owner ? undefined : target.sha;
149+
};
150+
100151
/** Abort a mid-stop rebase, then claim the worktree and its admin entry; a leaked replay must not outlive the check. */
101152
const removeReplayWorktree = (git: SystemGit, worktree: string): void => {
102153
const rebaseMerge = new SystemGit(worktree).runResult([
@@ -154,12 +205,22 @@ export const fixupFoldFailures = (
154205
const stopped = replay.runResult(["rev-parse", "--verify", "REBASE_HEAD"]);
155206
const stoppedSha = stopped.status === 0 ? stopped.stdout.trim() : "";
156207
const pair = fixups.owners.find(([fixup]) => stoppedSha.startsWith(fixup));
208+
let retarget: string | undefined;
209+
if (pair !== undefined)
210+
try {
211+
retarget = retargetFor(git, base, pair[0], pair[1], subjects);
212+
} catch {
213+
// The hint is advisory; the refusal stands without it.
214+
}
157215
const reason =
158216
pair === undefined
159217
? stoppedSha === ""
160218
? "the replay failed before applying a commit"
161219
: `the replay stopped at ${name(stoppedSha)}`
162-
: `fixup "${subjectOf(pair[0])}" (${shortSha(pair[0])}) does not fold into its owner "${subjectOf(pair[1])}" (${shortSha(pair[1])}): the replay stopped applying it there`;
220+
: `fixup "${subjectOf(pair[0])}" (${shortSha(pair[0])}) does not fold into its owner "${subjectOf(pair[1])}" (${shortSha(pair[1])}): the replay stopped applying it there` +
221+
(retarget === undefined
222+
? ""
223+
: `; name "${subjectOf(retarget)}" (${shortSha(retarget)}) instead, the newest commit that changed the lines around this edit`);
163224
const detail = [result.stderr.trim(), result.error?.message].filter(Boolean).join("\n");
164225
return [detail === "" ? reason : `${reason}\n${detail}`];
165226
}

‎scripts/fork-scan-authoring.ts‎

Lines changed: 34 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -47,10 +47,14 @@ export interface CommitPatch {
4747
readonly removedTestLines: ReadonlyMap<string, ReadonlyArray<string>>;
4848
// Every added/removed content line a commit's patch carries, keyed by path,
4949
// so the hook guard can classify the seam without parsing diffs again.
50-
readonly changedLines: ReadonlyMap<
51-
string,
52-
{ readonly added: ReadonlyArray<string>; readonly removed: ReadonlyArray<string> }
53-
>;
50+
// `addedAt` holds each added line's 1-based line in the committed file.
51+
readonly changedLines: ReadonlyMap<string, ChangedLines>;
52+
}
53+
54+
export interface ChangedLines {
55+
readonly added: ReadonlyArray<string>;
56+
readonly addedAt: ReadonlyArray<number>;
57+
readonly removed: ReadonlyArray<string>;
5458
}
5559

5660
export interface AuthoringGuardCommit {
@@ -77,18 +81,19 @@ export interface AuthoringGuardInput {
7781
// line the fork added itself removes nothing upstream wrote, so only lines here count. An absent
7882
// entry refuses every removal: an unread tree is not evidence the line was the fork's.
7983
readonly upstreamTestLines: ReadonlyMap<string, ReadonlySet<string>>;
80-
// The significant lines each touched upstream file carries in the target
81-
// tree, for the hook guard's mirror filter (RSI-Software/t3code-hyprws#1207):
82-
// an added line the target already has is a revert, not a fork insertion.
83-
// Absent on inputs built before the map existed; the guard then behaves
84-
// as it always has.
84+
// The significant lines each touched upstream file carries in the target tree, for the hook
85+
// guard: an added line the target already has is a revert. Absent on inputs built before the map
86+
// existed; the guard then behaves as it always has.
8587
readonly upstreamLines?: ReadonlyMap<string, ReadonlySet<string>> | undefined;
86-
// The target-tree text of each touched upstream test file, plus the
87-
// head-tree (scanned-head) text of every fork sibling. Read together,
88-
// they let the rule exempt a declared-superseded case structurally —
89-
// by the case's own lines — instead of by whole-file line membership,
90-
// which cannot tell a shared body line from an upstream one
91-
// (RSI-Software/t3code-hyprws#1208).
88+
readonly replayAddedLines?:
89+
| ReadonlyMap<string, ReadonlyMap<string, ReadonlyArray<string>>>
90+
| undefined;
91+
// A commit's own blob for a path, read only when the hook guard would
92+
// refuse: a marker on an unchanged line still covers the lines it marks.
93+
readonly readCommittedText?: ((sha: string, path: string) => string | undefined) | undefined;
94+
// The target-tree text of each touched upstream test file plus the head-tree text of every fork
95+
// sibling, so the rule exempts a declared-superseded case by its own lines, not by whole-file
96+
// membership, which cannot tell a shared body line from an upstream one.
9297
readonly upstreamTestTexts: ReadonlyMap<string, string>;
9398
// Head-tree text for count-aware removal checks: duplicate upstream text
9499
// survives when the fork only removes its own appended copy.
@@ -152,6 +157,9 @@ export const upstreamSourceLines = (text: string): ReadonlySet<string> =>
152157
.filter((line) => line !== ""),
153158
);
154159

160+
// `@@ -a,b +c,d @@`: `c` is the committed file's line of the hunk's first addition.
161+
const HUNK_TARGET_START = /^@@ -\d+(?:,\d+)? \+(\d+)/;
162+
155163
export const parseCommitPatches = (raw: string): ReadonlyMap<string, CommitPatch> => {
156164
const patches = new Map<string, CommitPatch>();
157165
for (const record of raw.replace(/\r\n/g, "\n").split(PATCH_RECORD_SEPARATOR)) {
@@ -163,6 +171,8 @@ export const parseCommitPatches = (raw: string): ReadonlyMap<string, CommitPatch
163171
const testBlockHunks: Array<TestBlockHunk> = [];
164172
const removedTestLines = new Map<string, Array<string>>();
165173
const addedLines = new Map<string, Array<string>>();
174+
const addedAt = new Map<string, Array<number>>();
175+
let nextAddedLine = 0;
166176
const removedLines = new Map<string, Array<string>>();
167177
// A deletion writes `+++ /dev/null`, so removals are attributed to the
168178
// source side and additions to the target side rather than to one path.
@@ -194,6 +204,7 @@ export const parseCommitPatches = (raw: string): ReadonlyMap<string, CommitPatch
194204
}
195205
if (line.startsWith("@@")) {
196206
flushTestBlockHunk();
207+
nextAddedLine = Number(HUNK_TARGET_START.exec(line)?.[1] ?? 0);
197208
continue;
198209
}
199210
const added = line.startsWith("+");
@@ -206,6 +217,12 @@ export const parseCommitPatches = (raw: string): ReadonlyMap<string, CommitPatch
206217
const held = side.get(path);
207218
if (held === undefined) side.set(path, [content]);
208219
else held.push(content);
220+
if (added) {
221+
const positions = addedAt.get(path) ?? [];
222+
positions.push(nextAddedLine);
223+
addedAt.set(path, positions);
224+
nextAddedLine += 1;
225+
}
209226
if (!added && TEST_FILE.test(path) && !FORK_TEST_FILE.test(path) && isSignificant(content)) {
210227
const heldLines = removedTestLines.get(path) ?? [];
211228
heldLines.push(content.trim());
@@ -226,13 +243,11 @@ export const parseCommitPatches = (raw: string): ReadonlyMap<string, CommitPatch
226243
}
227244
}
228245
flushTestBlockHunk();
229-
const changedLines = new Map<
230-
string,
231-
{ readonly added: ReadonlyArray<string>; readonly removed: ReadonlyArray<string> }
232-
>();
246+
const changedLines = new Map<string, ChangedLines>();
233247
for (const path of new Set([...addedLines.keys(), ...removedLines.keys()]))
234248
changedLines.set(path, {
235249
added: addedLines.get(path) ?? [],
250+
addedAt: addedAt.get(path) ?? [],
236251
removed: removedLines.get(path) ?? [],
237252
});
238253
patches.set(sha, {

‎scripts/fork-scan-gates.test.ts‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,74 @@ const replayHookWarnings = (
162162
: { replayAddedLines: new Map([["file.ts", replayAddedLines]]) }),
163163
});
164164

165+
it("covers an edit inside a hook whose marker line it leaves unchanged", () => {
166+
const patch = parseCommitPatches(
167+
[
168+
"abc1234",
169+
"--- a/file.ts",
170+
"+++ b/file.ts",
171+
"@@ -2 +2 @@",
172+
"-const value = upstreamCall(",
173+
"+const value = forkCall(",
174+
"@@ -6 +6 @@",
175+
"-const plain = 1;",
176+
"+const plain = 2;",
177+
"",
178+
].join("\n"),
179+
).get("abc1234");
180+
const committed = [
181+
'import { x } from "y";',
182+
"const value = forkCall(",
183+
" first,",
184+
" second,",
185+
"); // fork-hook: example/multi-line",
186+
"const plain = 2;",
187+
].join("\n");
188+
const warnings = hookGuardWarnings({
189+
commit: { short: "abc1234", domain: "example" },
190+
files: ["file.ts"],
191+
changedLines: patch?.changedLines ?? new Map(),
192+
upstreamFiles: new Set(["file.ts"]),
193+
readCommittedText: () => committed,
194+
});
195+
assert.lengthOf(warnings, 1);
196+
assert.match(warnings[0] ?? "", /1 added line.*plain/);
197+
});
198+
199+
it("refuses an edit after a JSX hook whose end marker it leaves unchanged", () => {
200+
const patch = parseCommitPatches(
201+
[
202+
"abc1234",
203+
"--- a/file.tsx",
204+
"+++ b/file.tsx",
205+
"@@ -2 +2 @@",
206+
"-{/* fork-hook: example/old-name */}",
207+
"+{/* fork-hook: example/new-name */}",
208+
"@@ -5 +5 @@",
209+
"-<Plain value={1} />",
210+
"+<Plain value={2} />",
211+
"",
212+
].join("\n"),
213+
).get("abc1234");
214+
const committed = [
215+
"<>",
216+
"{/* fork-hook: example/new-name */}",
217+
"<Fork />",
218+
"{/* fork-hook-end */}",
219+
"<Plain value={2} />",
220+
"</>",
221+
].join("\n");
222+
const warnings = hookGuardWarnings({
223+
commit: { short: "abc1234", domain: "example" },
224+
files: ["file.tsx"],
225+
changedLines: patch?.changedLines ?? new Map(),
226+
upstreamFiles: new Set(["file.tsx"]),
227+
readCommittedText: () => committed,
228+
});
229+
assert.lengthOf(warnings, 1);
230+
assert.match(warnings[0] ?? "", /1 added line.*Plain/);
231+
});
232+
165233
it("exempts identical replay additions", () => {
166234
assert.deepStrictEqual(
167235
replayHookWarnings(["const historical = true;"], ["const historical = true;"]),

‎scripts/fork-scan.ts‎

Lines changed: 9 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import {
1818
} from "./fork-delta.ts";
1919
import {
2020
type AuthoringGuardCommit,
21+
type AuthoringGuardInput,
2122
collectAuthoringWarnings,
2223
commitPatchArguments,
2324
parseCommitPatches,
@@ -327,25 +328,6 @@ export interface BaselineKeys {
327328
readonly additiveKeys: ReadonlySet<string>;
328329
}
329330

330-
export interface AuthoringGuardInput {
331-
readonly commits: ReadonlyArray<AuthoringGuardCommit>;
332-
readonly filesBySha: ReadonlyMap<string, ReadonlyArray<string>>;
333-
readonly patchesBySha: ReadonlyMap<string, CommitPatch>;
334-
readonly upstreamFiles: ReadonlySet<string>;
335-
readonly upstreamTestFiles: ReadonlySet<string>;
336-
readonly upstreamTestLines: ReadonlyMap<string, ReadonlySet<string>>;
337-
// Significant target-tree lines per touched upstream file, for the hook
338-
// guard's mirror filter (RSI-Software/t3code-hyprws#1207). Absent on
339-
// inputs built before the map existed; the guard then behaves as before.
340-
readonly upstreamLines?: ReadonlyMap<string, ReadonlySet<string>> | undefined;
341-
readonly replayAddedLines?:
342-
| ReadonlyMap<string, ReadonlyMap<string, ReadonlyArray<string>>>
343-
| undefined;
344-
readonly upstreamTestTexts: ReadonlyMap<string, string>;
345-
readonly headTestTexts?: ReadonlyMap<string, string> | undefined;
346-
readonly siblingTexts: ReadonlyMap<string, string>;
347-
}
348-
349331
const SHA_PATTERN = /\b[0-9a-f]{7,40}\b/g;
350332
// A whole-word integer between spaces is a count ("gains 4 fork test
351333
// block(s)"). A squash sums its members' counts, so the count leaves the key
@@ -458,6 +440,7 @@ export const buildScanResult = (input: ScanInput): ScanResult => {
458440
upstreamFiles: input.guard?.upstreamFiles ?? new Set(),
459441
upstreamLines: input.guard?.upstreamLines,
460442
replayAddedLines: input.guard?.replayAddedLines?.get(commit.sha),
443+
readCommittedText: (path) => input.guard?.readCommittedText?.(commit.sha, path),
461444
}).map((detail) => `${commit.short} ${commit.domain} ${detail}`);
462445
}),
463446
};
@@ -910,6 +893,13 @@ const buildGuardInput = (
910893
significantTestLines,
911894
),
912895
replayAddedLines,
896+
readCommittedText: (sha, path) => {
897+
try {
898+
return git.run(["show", `${sha}:${path}`]);
899+
} catch {
900+
return undefined;
901+
}
902+
},
913903
upstreamLines: readUpstreamLines(
914904
git,
915905
range.target,

0 commit comments

Comments
 (0)