@tiinex/core 0.18.0 → 0.20.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 (38) hide show
  1. package/package.json +8 -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.command-input.js +8 -1
  10. package/src/tooling/portable/adapters/cli/cli.common-author.js +117 -6
  11. package/src/tooling/portable/adapters/cli/cli.common-output.js +26 -0
  12. package/src/tooling/portable/adapters/cli/cli.handoff-manufacture.js +33 -17
  13. package/src/tooling/portable/adapters/cli/cli.handoff-sibling-allocation.js +139 -2
  14. package/src/tooling/portable/adapters/cli/cli.help.js +1 -1
  15. package/src/tooling/portable/adapters/node/handoff.manufacture.js +30 -5
  16. package/src/tooling/portable/adapters/node/handoff.manufacture.packageParent.js +123 -0
  17. package/src/tooling/portable/audit/audit.capability.js +10 -4
  18. package/src/tooling/portable/grounding/grounding.capsule.js +33 -2
  19. package/src/tooling/portable/grounding/grounding.delegationArtifactAuthority.js +220 -0
  20. package/src/tooling/portable/grounding/grounding.delegationReadiness.js +241 -0
  21. package/src/tooling/portable/grounding/grounding.holderAssignmentModes.js +125 -0
  22. package/src/tooling/portable/grounding/grounding.holderBindingAuthorization.js +80 -0
  23. package/src/tooling/portable/grounding/grounding.implementationSourceAuthority.js +109 -0
  24. package/src/tooling/portable/grounding/grounding.participantAuthority.js +1 -1
  25. package/src/tooling/portable/grounding/grounding.readiness.authority.js +15 -0
  26. package/src/tooling/portable/grounding/grounding.readiness.js +86 -13
  27. package/src/tooling/portable/grounding/grounding.readiness.support.js +2 -2
  28. package/src/tooling/portable/handoff/carrierProjection.routeQualification.js +20 -4
  29. package/src/tooling/portable/handoff/coldStartQualification.grounding.js +116 -5
  30. package/src/tooling/portable/handoff/coldStartQualification.materials.js +92 -10
  31. package/src/tooling/portable/handoff/delegationReturnReservation.js +4 -2
  32. package/src/tooling/portable/handoff/manufacture.js +1 -0
  33. package/src/tooling/portable/handoff/recipientV2.endpointRolePointers.js +1 -1
  34. package/src/tooling/portable/handoff/recipientV2.inspect.projection.js +7 -1
  35. package/src/tooling/portable/handoff/recipientV2.packageV1.build.js +2 -2
  36. package/src/tooling/portable/handoff/recipientV2.packageV1.inspect.js +1 -1
  37. package/src/tooling/portable/handoff/recipientV2.topology.js +5 -3
  38. package/src/tooling/portable/handoff/recipientV2.topology.materials.js +0 -0
@@ -3,6 +3,7 @@ import { inspectRecipientFacingV2Topology } from '../../handoff/recipientV2.insp
3
3
  import { parseHandoffPackageV1, RECIPIENT_V2_PACKAGE_V1_ROOT_PATH } from '../../handoff/recipientV2.packageV1.js';
4
4
  import { projectHandoffMaterialRequirements } from '../../handoff/materialClosure.requirements.js';
5
5
  import { parseWorkspaceQualifiedReference } from '../../handoff/workspaceQualifiedReference.js';
6
+ import { inspectStoredWorkspaceArchive } from '../../handoff/workspaceByteProvider.js';
6
7
 
7
8
  export function preparePackageParentWorkspaceReuse(input = {}) {
8
9
  const bundle = input.bundle || null;
@@ -77,6 +78,128 @@ export function preparePackageParentWorkspaceReuse(input = {}) {
77
78
  });
78
79
  }
79
80
 
81
+
82
+
83
+ export function preparePackageParentExactMaterialProvider(input = {}) {
84
+ const bundle = input.bundle || null;
85
+ const currentIds = new Set([...(input.currentWorkspaceIds || [])].map(normalizeId).filter(Boolean));
86
+ if (!bundle?.files?.length) return emptyExactMaterialProvider('unavailable');
87
+ const inspection = inspectRecipientFacingV2Topology(bundle);
88
+ const claims = [];
89
+ for (const cache of inspection.caches || []) {
90
+ const archivePath = String(cache.archivePath || '').trim();
91
+ const matches = (bundle.files || []).filter((file) => String(file.path || '') === archivePath);
92
+ let archive = null;
93
+ if (matches.length === 1) {
94
+ try { archive = inspectStoredWorkspaceArchive(packageFileBytes(matches[0]), { ownedBytes: true }); } catch { archive = null; }
95
+ }
96
+ const byPath = new Map((archive?.entries || []).map((entry) => [String(entry.path || ''), entry]));
97
+ for (const material of cache.materials || []) {
98
+ const referenceTarget = String(material.referenceTarget || '').trim();
99
+ if (!referenceTarget) continue;
100
+ const parsed = parseWorkspaceQualifiedReference(referenceTarget);
101
+ if (parsed && currentIds.has(normalizeId(parsed.workspaceId))) continue;
102
+ const entry = byPath.get(String(material.archiveEntry || '')) || null;
103
+ const declaredSha = String(material.sha256 || '').trim();
104
+ const declaredBytes = Number(material.bytes || 0);
105
+ const entrySha = entry ? String(entry.sha256 || sha256Hex(entry.data || new Uint8Array())) : '';
106
+ const entryBytes = entry ? Number(entry.bytes || packageFileBytes({ data: entry.data }).byteLength) : 0;
107
+ const qualified = inspection.status === 'valid' && archive?.state === 'qualified' && Boolean(entry)
108
+ && (!declaredSha || declaredSha === entrySha) && (!declaredBytes || declaredBytes === entryBytes);
109
+ claims.push(Object.freeze({
110
+ referenceTarget,
111
+ state: qualified ? 'available-qualified' : 'present-unqualified',
112
+ reason: qualified ? '' : inspection.status !== 'valid' ? 'parent-carrier-inspection-invalid' : archive?.state !== 'qualified' ? 'cache-archive-unqualified' : !entry ? 'cache-entry-unresolved' : 'cache-entry-identity-mismatch',
113
+ classification: String(material.classification || ''),
114
+ sourceRequirementId: String(material.requirementId || material.sourceRequirementId || ''),
115
+ workspaceId: String(cache.workspaceId || ''),
116
+ cacheArtifactPath: String(cache.artifactPath || ''),
117
+ cacheArchivePath: archivePath,
118
+ archiveEntry: String(material.archiveEntry || ''),
119
+ targetWorkspaceId: String(material.targetWorkspaceId || parsed?.workspaceId || ''),
120
+ targetPath: String(material.targetPath || material.originalPath || parsed?.path || ''),
121
+ bytes: entryBytes, sha256: entrySha, data: entry?.data || null
122
+ }));
123
+ }
124
+ }
125
+ const byTarget = new Map();
126
+ for (const claim of claims) {
127
+ const list = byTarget.get(claim.referenceTarget) || [];
128
+ list.push(claim); byTarget.set(claim.referenceTarget, list);
129
+ }
130
+ const entries = [];
131
+ for (const [referenceTarget, targetClaims] of byTarget.entries()) {
132
+ const qualified = targetClaims.filter((item) => item.state === 'available-qualified');
133
+ const digests = [...new Set(qualified.map((item) => item.sha256).filter(Boolean))];
134
+ if (digests.length !== 1) continue;
135
+ const same = qualified.filter((item) => item.sha256 === digests[0]);
136
+ if (!same.length) continue;
137
+ const first = same[0];
138
+ entries.push(Object.freeze({
139
+ referenceTarget, data: first.data, bytes: first.bytes, sha256: first.sha256,
140
+ providerId: 'qualified-package-parent-exact-material',
141
+ providerKind: 'qualified-package-parent-cache-material',
142
+ provenance: Object.freeze({
143
+ parentPackagePath: String(input.parentPackagePath || ''), parentPackageSha256: String(input.parentPackageSha256 || ''),
144
+ providerMode: 'qualified-package-parent-cache', cacheArtifactPath: first.cacheArtifactPath, cacheArchivePath: first.cacheArchivePath,
145
+ archiveEntry: first.archiveEntry, sourceRequirementIds: Object.freeze([...new Set(same.map((item) => item.sourceRequirementId).filter(Boolean))].sort()),
146
+ referenceTarget, workspaceId: first.targetWorkspaceId || first.workspaceId, path: first.targetPath, authority: 'none'
147
+ })
148
+ }));
149
+ }
150
+ return Object.freeze({
151
+ state: inspection.status === 'valid' ? 'qualified' : 'present-unqualified', inspectionStatus: String(inspection.status || ''),
152
+ entries: Object.freeze(entries), claims: Object.freeze(claims),
153
+ boundary: 'Exact material already present in a received qualified package cache may satisfy a newly authored return requirement only after exact declared-target and byte-identity qualification. Reuse is mechanical byte closure only: it does not select Workspace source, create semantic authority, infer delegation, or authorize repository discovery.'
154
+ });
155
+ }
156
+
157
+ export function resolvePackageParentRequirementMaterials(requirements = {}, provider = {}) {
158
+ const out = [];
159
+ const byTarget = new Map((provider.entries || []).map((entry) => [String(entry.referenceTarget || ''), entry]));
160
+ for (const requirement of allBlockingRequirements(requirements)) {
161
+ const target = String(requirement.reference?.target || requirement.materialReference || '').trim();
162
+ if (!target) continue;
163
+ const entry = byTarget.get(target);
164
+ if (!entry) continue;
165
+ out.push(Object.freeze({
166
+ requirementId: String(requirement.id || ''), referenceTarget: target, path: String(entry.provenance?.path || ''),
167
+ data: entry.data, bytes: Number(entry.bytes || 0), sha256: String(entry.sha256 || ''),
168
+ providerId: String(entry.providerId || ''), providerKind: String(entry.providerKind || ''),
169
+ provenance: Object.freeze({ ...(entry.provenance || {}), reboundRequirementId: String(requirement.id || ''), reboundClassification: String(requirement.classification || '') }),
170
+ authority: Object.freeze({ packageParentMaterialQualified: true, semanticAuthority: 'none', sourceSelectionAuthority: false })
171
+ }));
172
+ }
173
+ return Object.freeze(out);
174
+ }
175
+
176
+ export function projectPackageParentMaterialClosurePreflight(requirements = {}, provider = {}) {
177
+ const claimsByTarget = new Map();
178
+ for (const claim of provider.claims || []) { const list = claimsByTarget.get(String(claim.referenceTarget || '')) || []; list.push(claim); claimsByTarget.set(String(claim.referenceTarget || ''), list); }
179
+ const entryTargets = new Set((provider.entries || []).map((item) => String(item.referenceTarget || '')));
180
+ const projected = [];
181
+ for (const requirement of allBlockingRequirements(requirements)) {
182
+ const target = String(requirement.reference?.target || requirement.materialReference || '').trim();
183
+ if (!target) continue;
184
+ const claims = claimsByTarget.get(target) || [];
185
+ const state = entryTargets.has(target) ? 'available-qualified' : claims.length ? 'present-unqualified' : 'absent';
186
+ projected.push(Object.freeze({
187
+ requirementId: String(requirement.id || ''), classification: normalizeRequirementClass(requirement.classification), referenceTarget: target, state,
188
+ provenance: Object.freeze(claims.map((claim) => Object.freeze({ cacheArchivePath: claim.cacheArchivePath, archiveEntry: claim.archiveEntry, sha256: claim.sha256, reason: claim.reason }))),
189
+ nextAction: state === 'available-qualified' ? 'No action required; exact parent-carrier bytes are mechanically available.' : `Supply exact qualified material for ${target} through an explicit local binding, qualified Workspace provider, or qualified received-package cache surface. Tooling will not scan repositories or infer a source.`
190
+ }));
191
+ }
192
+ const blockers = projected.filter((item) => item.state !== 'available-qualified');
193
+ return Object.freeze({
194
+ state: blockers.length ? 'action-required' : 'ready', requirements: Object.freeze(projected), blockerCount: blockers.length,
195
+ boundary: 'This preflight classifies exact return-material closure only. Qualified received-package bytes may close declared material requirements, but this does not create semantic authority, select a Workspace source, establish process applicability, or authorize repository/network discovery.'
196
+ });
197
+ }
198
+
199
+ function allBlockingRequirements(requirements = {}) { return [...(requirements.required || []), ...(requirements.endpointRoles || []), ...(requirements.participantRoles || []), ...(requirements.dependencies || [])]; }
200
+ function normalizeRequirementClass(value = '') { const v = String(value || ''); return v === 'endpoint-role' || v === 'participant-role' ? v : v || 'required'; }
201
+ function emptyExactMaterialProvider(state = 'unavailable') { return Object.freeze({ state, inspectionStatus: '', entries: Object.freeze([]), claims: Object.freeze([]), boundary: 'No qualified received-package exact material provider is available; Tooling will not infer one.' }); }
202
+
80
203
  export function projectRequiredContextWorkspaceSelectionPreflight(input = {}) {
81
204
  const reuse = input.packageParentReuse || input.reuse || {};
82
205
  const currentWorkspaceIds = new Set([...(input.currentWorkspaceIds || [])].map(normalizeId).filter(Boolean));
@@ -8,15 +8,21 @@ export const PORTABLE_SHARED_AUDIT_CAPABILITY_SCHEMA_ID = 'tiinex.portable.share
8
8
  export function auditPortableRecord(record = {}, options = {}) {
9
9
  const schemaId = String(record.schemaId || record.currentSchemaId || '');
10
10
  const requireExactSchemaAuthority = options.requireExactSchemaAuthority === true;
11
- const runtimeAuthority = requireExactSchemaAuthority ? portableRuntimeValidationAuthorityForRecord(record) : null;
12
- const runtimeProjection = requireExactSchemaAuthority ? runtimeAuthority : portableRuntimeValidationContractForSchema(schemaId);
11
+ const explicitSchemaValidationAuthority = options.schemaValidationAuthority || null;
12
+ const runtimeAuthority = explicitSchemaValidationAuthority || (requireExactSchemaAuthority ? portableRuntimeValidationAuthorityForRecord(record) : null);
13
+ const runtimeProjection = explicitSchemaValidationAuthority
14
+ ? (explicitSchemaValidationAuthority.state === 'qualified' ? explicitSchemaValidationAuthority : null)
15
+ : requireExactSchemaAuthority
16
+ ? runtimeAuthority
17
+ : portableRuntimeValidationContractForSchema(schemaId);
13
18
  let result;
14
19
  try {
15
20
  result = runAudit({
16
21
  record,
17
22
  markdown: record.markdown,
18
- validationContractOverride: runtimeProjection?.state === 'qualified' ? runtimeProjection.compiledContract : null,
19
- schemaValidationAuthority: requireExactSchemaAuthority ? runtimeAuthority : null,
23
+ validationContractOverride: options.validationContractOverride || (runtimeProjection?.state === 'qualified' ? runtimeProjection.compiledContract : null),
24
+ schemaValidationAuthority: explicitSchemaValidationAuthority || (requireExactSchemaAuthority ? runtimeAuthority : null),
25
+ schemaReferenceAuthorities: options.schemaReferenceAuthorities || null,
20
26
  schemaReferenceContext: options.schemaReferenceContext || 'historical'
21
27
  });
22
28
  } catch (error) {
@@ -4,6 +4,9 @@ import { projectGroundingSourceEvidence } from './grounding.sourceEvidence.js';
4
4
  import { projectGroundingPlanningContext } from './grounding.planningContext.js';
5
5
  import { projectGroundingParticipantContext } from './grounding.participantContext.js';
6
6
  import { projectGroundingProcessApplicability } from './grounding.processApplicability.js';
7
+ import { projectGroundingImplementationSourceAuthority } from './grounding.implementationSourceAuthority.js';
8
+ import { projectGroundingDelegationReadiness } from './grounding.delegationReadiness.js';
9
+ import { projectGroundingDelegationArtifactAuthority } from './grounding.delegationArtifactAuthority.js';
7
10
 
8
11
  export const PORTABLE_GROUNDING_CAPSULE_SCHEMA_ID = 'tiinex.portable.grounding-capsule.v1';
9
12
 
@@ -15,8 +18,12 @@ export function projectGroundingCapsule({ authority = null, continuation = null,
15
18
  const workProvenance = projectWorkProvenance({ records, topology });
16
19
  const participantAuthority = projectParticipantAuthority(authority);
17
20
  const participantContext = projectGroundingParticipantContext(authority);
18
- const processApplicability = projectGroundingProcessApplicability(authority);
19
21
  const sourceEvidence = projectGroundingSourceEvidence({ records, contextAudit, continuation, requiredContext });
22
+ const delegationArtifactAuthority = projectGroundingDelegationArtifactAuthority({ authority, records, topology, sourceEvidence });
23
+ const effectiveAuthority = mergeArtifactDelegationAuthority(authority, delegationArtifactAuthority);
24
+ const processApplicability = projectGroundingProcessApplicability(effectiveAuthority);
25
+ const implementationSourceAuthority = projectGroundingImplementationSourceAuthority({ authority: effectiveAuthority, records, contextAudit, requiredContext });
26
+ const delegationReadiness = projectGroundingDelegationReadiness({ authority: effectiveAuthority, processApplicability, implementationSourceAuthority });
20
27
  return Object.freeze({
21
28
  schema: PORTABLE_GROUNDING_CAPSULE_SCHEMA_ID,
22
29
  semanticReductions: Object.freeze(requiredContext.slice(0, MAX_CONTEXT).map(reduceRequiredContext)),
@@ -29,22 +36,46 @@ export function projectGroundingCapsule({ authority = null, continuation = null,
29
36
  recipientState: String(authority?.role?.state || 'unresolved'),
30
37
  holder: String(authority?.holderBinding?.roleLabel || ''),
31
38
  holderState: String(authority?.holderBinding?.state || 'unresolved'),
32
- compatibility: String(authority?.holderBinding?.recipientCompatibility || 'unresolved')
39
+ compatibility: String(authority?.holderBinding?.recipientCompatibility || 'unresolved'),
40
+ authorizationState: String(authority?.holderBinding?.authorization?.state || (String(authority?.holderBinding?.state || '') === 'not-applicable' ? 'not-applicable' : 'unresolved')),
41
+ authorizationSource: String(authority?.holderBinding?.authorization?.source || ''),
42
+ assertionMode: String(authority?.holderBinding?.assertionMode || authority?.holderBinding?.authorization?.assignmentMode || ''),
43
+ authorizedModes: Object.freeze([...(authority?.holderBinding?.authorization?.authorizedModes || [])]),
44
+ authorizationBasis: String(authority?.holderBinding?.authorization?.modeAuthority?.provenance?.basis || authority?.holderBinding?.authorization?.provenance?.basis || ''),
45
+ durableIdentityState: String(authority?.holderBinding?.durableIdentity?.state || 'not-established')
33
46
  }),
34
47
  participantAuthority,
35
48
  participantContext,
36
49
  processApplicability,
50
+ implementationSourceAuthority,
51
+ delegationArtifactAuthority,
52
+ delegationReadiness,
37
53
  workProvenance,
38
54
  unresolved: Object.freeze([
39
55
  ...workProvenance.unresolved,
40
56
  ...participantContext.unresolved,
41
57
  ...processApplicability.unresolved,
58
+ ...implementationSourceAuthority.unresolved,
59
+ ...delegationReadiness.blockers.map((item) => ({ code: item.code, detail: item.request })),
42
60
  ...sourceEvidence.blockers.map((item) => ({ code: item.code, detail: item.request }))
43
61
  ]),
44
62
  boundary: 'Full Required Context bodies remain selector-gated.'
45
63
  });
46
64
  }
47
65
 
66
+ function mergeArtifactDelegationAuthority(authority = null, artifact = null) {
67
+ if (!artifact || typeof artifact !== 'object') return authority || {};
68
+ const base = authority && typeof authority === 'object' ? authority : {};
69
+ return Object.freeze({
70
+ ...base,
71
+ delegateCapabilityAuthority: base.delegateCapabilityAuthority || artifact.delegateCapabilityAuthority,
72
+ processApplicability: base.processApplicability || artifact.processApplicability,
73
+ delegationTargetAuthority: base.delegationTargetAuthority || artifact.delegationTargetAuthority,
74
+ implementationSourceAuthority: base.implementationSourceAuthority || artifact.implementationSourceAuthority,
75
+ delegationReturnReconciliationExpectation: base.delegationReturnReconciliationExpectation || artifact.delegationReturnReconciliationExpectation
76
+ });
77
+ }
78
+
48
79
  function reduceRequiredContext(entry = {}) {
49
80
  const qualified = String(entry.state || '') === 'qualified';
50
81
  const markdown = qualified && typeof entry.content === 'string' ? entry.content : '';
@@ -0,0 +1,220 @@
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 taskRecord = transferSelection?.record || null;
19
+ const targetWorkspaceId = String(taskRecord?.path || '').split('/')[0] || '';
20
+ const workspaceSource = (sourceEvidence?.workspaces || []).find((item) => String(item.workspace || '') === targetWorkspaceId && ['qualified', 'explicit-profile'].includes(String(item.state || ''))) || null;
21
+ if (!workspaceSource?.repository) unresolved.push('exact-target-repository-authority-not-established');
22
+
23
+ const delegateCapabilityAuthority = recipient && transferSelection ? delegateProjection(recipient, handoff, transferSelection) : null;
24
+ if (!delegateCapabilityAuthority) unresolved.push('delegate-capability-artifact-projection-not-established');
25
+
26
+ const processApplicability = sender && transferSelection ? processProjection(sender, handoff, transferSelection) : null;
27
+ if (!processApplicability) unresolved.push('delegation-applicability-artifact-projection-not-established');
28
+
29
+ const delegationTargetAuthority = taskRecord && workspaceSource && transferSelection
30
+ ? targetProjection(taskRecord, workspaceSource, handoff, transferSelection)
31
+ : null;
32
+ if (!delegationTargetAuthority) unresolved.push('delegation-target-artifact-projection-not-established');
33
+
34
+ const implementationSourceAuthority = taskRecord && recipient && transferSelection
35
+ ? sourceProjection(taskRecord, recipient, handoff, transferSelection)
36
+ : null;
37
+ if (!implementationSourceAuthority) unresolved.push('implementation-source-artifact-projection-not-established');
38
+
39
+ const delegationReturnReconciliationExpectation = transferSelection
40
+ ? returnProjection(handoff, transferSelection)
41
+ : null;
42
+ if (!delegationReturnReconciliationExpectation) unresolved.push('return-reconciliation-artifact-projection-not-established');
43
+
44
+ const ready = Boolean(delegateCapabilityAuthority && processApplicability && delegationTargetAuthority && implementationSourceAuthority && delegationReturnReconciliationExpectation);
45
+ return Object.freeze({
46
+ state: ready ? 'qualified-forward-artifact-closure' : 'not-established',
47
+ delegateCapabilityAuthority,
48
+ processApplicability,
49
+ delegationTargetAuthority,
50
+ implementationSourceAuthority,
51
+ delegationReturnReconciliationExpectation,
52
+ unresolved: Object.freeze([...new Set(unresolved)].map((code) => Object.freeze({ code }))),
53
+ provenance: Object.freeze({
54
+ basis: 'exact-qualified-forward-selected-artifact-chain',
55
+ selectedHandoff: sourceArtifactFromHandoff(handoff),
56
+ controllingTask: taskRecord ? sourceArtifactFromRecord(taskRecord) : null,
57
+ senderRole: sender ? sender.sourceArtifact : null,
58
+ recipientRole: recipient ? recipient.sourceArtifact : null,
59
+ boundary: 'Projection only. Exact Handoff transfer, exact endpoint Role authority, exact controlling Task and exact Workspace source identity are composed mechanically; Role/cache inventory, filenames, adjacency and arbitrary prose are never searched for delegation meaning.'
60
+ }),
61
+ boundary: 'Artifact-derived delegation closure is available only from the exact selected forward chain. It does not select a delegate, invent a process, create source permission, or treat an endpoint alone as delegation authority.'
62
+ });
63
+ }
64
+
65
+ function selectControllingTransfer(handoff, records, topology) {
66
+ const handoffPath = qualifiedHandoffPath(handoff);
67
+ const frontierPaths = new Set((topology?.currentFrontier || []).flatMap((item) => [String(item.path || ''), String(item.resolvedPath || '')]).filter(Boolean));
68
+ const candidates = [];
69
+ for (const transfer of handoff.transfers || []) {
70
+ const target = String(transfer.controllingArtifactTarget || '').trim();
71
+ if (!target) continue;
72
+ const resolved = resolveReference(target, handoffPath);
73
+ if (!resolved) continue;
74
+ const matches = (records || []).filter((record) => String(record.path || '') === resolved && String(record.schemaId || '') === 'tiinex.task.v1' && record.hasContinuityContext && record.hasIntegrity);
75
+ if (matches.length !== 1) continue;
76
+ if (frontierPaths.size && !frontierPaths.has(resolved) && !frontierPaths.has(String(matches[0].id || ''))) continue;
77
+ candidates.push(Object.freeze({ transfer, record: matches[0], resolvedPath: resolved }));
78
+ }
79
+ return candidates.length === 1 ? candidates[0] : null;
80
+ }
81
+
82
+ function qualifiedRole(role, declaredReference = '') {
83
+ const artifact = role?.material?.artifact || null;
84
+ if (String(role?.state || '') !== 'qualified' || String(role?.material?.state || '') !== 'qualified' || !artifact) return null;
85
+ const sha256 = String(artifact.sha256 || '').trim().toLowerCase();
86
+ if (!/^[0-9a-f]{64}$/i.test(sha256)) return null;
87
+ const reference = String(artifact.reference || declaredReference || '').trim();
88
+ if (!reference) return null;
89
+ return Object.freeze({
90
+ label: String(role?.endpoint?.label || artifact.roleLabel || ''),
91
+ kind: String(role?.endpoint?.kind || 'role'),
92
+ roleKind: String(artifact.roleKind || ''),
93
+ boundary: Object.freeze({ ...(role.exactBoundaryLoaded || {}) }),
94
+ authority: Object.freeze({ ...(role.authorityBoundaryLoaded || {}) }),
95
+ sourceArtifact: sourceArtifactFromReference(reference, sha256, String(artifact.schemaId || 'tiinex.party.role.v1'))
96
+ });
97
+ }
98
+
99
+ function delegateProjection(role, handoff, selected) {
100
+ const capabilities = [
101
+ role.roleKind ? Object.freeze({ kind: 'role-kind', value: role.roleKind }) : null,
102
+ role.boundary.inScope ? Object.freeze({ kind: 'role-in-scope', value: role.boundary.inScope }) : null,
103
+ role.authority.mayDo ? Object.freeze({ kind: 'role-may-do', value: role.authority.mayDo }) : null
104
+ ].filter(Boolean);
105
+ if (!role.label || !capabilities.length) return null;
106
+ return Object.freeze({
107
+ explicit: true,
108
+ qualification: 'qualified',
109
+ delegate: Object.freeze({ label: role.label, kind: role.kind || 'role' }),
110
+ capabilities: Object.freeze(capabilities),
111
+ selection: Object.freeze({ state: 'explicit-forward-selected', forwardSelected: true }),
112
+ sourceArtifact: role.sourceArtifact,
113
+ facts: Object.freeze([
114
+ Object.freeze({ kind: 'selected-handoff-transfer', handoff: qualifiedHandoffPath(handoff), transferId: String(selected.transfer.id || ''), transferKind: String(selected.transfer.transferKind || ''), controllingArtifact: selected.resolvedPath }),
115
+ Object.freeze({ kind: 'exact-recipient-role-authority', role: role.label, roleKind: role.roleKind })
116
+ ]),
117
+ provenance: Object.freeze({ source: role.sourceArtifact.path, basis: 'selected-handoff-transfer-to-exact-recipient-role-and-controlling-task', forwardSelector: Object.freeze({ handoff: qualifiedHandoffPath(handoff), transferId: String(selected.transfer.id || ''), controllingArtifact: selected.resolvedPath }) })
118
+ });
119
+ }
120
+
121
+ function processProjection(role, handoff, selected) {
122
+ const facts = [
123
+ role.authority.delegation ? Object.freeze({ kind: 'sender-role-delegation', value: role.authority.delegation }) : null,
124
+ role.authority.requiredInstrument ? Object.freeze({ kind: 'sender-role-required-instrument', value: role.authority.requiredInstrument }) : null,
125
+ role.authority.mayDo ? Object.freeze({ kind: 'sender-role-may-do', value: role.authority.mayDo }) : null,
126
+ Object.freeze({ kind: 'selected-handoff-work-transfer', transferId: String(selected.transfer.id || ''), transferKind: String(selected.transfer.transferKind || ''), controllingArtifact: selected.resolvedPath })
127
+ ].filter(Boolean);
128
+ if (facts.length < 2) return null;
129
+ return Object.freeze({
130
+ explicit: true,
131
+ qualification: 'qualified',
132
+ facts: Object.freeze(facts),
133
+ source: role.sourceArtifact.path,
134
+ 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 || '') }) })
135
+ });
136
+ }
137
+
138
+ function targetProjection(taskRecord, workspaceSource, handoff, selected) {
139
+ const workspaceId = String(taskRecord.path || '').split('/')[0];
140
+ const relativeTask = String(taskRecord.path || '').slice(workspaceId.length + 1);
141
+ const relativeHandoff = String(handoff.workspaceRelativePath || '').replace(/^\/+/, '');
142
+ return Object.freeze({
143
+ explicit: true,
144
+ qualification: 'qualified',
145
+ target: Object.freeze({
146
+ workspaceId,
147
+ repository: String(workspaceSource.repository || ''),
148
+ rootPath: String(workspaceSource.rootPath || ''),
149
+ taskDirectory: posix.dirname(relativeTask),
150
+ handoffDirectory: posix.dirname(relativeHandoff)
151
+ }),
152
+ sourceArtifact: sourceArtifactFromRecord(taskRecord),
153
+ facts: Object.freeze([
154
+ Object.freeze({ kind: 'controlling-task-placement', path: String(taskRecord.path || '') }),
155
+ Object.freeze({ kind: 'workspace-source-identity', workspaceId, repository: String(workspaceSource.repository || ''), rootPath: String(workspaceSource.rootPath || '') })
156
+ ]),
157
+ 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 || '') }) })
158
+ });
159
+ }
160
+
161
+ function sourceProjection(taskRecord, role, handoff, selected) {
162
+ const scope = section(taskRecord.markdown || '', 'Scope');
163
+ const facts = [
164
+ scope ? Object.freeze({ kind: 'controlling-task-scope', value: scope }) : null,
165
+ role.authority.mayDo ? Object.freeze({ kind: 'recipient-role-may-do', value: role.authority.mayDo }) : null,
166
+ role.authority.requiredInstrument ? Object.freeze({ kind: 'recipient-role-required-instrument', value: role.authority.requiredInstrument }) : null,
167
+ Object.freeze({ kind: 'selected-handoff-work-transfer', transferId: String(selected.transfer.id || ''), transferKind: String(selected.transfer.transferKind || ''), controllingArtifact: selected.resolvedPath })
168
+ ].filter(Boolean);
169
+ if (!scope || !role.authority.mayDo) return null;
170
+ return Object.freeze({
171
+ explicit: true,
172
+ qualification: 'qualified',
173
+ sourceArtifact: sourceArtifactFromRecord(taskRecord),
174
+ facts: Object.freeze(facts),
175
+ 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 })
176
+ });
177
+ }
178
+
179
+ function returnProjection(handoff, selected) {
180
+ const completion = handoff.completionExpectation || {};
181
+ const returnTo = String(completion.returnTo || '').trim();
182
+ const retained = (handoff.retainedResponsibilities || []).filter((item) => normalize(item.retainedBy) === normalize(returnTo));
183
+ if (!completion.signalKind || !completion.signalMeaning || !returnTo || retained.length !== 1) return null;
184
+ return Object.freeze({
185
+ explicit: true,
186
+ qualification: 'qualified',
187
+ completionExpectation: Object.freeze({ signalKind: String(completion.signalKind), signalMeaning: String(completion.signalMeaning), returnTo }),
188
+ reconciliation: Object.freeze({ state: 'retained-by-return-target', expectation: String(retained[0].responsibility || '') }),
189
+ sourceArtifact: sourceArtifactFromHandoff(handoff),
190
+ facts: Object.freeze([
191
+ Object.freeze({ kind: 'selected-handoff-completion-expectation', signalKind: String(completion.signalKind), returnTo }),
192
+ Object.freeze({ kind: 'return-target-retained-responsibility', id: String(retained[0].id || ''), retainedBy: returnTo, responsibility: String(retained[0].responsibility || '') })
193
+ ]),
194
+ 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 }) })
195
+ });
196
+ }
197
+
198
+ function sourceArtifactFromRecord(record) {
199
+ return Object.freeze({ workspaceId: String(record.path || '').split('/')[0] || '', path: String(record.path || ''), sha256: sha256(record.markdown || ''), schemaId: String(record.schemaId || '') });
200
+ }
201
+ function sourceArtifactFromHandoff(handoff) {
202
+ return Object.freeze({ workspaceId: String(handoff.workspaceId || ''), path: qualifiedHandoffPath(handoff), sha256: String(handoff.sha256 || '').trim().toLowerCase(), schemaId: String(handoff.schemaId || 'tiinex.handoff.v1') });
203
+ }
204
+ function sourceArtifactFromReference(reference, sha, schemaId) {
205
+ const raw = String(reference || '').trim();
206
+ const cross = raw.match(/^([^:/\\]+)::(.+)$/);
207
+ return Object.freeze({ workspaceId: cross ? cross[1] : '', path: raw, sha256: String(sha || '').toLowerCase(), schemaId: String(schemaId || '') });
208
+ }
209
+ function qualifiedHandoffPath(handoff) { return [String(handoff.workspaceId || ''), String(handoff.workspaceRelativePath || '').replace(/^\/+/, '')].filter(Boolean).join('/'); }
210
+ function resolveReference(reference, ownerPath) {
211
+ const raw = String(reference || '').split('#')[0].trim().replace(/\\/g, '/');
212
+ const cross = raw.match(/^([^:/\\]+)::(.+)$/);
213
+ const candidate = cross ? `${cross[1]}/${cross[2].replace(/^\/+/, '')}` : raw.startsWith('/') ? raw.slice(1) : posix.join(posix.dirname(ownerPath), raw);
214
+ const normalized = posix.normalize(candidate).replace(/^\.\//, '');
215
+ return !normalized || normalized === '..' || normalized.startsWith('../') ? '' : normalized;
216
+ }
217
+ 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() || ''; }
218
+ function sha256(markdown) { return sha256Hex(new TextEncoder().encode(String(markdown || ''))); }
219
+ function normalize(value) { return String(value || '').trim().toLowerCase(); }
220
+ 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.' }); }