@imdeadpool/guardex 8.4.19 → 8.4.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@imdeadpool/guardex",
3
- "version": "8.4.19",
3
+ "version": "8.4.20",
4
4
  "description": "Guardian T-Rex for your multi-agent repo. Isolated worktrees, file locks, and PR-only merges stop parallel Codex & Claude agents from overwriting each other's work. Auto-wires Oh My Codex, Oh My Claude, OpenSpec, and Caveman.",
5
5
  "license": "MIT",
6
6
  "preferGlobal": true,
@@ -65,5 +65,5 @@
65
65
  "prepublishOnly": "node scripts/prepublish-bump-version.js",
66
66
  "postinstall": "node -e \"require('./src/heavy').installReport()\""
67
67
  },
68
- "gitHead": "2ee7256650bf1738751be7b62ba8b2d3ebfcabfd"
68
+ "gitHead": "75e19acecbd80624b8dc0b0c0a5e2de1664847ed"
69
69
  }
@@ -478,6 +478,7 @@ function runReviewGate(
478
478
  provider,
479
479
  post: true,
480
480
  requireCompleteDiff: true,
481
+ expectedBaseSha: reviewedBaseSha,
481
482
  expectedHeadSha: pushedHeadSha,
482
483
  model: options.reviewModel,
483
484
  timeoutMs: options.reviewTimeoutMs,
@@ -0,0 +1,278 @@
1
+ const { isDeepStrictEqual } = require('node:util');
2
+ const { GH_BIN } = require('../context');
3
+
4
+ const SNAPSHOT = /^diff --git a\/((?:[\w@.-]+\/)*meta\/(\d{4})_snapshot\.json) b\/\1\n/;
5
+ const UUID = /^[\da-f]{8}-(?:[\da-f]{4}-){3}[\da-f]{12}$/i;
6
+ const SHA = /^[\da-f]{40}$/;
7
+ const MAPS = ['tables', 'enums', 'schemas', 'sequences', 'roles', 'policies', 'views'];
8
+ const TABLE_MAPS = [
9
+ 'columns',
10
+ 'indexes',
11
+ 'foreignKeys',
12
+ 'compositePrimaryKeys',
13
+ 'uniqueConstraints',
14
+ 'policies',
15
+ 'checkConstraints'
16
+ ];
17
+ const META = ['columns', 'schemas', 'tables'];
18
+
19
+ const record = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
20
+ const exactKeys = (value, keys) =>
21
+ record(value) &&
22
+ Object.keys(value).length === keys.length &&
23
+ keys.every((key) => Object.hasOwn(value, key));
24
+ const objectMap = (value) => record(value) && Object.values(value).every(record);
25
+ const nonemptyString = (value) => typeof value === 'string' && value.length > 0;
26
+
27
+ function validColumn(column) {
28
+ return (
29
+ nonemptyString(column.name) &&
30
+ nonemptyString(column.type) &&
31
+ typeof column.primaryKey === 'boolean' &&
32
+ typeof column.notNull === 'boolean'
33
+ );
34
+ }
35
+
36
+ function validEnum(enumeration) {
37
+ return (
38
+ nonemptyString(enumeration.name) &&
39
+ nonemptyString(enumeration.schema) &&
40
+ Array.isArray(enumeration.values) &&
41
+ enumeration.values.every((value) => typeof value === 'string')
42
+ );
43
+ }
44
+
45
+ function readGeneratedJson(text) {
46
+ if (text.includes('\uFFFD')) throw new Error('lossy JSON input');
47
+ const document = JSON.parse(text);
48
+ const generated = JSON.stringify(document, null, 2);
49
+ // Besides limiting the transform to a known output format, the exact
50
+ // roundtrip rejects duplicate keys and numbers that lost precision.
51
+ if (text !== generated && text !== `${generated}\n`) throw new Error('not generated JSON');
52
+ return document;
53
+ }
54
+
55
+ function validSnapshot(snapshot) {
56
+ return (
57
+ exactKeys(snapshot, ['id', 'prevId', 'version', 'dialect', '_meta', ...MAPS]) &&
58
+ snapshot.version === '7' &&
59
+ snapshot.dialect === 'postgresql' &&
60
+ typeof snapshot.id === 'string' &&
61
+ UUID.test(snapshot.id) &&
62
+ typeof snapshot.prevId === 'string' &&
63
+ UUID.test(snapshot.prevId) &&
64
+ snapshot.id !== snapshot.prevId &&
65
+ MAPS.every((key) => objectMap(snapshot[key])) &&
66
+ Object.values(snapshot.enums).every(validEnum) &&
67
+ exactKeys(snapshot._meta, META) &&
68
+ META.every(
69
+ (key) =>
70
+ record(snapshot._meta[key]) &&
71
+ Object.values(snapshot._meta[key]).every((value) => typeof value === 'string')
72
+ ) &&
73
+ Object.values(snapshot.tables).every(
74
+ (table) =>
75
+ nonemptyString(table.name) &&
76
+ typeof table.schema === 'string' &&
77
+ TABLE_MAPS.every((key) => objectMap(table[key])) &&
78
+ Object.values(table.columns).every(validColumn) &&
79
+ typeof table.isRLSEnabled === 'boolean'
80
+ )
81
+ );
82
+ }
83
+
84
+ function journalEntries(journal) {
85
+ if (
86
+ !exactKeys(journal, ['version', 'dialect', 'entries']) ||
87
+ journal.version !== '7' ||
88
+ journal.dialect !== 'postgresql' ||
89
+ !Array.isArray(journal.entries)
90
+ )
91
+ throw new Error('unrecognized migration journal');
92
+ return journal.entries;
93
+ }
94
+
95
+ function journalTag(entry, idx) {
96
+ const prefix = String(idx).padStart(4, '0');
97
+ if (
98
+ !exactKeys(entry, ['idx', 'version', 'when', 'tag', 'breakpoints']) ||
99
+ entry.idx !== idx ||
100
+ entry.version !== '7' ||
101
+ !Number.isSafeInteger(entry.when) ||
102
+ typeof entry.breakpoints !== 'boolean' ||
103
+ typeof entry.tag !== 'string' ||
104
+ !new RegExp(`^${prefix}_[\\w-]+$`).test(entry.tag)
105
+ )
106
+ throw new Error('unrecognized journal entry');
107
+ return entry.tag;
108
+ }
109
+
110
+ function uniqueJournalHistory(entries) {
111
+ let previousIdx = -1;
112
+ const tags = new Set();
113
+ for (const entry of entries) {
114
+ if (
115
+ !Number.isSafeInteger(entry?.idx) ||
116
+ entry.idx <= previousIdx ||
117
+ !nonemptyString(entry.tag) ||
118
+ tags.has(entry.tag)
119
+ )
120
+ return false;
121
+ previousIdx = entry.idx;
122
+ tags.add(entry.tag);
123
+ }
124
+ return true;
125
+ }
126
+
127
+ function fetchPrRevision(pr, repoRoot, runner) {
128
+ const gh = runner(GH_BIN, ['pr', 'view', String(pr), '--json', 'baseRefOid,headRefOid'], {
129
+ cwd: repoRoot,
130
+ timeout: 60_000
131
+ });
132
+ if (gh.status !== 0) return null;
133
+ const { baseRefOid: base, headRefOid: head } = JSON.parse(gh.stdout);
134
+ return typeof base === 'string' && SHA.test(base) && typeof head === 'string' && SHA.test(head)
135
+ ? { base, head }
136
+ : null;
137
+ }
138
+
139
+ function addedRegularText(section) {
140
+ return /^diff --git [^\n]+\nnew file mode 100644\nindex 0+\.\.[\da-f]+\n--- \/dev\/null\n\+\+\+ b\/[^\n]+\n@@ -0,0 \+1(?:,\d+)? @@\n\+/.test(
141
+ section
142
+ );
143
+ }
144
+
145
+ function diffSection(sections, file) {
146
+ return sections.find((part) => part.startsWith(`diff --git a/${file} b/${file}\n`));
147
+ }
148
+
149
+ function delta(before, after, path, lines) {
150
+ if (isDeepStrictEqual(before, after)) return;
151
+ if (record(before) && record(after)) {
152
+ const keys = new Set([...Object.keys(before), ...Object.keys(after)]);
153
+ for (const key of keys) {
154
+ delta(
155
+ Object.hasOwn(before, key) ? before[key] : undefined,
156
+ Object.hasOwn(after, key) ? after[key] : undefined,
157
+ [...path, key],
158
+ lines
159
+ );
160
+ }
161
+ } else {
162
+ // JSON omits undefined: absent "before" means added, absent "after" removed.
163
+ // Arrays and newly added/removed objects are retained in full.
164
+ lines.push(JSON.stringify({ path, before, after }));
165
+ }
166
+ }
167
+
168
+ /**
169
+ * Replace only a validated, added Drizzle PostgreSQL v7 snapshot for the
170
+ * provider. Refuse rather than guess if exact PR objects or provenance are
171
+ * unavailable. The caller retains rawDiff for anchors and all other checks.
172
+ */
173
+ function projectDrizzleSnapshot(rawDiff, { pr, repoRoot, expectedBase, expectedHead, runner }) {
174
+ const unchanged = { diff: rawDiff };
175
+ // The runner decodes Git and GitHub output as UTF-8. Refuse a lossy comparison.
176
+ if (rawDiff.includes('\uFFFD')) return unchanged;
177
+ const sections = rawDiff.split(/(?=^diff --git )/m);
178
+ const candidates = sections.flatMap((section, index) => {
179
+ const match = SNAPSHOT.exec(section);
180
+ return match ? [{ section, index, file: match[1], number: Number(match[2]) }] : [];
181
+ });
182
+ if (candidates.length !== 1) return unchanged;
183
+ const [{ section, index, file, number }] = candidates;
184
+ if (
185
+ !number ||
186
+ !addedRegularText(section) ||
187
+ file.split('/').some((part) => part === '.' || part === '..')
188
+ ) {
189
+ return unchanged;
190
+ }
191
+
192
+ try {
193
+ const revision = fetchPrRevision(pr, repoRoot, runner);
194
+ if (
195
+ !revision ||
196
+ (expectedBase && expectedBase !== revision.base) ||
197
+ (expectedHead && expectedHead !== revision.head)
198
+ )
199
+ return unchanged;
200
+ const { base, head } = revision;
201
+
202
+ const git = (...args) => {
203
+ const result = runner('git', args, {
204
+ cwd: repoRoot,
205
+ timeout: 60_000,
206
+ env: { GIT_NO_REPLACE_OBJECTS: '1' }
207
+ });
208
+ if (result.status !== 0) throw new Error('cannot read exact PR objects');
209
+ return result.stdout;
210
+ };
211
+ const ancestor = git('merge-base', '--all', base, head).trim();
212
+ if (
213
+ !SHA.test(ancestor) ||
214
+ git('diff', '--no-ext-diff', '--no-textconv', '--color=never', ancestor, head, '--') !==
215
+ rawDiff
216
+ ) {
217
+ return unchanged;
218
+ }
219
+
220
+ const metaDir = file.slice(0, file.lastIndexOf('/') + 1);
221
+ const previousFile = `${metaDir}${String(number - 1).padStart(4, '0')}_snapshot.json`;
222
+ const previousEntry = git('ls-tree', ancestor, '--', previousFile);
223
+ if (
224
+ !/^100644 blob [\da-f]{40}\t/.test(previousEntry) ||
225
+ previousEntry !== git('ls-tree', head, '--', previousFile)
226
+ )
227
+ return unchanged;
228
+ const oldSnapshot = readGeneratedJson(git('show', `${ancestor}:${previousFile}`));
229
+ const newSnapshot = readGeneratedJson(git('show', `${head}:${file}`));
230
+ if (
231
+ !validSnapshot(oldSnapshot) ||
232
+ !validSnapshot(newSnapshot) ||
233
+ newSnapshot.id === oldSnapshot.id ||
234
+ newSnapshot.id === oldSnapshot.prevId ||
235
+ newSnapshot.prevId !== oldSnapshot.id
236
+ )
237
+ return unchanged;
238
+
239
+ const journalFile = `${metaDir}_journal.json`;
240
+ const journalSection = diffSection(sections, journalFile);
241
+ if (
242
+ !journalSection ||
243
+ !/^diff --git [^\n]+\nindex [\da-f]+\.\.[\da-f]+ 100644\n--- a\/[^\n]+\n\+\+\+ b\/[^\n]+\n@@ /.test(
244
+ journalSection
245
+ )
246
+ )
247
+ return unchanged;
248
+ const older = journalEntries(readGeneratedJson(git('show', `${ancestor}:${journalFile}`)));
249
+ const newer = journalEntries(readGeneratedJson(git('show', `${head}:${journalFile}`)));
250
+ if (
251
+ newer.length !== older.length + 1 ||
252
+ !isDeepStrictEqual(older, newer.slice(0, -1)) ||
253
+ !uniqueJournalHistory(newer)
254
+ )
255
+ return unchanged;
256
+ journalTag(older.at(-1), number - 1);
257
+ const tag = journalTag(newer.at(-1), number);
258
+ const sqlFile = `${metaDir.slice(0, -'meta/'.length)}${tag}.sql`;
259
+ const sqlSection = diffSection(sections, sqlFile);
260
+ if (!sqlSection || !addedRegularText(sqlSection)) return unchanged;
261
+
262
+ const changes = [];
263
+ delta(oldSnapshot, newSnapshot, [], changes);
264
+ sections[index] = [
265
+ `diff --git a/${file} b/${file}`,
266
+ `[Validated Drizzle PostgreSQL v7 snapshot delta: ${previousFile} → ${file}; real anchor: line 1]`,
267
+ ...changes,
268
+ ''
269
+ ].join('\n');
270
+ return { diff: sections.join(''), snapshotPath: file, base, head };
271
+ } catch {
272
+ // Parse errors, missing objects, execution errors, and unsupported shapes
273
+ // leave the full original input in place. The normal size gate then blocks.
274
+ return unchanged;
275
+ }
276
+ }
277
+
278
+ module.exports = { fetchPrRevision, projectDrizzleSnapshot };
@@ -12,6 +12,7 @@ const {
12
12
  reviewFollowUpLines
13
13
  } = require('../pull-request/value-history');
14
14
  const { compactGeneratedReviewDiff } = require('./diff-context');
15
+ const { fetchPrRevision, projectDrizzleSnapshot } = require('./drizzle-snapshot');
15
16
  const abide = require('../abide');
16
17
  const {
17
18
  createRun,
@@ -131,7 +132,7 @@ function capDiff(diff, maxChars = MAX_DIFF_CHARS) {
131
132
 
132
133
  function compactReviewPrompt(
133
134
  diff,
134
- { prLens = false, compactedLockContext = false, truncated = false, previousImpact = [] } = {}
135
+ { prLens = false, compactedLockContext = false, snapshotPath, truncated = false, previousImpact = [] } = {}
135
136
  ) {
136
137
  return [
137
138
  'As gitguardex-code-assist, review this PR diff for bugs, regressions, security issues and missing tests.',
@@ -147,6 +148,9 @@ function compactReviewPrompt(
147
148
  ...(compactedLockContext ? [
148
149
  'In [unchanged lockfile context: ...] markers, old and new are original line numbers. Count the entire omitted range.'
149
150
  ] : []),
151
+ ...(snapshotPath ? [
152
+ 'A validated Drizzle snapshot delta replaces repeated schema content. Each JSON record lists the path and old/new values; omitted before/after means added/removed. Use original SQL or application lines when possible. For snapshot findings and evidence use real line 1 only, and never suggest a snapshot edit.'
153
+ ] : []),
150
154
  ...(prLens ? [GRAPH_PROMPT] : []),
151
155
  ...(!truncated && previousImpact.length
152
156
  ? [
@@ -339,7 +343,9 @@ function renderReviewSummary({
339
343
  unanchored = [],
340
344
  duplicates = 0,
341
345
  commit = '',
346
+ reviewedBaseSha,
342
347
  truncated = false,
348
+ snapshotPath,
343
349
  gate,
344
350
  degraded = false,
345
351
  abide: abideResult,
@@ -388,8 +394,10 @@ function renderReviewSummary({
388
394
 
389
395
  const footer = [`Provider \`${provider}\``];
390
396
  if (commit) footer.push(`commit \`${commit.slice(0, 7)}\``);
397
+ if (reviewedBaseSha) footer.push(`base \`${reviewedBaseSha.slice(0, 7)}\``);
391
398
  if (duplicates > 0) footer.push(`${duplicates} already reported`);
392
399
  if (truncated) footer.push('⚠️ diff truncated — review is partial');
400
+ if (snapshotPath) footer.push(`Validated Drizzle snapshot delta: \`${snapshotPath}\``);
393
401
  if (degraded)
394
402
  footer.push('⚠️ inline anchoring rejected by GitHub — reported in this summary instead');
395
403
  const abideLine = abideSummaryLine(abideResult);
@@ -405,10 +413,12 @@ function renderMarkdownReview({
405
413
  findings,
406
414
  unanchored = [],
407
415
  truncated = false,
416
+ snapshotPath,
408
417
  prLens,
409
418
  abide: abideResult,
410
419
  bugHunter,
411
420
  reviewedHeadSha,
421
+ reviewedBaseSha,
412
422
  value,
413
423
  followUp
414
424
  }) {
@@ -421,7 +431,9 @@ function renderMarkdownReview({
421
431
  `- Severity: ${severityLine(findings)}`
422
432
  ];
423
433
  if (reviewedHeadSha) lines.push(`- Reviewed commit: ${reviewedHeadSha}`);
434
+ if (reviewedBaseSha) lines.push(`- Reviewed base: ${reviewedBaseSha}`);
424
435
  if (truncated) lines.push('- ⚠️ Diff truncated — review is partial');
436
+ if (snapshotPath) lines.push(`- Validated Drizzle snapshot delta: \`${snapshotPath}\``);
425
437
  const abideLine = abideSummaryLine(abideResult);
426
438
  if (abideLine) lines.push(`- ${abideLine}`);
427
439
  if (prLens?.status)
@@ -727,9 +739,11 @@ function postGithubReview(pr, context, repoRoot, runner = run) {
727
739
  fresh = anchored.filter((finding) => !alreadyPosted.has(findingFingerprint(finding)));
728
740
  }
729
741
  const duplicates = anchored.length - fresh.length;
730
- const commit = fetchHeadSha(pr, repoRoot, runner);
731
- if (context.reviewedHeadSha && commit !== context.reviewedHeadSha) {
732
- throw new Error('PR changed before posting the PR Lens review; rerun against the current diff');
742
+ const revision = context.reviewedBaseSha ? fetchPrRevision(pr, repoRoot, runner) : null;
743
+ const commit = context.reviewedBaseSha ? revision?.head : fetchHeadSha(pr, repoRoot, runner);
744
+ if ((context.reviewedHeadSha && commit !== context.reviewedHeadSha)
745
+ || (context.reviewedBaseSha && revision?.base !== context.reviewedBaseSha)) {
746
+ throw new Error('PR changed before posting the review; rerun against the current diff');
733
747
  }
734
748
 
735
749
  const hasEvidence = context.value?.drivers.length || context.followUp?.some((item) => item.evidence);
@@ -740,7 +754,9 @@ function postGithubReview(pr, context, repoRoot, runner = run) {
740
754
  unanchored,
741
755
  duplicates,
742
756
  commit,
757
+ reviewedBaseSha: context.reviewedBaseSha,
743
758
  truncated,
759
+ snapshotPath: context.snapshotPath,
744
760
  gate,
745
761
  abide: context.abide,
746
762
  bugHunter: context.bugHunter,
@@ -1008,7 +1024,14 @@ function runPrReview(options, deps = {}) {
1008
1024
  }
1009
1025
  const impactStartedAt = Date.now();
1010
1026
  const rawDiff = fetchPrDiff(pr, repoRoot, runner);
1011
- const { diff, truncated } = capDiff(rawDiff);
1027
+ const projection = !lensContext && rawDiff.length > MAX_DIFF_CHARS
1028
+ ? projectDrizzleSnapshot(rawDiff, {
1029
+ pr, repoRoot, expectedBase: options.expectedBaseSha,
1030
+ expectedHead: options.expectedHeadSha || prHeadSha, runner
1031
+ })
1032
+ : { diff: rawDiff };
1033
+ const { diff, truncated } = capDiff(projection.diff);
1034
+ const { snapshotPath } = projection;
1012
1035
  if (lensContext && truncated)
1013
1036
  throw new Error('PR Lens requires a complete diff; review diff is truncated');
1014
1037
  if (options.requireCompleteDiff && truncated) {
@@ -1031,6 +1054,7 @@ function runPrReview(options, deps = {}) {
1031
1054
  model,
1032
1055
  agentQuiet: options.agentQuiet,
1033
1056
  compactedLockContext: providerDiff !== diff,
1057
+ snapshotPath,
1034
1058
  previousImpact,
1035
1059
  prLens: Boolean(lensContext),
1036
1060
  truncated
@@ -1045,7 +1069,12 @@ function runPrReview(options, deps = {}) {
1045
1069
  model = null;
1046
1070
  review = reviewWithProvider();
1047
1071
  }
1048
- const { findings: providerFindings, graph } = review;
1072
+ const { graph } = review;
1073
+ const providerFindings = review.findings.map((finding) => {
1074
+ if (finding.path !== snapshotPath) return finding;
1075
+ // Synthetic delta rows do not have real line numbers or safe replacements.
1076
+ return { ...finding, line: 1, startLine: 0, suggestion: '' };
1077
+ });
1049
1078
  let bugHunter;
1050
1079
  // An injected runner must opt in explicitly, independent of the caller's shell.
1051
1080
  if (bugHunterEnabled(deps.run ? deps.env || {} : env)) {
@@ -1069,6 +1098,9 @@ function runPrReview(options, deps = {}) {
1069
1098
  const findings = [...providerFindings, ...abideResult.findings];
1070
1099
  let prLens;
1071
1100
  const { anchored, unanchored, lineMap } = partitionByAnchor(findings, rawDiff);
1101
+ // Only the real sentinel line was presented for this path. Other real
1102
+ // lines must not validate evidence that refers to synthetic delta rows.
1103
+ if (snapshotPath) lineMap.set(snapshotPath, new Set([1]));
1072
1104
  const value = normalizeReviewValue(review.value, lineMap);
1073
1105
  const gate = {
1074
1106
  ...evaluateReviewGate(findings, { blockSeverities: options.blockSeverities }),
@@ -1081,13 +1113,15 @@ function runPrReview(options, deps = {}) {
1081
1113
  anchored,
1082
1114
  unanchored,
1083
1115
  truncated,
1116
+ snapshotPath,
1084
1117
  value,
1085
1118
  followUp: normalizeImpactFollowUp(previousImpact, review.followUp, lineMap),
1086
1119
  gate,
1087
1120
  prLens,
1088
1121
  abide: abideResult,
1089
1122
  ...advisory,
1090
- reviewedHeadSha: lensContext?.metadata.provenance.head.sha ?? prHeadSha
1123
+ reviewedBaseSha: projection.base,
1124
+ reviewedHeadSha: lensContext?.metadata.provenance.head.sha ?? projection.head ?? prHeadSha
1091
1125
  };
1092
1126
  let savedArtifact;
1093
1127
  if (lensContext) {