@tiinex/core 0.32.0 → 0.33.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tiinex/core",
3
- "version": "0.32.0",
3
+ "version": "0.33.0",
4
4
  "description": "Shared host-neutral Tiinex implementation core for artifacts, schemas, validation, lineage, grounding, Handoffs, provenance and deterministic workflows.",
5
5
  "type": "module",
6
6
  "sideEffects": true,
@@ -173,12 +173,12 @@
173
173
  "type": "git",
174
174
  "url": "git+https://github.com/Tiinex/core.git"
175
175
  },
176
- "gitHead": "036df699dd3a0455f849c4c4e421fee7c969e85a",
176
+ "gitHead": "a317bd83e450d04e6e9b0a5229944d958b61eb91",
177
177
  "tiinexRelease": {
178
178
  "policy": "tiinex.master-npm-release.v1",
179
- "sourceCommit": "036df699dd3a0455f849c4c4e421fee7c969e85a",
180
- "sourceTree": "540c88695f9de86c928a737e1ea2c51b5be5cd82",
179
+ "sourceCommit": "a317bd83e450d04e6e9b0a5229944d958b61eb91",
180
+ "sourceTree": "7f7ff3bb4a7926eb901476d777630c3d536ebed2",
181
181
  "repository": "Tiinex/core",
182
- "previousVersion": "0.31.0"
182
+ "previousVersion": "0.32.0"
183
183
  }
184
184
  }
@@ -10,6 +10,7 @@ import { projectPortableValidationContractWithQualifiedLocalRoot } from '../tool
10
10
  import { qualifyRootCreationRepresentation, qualifyContinuationCreationRepresentation } from './creation.representation.js';
11
11
  import { qualifyCreationSchemaReferences, schemaReferenceAuthoritiesForCreation } from './creation.schemaReferences.js';
12
12
  import { qualifySchemaReferenceValue } from './schema.reference.js';
13
+ import { qualifiedCreationAuthorityFromSchemaSource } from './schema.source.js';
13
14
  import { C14N_V2_METHOD_ID, integrityMethodReferenceAuthorityForCreation } from '../integrity/integrity.methodReference.js';
14
15
 
15
16
  export const ARTIFACT_CREATION_CONTRACT_SCHEMA_ID = 'tiinex.artifact.creation.contract.v1';
@@ -39,16 +40,7 @@ export function buildArtifactCreationContract(input = {}, options = {}) {
39
40
  const transitionType = String(input.transitionType || options.transitionType || 'create-artifact').trim();
40
41
  const creationCapability = qualifyArtifactCreationCapability(module, transitionType);
41
42
  const creationAuthority = creationCapability.authority?.compiledContract?.creation || {};
42
- const creation = Object.freeze({
43
- requiredInputs: list(creationAuthority.requiredInputs),
44
- optionalInputs: list(creationAuthority.optionalInputs),
45
- requiredSections: list(creationAuthority.requiredSections),
46
- representationSections: list(creationAuthority.representationSections),
47
- toolingConfigurationFields: list(creationAuthority.toolingConfigurationFields),
48
- inputBindings: list(creationAuthority.inputBindings),
49
- supplementalRequiredFields: list(creationAuthority.supplementalRequiredFields),
50
- requiredShape: list(creationAuthority.requiredShape)
51
- });
43
+ const creation = composeCreationAuthority(module, creationCapability.authority, creationAuthority);
52
44
  const renderer = creationCapability.implementation?.state === 'implemented'
53
45
  ? { status: CapabilityStatus.implemented, ...(creationCapability.implementation.renderer || {}) }
54
46
  : { status: CapabilityStatus.unavailable, id: '', scope: transitionType };
@@ -203,6 +195,96 @@ export function validateArtifactCreationResult(draft = {}, parentRecord = {}, op
203
195
 
204
196
 
205
197
 
198
+
199
+ function composeCreationAuthority(module = null, authority = {}, localCreation = {}) {
200
+ const validationContract = authority?.compiledContract?.validationContract || null;
201
+ const lineage = Array.isArray(validationContract?.lineage) && validationContract.lineage.length
202
+ ? validationContract.lineage
203
+ : [String(module?.id || authority?.schemaId || '')].filter(Boolean);
204
+ const creationAuthorities = [];
205
+ for (const schemaId of lineage) {
206
+ const lineageModule = schemaRegistry.byId?.get(schemaId) || null;
207
+ if (!lineageModule) continue;
208
+ const qualified = qualifiedCreationAuthorityFromSchemaSource(lineageModule);
209
+ if (qualified.state !== 'qualified' || !qualified.compiledContract?.creation) continue;
210
+ creationAuthorities.push({ schemaId, creation: qualified.compiledContract.creation });
211
+ }
212
+ if (!creationAuthorities.length) creationAuthorities.push({ schemaId: String(module?.id || ''), creation: localCreation });
213
+
214
+ const requiredHeadingOrder = [...(validationContract?.validation?.requiredHeadings || [])]
215
+ .filter((item) => Number(item?.level || 0) === 2 && String(item?.title || '').trim())
216
+ .map((item) => String(item.title).trim());
217
+ const requiredHeadingSet = new Set(requiredHeadingOrder);
218
+ const bindingByInput = new Map();
219
+ const requiredInputSet = new Set();
220
+ const optionalInputSet = new Set();
221
+ const toolingFields = [];
222
+ const supplementalByKey = new Map();
223
+ const shapeByKey = new Map();
224
+
225
+ for (const entry of creationAuthorities) {
226
+ const creation = entry.creation || {};
227
+ for (const value of creation.requiredInputs || []) requiredInputSet.add(String(value || '').trim());
228
+ for (const value of creation.optionalInputs || []) optionalInputSet.add(String(value || '').trim());
229
+ for (const value of creation.toolingConfigurationFields || []) pushUnique(toolingFields, String(value || '').trim());
230
+ for (const item of creation.inputBindings || []) {
231
+ const input = String(item?.input || '').trim();
232
+ if (!input) continue;
233
+ const section = String(item?.section || '').trim();
234
+ if (section && requiredHeadingSet.size && !requiredHeadingSet.has(section)) continue;
235
+ bindingByInput.set(input, item);
236
+ }
237
+ for (const item of creation.supplementalRequiredFields || []) {
238
+ const section = String(item?.section || '').trim();
239
+ if (section && requiredHeadingSet.size && !requiredHeadingSet.has(section)) continue;
240
+ const key = `${section}\u0000${String(item?.field || '')}`;
241
+ supplementalByKey.set(key, item);
242
+ }
243
+ for (const item of creation.requiredShape || []) {
244
+ const primitive = item?.primitive || {};
245
+ const section = String(primitive?.section || '').trim();
246
+ if (section && requiredHeadingSet.size && !requiredHeadingSet.has(section)) continue;
247
+ const key = `${String(primitive?.kind || '')}\u0000${String(primitive?.input || '')}\u0000${section}\u0000${String(primitive?.position || '')}`;
248
+ shapeByKey.set(key, item);
249
+ }
250
+ }
251
+
252
+ const bindings = [];
253
+ for (const item of bindingByInput.values()) if (!String(item?.section || '').trim()) bindings.push(item);
254
+ for (const section of requiredHeadingOrder) {
255
+ for (const item of bindingByInput.values()) if (String(item?.section || '').trim() === section && !bindings.includes(item)) bindings.push(item);
256
+ }
257
+ for (const item of bindingByInput.values()) if (!bindings.includes(item)) bindings.push(item);
258
+
259
+ const boundInputs = new Set(bindings.map((item) => String(item?.input || '').trim()).filter(Boolean));
260
+ const requiredInputs = [...requiredInputSet].filter((input) => input && boundInputs.has(input));
261
+ const optionalInputs = [...optionalInputSet].filter((input) => input && boundInputs.has(input) && !requiredInputSet.has(input));
262
+ const requiredSections = requiredHeadingOrder.length
263
+ ? requiredHeadingOrder.filter((section) => bindings.some((item) => String(item?.section || '').trim() === section))
264
+ : uniqueStrings(creationAuthorities.flatMap((entry) => entry.creation?.requiredSections || []));
265
+ const representationSections = requiredSections.length
266
+ ? requiredSections
267
+ : uniqueStrings(bindings.map((item) => String(item?.section || '').trim()).filter(Boolean));
268
+
269
+ return Object.freeze({
270
+ requiredInputs: Object.freeze(requiredInputs),
271
+ optionalInputs: Object.freeze(optionalInputs),
272
+ requiredSections: Object.freeze(requiredSections),
273
+ representationSections: Object.freeze(representationSections),
274
+ toolingConfigurationFields: Object.freeze(toolingFields),
275
+ inputBindings: Object.freeze(bindings),
276
+ supplementalRequiredFields: Object.freeze([...supplementalByKey.values()]),
277
+ requiredShape: Object.freeze([...shapeByKey.values()])
278
+ });
279
+ }
280
+
281
+ function uniqueStrings(values = []) {
282
+ const out = [];
283
+ for (const value of values || []) pushUnique(out, String(value || '').trim());
284
+ return out;
285
+ }
286
+ function pushUnique(values, value) { if (value && !values.includes(value)) values.push(value); }
287
+
206
288
  function validateParentTargetIntegrity(parsed = {}, parentRecord = {}, expectedTarget = '') {
207
289
  const entries = (parsed?.integrity?.entries || []).filter((entry) => entry?.method === C14N_V2_METHOD_ID && String(entry?.towards || '') !== 'self');
208
290
  if (entries.length !== 1) return [];
@@ -38,7 +38,7 @@ export function renderArtifactCreationDraftMarkdown(contract = {}, input = {}) {
38
38
  const lines = [
39
39
  '# Continuity Context', '',
40
40
  `- Envelope Schema: ${envelopeSchemaReference}`,
41
- ...(parent ? renderParent(parent) : []),
41
+ ...(parent ? renderParent(parent, { preserveUnqualifiedSchemaReference: input.preserveUnqualifiedParentSchemaReference === true }) : []),
42
42
  '- Current',
43
43
  ` - Current Schema: ${currentSchemaReference}`,
44
44
  ` - Created At: ${createdAt}`,
@@ -69,10 +69,10 @@ export const genericArtifactCreationImplementation = Object.freeze({
69
69
  execute: renderArtifactCreationDraftMarkdown
70
70
  });
71
71
 
72
- function renderParent(parent) {
72
+ function renderParent(parent, options = {}) {
73
73
  return [
74
74
  '- Parent',
75
- ` - Parent Schema: ${renderSchemaReference(parent.schemaReferenceAuthority)}`,
75
+ ` - Parent Schema: ${renderParentSchemaReference(parent.schemaReferenceAuthority, options.preserveUnqualifiedSchemaReference === true)}`,
76
76
  ...(parent.createdAt ? [` - Created At: ${parent.createdAt}`] : []),
77
77
  ` - Trace: [${parent.traceLabel}](${parent.traceReference})`,
78
78
  ' - Origin:',
@@ -81,6 +81,13 @@ function renderParent(parent) {
81
81
  ];
82
82
  }
83
83
 
84
+ function renderParentSchemaReference(authority = {}, preserveUnqualified = false) {
85
+ const schemaId = String(authority?.schemaId || '').trim();
86
+ const preferredTarget = String(authority?.preferredTarget || authority?.target || '').trim();
87
+ if (preserveUnqualified && schemaId && preferredTarget) return `[${schemaId}](${preferredTarget})`;
88
+ return renderSchemaReference(authority);
89
+ }
90
+
84
91
  function contractDrivenBodyMarkdown(contract = {}, { title = '', values = {} } = {}) {
85
92
  const creation = contract?.creation || {};
86
93
  const bindings = Array.isArray(creation.inputBindings) ? creation.inputBindings : [];
@@ -2,10 +2,13 @@ import { readFile } from 'node:fs/promises';
2
2
 
3
3
  export async function prepareEditorAssistanceCliInput(material = {}, flags = {}) {
4
4
  const focusPath = norm(flags.focus || flags.path || '');
5
- if (!focusPath || !flags.overlay) return { input: { ...material, focusPath }, options: {} };
5
+ const referenceResolutions = flags['reference-resolutions']
6
+ ? JSON.parse(await readFile(String(flags['reference-resolutions']), 'utf8'))
7
+ : [];
8
+ if (!focusPath || !flags.overlay) return { input: { ...material, focusPath, referenceResolutions }, options: {} };
6
9
  const overlayMarkdown = await readFile(String(flags.overlay), 'utf8');
7
10
  const files = (material.files || []).map((file) => norm(file.path || '') === focusPath ? { ...file, content: overlayMarkdown } : file);
8
- const input = { ...material, files, focusPath };
11
+ const input = { ...material, files, focusPath, referenceResolutions };
9
12
  if (Array.isArray(material.records)) input.records = material.records.map((record) => norm(record.path || record.id || '') === focusPath ? { ...record, markdown: overlayMarkdown } : record);
10
13
  return { input, options: {} };
11
14
  }
@@ -78,7 +78,7 @@ export function renderQualifiedPortableExactDraft({ contract = {}, schemaId = ''
78
78
  }
79
79
 
80
80
  export function renderPortableLocalContinuityDraft({ contract = {}, schemaId = '', transitionType = 'continue-from-record', parentSnapshot = {}, rendererInput = {} } = {}) {
81
- const markdown = renderArtifactCreationCandidateMarkdown(contract, { ...rendererInput, parentRecord: parentSnapshot, currentSchemaId: schemaId });
81
+ const markdown = renderArtifactCreationCandidateMarkdown(contract, { ...rendererInput, parentRecord: parentSnapshot, currentSchemaId: schemaId, preserveUnqualifiedParentSchemaReference: true });
82
82
  if (!markdown) return Object.freeze({ state: 'unqualified', reason: 'local-continuity-renderer-empty', markdown: '', validation: null, parentRepresentation: null });
83
83
  const parentRepresentation = qualifyPortableRenderedParentRepresentation(markdown, parentSnapshot, transitionType, rendererInput.childPath || '', { allowUnpublishedLocalParent: true });
84
84
  if (parentRepresentation.state !== 'qualified') return Object.freeze({ state: 'unqualified', reason: parentRepresentation.reason || 'local-continuity-parent-representation-mismatch', markdown: '', validation: null, parentRepresentation });
@@ -14,7 +14,7 @@ export function projectPortableEditorAssistance(input = {}) {
14
14
  const focusPath = norm(input.focusPath || input.focus || '');
15
15
  const selectedRecords = focusPath ? records.filter((record) => norm(record.path || record.id || '') === focusPath) : records;
16
16
  const lineageInspection = inspectPortableLineageIntegrity({ records });
17
- const documents = selectedRecords.map((record) => projectDocument(record, records, lineageInspection));
17
+ const documents = selectedRecords.map((record) => projectDocument(record, records, lineageInspection, referenceResolutionsForRecord(input.referenceResolutions || [], record)));
18
18
  const diagnostics = documents.flatMap((item) => item.diagnostics);
19
19
  return freeze({
20
20
  schema: PORTABLE_EDITOR_ASSISTANCE_SCHEMA_ID,
@@ -25,7 +25,7 @@ export function projectPortableEditorAssistance(input = {}) {
25
25
  });
26
26
  }
27
27
 
28
- function projectDocument(record = {}, records = [], lineageInspection = null) {
28
+ function projectDocument(record = {}, records = [], lineageInspection = null, referenceResolutions = []) {
29
29
  const audit = auditPortableRecord(record, { requireExactSchemaAuthority: true });
30
30
  const markdown = String(record.markdown || '');
31
31
  const recordPath = norm(record.path || record.id || '');
@@ -72,9 +72,15 @@ function projectDocument(record = {}, records = [], lineageInspection = null) {
72
72
  boundary: 'Repairs only deterministically malformed Workspace-qualified Parent recovery locators and/or a bare Current Schema id when exact qualified current-schema source authority exists; reseals self integrity and exposes the replacement only after shared audit and loaded-descendant guardrails re-qualify it. External Parent availability is not invented.'
73
73
  }));
74
74
 
75
- const integrityRepair = deterministicIntegrityHygieneRepair(markdown, audit.findings || []);
75
+ const referenceResolution = projectReferenceResolutionAssistance(markdown, referenceResolutions);
76
+ diagnostics.push(...referenceResolution.diagnostics);
77
+ actions.push(...referenceResolution.actions);
78
+
79
+ const integrityRepair = deterministicIntegrityHygieneRepair(markdown, sharedFindings);
76
80
  const repairQualification = integrityRepair.state === 'ready'
77
- ? qualifyReplacementAgainstSharedGuardrails(record, records, integrityRepair.markdown)
81
+ ? qualifyReplacementAgainstSharedGuardrails(record, records, integrityRepair.markdown, {
82
+ allowExistingWarningCodes: sharedFindings.filter((item) => item.severity === 'warning').map((item) => String(item.code || ''))
83
+ })
78
84
  : { state: 'unavailable' };
79
85
  if (integrityRepair.state === 'ready' && integrityRepair.markdown !== markdown && repairQualification.state === 'qualified') actions.push(freeze({
80
86
  id: 'refresh-primary-self-integrity',
@@ -232,6 +238,110 @@ function deterministicReferenceHygieneRepair(record = {}, audit = {}, markdown =
232
238
  return freeze({ state: 'ready', markdown: String(sealed.markdown || candidate), parentReferenceChanged, schemaReferenceChanged, diagnosticCodes: [...new Set(diagnosticCodes)] });
233
239
  }
234
240
 
241
+ function referenceResolutionsForRecord(resolutions = [], record = {}) {
242
+ const recordPath = norm(record.path || record.id || '');
243
+ return (Array.isArray(resolutions) ? resolutions : []).filter((item) => {
244
+ const itemPath = norm(item?.path || '');
245
+ return !itemPath || itemPath === recordPath;
246
+ });
247
+ }
248
+
249
+ function projectReferenceResolutionAssistance(markdown = '', resolutions = []) {
250
+ const source = String(markdown || '');
251
+ if (!source || !Array.isArray(resolutions) || !resolutions.length) return freeze({ diagnostics: [], actions: [] });
252
+ const byTarget = new Map(resolutions.map((item) => [String(item?.target || '').trim(), item]).filter(([target]) => Boolean(target)));
253
+ const references = versionBearingGitHubReferences(source).filter((item) => byTarget.has(item.target));
254
+ const diagnostics = [];
255
+ const actions = [];
256
+ for (const reference of references) {
257
+ const fact = byTarget.get(reference.target) || {};
258
+ const exact = fact.exact || {};
259
+ const latest = fact.latest || {};
260
+ const exactState = String(exact.state || 'unavailable');
261
+ const latestState = String(latest.state || 'unavailable');
262
+ const exactSha = String(exact.sha256 || '');
263
+ const latestSha = String(latest.sha256 || '');
264
+ const latestTarget = String(latest.target || '').trim();
265
+ let diagnostic = null;
266
+ let actionTitle = '';
267
+ if (exactState === 'missing') {
268
+ diagnostic = {
269
+ severity: 'error',
270
+ code: 'reference.permalink.unresolved',
271
+ message: `${reference.field} permalink does not resolve at its declared revision.`,
272
+ params: { field: reference.field, line: reference.line }
273
+ };
274
+ if (latestState === 'resolved' && latestTarget) actionTitle = `Repair ${reference.field} permalink to latest`;
275
+ } else if (exactState === 'unavailable') {
276
+ diagnostic = {
277
+ severity: 'warning',
278
+ code: 'reference.permalink.verification-unavailable',
279
+ message: `${reference.field} permalink could not be verified from the current host.`,
280
+ params: { field: reference.field, line: reference.line }
281
+ };
282
+ if (latestState === 'resolved' && latestTarget) actionTitle = `Use latest ${reference.field} permalink`;
283
+ } else if (exactState === 'resolved' && latestState === 'resolved' && exactSha && latestSha && exactSha !== latestSha) {
284
+ diagnostic = {
285
+ severity: 'warning',
286
+ code: 'reference.permalink.stale',
287
+ message: `${reference.field} permalink resolves, but master contains different bytes.`,
288
+ params: { field: reference.field, line: reference.line }
289
+ };
290
+ if (latestTarget) actionTitle = `Upgrade ${reference.field} permalink to latest`;
291
+ }
292
+ if (diagnostic) diagnostics.push(projectDiagnostic(diagnostic, source));
293
+ if (!actionTitle || !latestTarget || latestTarget === reference.target) continue;
294
+ const replacement = replaceReferenceTargetAtLine(source, reference, latestTarget);
295
+ if (!replacement || replacement === source) continue;
296
+ const sealed = sealIfSelfIntegrityPresent(replacement);
297
+ if (sealed.state === 'blocked') continue;
298
+ const replacementMarkdown = sealed.markdown;
299
+ actions.push(freeze({
300
+ id: `upgrade-permalink-${reference.field.toLowerCase().replace(/[^a-z0-9]+/g, '-')}-${reference.line}`,
301
+ title: actionTitle,
302
+ kind: 'replace-document',
303
+ qualification: 'deterministic-shared-core+explicit-host-resolution',
304
+ sourceSha256: sha256Hex(new TextEncoder().encode(source)),
305
+ replacementMarkdown,
306
+ diagnosticCodes: diagnostic ? [diagnostic.code] : [],
307
+ boundary: 'Uses explicit host-provided resolution evidence for the exact declared GitHub permalink and master candidate. A newer master revision is only offered as an operator-selected Quick Fix; it does not silently replace version-bearing source authority.'
308
+ }));
309
+ }
310
+ return freeze({ diagnostics, actions });
311
+ }
312
+
313
+ function versionBearingGitHubReferences(markdown = '') {
314
+ const lines = String(markdown || '').replace(/\r\n?/g, '\n').split('\n');
315
+ const refs = [];
316
+ for (let index = 0; index < lines.length; index += 1) {
317
+ const line = String(lines[index] || '');
318
+ const fieldMatch = line.match(/^\s*-\s+(Envelope Schema|Parent Schema|Current Schema)\s*:\s*\[[^\]]+\]\((https:\/\/github\.com\/[^)]+\/blob\/[^)]+)\)\s*$/i);
319
+ if (fieldMatch) refs.push({ field: fieldMatch[1], target: fieldMatch[2], line: index + 1 });
320
+ if (/^\s*-\s+\[sha256-base64url-c14n-v2\]\(/.test(line)) {
321
+ const methodMatch = line.match(/^\s*-\s+\[sha256-base64url-c14n-v2\]\((https:\/\/github\.com\/[^)]+\/blob\/[^)]+)\)\s*$/i);
322
+ if (methodMatch) refs.push({ field: 'Integrity method', target: methodMatch[1], line: index + 1 });
323
+ }
324
+ }
325
+ return refs;
326
+ }
327
+
328
+ function replaceReferenceTargetAtLine(markdown = '', reference = {}, latestTarget = '') {
329
+ const lines = String(markdown || '').replace(/\r\n?/g, '\n').split('\n');
330
+ const index = Number(reference.line || 0) - 1;
331
+ if (index < 0 || index >= lines.length) return '';
332
+ if (!lines[index].includes(reference.target)) return '';
333
+ lines[index] = lines[index].replace(reference.target, latestTarget);
334
+ return lines.join('\n');
335
+ }
336
+
337
+ function sealIfSelfIntegrityPresent(markdown = '') {
338
+ const state = canonicalC14nV2SelfState(markdown);
339
+ if (state.state === 'unavailable') return freeze({ state: 'ready', markdown: String(markdown || '') });
340
+ if (!['verified', 'mismatch', 'prepared'].includes(state.state)) return freeze({ state: 'blocked', markdown: String(markdown || '') });
341
+ const sealed = sealC14nV2Self(markdown);
342
+ return sealed.state === 'sealed' ? freeze({ state: 'ready', markdown: sealed.markdown }) : freeze({ state: 'blocked', markdown: String(markdown || '') });
343
+ }
344
+
235
345
  function normalizeMalformedWorkspaceQualifiedTarget(value = '') {
236
346
  const raw = String(value || '').trim();
237
347
  if (classifyParentRecoveryReference(raw).kind !== 'malformed-workspace-qualified') return raw;
@@ -281,6 +391,25 @@ function locatedLine(lines = [], index = -1, state = 'deterministic', basis = ''
281
391
  export function locateFindingLine(finding = {}, markdown = '') {
282
392
  const lines = String(markdown || '').replace(/\r\n?/g, '\n').split('\n');
283
393
  const params = finding.params || finding;
394
+ const code = String(finding.code || '');
395
+
396
+ // Integrity findings often carry the generic field name `Value`. That field
397
+ // appears once per integrity relation, so resolving `field:Value` first would
398
+ // incorrectly anchor a self-integrity finding on the first Parent digest.
399
+ // Resolve semantically-owned integrity locations before generic field lookup.
400
+ if (code === 'integrity.c14n-v2.mismatch' || code === 'integrity.c14n-v2.ambiguous' || code === 'portable.lineage-integrity.child-self-mismatch' || code === 'portable.lineage-integrity.child-self-unavailable') {
401
+ const selfValueIndex = primarySelfIntegrityValueLine(lines);
402
+ if (selfValueIndex >= 0) return locatedLine(lines, selfValueIndex, 'deterministic', 'continuity-integrity-primary-self-value');
403
+ }
404
+ if (code === 'integrity.method-reference.unqualified') {
405
+ const headingIndex = lines.findIndex((line) => line.trim() === '# Continuity Integrity');
406
+ const methodIndex = lines.findIndex((line, index) => index > headingIndex && /^\s*-\s+\[sha256-base64url-c14n-v2\]\([^)]+\)\s*$/.test(line));
407
+ if (methodIndex >= 0) return locatedLine(lines, methodIndex, 'deterministic', 'continuity-integrity-method-reference');
408
+ }
409
+
410
+ const explicitLine = Number(params.line || 0);
411
+ if (Number.isInteger(explicitLine) && explicitLine > 0) return locatedLine(lines, explicitLine - 1, 'deterministic', 'explicit-resolution-line');
412
+
284
413
  const field = String(params.field || '').trim();
285
414
  const section = String(params.section || '').trim();
286
415
  const heading = String(params.heading || '').replace(/^#{1,6}\s+/, '').trim();
@@ -295,19 +424,15 @@ export function locateFindingLine(finding = {}, markdown = '') {
295
424
  const envelopeIndex = lines.findIndex((line) => new RegExp(`^\\s*-\\s+${escapeRegExp(owner)}(?:\\s*:.*)?\\s*$`, 'i').test(line));
296
425
  if (envelopeIndex >= 0) return locatedLine(lines, envelopeIndex, 'deterministic-anchor', `envelope-owner:${owner}`);
297
426
  }
298
- const code = String(finding.code || '');
299
427
  if (code.includes('schema.') || code.endsWith('.schema.mismatch') || code === 'audit.schema-authority.unqualified') {
300
428
  const index = lines.findIndex((line) => /^\s*-\s+Current Schema\s*:/.test(line));
301
429
  if (index >= 0) return locatedLine(lines, index, 'deterministic', 'current-schema-field');
302
430
  }
303
- if (code === 'integrity.method-reference.unqualified') {
304
- const headingIndex = lines.findIndex((line) => line.trim() === '# Continuity Integrity');
305
- const methodIndex = lines.findIndex((line, index) => index > headingIndex && /^\s*-\s+\[sha256-base64url-c14n-v2\]\([^)]+\)\s*$/.test(line));
306
- if (methodIndex >= 0) return locatedLine(lines, methodIndex, 'deterministic', 'continuity-integrity-method-reference');
307
- }
308
431
  if (code.includes('integrity') || /integrity|checksum|digest/i.test(String(finding.message || ''))) {
309
432
  const headingIndex = lines.findIndex((line) => line.trim() === '# Continuity Integrity');
310
433
  if (headingIndex >= 0) {
434
+ const selfValueIndex = primarySelfIntegrityValueLine(lines);
435
+ if (selfValueIndex >= 0 && /self-integrity|canonical artifact bytes|child-self/i.test(String(finding.message || ''))) return locatedLine(lines, selfValueIndex, 'deterministic', 'continuity-integrity-primary-self-value');
311
436
  const index = lines.findIndex((line, i) => i > headingIndex && /^\s+-\s+Value\s*:/.test(line));
312
437
  if (index >= 0) return locatedLine(lines, index, 'deterministic', 'continuity-integrity-value');
313
438
  return locatedLine(lines, headingIndex, 'deterministic-anchor', 'continuity-integrity-heading');
@@ -326,6 +451,20 @@ export function locateFindingLine(finding = {}, markdown = '') {
326
451
  return freeze({ state: 'unresolved', line: null, sourceRange: null, basis: 'shared-finding-has-no-deterministic-line-evidence' });
327
452
  }
328
453
 
454
+ function primarySelfIntegrityValueLine(lines = []) {
455
+ const headingIndex = lines.findIndex((line) => String(line || '').trim() === '# Continuity Integrity');
456
+ if (headingIndex < 0) return -1;
457
+ let selfTowards = -1;
458
+ for (let index = headingIndex + 1; index < lines.length; index += 1) {
459
+ const line = String(lines[index] || '');
460
+ if (index > headingIndex + 1 && /^#\s+/.test(line)) break;
461
+ if (/^\s+-\s+Towards\s*:\s*self\s*$/i.test(line)) { selfTowards = index; continue; }
462
+ if (selfTowards >= 0 && /^\s+-\s+Value\s*:/.test(line)) return index;
463
+ if (selfTowards >= 0 && /^-\s+/.test(line)) selfTowards = -1;
464
+ }
465
+ return -1;
466
+ }
467
+
329
468
  function deterministicIntegrityHygieneRepair(markdown = '', findings = []) {
330
469
  const source = String(markdown || '');
331
470
  const codes = new Set((findings || []).map((item) => String(item?.code || '')));
@@ -357,7 +496,9 @@ function deterministicIntegrityHygieneRepair(markdown = '', findings = []) {
357
496
  const diagnosticCodes = [
358
497
  ...(methodReferenceChanged ? ['integrity.method-reference.unqualified'] : []),
359
498
  'integrity.c14n-v2.mismatch',
360
- 'integrity.c14n-v2.ambiguous'
499
+ 'integrity.c14n-v2.ambiguous',
500
+ 'portable.lineage-integrity.child-self-mismatch',
501
+ 'portable.lineage-integrity.child-self-unavailable'
361
502
  ];
362
503
  return freeze({ state: 'ready', markdown: sealed.markdown, methodReferenceChanged, diagnosticCodes: [...new Set(diagnosticCodes)] });
363
504
  }