Files
jobtrackingapp/docs/i18n/00/B03_inventory.py
T

252 lines
19 KiB
Python

"""Reproduce bounded I18N-00 lexical evidence; never translate or approve locales."""
from collections import Counter
from functools import lru_cache
import hashlib
import json
from pathlib import Path
import re
import subprocess
HERE = Path(__file__).resolve().parent
ROOT = HERE.parents[2]
SOURCE = '1db5f488f6138e4f0f33749452b7d9f47658f4b0'
OWNERS = {
'documents': ['CvVariantController', 'ProfileCvController', 'ProfileCvController.Import',
'ProfileCvController.Pipeline', 'ApplicationAssetsController', 'DocumentsController',
'PublicCvController', 'CareerProfileController', 'AttachmentsController'],
'communications': ['EmailController', 'EmailDraftsController', 'CorrespondenceController',
'GmailController', 'MicrosoftGraphController', 'ImapController'],
'discovery': ['JobDiscoveryController', 'JobImportController'],
'operations': ['AdminProcessingController', 'AdminSystemController', 'AdminAuditController'],
'account-billing': ['AccountLifecycleController', 'BillingController', 'TwoFactorController', 'UsersController'],
}
SCOPE = {f'JobTrackerApi/Controllers/{owner}.cs': namespace
for namespace, owners in OWNERS.items() for owner in owners}
SCOPE.update({f'JobTrackerApi/Services/EmailProviders/{owner}.cs': 'communications'
for owner in ['GmailProvider', 'MicrosoftGraphProvider', 'ImapProvider']})
SCOPE['JobTrackerApi/Services/CoverLetterDocumentRenderer.cs'] = 'documents'
LITERAL = re.compile(r'"((?:\\.|[^"\\])*)"')
DECLARATION = re.compile(r'^\s*(?:public|private|internal|protected)\s+.*?\b(\w+)\s*\(')
BOUNDARY = re.compile(r'\b(?:BadRequest|Conflict|NotFound|Unauthorized|Problem|ValidationProblem|StatusCode)\s*\(')
EXTRA_LINES = {
'JobTrackerApi/Controllers/UsersController.cs': {237: 'security-email-template', 238: 'security-email-template',
265: 'test-email-template', 273: 'test-email-template'},
'JobTrackerApi/Controllers/ProfileCvController.cs': {422: 'generation-prompt-frame', 424: 'generation-prompt-frame',
425: 'generation-prompt-frame', 426: 'generation-prompt-frame', 427: 'generation-prompt-frame',
428: 'generation-prompt-frame', 431: 'generation-prompt-frame', 442: 'http-error-boundary',
443: 'http-error-boundary', 446: 'http-error-boundary', 447: 'http-error-boundary'},
'JobTrackerApi/Controllers/ProfileCvController.Pipeline.cs': {383: 'upstream-error-forwarding',
439: 'processing-outcome-message', 440: 'processing-outcome-message',
564: 'persisted-error-forwarding', 571: 'persisted-error-forwarding'},
}
LABELS = {'Certifications', 'Projects', 'Languages', 'Profile', 'Experience', 'Skills', 'Education'}
PROTECTED = 'expectedVersion jobApplicationId jobId ThreadId CompanyName JobTitle threadId messageId clientRequestId linked rejected review suggested pending_review Pro Premium Stripe Gmail NAV SMTP PDF DOCX MB UUID'.split()
CONTEXT = {
'http-error-boundary': 'HTTP validation/conflict/failure display boundary; preserve status and code identities, inspect client masking or code mapping before choosing translation owner.',
'message-field': 'Display/response field literal; containing declaration and exact expression identify its producer. Do not treat adjacent data fields as interface text.',
'synthetic-preview-example': 'Repository preview/sample CV content, not real career facts; distinguish sample schema keys, labels and example facts before any locale-specific fixture adaptation.',
'exception-boundary': 'Exception or typed failure producer; exposure and forwarding domain need caller review. An exception string is not automatically a UI catalogue entry.',
'generation-prompt-frame': 'Model-instruction/output-language context, distinct from UI locale. Preserve factual source boundaries; no model execution or semantic qualification performed.',
'diagnostic-template': 'Operator diagnostic template; private identifier/path/provider parameters are excluded. Translation/exposure policy unresolved; not user-notification prose by default.',
'upstream-error-forwarding': 'Unbounded exception message forwarded to persisted processing history; inspect upstream code/controlled prose/private-value domains before export.',
'processing-outcome-message': 'Controlled processing admission/outcome prose; preserve machine status/category and distinguish user opt-out from entitlement failure.',
'persisted-error-forwarding': 'Failure text enters persisted history; locale-at-creation versus live-display policy and upstream message domains remain unresolved.',
'processing-email-template': 'Completion/failure email frame; run trigger/status/id, error and ISO completion time are runtime parameters, not translated source content.',
'owned-payload-or-empty-status': 'Owned payload or empty HTTP status boundary with no captured message literal; does not constitute a translatable message.',
'private-content-boundary': 'Subject/data reference without controlled literal; runtime user/provider/document values must retain original content and remain outside translation exports.',
'validation-producer': 'Controlled draft validation producer returned by multiple HTTP callers; numeric limits and protocol field names remain bound to validation semantics.',
'mail-subject-fallback': 'Controlled no-subject fallback only; real provider subject remains original private message content.',
'security-email-template': 'Security mail source frame; preserve token-bearing URL as an opaque private parameter and obtain recipient-language/security wording review.',
'test-email-template': 'Admin test-mail default/wrapper; preserve explicitly supplied subject/body. Timestamp formatting and recipient locale are independent contracts.',
'document-label-or-filename': 'Physical document label/ARIA/filename contract; document settings own language independently of UI. Filename policy remains unresolved.',
}
TRACE_SPEC = {
'discovery-masks-provider-detail': [('JobTrackerApi/Controllers/JobDiscoveryController.cs', [46, 76, 125]),
('job-tracker-ui/src/views/JobDiscoveryPage.tsx', [121, 140, 156])],
'draft-validation-to-presenter': [('JobTrackerApi/Controllers/EmailDraftsController.cs', [92, 128, 220, 222, 224]),
('job-tracker-ui/src/views/CorrespondenceInboxPage.tsx', [122, 404]), ('job-tracker-ui/src/api.ts', [18, 19, 20, 21, 22, 23, 24])],
'cv-revision-code-client-display': [('JobTrackerApi/Controllers/CvVariantController.cs', [140, 202, 212]),
('job-tracker-ui/src/views/CvBuilderEditor.tsx', [226, 227, 229, 315, 548])],
'processing-outcome-mail-and-history': [('JobTrackerApi/Controllers/ProfileCvController.Pipeline.cs', [383, 428, 537, 564, 571, 655, 659]),
('job-tracker-ui/src/views/CareerProfilePage.tsx', [506, 890, 892])],
'letter-output-language-and-aria': [('JobTrackerApi/Services/CoverLetterDocumentRenderer.cs', [36, 37, 42, 56, 59]),
('JobTrackerApi/Services/ApplicationAssetsService.cs', [300, 309])],
'admin-security-mail-transport': [('JobTrackerApi/Controllers/UsersController.cs', [235, 237, 238, 263, 265, 270, 273]),
('JobTrackerApi/Services/SmtpEmailSender.cs', [8, 22])],
'imap-send-failure-boundary': [('JobTrackerApi/Services/EmailProviders/ImapProvider.cs', [60, 61]),
('JobTrackerApi/Controllers/EmailController.cs', [196, 209, 210, 214])],
'admin-error-versus-diagnostic-display': [('JobTrackerApi/Controllers/AdminSystemController.cs', [126, 127, 155, 164]),
('job-tracker-ui/src/views/AdminSystemPage.tsx', [334, 447, 451])],
'processing-stable-code-and-private-labels': [('JobTrackerApi/Controllers/AdminProcessingController.cs', [183, 191, 200, 203, 206]),
('job-tracker-ui/src/views/AdminProcessingPage.tsx', [181, 183, 214, 215, 219])],
'persisted-notification-client-boundary': [('job-tracker-ui/src/components/NotificationsPopover.tsx', [185, 204, 206])],
}
TRACE_PATHS = {path for entries in TRACE_SPEC.values() for path, _ in entries}
PRIOR = {batch: json.loads((HERE / f'BACKEND_MESSAGE_CENSUS_{batch}.json').read_text(encoding='utf-8'))
for batch in ['B01', 'B02']}
PRIOR_PATHS = {binding['path'] for payload in PRIOR.values() for binding in payload['sourceBindings']}
def digest(value):
return hashlib.sha256(value).hexdigest()
@lru_cache(maxsize=None)
def blob(path):
assert path in SCOPE or path in TRACE_PATHS or path in PRIOR_PATHS, path
return subprocess.check_output(['git', 'show', f'{SOURCE}:{path}'], cwd=ROOT)
def selected(line, path):
text = line.strip()
if text.startswith('//'):
return None
if path.endswith('CoverLetterDocumentRenderer.cs'):
return 'document-label-or-filename' if re.search(r'var (letterLabel|bodyLabel) =|return new\(html', text) else None
if 'LogWarning(' in text or 'LogError(' in text or 'LogInformation(' in text:
return 'diagnostic-template' if '"' in text else None
if 'var subject =' in text:
if path.endswith('ProfileCvController.cs'):
return 'generation-prompt-frame'
if path.endswith('GmailController.cs'):
return 'mail-subject-fallback'
if path.endswith('UsersController.cs'):
return 'test-email-template'
if '"' not in text:
return 'private-content-boundary'
return 'processing-email-template'
if re.search(r'\? \$"Your CV|: \$"Your CV', text):
return 'processing-email-template'
if BOUNDARY.search(text) and ('"' in text or re.search(r'\b(?:ex|error|validation|result|outcome)\b', text)):
return 'http-error-boundary'
if ('throw new ' in text or 'new EmailProviderDeliveryException(' in text) and '"' in text:
return 'exception-boundary'
if re.search(r'\b(?:message|Message|Detail|Title|ErrorMessage)\s*=', text) and '"' in text:
return 'message-field'
if re.search(r'\berror\s*=\s*"', text):
return 'validation-producer'
return None
def partition(expression, reason):
raw = LITERAL.findall(expression)
# C# interpolation/raw-string parsing is outside this lexical census.
ambiguous = '"""' in expression or (('$"' in expression) and len(raw) > 2)
candidates, invariants, unresolved = [], [], []
for value in raw:
if ambiguous or reason in {'diagnostic-template', 'synthetic-preview-example', 'generation-prompt-frame'}:
unresolved.append(value)
elif (reason == 'document-label-or-filename' and value.endswith('.pdf')) or (('<' in value or '>' in value) and reason != 'http-error-boundary'):
unresolved.append(value)
elif value in LABELS or (len(value.split()) > 1 and re.search(r'[A-Za-zÀ-ž]', value)
and not value.startswith(('http', '/', 'data:'))) or value in ['Søknadsbrev', 'Brevtekst']:
candidates.append(value)
else:
invariants.append(value)
return raw, candidates, invariants, unresolved
def build():
records, bindings, coverage = [], [], []
for path, namespace in SCOPE.items():
data = blob(path)
lines = data.decode('utf-8').splitlines()
bindings.append({'path': path, 'sha256': digest(data), 'lineCount': len(lines)})
selected_lines = []
declaration, declaration_line = 'file scope / multiline declaration unresolved', 1
for number, line in enumerate(lines, 1):
if DECLARATION.match(line):
declaration, declaration_line = line.strip(), number
reason = EXTRA_LINES.get(path, {}).get(number) or selected(line, path)
if path.endswith('CvVariantController.cs') and 334 <= number <= 346 and reason:
reason = 'synthetic-preview-example'
if reason == 'http-error-boundary' and '"' not in line and not re.search(r'\b(?:ex\.Message|error|validation)\b', line):
reason = 'owned-payload-or-empty-status'
if not reason:
continue
selected_lines.append(number)
expression = line.strip()
raw, candidates, invariants, unresolved = partition(expression, reason)
placeholders = sorted(set(value for segment in raw for value in re.findall(r'(?<!\{)\{([^{}]+)\}(?!\})', segment)))
records.append({
'id': f'I00-B03-{len(records) + 1:04}', 'source': path, 'line': number,
'sourceSha256': digest(data), 'sourceLineSha256': digest(line.encode('utf-8')),
'sourceExpression': expression, 'namespace': namespace, 'owner': Path(path).stem,
'declarationContext': declaration, 'declarationLine': declaration_line,
'boundary': reason, 'sourceLiteralSegments': raw,
'translatorContext': CONTEXT[reason],
'sourceLanguage': 'en/nb-NO' if path.endswith('CoverLetterDocumentRenderer.cs') else 'en source templates; upstream/runtime language not inferred',
'translationCandidateSegments': candidates, 'nonTranslatableSegments': invariants,
'unresolvedSegments': unresolved, 'placeholderExpressions': placeholders,
'embeddedProtocolOrProperTokens': [token for token in PROTECTED if any(re.search(r'(?<!\w)' + re.escape(token) + r'(?!\w)', value) for value in candidates)],
'parameterTypeStatus': 'not resolved by lexical census; inspect declaration/caller before translation',
'sensitivity': 'source templates only; runtime user/provider/document/account/exception values excluded',
'contextStatus': 'owner/boundary inventoried; individual translator and upstream-domain context pending',
'classificationStatus': 'lexical suggestions only; not translator-ready or native reviewed',
'nativeReview': 'not-run', 'runtimeReview': 'not-run', 'translator': None,
})
coverage.append({'source': path, 'selectedLines': selected_lines, 'records': len(selected_lines),
'otherQuotedLinesNotClassified': [number for number, line in enumerate(lines, 1)
if '"' in line and number not in selected_lines],
'scope': 'all loci selected by versioned B03 predicate; not every string in the file'})
traces = []
for trace_id, entries in TRACE_SPEC.items():
evidence = []
for path, numbers in entries:
data = blob(path)
lines = data.decode('utf-8').splitlines()
if not any(binding['path'] == path for binding in bindings):
bindings.append({'path': path, 'sha256': digest(data), 'lineCount': len(lines)})
for number in numbers:
assert 1 <= number <= len(lines)
evidence.append({'source': path, 'line': number, 'sourceSha256': digest(data),
'sourceExpression': lines[number - 1].strip(),
'sourceLineSha256': digest(lines[number - 1].encode('utf-8'))})
traces.append({'id': trace_id, 'scope': 'source-level association only; no runtime execution or complete upstream-domain proof', 'evidence': evidence})
prior_comparison = {batch: {'recordedSource': payload['sourceCommit'], 'files': [
{'source': binding['path'], 'recordedSha256': binding['sha256'],
'currentSha256': digest(blob(binding['path'])),
'sourceBytesUnchanged': binding['sha256'] == digest(blob(binding['path']))}
for binding in payload['sourceBindings']]} for batch, payload in PRIOR.items()}
return {'status': 'partial-research-only', 'sourceCommit': SOURCE,
'method': 'B03 versioned line-boundary predicate and C# lexical captures; not an AST or semantic completeness claim',
'sourceBindings': bindings, 'ownerCoverage': coverage, 'records': records, 'traces': traces,
'priorBatchSourceComparison': prior_comparison,
'counts': {'sources': len(bindings), 'records': len(records),
'byNamespace': dict(Counter(record['namespace'] for record in records)),
'byBoundary': dict(Counter(record['boundary'] for record in records)),
'traces': len(traces), 'traceLineOccurrences': sum(len(trace['evidence']) for trace in traces)},
'segmentAccounting': {key: sum(len(record[key]) for record in records) for key in
['sourceLiteralSegments', 'translationCandidateSegments', 'nonTranslatableSegments', 'unresolvedSegments']}}
def validate(payload):
assert payload['status'] == 'partial-research-only'
assert payload['sourceCommit'] == SOURCE
expected = build()
assert payload == expected, 'inventory differs from immutable source, scope, metadata or reconciled accounting'
assert len({record['id'] for record in payload['records']}) == len(payload['records'])
for record in payload['records']:
assert Counter(record['sourceLiteralSegments']) == Counter(record['translationCandidateSegments'] +
record['nonTranslatableSegments'] + record['unresolvedSegments'])
catalogue = json.loads((HERE / 'LOCALE_CATALOG.json').read_text(encoding='utf-8'))
assert digest((HERE / 'LOCALE_CATALOG.json').read_bytes()) == 'e3c4071134b5aa890183d7c11fea793c25e13f19264012faaaa5131061e3a83b'
assert digest((HERE / 'LOCALE_SCHEMA.json').read_bytes()) == 'df189c9b83e52d9244839e80672fcc2e99bb66ee9f35d8afc457f27f676eb0c3'
assert len(catalogue['locales']) == 60
languages = {locale['tag'].split('-')[0] for locale in catalogue['locales']}
eu24 = set('bg hr cs da nl en et fi fr de el hu ga it lv lt mt pl pt ro sk sl es sv'.split())
assert eu24 <= languages
assert all(locale['status'] == 'planned' and set(locale['surfaces'].values()) == {'planned'} for locale in catalogue['locales'])
return {'status': 'inventory-integrity-only', 'sourceCommit': SOURCE, 'counts': payload['counts'],
'segmentAccounting': payload['segmentAccounting'], 'candidateTags': 60, 'euLanguageGroups': 24,
'fileRecordBindings': len(payload['sourceBindings']) + len(payload['records']),
'traceLineBindings': sum(len(trace['evidence']) for trace in payload['traces']),
'otherQuotedLineFrontier': sum(len(owner['otherQuotedLinesNotClassified']) for owner in payload['ownerCoverage']),
'inventorySha256': digest((HERE / 'B03_CENSUS.json').read_bytes()),
'validatorSha256': digest(Path(__file__).read_bytes()),
'testsSha256': digest((HERE / 'B03_tests.py').read_bytes()),
'priorBatchChangedFiles': {batch: [row['source'] for row in comparison['files'] if not row['sourceBytesUnchanged']]
for batch, comparison in payload['priorBatchSourceComparison'].items()},
'productNativeTests': 'NOT RUN', 'localeStageAcceptance': 'NOT GRANTED'}
if __name__ == '__main__':
import sys
if sys.argv[1:] == ['--build']:
(HERE / 'B03_CENSUS.json').write_text(json.dumps(build(), ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
else:
print(json.dumps(validate(json.loads((HERE / 'B03_CENSUS.json').read_text(encoding='utf-8'))), indent=2))