Skip to content

Commit b74652f

Browse files
committed
fix(metadata-protocol): a draft's _diagnostics reports what its publish will refuse
The draft read folds the runtime authoring gate's verdict on the stored draft body into _diagnostics: valid:false, each refused rule id as an entry's code, the publish's own message. The publish gate's body is split into judgeRuntimeAuthoringRules (the verdict) and assertRuntimeAuthoringRules (the verdict plus the throw), so the draft read and the publish read one judgement. The draft save is unchanged. Co-authored-by: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FEkQ5oVR19x7NPLf4YzCzj
1 parent 8b27638 commit b74652f

4 files changed

Lines changed: 659 additions & 18 deletions

File tree

‎packages/metadata-protocol/src/metadata-diagnostics.ts‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,11 @@ import { zodIssuesToMetadataIssues } from './protocol.js';
3737
// landed by #8300). Composed into `decorateMetadataItem` below — see the
3838
// ordering note there for why it is not applied per read exit.
3939
import { redactMetadataItem } from './metadata-redaction.js';
40+
// [#26707] The snapshot key a write type's findings are spelled under — the
41+
// runtime gate's own answer, so the publish verdict below is re-spelled
42+
// against the same prefix the gate wrote it with.
43+
import { stackKeyForType } from '@objectstack/lint/runtime';
44+
import type { RuntimeAuthoringIssue } from '@objectstack/spec/api';
4045

4146
/**
4247
* Re-export the canonical validation-result type so callers in this
@@ -316,6 +321,64 @@ export function decorateMetadataItems<T>(type: string, items: T[]): T[] {
316321
return items.map((item) => decorateMetadataItem(type, item));
317322
}
318323

324+
// ---------------------------------------------------------------------------
325+
// [#26707] The publish verdict on a draft's `_diagnostics`
326+
// ---------------------------------------------------------------------------
327+
328+
/**
329+
* A runtime-gate finding's path, re-spelled relative to the item it was found
330+
* on: the gate spells it inside its private per-write snapshot
331+
* (`flows[0].edges[1].condition`, `objects.invoice.fields.total`), and
332+
* `_diagnostics` paths are dotted and item-relative (`edges.1.condition`), the
333+
* spelling Studio's inline errors and canvas badges resolve. A path that does
334+
* not start at the written item (a finding located on a sibling, or a `where`-
335+
* style locator) is kept as the gate wrote it.
336+
*/
337+
function itemRelativeIssuePath(type: string, name: string, path: string): string {
338+
const stackKey = stackKeyForType(PLURAL_TO_SINGULAR[type] ?? type);
339+
if (!stackKey) return path;
340+
let rest: string | undefined;
341+
for (const prefix of [`${stackKey}[0]`, `${stackKey}.${name}`]) {
342+
if (path === prefix || path.startsWith(`${prefix}.`) || path.startsWith(`${prefix}[`)) {
343+
rest = path.slice(prefix.length);
344+
break;
345+
}
346+
}
347+
if (rest === undefined) return path;
348+
return rest.replace(/\[(\d+)\]/g, '.$1').replace(/^\./, '');
349+
}
350+
351+
/**
352+
* Fold what publishing a draft would refuse into the draft's `_diagnostics`.
353+
*
354+
* `issues` are the runtime authoring gate's refusal for the draft body —
355+
* `ObjectStackProtocolImplementation#draftPublishVerdict`, the judgement the
356+
* publish door enforces — and each becomes one `errors[]` entry carrying the
357+
* publish's own `message`, with its `rule` id as the entry's `code`. Any of
358+
* them makes the verdict `valid: false`: the draft is still stored, but it does
359+
* not say it is valid while the publish says it is not. No issues: the schema
360+
* verdict is returned as it was. A type with no schema verdict (`undefined`)
361+
* gets one only when there is something to report.
362+
*/
363+
export function withPublishVerdict(
364+
type: string,
365+
name: string,
366+
diagnostics: MetadataDiagnostics | undefined,
367+
issues: readonly RuntimeAuthoringIssue[],
368+
): MetadataDiagnostics | undefined {
369+
if (issues.length === 0) return diagnostics;
370+
const refusals = issues.map((issue) => ({
371+
path: itemRelativeIssuePath(type, name, issue.path),
372+
message: issue.message,
373+
code: issue.rule,
374+
}));
375+
return {
376+
...diagnostics,
377+
valid: false,
378+
errors: [...(diagnostics?.errors ?? []), ...refusals],
379+
};
380+
}
381+
319382
// ---------------------------------------------------------------------------
320383
// ADR-0047 — reference-integrity diagnostics for list views
321384
// ---------------------------------------------------------------------------

‎packages/metadata-protocol/src/protocol-authoring-gate.ts‎

Lines changed: 78 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@
4949
import type { ObjectStackProtocolImplementation } from './protocol.js';
5050
import { permissionSetOwnerBindingRefusal, runtimeHookWithoutBodyRefusal } from './protocol.js';
5151
import { evaluateRuntimeAuthoringGate } from './runtime-authoring-gate.js';
52-
import type { RuntimeAuthoringIssue, RuntimePendingDeclarations } from './runtime-authoring-gate.js';
52+
import type { RuntimeAuthoringIssue, RuntimeAuthoringVerdict, RuntimePendingDeclarations } from './runtime-authoring-gate.js';
5353
import { savedItemNameRefusal } from '@objectstack/metadata/view-container-name';
5454
import { PLURAL_TO_SINGULAR, SINGULAR_TO_PLURAL } from '@objectstack/spec/shared';
5555
import type { IObjectQLEngine } from '@objectstack/spec/contracts';
@@ -67,11 +67,13 @@ export interface AuthoringGateHost {
6767
assertRuntimeAuthoringRules: ObjectStackProtocolImplementation['assertRuntimeAuthoringRules'];
6868
readonly authoringChannel: ObjectStackProtocolImplementation['authoringChannel'];
6969
readonly authoringGates: ObjectStackProtocolImplementation['authoringGates'];
70+
collectBatchPendingDeclarations: ObjectStackProtocolImplementation['collectBatchPendingDeclarations'];
7071
credentialChannelFor: ObjectStackProtocolImplementation['credentialChannelFor'];
7172
defaultRecordPageSaveRefusal: ObjectStackProtocolImplementation['defaultRecordPageSaveRefusal'];
7273
readonly engine: ObjectStackProtocolImplementation['engine'];
7374
externalBindingSaveRefusal: ObjectStackProtocolImplementation['externalBindingSaveRefusal'];
7475
foldStoredCollection: ObjectStackProtocolImplementation['foldStoredCollection'];
76+
getOverlayRepo: ObjectStackProtocolImplementation['getOverlayRepo'];
7577
hierarchyResolverMounted: ObjectStackProtocolImplementation['hierarchyResolverMounted'];
7678
isArtifactBacked: ObjectStackProtocolImplementation['isArtifactBacked'];
7779
orgWallEnforced: ObjectStackProtocolImplementation['orgWallEnforced'];
@@ -167,9 +169,33 @@ export async function runAuthoringGate(
167169
});
168170
}
169171

172+
/**
173+
* The members {@link judgeRuntimeAuthoringRules} reads: the host facts and
174+
* collections every judgement of the shared rules is made against.
175+
*/
176+
type RuntimeRulesHost = Pick<AuthoringGateHost, 'authoringChannel' | 'engine' | 'foldStoredCollection' | 'hierarchyResolverMounted' | 'orgWallEnforced' | 'resolveSduiManifest' | 'resolveWritePackageScope' | 'rlsMembershipResolverKeys' | 'tenancyPostureInForce'>;
177+
170178
/** The body of `ObjectStackProtocolImplementation#assertRuntimeAuthoringRules`; the method's docblock there is its contract. */
171179
export async function assertRuntimeAuthoringRules(
172-
this: Pick<AuthoringGateHost, 'authoringChannel' | 'engine' | 'foldStoredCollection' | 'hierarchyResolverMounted' | 'orgWallEnforced' | 'resolveSduiManifest' | 'resolveWritePackageScope' | 'rlsMembershipResolverKeys' | 'tenancyPostureInForce'>,
180+
this: RuntimeRulesHost,
181+
evt: Parameters<typeof judgeRuntimeAuthoringRules>[0],
182+
): Promise<RuntimeAuthoringIssue[]> {
183+
const verdict = await judgeRuntimeAuthoringRules.call(this, evt);
184+
if (verdict.error) throw verdict.error;
185+
return verdict.advisories;
186+
}
187+
188+
/**
189+
* [#26707] The judgement {@link assertRuntimeAuthoringRules} enforces, handed
190+
* back instead of thrown: the gate's {@link RuntimeAuthoringVerdict}, its
191+
* refusal (`error`) beside its advisories. The assert above is this function
192+
* plus the throw, so a caller that only needs to KNOW the verdict — the draft
193+
* read's publish verdict ({@link draftPublishVerdict}) — reads the same
194+
* collections, the same host facts and the same early returns as the publish
195+
* that enforces it, and there is no second account of either.
196+
*/
197+
export async function judgeRuntimeAuthoringRules(
198+
this: RuntimeRulesHost,
173199
evt: {
174200
type: string; name: string; state: 'draft' | 'active'; body: unknown; source?: string;
175201
/**
@@ -211,7 +237,8 @@ export async function assertRuntimeAuthoringRules(
211237
* round trip for a secret it still holds.
212238
*/
213239
restoredCredentialPaths?: () => Promise<readonly string[]>;
214-
}): Promise<RuntimeAuthoringIssue[]> {
240+
}): Promise<RuntimeAuthoringVerdict> {
241+
const clean: RuntimeAuthoringVerdict = { error: null, advisories: [] };
215242
// [#6710] The ADR-0005 carve-out, now DECLARED instead of inferred.
216243
//
217244
// This line used to read `if (this.environmentId === undefined)
@@ -250,21 +277,24 @@ export async function assertRuntimeAuthoringRules(
250277
// #6710 re-keyed this activation and left that one on the retired
251278
// proxy, which cost the ADR-0090 D11 object posture gate every
252279
// host-config deployment until #7674 finished the move.
253-
if (this.authoringChannel === 'package-author') return [];
280+
if (this.authoringChannel === 'package-author') return clean;
254281
if (evt.state !== 'active') {
255282
// [#26188] D1: no rule gates a draft. The one finding a draft does hear
256283
// is a hierarchy scope this runtime cannot enforce, as a warning on the
257284
// 2xx; it needs no collection read, so the draft keeps paying none.
258285
// A `migrate-stored` pass heals storage and hears nothing (see below).
259-
if (evt.source === 'migrate-stored') return [];
286+
if (evt.source === 'migrate-stored') return clean;
260287
const hierarchyResolverMounted = this.hierarchyResolverMounted();
261-
return evaluateRuntimeAuthoringGate({
262-
type: PLURAL_TO_SINGULAR[evt.type] ?? evt.type,
263-
name: evt.name,
264-
state: evt.state,
265-
body: evt.body,
266-
...(hierarchyResolverMounted !== undefined ? { hierarchyResolverMounted } : {}),
267-
}).advisories;
288+
return {
289+
error: null,
290+
advisories: evaluateRuntimeAuthoringGate({
291+
type: PLURAL_TO_SINGULAR[evt.type] ?? evt.type,
292+
name: evt.name,
293+
state: evt.state,
294+
body: evt.body,
295+
...(hierarchyResolverMounted !== undefined ? { hierarchyResolverMounted } : {}),
296+
}).advisories,
297+
};
268298
}
269299
// `os migrate meta --stored --apply` rewrites rows that ALREADY EXIST
270300
// into the current dialect. It is not an author publishing anything —
@@ -280,7 +310,7 @@ export async function assertRuntimeAuthoringRules(
280310
// no caller can spell its way past the gate. `duplicatePackage` is
281311
// deliberately NOT here — it mints brand-new rows under new names, and
282312
// a copy of a broken flow is a new broken flow.
283-
if (evt.source === 'migrate-stored') return [];
313+
if (evt.source === 'migrate-stored') return clean;
284314
const singular = PLURAL_TO_SINGULAR[evt.type] ?? evt.type;
285315

286316
// Resolution context. Best-effort: a host without a registry (a
@@ -420,6 +450,39 @@ export async function assertRuntimeAuthoringRules(
420450
// [#26188] With it the gate refuses a hierarchy scope no resolver enforces.
421451
...(hierarchyResolverMounted !== undefined ? { hierarchyResolverMounted } : {}),
422452
});
423-
if (verdict.error) throw verdict.error;
424-
return verdict.advisories;
453+
return verdict;
454+
}
455+
456+
/** The body of `ObjectStackProtocolImplementation#draftPublishVerdict`; the method's docblock there is its contract. */
457+
export async function draftPublishVerdict(
458+
this: RuntimeRulesHost & Pick<AuthoringGateHost, 'collectBatchPendingDeclarations' | 'credentialChannelFor' | 'getOverlayRepo'>,
459+
draft: { type: string; name: string; body: unknown; packageId: string | null },
460+
): Promise<RuntimeAuthoringIssue[]> {
461+
const singular = PLURAL_TO_SINGULAR[draft.type] ?? draft.type;
462+
// The closure "Publish all" judges this draft against: its package's other
463+
// drafts, collected by the batch door's own collector from the batch door's
464+
// own listing. A package-unbound draft has no batch; its publish is the
465+
// per-item door's, which states none.
466+
let pending: RuntimePendingDeclarations | undefined;
467+
if (draft.packageId) {
468+
const repo = this.getOverlayRepo();
469+
if (typeof repo.listDrafts === 'function') {
470+
pending = await this.collectBatchPendingDeclarations(await repo.listDrafts({ packageId: draft.packageId }));
471+
}
472+
}
473+
// The promotion's restored-credential read: the stored draft holds no
474+
// credential the write-only channel holds, so the gate is told where one is.
475+
const channel = this.credentialChannelFor(singular);
476+
const verdict = await judgeRuntimeAuthoringRules.call(this, {
477+
type: singular,
478+
name: draft.name,
479+
state: 'active',
480+
body: draft.body,
481+
packageId: draft.packageId,
482+
...(pending !== undefined ? { pending } : {}),
483+
...(channel
484+
? { restoredCredentialPaths: () => channel.heldPaths({ name: draft.name, state: 'draft', item: draft.body }) }
485+
: {}),
486+
});
487+
return (verdict.error as { issues?: RuntimeAuthoringIssue[] } | null)?.issues ?? [];
425488
}

0 commit comments

Comments
 (0)