@aglyn/plugins-ai 1.0.0-beta.147 → 1.0.0-beta.149

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.
@@ -13,7 +13,8 @@
13
13
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
14
  * See the License for the specific language governing permissions and
15
15
  * limitations under the License.
16
- */ import { AI_LAYOUT_REGION_NAMES, aiBindsRepeatedItems, aiLayoutRegionOf, aiRepeatedItemCount, aiTreeLayoutRegions } from "../runtime/ai-doctrine-validators.js";
16
+ */ import { AI_LAYOUT_REGION_NAMES, aiBindsRepeatedItems, aiLayoutRegionOf, aiRepeatedItemCount, aiTreeLayoutRegions, walkTree } from "../runtime/ai-doctrine-validators.js";
17
+ import { aiBindingTokensIn } from "../model/ai-template-subjects.js";
17
18
  import { aiPlanCreation } from "./ai-job-generation.js";
18
19
  /**
19
20
  * The build held to the plan the member confirmed (AGL-3024).
@@ -41,6 +42,19 @@ import { aiPlanCreation } from "./ai-job-generation.js";
41
42
  * properties, so the planner is asked there for the one thing about a
42
43
  * layout worth promising and worth checking — a checkable assertion the
43
44
  * planner emits beside its prose, rather than English parsed out of it.
45
+ * - **A token**: `create[].fields` on a template, from the subject's own
46
+ * closed catalog (`AI_TEMPLATE_SUBJECT_DEFINITIONS[subject].tokens`), which
47
+ * is the template's analogue of a layout's regions — the one thing about a
48
+ * template that differs per record, and therefore the one worth promising.
49
+ *
50
+ * The third was added after a measured miss (AGL-3024, 2026-09-21). A brief
51
+ * asked for an attorney's bar admissions; the plan's `why` promised "a
52
+ * bar-admissions block"; the built template had no such thing and reported
53
+ * `Done`. Nothing had gone wrong in the build: `author` has six tokens —
54
+ * name, bio, image, jobTitle, worksFor, url — and no catalog anywhere fills a
55
+ * bar admission, so the promise was unkeepable when it was written. Read as a
56
+ * token list the promise cannot even be MADE, which is a better place to stop
57
+ * than after the document is paid for.
44
58
  *
45
59
  * ── It fails closed ──────────────────────────────────────────────────────
46
60
  *
@@ -156,6 +170,85 @@ import { aiPlanCreation } from "./ai-job-generation.js";
156
170
  }
157
171
  ];
158
172
  }
173
+ /** A token as the catalog spells it, for matching what a plan wrote against it. */ function tokenKey(value) {
174
+ return value.replace(/[{}\s]/g, '').toLowerCase();
175
+ }
176
+ /** Every binding token a built tree holds, spelled as the catalog spells them. */ export function aiTreeBoundTokens(tree) {
177
+ const bound = new Set();
178
+ const nodes = tree.nodes;
179
+ const strings = (value, out)=>{
180
+ if (typeof value === 'string') out.push(value);
181
+ else if (Array.isArray(value)) for (const inner of value)strings(inner, out);
182
+ else if (value && typeof value === 'object') {
183
+ for (const inner of Object.values(value))strings(inner, out);
184
+ }
185
+ return out;
186
+ };
187
+ for (const { node } of walkTree({
188
+ rootId: tree.rootId,
189
+ nodes
190
+ })){
191
+ for (const token of strings(node.props, []).flatMap(aiBindingTokensIn)){
192
+ bound.add(tokenKey(token));
193
+ }
194
+ }
195
+ return bound;
196
+ }
197
+ /**
198
+ * The subject tokens the confirmed plan's template creation names, and the
199
+ * words it named that the subject's catalog does not answer to. A plan with
200
+ * no template creation names none.
201
+ */ export function aiPlannedTemplateTokens(plan, definition) {
202
+ var _ref;
203
+ var _aiPlanCreation;
204
+ const catalog = new Map(definition.tokens.map((entry)=>[
205
+ tokenKey(entry.token),
206
+ entry.token
207
+ ]));
208
+ const tokens = new Set();
209
+ const unreadable = [];
210
+ for (const field of (_ref = (_aiPlanCreation = aiPlanCreation(plan, 'template')) == null ? void 0 : _aiPlanCreation.fields) != null ? _ref : []){
211
+ const token = catalog.get(tokenKey(field));
212
+ if (token) tokens.add(token);
213
+ else unreadable.push(field);
214
+ }
215
+ return {
216
+ tokens: [
217
+ ...tokens
218
+ ],
219
+ unreadable
220
+ };
221
+ }
222
+ /**
223
+ * The plan's promised tokens against a built template: one finding naming
224
+ * every token the plan lists that the template does not bind, and one naming
225
+ * a word the subject's catalog could not read — which is a promise this check
226
+ * cannot settle either way, and, more usefully, one the page could never have
227
+ * filled.
228
+ */ export function aiPlanTemplateTokenViolations(plan, definition, tree) {
229
+ const { tokens, unreadable } = aiPlannedTemplateTokens(plan, definition);
230
+ const violations = [];
231
+ if (tokens.length) {
232
+ const bound = aiTreeBoundTokens(tree);
233
+ const missing = tokens.filter((token)=>!bound.has(tokenKey(token)));
234
+ if (missing.length) {
235
+ const one = missing.length === 1;
236
+ violations.push({
237
+ rule: null,
238
+ code: 'plan-token-missing',
239
+ message: `The confirmed plan says this template shows ${listed(missing)}, and it binds ${one ? 'no such token' : 'no such tokens'}. Put ${one ? 'it' : 'each of them'} on the page, so every ${definition.noun.replace(/^an? /, '')} shows their own.`
240
+ });
241
+ }
242
+ }
243
+ if (unreadable.length) {
244
+ violations.push({
245
+ rule: null,
246
+ code: 'plan-token-unreadable',
247
+ message: `The confirmed plan says this template shows ${listed(unreadable)}, which ${definition.noun}'s page does not fill, so nothing can check the template shows ${unreadable.length === 1 ? 'it' : 'them'}. Promise only what the page fills: ${definition.tokens.map((entry)=>entry.token).join(', ')}.`
248
+ });
249
+ }
250
+ return violations;
251
+ }
159
252
  /** `"a"`, `"a" and "b"`, `"a", "b" and "c"`. */ function listed(values) {
160
253
  const quoted = values.map((value)=>`"${value}"`);
161
254
  return quoted.length <= 1 ? quoted.join('') : `${quoted.slice(0, -1).join(', ')} and ${quoted[quoted.length - 1]}`;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-plan-conformance.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { AiBuildPlanScreen, AiBuildPlanSection } from '../model/ai-build-plan'\nimport type { AiJobPlan } from '../model/ai-jobs.types'\nimport {\n AI_LAYOUT_REGION_NAMES,\n aiBindsRepeatedItems,\n aiLayoutRegionOf,\n aiRepeatedItemCount,\n aiTreeLayoutRegions,\n type AiDoctrineTree,\n type AiDoctrineViolation,\n type AiLayoutRegion,\n} from '../runtime/ai-doctrine-validators'\nimport { aiPlanCreation } from './ai-job-generation'\n\n/**\n * The build held to the plan the member confirmed (AGL-3024).\n *\n * The doctrine validators ask whether an artifact was built the way a careful\n * author builds one. They do not ask whether it is the artifact the plan\n * PROMISED, and a build that quietly delivers less still reports `Done` —\n * which is the dangerous part, because `Done` is what tells the customer they\n * have no reason to re-read it. Measured on beta.139: a plan promising four\n * practice areas built three cards; a plan promising a layout with a sidebar\n * built a verbatim copy of the base layout, the word \"sidebar\" nowhere in it.\n *\n * ── Structured commitments, never prose ──────────────────────────────────\n *\n * A plan's rationale (`why`) is prose a model wrote, and matching English\n * against a node tree after the fact would be a second guess dressed as a\n * check. Only the plan's STRUCTURE is read here, and only the two shapes that\n * are already numbers or names in `ai-build-plan.ts`:\n *\n * - **A count**: `screens[].sections[].items`, which the plan already\n * carries and the section prompt already states as \"It shows N items\".\n * Nothing read it back.\n * - **A region**: `create[].fields` on a layout, which is that kind's own\n * field for the regions it has (`AI_LAYOUT_REGIONS`). A layout has no\n * properties, so the planner is asked there for the one thing about a\n * layout worth promising and worth checking — a checkable assertion the\n * planner emits beside its prose, rather than English parsed out of it.\n *\n * ── It fails closed ──────────────────────────────────────────────────────\n *\n * Every function here answers \"the plan is kept\" only when it could look. A\n * layout the step never read is not a layout whose regions are present; the\n * layout door turns that into a stop for review rather than a `Done`. What it\n * will not do is guess: a count it cannot settle from the document — items a\n * collection fills at render — is not reported as short.\n *\n * The findings are ordinary `AiDoctrineViolation`s, so they ride the\n * mechanism every other rule rides: `runValidatedGeneration` re-asks the\n * model once with them, and a second answer that still breaks one stops the\n * job for a person with `aiDoctrineReview`. They carry `rule: null` on\n * purpose. The seventeen rules are how a document is BUILT; keeping the plan\n * is not one of them, and numbering these as rule 7 would print \"Rule 7\n * (Reuse before creating)\" over a finding about a count.\n */\n\n/** A count below this is not a repeat, so a plan promising one promises nothing to count. */\nexport const AI_PLAN_ITEMS_MIN = 2\n\n/**\n * The regions the confirmed plan's layout creation names, and the words it\n * named that no region answers to. A plan with no layout creation names none.\n */\nexport function aiPlannedLayoutRegions(plan: AiJobPlan | null): {\n regions: AiLayoutRegion[]\n unreadable: string[]\n} {\n const regions = new Set<AiLayoutRegion>()\n const unreadable: string[] = []\n for (const field of aiPlanCreation(plan, 'layout')?.fields ?? []) {\n const region = aiLayoutRegionOf(field)\n if (region) regions.add(region)\n else unreadable.push(field)\n }\n return { regions: [...regions], unreadable }\n}\n\n/**\n * The plan's promised regions against a built layout: one finding naming\n * every region the plan lists that the layout does not carry, and one naming\n * a word the vocabulary could not read, which is a promise this check cannot\n * settle either way.\n */\nexport function aiPlanRegionViolations(\n plan: AiJobPlan | null,\n tree: AiDoctrineTree,\n): AiDoctrineViolation[] {\n const { regions, unreadable } = aiPlannedLayoutRegions(plan)\n const built = aiTreeLayoutRegions(tree)\n const violations: AiDoctrineViolation[] = []\n const missing = regions.filter((region) => !built.has(region))\n if (missing.length) {\n const one = missing.length === 1\n violations.push({\n rule: null,\n code: 'plan-region-missing',\n message: `The confirmed plan gives this layout ${listed(\n missing,\n )}, and the layout has no ${one ? 'such region' : 'such regions'}. Build ${\n one ? 'it' : 'each of them'\n }: a sidebar is a Section whose element is aside, a header a Section whose element is header or an App Bar, a nav a Section whose element is nav, a footer a Section whose element is footer, and the main region the Layout Slot.`,\n })\n }\n if (unreadable.length) {\n violations.push({\n rule: null,\n code: 'plan-region-unreadable',\n message: `The confirmed plan gives this layout ${listed(\n unreadable,\n )}, which is no region this platform builds, so nothing can check the layout has ${\n unreadable.length === 1 ? 'it' : 'them'\n }. A layout's regions are ${AI_LAYOUT_REGION_NAMES.join(', ')}.`,\n })\n }\n return violations\n}\n\n/**\n * The plan's promised item count against a built section. Silent where there\n * is nothing to settle: a section promising fewer than `AI_PLAN_ITEMS_MIN`\n * promises no repeat, and one whose items a collection fills draws them from\n * data at render, where the document cannot be counted and rule 8 asked for\n * exactly that. Silent, too, when the section shows MORE than it promised:\n * the count is read generously (`aiRepeatedItemCount`), so a number above the\n * promise is as likely to be the reading as the section.\n */\nexport function aiPlanItemCountViolations(\n section: Pick<AiBuildPlanSection, 'name' | 'items'>,\n tree: AiDoctrineTree,\n): AiDoctrineViolation[] {\n if (section.items < AI_PLAN_ITEMS_MIN) return []\n if (aiBindsRepeatedItems(tree)) return []\n const shown = aiRepeatedItemCount(tree)\n if (shown >= section.items) return []\n return [\n {\n rule: null,\n code: 'plan-items-short',\n message: `The confirmed plan says the \"${section.name}\" section shows ${section.items} items, and this section shows ${shown}. Build all ${section.items}.`,\n },\n ]\n}\n\n/**\n * The counts the plan's sections promised against a page a COPY produced\n * (AGL-3024), read over the whole page because a copy has no section of the\n * plan's in it to read one at a time.\n *\n * A copied screen carries the SOURCE's nodes under the source's ids: nothing\n * maps \"the practice areas section\" onto a subtree of it, so the per-section\n * reading `aiPlanItemCountViolations` does at a generation pass has nothing\n * to stand on here. What can still be settled is the weaker claim, and it is\n * the one that catches the measured shape: a plan promising a section of four\n * against a copy in which NO group of four repeated things exists anywhere is\n * a promise the copy did not keep, whichever section was meant to keep it.\n *\n * Weaker on purpose, and so quieter: a copy holding six of something else\n * reads as six and is let through. A screen carries no app bar and no footer\n * — those are its layout's — so what is counted is the page's own content.\n */\nexport function aiPlanCopiedPageViolations(\n screen: Pick<AiBuildPlanScreen, 'sections'>,\n tree: AiDoctrineTree,\n): AiDoctrineViolation[] {\n const promised = screen.sections\n .filter((section) => section.items >= AI_PLAN_ITEMS_MIN)\n .sort((a, b) => b.items - a.items)[0]\n if (!promised) return []\n if (aiBindsRepeatedItems(tree)) return []\n const shown = aiRepeatedItemCount(tree)\n if (shown >= promised.items) return []\n return [\n {\n rule: null,\n code: 'plan-items-short',\n message: `The confirmed plan says the \"${promised.name}\" section shows ${promised.items} items, and this page is a copy that shows at most ${shown} of anything. Build the ${promised.items}.`,\n },\n ]\n}\n\n/** `\"a\"`, `\"a\" and \"b\"`, `\"a\", \"b\" and \"c\"`. */\nfunction listed(values: readonly string[]): string {\n const quoted = values.map((value) => `\"${value}\"`)\n return quoted.length <= 1\n ? quoted.join('')\n : `${quoted.slice(0, -1).join(', ')} and ${quoted[quoted.length - 1]}`\n}\n"],"names":["AI_LAYOUT_REGION_NAMES","aiBindsRepeatedItems","aiLayoutRegionOf","aiRepeatedItemCount","aiTreeLayoutRegions","aiPlanCreation","AI_PLAN_ITEMS_MIN","aiPlannedLayoutRegions","plan","regions","Set","unreadable","field","fields","region","add","push","aiPlanRegionViolations","tree","built","violations","missing","filter","has","length","one","rule","code","message","listed","join","aiPlanItemCountViolations","section","items","shown","name","aiPlanCopiedPageViolations","screen","promised","sections","sort","a","b","values","quoted","map","value","slice"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAID,SACEA,sBAAsB,EACtBC,oBAAoB,EACpBC,gBAAgB,EAChBC,mBAAmB,EACnBC,mBAAmB,QAId,uCAAmC;AAC1C,SAASC,cAAc,QAAQ,yBAAqB;AAEpD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA0CC,GAED,2FAA2F,GAC3F,OAAO,MAAMC,oBAAoB,EAAC;AAElC;;;CAGC,GACD,OAAO,SAASC,uBAAuBC,IAAsB;;QAMvCH;IAFpB,MAAMI,UAAU,IAAIC;IACpB,MAAMC,aAAuB,EAAE;IAC/B,KAAK,MAAMC,kBAASP,kBAAAA,eAAeG,MAAM,8BAArBH,gBAAgCQ,MAAM,mBAAI,EAAE,CAAE;QAChE,MAAMC,SAASZ,iBAAiBU;QAChC,IAAIE,QAAQL,QAAQM,GAAG,CAACD;aACnBH,WAAWK,IAAI,CAACJ;IACvB;IACA,OAAO;QAA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EC,MAAM,YAAY,EAAEF,QAAQC,KAAK,CAAC,CAAC,CAAC;QAC7J;KACD;AACH;AAEA;;;;;;;;;;;;;;;;CAgBC,GACD,OAAO,SAASG,2BACdC,MAA2C,EAC3CnB,IAAoB;IAEpB,MAAMoB,WAAWD,OAAOE,QAAQ,CAC7BjB,MAAM,CAAC,CAACU,UAAYA,QAAQC,KAAK,IAAI3B,mBACrCkC,IAAI,CAAC,CAACC,GAAGC,IAAMA,EAAET,KAAK,GAAGQ,EAAER,KAAK,CAAC,CAAC,EAAE;IACvC,IAAI,CAACK,UAAU,OAAO,EAAE;IACxB,IAAIrC,qBAAqBiB,OAAO,OAAO,EAAE;IACzC,MAAMgB,QAAQ/B,oBAAoBe;IAClC,IAAIgB,SAASI,SAASL,KAAK,EAAE,OAAO,EAAE;IACtC,OAAO;QACL;YACEP,MAAM;YACNC,MAAM;YACNC,SAAS,CAAC,6BAA6B,EAAEU,SAASH,IAAI,CAAC,gBAAgB,EAAEG,SAASL,KAAK,CAAC,mDAAmD,EAAEC,MAAM,wBAAwB,EAAEI,SAASL,KAAK,CAAC,CAAC,CAAC;QAChM;KACD;AACH;AAEA,8CAA8C,GAC9C,SAASJ,OAAOc,MAAyB;IACvC,MAAMC,SAASD,OAAOE,GAAG,CAAC,CAACC,QAAU,CAAC,CAAC,EAAEA,MAAM,CAAC,CAAC;IACjD,OAAOF,OAAOpB,MAAM,IAAI,IACpBoB,OAAOd,IAAI,CAAC,MACZ,GAAGc,OAAOG,KAAK,CAAC,GAAG,CAAC,GAAGjB,IAAI,CAAC,MAAM,KAAK,EAAEc,MAAM,CAACA,OAAOpB,MAAM,GAAG,EAAE,EAAE;AAC1E"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-plan-conformance.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { AiBuildPlanScreen, AiBuildPlanSection } from '../model/ai-build-plan'\nimport type { AiJobPlan } from '../model/ai-jobs.types'\nimport {\n AI_LAYOUT_REGION_NAMES,\n aiBindsRepeatedItems,\n aiLayoutRegionOf,\n aiRepeatedItemCount,\n aiTreeLayoutRegions,\n walkTree,\n type AiDoctrineNode,\n type AiDoctrineTree,\n type AiDoctrineViolation,\n type AiLayoutRegion,\n} from '../runtime/ai-doctrine-validators'\nimport { aiBindingTokensIn, type AiTemplateSubjectDefinition } from '../model/ai-template-subjects'\nimport { aiPlanCreation } from './ai-job-generation'\n\n/**\n * The build held to the plan the member confirmed (AGL-3024).\n *\n * The doctrine validators ask whether an artifact was built the way a careful\n * author builds one. They do not ask whether it is the artifact the plan\n * PROMISED, and a build that quietly delivers less still reports `Done` —\n * which is the dangerous part, because `Done` is what tells the customer they\n * have no reason to re-read it. Measured on beta.139: a plan promising four\n * practice areas built three cards; a plan promising a layout with a sidebar\n * built a verbatim copy of the base layout, the word \"sidebar\" nowhere in it.\n *\n * ── Structured commitments, never prose ──────────────────────────────────\n *\n * A plan's rationale (`why`) is prose a model wrote, and matching English\n * against a node tree after the fact would be a second guess dressed as a\n * check. Only the plan's STRUCTURE is read here, and only the two shapes that\n * are already numbers or names in `ai-build-plan.ts`:\n *\n * - **A count**: `screens[].sections[].items`, which the plan already\n * carries and the section prompt already states as \"It shows N items\".\n * Nothing read it back.\n * - **A region**: `create[].fields` on a layout, which is that kind's own\n * field for the regions it has (`AI_LAYOUT_REGIONS`). A layout has no\n * properties, so the planner is asked there for the one thing about a\n * layout worth promising and worth checking — a checkable assertion the\n * planner emits beside its prose, rather than English parsed out of it.\n * - **A token**: `create[].fields` on a template, from the subject's own\n * closed catalog (`AI_TEMPLATE_SUBJECT_DEFINITIONS[subject].tokens`), which\n * is the template's analogue of a layout's regions — the one thing about a\n * template that differs per record, and therefore the one worth promising.\n *\n * The third was added after a measured miss (AGL-3024, 2026-09-21). A brief\n * asked for an attorney's bar admissions; the plan's `why` promised \"a\n * bar-admissions block\"; the built template had no such thing and reported\n * `Done`. Nothing had gone wrong in the build: `author` has six tokens —\n * name, bio, image, jobTitle, worksFor, url — and no catalog anywhere fills a\n * bar admission, so the promise was unkeepable when it was written. Read as a\n * token list the promise cannot even be MADE, which is a better place to stop\n * than after the document is paid for.\n *\n * ── It fails closed ──────────────────────────────────────────────────────\n *\n * Every function here answers \"the plan is kept\" only when it could look. A\n * layout the step never read is not a layout whose regions are present; the\n * layout door turns that into a stop for review rather than a `Done`. What it\n * will not do is guess: a count it cannot settle from the document — items a\n * collection fills at render — is not reported as short.\n *\n * The findings are ordinary `AiDoctrineViolation`s, so they ride the\n * mechanism every other rule rides: `runValidatedGeneration` re-asks the\n * model once with them, and a second answer that still breaks one stops the\n * job for a person with `aiDoctrineReview`. They carry `rule: null` on\n * purpose. The seventeen rules are how a document is BUILT; keeping the plan\n * is not one of them, and numbering these as rule 7 would print \"Rule 7\n * (Reuse before creating)\" over a finding about a count.\n */\n\n/** A count below this is not a repeat, so a plan promising one promises nothing to count. */\nexport const AI_PLAN_ITEMS_MIN = 2\n\n/**\n * The regions the confirmed plan's layout creation names, and the words it\n * named that no region answers to. A plan with no layout creation names none.\n */\nexport function aiPlannedLayoutRegions(plan: AiJobPlan | null): {\n regions: AiLayoutRegion[]\n unreadable: string[]\n} {\n const regions = new Set<AiLayoutRegion>()\n const unreadable: string[] = []\n for (const field of aiPlanCreation(plan, 'layout')?.fields ?? []) {\n const region = aiLayoutRegionOf(field)\n if (region) regions.add(region)\n else unreadable.push(field)\n }\n return { regions: [...regions], unreadable }\n}\n\n/**\n * The plan's promised regions against a built layout: one finding naming\n * every region the plan lists that the layout does not carry, and one naming\n * a word the vocabulary could not read, which is a promise this check cannot\n * settle either way.\n */\nexport function aiPlanRegionViolations(\n plan: AiJobPlan | null,\n tree: AiDoctrineTree,\n): AiDoctrineViolation[] {\n const { regions, unreadable } = aiPlannedLayoutRegions(plan)\n const built = aiTreeLayoutRegions(tree)\n const violations: AiDoctrineViolation[] = []\n const missing = regions.filter((region) => !built.has(region))\n if (missing.length) {\n const one = missing.length === 1\n violations.push({\n rule: null,\n code: 'plan-region-missing',\n message: `The confirmed plan gives this layout ${listed(\n missing,\n )}, and the layout has no ${one ? 'such region' : 'such regions'}. Build ${\n one ? 'it' : 'each of them'\n }: a sidebar is a Section whose element is aside, a header a Section whose element is header or an App Bar, a nav a Section whose element is nav, a footer a Section whose element is footer, and the main region the Layout Slot.`,\n })\n }\n if (unreadable.length) {\n violations.push({\n rule: null,\n code: 'plan-region-unreadable',\n message: `The confirmed plan gives this layout ${listed(\n unreadable,\n )}, which is no region this platform builds, so nothing can check the layout has ${\n unreadable.length === 1 ? 'it' : 'them'\n }. A layout's regions are ${AI_LAYOUT_REGION_NAMES.join(', ')}.`,\n })\n }\n return violations\n}\n\n/**\n * The plan's promised item count against a built section. Silent where there\n * is nothing to settle: a section promising fewer than `AI_PLAN_ITEMS_MIN`\n * promises no repeat, and one whose items a collection fills draws them from\n * data at render, where the document cannot be counted and rule 8 asked for\n * exactly that. Silent, too, when the section shows MORE than it promised:\n * the count is read generously (`aiRepeatedItemCount`), so a number above the\n * promise is as likely to be the reading as the section.\n */\nexport function aiPlanItemCountViolations(\n section: Pick<AiBuildPlanSection, 'name' | 'items'>,\n tree: AiDoctrineTree,\n): AiDoctrineViolation[] {\n if (section.items < AI_PLAN_ITEMS_MIN) return []\n if (aiBindsRepeatedItems(tree)) return []\n const shown = aiRepeatedItemCount(tree)\n if (shown >= section.items) return []\n return [\n {\n rule: null,\n code: 'plan-items-short',\n message: `The confirmed plan says the \"${section.name}\" section shows ${section.items} items, and this section shows ${shown}. Build all ${section.items}.`,\n },\n ]\n}\n\n/**\n * The counts the plan's sections promised against a page a COPY produced\n * (AGL-3024), read over the whole page because a copy has no section of the\n * plan's in it to read one at a time.\n *\n * A copied screen carries the SOURCE's nodes under the source's ids: nothing\n * maps \"the practice areas section\" onto a subtree of it, so the per-section\n * reading `aiPlanItemCountViolations` does at a generation pass has nothing\n * to stand on here. What can still be settled is the weaker claim, and it is\n * the one that catches the measured shape: a plan promising a section of four\n * against a copy in which NO group of four repeated things exists anywhere is\n * a promise the copy did not keep, whichever section was meant to keep it.\n *\n * Weaker on purpose, and so quieter: a copy holding six of something else\n * reads as six and is let through. A screen carries no app bar and no footer\n * — those are its layout's — so what is counted is the page's own content.\n */\nexport function aiPlanCopiedPageViolations(\n screen: Pick<AiBuildPlanScreen, 'sections'>,\n tree: AiDoctrineTree,\n): AiDoctrineViolation[] {\n const promised = screen.sections\n .filter((section) => section.items >= AI_PLAN_ITEMS_MIN)\n .sort((a, b) => b.items - a.items)[0]\n if (!promised) return []\n if (aiBindsRepeatedItems(tree)) return []\n const shown = aiRepeatedItemCount(tree)\n if (shown >= promised.items) return []\n return [\n {\n rule: null,\n code: 'plan-items-short',\n message: `The confirmed plan says the \"${promised.name}\" section shows ${promised.items} items, and this page is a copy that shows at most ${shown} of anything. Build the ${promised.items}.`,\n },\n ]\n}\n\n/** A token as the catalog spells it, for matching what a plan wrote against it. */\nfunction tokenKey(value: string): string {\n return value.replace(/[{}\\s]/g, '').toLowerCase()\n}\n\n/** Every binding token a built tree holds, spelled as the catalog spells them. */\nexport function aiTreeBoundTokens(tree: AiDoctrineTree): Set<string> {\n const bound = new Set<string>()\n const nodes = tree.nodes as unknown as Record<string, AiDoctrineNode>\n const strings = (value: unknown, out: string[]): string[] => {\n if (typeof value === 'string') out.push(value)\n else if (Array.isArray(value)) for (const inner of value) strings(inner, out)\n else if (value && typeof value === 'object') {\n for (const inner of Object.values(value as Record<string, unknown>)) strings(inner, out)\n }\n return out\n }\n for (const { node } of walkTree({ rootId: tree.rootId, nodes })) {\n for (const token of strings(node.props, []).flatMap(aiBindingTokensIn)) {\n bound.add(tokenKey(token))\n }\n }\n return bound\n}\n\n/**\n * The subject tokens the confirmed plan's template creation names, and the\n * words it named that the subject's catalog does not answer to. A plan with\n * no template creation names none.\n */\nexport function aiPlannedTemplateTokens(\n plan: AiJobPlan | null,\n definition: AiTemplateSubjectDefinition,\n): { tokens: string[]; unreadable: string[] } {\n const catalog = new Map(definition.tokens.map((entry) => [tokenKey(entry.token), entry.token]))\n const tokens = new Set<string>()\n const unreadable: string[] = []\n for (const field of aiPlanCreation(plan, 'template')?.fields ?? []) {\n const token = catalog.get(tokenKey(field))\n if (token) tokens.add(token)\n else unreadable.push(field)\n }\n return { tokens: [...tokens], unreadable }\n}\n\n/**\n * The plan's promised tokens against a built template: one finding naming\n * every token the plan lists that the template does not bind, and one naming\n * a word the subject's catalog could not read — which is a promise this check\n * cannot settle either way, and, more usefully, one the page could never have\n * filled.\n */\nexport function aiPlanTemplateTokenViolations(\n plan: AiJobPlan | null,\n definition: AiTemplateSubjectDefinition,\n tree: AiDoctrineTree,\n): AiDoctrineViolation[] {\n const { tokens, unreadable } = aiPlannedTemplateTokens(plan, definition)\n const violations: AiDoctrineViolation[] = []\n if (tokens.length) {\n const bound = aiTreeBoundTokens(tree)\n const missing = tokens.filter((token) => !bound.has(tokenKey(token)))\n if (missing.length) {\n const one = missing.length === 1\n violations.push({\n rule: null,\n code: 'plan-token-missing',\n message: `The confirmed plan says this template shows ${listed(missing)}, and it binds ${\n one ? 'no such token' : 'no such tokens'\n }. Put ${one ? 'it' : 'each of them'} on the page, so every ${\n definition.noun.replace(/^an? /, '')\n } shows their own.`,\n })\n }\n }\n if (unreadable.length) {\n violations.push({\n rule: null,\n code: 'plan-token-unreadable',\n message: `The confirmed plan says this template shows ${listed(\n unreadable,\n )}, which ${definition.noun}'s page does not fill, so nothing can check the template shows ${\n unreadable.length === 1 ? 'it' : 'them'\n }. Promise only what the page fills: ${definition.tokens\n .map((entry) => entry.token)\n .join(', ')}.`,\n })\n }\n return violations\n}\n\n/** `\"a\"`, `\"a\" and \"b\"`, `\"a\", \"b\" and \"c\"`. */\nfunction listed(values: readonly string[]): string {\n const quoted = values.map((value) => `\"${value}\"`)\n return quoted.length <= 1\n ? quoted.join('')\n : `${quoted.slice(0, -1).join(', ')} and ${quoted[quoted.length - 1]}`\n}\n"],"names":["AI_LAYOUT_REGION_NAMES","aiBindsRepeatedItems","aiLayoutRegionOf","aiRepeatedItemCount","aiTreeLayoutRegions","walkTree","aiBindingTokensIn","aiPlanCreation","AI_PLAN_ITEMS_MIN","aiPlannedLayoutRegions","plan","regions","Set","unreadable","field","fields","region","add","push","aiPlanRegionViolations","tree","built","violations","missing","filter","has","length","one","rule","code","message","listed","join","aiPlanItemCountViolations","section","items","shown","name","aiPlanCopiedPageViolations","screen","promised","sections","sort","a","b","tokenKey","value","replace","toLowerCase","aiTreeBoundTokens","bound","nodes","strings","out","Array","isArray","inner","Object","values","node","rootId","token","props","flatMap","aiPlannedTemplateTokens","definition","catalog","Map","tokens","map","entry","get","aiPlanTemplateTokenViolations","noun","quoted","slice"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAID,SACEA,sBAAsB,EACtBC,oBAAoB,EACpBC,gBAAgB,EAChBC,mBAAmB,EACnBC,mBAAmB,EACnBC,QAAQ,QAKH,uCAAmC;AAC1C,SAASC,iBAAiB,QAA0C,mCAA+B;AACnG,SAASC,cAAc,QAAQ,yBAAqB;AAEpD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuDC,GAED,2FAA2F,GAC3F,OAAO,MAAMC,oBAAoB,EAAC;AAElC;;;CAGC,GACD,OAAO,SAASC,uBAAuBC,IAAsB;;QAMvCH;IAFpB,MAAMI,UAAU,IAAIC;IACpB,MAAMC,aAAuB,EAAE;IAC/B,KAAK,MAAMC,kBAASP,kBAAAA,eAAeG,MAAM,8BAArBH,gBAAgCQ,MAAM,mBAA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CAACqC,QAAU,CAACX,MAAMzB,GAAG,CAACoB,SAASgB;QAC7D,IAAItC,QAAQG,MAAM,EAAE;YAClB,MAAMC,MAAMJ,QAAQG,MAAM,KAAK;YAC/BJ,WAAWJ,IAAI,CAAC;gBACdU,MAAM;gBACNC,MAAM;gBACNC,SAAS,CAAC,4CAA4C,EAAEC,OAAOR,SAAS,eAAe,EACrFI,MAAM,kBAAkB,iBACzB,MAAM,EAAEA,MAAM,OAAO,eAAe,uBAAuB,EAC1DsC,WAAWQ,IAAI,CAAC1B,OAAO,CAAC,SAAS,IAClC,iBAAiB,CAAC;YACrB;QACF;IACF;IACA,IAAIlC,WAAWa,MAAM,EAAE;QACrBJ,WAAWJ,IAAI,CAAC;YACdU,MAAM;YACNC,MAAM;YACNC,SAAS,CAAC,4CAA4C,EAAEC,OACtDlB,YACA,QAAQ,EAAEoD,WAAWQ,IAAI,CAAC,+DAA+D,EACzF5D,WAAWa,MAAM,KAAK,IAAI,OAAO,OAClC,oCAAoC,EAAEuC,WAAWG,MAAM,CACrDC,GAAG,CAAC,CAACC,QAAUA,MAAMT,KAAK,EAC1B7B,IAAI,CAAC,MAAM,CAAC,CAAC;QAClB;IACF;IACA,OAAOV;AACT;AAEA,8CAA8C,GAC9C,SAASS,OAAO2B,MAAyB;IACvC,MAAMgB,SAAShB,OAAOW,GAAG,CAAC,CAACvB,QAAU,CAAC,CAAC,EAAEA,MAAM,CAAC,CAAC;IACjD,OAAO4B,OAAOhD,MAAM,IAAI,IACpBgD,OAAO1C,IAAI,CAAC,MACZ,GAAG0C,OAAOC,KAAK,CAAC,GAAG,CAAC,GAAG3C,IAAI,CAAC,MAAM,KAAK,EAAE0C,MAAM,CAACA,OAAOhD,MAAM,GAAG,EAAE,EAAE;AAC1E"}
@@ -84,6 +84,20 @@ export declare const AI_JOB_PLAN_REVIEW_COPY = "The plan is ready. Review what t
84
84
  * never in a system block the platform's cache entry is keyed on.
85
85
  */
86
86
  export declare function aiJobPlanPrompt(job: Pick<AiJob, 'kind' | 'brief' | 'inputs'>, capabilities?: AiPlanCapabilities | null): string;
87
+ /**
88
+ * What a TEMPLATE job's plan is told its creation's `fields` are (AGL-3143
89
+ * §11): the subject's binding tokens, listed so the planner promises only
90
+ * what the page can fill and the build can be held to it
91
+ * (`aiPlanTemplateTokenViolations`).
92
+ *
93
+ * ⛔ It rides the job's own turn and NOT the `fields` description in the plan
94
+ * tool, which every kind's request caches. Written there it read better and
95
+ * cost 40 tokens of the shared prefix — 2,980 to 3,020 — which is one credit
96
+ * of the Free page's 300-credit wall, taking the room it keeps for a re-asked
97
+ * section from 45 credits to 44 and breaking `ai-job-free-page.spec.ts`. A
98
+ * page job must not pay for a sentence about templates.
99
+ */
100
+ export declare function aiPlanTemplateTokenLines(job: Pick<AiJob, 'kind' | 'inputs'>): string[];
87
101
  /** A kind that builds only some plans: the creations it makes, and the shapes it refuses. */
88
102
  export interface AiJobPlanScope extends AiPlanJobScope {
89
103
  /** Why a job of the kind cannot build a plan of this shape; `null` when it can. Pure. */
@@ -16,6 +16,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
16
16
  * limitations under the License.
17
17
  */ import { createHash } from "node:crypto";
18
18
  import { AI_BUILD_PLAN_TOOL, isAiPlanNewRef } from "../model/ai-build-plan.js";
19
+ import { AI_TEMPLATE_SUBJECT_DEFINITIONS } from "../model/ai-template-subjects.js";
19
20
  import { AI_PAGE_CREATE_KINDS, aiPagePlanShapeRefusal } from "../model/ai-page-job.js";
20
21
  import { aiPlanCapabilitiesForJob, aiPlanCapabilityLines } from "../model/ai-plan-capabilities.js";
21
22
  import { AI_SITE_CREATE_KINDS, aiSitePlanShapeRefusal } from "../model/ai-site-job.js";
@@ -104,8 +105,31 @@ import { AI_JOBS_COLLECTION, registerAiJobPlanStep } from "./ai-jobs.js";
104
105
  }
105
106
  }
106
107
  if (capabilities) lines.push(...aiPlanCapabilityLines(capabilities));
108
+ lines.push(...aiPlanTemplateTokenLines(job));
107
109
  return lines.join('\n');
108
110
  }
111
+ /**
112
+ * What a TEMPLATE job's plan is told its creation's `fields` are (AGL-3143
113
+ * §11): the subject's binding tokens, listed so the planner promises only
114
+ * what the page can fill and the build can be held to it
115
+ * (`aiPlanTemplateTokenViolations`).
116
+ *
117
+ * ⛔ It rides the job's own turn and NOT the `fields` description in the plan
118
+ * tool, which every kind's request caches. Written there it read better and
119
+ * cost 40 tokens of the shared prefix — 2,980 to 3,020 — which is one credit
120
+ * of the Free page's 300-credit wall, taking the room it keeps for a re-asked
121
+ * section from 45 credits to 44 and breaking `ai-job-free-page.spec.ts`. A
122
+ * page job must not pay for a sentence about templates.
123
+ */ export function aiPlanTemplateTokenLines(job) {
124
+ var _job_inputs;
125
+ if (job.kind !== 'template') return [];
126
+ const subject = ((_job_inputs = job.inputs) != null ? _job_inputs : {})['subject'];
127
+ const definition = typeof subject === 'string' ? AI_TEMPLATE_SUBJECT_DEFINITIONS[subject] : undefined;
128
+ if (!definition) return [];
129
+ return [
130
+ `The template's fields are the binding tokens its page shows, each one of: ${definition.tokens.map((entry)=>entry.token).join(', ')}. Promise only what the page fills.`
131
+ ];
132
+ }
109
133
  /**
110
134
  * The kinds whose confirm door builds only some plans (AGL-3030). A page job
111
135
  * builds one screen and a scaffold four to eight; each builds only the
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-plan-step.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { createHash } from 'node:crypto'\nimport type { AglynOrgBilling } from '@aglyn/aglyn/foundation/definitions/org-billing.types'\nimport {\n AI_BUILD_PLAN_TOOL,\n isAiPlanNewRef,\n type AiBuildPlan,\n} from '../model/ai-build-plan'\nimport type { AiJob, AiJobKind, AiJobPlan, AiJobStatus } from '../model/ai-jobs.types'\nimport { AI_PAGE_CREATE_KINDS, aiPagePlanShapeRefusal } from '../model/ai-page-job'\nimport {\n aiPlanCapabilitiesForJob,\n aiPlanCapabilityLines,\n type AiPlanCapabilities,\n type AiPlanJobScope,\n} from '../model/ai-plan-capabilities'\nimport type { AiSiteInventory } from '../model/ai-site-inventory'\nimport { AI_SITE_CREATE_KINDS, aiSitePlanShapeRefusal } from '../model/ai-site-job'\nimport { aiDoctrineSystemBlocks, runValidatedGeneration } from '../runtime/ai-doctrine'\nimport { AI_STEP_TIERS } from '../providers/catalog'\nimport type { AiDoctrineViolation } from '../runtime/ai-doctrine-validators'\nimport { AI_ROUTING_TABLE, aiModelForStep } from '../providers/routing'\nimport type { AiSystemBlock } from '../runtime/ai-runtime'\nimport { readSiteInventory } from '../runtime/site-inventory'\nimport { aiJobAdmissionRefusal } from './ai-job-admission'\nimport { readAiPlanCapabilities } from './ai-job-drafts'\nimport {\n AI_JOB_BRIEF_MAX_CHARS,\n type AiJobStepOutcome,\n type AiJobStepRunner,\n} from './ai-job-text-step'\nimport { aiJobStepBudget } from './ai-job-budget'\nimport { aiDoctrineReview, aiUnspentOutcome } from './ai-job-generation'\nimport { aiPlanWithDraftIds } from './ai-job-draft-ids'\nimport { AI_JOBS_COLLECTION, registerAiJobPlanStep } from './ai-jobs'\n\n/**\n * The plan step (AGL-2935): the first step of every job that builds site\n * structure. Before a node is generated, the model answers with a typed plan\n * — what the site already has that the job reuses, what it creates and why,\n * and the screens it builds from them — held to the doctrine's plan rules\n * against the site's inventory and re-asked once when it breaks one.\n *\n * A plan that passes is kept on the job, and the job stops for review: the\n * member reads what it will build before a credit is spent building it, and\n * confirms through the resume door. A plan that still breaks a rule on its\n * re-ask stops the job the same way, with the rules named. Either way the\n * step writes nothing itself; the machine records the plan, the spend and\n * the stop, as it records every step.\n *\n * ── Told what it may create, refused what it cannot build (AGL-3030) ─────\n *\n * Before it asks, the step reads what the job may create on its site: the\n * workspace's plan, the site's counts against its limits, and — for a kind\n * that builds only some plans — what the job builds itself. The user turn\n * states it, the plan rules refuse a creation outside it with the one re-ask,\n * and where the workspace keeps no reusable components they accept the page\n * built inline. A plan the confirm door would still refuse — the kind's own\n * admission, handed the plan, as the resume door hands it — is refused HERE,\n * before a member is shown a Confirm: the job fails with the door's sentence,\n * its plan is not kept, and it holds nothing.\n */\n\n/** The plan step's own instructions, cached after the doctrine. */\nexport const AI_JOB_PLAN_INSTRUCTIONS: readonly AiSystemBlock[] = [\n {\n text:\n 'You plan what a website builder job will build, before anything is built. You are given the kind of job and the brief from the person who owns the site. ' +\n 'Answer with submit_build_plan: what the site inventory already has that the job reuses, what it must create and why nothing listed will do, and each screen it builds with its layout, template, slug, search title, search description and sections from top to bottom. ' +\n 'Refer to inventory records by id and to what the plan creates as new:<name>. Plan only what the brief asks for: a component, layout, template, form or email job plans no screens unless the brief asks for pages, and a page job plans exactly one screen.',\n },\n]\n\n/**\n * The plan step's time (AGL-3026, AGL-3036): its two inventory-lookup rounds,\n * its answer and its re-ask at the routing table's ceiling for `job.plan`, on\n * the tier that step kind is served from, with the step's reads and writes,\n * at the rates `ai-job-budget.ts` assumes — fitted to what a beat can give a\n * step, so the served tier asks a little under the routing ceiling.\n */\nexport const AI_JOB_PLAN_STEP_BUDGET = aiJobStepBudget({\n tier: AI_STEP_TIERS['job.plan'],\n maxTokens: AI_ROUTING_TABLE['job.plan'].maxTokens,\n})\n\n/**\n * The least time a plan needs before it starts. Registered with the step, so\n * an inline door never starts a plan. A plan thinks before it answers and\n * routinely runs past an inline door's budget, and a provider call that\n * budget cuts off is still generated and billed upstream while the meter\n * records nothing. The beat starts a plan only with this much of its own\n * budget left, and a spec holds it inside that budget.\n */\nexport const AI_JOB_PLAN_STEP_MINIMUM_MS = AI_JOB_PLAN_STEP_BUDGET.minimumMs\n\n/**\n * The plan's answer ceiling on the model a job runs: the most whose worst\n * case fits the least time the step registered, and never more than the\n * routing table's. A model the catalog does not know is planned at the\n * slowest.\n */\nexport function aiJobPlanMaxTokens(model: string): number {\n return AI_JOB_PLAN_STEP_BUDGET.maxTokens(model)\n}\n\n/** What the member reads while a plan waits for them. */\nexport const AI_JOB_PLAN_REVIEW_COPY =\n 'The plan is ready. Review what the job will reuse and create, then confirm it to build.'\n\n/**\n * The job as the plan step's user turn: its kind, its brief, its scalar\n * inputs and, where the job read them, what it may create on its site\n * (AGL-3030). Per workspace and per site, which is why they ride here and\n * never in a system block the platform's cache entry is keyed on.\n */\nexport function aiJobPlanPrompt(\n job: Pick<AiJob, 'kind' | 'brief' | 'inputs'>,\n capabilities: AiPlanCapabilities | null = null,\n): string {\n const lines = [`Job kind: ${job.kind}`, `Brief: ${job.brief.slice(0, AI_JOB_BRIEF_MAX_CHARS)}`]\n for (const [key, value] of Object.entries(job.inputs ?? {})) {\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {\n lines.push(`${key}: ${String(value)}`)\n }\n }\n if (capabilities) lines.push(...aiPlanCapabilityLines(capabilities))\n return lines.join('\\n')\n}\n\n/** A kind that builds only some plans: the creations it makes, and the shapes it refuses. */\nexport interface AiJobPlanScope extends AiPlanJobScope {\n /** Why a job of the kind cannot build a plan of this shape; `null` when it can. Pure. */\n shapeRefusal: (plan: AiBuildPlan) => string | null\n}\n\n/**\n * The kinds whose confirm door builds only some plans (AGL-3030). A page job\n * builds one screen and a scaffold four to eight; each builds only the\n * creations its list names. Every other planned kind builds its own one\n * output, and its plan is held to the workspace alone.\n */\nexport const AI_JOB_PLAN_SCOPES: Readonly<Partial<Record<AiJobKind, AiJobPlanScope>>> = {\n page: { noun: 'a page job', creates: AI_PAGE_CREATE_KINDS, shapeRefusal: aiPagePlanShapeRefusal },\n site: { noun: 'a site scaffold', creates: AI_SITE_CREATE_KINDS, shapeRefusal: aiSitePlanShapeRefusal },\n}\n\n/** A kind's shape refusal as the violation the plan's one re-ask names. */\nfunction shapeViolations(scope: AiJobPlanScope | null): ((plan: AiBuildPlan) => AiDoctrineViolation[]) | undefined {\n if (!scope) return undefined\n return (plan) => {\n const message = scope.shapeRefusal(plan)\n return message ? [{ rule: null, code: 'plan-job-shape', message }] : []\n }\n}\n\n/**\n * The inventory names of every id the plan references, so the proposal reads\n * \"the Services layout\" rather than an id — kept on the plan because the\n * inventory is not read again when the member opens it.\n */\nexport function aiPlanLabels(\n plan: AiBuildPlan,\n inventory: AiSiteInventory | null,\n): Record<string, string> {\n const names = new Map<string, string>()\n for (const rows of [\n inventory?.components,\n inventory?.layouts,\n inventory?.templates,\n inventory?.forms,\n inventory?.datasets,\n inventory?.collections,\n inventory?.screens,\n ]) {\n for (const row of rows ?? []) names.set(row.id, row.name)\n }\n const refs = [\n ...plan.reuse.map((entry) => entry.id),\n ...plan.create.map((entry) => entry.duplicateOf),\n ...plan.screens.flatMap((screen) => [\n screen.layout,\n screen.template,\n screen.duplicateOf,\n ...screen.sections.flatMap((section) => section.uses),\n ]),\n ]\n const labels: Record<string, string> = {}\n for (const ref of refs) {\n if (!ref || isAiPlanNewRef(ref)) continue\n const name = names.get(ref)\n if (name) labels[ref] = name\n }\n return labels\n}\n\n/* ------------------------------------------------------------------------ *\n * Reusing an identical brief's plan\n * ------------------------------------------------------------------------ */\n\n/**\n * How long a plan may be reused for (AGL-2937).\n *\n * The window is what makes reuse safe rather than merely cheap. The key\n * already covers everything the request said — the brief, the inputs, the\n * model and the prompt as rendered, site inventory included — so a plan is\n * reused only when nothing the model was shown has changed. What the key\n * cannot see is the world outside the request: a page published, a component\n * renamed after the inventory was read, a member who meant something\n * different the second time. Fifteen minutes is short enough that the answer\n * is still the one the site would give, and long enough to cover what reuse\n * is actually for — the same brief run twice in a sitting, a job resubmitted\n * after a refused reservation, two members starting the same work.\n */\nexport const AI_PLAN_REUSE_WINDOW_MS = 15 * 60 * 1_000\n\n/** Jobs one lookup reads. More than one can share a key; the newest plan wins. */\nexport const AI_PLAN_REUSE_CANDIDATES = 5\n\n/** A job whose plan might be reused, as the finder reports it. */\nexport interface AiJobPlanCandidate {\n jobId: string\n status: AiJobStatus\n plan: AiJobPlan\n}\n\n/**\n * The digest a plan is reused by: the whole request, never the answer.\n *\n * It hashes what the model was asked and what it was shown — the job's kind\n * and site, the user turn (which carries the trimmed brief and every scalar\n * input), the model that would answer, every rendered system block including\n * the site inventory, and the tool's schema. Two requests that hash the same\n * would have been sent the same bytes to the same model, so the second can\n * keep the first's answer.\n *\n * The version tag is the escape hatch: anything that changes what a key\n * MEANS, rather than what it covers, bumps it and strands every old key\n * harmlessly, since a key nothing matches simply asks the model.\n */\nexport function aiJobPlanKey(input: {\n job: Pick<AiJob, 'kind' | 'hostId'>\n prompt: string\n model: string\n system: readonly AiSystemBlock[]\n}): string {\n const digest = createHash('sha256')\n for (const part of [\n 'plan.v1',\n input.job.kind,\n input.job.hostId ?? '',\n input.model,\n input.prompt,\n ...input.system.map((block) => block.text),\n JSON.stringify(AI_BUILD_PLAN_TOOL),\n ]) {\n // Length-prefixed, so two different splits of the same characters cannot\n // collide by running into one another.\n digest.update(`${part.length}:${part}\\u0000`)\n }\n return digest.digest('hex')\n}\n\n/** A job that could not have produced a reusable plan, whatever its key says. */\nconst UNREUSABLE: readonly AiJobStatus[] = ['canceled', 'failed']\n\nfunction planMillis(plan: AiJobPlan): number | null {\n const at = plan.proposedAt as unknown\n if (at instanceof Date) return at.getTime()\n if (at && typeof (at as { toMillis?: unknown }).toMillis === 'function') {\n return (at as { toMillis(): number }).toMillis()\n }\n return null\n}\n\n/**\n * The newest plan worth reusing out of what the finder returned: another\n * job's, still proposed or already confirmed, on a job that was neither\n * canceled nor failed, proposed inside the window.\n *\n * A canceled or failed job is excluded even though its plan may be perfectly\n * good: those are the jobs a member walked away from, and handing their plan\n * to the next one would make a rejected answer look like a fresh one.\n */\nexport function aiReusablePlan(\n candidates: readonly AiJobPlanCandidate[],\n context: { jobId: string; now: Date },\n): AiJobPlanCandidate | null {\n const floor = context.now.getTime() - AI_PLAN_REUSE_WINDOW_MS\n let best: AiJobPlanCandidate | null = null\n let bestAt = -1\n for (const candidate of candidates) {\n if (candidate.jobId === context.jobId) continue\n if (UNREUSABLE.includes(candidate.status)) continue\n if (candidate.plan.status !== 'proposed' && candidate.plan.status !== 'confirmed') continue\n const at = planMillis(candidate.plan)\n if (at === null || at < floor || at > context.now.getTime()) continue\n if (at > bestAt) {\n best = candidate\n bestAt = at\n }\n }\n return best\n}\n\nexport type AiJobPlanFinder = (\n orgId: string,\n key: string,\n firestore?: FirebaseFirestore.Firestore,\n) => Promise<AiJobPlanCandidate[]>\n\n/**\n * The finder the step uses in production: an equality on `plan.key` inside\n * the org's own jobs.\n *\n * One equality on one field, with no ordering beside it, so Firestore's\n * automatic single-field index answers it and no composite index is deployed.\n * The window and the statuses are applied in memory instead, which is what\n * keeps it that way.\n */\nexport const findAiJobsByPlanKey: AiJobPlanFinder = async (orgId, key, firestore) => {\n if (!firestore) return []\n const snapshot = await firestore\n .collection('orgs')\n .doc(orgId)\n .collection(AI_JOBS_COLLECTION)\n .where('plan.key', '==', key)\n .limit(AI_PLAN_REUSE_CANDIDATES)\n .get()\n return snapshot.docs.flatMap((doc) => {\n const data = doc.data() as { status?: AiJobStatus; plan?: AiJobPlan | null }\n return data.plan\n ? [{ jobId: doc.id, status: data.status ?? 'queued', plan: data.plan }]\n : []\n })\n}\n\n/** What a job may create on its site, read for the plan step; `null` for no site. */\nexport type AiPlanCapabilitiesReader = (input: {\n job: AiJob\n org: Partial<AglynOrgBilling> | null\n firestore: FirebaseFirestore.Firestore\n}) => Promise<AiPlanCapabilities | null>\n\n/** The reader the step uses in production: the draft bands' own arithmetic, for the job's site. */\nexport const readAiJobPlanCapabilities: AiPlanCapabilitiesReader = async ({ job, org, firestore }) =>\n job.hostId ? readAiPlanCapabilities(firestore, { hostId: job.hostId, org }) : null\n\nexport interface AiJobPlanStepDeps {\n /** The inventory reader; specs hand in a fake. */\n readInventory?: typeof readSiteInventory\n /** The reuse lookup; specs hand in a fake, and `null` turns reuse off. */\n findPlansByKey?: AiJobPlanFinder | null\n /** What the job may create on its site (AGL-3030); specs and the eval recorder hand in their own. */\n readCapabilities?: AiPlanCapabilitiesReader\n /** The kind's admission, asked of a plan before it is kept; the registry's otherwise. */\n admissionRefusal?: typeof aiJobAdmissionRefusal\n}\n\nexport function createAiJobPlanStep(deps: AiJobPlanStepDeps = {}): AiJobStepRunner {\n const readInventory = deps.readInventory ?? readSiteInventory\n const findPlansByKey =\n deps.findPlansByKey === undefined ? findAiJobsByPlanKey : deps.findPlansByKey\n const readCapabilities = deps.readCapabilities ?? readAiJobPlanCapabilities\n const admissionRefusal = deps.admissionRefusal ?? aiJobAdmissionRefusal\n return async ({ job, now, signal, firestore, modelFor, org: orgDocument }) => {\n const org = (orgDocument ?? null) as Partial<AglynOrgBilling> | null\n const [inventory, workspace] = await Promise.all([\n job.hostId ? readInventory(job.orgId, job.hostId, { firestore }) : Promise.resolve(null),\n readCapabilities({ job, org, firestore }),\n ])\n const scope = AI_JOB_PLAN_SCOPES[job.kind] ?? null\n const capabilities = workspace ? aiPlanCapabilitiesForJob(workspace, scope) : null\n // The model switch's answer for this job (AGL-2942): the creator's pick\n // where the plan, the org restriction and the allotment allowlists allow\n // it, and Auto held to those same lists otherwise. Without a resolver the\n // doctrine asks the routing table itself.\n const model = modelFor?.('job.plan')\n const route = AI_ROUTING_TABLE['job.plan']\n const prompt = aiJobPlanPrompt(job, capabilities)\n\n /**\n * The confirm door's answer for this plan, asked before the plan is kept\n * (AGL-3030): the kind's own admission, handed the plan as the resume\n * door hands it. A refusal fails the job with the door's sentence; a door\n * that could not answer keeps the plan, since the resume door asks again\n * before anything is built.\n */\n const refusalOnKeep = async (plan: AiJobPlan, outcome: AiJobStepOutcome): Promise<AiJobStepOutcome | null> => {\n let refusal: Awaited<ReturnType<typeof aiJobAdmissionRefusal>> = null\n try {\n refusal = await admissionRefusal(job.kind, {\n firestore,\n orgId: job.orgId,\n hostId: job.hostId ?? null,\n inputs: job.inputs ?? {},\n org,\n plan,\n uid: job.createdBy,\n })\n } catch (error) {\n console.error('ai plan admission failed', { orgId: job.orgId, jobId: job.$id, error })\n }\n return refusal ? { ...outcome, failure: refusal.error } : null\n }\n\n // Reuse before asking (AGL-2937). The key covers the whole request, so a\n // hit is a request that would have been sent the same bytes to the same\n // model; the window covers what the key cannot see. A reused plan spends\n // nothing, so the machine's spent-nothing branch releases the reservation\n // and meters no credit, and the job still stops for the member to confirm\n // — this job's plan is proposed to this member, whatever the last one did\n // with theirs.\n const resolved = model ?? aiModelForStep('job.plan')\n const key = aiJobPlanKey({\n job,\n prompt,\n model: resolved,\n system: aiDoctrineSystemBlocks(inventory, { instructions: AI_JOB_PLAN_INSTRUCTIONS }),\n })\n const reused = findPlansByKey\n ? aiReusablePlan(await findPlansByKey(job.orgId, key, firestore), {\n jobId: job.$id,\n now,\n })\n : null\n if (reused) {\n // The reused plan's draft ids name the other job's drafts; this job's are its own.\n const plan: AiJobPlan = aiPlanWithDraftIds(job.kind, {\n ...reused.plan,\n status: 'proposed',\n labels: aiPlanLabels(reused.plan, inventory),\n proposedAt: now as unknown as AiJobPlan['proposedAt'],\n confirmedAt: null,\n confirmedBy: null,\n key,\n reusedFrom: reused.jobId,\n })\n const unspent = aiUnspentOutcome(resolved)\n return (\n (await refusalOnKeep(plan, unspent)) ?? {\n ...unspent,\n plan,\n review: { reason: 'plan', message: AI_JOB_PLAN_REVIEW_COPY, findings: [] },\n }\n )\n }\n\n const result = await runValidatedGeneration('plan', {\n step: 'job.plan',\n ...(model ? { model } : {}),\n instructions: AI_JOB_PLAN_INSTRUCTIONS,\n inventory,\n messages: [{ role: 'user', content: prompt }],\n tool: AI_BUILD_PLAN_TOOL,\n // The routing ceiling, lowered on a tier too slow to look records up,\n // answer and ask again inside the least time the step registered.\n maxTokens: aiJobPlanMaxTokens(resolved),\n ...(route.thinking ? { thinking: route.thinking } : {}),\n ...(route.effort ? { effort: route.effort } : {}),\n ...(signal ? { signal } : {}),\n capabilities,\n extend: shapeViolations(scope),\n })\n const spent: AiJobStepOutcome = {\n outputs: [],\n usage: result.usage,\n estCostUsd: result.estCostUsd,\n model: result.model,\n stopReason: result.stopReason,\n ...(result.effort ? { effort: result.effort } : {}),\n }\n if (result.status === 'refused') return { ...spent, refused: true }\n if (result.status === 'needs_input') return { ...spent, review: aiDoctrineReview(result) }\n // Each draft the plan decides is named as the plan is kept, before anything is built (AGL-3079).\n const plan: AiJobPlan = aiPlanWithDraftIds(job.kind, {\n ...result.value,\n status: 'proposed',\n labels: aiPlanLabels(result.value, inventory),\n // A Date the Admin SDK stores as a timestamp, like every instant the machine writes.\n proposedAt: now as unknown as AiJobPlan['proposedAt'],\n confirmedAt: null,\n confirmedBy: null,\n key,\n })\n return (\n (await refusalOnKeep(plan, spent)) ?? {\n ...spent,\n plan,\n review: { reason: 'plan', message: AI_JOB_PLAN_REVIEW_COPY, findings: [] },\n }\n )\n }\n}\n\nexport const runAiJobPlanStep = createAiJobPlanStep()\n\n/**\n * Registers the plan step every planned kind runs first, with the least time\n * a plan needs; the plugin's console surface calls it.\n */\nexport function registerAiJobPlan(): void {\n registerAiJobPlanStep(runAiJobPlanStep, { minimumMs: AI_JOB_PLAN_STEP_MINIMUM_MS })\n}\n"],"names":["createHash","AI_BUILD_PLAN_TOOL","isAiPlanNewRef","AI_PAGE_CREATE_KINDS","aiPagePlanShapeRefusal","aiPlanCapabilitiesForJob","aiPlanCapabilityLines","AI_SITE_CREATE_KINDS","aiSitePlanShapeRefusal","aiDoctrineSystemBlocks","runValidatedGeneration","AI_STEP_TIERS","AI_ROUTING_TABLE","aiModelForStep","readSiteInventory","aiJobAdmissionRefusal","readAiPlanCapabilities","AI_JOB_BRIEF_MAX_CHARS","aiJobStepBudget","aiDoctrineReview","aiUnspentOutcome","aiPlanWithDraftIds","AI_JOBS_COLLECTION","registerAiJobPlanStep","AI_JOB_PLAN_INSTRUCTIONS","text","AI_JOB_PLAN_STEP_BUDGET","tier","maxTokens","AI_JOB_PLAN_STEP_MINIMUM_MS","minimumMs","aiJobPlanMaxTokens","model","AI_JOB_PLAN_REVIEW_COPY","aiJobPlanPrompt","job","capabilities","lines","kind","brief","slice","key","value","Object","entries","inputs","push","String","join","AI_JOB_PLAN_SCOPES","page","noun","creates","shapeRefusal","site","shapeViolations","scope","undefined","plan","message","rule","code","aiPlanLabels","inventory","names","Map","rows","components","layouts","templates","forms","datasets","collections","screens","row","set","id","name","refs","reuse","map","entry","create","duplicateOf","flatMap","screen","layout","template","sections","section","uses","labels","ref","get","AI_PLAN_REUSE_WINDOW_MS","AI_PLAN_REUSE_CANDIDATES","aiJobPlanKey","input","digest","part","hostId","prompt","system","block","JSON","stringify","update","length","UNREUSABLE","planMillis","at","proposedAt","Date","getTime","toMillis","aiReusablePlan","candidates","context","floor","now","best","bestAt","candidate","jobId","includes","status","findAiJobsByPlanKey","orgId","firestore","snapshot","collection","doc","where","limit","docs","data","readAiJobPlanCapabilities","org","createAiJobPlanStep","deps","readInventory","findPlansByKey","readCapabilities","admissionRefusal","signal","modelFor","orgDocument","workspace","Promise","all","resolve","route","refusalOnKeep","outcome","refusal","uid","createdBy","error","console","$id","failure","resolved","instructions","reused","confirmedAt","confirmedBy","reusedFrom","unspent","review","reason","findings","result","step","messages","role","content","tool","thinking","effort","extend","spent","outputs","usage","estCostUsd","stopReason","refused","runAiJobPlanStep","registerAiJobPlan"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,QAAQ,cAAa;AAExC,SACEC,kBAAkB,EAClBC,cAAc,QAET,4BAAwB;AAE/B,SAASC,oBAAoB,EAAEC,sBAAsB,QAAQ,0BAAsB;AACnF,SACEC,wBAAwB,EACxBC,qBAAqB,QAGhB,mCAA+B;AAEtC,SAASC,oBAAoB,EAAEC,sBAAsB,QAAQ,0BAAsB;AACnF,SAASC,sBAAsB,EA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AAOZ,QAAQrJ,iBAAiBwJ;;QACjF,iGAAiG;QACjG,MAAMjH,OAAkBrC,mBAAmBc,IAAIG,IAAI,EAAE,aAChDqI,OAAOjI,KAAK;YACfmF,QAAQ;YACRlC,QAAQ7B,aAAa6G,OAAOjI,KAAK,EAAEqB;YACnC,qFAAqF;YACrFgD,YAAYQ;YACZ6C,aAAa;YACbC,aAAa;YACb5H;;QAEF,QACG,OAAA,MAAM+G,cAAc9F,MAAM0H,kBAA1B,OAAqC,aACjCA;YACH1H;YACA8G,QAAQ;gBAAEC,QAAQ;gBAAQ9G,SAAS1B;gBAAyByI,UAAU,EAAE;YAAC;;IAG/E;AACF;AAEA,OAAO,MAAMgB,mBAAmBhD,sBAAqB;AAErD;;;CAGC,GACD,OAAO,SAASiD;IACdpK,sBAAsBmK,kBAAkB;QAAE5J,WAAWD;IAA4B;AACnF"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-plan-step.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { createHash } from 'node:crypto'\nimport type { AglynOrgBilling } from '@aglyn/aglyn/foundation/definitions/org-billing.types'\nimport {\n AI_BUILD_PLAN_TOOL,\n isAiPlanNewRef,\n type AiBuildPlan,\n} from '../model/ai-build-plan'\nimport type { AiJob, AiJobKind, AiJobPlan, AiJobStatus } from '../model/ai-jobs.types'\nimport {\n AI_TEMPLATE_SUBJECT_DEFINITIONS,\n type AiTemplateSubject,\n} from '../model/ai-template-subjects'\nimport { AI_PAGE_CREATE_KINDS, aiPagePlanShapeRefusal } from '../model/ai-page-job'\nimport {\n aiPlanCapabilitiesForJob,\n aiPlanCapabilityLines,\n type AiPlanCapabilities,\n type AiPlanJobScope,\n} from '../model/ai-plan-capabilities'\nimport type { AiSiteInventory } from '../model/ai-site-inventory'\nimport { AI_SITE_CREATE_KINDS, aiSitePlanShapeRefusal } from '../model/ai-site-job'\nimport { aiDoctrineSystemBlocks, runValidatedGeneration } from '../runtime/ai-doctrine'\nimport { AI_STEP_TIERS } from '../providers/catalog'\nimport type { AiDoctrineViolation } from '../runtime/ai-doctrine-validators'\nimport { AI_ROUTING_TABLE, aiModelForStep } from '../providers/routing'\nimport type { AiSystemBlock } from '../runtime/ai-runtime'\nimport { readSiteInventory } from '../runtime/site-inventory'\nimport { aiJobAdmissionRefusal } from './ai-job-admission'\nimport { readAiPlanCapabilities } from './ai-job-drafts'\nimport {\n AI_JOB_BRIEF_MAX_CHARS,\n type AiJobStepOutcome,\n type AiJobStepRunner,\n} from './ai-job-text-step'\nimport { aiJobStepBudget } from './ai-job-budget'\nimport { aiDoctrineReview, aiUnspentOutcome } from './ai-job-generation'\nimport { aiPlanWithDraftIds } from './ai-job-draft-ids'\nimport { AI_JOBS_COLLECTION, registerAiJobPlanStep } from './ai-jobs'\n\n/**\n * The plan step (AGL-2935): the first step of every job that builds site\n * structure. Before a node is generated, the model answers with a typed plan\n * — what the site already has that the job reuses, what it creates and why,\n * and the screens it builds from them — held to the doctrine's plan rules\n * against the site's inventory and re-asked once when it breaks one.\n *\n * A plan that passes is kept on the job, and the job stops for review: the\n * member reads what it will build before a credit is spent building it, and\n * confirms through the resume door. A plan that still breaks a rule on its\n * re-ask stops the job the same way, with the rules named. Either way the\n * step writes nothing itself; the machine records the plan, the spend and\n * the stop, as it records every step.\n *\n * ── Told what it may create, refused what it cannot build (AGL-3030) ─────\n *\n * Before it asks, the step reads what the job may create on its site: the\n * workspace's plan, the site's counts against its limits, and — for a kind\n * that builds only some plans — what the job builds itself. The user turn\n * states it, the plan rules refuse a creation outside it with the one re-ask,\n * and where the workspace keeps no reusable components they accept the page\n * built inline. A plan the confirm door would still refuse — the kind's own\n * admission, handed the plan, as the resume door hands it — is refused HERE,\n * before a member is shown a Confirm: the job fails with the door's sentence,\n * its plan is not kept, and it holds nothing.\n */\n\n/** The plan step's own instructions, cached after the doctrine. */\nexport const AI_JOB_PLAN_INSTRUCTIONS: readonly AiSystemBlock[] = [\n {\n text:\n 'You plan what a website builder job will build, before anything is built. You are given the kind of job and the brief from the person who owns the site. ' +\n 'Answer with submit_build_plan: what the site inventory already has that the job reuses, what it must create and why nothing listed will do, and each screen it builds with its layout, template, slug, search title, search description and sections from top to bottom. ' +\n 'Refer to inventory records by id and to what the plan creates as new:<name>. Plan only what the brief asks for: a component, layout, template, form or email job plans no screens unless the brief asks for pages, and a page job plans exactly one screen.',\n },\n]\n\n/**\n * The plan step's time (AGL-3026, AGL-3036): its two inventory-lookup rounds,\n * its answer and its re-ask at the routing table's ceiling for `job.plan`, on\n * the tier that step kind is served from, with the step's reads and writes,\n * at the rates `ai-job-budget.ts` assumes — fitted to what a beat can give a\n * step, so the served tier asks a little under the routing ceiling.\n */\nexport const AI_JOB_PLAN_STEP_BUDGET = aiJobStepBudget({\n tier: AI_STEP_TIERS['job.plan'],\n maxTokens: AI_ROUTING_TABLE['job.plan'].maxTokens,\n})\n\n/**\n * The least time a plan needs before it starts. Registered with the step, so\n * an inline door never starts a plan. A plan thinks before it answers and\n * routinely runs past an inline door's budget, and a provider call that\n * budget cuts off is still generated and billed upstream while the meter\n * records nothing. The beat starts a plan only with this much of its own\n * budget left, and a spec holds it inside that budget.\n */\nexport const AI_JOB_PLAN_STEP_MINIMUM_MS = AI_JOB_PLAN_STEP_BUDGET.minimumMs\n\n/**\n * The plan's answer ceiling on the model a job runs: the most whose worst\n * case fits the least time the step registered, and never more than the\n * routing table's. A model the catalog does not know is planned at the\n * slowest.\n */\nexport function aiJobPlanMaxTokens(model: string): number {\n return AI_JOB_PLAN_STEP_BUDGET.maxTokens(model)\n}\n\n/** What the member reads while a plan waits for them. */\nexport const AI_JOB_PLAN_REVIEW_COPY =\n 'The plan is ready. Review what the job will reuse and create, then confirm it to build.'\n\n/**\n * The job as the plan step's user turn: its kind, its brief, its scalar\n * inputs and, where the job read them, what it may create on its site\n * (AGL-3030). Per workspace and per site, which is why they ride here and\n * never in a system block the platform's cache entry is keyed on.\n */\nexport function aiJobPlanPrompt(\n job: Pick<AiJob, 'kind' | 'brief' | 'inputs'>,\n capabilities: AiPlanCapabilities | null = null,\n): string {\n const lines = [`Job kind: ${job.kind}`, `Brief: ${job.brief.slice(0, AI_JOB_BRIEF_MAX_CHARS)}`]\n for (const [key, value] of Object.entries(job.inputs ?? {})) {\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {\n lines.push(`${key}: ${String(value)}`)\n }\n }\n if (capabilities) lines.push(...aiPlanCapabilityLines(capabilities))\n lines.push(...aiPlanTemplateTokenLines(job))\n return lines.join('\\n')\n}\n\n/**\n * What a TEMPLATE job's plan is told its creation's `fields` are (AGL-3143\n * §11): the subject's binding tokens, listed so the planner promises only\n * what the page can fill and the build can be held to it\n * (`aiPlanTemplateTokenViolations`).\n *\n * ⛔ It rides the job's own turn and NOT the `fields` description in the plan\n * tool, which every kind's request caches. Written there it read better and\n * cost 40 tokens of the shared prefix — 2,980 to 3,020 — which is one credit\n * of the Free page's 300-credit wall, taking the room it keeps for a re-asked\n * section from 45 credits to 44 and breaking `ai-job-free-page.spec.ts`. A\n * page job must not pay for a sentence about templates.\n */\nexport function aiPlanTemplateTokenLines(job: Pick<AiJob, 'kind' | 'inputs'>): string[] {\n if (job.kind !== 'template') return []\n const subject = (job.inputs ?? {})['subject']\n const definition =\n typeof subject === 'string'\n ? AI_TEMPLATE_SUBJECT_DEFINITIONS[subject as AiTemplateSubject]\n : undefined\n if (!definition) return []\n return [\n `The template's fields are the binding tokens its page shows, each one of: ${definition.tokens\n .map((entry) => entry.token)\n .join(', ')}. Promise only what the page fills.`,\n ]\n}\n\n/** A kind that builds only some plans: the creations it makes, and the shapes it refuses. */\nexport interface AiJobPlanScope extends AiPlanJobScope {\n /** Why a job of the kind cannot build a plan of this shape; `null` when it can. Pure. */\n shapeRefusal: (plan: AiBuildPlan) => string | null\n}\n\n/**\n * The kinds whose confirm door builds only some plans (AGL-3030). A page job\n * builds one screen and a scaffold four to eight; each builds only the\n * creations its list names. Every other planned kind builds its own one\n * output, and its plan is held to the workspace alone.\n */\nexport const AI_JOB_PLAN_SCOPES: Readonly<Partial<Record<AiJobKind, AiJobPlanScope>>> = {\n page: { noun: 'a page job', creates: AI_PAGE_CREATE_KINDS, shapeRefusal: aiPagePlanShapeRefusal },\n site: { noun: 'a site scaffold', creates: AI_SITE_CREATE_KINDS, shapeRefusal: aiSitePlanShapeRefusal },\n}\n\n/** A kind's shape refusal as the violation the plan's one re-ask names. */\nfunction shapeViolations(scope: AiJobPlanScope | null): ((plan: AiBuildPlan) => AiDoctrineViolation[]) | undefined {\n if (!scope) return undefined\n return (plan) => {\n const message = scope.shapeRefusal(plan)\n return message ? [{ rule: null, code: 'plan-job-shape', message }] : []\n }\n}\n\n/**\n * The inventory names of every id the plan references, so the proposal reads\n * \"the Services layout\" rather than an id — kept on the plan because the\n * inventory is not read again when the member opens it.\n */\nexport function aiPlanLabels(\n plan: AiBuildPlan,\n inventory: AiSiteInventory | null,\n): Record<string, string> {\n const names = new Map<string, string>()\n for (const rows of [\n inventory?.components,\n inventory?.layouts,\n inventory?.templates,\n inventory?.forms,\n inventory?.datasets,\n inventory?.collections,\n inventory?.screens,\n ]) {\n for (const row of rows ?? []) names.set(row.id, row.name)\n }\n const refs = [\n ...plan.reuse.map((entry) => entry.id),\n ...plan.create.map((entry) => entry.duplicateOf),\n ...plan.screens.flatMap((screen) => [\n screen.layout,\n screen.template,\n screen.duplicateOf,\n ...screen.sections.flatMap((section) => section.uses),\n ]),\n ]\n const labels: Record<string, string> = {}\n for (const ref of refs) {\n if (!ref || isAiPlanNewRef(ref)) continue\n const name = names.get(ref)\n if (name) labels[ref] = name\n }\n return labels\n}\n\n/* ------------------------------------------------------------------------ *\n * Reusing an identical brief's plan\n * ------------------------------------------------------------------------ */\n\n/**\n * How long a plan may be reused for (AGL-2937).\n *\n * The window is what makes reuse safe rather than merely cheap. The key\n * already covers everything the request said — the brief, the inputs, the\n * model and the prompt as rendered, site inventory included — so a plan is\n * reused only when nothing the model was shown has changed. What the key\n * cannot see is the world outside the request: a page published, a component\n * renamed after the inventory was read, a member who meant something\n * different the second time. Fifteen minutes is short enough that the answer\n * is still the one the site would give, and long enough to cover what reuse\n * is actually for — the same brief run twice in a sitting, a job resubmitted\n * after a refused reservation, two members starting the same work.\n */\nexport const AI_PLAN_REUSE_WINDOW_MS = 15 * 60 * 1_000\n\n/** Jobs one lookup reads. More than one can share a key; the newest plan wins. */\nexport const AI_PLAN_REUSE_CANDIDATES = 5\n\n/** A job whose plan might be reused, as the finder reports it. */\nexport interface AiJobPlanCandidate {\n jobId: string\n status: AiJobStatus\n plan: AiJobPlan\n}\n\n/**\n * The digest a plan is reused by: the whole request, never the answer.\n *\n * It hashes what the model was asked and what it was shown — the job's kind\n * and site, the user turn (which carries the trimmed brief and every scalar\n * input), the model that would answer, every rendered system block including\n * the site inventory, and the tool's schema. Two requests that hash the same\n * would have been sent the same bytes to the same model, so the second can\n * keep the first's answer.\n *\n * The version tag is the escape hatch: anything that changes what a key\n * MEANS, rather than what it covers, bumps it and strands every old key\n * harmlessly, since a key nothing matches simply asks the model.\n */\nexport function aiJobPlanKey(input: {\n job: Pick<AiJob, 'kind' | 'hostId'>\n prompt: string\n model: string\n system: readonly AiSystemBlock[]\n}): string {\n const digest = createHash('sha256')\n for (const part of [\n 'plan.v1',\n input.job.kind,\n input.job.hostId ?? '',\n input.model,\n input.prompt,\n ...input.system.map((block) => block.text),\n JSON.stringify(AI_BUILD_PLAN_TOOL),\n ]) {\n // Length-prefixed, so two different splits of the same characters cannot\n // collide by running into one another.\n digest.update(`${part.length}:${part}\\u0000`)\n }\n return digest.digest('hex')\n}\n\n/** A job that could not have produced a reusable plan, whatever its key says. */\nconst UNREUSABLE: readonly AiJobStatus[] = ['canceled', 'failed']\n\nfunction planMillis(plan: AiJobPlan): number | null {\n const at = plan.proposedAt as unknown\n if (at instanceof Date) return at.getTime()\n if (at && typeof (at as { toMillis?: unknown }).toMillis === 'function') {\n return (at as { toMillis(): number }).toMillis()\n }\n return null\n}\n\n/**\n * The newest plan worth reusing out of what the finder returned: another\n * job's, still proposed or already confirmed, on a job that was neither\n * canceled nor failed, proposed inside the window.\n *\n * A canceled or failed job is excluded even though its plan may be perfectly\n * good: those are the jobs a member walked away from, and handing their plan\n * to the next one would make a rejected answer look like a fresh one.\n */\nexport function aiReusablePlan(\n candidates: readonly AiJobPlanCandidate[],\n context: { jobId: string; now: Date },\n): AiJobPlanCandidate | null {\n const floor = context.now.getTime() - AI_PLAN_REUSE_WINDOW_MS\n let best: AiJobPlanCandidate | null = null\n let bestAt = -1\n for (const candidate of candidates) {\n if (candidate.jobId === context.jobId) continue\n if (UNREUSABLE.includes(candidate.status)) continue\n if (candidate.plan.status !== 'proposed' && candidate.plan.status !== 'confirmed') continue\n const at = planMillis(candidate.plan)\n if (at === null || at < floor || at > context.now.getTime()) continue\n if (at > bestAt) {\n best = candidate\n bestAt = at\n }\n }\n return best\n}\n\nexport type AiJobPlanFinder = (\n orgId: string,\n key: string,\n firestore?: FirebaseFirestore.Firestore,\n) => Promise<AiJobPlanCandidate[]>\n\n/**\n * The finder the step uses in production: an equality on `plan.key` inside\n * the org's own jobs.\n *\n * One equality on one field, with no ordering beside it, so Firestore's\n * automatic single-field index answers it and no composite index is deployed.\n * The window and the statuses are applied in memory instead, which is what\n * keeps it that way.\n */\nexport const findAiJobsByPlanKey: AiJobPlanFinder = async (orgId, key, firestore) => {\n if (!firestore) return []\n const snapshot = await firestore\n .collection('orgs')\n .doc(orgId)\n .collection(AI_JOBS_COLLECTION)\n .where('plan.key', '==', key)\n .limit(AI_PLAN_REUSE_CANDIDATES)\n .get()\n return snapshot.docs.flatMap((doc) => {\n const data = doc.data() as { status?: AiJobStatus; plan?: AiJobPlan | null }\n return data.plan\n ? [{ jobId: doc.id, status: data.status ?? 'queued', plan: data.plan }]\n : []\n })\n}\n\n/** What a job may create on its site, read for the plan step; `null` for no site. */\nexport type AiPlanCapabilitiesReader = (input: {\n job: AiJob\n org: Partial<AglynOrgBilling> | null\n firestore: FirebaseFirestore.Firestore\n}) => Promise<AiPlanCapabilities | null>\n\n/** The reader the step uses in production: the draft bands' own arithmetic, for the job's site. */\nexport const readAiJobPlanCapabilities: AiPlanCapabilitiesReader = async ({ job, org, firestore }) =>\n job.hostId ? readAiPlanCapabilities(firestore, { hostId: job.hostId, org }) : null\n\nexport interface AiJobPlanStepDeps {\n /** The inventory reader; specs hand in a fake. */\n readInventory?: typeof readSiteInventory\n /** The reuse lookup; specs hand in a fake, and `null` turns reuse off. */\n findPlansByKey?: AiJobPlanFinder | null\n /** What the job may create on its site (AGL-3030); specs and the eval recorder hand in their own. */\n readCapabilities?: AiPlanCapabilitiesReader\n /** The kind's admission, asked of a plan before it is kept; the registry's otherwise. */\n admissionRefusal?: typeof aiJobAdmissionRefusal\n}\n\nexport function createAiJobPlanStep(deps: AiJobPlanStepDeps = {}): AiJobStepRunner {\n const readInventory = deps.readInventory ?? readSiteInventory\n const findPlansByKey =\n deps.findPlansByKey === undefined ? findAiJobsByPlanKey : deps.findPlansByKey\n const readCapabilities = deps.readCapabilities ?? readAiJobPlanCapabilities\n const admissionRefusal = deps.admissionRefusal ?? aiJobAdmissionRefusal\n return async ({ job, now, signal, firestore, modelFor, org: orgDocument }) => {\n const org = (orgDocument ?? null) as Partial<AglynOrgBilling> | null\n const [inventory, workspace] = await Promise.all([\n job.hostId ? readInventory(job.orgId, job.hostId, { firestore }) : Promise.resolve(null),\n readCapabilities({ job, org, firestore }),\n ])\n const scope = AI_JOB_PLAN_SCOPES[job.kind] ?? null\n const capabilities = workspace ? aiPlanCapabilitiesForJob(workspace, scope) : null\n // The model switch's answer for this job (AGL-2942): the creator's pick\n // where the plan, the org restriction and the allotment allowlists allow\n // it, and Auto held to those same lists otherwise. Without a resolver the\n // doctrine asks the routing table itself.\n const model = modelFor?.('job.plan')\n const route = AI_ROUTING_TABLE['job.plan']\n const prompt = aiJobPlanPrompt(job, capabilities)\n\n /**\n * The confirm door's answer for this plan, asked before the plan is kept\n * (AGL-3030): the kind's own admission, handed the plan as the resume\n * door hands it. A refusal fails the job with the door's sentence; a door\n * that could not answer keeps the plan, since the resume door asks again\n * before anything is built.\n */\n const refusalOnKeep = async (plan: AiJobPlan, outcome: AiJobStepOutcome): Promise<AiJobStepOutcome | null> => {\n let refusal: Awaited<ReturnType<typeof aiJobAdmissionRefusal>> = null\n try {\n refusal = await admissionRefusal(job.kind, {\n firestore,\n orgId: job.orgId,\n hostId: job.hostId ?? null,\n inputs: job.inputs ?? {},\n org,\n plan,\n uid: job.createdBy,\n })\n } catch (error) {\n console.error('ai plan admission failed', { orgId: job.orgId, jobId: job.$id, error })\n }\n return refusal ? { ...outcome, failure: refusal.error } : null\n }\n\n // Reuse before asking (AGL-2937). The key covers the whole request, so a\n // hit is a request that would have been sent the same bytes to the same\n // model; the window covers what the key cannot see. A reused plan spends\n // nothing, so the machine's spent-nothing branch releases the reservation\n // and meters no credit, and the job still stops for the member to confirm\n // — this job's plan is proposed to this member, whatever the last one did\n // with theirs.\n const resolved = model ?? aiModelForStep('job.plan')\n const key = aiJobPlanKey({\n job,\n prompt,\n model: resolved,\n system: aiDoctrineSystemBlocks(inventory, { instructions: AI_JOB_PLAN_INSTRUCTIONS }),\n })\n const reused = findPlansByKey\n ? aiReusablePlan(await findPlansByKey(job.orgId, key, firestore), {\n jobId: job.$id,\n now,\n })\n : null\n if (reused) {\n // The reused plan's draft ids name the other job's drafts; this job's are its own.\n const plan: AiJobPlan = aiPlanWithDraftIds(job.kind, {\n ...reused.plan,\n status: 'proposed',\n labels: aiPlanLabels(reused.plan, inventory),\n proposedAt: now as unknown as AiJobPlan['proposedAt'],\n confirmedAt: null,\n confirmedBy: null,\n key,\n reusedFrom: reused.jobId,\n })\n const unspent = aiUnspentOutcome(resolved)\n return (\n (await refusalOnKeep(plan, unspent)) ?? {\n ...unspent,\n plan,\n review: { reason: 'plan', message: AI_JOB_PLAN_REVIEW_COPY, findings: [] },\n }\n )\n }\n\n const result = await runValidatedGeneration('plan', {\n step: 'job.plan',\n ...(model ? { model } : {}),\n instructions: AI_JOB_PLAN_INSTRUCTIONS,\n inventory,\n messages: [{ role: 'user', content: prompt }],\n tool: AI_BUILD_PLAN_TOOL,\n // The routing ceiling, lowered on a tier too slow to look records up,\n // answer and ask again inside the least time the step registered.\n maxTokens: aiJobPlanMaxTokens(resolved),\n ...(route.thinking ? { thinking: route.thinking } : {}),\n ...(route.effort ? { effort: route.effort } : {}),\n ...(signal ? { signal } : {}),\n capabilities,\n extend: shapeViolations(scope),\n })\n const spent: AiJobStepOutcome = {\n outputs: [],\n usage: result.usage,\n estCostUsd: result.estCostUsd,\n model: result.model,\n stopReason: result.stopReason,\n ...(result.effort ? { effort: result.effort } : {}),\n }\n if (result.status === 'refused') return { ...spent, refused: true }\n if (result.status === 'needs_input') return { ...spent, review: aiDoctrineReview(result) }\n // Each draft the plan decides is named as the plan is kept, before anything is built (AGL-3079).\n const plan: AiJobPlan = aiPlanWithDraftIds(job.kind, {\n ...result.value,\n status: 'proposed',\n labels: aiPlanLabels(result.value, inventory),\n // A Date the Admin SDK stores as a timestamp, like every instant the machine writes.\n proposedAt: now as unknown as AiJobPlan['proposedAt'],\n confirmedAt: null,\n confirmedBy: null,\n key,\n })\n return (\n (await refusalOnKeep(plan, spent)) ?? {\n ...spent,\n plan,\n review: { reason: 'plan', message: AI_JOB_PLAN_REVIEW_COPY, findings: [] },\n }\n )\n }\n}\n\nexport const runAiJobPlanStep = createAiJobPlanStep()\n\n/**\n * Registers the plan step every planned kind runs first, with the least time\n * a plan needs; the plugin's console surface calls it.\n */\nexport function registerAiJobPlan(): void {\n registerAiJobPlanStep(runAiJobPlanStep, { minimumMs: AI_JOB_PLAN_STEP_MINIMUM_MS })\n}\n"],"names":["createHash","AI_BUILD_PLAN_TOOL","isAiPlanNewRef","AI_TEMPLATE_SUBJECT_DEFINITIONS","AI_PAGE_CREATE_KINDS","aiPagePlanShapeRefusal","aiPlanCapabilitiesForJob","aiPlanCapabilityLines","AI_SITE_CREATE_KINDS","aiSitePlanShapeRefusal","aiDoctrineSystemBlocks","runValidatedGeneration","AI_STEP_TIERS","AI_ROUTING_TABLE","aiModelForStep","readSiteInventory","aiJobAdmissionRefusal","readAiPlanCapabilities","AI_JOB_BRIEF_MAX_CHARS","aiJobStepBudget","aiDoctrineReview","aiUnspentOutcome","aiPlanWithDraftIds","AI_JOBS_COLLECTION","registerAiJobPlanStep","AI_JOB_PLAN_INSTRUCTIONS","text","AI_JOB_PLAN_STEP_BUDGET","tier","maxTokens","AI_JOB_PLAN_STEP_MINIMUM_MS","minimumMs","aiJobPlanMaxTokens","model","AI_JOB_PLAN_REVIEW_COPY","aiJobPlanPrompt","job","capabilities","lines","kind","brief","slice","key","value","Object","entries","inputs","push","String","aiPlanTemplateTokenLines","join","subject","definition","undefined","tokens","map","entry","token","AI_JOB_PLAN_SCOPES","page","noun","creates","shapeRefusal","site","shapeViolations","scope","plan","message","rule","code","aiPlanLabels","inventory","names","Map","rows","components","layouts","templates","forms","datasets","collections","screens","row","set","id","name","refs","reuse","create","duplicateOf","flatMap","screen","layout","template","sections","section","uses","labels","ref","get","AI_PLAN_REUSE_WINDOW_MS","AI_PLAN_REUSE_CANDIDATES","aiJobPlanKey","input","digest","part","hostId","prompt","system","block","JSON","stringify","update","length","UNREUSABLE","planMillis","at","proposedAt","Date","getTime","toMillis","aiReusablePlan","candidates","context","floor","now","best","bestAt","candidate","jobId","includes","status","findAiJobsByPlanKey","orgId","firestore","snapshot","collection","doc","where","limit","docs","data","readAiJobPlanCapabilities","org","createAiJobPlanStep","deps","readInventory","findPlansByKey","readCapabilities","admissionRefusal","signal","modelFor","orgDocument","workspace","Promise","all","resolve","route","refusalOnKeep","outcome","refusal","uid","createdBy","error","console","$id","failure","resolved","instructions","reused","confirmedAt","confirmedBy","reusedFrom","unspent","review","reason","findings","result","step","messages","role","content","tool","thinking","effort","extend","spent","outputs","usage","estCostUsd","stopReason","refused","runAiJobPlanStep","registerAiJobPlan"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,QAAQ,cAAa;AAExC,SACEC,kBAAkB,EAClBC,cAAc,QAET,4BAAwB;AAE/B,SACEC,+BAA+B,QAE1B,mCAA+B;AACtC,SAASC,oBAAoB,EAAEC,sBAAsB,QAAQ,0BAAsB;AACnF,SACEC,wBAAwB,EACxBC,qBAAqB,QAGhB,mCAA+B;AAEtC,SAASC,oBAAoB,EAAEC,sBAAsB,QAAQ,0BAAsB;AACnF,SAASC,sBAAsB,EAAEC,sBAAsB,QAAQ,4BAAwB;AACvF,SAASC,aAAa,QAAQ,0BAAsB;AAEpD,SAASC,gBAAgB,EAAEC,cAAc,QAAQ,0BAAsB;AAEvE,SAASC,iBAAiB,QAAQ,+BAA2B;AAC7D,SAASC,qBAAqB,QAAQ,wBAAoB;AAC1D,SAASC,sBAAsB,QAAQ,qBAAiB;AACxD,SACEC,sBAAsB,QAGjB,wBAAoB;AAC3B,SAASC,eAAe,QAAQ,qBAAiB;AACjD,SAASC,gBAAgB,EAAEC,gBAAgB,QAAQ,yBAAqB;AACxE,SAASC,kBAAkB,QAAQ,wBAAoB;AACvD,SAASC,kBAAkB,EAAEC,qBAAqB,QAAQ,eAAW;AAErE;;;;;;;;;;;;;;;;;;;;;;;;;CAyBC,GAED,iEAAiE,GACjE,OAAO,MAAMC,2BAAqD;IAChE;QACEC,MACE,8JACA,8QACA;IACJ;CACD,CAAA;AAED;;;;;;CAMC,GACD,OAAO,MAAMC,0BAA0BR,gBAAgB;IACrDS,MAAMhB,aAAa,CAAC,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,QAAQ;YACRlC,QAAQ3B,aAAa2G,OAAOtI,KAAK,EAAE4B;YACnC,qFAAqF;YACrF8C,YAAYQ;YACZ6C,aAAa;YACbC,aAAa;YACbjI;;QAEF,QACG,OAAA,MAAMoH,cAAc5F,MAAMwH,kBAA1B,OAAqC,aACjCA;YACHxH;YACA4G,QAAQ;gBAAEC,QAAQ;gBAAQ5G,SAASjC;gBAAyB8I,UAAU,EAAE;YAAC;;IAG/E;AACF;AAEA,OAAO,MAAMgB,mBAAmBhD,sBAAqB;AAErD;;;CAGC,GACD,OAAO,SAASiD;IACdzK,sBAAsBwK,kBAAkB;QAAEjK,WAAWD;IAA4B;AACnF"}
@@ -29,6 +29,7 @@ import { registerAiJobAdmission } from "./ai-job-admission.js";
29
29
  import { aiJobDraftId } from "./ai-job-draft-ids.js";
30
30
  import { aiDraftAdmissionRefusal, aiDraftAllowanceRefusal, aiSiteSubdomain, readAiDraft, writeAiDraft } from "./ai-job-drafts.js";
31
31
  import { aiConfirmedPlan, aiDoctrineReview, aiGenerationSpent, aiJobBriefLine, aiLimitReview, aiModelNodeIds, aiPlanCreation, aiPlanReferenceLines, aiUnspentOutcome } from "./ai-job-generation.js";
32
+ import { aiPlanTemplateTokenViolations } from "./ai-job-plan-conformance.js";
32
33
  import { aiJobStepBudget } from "./ai-job-budget.js";
33
34
  import { registerAiJobStep } from "./ai-jobs.js";
34
35
  /**
@@ -345,7 +346,15 @@ export function createAiJobTemplateStep(deps = {}) {
345
346
  context: {
346
347
  bindingTokens: aiTemplateAddressTokens(definition)
347
348
  },
348
- extend: aiTemplateBindingCheck(definition)
349
+ // Rule 8's binding check, and the confirmed plan kept: a token the
350
+ // plan promised that the template does not bind (AGL-3143 §11).
351
+ extend: (tree)=>[
352
+ ...aiTemplateBindingCheck(definition)(tree),
353
+ ...aiPlanTemplateTokenViolations(plan, definition, {
354
+ rootId: tree.rootId,
355
+ nodes: tree.nodes
356
+ })
357
+ ]
349
358
  }, signal ? {
350
359
  signal
351
360
  } : {}));