11import { db } from '@sim/db'
22import { workflow } from '@sim/db/schema'
3+ import { sha256Hex } from '@sim/security/hash'
34import { isRecordLike , sortObjectKeysDeep , toRecord } from '@sim/utils/object'
4- import { eq } from 'drizzle-orm'
5+ import { eq , sql } from 'drizzle-orm'
56import { OrchestrationError } from '@/lib/core/orchestration/types'
67import type { DbOrTx } from '@/lib/db/types'
78import { 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
3243function 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+ */
47102export 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+ */
78176export 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