Skip to content

Commit 36585e7

Browse files
committed
wip(runtime): a declared record-id start input is loaded at every flow start door
Co-authored-by: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Utp6CbNMpDS92ifzhDw9vf
1 parent 2ffdb64 commit 36585e7

3 files changed

Lines changed: 237 additions & 10 deletions

File tree

‎packages/runtime/src/action-execution.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3858,9 +3858,9 @@ export type FlowStartRecordKeys = ReadonlyArray<readonly [key: string, value: un
38583858
*
38593859
* The object the start names is not always the object the run reads. A flow's
38603860
* own definition can state that it reads a start input as the id of a row of
3861-
* a fixed object ({@link flowDeclaredRecordReads}: a CRUD node's `filter.id`,
3862-
* a screen edit form's `recordId`, handed on through `subflow` and `map`
3863-
* inputs). Every such input the start hands the run (`start.inputs`, the
3861+
* a fixed object ({@link flowDeclaredRecordReads}: the input's own
3862+
* `objectName` declaration, a CRUD node's `filter.id`, a screen edit form's
3863+
* `recordId`, handed on through `subflow` and `map` inputs). Every such input the start hands the run (`start.inputs`, the
38643864
* `params` the run's input variables are bound from, row slots included) is
38653865
* judged against THAT object too, by the same load and the same refusals: the
38663866
* value must be one record id (a list of ids where the flow reads a list), or

‎packages/runtime/src/flow-start-admission.ts‎

Lines changed: 27 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,10 @@
6868
* says nothing about the row the run reads elsewhere under the same id. Every
6969
* start input the definition reads as a record id is judged that way, row
7070
* slot or not, and must be an id (or a list of ids, where it is read as one).
71+
* An input the author DECLARES a record id (`objectName` on the variable) is
72+
* judged the same way against the declared object, whether or not the
73+
* definition reads it in plain sight; an undeclared input keeps the
74+
* visible-read rule alone.
7175
*
7276
* ## Why a module, and why every door asks it
7377
*
@@ -240,6 +244,14 @@ function recordOf(value: unknown): Record<string, unknown> | undefined {
240244
* input as a record id of a FIXED object in these places, and only these,
241245
* across every region of the flow (`collectFlowGraphs`):
242246
*
247+
* - the input's own declaration, `objectName` on the variable (#29425 ruling
248+
* A): one id of that object, whatever the rest of the definition does with
249+
* it. It is ADDED to the reads below, never in place of them: a run that
250+
* also reads the input from another object reads that row too, so the
251+
* caller must be able to read both. Being the author's word about the
252+
* caller's value, it holds even where a `loop` or `map` later rebinds the
253+
* name, and a callee's declaration is followed through the hand-offs below
254+
* like any other callee read;
243255
* - a `get_record`, `update_record` or `delete_record` node with a literal
244256
* `objectName` whose `filter.id` is the input (one id), or whose
245257
* `filter.id.$eq` / `filter.id.$in` is (one id / a list of ids);
@@ -283,8 +295,22 @@ async function declaredReadsOf(
283295
const flow = (await getFlow(flowName)) as FlowParsed | null | undefined;
284296
if (!flow || typeof flow !== 'object') return reads;
285297
const inputs = new Set<string>();
298+
const add = (input: string, read: FlowDeclaredRecordRead): void => {
299+
const list = reads.get(input) ?? [];
300+
if (!list.some((r) => r.object === read.object && r.many === read.many)) list.push(read);
301+
reads.set(input, list);
302+
};
286303
for (const variable of Array.isArray(flow.variables) ? flow.variables : []) {
287-
if (variable && variable.isInput === true && typeof variable.name === 'string') inputs.add(variable.name);
304+
if (!variable || variable.isInput !== true || typeof variable.name !== 'string') continue;
305+
inputs.add(variable.name);
306+
// The author's own word (`objectName` on the input, #29425 ruling A):
307+
// the value is the id of one record of that object. It reads the
308+
// caller's value, so a `loop` or `map` that rebinds the name further
309+
// down does not withdraw it, and it sits beside every read the
310+
// definition makes in plain sight, never in place of one.
311+
if (typeof variable.objectName === 'string' && variable.objectName !== '') {
312+
add(variable.name, { object: variable.objectName, many: false });
313+
}
288314
}
289315
const graphs = collectFlowGraphs(flow);
290316
// A `loop` or `map` node binds its item (and index) variable over the run's
@@ -302,11 +328,6 @@ async function declaredReadsOf(
302328
}
303329
}
304330
if (inputs.size === 0) return reads;
305-
const add = (input: string, read: FlowDeclaredRecordRead): void => {
306-
const list = reads.get(input) ?? [];
307-
if (!list.some((r) => r.object === read.object && r.many === read.many)) list.push(read);
308-
reads.set(input, list);
309-
};
310331
const inputOf = (slot: unknown): string | undefined => {
311332
const name = handedOnVariable(slot);
312333
return name !== undefined && inputs.has(name) ? name : undefined;

‎packages/runtime/src/flow-start-declared-record-reads.test.ts‎

Lines changed: 207 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,10 @@
2424
* 6. **What stays as it was**: a readable id starts the run (the firing
2525
* control for every zero above), a read the definition does not declare,
2626
* the system principal.
27+
* 7. **An input the author declares a record id** (`objectName` on the
28+
* variable): loaded from the declared object at every door, read in plain
29+
* sight or not, beside any visible read of another object, followed into a
30+
* callee; the same input undeclared keeps today's rule (the control).
2731
*
2832
* The data double is ROW-SCOPED per object: each row is visible to its owner
2933
* and to nobody else, and no other id exists, so the real
@@ -84,6 +88,18 @@ const BY_COMPUTED = 'contract_by_computed';
8488
const SCREEN_EDIT = 'contract_screen_edit';
8589
const SUBFLOW_PARENT = 'contract_subflow_parent';
8690
const MAP_PARENT = 'contract_map_parent';
91+
const DECLARED = 'contract_declared';
92+
const UNDECLARED = 'contract_undeclared';
93+
const DECLARED_AND_READ = 'case_declared_contract_read';
94+
const DECLARED_CALLEE_PARENT = 'contract_declared_callee_parent';
95+
96+
/** A flow whose start input `name` the author declares a record id of `object` (`objectName`). */
97+
function declaring(def: FlowDef, input: string, object: string): FlowDef {
98+
return {
99+
...def,
100+
variables: (def.variables as Array<Record<string, unknown>>).map((v) => (v.name === input ? { ...v, objectName: object } : v)),
101+
};
102+
}
87103

88104
const FLOWS: Record<string, FlowDef> = {
89105
[BY_RECORD]: flow(BY_RECORD, ['recordId'], [getRow(CONTRACT, { id: cel('recordId') })], { runAs: 'system' }),
@@ -99,6 +115,19 @@ const FLOWS: Record<string, FlowDef> = {
99115
[MAP_PARENT]: flow(MAP_PARENT, ['contractIds'], [
100116
{ id: 'each', type: 'map', label: 'Each', config: { collection: cel('contractIds'), flowName: BY_CUSTOM, input: { contractId: cel('item') } } },
101117
]),
118+
// The declared input is read by no node: only the declaration says it is a record id.
119+
[DECLARED]: declaring(flow(DECLARED, ['contractId'], [], { runAs: 'system' }), 'contractId', CONTRACT),
120+
// The control: the same flow without the declaration.
121+
[UNDECLARED]: flow(UNDECLARED, ['contractId'], [], { runAs: 'system' }),
122+
// Declared an id of `crm_case`, and read in plain sight as an id of `crm_contract`.
123+
[DECLARED_AND_READ]: declaring(
124+
flow(DECLARED_AND_READ, ['subjectId'], [getRow(CONTRACT, { id: cel('subjectId') })], { runAs: 'system' }),
125+
'subjectId', CASE,
126+
),
127+
// Hands its own undeclared input to the declared input of a callee.
128+
[DECLARED_CALLEE_PARENT]: flow(DECLARED_CALLEE_PARENT, ['target'], [
129+
{ id: 'sub', type: 'subflow', label: 'Sub', config: { flowName: DECLARED, input: { contractId: cel('target') } } },
130+
]),
102131
};
103132

104133
/** The acting principal, as `resolveExecutionContext` builds one. */
@@ -115,7 +144,13 @@ const CUSTOM_ACTION = {
115144
params: [{ name: 'contractId', label: 'Contract', type: 'text' }],
116145
};
117146
const SCRIPT_ACTION = { name: 'touch_case', label: 'Touch', objectName: CASE, type: 'script', execute: 'return 1' };
118-
const CASE_DEF = { name: CASE, actions: [CONTRACT_ACTION, CUSTOM_ACTION, SCRIPT_ACTION] };
147+
const DECLARED_ACTION = {
148+
name: 'open_declared_contract', label: 'Open declared contract', objectName: CASE, type: 'flow', target: DECLARED,
149+
params: [{ name: 'contractId', label: 'Contract', type: 'text' }],
150+
ai: { exposed: true, description: 'Open the declared contract.' },
151+
};
152+
const UNDECLARED_ACTION = { ...DECLARED_ACTION, name: 'open_undeclared_contract', label: 'Open undeclared contract', target: UNDECLARED };
153+
const CASE_DEF = { name: CASE, actions: [CONTRACT_ACTION, CUSTOM_ACTION, SCRIPT_ACTION, DECLARED_ACTION, UNDECLARED_ACTION] };
119154
const CONTRACT_DEF = { name: CONTRACT, actions: [] };
120155
const schemaOf = (n: string) => (n === CASE ? CASE_DEF : n === CONTRACT ? CONTRACT_DEF : undefined);
121156

@@ -574,3 +609,174 @@ describe('the REST action door refuses a routed record that is not one id, befor
574609
expect(reads(h).length).toBeGreaterThan(0);
575610
});
576611
});
612+
613+
// ───────────────────────────────────────────────────────────────────────────
614+
// 7. An input the author declares a record id (`objectName`, #29425 ruling A)
615+
// ───────────────────────────────────────────────────────────────────────────
616+
617+
describe('a start input declared a record id is loaded from the declared object at every door, before the run exists', () => {
618+
const readsOf = (name: string) =>
619+
flowDeclaredRecordReads({ getFlow: async (n: string) => FLOWS[n] ?? null }, name).then((m) => Object.fromEntries(m));
620+
621+
/** The declared `type: 'flow'` endpoint door, on the real `callData`. */
622+
async function endpoint(target: string, body: unknown) {
623+
const declared = ApiEndpointSchema.parse({
624+
name: `${target}_open`, path: `/api/v1/apps/${target}/open`, method: 'POST', type: 'flow', target,
625+
});
626+
const ql = makeQl();
627+
const automation = makeAutomation();
628+
const deps: any = { resolveService: async () => undefined, getObjectQL: async () => ql };
629+
const protocolContext: any = { request: {}, environmentId: 'platform', executionContext: ec(MEMBER) };
630+
const answer = await executeEndpointTarget(
631+
buildEndpointExecutionContext({
632+
request: { method: 'POST', path: declared.path, query: {}, headers: {}, body },
633+
match: { endpoint: declared, params: {} },
634+
executionContext: ec(MEMBER) as any,
635+
environmentId: 'platform',
636+
}),
637+
{
638+
automationService: automation,
639+
callData: (action, params, dataDriver, scopeId, execCtx) =>
640+
callData(deps, protocolContext, action, params, dataDriver, scopeId, execCtx),
641+
},
642+
);
643+
return { status: answer.status, error: (answer.body as any)?.error ?? {}, ql, automation };
644+
}
645+
646+
/**
647+
* One start of `flowName` with `contractId` set to `value`, at each door that
648+
* starts a flow by name, read back as status + error + what was loaded + runs.
649+
*/
650+
const DOORS: Record<string, (flowName: string, value: unknown) => Promise<{ status: unknown; error: any; ql: any; automation: any }>> = {
651+
'POST /automation/:name/trigger': async (flowName, value) => {
652+
const h = boot(ec(MEMBER));
653+
const res = await h.trigger(flowName, { params: { contractId: value } });
654+
return { status: statusOf(res), error: errorOf(res), ql: h.ql, automation: h.automation };
655+
},
656+
'legacy POST /automation/trigger/:name': async (flowName, value) => {
657+
const h = boot(ec(MEMBER));
658+
const res = await h.trigger(flowName, { params: { contractId: value } }, true);
659+
return { status: statusOf(res), error: errorOf(res), ql: h.ql, automation: h.automation };
660+
},
661+
'a declared `type: flow` endpoint': (flowName, value) => endpoint(flowName, { params: { contractId: value } }),
662+
'REST POST /actions/:object/:action': async (flowName, value) => {
663+
const h = boot(ec(MEMBER));
664+
const action = flowName === DECLARED ? DECLARED_ACTION : UNDECLARED_ACTION;
665+
const res = await h.actions(`/${CASE}/${action.name}/${BOTH}`, { params: { contractId: value } });
666+
return { status: statusOf(res), error: errorOf(res), ql: h.ql, automation: h.automation };
667+
},
668+
'MCP run_action': async (flowName, value) => {
669+
const h = boot(ec(MEMBER));
670+
const action = flowName === DECLARED ? DECLARED_ACTION : UNDECLARED_ACTION;
671+
try {
672+
await h.runAction(action.name, { objectName: CASE, recordId: BOTH, params: { contractId: value } });
673+
return { status: 200, error: {}, ql: h.ql, automation: h.automation };
674+
} catch (err: any) {
675+
return { status: err?.status, error: err ?? {}, ql: h.ql, automation: h.automation };
676+
}
677+
},
678+
};
679+
/** Every `crm_contract` row the start loaded. */
680+
const contractReads = (ql: any) => ql.find.mock.calls.filter((c: any[]) => c[0] === CONTRACT).map((c: any[]) => c[1]?.where?.id);
681+
682+
it('the reading: a declared input is one id of the declared object, read by no node', async () => {
683+
expect(await readsOf(DECLARED)).toEqual({ contractId: [{ object: CONTRACT, many: false }] });
684+
expect(await readsOf(UNDECLARED)).toEqual({});
685+
});
686+
687+
it('the reading: a declaration sits beside a read in plain sight of another object, never in place of it', async () => {
688+
expect(await readsOf(DECLARED_AND_READ)).toEqual({
689+
subjectId: [{ object: CASE, many: false }, { object: CONTRACT, many: false }],
690+
});
691+
});
692+
693+
it('the reading: a callee\'s declared input is followed through the hand-off', async () => {
694+
expect(await readsOf(DECLARED_CALLEE_PARENT)).toEqual({ target: [{ object: CONTRACT, many: false }] });
695+
});
696+
697+
it('the reading: a loop that rebinds the name does not withdraw the declaration', async () => {
698+
const looped = declaring(flow('looped', ['x'], [
699+
{ id: 'loop', type: 'loop', label: 'Loop', config: { collection: [1], iteratorVariable: 'x', body: { nodes: [getRow(CASE, { id: cel('x') })], edges: [] } } },
700+
]), 'x', CONTRACT);
701+
const got = await flowDeclaredRecordReads({ getFlow: async () => looped }, 'looped');
702+
expect(Object.fromEntries(got)).toEqual({ x: [{ object: CONTRACT, many: false }] });
703+
});
704+
705+
for (const [door, start] of Object.entries(DOORS)) {
706+
describe(door, () => {
707+
it('a declared input naming a record the caller can read: the run starts, the firing control', async () => {
708+
const got = await start(DECLARED, BOTH);
709+
710+
expect(got.status, JSON.stringify(got.error)).toBe(200);
711+
expect(got.automation.execute).toHaveBeenCalledTimes(1);
712+
expect(contractReads(got.ql)).toContain(BOTH);
713+
});
714+
715+
it.each([
716+
['the caller cannot read', CONTRACT_OTHER],
717+
['does not exist', GHOST],
718+
])('a declared input naming a record the caller %s: 404 RECORD_NOT_FOUND, no run', async (_label, id) => {
719+
const got = await start(DECLARED, id);
720+
721+
expect(got.status).toBe(404);
722+
expect(got.error.code).toBe('RECORD_NOT_FOUND');
723+
expect(contractReads(got.ql)).toContain(id);
724+
expect(got.automation.execute).not.toHaveBeenCalled();
725+
});
726+
727+
it.each([
728+
['an object', { id: BOTH }],
729+
['a list', [BOTH]],
730+
['a boolean', true],
731+
])('a declared input given %s: 400 VALIDATION_FAILED naming the input, nothing loaded from the declared object, no run', async (_label, value) => {
732+
const got = await start(DECLARED, value);
733+
734+
expect(got.status).toBe(400);
735+
expect(got.error.code).toBe('VALIDATION_FAILED');
736+
expect(String(got.error.message)).toContain('`contractId`');
737+
expect(contractReads(got.ql)).toHaveLength(0);
738+
expect(got.automation.execute).not.toHaveBeenCalled();
739+
});
740+
741+
it('the same input undeclared, read by no node: not judged, the run starts on an id the caller cannot read (today\'s rule)', async () => {
742+
const got = await start(UNDECLARED, CONTRACT_OTHER);
743+
744+
expect(got.status, JSON.stringify(got.error)).toBe(200);
745+
expect(got.automation.execute).toHaveBeenCalledTimes(1);
746+
expect(contractReads(got.ql)).toHaveLength(0);
747+
});
748+
});
749+
}
750+
751+
it('declared one object and read from another: the caller must read the row in both', async () => {
752+
const inCaseOnly = boot(ec(MEMBER));
753+
const refused = await inCaseOnly.trigger(DECLARED_AND_READ, { params: { subjectId: CASE_ONLY } });
754+
expect(statusOf(refused)).toBe(404);
755+
expect(errorOf(refused).code).toBe('RECORD_NOT_FOUND');
756+
expect(reads(inCaseOnly)).toEqual(expect.arrayContaining([[CASE, CASE_ONLY], [CONTRACT, CASE_ONLY]]));
757+
expect(inCaseOnly.automation.execute).not.toHaveBeenCalled();
758+
759+
const inBoth = boot(ec(MEMBER));
760+
const started = await inBoth.trigger(DECLARED_AND_READ, { params: { subjectId: BOTH } });
761+
expect(statusOf(started), JSON.stringify(started?.response?.body)).toBe(200);
762+
expect(inBoth.automation.execute).toHaveBeenCalledTimes(1);
763+
});
764+
765+
it('a parent that hands its input to a callee\'s declared input is judged by the callee\'s declaration', async () => {
766+
const h = boot(ec(MEMBER));
767+
const res = await h.trigger(DECLARED_CALLEE_PARENT, { params: { target: CONTRACT_OTHER } });
768+
769+
expect(statusOf(res)).toBe(404);
770+
expect(errorOf(res).code).toBe('RECORD_NOT_FOUND');
771+
expect(h.automation.execute).not.toHaveBeenCalled();
772+
});
773+
774+
it('the system principal starts on any declared id, nothing loaded', async () => {
775+
const h = boot({ isSystem: true });
776+
const res = await h.trigger(DECLARED, { params: { contractId: CONTRACT_OTHER } });
777+
778+
expect(statusOf(res)).toBe(200);
779+
expect(h.automation.execute).toHaveBeenCalledTimes(1);
780+
expect(reads(h)).toHaveLength(0);
781+
});
782+
});

0 commit comments

Comments
 (0)