@tiinex/core 0.19.0 → 0.21.0

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.
Files changed (28) hide show
  1. package/package.json +7 -6
  2. package/src/schemas/creation.contracts.js +1 -1
  3. package/src/schemas/party/role/tiinex.party.role.v1.schema.js +5 -0
  4. package/src/schemas/party/role/tiinex.party.role.v1.schema.json +2 -2
  5. package/src/schemas/party/role/tiinex.party.role.v1.schema.md +313 -0
  6. package/src/schemas/party/role/tiinex.party.role.v1.schema.runtime.json +18 -6
  7. package/src/schemas/party/role/tiinex.party.role.v1.validate.js +36 -0
  8. package/src/schemas/schema.reference.js +29 -0
  9. package/src/tooling/portable/adapters/cli/cli.common-author.js +117 -6
  10. package/src/tooling/portable/adapters/cli/cli.common-output.js +19 -0
  11. package/src/tooling/portable/adapters/node/handoff.manufacture.js +26 -4
  12. package/src/tooling/portable/adapters/node/handoff.manufacture.packageParent.js +123 -0
  13. package/src/tooling/portable/audit/audit.capability.js +10 -4
  14. package/src/tooling/portable/grounding/grounding.capsule.js +26 -2
  15. package/src/tooling/portable/grounding/grounding.delegationArtifactAuthority.js +314 -0
  16. package/src/tooling/portable/grounding/grounding.delegationReadiness.js +241 -0
  17. package/src/tooling/portable/grounding/grounding.holderAssignmentModes.js +125 -0
  18. package/src/tooling/portable/grounding/grounding.holderBindingAuthorization.js +49 -50
  19. package/src/tooling/portable/grounding/grounding.readiness.js +19 -3
  20. package/src/tooling/portable/grounding/grounding.readiness.support.js +1 -1
  21. package/src/tooling/portable/handoff/carrierProjection.routeQualification.js +20 -4
  22. package/src/tooling/portable/handoff/coldStartQualification.grounding.js +67 -4
  23. package/src/tooling/portable/handoff/coldStartQualification.materials.js +84 -10
  24. package/src/tooling/portable/handoff/recipientV2.endpointRolePointers.js +1 -1
  25. package/src/tooling/portable/handoff/recipientV2.inspect.projection.js +5 -2
  26. package/src/tooling/portable/handoff/recipientV2.packageV1.build.js +2 -2
  27. package/src/tooling/portable/handoff/recipientV2.topology.js +5 -3
  28. package/src/tooling/portable/handoff/recipientV2.topology.materials.js +0 -0
@@ -0,0 +1,314 @@
1
+ import { posix } from 'node:path';
2
+ import { sha256Hex } from '../../../export/package.bytes.js';
3
+
4
+ export function projectGroundingDelegationArtifactAuthority({ authority = null, records = [], topology = {}, sourceEvidence = null } = {}) {
5
+ const unresolved = [];
6
+ const handoff = authority?.handoff || null;
7
+ const recipientRole = authority?.role || null;
8
+ const senderRole = authority?.senderRole || null;
9
+ if (!handoff || String(handoff.schemaId || '') !== 'tiinex.handoff.v1') return empty('selected-qualified-handoff-not-established');
10
+
11
+ const transferSelection = selectControllingTransfer(handoff, records, topology);
12
+ if (!transferSelection) unresolved.push('forward-controlling-transfer-not-established');
13
+ const recipient = qualifiedRole(recipientRole, handoff.toReference || '');
14
+ if (!recipient) unresolved.push('exact-recipient-role-authority-not-established');
15
+ const sender = qualifiedRole(senderRole, handoff.fromReference || '');
16
+ if (!sender) unresolved.push('exact-sender-role-authority-not-established');
17
+
18
+ const delegateSelection = transferSelection ? selectForwardDelegate(transferSelection.record, authority) : null;
19
+ if (transferSelection && !delegateSelection?.selector) unresolved.push('forward-delegate-selector-not-established');
20
+ if (delegateSelection?.selector && !delegateSelection?.role) unresolved.push('exact-forward-selected-delegate-role-authority-not-established');
21
+
22
+ const taskRecord = transferSelection?.record || null;
23
+ const targetWorkspaceId = String(taskRecord?.path || '').split('/')[0] || '';
24
+ const workspaceSource = (sourceEvidence?.workspaces || []).find((item) => String(item.workspace || '') === targetWorkspaceId && ['qualified', 'explicit-profile'].includes(String(item.state || ''))) || null;
25
+ if (!workspaceSource?.repository) unresolved.push('exact-target-repository-authority-not-established');
26
+
27
+ const delegateCapabilityAuthority = delegateSelection?.role && delegateSelection?.selector && transferSelection
28
+ ? delegateProjection(delegateSelection.role, handoff, transferSelection, delegateSelection.selector)
29
+ : null;
30
+ if (!delegateCapabilityAuthority) unresolved.push('delegate-capability-artifact-projection-not-established');
31
+
32
+ const processApplicability = sender && transferSelection ? processProjection(sender, handoff, transferSelection) : null;
33
+ if (!processApplicability) unresolved.push('delegation-applicability-artifact-projection-not-established');
34
+
35
+ const delegationTargetAuthority = taskRecord && workspaceSource && transferSelection
36
+ ? targetProjection(taskRecord, workspaceSource, handoff, transferSelection)
37
+ : null;
38
+ if (!delegationTargetAuthority) unresolved.push('delegation-target-artifact-projection-not-established');
39
+
40
+ const implementationSourceAuthority = taskRecord && recipient && transferSelection
41
+ ? sourceProjection(taskRecord, recipient, handoff, transferSelection)
42
+ : null;
43
+ if (!implementationSourceAuthority) unresolved.push('implementation-source-artifact-projection-not-established');
44
+
45
+ const delegationReturnReconciliationExpectation = transferSelection
46
+ ? returnProjection(handoff, transferSelection)
47
+ : null;
48
+ if (!delegationReturnReconciliationExpectation) unresolved.push('return-reconciliation-artifact-projection-not-established');
49
+
50
+ const ready = Boolean(delegateCapabilityAuthority && processApplicability && delegationTargetAuthority && implementationSourceAuthority && delegationReturnReconciliationExpectation);
51
+ return Object.freeze({
52
+ state: ready ? 'qualified-forward-artifact-closure' : 'not-established',
53
+ delegateCapabilityAuthority,
54
+ processApplicability,
55
+ delegationTargetAuthority,
56
+ implementationSourceAuthority,
57
+ delegationReturnReconciliationExpectation,
58
+ unresolved: Object.freeze([...new Set(unresolved)].map((code) => Object.freeze({ code }))),
59
+ provenance: Object.freeze({
60
+ basis: 'exact-qualified-forward-selected-artifact-chain',
61
+ selectedHandoff: sourceArtifactFromHandoff(handoff),
62
+ controllingTask: taskRecord ? sourceArtifactFromRecord(taskRecord) : null,
63
+ senderRole: sender ? sender.sourceArtifact : null,
64
+ recipientRole: recipient ? recipient.sourceArtifact : null,
65
+ delegateSelector: delegateSelection?.selector || null,
66
+ delegateRole: delegateSelection?.role?.sourceArtifact || null,
67
+ boundary: 'Projection only. The inbound Handoff recipient/current holder and downstream specialist are independent claims. The downstream Role is resolved only after one exact explicit selector declaration on the controlling current Task; route-bounded Role material then qualifies that already-selected Role. Role/cache inventory, endpoint identity, filenames, adjacency and arbitrary prose are never used to choose a delegate.'
68
+ }),
69
+ boundary: 'Artifact-derived delegation closure is available only from the exact selected forward chain. The current-work declaration selects the downstream Role; exact Role material qualifies capability. Inbound recipient/holder identity, Role-cache carriage, process applicability, source permission and return authority remain separate.'
70
+ });
71
+ }
72
+
73
+ function selectControllingTransfer(handoff, records, topology) {
74
+ const handoffPath = qualifiedHandoffPath(handoff);
75
+ const frontierPaths = new Set((topology?.currentFrontier || []).flatMap((item) => [String(item.path || ''), String(item.resolvedPath || '')]).filter(Boolean));
76
+ const candidates = [];
77
+ for (const transfer of handoff.transfers || []) {
78
+ const target = String(transfer.controllingArtifactTarget || '').trim();
79
+ if (!target) continue;
80
+ const resolved = resolveReference(target, handoffPath);
81
+ if (!resolved) continue;
82
+ const matches = (records || []).filter((record) => String(record.path || '') === resolved && String(record.schemaId || '') === 'tiinex.task.v1' && record.hasContinuityContext && record.hasIntegrity);
83
+ if (matches.length !== 1) continue;
84
+ if (frontierPaths.size && !frontierPaths.has(resolved) && !frontierPaths.has(String(matches[0].id || ''))) continue;
85
+ candidates.push(Object.freeze({ transfer, record: matches[0], resolvedPath: resolved }));
86
+ }
87
+ return candidates.length === 1 ? candidates[0] : null;
88
+ }
89
+
90
+ function qualifiedRole(role, declaredReference = '') {
91
+ const artifact = role?.material?.artifact || null;
92
+ if (String(role?.state || '') !== 'qualified' || String(role?.material?.state || '') !== 'qualified' || !artifact) return null;
93
+ const sha256 = String(artifact.sha256 || '').trim().toLowerCase();
94
+ if (!/^[0-9a-f]{64}$/i.test(sha256)) return null;
95
+ const reference = String(artifact.reference || declaredReference || '').trim();
96
+ if (!reference) return null;
97
+ return Object.freeze({
98
+ label: String(role?.endpoint?.label || artifact.roleLabel || ''),
99
+ kind: String(role?.endpoint?.kind || 'role'),
100
+ roleKind: String(artifact.roleKind || ''),
101
+ boundary: Object.freeze({ ...(role.exactBoundaryLoaded || {}) }),
102
+ authority: Object.freeze({ ...(role.authorityBoundaryLoaded || {}) }),
103
+ sourceArtifact: sourceArtifactFromReference(reference, sha256, String(artifact.schemaId || 'tiinex.party.role.v1'))
104
+ });
105
+ }
106
+
107
+ function selectForwardDelegate(taskRecord, authority = {}) {
108
+ const selector = explicitTaskSpecialistSelector(taskRecord);
109
+ if (!selector) return Object.freeze({ selector: null, role: null, candidates: Object.freeze([]) });
110
+ const candidates = exactRouteRoleMaterials(authority).filter((role) => normalize(role.label) === normalize(selector.roleLabel));
111
+ const unique = dedupeRoles(candidates);
112
+ return Object.freeze({ selector, role: unique.length === 1 ? unique[0] : null, candidates: Object.freeze(unique) });
113
+ }
114
+
115
+ function explicitTaskSpecialistSelector(taskRecord = {}) {
116
+ if (String(taskRecord.schemaId || '') !== 'tiinex.task.v1' || !taskRecord.hasContinuityContext || !taskRecord.hasIntegrity) return null;
117
+ const objective = section(taskRecord.markdown || '', 'Objective');
118
+ if (!objective) return null;
119
+ const declarations = objective
120
+ .split(/\r?\n\s*\r?\n/u)
121
+ .map((item) => item.trim())
122
+ .filter(Boolean)
123
+ .flatMap((paragraph) => {
124
+ if (/\r|\n/u.test(paragraph)) return [];
125
+ const match = paragraph.match(/^(.{1,80}?) is the explicitly selected specialist for this (.{1,120}?)\.$/u);
126
+ if (!match) return [];
127
+ const roleLabel = match[1].trim();
128
+ const scope = match[2].trim();
129
+ if (!roleLabel || !scope || /[\r\n]/u.test(roleLabel)) return [];
130
+ return [Object.freeze({
131
+ state: 'explicit-current-work-selector',
132
+ roleLabel,
133
+ selectorKind: 'explicit-specialist-declaration-paragraph',
134
+ section: 'Objective',
135
+ declaration: paragraph,
136
+ scope,
137
+ sourceArtifact: sourceArtifactFromRecord(taskRecord),
138
+ boundary: 'Closed lexical declaration paragraph only. Core does not interpret surrounding prose: no Role label is searched for, guessed from inventory, inferred from endpoint identity, or recovered from near-match text.'
139
+ })];
140
+ });
141
+ return declarations.length === 1 ? declarations[0] : null;
142
+ }
143
+
144
+ function exactRouteRoleMaterials(authority = {}) {
145
+ const roles = [];
146
+ const recipient = qualifiedRole(authority?.role || null, authority?.handoff?.toReference || '');
147
+ const sender = qualifiedRole(authority?.senderRole || null, authority?.handoff?.fromReference || '');
148
+ if (recipient) roles.push(recipient);
149
+ if (sender) roles.push(sender);
150
+ for (const item of authority?.participation?.packageRoleGrounding || []) {
151
+ const role = qualifiedPackageGroundingRole(item);
152
+ if (role) roles.push(role);
153
+ }
154
+ return Object.freeze(dedupeRoles(roles));
155
+ }
156
+
157
+ function qualifiedPackageGroundingRole(entry = {}) {
158
+ const artifact = entry?.roleArtifact || null;
159
+ if (!entry?.groundingOnly || String(entry?.materialQualification || '') !== 'qualified' || !artifact) return null;
160
+ const sha256 = String(artifact.sha256 || '').trim().toLowerCase();
161
+ if (!/^[0-9a-f]{64}$/iu.test(sha256)) return null;
162
+ const reference = String(artifact.reference || artifact.path || '').trim();
163
+ const label = String(artifact.roleLabel || entry.label || '').trim();
164
+ if (!reference || !label || String(artifact.schemaId || '') !== 'tiinex.party.role.v1') return null;
165
+ return Object.freeze({
166
+ label,
167
+ kind: 'role',
168
+ roleKind: String(artifact.roleKind || ''),
169
+ boundary: Object.freeze({ ...(entry.exactBoundaryLoaded || {}) }),
170
+ authority: Object.freeze({ ...(entry.authorityBoundaryLoaded || {}) }),
171
+ sourceArtifact: sourceArtifactFromReference(reference, sha256, String(artifact.schemaId || 'tiinex.party.role.v1')),
172
+ materialResolution: Object.freeze({ pointerPath: String(entry.pointerPath || ''), groundingOnly: true })
173
+ });
174
+ }
175
+
176
+ function dedupeRoles(roles = []) {
177
+ const map = new Map();
178
+ for (const role of roles) {
179
+ const key = `${normalize(role?.label)}\u0000${String(role?.sourceArtifact?.path || '')}\u0000${String(role?.sourceArtifact?.sha256 || '')}`;
180
+ if (!map.has(key)) map.set(key, role);
181
+ }
182
+ return [...map.values()];
183
+ }
184
+
185
+ function delegateProjection(role, handoff, selected, selector) {
186
+ const capabilities = [
187
+ role.roleKind ? Object.freeze({ kind: 'role-kind', value: role.roleKind }) : null,
188
+ role.boundary.inScope ? Object.freeze({ kind: 'role-in-scope', value: role.boundary.inScope }) : null,
189
+ role.authority.mayDo ? Object.freeze({ kind: 'role-may-do', value: role.authority.mayDo }) : null
190
+ ].filter(Boolean);
191
+ if (!role.label || !capabilities.length) return null;
192
+ return Object.freeze({
193
+ explicit: true,
194
+ qualification: 'qualified',
195
+ delegate: Object.freeze({ label: role.label, kind: role.kind || 'role' }),
196
+ capabilities: Object.freeze(capabilities),
197
+ selection: Object.freeze({ state: 'explicit-forward-selected', forwardSelected: true }),
198
+ sourceArtifact: role.sourceArtifact,
199
+ facts: Object.freeze([
200
+ Object.freeze({ kind: 'current-work-forward-delegate-selector', role: selector.roleLabel, section: selector.section, selectorKind: selector.selectorKind, controllingArtifact: selected.resolvedPath }),
201
+ Object.freeze({ kind: 'exact-forward-selected-role-authority', role: role.label, roleKind: role.roleKind }),
202
+ Object.freeze({ kind: 'selected-handoff-current-work-transfer', handoff: qualifiedHandoffPath(handoff), transferId: String(selected.transfer.id || ''), transferKind: String(selected.transfer.transferKind || ''), controllingArtifact: selected.resolvedPath })
203
+ ]),
204
+ provenance: Object.freeze({
205
+ source: role.sourceArtifact.path,
206
+ basis: 'exact-controlling-task-explicit-specialist-selector-plus-exact-selected-role-material',
207
+ forwardSelector: selector,
208
+ roleSourceArtifact: role.sourceArtifact,
209
+ materialResolution: role.materialResolution || null,
210
+ currentWorkTransfer: Object.freeze({ handoff: qualifiedHandoffPath(handoff), transferId: String(selected.transfer.id || ''), controllingArtifact: selected.resolvedPath })
211
+ })
212
+ });
213
+ }
214
+
215
+ function processProjection(role, handoff, selected) {
216
+ const facts = [
217
+ role.authority.delegation ? Object.freeze({ kind: 'sender-role-delegation', value: role.authority.delegation }) : null,
218
+ role.authority.requiredInstrument ? Object.freeze({ kind: 'sender-role-required-instrument', value: role.authority.requiredInstrument }) : null,
219
+ role.authority.mayDo ? Object.freeze({ kind: 'sender-role-may-do', value: role.authority.mayDo }) : null,
220
+ Object.freeze({ kind: 'selected-handoff-work-transfer', transferId: String(selected.transfer.id || ''), transferKind: String(selected.transfer.transferKind || ''), controllingArtifact: selected.resolvedPath })
221
+ ].filter(Boolean);
222
+ if (facts.length < 2) return null;
223
+ return Object.freeze({
224
+ explicit: true,
225
+ qualification: 'qualified',
226
+ facts: Object.freeze(facts),
227
+ source: role.sourceArtifact.path,
228
+ provenance: Object.freeze({ source: role.sourceArtifact.path, sourceArtifact: role.sourceArtifact, basis: 'exact-sender-role-authority-plus-selected-handoff-work-transfer', forwardSelector: Object.freeze({ handoff: qualifiedHandoffPath(handoff), transferId: String(selected.transfer.id || '') }) })
229
+ });
230
+ }
231
+
232
+ function targetProjection(taskRecord, workspaceSource, handoff, selected) {
233
+ const workspaceId = String(taskRecord.path || '').split('/')[0];
234
+ const relativeTask = String(taskRecord.path || '').slice(workspaceId.length + 1);
235
+ const relativeHandoff = String(handoff.workspaceRelativePath || '').replace(/^\/+/, '');
236
+ return Object.freeze({
237
+ explicit: true,
238
+ qualification: 'qualified',
239
+ target: Object.freeze({
240
+ workspaceId,
241
+ repository: String(workspaceSource.repository || ''),
242
+ rootPath: String(workspaceSource.rootPath || ''),
243
+ taskDirectory: posix.dirname(relativeTask),
244
+ handoffDirectory: posix.dirname(relativeHandoff)
245
+ }),
246
+ sourceArtifact: sourceArtifactFromRecord(taskRecord),
247
+ facts: Object.freeze([
248
+ Object.freeze({ kind: 'controlling-task-placement', path: String(taskRecord.path || '') }),
249
+ Object.freeze({ kind: 'workspace-source-identity', workspaceId, repository: String(workspaceSource.repository || ''), rootPath: String(workspaceSource.rootPath || '') })
250
+ ]),
251
+ provenance: Object.freeze({ source: String(taskRecord.path || ''), basis: 'exact-controlling-task-plus-qualified-workspace-source-identity', forwardSelector: Object.freeze({ handoff: qualifiedHandoffPath(handoff), transferId: String(selected.transfer.id || '') }) })
252
+ });
253
+ }
254
+
255
+ function sourceProjection(taskRecord, role, handoff, selected) {
256
+ const scope = section(taskRecord.markdown || '', 'Scope');
257
+ const facts = [
258
+ scope ? Object.freeze({ kind: 'controlling-task-scope', value: scope }) : null,
259
+ role.authority.mayDo ? Object.freeze({ kind: 'recipient-role-may-do', value: role.authority.mayDo }) : null,
260
+ role.authority.requiredInstrument ? Object.freeze({ kind: 'recipient-role-required-instrument', value: role.authority.requiredInstrument }) : null,
261
+ Object.freeze({ kind: 'selected-handoff-work-transfer', transferId: String(selected.transfer.id || ''), transferKind: String(selected.transfer.transferKind || ''), controllingArtifact: selected.resolvedPath })
262
+ ].filter(Boolean);
263
+ if (!scope || !role.authority.mayDo) return null;
264
+ return Object.freeze({
265
+ explicit: true,
266
+ qualification: 'qualified',
267
+ sourceArtifact: sourceArtifactFromRecord(taskRecord),
268
+ facts: Object.freeze(facts),
269
+ provenance: Object.freeze({ source: String(taskRecord.path || ''), basis: 'exact-controlling-task-scope-plus-recipient-role-authority-plus-selected-transfer', forwardSelector: Object.freeze({ handoff: qualifiedHandoffPath(handoff), transferId: String(selected.transfer.id || '') }), recipientRoleSourceArtifact: role.sourceArtifact })
270
+ });
271
+ }
272
+
273
+ function returnProjection(handoff, selected) {
274
+ const completion = handoff.completionExpectation || {};
275
+ const returnTo = String(completion.returnTo || '').trim();
276
+ const retained = (handoff.retainedResponsibilities || []).filter((item) => normalize(item.retainedBy) === normalize(returnTo));
277
+ if (!completion.signalKind || !completion.signalMeaning || !returnTo || retained.length !== 1) return null;
278
+ return Object.freeze({
279
+ explicit: true,
280
+ qualification: 'qualified',
281
+ completionExpectation: Object.freeze({ signalKind: String(completion.signalKind), signalMeaning: String(completion.signalMeaning), returnTo }),
282
+ reconciliation: Object.freeze({ state: 'retained-by-return-target', expectation: String(retained[0].responsibility || '') }),
283
+ sourceArtifact: sourceArtifactFromHandoff(handoff),
284
+ facts: Object.freeze([
285
+ Object.freeze({ kind: 'selected-handoff-completion-expectation', signalKind: String(completion.signalKind), returnTo }),
286
+ Object.freeze({ kind: 'return-target-retained-responsibility', id: String(retained[0].id || ''), retainedBy: returnTo, responsibility: String(retained[0].responsibility || '') })
287
+ ]),
288
+ provenance: Object.freeze({ source: qualifiedHandoffPath(handoff), basis: 'exact-selected-handoff-completion-plus-return-target-retained-responsibility', forwardSelector: Object.freeze({ transferId: String(selected.transfer.id || ''), controllingArtifact: selected.resolvedPath }) })
289
+ });
290
+ }
291
+
292
+ function sourceArtifactFromRecord(record) {
293
+ return Object.freeze({ workspaceId: String(record.path || '').split('/')[0] || '', path: String(record.path || ''), sha256: sha256(record.markdown || ''), schemaId: String(record.schemaId || '') });
294
+ }
295
+ function sourceArtifactFromHandoff(handoff) {
296
+ return Object.freeze({ workspaceId: String(handoff.workspaceId || ''), path: qualifiedHandoffPath(handoff), sha256: String(handoff.sha256 || '').trim().toLowerCase(), schemaId: String(handoff.schemaId || 'tiinex.handoff.v1') });
297
+ }
298
+ function sourceArtifactFromReference(reference, sha, schemaId) {
299
+ const raw = String(reference || '').trim();
300
+ const cross = raw.match(/^([^:/\\]+)::(.+)$/);
301
+ return Object.freeze({ workspaceId: cross ? cross[1] : '', path: raw, sha256: String(sha || '').toLowerCase(), schemaId: String(schemaId || '') });
302
+ }
303
+ function qualifiedHandoffPath(handoff) { return [String(handoff.workspaceId || ''), String(handoff.workspaceRelativePath || '').replace(/^\/+/, '')].filter(Boolean).join('/'); }
304
+ function resolveReference(reference, ownerPath) {
305
+ const raw = String(reference || '').split('#')[0].trim().replace(/\\/g, '/');
306
+ const cross = raw.match(/^([^:/\\]+)::(.+)$/);
307
+ const candidate = cross ? `${cross[1]}/${cross[2].replace(/^\/+/, '')}` : raw.startsWith('/') ? raw.slice(1) : posix.join(posix.dirname(ownerPath), raw);
308
+ const normalized = posix.normalize(candidate).replace(/^\.\//, '');
309
+ return !normalized || normalized === '..' || normalized.startsWith('../') ? '' : normalized;
310
+ }
311
+ function section(markdown = '', heading = '') { const escaped = String(heading || '').replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); return String(markdown || '').match(new RegExp(`(?:^|\\n)##\\s+${escaped}\\s*\\r?\\n([\\s\\S]*?)(?=\\n##\\s+|\\n#\\s+Continuity Integrity|$)`, 'i'))?.[1]?.trim() || ''; }
312
+ function sha256(markdown) { return sha256Hex(new TextEncoder().encode(String(markdown || ''))); }
313
+ function normalize(value) { return String(value || '').trim().toLowerCase(); }
314
+ function empty(code) { return Object.freeze({ state: 'not-established', delegateCapabilityAuthority: null, processApplicability: null, delegationTargetAuthority: null, implementationSourceAuthority: null, delegationReturnReconciliationExpectation: null, unresolved: Object.freeze([Object.freeze({ code })]), provenance: null, boundary: 'No exact selected qualified Handoff authority was available for artifact-derived delegation projection.' }); }
@@ -0,0 +1,241 @@
1
+ const MAX_CAPABILITIES = 12;
2
+ const MAX_FACTS = 12;
3
+
4
+ export function projectGroundingDelegationReadiness({ authority = null, processApplicability = null, implementationSourceAuthority = null } = {}) {
5
+ const delegateCapabilityAuthority = projectDelegateCapabilityAuthority(authority?.delegateCapabilityAuthority || authority?.delegationContext?.delegateCapabilityAuthority || null);
6
+ const targetAuthority = projectDelegationTargetAuthority(authority?.delegationTargetAuthority || authority?.delegationContext?.targetAuthority || authority?.delegationContext?.delegationTargetAuthority || null);
7
+ const returnReconciliationExpectation = projectDelegationReturnReconciliationExpectation(authority?.delegationReturnReconciliationExpectation || authority?.delegationContext?.returnReconciliationExpectation || authority?.delegationContext?.delegationReturnReconciliationExpectation || null);
8
+ const process = processApplicability || Object.freeze({ state: 'not-established', unresolved: Object.freeze([]) });
9
+ const source = implementationSourceAuthority || Object.freeze({ state: 'unresolved', unresolved: Object.freeze([]) });
10
+ const blockers = [];
11
+
12
+ if (delegateCapabilityAuthority.state !== 'explicit-qualified-forward-selection') blockers.push(blocker(
13
+ 'delegate-capability-authority-not-established',
14
+ delegateCapabilityAuthority.unresolved?.[0]?.detail || 'No explicit upstream-qualified forward-selected delegate/capability authority is established.',
15
+ 'Provide an explicit upstream-qualified forward-selected delegate/capability projection with exact source-artifact identity. Cached Role presence, participant inventory, Handoff endpoint labels, filenames and chat position are not delegate selection authority.'
16
+ ));
17
+ const processReady = String(process.state || '') === 'explicit-qualified-authority' && Array.isArray(process.facts) && process.facts.length > 0 && Boolean(String(process.provenance?.source || process.provenance?.upstreamProvenance?.source || '').trim());
18
+ if (!processReady) blockers.push(blocker(
19
+ 'delegation-process-applicability-not-established',
20
+ process.unresolved?.[0]?.detail || 'Delegation/process applicability is not explicitly established by upstream semantic authority.',
21
+ 'Provide the explicit upstream-qualified process/delegation applicability projection. Do not infer applicability from Role/cache inventory or repository adjacency.'
22
+ ));
23
+ if (targetAuthority.state !== 'explicit-qualified-target-authority') blockers.push(blocker(
24
+ 'delegation-target-authority-not-established',
25
+ targetAuthority.unresolved?.[0]?.detail || 'Target repository/workspace authority and repo-local Task/Handoff placement are not explicitly established.',
26
+ 'Provide an explicit upstream-qualified delegation target projection naming repository, workspaceId, taskDirectory and handoffDirectory with exact source-artifact identity.'
27
+ ));
28
+ const sourceReady = String(source.state || '') === 'explicit-qualified-upstream-projection' && Array.isArray(source.facts) && source.facts.length > 0;
29
+ if (!sourceReady) blockers.push(blocker(
30
+ 'delegation-source-authority-not-established',
31
+ source.unresolved?.[0]?.detail || 'Implementation/source authority is not explicitly established by upstream semantic authority.',
32
+ 'Provide the exact upstream-qualified implementation-source authority projection. Workspace carriage, writability text, repository identity and executable Task presence remain descriptive only.'
33
+ ));
34
+ if (returnReconciliationExpectation.state !== 'explicit-qualified-return-reconciliation') blockers.push(blocker(
35
+ 'delegation-return-reconciliation-expectation-not-established',
36
+ returnReconciliationExpectation.unresolved?.[0]?.detail || 'Return/reconciliation responsibility is not explicitly established.',
37
+ 'Provide an explicit upstream-qualified return/reconciliation projection with Completion Expectation and an explicit reconciliation state/expectation.'
38
+ ));
39
+
40
+ const ready = blockers.length === 0;
41
+ return Object.freeze({
42
+ state: ready ? 'qualified-for-delegation-authoring' : 'not-established',
43
+ delegateCapabilityAuthority,
44
+ processApplicability: process,
45
+ targetAuthority,
46
+ sourceAuthority: source,
47
+ returnReconciliationExpectation,
48
+ blockers: Object.freeze(blockers),
49
+ plainChatFallbackPermitted: false,
50
+ repositoryScanningFallbackPermitted: false,
51
+ nextOperations: ready ? projectNextOperations({ delegateCapabilityAuthority, targetAuthority, returnReconciliationExpectation }) : Object.freeze([]),
52
+ boundary: 'Mechanical delegation qualification only. Core consumes already-explicit, already-qualified semantic projections and exposes the normal Task -> Handoff -> carrier Tooling path; it never selects a delegate, invents process applicability, generates a work plan, grants source authority, or treats cached Role presence as delegation authority.'
53
+ });
54
+ }
55
+
56
+ export function projectDelegateCapabilityAuthority(value = null) {
57
+ const base = qualifyExplicitProjection(value);
58
+ if (!base.qualified) return unresolvedProjection('delegate-capability-authority-not-established', 'No exact upstream-qualified explicit delegate/capability projection is present.');
59
+ const delegate = value?.delegate || value?.selectedDelegate || {};
60
+ const label = String(delegate.label || delegate.roleLabel || value?.delegateLabel || '').trim();
61
+ const kind = String(delegate.kind || value?.delegateKind || 'role').trim();
62
+ const capabilities = Array.isArray(value?.capabilities) ? value.capabilities : Array.isArray(delegate.capabilities) ? delegate.capabilities : [];
63
+ const selectionState = String(value?.selection?.state || value?.selectionState || '').trim().toLowerCase();
64
+ const forwardSelected = value?.selection?.forwardSelected === true || value?.forwardSelected === true || ['forward-selected', 'explicit-forward-selected'].includes(selectionState);
65
+ if (!label || !capabilities.length || !forwardSelected) return unresolvedProjection(
66
+ 'delegate-capability-authority-incomplete',
67
+ 'The upstream delegate/capability projection is marked qualified but does not expose one explicit forward-selected delegate label plus at least one capability.'
68
+ );
69
+ return Object.freeze({
70
+ state: 'explicit-qualified-forward-selection',
71
+ delegate: Object.freeze({ label, kind }),
72
+ capabilities: Object.freeze(capabilities.slice(0, MAX_CAPABILITIES).map((item) => freezeValue(item))),
73
+ sourceArtifact: Object.freeze(base.sourceArtifact),
74
+ facts: Object.freeze(projectFacts(value)),
75
+ provenance: Object.freeze({
76
+ basis: 'exact-upstream-qualified-forward-selected-delegate-capability-projection',
77
+ sourceArtifact: Object.freeze(base.sourceArtifact),
78
+ upstreamProvenance: value?.provenance ? Object.freeze({ ...(value.provenance || {}) }) : null,
79
+ boundary: 'Delegate relevance/capability is passed through from explicit upstream authority. Core does not select a Role from cache or participant inventory.'
80
+ }),
81
+ unresolved: Object.freeze([]),
82
+ boundary: 'Forward selection is semantic input, not a Role-discovery result.'
83
+ });
84
+ }
85
+
86
+ export function projectDelegationTargetAuthority(value = null) {
87
+ const base = qualifyExplicitProjection(value);
88
+ if (!base.qualified) return unresolvedProjection('delegation-target-authority-not-established', 'No exact upstream-qualified delegation target projection is present.');
89
+ const target = value?.target || value?.placement || {};
90
+ const workspaceId = String(target.workspaceId || value?.workspaceId || '').trim();
91
+ const repository = String(target.repository || value?.repository || '').trim();
92
+ const taskDirectory = normalizeDirectory(target.taskDirectory || value?.taskDirectory || '');
93
+ const handoffDirectory = normalizeDirectory(target.handoffDirectory || value?.handoffDirectory || '');
94
+ if (!workspaceId || !repository || !taskDirectory || !handoffDirectory) return unresolvedProjection(
95
+ 'delegation-target-authority-incomplete',
96
+ 'The upstream delegation target projection is marked qualified but does not expose repository, workspaceId, taskDirectory and handoffDirectory.'
97
+ );
98
+ return Object.freeze({
99
+ state: 'explicit-qualified-target-authority',
100
+ target: Object.freeze({ workspaceId, repository, taskDirectory, handoffDirectory, rootPath: String(target.rootPath || value?.rootPath || '').trim() }),
101
+ sourceArtifact: Object.freeze(base.sourceArtifact),
102
+ facts: Object.freeze(projectFacts(value)),
103
+ provenance: Object.freeze({
104
+ basis: 'exact-upstream-qualified-delegation-target-projection',
105
+ sourceArtifact: Object.freeze(base.sourceArtifact),
106
+ upstreamProvenance: value?.provenance ? Object.freeze({ ...(value.provenance || {}) }) : null,
107
+ boundary: 'Repository/Workspace identity and repo-local Task/Handoff placement are passed through from upstream authority; Core does not discover or choose a repository.'
108
+ }),
109
+ unresolved: Object.freeze([]),
110
+ boundary: 'Target placement is explicit authority input only; source mutation permission is separate.'
111
+ });
112
+ }
113
+
114
+ export function projectDelegationReturnReconciliationExpectation(value = null) {
115
+ const base = qualifyExplicitProjection(value);
116
+ if (!base.qualified) return unresolvedProjection('delegation-return-reconciliation-expectation-not-established', 'No exact upstream-qualified return/reconciliation projection is present.');
117
+ const completion = value?.completionExpectation || value?.returnExpectation || {};
118
+ const signalKind = String(completion.signalKind || '').trim();
119
+ const signalMeaning = String(completion.signalMeaning || '').trim();
120
+ const returnTo = String(completion.returnTo || '').trim();
121
+ const reconciliation = normalizeReconciliation(value?.reconciliation || value?.reconciliationExpectation || null);
122
+ if (!signalKind || !signalMeaning || !returnTo || !reconciliation.state) return unresolvedProjection(
123
+ 'delegation-return-reconciliation-expectation-incomplete',
124
+ 'The upstream return/reconciliation projection is marked qualified but does not expose a complete Completion Expectation and an explicit reconciliation state/expectation.'
125
+ );
126
+ return Object.freeze({
127
+ state: 'explicit-qualified-return-reconciliation',
128
+ completionExpectation: Object.freeze({ signalKind, signalMeaning, returnTo }),
129
+ reconciliation,
130
+ sourceArtifact: Object.freeze(base.sourceArtifact),
131
+ facts: Object.freeze(projectFacts(value)),
132
+ provenance: Object.freeze({
133
+ basis: 'exact-upstream-qualified-return-reconciliation-projection',
134
+ sourceArtifact: Object.freeze(base.sourceArtifact),
135
+ upstreamProvenance: value?.provenance ? Object.freeze({ ...(value.provenance || {}) }) : null,
136
+ boundary: 'Return and reconciliation responsibility are passed through exactly; Core does not invent acceptance, completion or merge semantics.'
137
+ }),
138
+ unresolved: Object.freeze([]),
139
+ boundary: 'Completion and reconciliation expectations are semantic-owner inputs; carrier manufacture remains a separate mechanical operation.'
140
+ });
141
+ }
142
+
143
+ function projectNextOperations({ delegateCapabilityAuthority, targetAuthority, returnReconciliationExpectation }) {
144
+ const target = targetAuthority.target;
145
+ const delegate = delegateCapabilityAuthority.delegate;
146
+ return Object.freeze([
147
+ Object.freeze({
148
+ kind: 'author-delegation-task',
149
+ command: 'author',
150
+ schemaId: 'tiinex.task.v1',
151
+ workspaceId: target.workspaceId,
152
+ repository: target.repository,
153
+ directory: target.taskDirectory,
154
+ bodyAuthority: 'caller/upstream-authored-work-semantics-required',
155
+ boundary: 'Mechanical authoring coordinate only. Core does not generate the Task objective, Done Criteria, scope or work plan.'
156
+ }),
157
+ Object.freeze({
158
+ kind: 'author-delegation-handoff',
159
+ command: 'author',
160
+ schemaId: 'tiinex.handoff.v1',
161
+ workspaceId: target.workspaceId,
162
+ repository: target.repository,
163
+ directory: target.handoffDirectory,
164
+ parent: 'newly-authored-qualified-task',
165
+ recipient: Object.freeze({ ...delegate }),
166
+ completionExpectation: Object.freeze({ ...(returnReconciliationExpectation.completionExpectation || {}) }),
167
+ boundary: 'Author the Handoff through normal Tooling with the qualified Task as Parent and the upstream-selected delegate/return semantics; Core does not synthesize transfer semantics.'
168
+ }),
169
+ Object.freeze({
170
+ kind: 'manufacture-delegation-carrier',
171
+ command: 'handoff',
172
+ workspaceId: target.workspaceId,
173
+ recipient: Object.freeze({ ...delegate }),
174
+ carrierAllocation: 'machine-derived-from-qualified-parent-pointer-topology',
175
+ reconciliation: returnReconciliationExpectation.reconciliation,
176
+ boundary: 'Manufacture only after the Task and Handoff qualify. Carrier topology is transport-only and does not create semantic delegation authority.'
177
+ })
178
+ ]);
179
+ }
180
+
181
+ function qualifyExplicitProjection(value = null) {
182
+ if (!value || typeof value !== 'object' || value.explicit !== true) return { qualified: false, sourceArtifact: emptySourceArtifact() };
183
+ if (String(value.qualification || value.state || '').trim().toLowerCase() !== 'qualified') return { qualified: false, sourceArtifact: emptySourceArtifact() };
184
+ const sourceArtifact = projectSourceArtifact(value);
185
+ if (!sourceArtifact.path || !/^[0-9a-f]{64}$/i.test(sourceArtifact.sha256)) return { qualified: false, sourceArtifact };
186
+ return { qualified: true, sourceArtifact };
187
+ }
188
+
189
+ function projectSourceArtifact(value = {}) {
190
+ const source = value.sourceArtifact || value.provenance?.sourceArtifact || {};
191
+ return Object.freeze({
192
+ workspaceId: String(source.workspaceId || source.workspace || '').trim(),
193
+ path: String(source.path || source.workspaceRelativePath || value.provenance?.sourceArtifactPath || '').trim(),
194
+ sha256: String(source.sha256 || value.provenance?.sourceArtifactSha256 || '').trim().toLowerCase(),
195
+ schemaId: String(source.schemaId || '').trim()
196
+ });
197
+ }
198
+
199
+ function unresolvedProjection(code, detail) {
200
+ return Object.freeze({
201
+ state: 'not-established',
202
+ facts: Object.freeze([]),
203
+ sourceArtifact: Object.freeze(emptySourceArtifact()),
204
+ unresolved: Object.freeze([Object.freeze({ code, detail })]),
205
+ boundary: 'No semantic meaning is inferred from Role/cache inventory, Handoff endpoints, filenames, repository adjacency or transport placement.'
206
+ });
207
+ }
208
+
209
+ function blocker(code, detail, request) {
210
+ return Object.freeze({
211
+ code,
212
+ detail: String(detail || ''),
213
+ request: `${String(request || '')} Do not fall back to plain-chat delegation, repository scanning, network discovery, or selecting a Role merely because it is carried.`
214
+ });
215
+ }
216
+
217
+ function projectFacts(value = {}) {
218
+ const facts = Array.isArray(value.facts) ? value.facts : Array.isArray(value.items) ? value.items : [];
219
+ return facts.slice(0, MAX_FACTS).map((item) => freezeValue(item));
220
+ }
221
+
222
+ function freezeValue(value) {
223
+ if (value && typeof value === 'object' && !Array.isArray(value)) return Object.freeze({ ...value });
224
+ if (Array.isArray(value)) return Object.freeze([...value]);
225
+ return value;
226
+ }
227
+
228
+ function normalizeDirectory(value = '') {
229
+ return String(value || '').replace(/\\/g, '/').replace(/^\/+/, '').replace(/\/+$/, '').trim();
230
+ }
231
+
232
+ function normalizeReconciliation(value = null) {
233
+ if (typeof value === 'string') return Object.freeze({ state: String(value || '').trim(), expectation: '' });
234
+ if (!value || typeof value !== 'object') return Object.freeze({ state: '', expectation: '' });
235
+ return Object.freeze({
236
+ state: String(value.state || value.disposition || '').trim(),
237
+ expectation: String(value.expectation || value.description || '').trim()
238
+ });
239
+ }
240
+
241
+ function emptySourceArtifact() { return { workspaceId: '', path: '', sha256: '', schemaId: '' }; }