Skip to content

Commit b094961

Browse files
committed
fix(build-notes): hold the build check under the workflow lock and tighten review findings
- spend the evaluation and re-check the baseline inside the write transaction; notes writes spend it too, so a build racing a notes edit is refused - record the baseline from the build's own commit (afterWrite hook) - refuse a Copilot whole-graph replace on a workflow with notes, and a build with no baseline - detect credential switches through salted hashes of withheld values - compare lint findings by block id, as counts - restore build notes with a restored folder; skip the archive step on a schema that predates the table - read the baseline in one snapshot, refuse oversize baselines, anchor the operations fence, accept any list marker for open items
1 parent 1d34bab commit b094961

16 files changed

Lines changed: 508 additions & 127 deletions

File tree

‎apps/sim/lib/build-notes/application/build-notes.ts‎

Lines changed: 29 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,10 @@ export const getBuildNotesStatus = defineAuthorizedWorkflowUseCase({
113113
exists: true as const,
114114
...paths(context.workflowId),
115115
evaluated: notes.evaluatedNotesHash !== null,
116-
/** True when the workflow was saved after the baseline was recorded; `changes` says whether it matters. */
116+
/**
117+
* A hint, from the workflow's save time: true when it was saved after the baseline. A field
118+
* edit in the editor may not move that time; `changes` is the authority, and a build checks it.
119+
*/
117120
mayHaveChangedOutsideAgent:
118121
!notes.baselineWorkflowUpdatedAt ||
119122
context.workflow.updatedAt > notes.baselineWorkflowUpdatedAt,
@@ -172,15 +175,15 @@ function parseBatch(reading: ReturnType<typeof readBuildNotes>): BatchReading {
172175
}
173176

174177
/**
175-
* The saved graph's lint findings, from the same lint the apply's dry run reports, so a build is
176-
* held only for what its batch adds and never for a person's unfinished edit.
178+
* The saved graph's lint findings counted by key, from the same lint the apply's dry run reports,
179+
* so a build is held only for what its batch adds and never for a person's unfinished edit.
177180
*/
178181
async function savedGraphLintFindings(
179182
principal: Principal,
180183
context: ActiveWorkflowApplicationContext
181-
): Promise<Set<string>> {
184+
): Promise<Map<string, number>> {
182185
const state = await loadWorkflowDeploymentSnapshot(context.workflowId)
183-
if (!state) return new Set()
186+
if (!state) return new Map()
184187
const lint = await withWorkflowBlockScope(context, () =>
185188
buildWorkflowLintReport(
186189
{ blocks: state.blocks, edges: state.edges },
@@ -191,7 +194,9 @@ async function savedGraphLintFindings(
191194
}
192195
)
193196
)
194-
return new Set(listWorkflowLintFindings(lint))
197+
const counts = new Map<string, number>()
198+
for (const { key } of listWorkflowLintFindings(lint)) counts.set(key, (counts.get(key) ?? 0) + 1)
199+
return counts
195200
}
196201

197202
async function readAdmittedNotes(
@@ -232,14 +237,22 @@ export const evaluateBuildNotes = defineAuthorizedWorkflowUseCase({
232237
}),
233238
savedGraphLintFindings(principal, context),
234239
])
235-
const findings = listWorkflowLintFindings(result.lint)
240+
const lint: string[] = []
241+
const lintAlreadyInGraph: string[] = []
242+
for (const finding of listWorkflowLintFindings(result.lint)) {
243+
const remaining = saved.get(finding.key) ?? 0
244+
if (remaining > 0) {
245+
saved.set(finding.key, remaining - 1)
246+
lintAlreadyInGraph.push(finding.text)
247+
} else lint.push(finding.text)
248+
}
236249
dryRun = {
237250
operationCount: result.operationCount,
238251
applied: result.applied,
239252
skipped: result.skipped,
240253
inputValidationErrors: result.inputValidationErrors,
241-
lint: findings.filter((finding) => !saved.has(finding)),
242-
lintAlreadyInGraph: findings.filter((finding) => saved.has(finding)),
254+
lint,
255+
lintAlreadyInGraph,
243256
}
244257
if (result.skipped.length) problems.push(`Dry run skipped ${result.skipped.length} item(s)`)
245258
if (result.inputValidationErrors.length)
@@ -251,7 +264,7 @@ export const evaluateBuildNotes = defineAuthorizedWorkflowUseCase({
251264
for (const placeholder of reading.placeholders)
252265
problems.push(`Placeholder still open: <<open:${placeholder}>>`)
253266
for (const item of reading.blockingOpenItems)
254-
problems.push(`Open item marked [${item.mark}]: ${item.text}`)
267+
problems.push(`Open item marked [${item.mark}]: ${item.text || '(no text)'}`)
255268
const passed = batch !== null && problems.length === 0
256269
if (passed && batch) {
257270
await recordBuildNotesEvaluation(notes.id, {
@@ -327,12 +340,17 @@ export const getBuildNotesChanges = defineAuthorizedWorkflowUseCase({
327340
),
328341
loadCurrentBaselineState(context.workflowId),
329342
])
330-
const { hasChanges, diff } = diffFromBaseline(parseBaseline(baselineText), current.state)
343+
const { hasChanges, diff, clearedFieldChanges } = diffFromBaseline(
344+
parseBaseline(baselineText),
345+
current
346+
)
331347
return {
332348
workflowId: context.workflowId,
333349
baseline: buildNotesPath(context.workflowId, 'baseline'),
334350
hasChanges,
335351
diff,
352+
/** Blocks whose credential or other withheld value changed; the values are never shown. */
353+
changedWithheldFields: clearedFieldChanges,
336354
}
337355
},
338356
})
Lines changed: 132 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import { db } from '@sim/db'
22
import { workflow } from '@sim/db/schema'
3+
import { sha256Hex } from '@sim/security/hash'
34
import { isRecordLike, sortObjectKeysDeep, toRecord } from '@sim/utils/object'
4-
import { eq } from 'drizzle-orm'
5+
import { eq, sql } from 'drizzle-orm'
56
import { OrchestrationError } from '@/lib/core/orchestration/types'
67
import type { DbOrTx } from '@/lib/db/types'
78
import { generateWorkflowDiffSummary, omitPresentationChanges } from '@/lib/workflows/comparison'
@@ -23,10 +24,20 @@ const BASELINE_SANITIZATION = {
2324
redactOpaqueCredentialInputs: true,
2425
} as const
2526

26-
/** The graph a baseline holds: the stored workflow, sanitized, with no save clock. */
27-
function sanitizedState(state: WorkflowState): WorkflowState {
28-
const sanitized = sanitizeWorkflowForSharing(state, BASELINE_SANITIZATION)
29-
return toWorkflowState({ ...sanitized, lastSaved: 0 })
27+
/** `blockId` → `subBlockId` → a salted hash of a value sanitization cleared. */
28+
type ClearedFieldHashes = Record<string, Record<string, string>>
29+
30+
/**
31+
* What a baseline records: the sanitized graph, plus a hash of each value sanitization cleared,
32+
* so switching a block's credential is a change even though the credential itself is never kept.
33+
*/
34+
export interface BaselineGraph {
35+
state: WorkflowState
36+
clearedFields: ClearedFieldHashes
37+
}
38+
39+
export interface BaselineSnapshot extends BaselineGraph {
40+
workflowUpdatedAt: Date
3041
}
3142

3243
function toWorkflowState(value: unknown): WorkflowState {
@@ -43,45 +54,140 @@ function toWorkflowState(value: unknown): WorkflowState {
4354
}
4455
}
4556

46-
/** The workflow as it is stored now, sanitized, and the `updatedAt` it was read at. */
57+
function subBlockValues(block: unknown): Record<string, unknown> {
58+
const subBlocks = isRecordLike(block) ? toRecord(block.subBlocks) : {}
59+
return Object.fromEntries(
60+
Object.entries(subBlocks).map(([id, subBlock]) => [
61+
id,
62+
isRecordLike(subBlock) ? subBlock.value : undefined,
63+
])
64+
)
65+
}
66+
67+
/** Hashes each subblock value the sanitized graph no longer carries, salted by its place. */
68+
function clearedFieldHashes(
69+
workflowId: string,
70+
stored: WorkflowState,
71+
sanitized: WorkflowState
72+
): ClearedFieldHashes {
73+
const hashes: ClearedFieldHashes = {}
74+
for (const [blockId, block] of Object.entries(stored.blocks)) {
75+
const kept = subBlockValues(sanitized.blocks[blockId])
76+
for (const [field, value] of Object.entries(subBlockValues(block))) {
77+
if (value === undefined || value === null || value === '') continue
78+
if (JSON.stringify(kept[field]) === JSON.stringify(value)) continue
79+
hashes[blockId] ??= {}
80+
hashes[blockId][field] = sha256Hex(
81+
`${workflowId}\u0000${blockId}\u0000${field}\u0000${JSON.stringify(value)}`
82+
)
83+
}
84+
}
85+
return hashes
86+
}
87+
88+
/** The graph a baseline holds: the stored workflow, sanitized, with no save clock. */
89+
function baselineGraph(workflowId: string, stored: WorkflowState): BaselineGraph {
90+
const state = toWorkflowState({
91+
...sanitizeWorkflowForSharing(stored, BASELINE_SANITIZATION),
92+
lastSaved: 0,
93+
})
94+
return { state, clearedFields: clearedFieldHashes(workflowId, stored, state) }
95+
}
96+
97+
/**
98+
* The workflow as it is stored now, as a baseline, and the `updatedAt` it was read at, both from
99+
* one snapshot: inside `executor` when one is passed (a write transaction sees its own write),
100+
* otherwise a repeatable-read transaction of its own.
101+
*/
47102
export async function loadCurrentBaselineState(
48103
workflowId: string,
49-
executor: DbOrTx = db
50-
): Promise<{ state: WorkflowState; workflowUpdatedAt: Date }> {
51-
const [snapshot, [row]] = await Promise.all([
52-
loadWorkflowDeploymentSnapshot(workflowId, executor),
53-
executor
104+
executor?: DbOrTx
105+
): Promise<BaselineSnapshot> {
106+
const read = async (tx: DbOrTx): Promise<BaselineSnapshot> => {
107+
const snapshot = await loadWorkflowDeploymentSnapshot(workflowId, tx)
108+
const [row] = await tx
54109
.select({ updatedAt: workflow.updatedAt })
55110
.from(workflow)
56111
.where(eq(workflow.id, workflowId))
57-
.limit(1),
58-
])
59-
if (!snapshot || !row) throw new OrchestrationError('not_found', 'Workflow not found')
60-
return { state: sanitizedState(snapshot), workflowUpdatedAt: row.updatedAt }
112+
.limit(1)
113+
if (!snapshot || !row) throw new OrchestrationError('not_found', 'Workflow not found')
114+
return { ...baselineGraph(workflowId, snapshot), workflowUpdatedAt: row.updatedAt }
115+
}
116+
if (executor) return read(executor)
117+
return db.transaction(async (tx) => {
118+
await tx.execute(sql`SET TRANSACTION ISOLATION LEVEL REPEATABLE READ`)
119+
return read(tx)
120+
})
61121
}
62122

63-
export function serializeBaseline(state: WorkflowState): string {
64-
return `${JSON.stringify(sortObjectKeysDeep(state), null, 2)}\n`
123+
export function serializeBaseline(baseline: BaselineGraph): string {
124+
return `${JSON.stringify(
125+
sortObjectKeysDeep({ ...baseline.state, clearedFields: baseline.clearedFields }),
126+
null,
127+
2
128+
)}\n`
65129
}
66130

67-
export function parseBaseline(content: string): WorkflowState {
131+
export function parseBaseline(content: string): BaselineGraph {
68132
let parsed: unknown
69133
try {
70134
parsed = JSON.parse(content)
71135
} catch {
72136
throw new OrchestrationError('internal', 'A build-notes baseline is not valid JSON')
73137
}
74-
return toWorkflowState(parsed)
138+
const clearedFields: ClearedFieldHashes = {}
139+
if (isRecordLike(parsed)) {
140+
for (const [blockId, fields] of Object.entries(toRecord(parsed.clearedFields))) {
141+
for (const [field, hash] of Object.entries(toRecord(fields))) {
142+
if (typeof hash !== 'string') continue
143+
clearedFields[blockId] ??= {}
144+
clearedFields[blockId][field] = hash
145+
}
146+
}
147+
}
148+
return { state: toWorkflowState(parsed), clearedFields }
75149
}
76150

77-
/** What changed from the baseline to the current graph, ignoring layout-only moves. */
151+
/** Fields whose cleared value (a credential, a password) differs, without revealing either. */
152+
function clearedFieldChanges(
153+
baseline: BaselineGraph,
154+
current: BaselineGraph
155+
): { blockId: string; field: string }[] {
156+
const changes: { blockId: string; field: string }[] = []
157+
const blockIds = new Set([
158+
...Object.keys(baseline.clearedFields),
159+
...Object.keys(current.clearedFields),
160+
])
161+
for (const blockId of blockIds) {
162+
if (!baseline.state.blocks[blockId] || !current.state.blocks[blockId]) continue
163+
const before = baseline.clearedFields[blockId] ?? {}
164+
const after = current.clearedFields[blockId] ?? {}
165+
for (const field of new Set([...Object.keys(before), ...Object.keys(after)])) {
166+
if (before[field] !== after[field]) changes.push({ blockId, field })
167+
}
168+
}
169+
return changes
170+
}
171+
172+
/**
173+
* What changed from the baseline to the current graph, ignoring layout-only moves. A block whose
174+
* credential or other cleared value changed is listed in `clearedFieldChanges`, by field only.
175+
*/
78176
export function diffFromBaseline(
79-
baseline: WorkflowState,
80-
current: WorkflowState
81-
): { hasChanges: boolean; diff: PublicWorkflowDiffSummary } {
82-
const summary = omitPresentationChanges(generateWorkflowDiffSummary(current, baseline))
177+
baseline: BaselineGraph,
178+
current: BaselineGraph
179+
): {
180+
hasChanges: boolean
181+
diff: PublicWorkflowDiffSummary
182+
clearedFieldChanges: { blockId: string; field: string }[]
183+
} {
184+
const summary = omitPresentationChanges(
185+
generateWorkflowDiffSummary(current.state, baseline.state)
186+
)
187+
const cleared = clearedFieldChanges(baseline, current)
83188
return {
84-
hasChanges: summary.hasChanges,
85-
diff: redactWorkflowDiffSummary(summary, baseline, current),
189+
hasChanges: summary.hasChanges || cleared.length > 0,
190+
diff: redactWorkflowDiffSummary(summary, baseline.state, current.state),
191+
clearedFieldChanges: cleared,
86192
}
87193
}

0 commit comments

Comments
 (0)