Compare commits

...

43 Commits

Author SHA1 Message Date
Roberto Treviño Cervantes 675ebffc09 Findings: cin2_logistic predictors() crashes on a cohort with no citología rows at all (I-DBT-3)
selective-ci / selective-ci (pull_request) Failing after 8s
2026-11-16 01:12:54 -06:00
Roberto Treviño Cervantes 7fc0d8ff31 AGENTS and architecture notes: the kit is retired, its jobs named by their new owners 2026-11-15 05:41:19 -06:00
Roberto Treviño Cervantes d83940c966 ISSSTELEON submodule pointer: the kit-exit integration branch 2026-11-15 05:40:28 -06:00
Roberto Treviño Cervantes f11efe9bb0 Ledgers: what the kit-exit integration leaves open; migration heads with the TEA join 2026-11-15 00:49:31 -06:00
Roberto Treviño Cervantes 3db4f1f8f8 Merge remote-tracking branch 'origin/feature/163-tea-redesign' into feature/kit-exit-integration
# Conflicts:
#	AGENTS.md
#	ISSSTELEON
#	docs/ledgers/open-items.md
2026-11-15 00:43:11 -06:00
Roberto Treviño Cervantes 79c7d36756 Merge remote-tracking branch 'origin/main' into feature/kit-exit-integration 2026-11-15 00:42:33 -06:00
Roberto Treviño Cervantes 8615395304 Docs: scope status against the contract, session history and open items as of 2026-11-13 2026-11-15 00:42:33 -06:00
alberto d6244ebb6e ISSSTELEON submodule pointer: history chart and KPI card with measures that publish more groups (#163) 2026-11-13 21:15:48 -06:00
alberto 3bd2ebf505 ISSSTELEON submodule pointer: the EEG result measure draws one bar per alteration (#163) 2026-11-13 19:38:47 -06:00
alberto e0c7643dba dev-data submodule pointer: synthetic EDFs and more EEG alterations; manual deployment shows the EEG alterations (#163) 2026-11-13 19:12:45 -06:00
rockdrigo ae3f6c89fa ISSSTELEON submodule pointer: indicators over FHIR and the TEA views (#163) 2026-11-13 17:03:23 -06:00
rockdrigo f296760c9b Ledgers: G-GEN-1, source terminology as catalog tables, and its implementation; migration heads of the branch (#163)
How: grooming.md gets G-GEN-1 (the proposal, its open questions and the commits that implement layers 1 to 3); AGENTS.md lists the source-terminology revisions on feature/163-source-terminology.

Implications: the issue can cite the branch's commits; the heads in dev are unchanged until it's merged.
2026-11-13 15:59:28 -06:00
alberto a820c7c2bf Manual deployment: indicators section in the guide, patient-level views on for the simulated data; ISSSTELEON submodule pointer (#163) 2026-11-13 15:31:29 -06:00
alberto 415873c767 Merge remote-tracking branch 'origin/feature/163-tea-redesign' into feature/163-tea-redesign
# Conflicts:
#	ISSSTELEON
2026-11-13 15:13:49 -06:00
alberto a9b8623bc5 ISSSTELEON and dev-data submodule pointers: TEA orders hold the study's PDF, and dev-data fills it for the ADOS-2 (#163) 2026-11-13 15:03:02 -06:00
Angel Capetillo Zavala 50034dd471 Add TEA FHIR journey verification 2026-11-13 14:28:18 -06:00
alberto 22331edfe6 Ignore samples/, the generated example documents (#174) 2026-11-13 13:44:28 -06:00
alberto 7dfb4df498 dev-data submodule pointer: CaCu records and TEA ADOS-2 summaries as test documents (#174) 2026-11-13 13:36:21 -06:00
alberto 541a8114c7 Manual deployment: guide, and a one-shot job that writes the CaCu and TEA test documents (#174) 2026-11-13 13:35:40 -06:00
alberto 8a7ed7669d dev-data submodule pointer: TEA data on the redesigned schema (#163) 2026-11-13 12:00:36 -06:00
Roberto Treviño Cervantes 52f378a625 Merge remote-tracking branch 'origin/dev' into dev 2026-11-13 11:54:22 -06:00
Roberto Treviño Cervantes 26dd5b8a01 updating nlp policies; more robust recognition beyond rules 2026-11-13 11:53:48 -06:00
Roberto Treviño Cervantes 35544fc98a fix governance reqs; allow for sandboxed jupyter notebooks for testing 2026-11-13 11:53:48 -06:00
Roberto Treviño Cervantes f9560aee8c improve ingestion system to match isssteleon setup 2026-11-13 11:53:48 -06:00
alberto 74af823764 Merge branch 'worktree-manual-deploy' into feature/163-tea-redesign 2026-11-13 11:52:44 -06:00
alberto 23708bfff9 Manual deployment: compose file renamed to docker-compose.yml, ports 5210-5212 (#163) 2026-11-13 11:52:34 -06:00
alberto 7a08c0b335 Merge branch 'worktree-manual-deploy' into feature/163-tea-redesign 2026-11-12 20:06:54 -06:00
alberto 35df57fcec Manual deployment: one compose project for the platform and the simulated hospital, ports from .env 2026-11-12 19:57:42 -06:00
alberto a495fc2852 Ignore Claude Code's local folder (#163) 2026-11-12 19:50:26 -06:00
alberto dadd7249fa Ignore graphify's output; submodule pointer (#163) 2026-11-12 19:47:50 -06:00
alberto 4a47d5f965 TEA redesign: review fixes (knowledge versions, note within the chain, M30 hidden outside FHIR), the plan and its implementation notes (#163) 2026-11-12 19:47:19 -06:00
edgar 2cfa573204 TEA redesign implemented except the WebApp: submodule pointer and open items (#163) 2026-11-12 15:22:04 -06:00
Roberto Treviño Cervantes bcff4d495d Merge staging into dev 2026-11-12 01:12:36 -06:00
angel 285575bfce Merge pull request 'Chore: Updating main with dev new deploy mechanism' (#173) from dev into main
Reviewed-on: #173
2026-11-11 20:57:03 -06:00
angel e7617dd8ea Merge branch 'main' into dev 2026-11-11 20:56:52 -06:00
angel cd89c1192a Merge pull request 'feat(deploy): add native release deployment via Gitea Actions' (#172) from feature/deploy-terminal-release into dev
Reviewed-on: #172
2026-11-11 15:17:44 -06:00
Angel Capetillo Zavala ad9ab50ff2 feat(deploy): add native release deployment workflow
selective-ci / selective-ci (pull_request) Successful in 25m25s
2026-11-11 13:55:56 -06:00
angel e8d19e88e1 Merge pull request 'fix(deploy): accept canonical Gitea checkout origin variants' (#171) from feature/deploy-any-branch into dev
Reviewed-on: #171
2026-11-11 10:32:32 -06:00
Angel Capetillo Zavala c3760309aa fix(deploy): accept canonical Gitea checkout origin variants
selective-ci / selective-ci (pull_request) Successful in 32s
2026-11-11 10:29:20 -06:00
Angel Capetillo Zavala 91f3b9942a feat(deploy): support centralized deployment from selected branch 2026-11-11 10:14:36 -06:00
angel ddbca8e1e2 Actualizar .gitea/workflows/deploy-dev.yml 2026-11-11 10:00:40 -06:00
angel 0da1bb6a8f Actualizar .gitea/workflows/deploy-dev.yml 2026-11-11 09:59:23 -06:00
angel 8ec9c86d10 Merge pull request 'Chore: Update main with dev.' (#170) from dev into main
Reviewed-on: #170
2026-11-10 20:15:40 -06:00
51 changed files with 4764 additions and 148 deletions
+202
View File
@@ -0,0 +1,202 @@
# Native release deployment
This manual-dispatch workflow prepares and deploys a published Release to
`10.0.10.41` using native Ubuntu processes. A successful run means it has
resolved the tag, transferred the pinned application source, prepared the
instance, started three supervised user services, verified local health and
confirmed that the runner can reach WebApp and the proxied API at
`http://10.0.10.41:<puerto>/`. It then checks the service states once more.
The intermediate bundle remains in the job workspace; no manual download,
transfer, installation or activation is required per deployment.
The installer revision comes from the selected workflow branch, normally
`dev`; the application revision comes exclusively from the tag. It is not
restricted to `dev`, `staging` or `main`. The first intended test is a
published Release for the operator-selected `staging` commit on port `18090`.
No Release, tag, deployment or infrastructure change is created by this work.
## Architecture and prerequisites
An isolated non-root deployment account connects to the host over SSH with a
dedicated key and a verified host key. It owns an isolated installation parent
and runs its own `systemd --user` manager, with lingering enabled once by the
operator. The account must not have Docker, sudo, wheel or root group
membership; it must have no other administrative grants or capabilities. It
can execute commands and write within its own permissions, so the private key
is sensitive even though it does not confer root access. SSH key `restrict`
options can disable forwarding and interactive PTY access; they do not prevent
the account from executing arbitrary commands as itself.
The workflow uses no `sudo` and never changes the existing runner or Docker
configuration. The operator confirmed that `ubuntu-latest`, `ubuntu-24.04` and
`ubuntu-22.04` jobs use `docker://docker.gitea.com/runner-images` as configured
in `/etc/act_runner/config.yaml`. The application itself runs as native user
services on the host. The job must be able to reach Gitea, SSH on labserver, and the
application's public port; these are required for the final checks. The host
must provide Python >=3.12, uv, compatible Node/npm, nginx with
`/etc/nginx/mime.types`, Tesseract and `spa`/`eng` language data. The inspected
application container uses Node 22. The account must be able to reach any
required package registries, and uv, npm, nginx and Tesseract must be on its
noninteractive SSH PATH. `systemd --user`, its D-Bus runtime and the
sandbox options in the units must work on the target Ubuntu configuration.
User services explicitly use `PrivateUsers=true` with filesystem sandboxing;
this requires unprivileged user namespaces to be available. Depending on the
host, sandbox settings may fail or be ineffective; validate their effective
behavior before relying on them. Availability and compatibility have not been
demonstrated by local tests.
The operator reports that `admon` has interactive sudo and that the runner is
an `act-runner` host process. `admon` is a member of Docker and sudo groups and
must not be the deployment/service account. No assumption is made about runner
sudo access. Use `admon` for the one-time authorized setup, not as the runtime
identity or as an Action credential.
## One-time operator setup
Only after authorization for physical changes, an administrator should:
1. Provision a dedicated non-root account with a real home and a shell capable
of the SSH commands and SFTP used here. Verify it has no Docker,
administrative, custom sudoers or capability grants. The installer rejects
the standard privileged groups but cannot detect every possible grant.
2. Create an isolated parent directory outside `/srv/workingnarrative-dev`
and all existing installation/data paths; give only that account the needed
access. For a new directory an administrator may use, for example,
`sudo mkdir /srv/workingnarrative-native`, followed by a reviewed `chown`
and `chmod 0750` for the chosen account. Do not overwrite or reassign an
existing directory without a separate review.
3. Provision an SSH deployment key for that account through the authorized
channel. Restrict its `authorized_keys` entry appropriately and verify the
server host-key fingerprint independently. Do not store the `admon` password
or enable passwordless sudo. Confirm SSH and SFTP work for this account.
4. Enable lingering once with `sudo loginctl enable-linger <account>`. Confirm
the account's user manager and `/run/user/<uid>/bus` are available. This is
needed so services survive the SSH session and start after reboot. Confirm
that the required systemd user-service sandbox options work; the deployment
fails closed if its manager or services cannot start.
5. Configure the following Gitea Actions variables and secrets through the
authorized administrative process. No credentials are provisioned here.
| Kind | Name | Value |
|---|---|---|
| Variable | `NATIVE_ACCOUNT` | Dedicated deployment/service account |
| Variable | `NATIVE_SSH_PORT` | SSH port for the host |
| Variable | `NATIVE_HOSTNAME` | Exact hostname returned by the host |
| Variable | `NATIVE_PARENT` | Existing dedicated absolute parent directory |
| Secret | `NATIVE_SSH_KEY` | Dedicated account's private key, in full |
| Secret | `NATIVE_KNOWN_HOSTS` | Independently verified SSH known-hosts entry |
The job writes the key and known-hosts data to temporary files with a private
umask and removes them on normal shell exit. Use a trusted runner and its
secret controls; abrupt termination may prevent cleanup. The Gitea job token must have read access to the published Release and all
private application submodules. Configure only the required cross-repository
read access through the authorized Gitea administration process. The resolver
passes the job token to Git as an HTTP header scoped to the institutional
repository namespace; it does not embed credentials in repository URLs.
## Running a deployment
After review, integration and one-time setup, the operator may publish the
Release pointing to the selected application commit. In Gitea, dispatch
`deploy-terminal-release` from the reviewed installer branch and supply the
exactly three inputs: published `tag`, public `puerto` (default `18090`) and
loopback `puerto_api` (default `28090`). Both ports must be integers in
`1024..65535`, distinct and available on the host. This is a new-install-only
workflow. It rejects an existing instance, unit path or occupied port rather
than updating or overwriting it. Choose a different free API port when another
native instance already uses the requested value.
The Action performs these steps:
1. Validate the institutional event, origin and published Release, fetch the
exact tag, peel it to a commit and check that neither tag nor Release changed.
2. Check out only recognized institutional application gitlinks at their
committed SHAs, independently of branch heads. Archive committed application
components and record tag, release ID, tag object, application and installer
commits, gitlinks, installer file hashes and bundle digest.
3. Connect to the configured host with strict SSH host-key checking. Check the
hostname, account, groups, user manager and lingering, create a unique
account-owned staging directory, and transfer the bundle and reviewed
installer. The requested API port is included in the release record and
checked against the value passed to the remote installer. The job does not copy any files into system-wide systemd paths.
4. Exclusively create `NATIVE_PARENT/isssteleon-native-<puerto>`, check both
ports, install Python and Node dependencies using the release's lockfiles,
and compile Angular. Create four new SQLite files and validate the effective
Persistance URLs and empty isolated files before running Alembic.
5. Generate three units in the instance, link them exclusively into the
account's user-unit directory, reload its user manager, and enable/start the
API, indicator worker and nginx. There is no privileged operation per run.
6. Verify the three units, direct and proxied `/health`, Angular root and SPA
fallback on the host. From the runner check the public root and proxied API
on `10.0.10.41:<puerto>`, then recheck the host services. Any failure makes
the Action fail; a successful external check is recorded on the host.
Preparation uses the selected release's equivalents of these commands:
```sh
# application/WebApi
uv sync --locked --no-dev --extra sql-drivers
uv run --no-sync alembic -c ../Persistance/persistance/cacu/alembic.ini upgrade head
uv run --no-sync alembic -c ../Persistance/persistance/cama/alembic.ini upgrade head
uv run --no-sync alembic -c ../Persistance/persistance/tea/alembic.ini upgrade head
uv run --no-sync alembic -c ../Persistance/persistance/governance/alembic.ini upgrade head
# application/WebApp
npm ci
npm run build -- --configuration production
```
The service commands use `.venv/bin/gunicorn` on `127.0.0.1:<API port>`,
`.venv/bin/python -m webapi.indicadores_vivos`, and a dedicated nginx process
for the Angular production files and proxy. The nginx process listens on the
requested public port. The four domain databases, MLflow database and
artifacts, reports, indicator queue and nginx temporary files are under the new
instance's `data/`. No Docker volume, database, compose project or existing
Docker installer is used or modified.
`installation.json` records identity, paths, service names, both requested ports, phases,
status and health checks. User services use `default.target`, restart on
failure and write to the user journal. For example, under the service account:
```sh
systemctl --user status isssteleon-native-18090-{api,worker,web}.service
journalctl --user -u isssteleon-native-18090-api.service -u isssteleon-native-18090-worker.service -u isssteleon-native-18090-web.service
```
The helper explicitly sets `XDG_RUNTIME_DIR` and `DBUS_SESSION_BUS_ADDRESS`
for noninteractive SSH. An operator's interactive session may also need these
set for `systemctl --user` and `journalctl --user`. The host-local checks do
not prove that the indicator worker completed a calculation or exercise
clinical workflows; perform an authorized functional smoke test separately.
## Failure handling and validation
A failed build, migration, activation or health check makes the job fail.
Instance files and databases are retained for inspection; no retry automatically
reuses or migrates them. Failed activation attempts to disable/stop only the
newly linked user units and records failure; any links left by systemd remain
for inspection. If that stop
itself fails, the operator must inspect the user manager; no global cleanup is
performed. A public HTTP failure is reported back into the instance record when
SSH remains available. If SSH fails while reporting, the job log is authoritative
about that failure. Recovery, deletion or updates require a separate review.
Automated local tests use temporary Git repositories and bundles, mock SSH and
systemd subprocesses, and exercise a real local port conflict. The observed
staging application trees were exported and extracted from cached objects.
These tests do not prove that user systemd, nginx, package downloads, real
migrations, SSH, or the Gitea Actions context work on Ubuntu. Validate the full
path in a disposable Ubuntu environment and complete the authorized one-time
setup before requesting a physical test. The operator must check the actual
public and loopback port availability and dedicated paths before that test.
The inspected local `dev` base was `e8d19e88e1022953f5714cf891129adfe992d3f7`;
the older `91f3b9942a9df390da3435267c7131fe7464240c` was a historical local
reference. The observed `staging` commit was
`234c45c10ad901e75907d56b5443ecbc619af342` with application gitlink
`f6d00f51f30cc5482c1711082f8656f2b3d9cd30`. A later selected commit must be
reviewed against its own commands, migrations and gitlinks before publication.
A future `release: { types: [published] }` trigger is intentionally absent.
After the manual workflow is validated, design and test event-specific tag
handling and a trusted installer revision before enabling automatic publication
triggers.
+126
View File
@@ -0,0 +1,126 @@
#!/usr/bin/env python3
"""Activate only this prepared instance through the account's user systemd manager."""
import argparse
import json
import os
import stat
from pathlib import Path
import subprocess
import sys
import time
import install
def manager_environment(account):
import pwd
install.validate_service_account(account)
entry = pwd.getpwuid(os.geteuid())
home = Path(entry.pw_dir)
if (not home.is_absolute() or home.resolve() != home or not home.is_dir()
or home.stat().st_uid != os.geteuid() or home.stat().st_mode & 0o022):
raise ValueError('service account home must be owned by the account and not group/world writable')
runtime = Path('/run/user') / str(os.geteuid())
bus = runtime / 'bus'
if (runtime.is_symlink() or not runtime.is_dir() or runtime.stat().st_uid != os.geteuid()
or bus.is_symlink() or not bus.exists() or not stat.S_ISSOCK(bus.stat().st_mode)):
raise ValueError('user systemd runtime or D-Bus socket is unavailable')
return {'PATH': os.environ.get('PATH', '/usr/local/bin:/usr/bin:/bin'), 'HOME': str(home),
'XDG_RUNTIME_DIR': str(runtime), 'DBUS_SESSION_BUS_ADDRESS': 'unix:path=' + str(runtime / 'bus')}
def command(args, env, *, check=True):
return subprocess.run(args, env=env, capture_output=True, text=True, check=check)
def units_directory(home):
"""Create account-owned systemd configuration without traversing symlinks."""
current = Path(home)
for part in ('.config', 'systemd', 'user'):
current = current / part
try:
current.mkdir(mode=0o700)
except FileExistsError:
pass
if current.is_symlink() or not current.is_dir() or current.stat().st_uid != os.geteuid() or current.stat().st_mode & 0o022:
raise ValueError('unsafe user systemd unit directory: ' + str(current))
return current
def activate(instance, record, env):
"""Link and start only fresh instance units; retain data and failure evidence."""
base = Path(instance)
install.validate_record(record)
if (record.get('status') != 'prepared' or Path(record.get('base', '')) != base
or base.is_symlink() or base.resolve() != base):
raise ValueError('instance is not a freshly prepared installation')
port = record['public_port']
names = [f'isssteleon-native-{port}-{part}.service' for part in ('api', 'worker', 'web')]
if record.get('services') != names or base.name != f'isssteleon-native-{port}':
raise ValueError('invalid service identity')
linger = command(['loginctl', 'show-user', record['account'], '--property=Linger', '--value'], env)
if linger.stdout.strip().lower() != 'yes':
raise ValueError('user lingering is not enabled; one-time operator setup is required')
command(['systemctl', '--user', 'show-environment'], env)
unit_dir = units_directory(env['HOME'])
for name in names:
source = base / 'units' / name
dest = unit_dir / name
if source.is_symlink() or not source.is_file() or dest.exists() or dest.is_symlink():
raise ValueError('missing source or existing unit path: ' + name)
state = command(['systemctl', '--user', 'show', name, '--property=LoadState', '--value'], env)
if state.stdout.strip() != 'not-found':
raise ValueError('systemd unit already exists: ' + name)
record.update(status='activating', phase='linking_user_units', unit_directory=str(unit_dir))
install.atomic_record(base / 'installation.json', record)
linked = []
try:
for name in names:
os.symlink(base / 'units' / name, unit_dir / name)
linked.append(name)
command(['systemctl', '--user', 'daemon-reload'], env)
record.update(phase='starting_user_units')
install.atomic_record(base / 'installation.json', record)
for name in names:
command(['systemctl', '--user', 'enable', '--now', name], env)
record.update(status='started', phase='awaiting_health', started_at=int(time.time()))
install.atomic_record(base / 'installation.json', record)
return record
except BaseException as exc:
if linked:
try:
command(['systemctl', '--user', 'disable', '--now', *linked], env, check=False)
except OSError:
pass
record.update(status='activation_failed', phase='activation_failed', error=type(exc).__name__)
try:
install.atomic_record(base / 'installation.json', record)
except OSError:
pass
raise
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('instance', type=Path)
args = parser.parse_args()
try:
base = args.instance
if not base.is_absolute() or base.is_symlink() or base.resolve() != base:
raise ValueError('instance path must be absolute and not symlinked')
path = base / 'installation.json'
if path.is_symlink():
raise ValueError('symlinked installation record')
record = json.loads(path.read_text(encoding='utf-8'))
install.validate_record(record)
install.check_installer_files(Path(__file__).resolve().parent, record)
result = activate(base, record, manager_environment(record['account']))
print(json.dumps(result, sort_keys=True))
return 0
except (OSError, ValueError, subprocess.CalledProcessError, json.JSONDecodeError) as exc:
print('Activation failed: ' + str(exc), file=sys.stderr)
return 1
if __name__ == '__main__':
sys.exit(main())
+63
View File
@@ -0,0 +1,63 @@
#!/usr/bin/env python3
"""Export exact committed application trees as a guarded release bundle."""
import hashlib
import gzip
import json
from pathlib import Path, PurePosixPath
import subprocess
import tarfile
import tempfile
import source
APPLICATION_COMPONENTS = {'Core', 'Persistance', 'Extraction', 'WebApi', 'WebApp', 'models', 'indicadores_kit'}
def safe_member(member):
path = PurePosixPath(member.name)
return (not path.is_absolute() and member.name not in ('', '.')
and all(part not in ('', '.', '..') for part in path.parts)
and '\\' not in member.name and (member.isdir() or member.isfile()))
def export(checkout, manifest, output):
"""Export each verified commit, excluding Git metadata and untracked files."""
checkout, output = Path(checkout), Path(output)
seen = set()
with output.open('xb') as raw, gzip.GzipFile(fileobj=raw, mode='wb', filename='', mtime=0) as zipped, tarfile.open(fileobj=zipped, mode='w:', format=tarfile.PAX_FORMAT) as bundle:
for full, sha in sorted(manifest.items(), key=lambda item: (item[0].count('/'), item[0])):
repo = checkout / full
if source.git(repo, 'rev-parse', 'HEAD') != sha:
raise ValueError('source checkout changed: ' + full)
prefix = PurePosixPath('application') / PurePosixPath(full).relative_to('ISSSTELEON')
with tempfile.TemporaryFile() as stream:
subprocess.run(['git', '-C', str(repo), 'archive', '--format=tar', sha], stdout=stream, check=True)
stream.seek(0)
with tarfile.open(fileobj=stream, mode='r:') as archive:
for member in archive:
if full == 'ISSSTELEON' and PurePosixPath(member.name).parts[0] not in APPLICATION_COMPONENTS:
continue
if not safe_member(member):
raise ValueError('unsafe Git archive member: ' + member.name)
name = str(prefix / member.name)
if name in seen:
if member.isdir():
continue
raise ValueError('overlapping archive member: ' + name)
seen.add(name)
member.name = name
member.uid = member.gid = 0
member.uname = member.gname = ''
member.mode = (0o755 if member.isdir() or member.mode & 0o111 else 0o644)
bundle.addfile(member, archive.extractfile(member) if member.isfile() else None)
digest = hashlib.sha256()
with output.open('rb') as stream:
for block in iter(lambda: stream.read(1024 * 1024), b''):
digest.update(block)
return digest.hexdigest()
def write_record(path, record):
with Path(path).open('x', encoding='utf-8') as stream:
json.dump(record, stream, indent=2, sort_keys=True)
stream.write('\n')
+350
View File
@@ -0,0 +1,350 @@
#!/usr/bin/env python3
"""Prepare a new isolated native instance; never activate privileged services."""
import argparse
import errno
import hashlib
import json
import os
from pathlib import Path, PurePosixPath
import re
import shutil
import socket
import subprocess
import sys
import tarfile
import time
import urllib.request
import bundle
NAME = re.compile(r'^[a-z_][a-z0-9_-]{0,30}$')
SHA = re.compile(r'^[0-9a-f]{40}$')
DIGEST = re.compile(r'^[0-9a-f]{64}$')
SAFE_PATH = re.compile(r'^/[A-Za-z0-9_./-]+$')
DOCKER_ROOT = Path('/srv/workingnarrative-dev')
DOMAINS = ('cacu', 'cama', 'tea', 'governance')
INSTALLER_FILES = {'install.py', 'activate.py', 'verify.py', 'remote.py', 'bundle.py', 'source.py'}
REQUIRED_LINKS = {'ISSSTELEON', 'ISSSTELEON/WebApi', 'ISSSTELEON/WebApp',
'ISSSTELEON/models', 'ISSSTELEON/indicadores_kit'}
def validate_record(record):
if not isinstance(record, dict):
raise ValueError('invalid release record')
if (not isinstance(record.get('tag'), str) or not record['tag'] or len(record['tag']) > 255
or any(ord(c) < 32 for c in record['tag']) or type(record.get('release_id')) is not int
or record['release_id'] <= 0 or type(record.get('public_port')) is not int
or not 1024 <= record['public_port'] <= 65535
or type(record.get('api_port')) is not int or not 1024 <= record['api_port'] <= 65535
or record['api_port'] == record['public_port']):
raise ValueError('invalid release identity or port')
if any(not isinstance(record.get(k), str) or not SHA.fullmatch(record[k])
for k in ('application_sha', 'installer_sha', 'tag_object')):
raise ValueError('invalid commit identity')
if not isinstance(record.get('bundle_sha256'), str) or not DIGEST.fullmatch(record['bundle_sha256']):
raise ValueError('invalid bundle digest')
files = record.get('installer_files')
if (not isinstance(files, dict) or set(files) != INSTALLER_FILES
or any(not isinstance(value, str) or not DIGEST.fullmatch(value) for value in files.values())):
raise ValueError('invalid installer file manifest')
links = record.get('gitlinks')
if (not isinstance(links, dict) or set(links) != REQUIRED_LINKS
or any(not isinstance(value, str) or not SHA.fullmatch(value) for value in links.values())):
raise ValueError('unsupported or incomplete gitlinks')
if not isinstance(record.get('installer_ref'), str) or not record['installer_ref'].startswith('refs/heads/'):
raise ValueError('invalid installer reference')
def digest(path):
value = hashlib.sha256()
with open(path, 'rb') as stream:
for block in iter(lambda: stream.read(1024 * 1024), b''):
value.update(block)
return value.hexdigest()
def check_installer_files(directory, record):
for name, expected in record['installer_files'].items():
file = Path(directory) / name
if file.is_symlink() or not file.is_file() or digest(file) != expected:
raise ValueError('installer file differs from release record: ' + name)
def validate_service_account(account):
"""Reject root and accounts with common administrative or Docker groups."""
import grp
import pwd
if not NAME.fullmatch(account) or os.geteuid() == 0:
raise ValueError('a non-root service account is required')
entry = pwd.getpwuid(os.geteuid())
if entry.pw_name != account:
raise ValueError('preparation must run as the selected service account')
groups = set(os.getgroups()) | set(os.getgrouplist(account, entry.pw_gid))
groups.update((entry.pw_gid, os.getegid()))
privileged = {0}
for name in ('docker', 'sudo', 'wheel'):
try:
privileged.add(grp.getgrnam(name).gr_gid)
except KeyError:
pass
if groups & privileged:
raise ValueError('service account belongs to a privileged administrative or Docker group')
def require_private_parent(parent):
"""Reject installation parents that other accounts can replace or modify."""
metadata = parent.stat()
if metadata.st_uid != os.geteuid() or metadata.st_mode & 0o022:
raise ValueError('installation parent must be owned by the service account and not group/world writable')
def validate_parent(parent):
parent = Path(parent)
if not parent.is_absolute() or not SAFE_PATH.fullmatch(str(parent)) or not parent.is_dir():
raise ValueError('parent must be an existing absolute path without whitespace or shell metacharacters')
if parent.resolve() != parent:
raise ValueError('parent and its ancestors must not be symlinks or contain dot components')
destination = parent / 'instance'
if destination == DOCKER_ROOT or DOCKER_ROOT in destination.parents or destination in DOCKER_ROOT.parents:
raise ValueError('native installation must be separate from the Docker deployment')
require_private_parent(parent)
return parent
def check_port(port, public):
if type(port) is not int or not 1024 <= port <= 65535:
raise ValueError('ports must be between 1024 and 65535')
families = [(socket.AF_INET, '0.0.0.0' if public else '127.0.0.1')]
if socket.has_ipv6:
families.append((socket.AF_INET6, '::' if public else '::1'))
for family, address in families:
try:
with socket.socket(family, socket.SOCK_STREAM) as sock:
if family == socket.AF_INET6:
sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
sock.bind((address, port))
except OSError as exc:
if exc.errno in (errno.EAFNOSUPPORT, errno.EADDRNOTAVAIL) and family == socket.AF_INET6:
continue
raise ValueError(f'port {port} is unavailable: {exc}') from exc
def extract_bundle(archive_path, target):
"""Extract regular files only into a new directory; reject links and duplicates."""
target = Path(target)
seen = set()
total = 0
with tarfile.open(archive_path, 'r:gz') as archive:
for member in archive:
if not bundle.safe_member(member):
raise ValueError('unsafe archive member')
path = PurePosixPath(member.name)
if not path.parts or path.parts[0] != 'application' or member.name in seen:
raise ValueError('invalid or duplicate archive member')
seen.add(member.name)
total += member.size
if total > 4 * 1024 ** 3 or len(seen) > 250000:
raise ValueError('archive exceeds extraction limits')
dest = target.joinpath(*path.parts)
if member.isdir():
dest.mkdir(parents=True, exist_ok=True, mode=0o755)
else:
dest.parent.mkdir(parents=True, exist_ok=True, mode=0o755)
with archive.extractfile(member) as source_stream, dest.open('xb') as out:
shutil.copyfileobj(source_stream, out, 1024 * 1024)
os.chmod(dest, 0o755 if member.mode & 0o111 else 0o644)
app = target / 'application'
required = ['WebApi/pyproject.toml', 'WebApi/uv.lock', 'WebApi/webapi/indicadores_vivos.py',
'WebApp/package.json', 'WebApp/package-lock.json']
required += [f'Persistance/persistance/{domain}/alembic.ini' for domain in DOMAINS]
if any(not (app / path).is_file() for path in required):
raise ValueError('bundle lacks required locked application components')
def atomic_record(path, record):
temporary = path.with_suffix('.tmp')
with temporary.open('x', encoding='utf-8') as stream:
json.dump(record, stream, indent=2, sort_keys=True)
stream.write('\n')
stream.flush()
os.fsync(stream.fileno())
os.replace(temporary, path)
def environment(base):
data = base / 'data'
result = {'PATH': os.environ.get('PATH', '/usr/local/bin:/usr/bin:/bin'),
'HOME': str(data), 'LANG': 'C.UTF-8', 'UV_CACHE_DIR': str(data / 'uv-cache'),
'npm_config_cache': str(data / 'npm-cache'),
'MLFLOW_TRACKING_URI': 'sqlite:///' + str(data / 'mlflow.db'),
'MLFLOW_ARTIFACT_ROOT': str(data / 'mlflow-artifacts'),
'MLFLOW_DISABLE_TELEMETRY': 'true', 'DO_NOT_TRACK': 'true',
'MLFLOW_DISABLE_AGENT_HINT': '1', 'WEBAPI_REPORT_DIR': str(data / 'reportes'),
'INDICADORES_DIR': str(data / 'indicadores')}
for domain in DOMAINS:
result[domain.upper() + '_DATABASE_URL'] = 'sqlite:///' + str(data / (domain + '.db'))
return result
def run(args, cwd, env):
subprocess.run([str(arg) for arg in args], cwd=cwd, env=env, check=True)
def verify_database_targets(uv, app, env, data):
"""Check the selected application's effective settings before any migration."""
code = """import os, sys
from pathlib import Path
from sqlalchemy.engine import make_url
from persistance.settings import settings
base = Path(sys.argv[1]).resolve()
for domain in ('cacu', 'cama', 'tea', 'governance'):
expected = base / (domain + '.db')
url = getattr(settings, domain + '_database_url')
parsed = make_url(url)
if (url != os.environ[domain.upper() + '_DATABASE_URL'] or parsed.drivername != 'sqlite'
or not parsed.database or Path(parsed.database) != expected or expected.is_symlink()
or expected.resolve().parent != base or not expected.is_file() or expected.stat().st_size != 0):
raise SystemExit('effective migration destination rejected: ' + domain)
print('Verified four new isolated SQLite migration targets')
"""
run([uv, 'run', '--no-sync', 'python', '-c', code, data], app / 'WebApi', env)
def systemd_unit(base, account, service, api_port, nginx):
work = base / 'application' / 'WebApi'
binary = work / '.venv' / 'bin'
name = base.name
common = f'''[Unit]\nDescription=ISSSTELEON native {service} {name}\nAfter=network.target\n'''
if service == 'worker':
common += f'After={name}-api.service\nRequires={name}-api.service\n'
if service == 'web':
common += f'After={name}-api.service\nRequires={name}-api.service\n'
command = {
'api': f'{binary}/gunicorn --bind 127.0.0.1:{api_port} --workers 2 --timeout 600 --access-logfile - webapi:create_app()',
'worker': f'{binary}/python -m webapi.indicadores_vivos',
'web': f'{nginx} -c {base}/nginx.conf -p {base}/',
}[service]
directory = base if service == 'web' else work
return common + f'''\n[Service]\nType=simple\nWorkingDirectory={directory}\nEnvironmentFile={base}/service.env\nExecStart={command}\nRestart=on-failure\nRestartSec=5\nNoNewPrivileges=true\nPrivateUsers=true\nPrivateTmp=true\nProtectSystem=strict\nReadWritePaths={base}/data\n\n[Install]\nWantedBy=default.target\n'''
def nginx_conf(base, port, api_port):
data = base / 'data'
return f'''worker_processes 1;\ndaemon off;\npid {data}/nginx.pid;\nerror_log stderr;\nevents {{ worker_connections 1024; }}\nhttp {{\n include /etc/nginx/mime.types;\n default_type application/octet-stream;\n access_log /dev/stdout;\n client_body_temp_path {data}/nginx-client;\n proxy_temp_path {data}/nginx-proxy;\n fastcgi_temp_path {data}/nginx-fastcgi;\n uwsgi_temp_path {data}/nginx-uwsgi;\n scgi_temp_path {data}/nginx-scgi;\n server {{\n listen {port};\n server_name _;\n root {base}/application/WebApp/dist/WebApp/browser;\n client_max_body_size 270m;\n location ~ ^/(api|imports|data|cacu|cama|tea|governance|reportes|health)(/|$) {{\n proxy_pass http://127.0.0.1:{api_port};\n proxy_set_header Host $host;\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header X-Forwarded-Proto $scheme;\n proxy_read_timeout 600s;\n }}\n location ~* \\.(js|css)$ {{ add_header Cache-Control "public, max-age=31536000, immutable"; try_files $uri =404; }}\n location / {{ add_header Cache-Control "no-cache"; try_files $uri $uri/ /index.html; }}\n }}\n}}\n'''
def prepare(parent, record, archive_path, expected_digest, api_port, account, expected_hostname, tools):
"""Create a fresh instance; failure retains its data and prevents retries over it."""
validate_record(record)
if (not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9.-]{0,252}', expected_hostname)
or socket.gethostname().lower() != expected_hostname.lower()):
raise ValueError('host identity does not match the explicitly expected hostname')
parent = validate_parent(parent)
validate_service_account(account)
if expected_digest != record['bundle_sha256'] or digest(archive_path) != expected_digest:
raise ValueError('bundle digest does not match the independently supplied digest and record')
port = record['public_port']
if type(api_port) is not int or api_port != record['api_port']:
raise ValueError('API port does not match the validated release request')
check_port(port, True)
check_port(api_port, False)
base = parent / f'isssteleon-native-{port}'
base.mkdir(mode=0o750) # exclusive; no update or reuse
state = dict(record, status='preparing', phase='reserved', base=str(base), api_port=api_port,
account=account, hostname=expected_hostname, services=[f'{base.name}-{part}.service' for part in ('api', 'worker', 'web')])
metadata = base / 'installation.json'
try:
atomic_record(metadata, state)
(base / 'data').mkdir(mode=0o700)
extract_bundle(archive_path, base)
app = base / 'application'
env = environment(base)
for domain in DOMAINS:
path = base / 'data' / (domain + '.db')
with path.open('xb'):
pass
os.chmod(path, 0o600)
state.update(phase='dependencies')
atomic_record(metadata, state)
run([tools['uv'], 'sync', '--locked', '--no-dev', '--extra', 'sql-drivers'], app / 'WebApi', env)
run([tools['npm'], 'ci'], app / 'WebApp', env)
run([tools['npm'], 'run', 'build', '--', '--configuration', 'production'], app / 'WebApp', env)
if not (app / 'WebApp' / 'dist' / 'WebApp' / 'browser' / 'index.html').is_file():
raise ValueError('Angular distribution index is missing')
state.update(phase='verifying_migration_targets')
atomic_record(metadata, state)
verify_database_targets(tools['uv'], app, env, base / 'data')
state.update(phase='migrations')
atomic_record(metadata, state)
for domain in DOMAINS:
target = base / 'data' / (domain + '.db')
if target.is_symlink() or target.resolve().parent != (base / 'data').resolve() or target.stat().st_size != 0:
raise ValueError('migration target is not a new isolated database: ' + domain)
run([tools['uv'], 'run', '--no-sync', 'alembic', '-c', app / 'Persistance' / 'persistance' / domain / 'alembic.ini', 'upgrade', 'head'], app / 'WebApi', env)
service_env = {k: v for k, v in env.items() if k not in ('PATH', 'LANG', 'npm_config_cache', 'UV_CACHE_DIR')}
(base / 'service.env').write_text(''.join(f'{key}={value}\n' for key, value in sorted(service_env.items())), encoding='utf-8')
(base / 'nginx.conf').write_text(nginx_conf(base, port, api_port), encoding='utf-8')
units = base / 'units'
units.mkdir(mode=0o750)
for service in ('api', 'worker', 'web'):
(units / f'{base.name}-{service}.service').write_text(systemd_unit(base, account, service, api_port, tools['nginx']), encoding='utf-8')
run([tools['nginx'], '-t', '-c', base / 'nginx.conf', '-p', str(base) + '/'], base, env)
state.update(status='prepared', phase='awaiting_systemd_activation', prepared_at=int(time.time()))
atomic_record(metadata, state)
return state
except BaseException as exc:
state.update(status='failed', error=type(exc).__name__)
try:
atomic_record(metadata, state)
except OSError:
pass
raise
def available_tools():
result = {}
for name in ('uv', 'npm', 'nginx', 'tesseract'):
path = shutil.which(name)
if not path or not SAFE_PATH.fullmatch(path):
raise ValueError('missing or unsafe executable path: ' + name)
result[name] = path
languages = subprocess.run([result['tesseract'], '--list-langs'], capture_output=True, text=True, check=True).stdout.splitlines()
if not {'spa', 'eng'} <= set(languages):
raise ValueError('Tesseract requires spa and eng language data')
if not Path('/etc/nginx/mime.types').is_file():
raise ValueError('nginx mime.types is missing')
return result
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--record', required=True, type=Path)
parser.add_argument('--bundle', required=True, type=Path)
parser.add_argument('--bundle-sha256', required=True)
parser.add_argument('--parent', required=True, type=Path)
parser.add_argument('--api-port', required=True, type=int)
parser.add_argument('--account', required=True)
parser.add_argument('--expected-hostname', required=True)
args = parser.parse_args()
if sys.platform != 'linux':
parser.error('native installation requires Linux')
try:
if Path('/.dockerenv').exists() or Path('/run/.containerenv').exists():
raise ValueError('run preparation on the selected host, not inside a container')
record = json.loads(args.record.read_text(encoding='utf-8'))
validate_record(record)
check_installer_files(Path(__file__).resolve().parent, record)
result = prepare(args.parent, record, args.bundle, args.bundle_sha256, args.api_port, args.account, args.expected_hostname, available_tools())
print(json.dumps(result, indent=2, sort_keys=True))
return 0
except (OSError, ValueError, subprocess.CalledProcessError, tarfile.TarError, json.JSONDecodeError) as exc:
print('Native preparation failed: ' + str(exc), file=sys.stderr)
return 1
if __name__ == '__main__':
sys.exit(main())
+152
View File
@@ -0,0 +1,152 @@
#!/usr/bin/env python3
"""Deploy and verify a release through an explicitly configured non-root SSH account."""
import argparse
import json
from pathlib import Path
import re
import shlex
import shutil
import subprocess
import sys
import uuid
import time
import urllib.error
import verify
import install
FILES = ('install.py', 'activate.py', 'verify.py', 'remote.py', 'bundle.py', 'source.py', 'release-record.json', 'release-source.tar.gz')
HOST = re.compile(r'^[A-Za-z0-9][A-Za-z0-9.-]{0,252}$')
def ssh_options(identity, known_hosts):
return ['-i', str(identity), '-o', 'BatchMode=yes', '-o', 'IdentitiesOnly=yes',
'-o', 'StrictHostKeyChecking=yes', '-o', 'UserKnownHostsFile=' + str(known_hosts)]
def remote_command(arguments):
return shlex.join([str(part) for part in arguments])
def check_public(host, port, timeout=90):
"""Require the runner to reach both the application and proxied API."""
deadline = time.monotonic() + timeout
while True:
try:
status, body = verify.request(f'http://{host}:{port}/health')
health = json.loads(body)
index_status, index = verify.request(f'http://{host}:{port}/')
if status != 200 or not isinstance(health, dict) or health.get('status') != 'ok' or index_status != 200 or not index:
raise ValueError('public HTTP or proxied API health check failed')
return
except (OSError, ValueError, urllib.error.URLError, json.JSONDecodeError) as exc:
if time.monotonic() >= deadline:
raise ValueError('public endpoint is unavailable: ' + str(exc)) from exc
time.sleep(2)
def prepare(bundle_dir, digest, host, port, account, expected_hostname, parent, api_port, identity, known_hosts):
"""Use pinned host keys and create a unique staging directory without elevated privileges."""
bundle_dir = Path(bundle_dir).resolve()
identity, known_hosts = Path(identity).resolve(), Path(known_hosts).resolve()
if (not HOST.fullmatch(host) or not HOST.fullmatch(expected_hostname) or not install.NAME.fullmatch(account)
or account == 'root' or not 1 <= port <= 65535 or not identity.is_file() or not known_hosts.is_file()
or not install.SAFE_PATH.fullmatch(parent) or parent == '/' or '..' in Path(parent).parts):
raise ValueError('invalid explicit SSH endpoint, host key, account or parent')
files = [bundle_dir / name for name in FILES]
if any(not item.is_file() or item.is_symlink() for item in files):
raise ValueError('bundle or installer file is missing or symlinked')
record = json.loads((bundle_dir / 'release-record.json').read_text(encoding='utf-8'))
install.validate_record(record)
install.check_installer_files(bundle_dir, record)
if digest != record['bundle_sha256'] or install.digest(bundle_dir / 'release-source.tar.gz') != digest:
raise ValueError('bundle checksum mismatch')
if type(api_port) is not int or api_port != record['api_port']:
raise ValueError('API port does not match the validated release request')
ssh, scp = shutil.which('ssh'), shutil.which('scp')
if not ssh or not scp:
raise ValueError('ssh and scp are required')
endpoint = account + '@' + host
stage = parent.rstrip('/') + '/.release-' + uuid.uuid4().hex
options = ssh_options(identity, known_hosts)
# Check identity and containment remotely before making any files.
guard = '''import grp,os,pathlib,pwd,socket,subprocess,sys
parent,stage,account,host=sys.argv[1:]
p=pathlib.Path(parent)
resolved=p.resolve(strict=True)
docker=pathlib.Path('/srv/workingnarrative-dev')
entry=pwd.getpwuid(os.geteuid())
if str(resolved)!=parent or not p.is_dir() or p.stat().st_uid!=os.geteuid() or p.stat().st_mode & 0o022 or docker==resolved or docker in resolved.parents or socket.gethostname().lower()!=host.lower() or os.geteuid()==0 or entry.pw_name!=account:
raise SystemExit('remote identity or parent rejected')
groups=set(os.getgroups()) | set(os.getgrouplist(account,entry.pw_gid)) | {entry.pw_gid,os.getegid()}
privileged={0}
for name in ('docker','sudo','wheel'):
try:
privileged.add(grp.getgrnam(name).gr_gid)
except KeyError:
pass
if groups & privileged:
raise SystemExit('remote service account has privileged group membership')
runtime=pathlib.Path('/run/user') / str(os.geteuid())
if not runtime.is_dir() or not (runtime / 'bus').exists():
raise SystemExit('user manager runtime is unavailable')
env=dict(os.environ, HOME=entry.pw_dir, XDG_RUNTIME_DIR=str(runtime), DBUS_SESSION_BUS_ADDRESS='unix:path=' + str(runtime / 'bus'))
linger=subprocess.run(['loginctl','show-user',account,'--property=Linger','--value'],env=env,text=True,capture_output=True,check=True)
if linger.stdout.strip().lower() != 'yes':
raise SystemExit('user lingering is not enabled')
subprocess.run(['systemctl','--user','show-environment'],env=env,capture_output=True,check=True)
os.mkdir(stage,0o700)
'''
subprocess.run([ssh, *options, '-p', str(port), endpoint,
remote_command(['python3', '-c', guard, parent, stage, account, expected_hostname])], check=True)
print('Remote staging directory:', stage, flush=True)
subprocess.run([scp, *options, '-P', str(port), *map(str, files), endpoint + ':' + stage + '/'], check=True)
command = ['python3', stage + '/install.py', '--record', stage + '/release-record.json',
'--bundle', stage + '/release-source.tar.gz', '--bundle-sha256', digest,
'--parent', parent, '--account', account, '--expected-hostname', expected_hostname,
'--api-port', str(api_port)]
subprocess.run([ssh, *options, '-p', str(port), endpoint, remote_command(command)], check=True)
instance = parent.rstrip('/') + '/isssteleon-native-' + str(record['public_port'])
def remote_run(args, check=True):
return subprocess.run([ssh, *options, '-p', str(port), endpoint, remote_command(args)], check=check)
remote_run(['python3', stage + '/activate.py', instance])
remote_run(['python3', stage + '/verify.py', instance, '--wait-seconds', '180'])
try:
check_public(host, record['public_port'])
except (OSError, ValueError) as exc:
try:
remote_run(['python3', stage + '/verify.py', instance, '--public-result', 'failed', '--wait-seconds', '0'], check=False)
except OSError:
pass
raise exc
remote_run(['python3', stage + '/verify.py', instance, '--public-result', 'ok', '--wait-seconds', '0'])
return stage
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--bundle-dir', required=True, type=Path)
parser.add_argument('--bundle-sha256', required=True)
parser.add_argument('--host', required=True)
parser.add_argument('--ssh-port', required=True, type=int)
parser.add_argument('--account', required=True)
parser.add_argument('--expected-hostname', required=True)
parser.add_argument('--parent', required=True)
parser.add_argument('--api-port', required=True, type=int)
parser.add_argument('--identity', required=True, type=Path)
parser.add_argument('--known-hosts', required=True, type=Path)
args = parser.parse_args()
try:
prepare(args.bundle_dir, args.bundle_sha256, args.host, args.ssh_port, args.account,
args.expected_hostname, args.parent, args.api_port, args.identity, args.known_hosts)
print('Native deployment is active and public HTTP checks passed.')
return 0
except (OSError, ValueError, subprocess.CalledProcessError, json.JSONDecodeError) as exc:
print('Remote preparation failed: ' + str(exc), file=sys.stderr)
return 1
if __name__ == '__main__':
sys.exit(main())
+168
View File
@@ -0,0 +1,168 @@
#!/usr/bin/env python3
"""Resolve a published institutional release without deploying it."""
import json
import hashlib
import os
from pathlib import Path
import re
import subprocess
import sys
import tempfile
import source
import bundle
import urllib.error
import urllib.parse
import urllib.request
import uuid
ROOT = Path(__file__).resolve().parents[2]
SERVER = 'http://10.0.10.41:3000'
REPOSITORY = 'ISSSTELEON/WorkingNarrative'
ORIGIN = SERVER + '/' + REPOSITORY + '.git'
SHA = re.compile(r'^[0-9a-f]{40}$')
def git(root, *args):
return subprocess.run(['git', '-C', str(root), *args], check=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True).stdout.strip()
def validate_tag(tag):
if not tag or tag.startswith(('-', 'refs/')) or re.fullmatch(r'[0-9a-fA-F]{40}', tag):
raise ValueError('tag must be an unambiguous tag name')
subprocess.run(['git', 'check-ref-format', 'refs/tags/' + tag], check=True,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
return tag
def validate_port(port):
if not re.fullmatch(r'[0-9]{1,5}', port) or not 1024 <= int(port) <= 65535:
raise ValueError('port must be an integer from 1024 to 65535')
return int(port)
def dispatch(root, env):
ref, name, sha = (env.get('DISPATCH_REF', ''), env.get('DISPATCH_REF_NAME', ''), env.get('DISPATCH_SHA', ''))
if (env.get('DISPATCH_REPOSITORY') != REPOSITORY or env.get('DISPATCH_SERVER', '').rstrip('/') != SERVER
or env.get('DISPATCH_REF_TYPE') != 'branch' or not name or ref != 'refs/heads/' + name
or not SHA.fullmatch(sha)):
raise ValueError('invalid workflow dispatch identity')
subprocess.run(['git', 'check-ref-format', ref], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
if git(root, 'rev-parse', 'HEAD') != sha or git(root, 'remote', 'get-url', 'origin') not in (ORIGIN, ORIGIN.removesuffix('.git')):
raise ValueError('workflow checkout identity mismatch')
return {'installer_ref': ref, 'installer_sha': sha}
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None
def release(tag, token):
if not token:
raise ValueError('Gitea token is required')
url = SERVER + '/api/v1/repos/' + REPOSITORY + '/releases/tags/' + urllib.parse.quote(tag, safe='')
req = urllib.request.Request(url, headers={'Authorization': 'token ' + token, 'Accept': 'application/json'})
with urllib.request.build_opener(NoRedirect).open(req, timeout=15) as response:
data = json.load(response)
if (not isinstance(data, dict) or type(data.get('id')) is not int or data['id'] <= 0
or data.get('tag_name') != tag or data.get('draft') is not False
or not data.get('published_at')):
raise ValueError('tag does not identify a published release')
return {'release_id': data['id'], 'tag': tag}
def resolve(root, tag, port, api_port, env):
validate_tag(tag)
port = validate_port(port)
api_port = validate_port(api_port)
if port == api_port:
raise ValueError('public and API ports must differ')
installer = dispatch(root, env)
first = release(tag, env.get('RELEASE_TOKEN', ''))
ref = 'refs/deploy-terminal/' + uuid.uuid4().hex
try:
git(root, 'fetch', '--no-tags', 'origin', '+refs/tags/' + tag + ':' + ref)
object_sha = git(root, 'rev-parse', '--verify', ref)
commit = git(root, 'rev-parse', '--verify', ref + '^{commit}')
if not SHA.fullmatch(object_sha) or not SHA.fullmatch(commit):
raise ValueError('invalid fetched tag object or commit')
# A remote tag changed during resolution must not be silently accepted.
lines = git(root, 'ls-remote', '--refs', 'origin', 'refs/tags/' + tag).splitlines()
if lines != [object_sha + '\trefs/tags/' + tag]:
raise ValueError('remote tag changed during resolution')
if release(tag, env.get('RELEASE_TOKEN', '')) != first:
raise ValueError('release changed during resolution')
return dict(first, **installer, tag_object=object_sha, application_sha=commit, public_port=port, api_port=api_port)
finally:
git(root, 'update-ref', '-d', ref)
def prepare_source(root, record, output=None):
"""Fetch the same tag again into a disposable checkout and verify gitlinks."""
ref = 'refs/deploy-terminal/' + uuid.uuid4().hex
try:
git(root, 'fetch', '--no-tags', 'origin', '+refs/tags/' + record['tag'] + ':' + ref)
if (git(root, 'rev-parse', '--verify', ref) != record['tag_object']
or git(root, 'rev-parse', '--verify', ref + '^{commit}') != record['application_sha']):
raise ValueError('tag changed before source preparation')
with tempfile.TemporaryDirectory(prefix='isssteleon-release-') as temporary:
checkout = Path(temporary)
subprocess.run(['git', 'init', '--quiet', str(checkout)], check=True)
git(checkout, 'fetch', '--no-tags', str(root), ref)
git(checkout, 'checkout', '--quiet', '--detach', record['application_sha'])
if git(checkout, 'rev-parse', 'HEAD') != record['application_sha']:
raise ValueError('application checkout mismatch')
manifest = source.checkout_pinned(checkout)
if output is not None:
record['bundle_sha256'] = bundle.export(checkout, manifest, output)
return manifest
finally:
git(root, 'update-ref', '-d', ref)
def installer_manifest(root, sha):
"""Bind exported installer scripts to the dispatched committed revision."""
manifest = {}
for name in ('install.py', 'activate.py', 'verify.py', 'remote.py', 'bundle.py', 'source.py'):
relative = '.gitea/deploy-terminal/' + name
committed = subprocess.run(['git', '-C', str(root), 'show', sha + ':' + relative],
check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout
if (Path(root) / relative).read_bytes() != committed:
raise ValueError('installer file differs from dispatched revision: ' + name)
manifest[name] = hashlib.sha256(committed).hexdigest()
return manifest
def revalidate(root, record, token):
"""Fail if the tag or publication changed while the bundle was being built."""
tag = validate_tag(record['tag'])
lines = git(root, 'ls-remote', '--refs', 'origin', 'refs/tags/' + tag).splitlines()
if lines != [record['tag_object'] + '\trefs/tags/' + tag]:
raise ValueError('remote tag changed before bundle publication')
if release(tag, token) != {'tag': tag, 'release_id': record['release_id']}:
raise ValueError('release changed before bundle publication')
def main():
try:
record = resolve(ROOT, os.environ.get('REQUESTED_TAG', ''), os.environ.get('REQUESTED_PORT', ''),
os.environ.get('REQUESTED_API_PORT', ''), os.environ)
output = Path(os.environ.get('RELEASE_OUTPUT', 'release-source.tar.gz'))
record['installer_files'] = installer_manifest(ROOT, record['installer_sha'])
record['gitlinks'] = prepare_source(ROOT, record, output)
revalidate(ROOT, record, os.environ.get('RELEASE_TOKEN', ''))
bundle.write_record(output.with_name('release-record.json'), record)
print(json.dumps(record, sort_keys=True), flush=True)
print('Release bundle prepared for automated native deployment.', flush=True)
return 0
except (ValueError, subprocess.CalledProcessError, OSError, urllib.error.URLError, json.JSONDecodeError) as exc:
print('Release resolution failed: ' + str(exc), file=sys.stderr)
return 1
if __name__ == '__main__':
sys.exit(main())
+91
View File
@@ -0,0 +1,91 @@
#!/usr/bin/env python3
"""Check out only institutional application gitlinks at their committed SHAs."""
import os
import base64
from pathlib import Path
import re
import subprocess
ORIGINS = {
'ISSSTELEON': 'ISSSTELEON',
'ISSSTELEON/WebApi': 'WebApi',
'ISSSTELEON/WebApp': 'WebApp',
'ISSSTELEON/models': 'models',
'ISSSTELEON/indicadores_kit': 'indicadores_kit',
}
SHA = re.compile(r'^[0-9a-f]{40}$')
def git(repo, *args, binary=False):
env = os.environ.copy()
token = env.get('RELEASE_TOKEN')
if token:
try:
count = int(env.get('GIT_CONFIG_COUNT', '0'))
except ValueError as exc:
raise ValueError('invalid inherited Git configuration count') from exc
if not 0 <= count < 32:
raise ValueError('invalid inherited Git configuration count')
encoded = base64.b64encode(('x-access-token:' + token).encode()).decode('ascii')
env['GIT_CONFIG_KEY_' + str(count)] = 'http.http://10.0.10.41:3000/ISSSTELEON/.extraheader'
env['GIT_CONFIG_VALUE_' + str(count)] = 'AUTHORIZATION: basic ' + encoded
env['GIT_CONFIG_COUNT'] = str(count + 1)
env['GIT_TERMINAL_PROMPT'] = '0'
result = subprocess.run(['git', '-C', str(repo), *args], check=True, env=env,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=not binary)
return result.stdout if binary else result.stdout.strip()
def gitlinks(repo):
entries = git(repo, 'ls-tree', '-rz', '--full-tree', 'HEAD', binary=True)
links = {}
for entry in entries.split(b'\0'):
if not entry:
continue
meta, name = entry.split(b'\t', 1)
mode, kind, sha = meta.decode('ascii').split()
if mode != '160000':
continue
path = os.fsdecode(name)
if (kind != 'commit' or not SHA.fullmatch(sha) or path.startswith('/')
or any(part in ('', '.', '..') for part in path.split('/')) or '\\' in path):
raise ValueError('unsafe gitlink entry')
links[path] = sha
return links
def checkout_pinned(root):
"""Ignore unrelated top-level submodules; reject unknown application origins."""
root = Path(root)
outer = gitlinks(root)
if 'ISSSTELEON' not in outer:
raise ValueError('application gitlink is missing')
manifest = {}
def visit(repo, path, prefix, sha):
full = prefix + '/' + path if prefix else path
if full not in ORIGINS:
raise ValueError('unrecognized application gitlink: ' + full)
config = git(repo, 'config', '-f', '.gitmodules', '--get-regexp', r'^submodule\..*\.path$')
matches = []
for line in config.splitlines():
parts = line.split(None, 1)
if len(parts) == 2 and parts[1] == path:
matches.append(parts[0][len('submodule.'):-len('.path')])
if len(matches) != 1 or not re.fullmatch(r'[A-Za-z0-9_-]+', matches[0]):
raise ValueError('ambiguous submodule mapping: ' + full)
name = matches[0]
origin = 'ssh://git@10.0.10.41:2222/ISSSTELEON/' + ORIGINS[full] + '.git'
if git(repo, 'config', '-f', '.gitmodules', '--get', f'submodule.{name}.url') != origin:
raise ValueError('untrusted submodule origin: ' + full)
git(repo, '-c', 'protocol.file.allow=never', '-c', f'submodule.{name}.url={origin}',
'submodule', 'update', '--init', '--checkout', '--', path)
child = repo / path
if git(child, 'rev-parse', 'HEAD') != sha:
raise ValueError('gitlink checkout mismatch: ' + full)
manifest[full] = sha
for nested, child_sha in gitlinks(child).items():
visit(child, nested, full, child_sha)
visit(root, 'ISSSTELEON', '', outer['ISSSTELEON'])
return manifest
+94
View File
@@ -0,0 +1,94 @@
"""Test user-service activation and failure handling with isolated unit directories."""
import json
from pathlib import Path
import subprocess
import tempfile
import types
import unittest
from unittest.mock import patch
import activate
import install
class ActivationTests(unittest.TestCase):
"""Temporary files and a mocked user manager stand in for systemd and the host."""
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.root = Path(self.tmp.name).resolve()
self.base = self.root / 'isssteleon-native-18090'
self.base.mkdir()
(self.base / 'data').mkdir()
(self.base / 'data' / 'cacu.db').write_bytes(b'existing')
(self.base / 'units').mkdir()
self.names = [f'isssteleon-native-18090-{part}.service' for part in ('api', 'worker', 'web')]
for name in self.names:
(self.base / 'units' / name).write_text('[Service]\n', encoding='utf-8')
self.unit_dir = self.root / 'user-units'
self.unit_dir.mkdir()
self.record = {'tag': 'v1', 'release_id': 1, 'public_port': 18090,
'application_sha': 'a' * 40, 'installer_sha': 'b' * 40,
'tag_object': 'c' * 40, 'installer_ref': 'refs/heads/dev',
'bundle_sha256': 'd' * 64, 'installer_files': {name: 'e' * 64 for name in install.INSTALLER_FILES},
'gitlinks': {name: 'f' * 40 for name in install.REQUIRED_LINKS},
'status': 'prepared', 'base': str(self.base), 'api_port': 28090,
'account': 'wnnative', 'services': self.names}
(self.base / 'installation.json').write_text(json.dumps(self.record), encoding='utf-8')
self.commands = []
self.env = {'HOME': str(self.root)}
def fake_command(self, args, env, check=True):
self.commands.append(args)
if args[0] == 'loginctl': return types.SimpleNamespace(stdout='yes\n', returncode=0)
if '--property=LoadState' in args: return types.SimpleNamespace(stdout='not-found\n', returncode=0)
return types.SimpleNamespace(stdout='', returncode=0)
def fake_symlink(self, source, dest):
Path(dest).write_text(str(source), encoding='utf-8')
def run_activate(self):
with patch.object(activate, 'units_directory', return_value=self.unit_dir), patch.object(activate, 'command', side_effect=self.fake_command), patch.object(activate.os, 'symlink', side_effect=self.fake_symlink):
return activate.activate(self.base, self.record, self.env)
def test_starts_only_new_user_units(self):
"""Activation enables the three instance units in the user manager without root operations."""
result = self.run_activate()
self.assertEqual(result['status'], 'started')
enabled = [cmd for cmd in self.commands if 'enable' in cmd]
self.assertEqual(len(enabled), 3)
self.assertTrue(all(cmd[:2] == ['systemctl', '--user'] for cmd in enabled))
self.assertEqual((self.base / 'data' / 'cacu.db').read_bytes(), b'existing')
def test_existing_unit_is_never_replaced(self):
"""An existing user unit must stop activation without modifying the existing unit or data."""
existing = self.unit_dir / self.names[0]
existing.write_text('keep', encoding='utf-8')
with self.assertRaises(ValueError): self.run_activate()
self.assertEqual(existing.read_text(), 'keep')
self.assertFalse(any('enable' in cmd for cmd in self.commands))
def test_linger_is_required(self):
"""A user manager without lingering must fail before creating or starting a unit."""
def no_linger(args, env, check=True):
return types.SimpleNamespace(stdout='no\n', returncode=0)
with patch.object(activate, 'command', side_effect=no_linger), patch.object(activate, 'units_directory') as units:
with self.assertRaises(ValueError): activate.activate(self.base, self.record, self.env)
units.assert_not_called()
def test_start_failure_stops_only_new_units_and_keeps_data(self):
"""A failed startup must mark failure and stop the newly linked units while retaining data."""
def fail_start(args, env, check=True):
if 'enable' in args and args[-1].endswith('-worker.service'):
raise subprocess.CalledProcessError(1, args)
return self.fake_command(args, env, check)
with patch.object(activate, 'units_directory', return_value=self.unit_dir), patch.object(activate, 'command', side_effect=fail_start), patch.object(activate.os, 'symlink', side_effect=self.fake_symlink):
with self.assertRaises(subprocess.CalledProcessError): activate.activate(self.base, self.record, self.env)
state = json.loads((self.base / 'installation.json').read_text())
self.assertEqual(state['status'], 'activation_failed')
self.assertTrue(any(cmd[:4] == ['systemctl', '--user', 'disable', '--now'] for cmd in self.commands))
self.assertEqual((self.base / 'data' / 'cacu.db').read_bytes(), b'existing')
if __name__ == '__main__':
unittest.main()
+65
View File
@@ -0,0 +1,65 @@
"""Verify bundles export committed trees, excluding working files and Git metadata."""
import hashlib
from pathlib import Path
import subprocess
import tarfile
import tempfile
import unittest
import bundle
def git(repo, *args):
return subprocess.run(['git', '-C', str(repo), *args], check=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True).stdout.strip()
class BundleTests(unittest.TestCase):
"""Two small temporary Git repositories model the application and a pinned child."""
def test_export_uses_git_objects_and_pinned_nested_checkout(self):
"""Uncommitted changes and untracked files cannot enter a release archive."""
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
app = root / 'ISSSTELEON'
child = app / 'WebApi'
for repo in (app, child):
repo.mkdir(parents=True, exist_ok=True)
git(repo, 'init', '--quiet')
git(repo, 'config', 'user.name', 'Fixture')
git(repo, 'config', 'user.email', 'fixture@example.invalid')
tracked = repo / ('Core/tracked.txt' if repo == app else 'tracked.txt')
tracked.parent.mkdir(parents=True, exist_ok=True)
tracked.write_text('committed', encoding='utf-8')
git(repo, 'add', str(tracked.relative_to(repo)))
git(repo, 'commit', '-m', 'fixture')
manifest = {'ISSSTELEON': git(app, 'rev-parse', 'HEAD'), 'ISSSTELEON/WebApi': git(child, 'rev-parse', 'HEAD')}
(child / 'tracked.txt').write_text('modified', encoding='utf-8')
(child / 'private.txt').write_text('untracked', encoding='utf-8')
output = root / 'bundle.tar.gz'
sha = bundle.export(root, manifest, output)
self.assertEqual(sha, hashlib.sha256(output.read_bytes()).hexdigest())
duplicate = root / 'duplicate.tar.gz'
self.assertEqual(bundle.export(root, manifest, duplicate), sha)
self.assertEqual(output.read_bytes(), duplicate.read_bytes())
with tarfile.open(output) as archive:
self.assertEqual(archive.extractfile('application/WebApi/tracked.txt').read(), b'committed')
self.assertNotIn('application/WebApi/private.txt', archive.getnames())
self.assertFalse(any('.git/' in name for name in archive.getnames()))
def test_unknown_checkout_is_rejected(self):
"""A child checkout at a different SHA cannot be archived under a recorded gitlink."""
with tempfile.TemporaryDirectory() as tmp:
repo = Path(tmp) / 'ISSSTELEON'
repo.mkdir()
git(repo, 'init', '--quiet')
git(repo, 'config', 'user.name', 'Fixture')
git(repo, 'config', 'user.email', 'fixture@example.invalid')
(repo / 'file').write_text('data', encoding='utf-8')
git(repo, 'add', 'file')
git(repo, 'commit', '-m', 'fixture')
with self.assertRaises(ValueError):
bundle.export(Path(tmp), {'ISSSTELEON': '0' * 40}, Path(tmp) / 'out.tar.gz')
if __name__ == '__main__':
unittest.main()
+297
View File
@@ -0,0 +1,297 @@
"""Test isolated preparation and health verification with temporary release bundles and fake commands."""
import hashlib
import io
import json
import os
import subprocess
from pathlib import Path
import socket
import sys
import tarfile
import tempfile
import types
import unittest
from unittest.mock import patch
import install
import verify
class InstallerTests(unittest.TestCase):
"""A temporary directory represents an empty dedicated installation parent."""
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.root = Path(self.tmp.name)
self.bundle = self.root / 'release.tar.gz'
with tarfile.open(self.bundle, 'w:gz') as archive:
files = [('application/WebApi/pyproject.toml', b'[project]'),
('application/WebApi/uv.lock', b''),
('application/WebApi/webapi/indicadores_vivos.py', b''),
('application/WebApp/package.json', b'{}'),
('application/WebApp/package-lock.json', b'{}')]
files += [(f'application/Persistance/persistance/{domain}/alembic.ini', b'')
for domain in install.DOMAINS]
for name, content in files:
info = tarfile.TarInfo(name)
info.size = len(content)
archive.addfile(info, io.BytesIO(content))
self.digest = hashlib.sha256(self.bundle.read_bytes()).hexdigest()
self.record = {'tag': 'v1', 'release_id': 1, 'public_port': 18090, 'api_port': 28090,
'application_sha': 'a' * 40, 'installer_sha': 'b' * 40,
'tag_object': 'c' * 40, 'installer_ref': 'refs/heads/dev',
'bundle_sha256': self.digest,
'installer_files': {name: 'e' * 64 for name in install.INSTALLER_FILES},
'gitlinks': {name: 'd' * 40 for name in install.REQUIRED_LINKS}}
self.account = 'wnnative'
self.hostname = socket.gethostname()
self.tools = {'uv': '/usr/bin/uv', 'npm': '/usr/bin/npm', 'nginx': '/usr/sbin/nginx'}
self.calls = []
self.real_check_port = install.check_port
self.real_validate_parent = install.validate_parent
self.real_validate_service_account = install.validate_service_account
self.patches = [patch.object(install, 'validate_parent', return_value=self.root),
patch.object(install, 'validate_service_account'),
patch.object(install.os, 'geteuid', return_value=1234, create=True),
patch.dict(sys.modules, {'pwd': types.SimpleNamespace(getpwuid=lambda uid: types.SimpleNamespace(pw_name=self.account))}),
patch.object(install, 'check_port'), patch.object(install, 'run', side_effect=self.fake_run)]
for item in self.patches:
item.start()
self.addCleanup(item.stop)
def fake_run(self, args, cwd, env):
self.calls.append((list(map(str, args)), Path(cwd), dict(env)))
if args[1:3] == ['run', 'build']:
index = Path(cwd) / 'dist' / 'WebApp' / 'browser' / 'index.html'
index.parent.mkdir(parents=True)
index.write_text('app', encoding='utf-8')
if 'alembic' in args:
domain = next(part for part in install.DOMAINS if part in str(args[-3]))
self.assertTrue(env[domain.upper() + '_DATABASE_URL'].replace('\\', '/').endswith('/data/' + domain + '.db'))
(self.root / 'isssteleon-native-18090' / 'data' / (domain + '.db')).write_bytes(b'migrated')
def prepare(self, api_port=28090):
return install.prepare(self.root, self.record, self.bundle, self.digest, api_port, self.account, self.hostname, self.tools)
def test_new_installation_prepares_locked_build_migrations_and_units(self):
"""A new instance must use locked builds, four isolated databases and three inactive unit files."""
result = self.prepare()
base = self.root / 'isssteleon-native-18090'
self.assertEqual(result['status'], 'prepared')
self.assertEqual([item[0][1:3] for item in self.calls[:3]], [['sync', '--locked'], ['ci'], ['run', 'build']])
self.assertEqual(sum('alembic' in args for args, _, _ in self.calls), 4)
guard_index = next(i for i, (args, _, _) in enumerate(self.calls) if args[1:4] == ['run', '--no-sync', 'python'])
first_migration = next(i for i, (args, _, _) in enumerate(self.calls) if 'alembic' in args)
self.assertLess(guard_index, first_migration)
for domain in install.DOMAINS:
self.assertEqual((base / 'data' / (domain + '.db')).read_bytes(), b'migrated')
self.assertEqual(len(list((base / 'units').glob('*.service'))), 3)
api = (base / 'units' / 'isssteleon-native-18090-api.service').read_text()
worker = (base / 'units' / 'isssteleon-native-18090-worker.service').read_text()
self.assertIn('127.0.0.1:28090', api)
self.assertNotIn('User=', api)
self.assertIn('WantedBy=default.target', api)
self.assertIn('PrivateUsers=true', api)
self.assertIn('webapi.indicadores_vivos', worker)
self.assertIn('proxy_pass http://127.0.0.1:28090', (base / 'nginx.conf').read_text())
self.assertFalse(any('systemctl' in args for args, _, _ in self.calls))
def test_custom_api_port_reaches_configuration_record_and_health_checks(self):
"""The selected API port must drive loopback Gunicorn, nginx, metadata and verification."""
self.record['api_port'] = 31001
result = self.prepare(31001)
base = self.root / 'isssteleon-native-18090'
self.assertEqual(result['api_port'], 31001)
self.assertEqual(json.loads((base / 'installation.json').read_text())['api_port'], 31001)
self.assertIn('127.0.0.1:31001', (base / 'units' / 'isssteleon-native-18090-api.service').read_text())
self.assertIn('proxy_pass http://127.0.0.1:31001', (base / 'nginx.conf').read_text())
urls = []
def request(url):
urls.append(url)
return 200, b'{"status":"ok"}' if url.endswith('/health') else b'<html>app</html>'
verify.check(dict(result, status='started'), command=lambda *a, **k: types.SimpleNamespace(returncode=0), get=request)
self.assertIn('http://127.0.0.1:31001/health', urls)
self.assertIn('http://127.0.0.1:18090/health', urls)
def test_api_port_mismatch_stops_before_creating_instance(self):
"""A changed API port must not override the port recorded in the validated release request."""
with self.assertRaises(ValueError): self.prepare(31001)
self.assertFalse((self.root / 'isssteleon-native-18090').exists())
self.assertEqual(self.calls, [])
def test_existing_instance_is_never_overwritten_or_migrated(self):
"""A repeated installation must reject the existing directory and preserve data."""
self.prepare()
marker = self.root / 'isssteleon-native-18090' / 'data' / 'cacu.db'
before = marker.read_bytes()
call_count = len(self.calls)
with self.assertRaises(FileExistsError):
self.prepare()
self.assertEqual(marker.read_bytes(), before)
self.assertEqual(len(self.calls), call_count)
def test_digest_mismatch_and_port_conflict_stop_before_reservation(self):
"""Wrong source integrity or occupied ports must not create an installation directory."""
with self.assertRaises(ValueError):
install.prepare(self.root, self.record, self.bundle, '0' * 64, 28090, self.account, self.hostname, self.tools)
with patch.object(install, 'check_port', side_effect=ValueError('occupied')):
with self.assertRaises(ValueError): self.prepare()
self.assertFalse((self.root / 'isssteleon-native-18090').exists())
def test_partial_failure_preserves_data_and_rejects_retry(self):
"""A build error must leave a failed record and data rather than erase or reuse it."""
with patch.object(install, 'run', side_effect=RuntimeError('build failed')):
with self.assertRaises(RuntimeError): self.prepare()
base = self.root / 'isssteleon-native-18090'
state = json.loads((base / 'installation.json').read_text())
self.assertEqual(state['status'], 'failed')
self.assertTrue((base / 'data' / 'cacu.db').exists())
with self.assertRaises(FileExistsError): self.prepare()
def test_effective_target_guard_executes_and_rejects_mismatch(self):
"""The guard must inspect effective settings in a separate Python process without migrating files."""
data = self.root / 'guard-data'
data.mkdir()
for domain in install.DOMAINS:
(data / (domain + '.db')).touch()
env = dict(os.environ)
env.update(install.environment(self.root))
for domain in install.DOMAINS:
env[domain.upper() + '_DATABASE_URL'] = 'sqlite:///' + str(data / (domain + '.db'))
captured = []
with patch.object(install, 'run', side_effect=lambda args, cwd, env: captured.append(args)):
install.verify_database_targets('/usr/bin/uv', self.root, env, data)
code = captured[0][-2]
bootstrap = """import os, sys, types
root = types.ModuleType('persistance')
settings_module = types.ModuleType('persistance.settings')
settings_module.settings = types.SimpleNamespace(**{d + '_database_url': os.environ[d.upper() + '_DATABASE_URL'] for d in ('cacu','cama','tea','governance')})
if os.environ.get('FIXTURE_MISMATCH'):
settings_module.settings.cacu_database_url = 'sqlite:////outside/data.db'
sys.modules['persistance'] = root
sys.modules['persistance.settings'] = settings_module
sqlalchemy = types.ModuleType('sqlalchemy')
engine = types.ModuleType('sqlalchemy.engine')
engine.make_url = lambda url: types.SimpleNamespace(drivername='sqlite', database=url[len('sqlite:///'):])
sys.modules['sqlalchemy'] = sqlalchemy
sys.modules['sqlalchemy.engine'] = engine
"""
ok = subprocess.run([sys.executable, '-c', bootstrap + code, str(data)], env=env, capture_output=True)
self.assertEqual(ok.returncode, 0, ok.stderr)
mismatch = subprocess.run([sys.executable, '-c', bootstrap + code, str(data)], env=dict(env, FIXTURE_MISMATCH='1'), capture_output=True)
self.assertNotEqual(mismatch.returncode, 0)
(data / 'tea.db').write_bytes(b'existing')
occupied = subprocess.run([sys.executable, '-c', bootstrap + code, str(data)], env=env, capture_output=True)
self.assertNotEqual(occupied.returncode, 0)
self.assertEqual((data / 'tea.db').read_bytes(), b'existing')
def test_effective_target_guard_failure_blocks_all_migrations(self):
"""An application settings mismatch must stop the installer before any Alembic command."""
def reject_guard(args, cwd, env):
self.fake_run(args, cwd, env)
if args[1:4] == ['run', '--no-sync', 'python']:
raise RuntimeError('effective database URL mismatch')
with patch.object(install, 'run', side_effect=reject_guard), self.assertRaises(RuntimeError):
self.prepare()
self.assertFalse(any('alembic' in args for args, _, _ in self.calls))
record = json.loads((self.root / 'isssteleon-native-18090' / 'installation.json').read_text())
self.assertEqual(record['phase'], 'verifying_migration_targets')
self.assertEqual(record['status'], 'failed')
def test_migration_rejects_nonempty_target(self):
"""Unexpected existing database contents must stop migrations rather than touch the data."""
def inject(args, cwd, env):
self.fake_run(args, cwd, env)
if args[1:3] == ['run', 'build']:
(self.root / 'isssteleon-native-18090' / 'data' / 'cacu.db').write_bytes(b'existing')
with patch.object(install, 'run', side_effect=inject), self.assertRaises(ValueError): self.prepare()
self.assertEqual((self.root / 'isssteleon-native-18090' / 'data' / 'cacu.db').read_bytes(), b'existing')
self.assertFalse(any('alembic' in args for args, _, _ in self.calls))
def test_install_parent_must_be_private_and_account_owned(self):
"""A parent writable by another account cannot hold a trusted fresh installation."""
for owner, mode in [(9999, 0o750), (1234, 0o770), (1234, 0o757)]:
parent = types.SimpleNamespace(stat=lambda: types.SimpleNamespace(st_uid=owner, st_mode=mode))
with self.subTest(owner=owner, mode=mode), self.assertRaises(ValueError):
install.require_private_parent(parent)
parent = types.SimpleNamespace(stat=lambda: types.SimpleNamespace(st_uid=1234, st_mode=0o750))
install.require_private_parent(parent)
def test_privileged_service_group_memberships_are_rejected(self):
"""Reject Docker, sudo and root group membership even for non-root accounts."""
user = types.SimpleNamespace(pw_name=self.account, pw_gid=1001)
fake_pwd = types.SimpleNamespace(getpwuid=lambda uid: user)
fake_grp = types.SimpleNamespace(getgrnam=lambda name: types.SimpleNamespace(gr_gid={'docker': 998, 'sudo': 27, 'wheel': 10}[name]))
with patch.dict(sys.modules, {'pwd': fake_pwd, 'grp': fake_grp}), patch.object(install.os, 'geteuid', return_value=1001, create=True), patch.object(install.os, 'getegid', return_value=1001, create=True), patch.object(install.os, 'getgroups', return_value=[1001], create=True), patch.object(install.os, 'getgrouplist', return_value=[1001, 998], create=True), patch.object(install, 'validate_service_account', wraps=self.real_validate_service_account):
with self.assertRaises(ValueError): install.validate_service_account(self.account)
with patch.dict(sys.modules, {'pwd': fake_pwd, 'grp': fake_grp}), patch.object(install.os, 'geteuid', return_value=1001, create=True), patch.object(install.os, 'getegid', return_value=1001, create=True), patch.object(install.os, 'getgroups', return_value=[27], create=True), patch.object(install.os, 'getgrouplist', return_value=[1001], create=True), patch.object(install, 'validate_service_account', wraps=self.real_validate_service_account):
with self.assertRaises(ValueError): install.validate_service_account(self.account)
with patch.dict(sys.modules, {'pwd': fake_pwd, 'grp': fake_grp}), patch.object(install.os, 'geteuid', return_value=1001, create=True), patch.object(install.os, 'getegid', return_value=1001, create=True), patch.object(install.os, 'getgroups', return_value=[1001], create=True), patch.object(install.os, 'getgrouplist', return_value=[1001], create=True), patch.object(install, 'validate_service_account', wraps=self.real_validate_service_account):
install.validate_service_account(self.account)
def test_host_mismatch_and_docker_root_are_rejected(self):
"""An unexpected host or Docker data parent cannot receive an installation."""
with self.assertRaises(ValueError):
install.prepare(self.root, self.record, self.bundle, self.digest, 28090, self.account, 'different-host', self.tools)
parent = self.root / 'docker'
parent.mkdir()
import re
real_validate_parent = self.real_validate_parent
with patch.object(install, 'SAFE_PATH', re.compile(r'^.+$')), patch.object(install, 'DOCKER_ROOT', parent), patch.object(install, 'validate_parent', wraps=real_validate_parent):
with self.assertRaises(ValueError): install.validate_parent(parent)
self.assertFalse((parent / 'isssteleon-native-18090').exists())
def test_archive_rejects_traversal_and_links(self):
"""Archive extraction must reject paths and links that escape the fresh instance."""
for name, member_type in [('../escape', tarfile.REGTYPE), ('application/link', tarfile.SYMTYPE)]:
path = self.root / ('bad-' + str(member_type[0]) + '.tar.gz')
with tarfile.open(path, 'w:gz') as archive:
info = tarfile.TarInfo(name)
info.type = member_type
if member_type == tarfile.SYMTYPE: info.linkname = '/tmp'
archive.addfile(info)
with self.subTest(name=name), self.assertRaises(ValueError):
install.extract_bundle(path, self.root / 'extract')
self.assertFalse((self.root / 'escape').exists())
def test_socket_conflict_detection(self):
"""A real loopback listener must prevent the installer from using the same API port."""
with socket.socket() as listener:
listener.bind(('127.0.0.1', 0))
listener.listen()
with patch.object(install, 'check_port', wraps=self.real_check_port):
with self.assertRaises(ValueError): install.check_port(listener.getsockname()[1], False)
with socket.socket() as listener:
listener.bind(('0.0.0.0', 0))
listener.listen()
with patch.object(install, 'check_port', wraps=self.real_check_port):
with self.assertRaises(ValueError): install.check_port(listener.getsockname()[1], True)
def test_failed_verification_is_recorded_and_can_be_retried(self):
"""A startup failure remains visible in the record and permits another health check."""
record = dict(self.prepare(), status='started')
base = self.root / 'isssteleon-native-18090'
(base / 'installation.json').write_text(json.dumps(record), encoding='utf-8')
with patch.object(sys, 'argv', ['verify.py', str(base), '--wait-seconds', '0']), patch.object(verify.activate, 'manager_environment', return_value={}), patch.object(verify, 'check', side_effect=ValueError('service failed')):
self.assertEqual(verify.main(), 1)
record = json.loads((base / 'installation.json').read_text())
self.assertEqual(record['status'], 'verification_failed')
self.assertIn('service failed', record['health']['error'])
ok = lambda *args, **kwargs: types.SimpleNamespace(returncode=0)
get = lambda url: (200, b'{"status":"ok"}' if url.endswith('/health') else b'<html>app</html>')
self.assertEqual(verify.check(record, command=ok, get=get)['proxy_health'], 'ok')
def test_health_requires_all_services_and_spa_fallback(self):
"""Health fails if a unit is inactive or proxy and SPA checks do not match."""
record = dict(self.prepare(), status='started')
ok = lambda *args, **kwargs: types.SimpleNamespace(returncode=0)
get = lambda url: (200, b'{"status":"ok"}' if url.endswith('/health') else b'<html>app</html>')
self.assertEqual(verify.check(record, command=ok, get=get)['proxy_health'], 'ok')
with self.assertRaises(ValueError):
verify.check(record, command=lambda *a, **k: types.SimpleNamespace(returncode=3), get=get)
with self.assertRaises(ValueError):
verify.check(record, command=ok, get=lambda url: (200, b'{"status":"ok"}' if url.endswith('/health') else url.encode()))
if __name__ == '__main__':
unittest.main()
+108
View File
@@ -0,0 +1,108 @@
"""Test explicit, pinned-key SSH preparation with synthetic artifacts and no network."""
import hashlib
import json
from pathlib import Path
import subprocess
import tempfile
import unittest
from unittest.mock import patch
import install
import remote
class RemoteTests(unittest.TestCase):
"""Local fake files and mocked processes represent an authorized operator channel."""
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.root = Path(self.tmp.name)
self.dir = self.root / 'bundle'
self.dir.mkdir()
for name in install.INSTALLER_FILES:
(self.dir / name).write_bytes(('content:' + name).encode())
(self.dir / 'release-source.tar.gz').write_bytes(b'archive')
self.sha = hashlib.sha256(b'archive').hexdigest()
self.record = {'tag': 'v1', 'release_id': 1, 'public_port': 18090, 'api_port': 28090,
'application_sha': 'a' * 40, 'installer_sha': 'b' * 40,
'tag_object': 'c' * 40, 'installer_ref': 'refs/heads/dev',
'bundle_sha256': self.sha,
'gitlinks': {name: 'd' * 40 for name in install.REQUIRED_LINKS},
'installer_files': {name: install.digest(self.dir / name) for name in install.INSTALLER_FILES}}
(self.dir / 'release-record.json').write_text(json.dumps(self.record), encoding='utf-8')
self.key = self.root / 'identity'
self.known = self.root / 'known_hosts'
self.key.write_text('fixture')
self.known.write_text('fixture')
def call(self, host='10.0.10.41', account='wnnative', api_port=28090):
return remote.prepare(self.dir, self.sha, host, 22, account, 'labserver',
'/srv/workingnarrative-native', api_port, self.key, self.known)
def test_only_explicit_nonprivileged_ssh_and_pinned_host_keys(self):
"""Preparation uses strict host-key checks and never invokes sudo or systemctl."""
with patch.object(remote.shutil, 'which', side_effect=lambda name: '/usr/bin/' + name), patch.object(remote.subprocess, 'run') as run, patch.object(remote, 'check_public') as public:
stage = self.call()
self.assertTrue(stage.startswith('/srv/workingnarrative-native/.release-'))
self.assertEqual(run.call_count, 6)
public.assert_called_once_with('10.0.10.41', 18090)
for call in run.call_args_list:
args = call.args[0]
self.assertIn('StrictHostKeyChecking=yes', args)
self.assertIn('BatchMode=yes', args)
self.assertNotIn('sudo', args)
self.assertNotIn('systemctl', args)
self.assertIn('install.py', str(run.call_args_list[2]))
self.assertIn('activate.py', str(run.call_args_list[3]))
self.assertIn('--public-result ok', str(run.call_args_list[-1]))
def test_requested_api_port_is_transferred_and_mismatch_rejected(self):
"""SSH must pass the exact recorded API port and reject any altered value before connection."""
with patch.object(remote.subprocess, 'run') as run:
with self.assertRaises(ValueError): self.call(api_port=31001)
run.assert_not_called()
self.record['api_port'] = 31001
(self.dir / 'release-record.json').write_text(json.dumps(self.record), encoding='utf-8')
with patch.object(remote.shutil, 'which', side_effect=lambda name: '/usr/bin/' + name), patch.object(remote.subprocess, 'run') as run, patch.object(remote, 'check_public'):
self.call(api_port=31001)
self.assertIn('--api-port 31001', str(run.call_args_list[2]))
def test_bad_endpoint_or_tampered_installer_never_connects(self):
"""Unsafe endpoint syntax or altered installer scripts must fail before SSH."""
with patch.object(remote.subprocess, 'run') as run:
with self.assertRaises(ValueError): self.call(host='host;evil')
with self.assertRaises(ValueError): self.call(account='root')
(self.dir / 'install.py').write_text('tampered', encoding='utf-8')
with self.assertRaises(ValueError): self.call()
run.assert_not_called()
def test_public_failure_fails_action_and_records_failure(self):
"""An unreachable public endpoint must report failure instead of a successful deployment."""
with patch.object(remote.shutil, 'which', side_effect=lambda name: '/usr/bin/' + name), patch.object(remote.subprocess, 'run') as run, patch.object(remote, 'check_public', side_effect=ValueError('unreachable')):
with self.assertRaises(ValueError): self.call()
self.assertIn('--public-result failed', str(run.call_args_list[-1]))
self.assertFalse(run.call_args_list[-1].kwargs['check'])
def test_activation_failure_prevents_public_success(self):
"""A failed service activation must stop before any public health check."""
with patch.object(remote.shutil, 'which', side_effect=lambda name: '/usr/bin/' + name), patch.object(remote.subprocess, 'run', side_effect=[None, None, None, subprocess.CalledProcessError(1, 'ssh')]), patch.object(remote, 'check_public') as public:
with self.assertRaises(subprocess.CalledProcessError): self.call()
public.assert_not_called()
def test_public_probe_rejects_bad_health(self):
"""The public endpoint must serve both the WebApp and a healthy proxied API."""
responses = [(200, b'{"status":"ok"}'), (200, b'<html>app</html>')]
with patch.object(remote.verify, 'request', side_effect=responses):
remote.check_public('10.0.10.41', 18090, timeout=0)
with patch.object(remote.verify, 'request', side_effect=[(200, b'{"status":"bad"}'), (200, b'app')]):
with self.assertRaises(ValueError): remote.check_public('10.0.10.41', 18090, timeout=0)
def test_failed_remote_identity_check_never_uploads(self):
"""A failed remote guard must prevent copying or executing the installer."""
with patch.object(remote.shutil, 'which', side_effect=lambda name: '/usr/bin/' + name), patch.object(remote.subprocess, 'run', side_effect=subprocess.CalledProcessError(1, 'ssh')) as run:
with self.assertRaises(subprocess.CalledProcessError): self.call()
self.assertEqual(run.call_count, 1)
if __name__ == '__main__':
unittest.main()
+218
View File
@@ -0,0 +1,218 @@
"""Exercise release identity and fail-closed behavior using temporary Git repositories and fake API responses."""
import importlib.util
import json
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
from unittest.mock import patch
spec = importlib.util.spec_from_file_location('resolve', Path(__file__).with_name('resolve.py'))
resolver = importlib.util.module_from_spec(spec)
spec.loader.exec_module(resolver)
def command(*args, cwd):
return subprocess.run(args, cwd=cwd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True).stdout.strip()
class ResolutionTests(unittest.TestCase):
"""A bare local origin stands in for the institutional repository."""
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
root = Path(self.temp.name)
self.origin = root / 'origin.git'
self.repo = root / 'repo'
command('git', 'init', '--bare', str(self.origin), cwd=root)
command('git', 'init', str(self.repo), cwd=root)
command('git', 'config', 'user.name', 'Test', cwd=self.repo)
command('git', 'config', 'user.email', 'test@example.invalid', cwd=self.repo)
(self.repo / 'file').write_text('test', encoding='utf-8')
command('git', 'add', 'file', cwd=self.repo)
command('git', 'commit', '-m', 'initial', cwd=self.repo)
self.sha = command('git', 'rev-parse', 'HEAD', cwd=self.repo)
command('git', 'remote', 'add', 'origin', str(self.origin), cwd=self.repo)
command('git', 'tag', '-a', 'v1', '-m', 'release', cwd=self.repo)
command('git', 'push', 'origin', 'refs/tags/v1', cwd=self.repo)
self.env = {'DISPATCH_REF': 'refs/heads/dev', 'DISPATCH_REF_NAME': 'dev',
'DISPATCH_REF_TYPE': 'branch', 'DISPATCH_SHA': self.sha,
'DISPATCH_REPOSITORY': resolver.REPOSITORY, 'DISPATCH_SERVER': resolver.SERVER,
'RELEASE_TOKEN': 'test'}
def test_annotated_tag_resolves_to_commit_and_preserves_installer_identity(self):
"""Peeling must return the commit while retaining the distinct tag object and installer revision."""
with patch.object(resolver, 'ORIGIN', str(self.origin)), patch.object(resolver, 'release', return_value={'release_id': 7, 'tag': 'v1'}):
record = resolver.resolve(self.repo, 'v1', '18090', '28090', self.env)
self.assertEqual(record['application_sha'], self.sha)
self.assertEqual(record['installer_sha'], self.sha)
self.assertNotEqual(record['tag_object'], self.sha)
self.assertEqual(record['release_id'], 7)
self.assertEqual(record['public_port'], 18090)
self.assertEqual(record['api_port'], 28090)
self.assertEqual(command('git', 'for-each-ref', '--format=%(refname)', 'refs/deploy-terminal', cwd=self.repo), '')
def test_invalid_or_missing_tags_and_ports_fail(self):
"""Invalid inputs and absent remote refs must fail before they can identify a deployment."""
for tag in ('', '-x', 'refs/tags/v1', 'bad..tag', 'a' * 40):
with self.subTest(tag=tag), self.assertRaises((ValueError, subprocess.CalledProcessError)):
resolver.validate_tag(tag)
for port in ('0', '65536', 'abc'):
with self.subTest(port=port), self.assertRaises(ValueError):
resolver.validate_port(port)
with patch.object(resolver, 'ORIGIN', str(self.origin)), patch.object(resolver, 'release', return_value={'release_id': 7, 'tag': 'missing'}):
with self.assertRaises(subprocess.CalledProcessError):
resolver.resolve(self.repo, 'missing', '18090', '28090', self.env)
self.assertEqual(command('git', 'for-each-ref', '--format=%(refname)', 'refs/deploy-terminal', cwd=self.repo), '')
def test_custom_public_and_api_ports_are_recorded(self):
"""The release record must retain both operator-selected ports without replacing either default."""
with patch.object(resolver, 'ORIGIN', str(self.origin)), patch.object(resolver, 'release', return_value={'release_id': 7, 'tag': 'v1'}):
record = resolver.resolve(self.repo, 'v1', '18123', '31001', self.env)
self.assertEqual(record['public_port'], 18123)
self.assertEqual(record['api_port'], 31001)
def test_both_requested_ports_are_validated_before_release_lookup(self):
"""Invalid, privileged, oversized or equal ports must fail before any network access."""
requests = [('0', '28090'), ('65536', '28090'), ('18090', '0'),
('18090', '65536'), ('18090', 'abc'), ('18090', '18090')]
with patch.object(resolver, 'dispatch') as dispatch, patch.object(resolver, 'release') as release:
for public, api in requests:
with self.subTest(public=public, api=api), self.assertRaises(ValueError):
resolver.resolve(self.repo, 'v1', public, api, self.env)
dispatch.assert_not_called()
release.assert_not_called()
def test_wrong_identity_is_rejected(self):
"""External repository, server and checkout identities cannot authorize resolution."""
with patch.object(resolver, 'ORIGIN', str(self.origin)):
for key, value in [('DISPATCH_REPOSITORY', 'other/repo'), ('DISPATCH_SERVER', 'http://evil'), ('DISPATCH_SHA', '0' * 40)]:
with self.subTest(key=key), self.assertRaises(ValueError):
resolver.dispatch(self.repo, dict(self.env, **{key: value}))
with self.assertRaises(ValueError):
resolver.dispatch(self.repo, self.env)
def test_release_change_fails_and_cleans_temporary_ref(self):
"""A changed release cannot pass the second check and failure removes its temporary ref."""
with patch.object(resolver, 'ORIGIN', str(self.origin)), patch.object(resolver, 'release', side_effect=[{'release_id': 7, 'tag': 'v1'}, {'release_id': 8, 'tag': 'v1'}]):
with self.assertRaises(ValueError):
resolver.resolve(self.repo, 'v1', '18090', '28090', self.env)
self.assertEqual(command('git', 'for-each-ref', '--format=%(refname)', 'refs/deploy-terminal', cwd=self.repo), '')
def test_source_preparation_uses_selected_commit_in_a_disposable_tree(self):
"""Source preparation must retain the installer checkout and discard temporary application files."""
tag_object = command('git', 'rev-parse', 'refs/tags/v1', cwd=self.repo)
record = {'tag': 'v1', 'tag_object': tag_object, 'application_sha': self.sha}
captured = []
def inspect(checkout):
captured.append(checkout)
self.assertEqual(command('git', 'rev-parse', 'HEAD', cwd=checkout), self.sha)
return {'ISSSTELEON': 'a' * 40}
with patch.object(resolver.source, 'checkout_pinned', side_effect=inspect):
self.assertEqual(resolver.prepare_source(self.repo, record), {'ISSSTELEON': 'a' * 40})
self.assertFalse(captured[0].exists())
self.assertEqual(command('git', 'rev-parse', 'HEAD', cwd=self.repo), self.sha)
self.assertEqual(command('git', 'for-each-ref', '--format=%(refname)', 'refs/deploy-terminal', cwd=self.repo), '')
def test_source_preparation_rejects_changed_tag(self):
"""A tag that changes between resolution and source checkout cannot reach submodule preparation."""
record = {'tag': 'v1', 'tag_object': '0' * 40, 'application_sha': self.sha}
with patch.object(resolver.source, 'checkout_pinned') as checkout:
with self.assertRaises(ValueError):
resolver.prepare_source(self.repo, record)
checkout.assert_not_called()
self.assertEqual(command('git', 'for-each-ref', '--format=%(refname)', 'refs/deploy-terminal', cwd=self.repo), '')
def test_remote_tag_change_fails_closed(self):
"""A tag moved after fetch must not be used even if the release remains published."""
original_git = resolver.git
def changed_git(root, *args):
if args[0] == 'ls-remote':
return '0' * 40 + '\trefs/tags/v1'
return original_git(root, *args)
with patch.object(resolver, 'ORIGIN', str(self.origin)), patch.object(resolver, 'release', return_value={'release_id': 7, 'tag': 'v1'}), patch.object(resolver, 'git', side_effect=changed_git):
with self.assertRaises(ValueError):
resolver.resolve(self.repo, 'v1', '18090', '28090', self.env)
self.assertEqual(command('git', 'for-each-ref', '--format=%(refname)', 'refs/deploy-terminal', cwd=self.repo), '')
def test_application_and_installer_commits_are_independent(self):
"""A release can point to an older commit without changing the installer checkout."""
(self.repo / 'file').write_text('installer', encoding='utf-8')
command('git', 'commit', '-am', 'installer', cwd=self.repo)
installer_sha = command('git', 'rev-parse', 'HEAD', cwd=self.repo)
env = dict(self.env, DISPATCH_SHA=installer_sha)
with patch.object(resolver, 'ORIGIN', str(self.origin)), patch.object(resolver, 'release', return_value={'release_id': 7, 'tag': 'v1'}):
record = resolver.resolve(self.repo, 'v1', '18090', '28090', env)
self.assertEqual(record['application_sha'], self.sha)
self.assertEqual(record['installer_sha'], installer_sha)
self.assertEqual(command('git', 'rev-parse', 'HEAD', cwd=self.repo), installer_sha)
def test_installer_files_match_dispatched_commit(self):
"""Every transferred installer script must be the committed installer revision."""
directory = self.repo / '.gitea' / 'deploy-terminal'
directory.mkdir(parents=True)
for name in ('install.py', 'activate.py', 'verify.py', 'remote.py', 'bundle.py', 'source.py'):
(directory / name).write_bytes(('fixture ' + name).encode())
command('git', 'add', '.gitea', cwd=self.repo)
command('git', 'commit', '-m', 'installer', cwd=self.repo)
sha = command('git', 'rev-parse', 'HEAD', cwd=self.repo)
self.assertEqual(len(resolver.installer_manifest(self.repo, sha)), 6)
(directory / 'install.py').write_text('modified', encoding='utf-8')
with self.assertRaises(ValueError): resolver.installer_manifest(self.repo, sha)
def test_manual_workflow_prepares_bundle_and_release_record(self):
"""A manual dispatch must publish the resolved identity and source digest together."""
directory = self.repo / '.gitea' / 'deploy-terminal'
directory.mkdir(parents=True)
for name in ('install.py', 'activate.py', 'verify.py', 'remote.py', 'bundle.py', 'source.py'):
(directory / name).write_bytes(('fixture ' + name).encode())
command('git', 'add', '.gitea', cwd=self.repo)
command('git', 'commit', '-m', 'installer', cwd=self.repo)
installer_sha = command('git', 'rev-parse', 'HEAD', cwd=self.repo)
output = self.repo.parent / 'artifact' / 'release-source.tar.gz'
output.parent.mkdir()
env = dict(self.env, DISPATCH_SHA=installer_sha, REQUESTED_TAG='v1', REQUESTED_PORT='18090', REQUESTED_API_PORT='28090', RELEASE_OUTPUT=str(output))
links = {'ISSSTELEON': 'a' * 40}
def export(checkout, manifest, path):
Path(path).write_bytes(b'fixture bundle')
return 'd' * 64
with patch.object(resolver, 'ROOT', self.repo), patch.object(resolver, 'ORIGIN', str(self.origin)), patch.dict(os.environ, env), patch.object(resolver, 'release', return_value={'release_id': 7, 'tag': 'v1'}), patch.object(resolver.source, 'checkout_pinned', return_value=links), patch.object(resolver.bundle, 'export', side_effect=export):
self.assertEqual(resolver.main(), 0)
record = json.loads((output.parent / 'release-record.json').read_text())
self.assertEqual(record['installer_sha'], installer_sha)
self.assertEqual(record['application_sha'], self.sha)
self.assertEqual(record['api_port'], 28090)
self.assertEqual(record['gitlinks'], links)
self.assertEqual(record['bundle_sha256'], 'd' * 64)
self.assertEqual(len(record['installer_files']), 6)
def test_publication_is_rechecked_after_packaging(self):
"""A release or tag changed during archive creation must not produce an artifact record."""
record = {'tag': 'v1', 'tag_object': 'a' * 40, 'release_id': 7}
with patch.object(resolver, 'git', return_value='b' * 40 + '\trefs/tags/v1'), patch.object(resolver, 'release') as release:
with self.assertRaises(ValueError): resolver.revalidate(self.repo, record, 'token')
release.assert_not_called()
with patch.object(resolver, 'git', return_value='a' * 40 + '\trefs/tags/v1'), patch.object(resolver, 'release', return_value={'tag': 'v1', 'release_id': 8}):
with self.assertRaises(ValueError): resolver.revalidate(self.repo, record, 'token')
def test_release_metadata_must_be_published_and_match_tag(self):
"""Drafts, missing publication times and mismatched tags must not qualify as published releases."""
class Response:
def __init__(self, data): self.data = json.dumps(data).encode()
def __enter__(self): return self
def __exit__(self, *args): pass
def read(self, *args): return self.data
class Opener:
def __init__(self, data): self.data = data
def open(self, req, timeout): return Response(self.data)
good = {'id': 1, 'tag_name': 'v1', 'draft': False, 'published_at': '2026-01-01T00:00:00Z'}
for change in ({'draft': True}, {'published_at': None}, {'tag_name': 'v2'}, {'id': True}):
with self.subTest(change=change), patch.object(resolver.urllib.request, 'build_opener', return_value=Opener(dict(good, **change))):
with self.assertRaises(ValueError): resolver.release('v1', 'token')
with patch.object(resolver.urllib.request, 'build_opener', return_value=Opener(good)):
self.assertEqual(resolver.release('v1', 'token')['release_id'], 1)
if __name__ == '__main__':
unittest.main()
+88
View File
@@ -0,0 +1,88 @@
"""Check pinned application traversal with synthetic Git-tree and configuration fixtures."""
from pathlib import Path
import unittest
import os
import types
from unittest.mock import patch
import source
class SourceTests(unittest.TestCase):
"""A mocked Git interface models one outer and one nested application repository."""
def setUp(self):
self.a, self.b = 'a' * 40, 'b' * 40
self.outer = Path('/fixture')
self.application = self.outer / 'ISSSTELEON'
self.api = self.application / 'WebApi'
self.calls = []
def fake_git(self, repo, *args, binary=False):
repo = Path(repo)
self.calls.append((repo, args))
if args[:1] == ('ls-tree',):
if repo == self.outer:
return (f'160000 commit {self.a}\tISSSTELEON\0' + f'160000 commit {self.b}\tdev-data\0').encode()
if repo == self.application:
return f'160000 commit {self.b}\tWebApi\0'.encode()
return b''
if args[:4] == ('config', '-f', '.gitmodules', '--get-regexp'):
return 'submodule.ISSSTELEON.path ISSSTELEON' if repo == self.outer else 'submodule.WebApi.path WebApi'
if args[:4] == ('config', '-f', '.gitmodules', '--get'):
name = 'ISSSTELEON' if repo == self.outer else 'WebApi'
return 'ssh://git@10.0.10.41:2222/ISSSTELEON/' + name + '.git'
if args[:2] == ('rev-parse', 'HEAD'):
return self.a if repo == self.application else self.b
return ''
def test_institutional_git_auth_is_scoped_and_not_in_command(self):
"""Private nested Git fetches use a host-scoped job token without exposing it in arguments."""
env = {'RELEASE_TOKEN': 'fixture-token', 'GIT_CONFIG_COUNT': '1',
'GIT_CONFIG_KEY_0': 'url.http://10.0.10.41:3000/ISSSTELEON/.insteadOf',
'GIT_CONFIG_VALUE_0': 'ssh://git@10.0.10.41:2222/ISSSTELEON/'}
with patch.dict(os.environ, env, clear=True), patch.object(source.subprocess, 'run', return_value=types.SimpleNamespace(stdout='result')) as run:
self.assertEqual(source.git(self.outer, 'status'), 'result')
args, kwargs = run.call_args
self.assertNotIn('fixture-token', str(args))
self.assertEqual(kwargs['env']['GIT_CONFIG_COUNT'], '2')
self.assertEqual(kwargs['env']['GIT_CONFIG_KEY_1'], 'http.http://10.0.10.41:3000/ISSSTELEON/.extraheader')
self.assertEqual(kwargs['env']['GIT_TERMINAL_PROMPT'], '0')
def test_nested_links_are_pinned_and_unrelated_tree_is_ignored(self):
"""Traverse the application link and its nested link without touching dev-data."""
with patch.object(source, 'git', side_effect=self.fake_git):
result = source.checkout_pinned(self.outer)
self.assertEqual(result, {'ISSSTELEON': self.a, 'ISSSTELEON/WebApi': self.b})
self.assertFalse(any('dev-data' in str(args) for _, args in self.calls if '--checkout' in args))
self.assertTrue(all('--checkout' in args for _, args in self.calls if 'update' in args))
def test_external_origin_is_rejected(self):
"""An external submodule URL must fail before Git can initialize it."""
def fake(repo, *args, **kwargs):
if args[:4] == ('config', '-f', '.gitmodules', '--get'):
return 'https://outside.invalid/repo.git'
return self.fake_git(repo, *args, **kwargs)
with patch.object(source, 'git', side_effect=fake), self.assertRaises(ValueError):
source.checkout_pinned(self.outer)
self.assertFalse(any('--checkout' in args for _, args in self.calls))
def test_wrong_nested_checkout_is_rejected(self):
"""A nested checkout that differs from its gitlink must stop preparation."""
def fake(repo, *args, **kwargs):
if Path(repo) == self.api and args[:2] == ('rev-parse', 'HEAD'):
return 'c' * 40
return self.fake_git(repo, *args, **kwargs)
with patch.object(source, 'git', side_effect=fake), self.assertRaises(ValueError):
source.checkout_pinned(self.outer)
def test_unknown_nested_gitlink_is_rejected(self):
"""Unrecognized nested repositories must never be initialized implicitly."""
def fake(repo, *args, **kwargs):
if Path(repo) == self.application and args[:1] == ('ls-tree',):
return f'160000 commit {self.b}\tUnknown\0'.encode()
return self.fake_git(repo, *args, **kwargs)
with patch.object(source, 'git', side_effect=fake), self.assertRaises(ValueError):
source.checkout_pinned(self.outer)
if __name__ == '__main__':
unittest.main()
+41
View File
@@ -0,0 +1,41 @@
"""Protect the manual workflow's deployment chain and Docker independence."""
from pathlib import Path
import subprocess
import re
import unittest
ROOT = Path(__file__).resolve().parents[2]
WORKFLOW = ROOT / '.gitea' / 'workflows' / 'deploy-terminal-release.yml'
class WorkflowTests(unittest.TestCase):
"""The current checkout provides the uncommitted workflow and the Docker baseline."""
def test_workflow_dispatch_builds_and_executes_host_deployment(self):
"""A manual dispatch must resolve first and invoke the automated host helper."""
text = WORKFLOW.read_text(encoding='utf-8')
self.assertIn('workflow_dispatch:', text)
inputs = text.split(' inputs:', 1)[1].split('\njobs:', 1)[0]
self.assertEqual(set(re.findall(r'^ ([a-z_]+):$', inputs, re.MULTILINE)), {'tag', 'puerto', 'puerto_api'})
self.assertRegex(inputs, r"puerto_api:\s+description:[^\n]+\s+required: true\s+default: '28090'")
self.assertNotIn('release:', text)
self.assertIn('tag:', text)
self.assertIn('puerto:', text)
self.assertIn('puerto_api:', text)
self.assertIn('inputs.puerto_api', text)
self.assertIn('--api-port "$REQUESTED_API_PORT"', text)
self.assertNotIn('NATIVE_API_PORT', text)
self.assertLess(text.index('resolve.py'), text.index('remote.py \\'))
self.assertIn('--host 10.0.10.41', text)
self.assertIn('secrets.NATIVE_SSH_KEY', text)
self.assertIn('secrets.NATIVE_KNOWN_HOSTS', text)
self.assertNotIn('sudo ', text)
def test_existing_docker_workflow_is_not_modified(self):
"""The independent deployment must not alter the Docker workflow or its installers."""
result = subprocess.run(['git', '-C', str(ROOT), 'diff', '--quiet', 'HEAD', '--',
'.gitea/workflows/deploy-dev.yml', '.gitea/deploy'], check=False)
self.assertEqual(result.returncode, 0)
if __name__ == '__main__':
unittest.main()
+102
View File
@@ -0,0 +1,102 @@
#!/usr/bin/env python3
"""Verify native unit state, API health and Angular routing after activation."""
import argparse
import json
from pathlib import Path
import subprocess
import sys
import time
import urllib.error
import urllib.request
import install
import activate
def request(url):
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
with opener.open(url, timeout=5) as response:
return response.status, response.read(1024 * 1024)
def check(record, command=subprocess.run, get=request, manager_env=None):
install.validate_record(record)
if record.get('status') not in ('started', 'local_healthy', 'healthy', 'verification_failed'):
raise ValueError('installation is not prepared')
port = record['public_port']
api = record.get('api_port')
expected = [f'isssteleon-native-{port}-{part}.service' for part in ('api', 'worker', 'web')]
if record.get('services') != expected or type(api) is not int or api == port or not 1024 <= api <= 65535:
raise ValueError('invalid installed service metadata')
for unit in expected:
result = command(['systemctl', '--user', 'is-active', '--quiet', unit], check=False, capture_output=True, env=manager_env)
if result.returncode:
raise ValueError('service is not active: ' + unit)
for url in (f'http://127.0.0.1:{api}/health', f'http://127.0.0.1:{port}/health'):
status, body = get(url)
health = json.loads(body)
if status != 200 or not isinstance(health, dict) or health.get('status') != 'ok':
raise ValueError('API health check failed: ' + url)
status, index = get(f'http://127.0.0.1:{port}/')
route_status, route = get(f'http://127.0.0.1:{port}/native-health-route')
if status != 200 or route_status != 200 or not index or index != route:
raise ValueError('Angular distribution or SPA fallback failed')
return {'services': expected, 'api_health': 'ok', 'proxy_health': 'ok', 'spa_fallback': 'ok'}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('instance', type=Path)
parser.add_argument('--wait-seconds', type=int, default=90)
parser.add_argument('--public-result', choices=('ok', 'failed'))
args = parser.parse_args()
if not 0 <= args.wait_seconds <= 300:
parser.error('wait-seconds must be between 0 and 300')
record = None
path = None
tracked = False
try:
path = args.instance.resolve() / 'installation.json'
if args.instance.is_symlink() or path.is_symlink():
raise ValueError('symlinked installation or metadata')
record = json.loads(path.read_text(encoding='utf-8'))
if Path(record.get('base', '')) != args.instance.resolve():
raise ValueError('installation path does not match record')
install.validate_record(record)
if record.get('status') not in ('started', 'local_healthy', 'healthy', 'verification_failed'):
raise ValueError('installation is not prepared')
tracked = True
if args.public_result == 'failed':
raise ValueError('external HTTP check failed from the Actions runner')
manager_env = activate.manager_environment(record['account'])
deadline = time.monotonic() + args.wait_seconds
while True:
try:
checks = check(record, manager_env=manager_env)
break
except (OSError, ValueError, urllib.error.URLError, json.JSONDecodeError) as exc:
if time.monotonic() >= deadline:
raise ValueError('health verification failed: ' + str(exc)) from exc
time.sleep(2)
if args.public_result == 'ok':
checks['public_http'] = 'ok'
record.update(status='healthy' if args.public_result == 'ok' else 'local_healthy',
phase='running' if args.public_result == 'ok' else 'awaiting_external_health',
health=checks, verified_at=int(time.time()))
install.atomic_record(path, record)
print(json.dumps(checks, indent=2, sort_keys=True))
return 0
except (OSError, ValueError, json.JSONDecodeError) as exc:
if tracked:
record.update(status='verification_failed', phase='verification_failed',
health={'result': 'failed', 'error': str(exc)}, verified_at=int(time.time()))
try:
install.atomic_record(path, record)
except OSError:
pass
print('Verification failed: ' + str(exc), file=sys.stderr)
return 1
if __name__ == '__main__':
sys.exit(main())
+3 -2
View File
@@ -1,7 +1,8 @@
# General DEV workflow integration
`.gitea/workflows/deploy-dev.yml` accepts only `puerto` on `dev`. It checks out
the dispatched SHA and recursive application gitlinks, then routes an unregistered
`.gitea/workflows/deploy-dev.yml` accepts `puerto` and `rama`. The workflow
branch supplies the installer; `rama` resolves independently to an application
commit and its recognized recursive gitlinks, then routes an unregistered
free port to installation and a registered installation to conservative update.
The same revision takes a verified no-op path. Existing storage is never reset as
a fallback. Pending migrations are rejected for updates; post-activation failures
+36 -54
View File
@@ -1,6 +1,6 @@
# DEV installation and conservative updates
The manual `deploy-dev` workflow accepts `puerto` on `dev`. An unregistered,
The manual `deploy-dev` workflow accepts `puerto` and the application branch `rama` (default `dev`). An unregistered,
available port installs a new instance. A registered port updates its existing
managed instance, retaining the original `data/`, project, port and connections.
Repeating the same outer revision verifies recursive gitlinks, recorded image
@@ -11,9 +11,10 @@ to resetting or recreating storage.
## Operator quick start
After the reviewed change reaches `dev`, open repository **Actions → deploy-dev →
Run workflow**, select **dev**, enter only **puerto**, then inspect the run's SHA
and final log. The same action installs a free port or updates its registered
After the reviewed change reaches `dev`, open **Actions → deploy-dev → Run workflow**.
Select `dev` under **Use workflow from** for the central installer, enter the public
`puerto` and application `rama` (for example `18083` and `staging`), then inspect
the workflow and application revisions and final log. The same action installs a free port or updates its registered
installation. Existing projects are discovered from their records; their names
do not have to contain the port.
@@ -31,7 +32,7 @@ outer commit with unchanged application pins still takes the checked update path
Updates do not execute pending migrations: they retain the existing migration
compatibility gate. New installations continue to run their initial migrations.
Successful records contain `status=installed`, `revision`, `gitlinks`, `images`
Successful records contain `status=installed`, `branch`, `workflow_ref`, `workflow_sha`, `revision`, `gitlinks`, `images`
and `result=installed|updated|unchanged`. Updates also retain operation, target,
backup and archive references. `unchanged` preserves previous recovery evidence
and records `verification=complete`; it does not claim a new recalculation.
@@ -50,65 +51,46 @@ for path in pathlib.Path('/srv/workingnarrative-dev').glob('*/installation.json'
if len(matches) != 1:
raise SystemExit('Expected exactly one registered installation; inspect the registry')
record = matches[0]
keys = ('project', 'port', 'status', 'phase', 'result', 'revision', 'gitlinks', 'images',
keys = ('project', 'port', 'status', 'phase', 'result', 'branch', 'workflow_ref', 'workflow_sha', 'revision', 'gitlinks', 'images',
'verification', 'recalculation', 'operation_id', 'target_revision', 'target_images',
'backup', 'archive', 'recovery')
print(json.dumps({key: record[key] for key in keys if key in record}, indent=2))
PY
```
### Dispatch when the UI does not offer dev
### Central workflow and application branch
Read-only API checks on 2026-11-10 confirmed Gitea **1.26.2**, repository default
branch **main**, and Actions enabled. Anonymous workflow metadata returned 401;
authenticated UI visibility and dispatch were not tested. Do not dispatch `main`
or the old resetting workflow to work around the UI. Keep the general workflow's
`refs/heads/dev` guard.
Gitea 1.26.2 loads the workflow from the selected **Use workflow from** branch,
as shown by its [dispatch implementation](https://github.com/go-gitea/gitea/blob/v1.26.2/services/actions/workflow.go).
Choose a trusted stable branch that contains this reviewed workflow and installer.
At the time of review, remote `main` does not contain `deploy-dev.yml`; use `dev`
after this change is integrated there, or another reviewed branch containing it.
A different or old workflow can omit these controls, so protect the stable branch
and restrict workflow dispatch to trusted operators.
An authorized operator can use the official
[workflow dispatch endpoint](https://docs.gitea.com/api/operations/actions-dispatch-workflow/)
with filename `deploy-dev.yml`, `ref=dev` and only the `puerto` input. Gitea's
[v1.26.2 implementation](https://github.com/go-gitea/gitea/blob/v1.26.2/services/actions/workflow.go)
resolves that branch's commit and reads the workflow from it. This supports using
the API independently of default-branch UI discovery; it is source-based evidence,
not a dispatch performed against this server.
`rama` is independent of the workflow ref. The central installer validates the
branch name, fetches its exact `refs/heads/...` from the official repository,
and freezes the resulting commit in a separate temporary checkout. It does not
execute the target branch's workflow or deployment scripts. The target branch
may lack the workflow or contain an older version. A missing branch fails; a tag,
SHA or arbitrary ref is not substituted. A branch move after fetch does not alter
the selected commit. Builds still execute code from the application branch;
choose trusted code and retain existing Actions authorization.
**This submits a real deployment. Use only after review/merge and explicit
authorization for the intended environment and port.** Set `PORT` and provide
`GITEA_TOKEN` through the operator's private environment, then run:
The installer verifies the workflow event and checkout, then uses the exact
recursive application gitlinks. Supported paths are ISSSTELEON, WebApp, WebApi,
models and indicadores_kit at their institutional origins; unknown paths and
origins are rejected. `branch` and `revision` describe the application, while
`workflow_ref` and `workflow_sha` describe the installer. Older records remain
eligible; a verified same-SHA no-op records the new selection without rebuilding.
```sh
python3 -B - "$PORT" <<'PY'
import json, os, sys, urllib.request
port = sys.argv[1]
if not port.isascii() or not port.isdigit() or not 1024 <= int(port) <= 65535:
raise SystemExit('Invalid public port')
request = urllib.request.Request(
'http://10.0.10.41:3000/api/v1/repos/ISSSTELEON/WorkingNarrative/actions/workflows/deploy-dev.yml/dispatches',
data=json.dumps({'ref': 'dev', 'inputs': {'puerto': port}}).encode(),
headers={'Authorization': 'token ' + os.environ['GITEA_TOKEN'], 'Content-Type': 'application/json'},
method='POST')
with urllib.request.urlopen(request, timeout=30) as response:
print('Dispatch HTTP status:', response.status)
PY
```
Use an account/token with the repository's required Actions write access. An HTTP
success only confirms dispatch acceptance: open the resulting run in Actions,
verify `ref=dev`, the captured SHA and the intended port, then read its final
result and installation record. A 401/403 requires access correction; a 404 may
mean the workflow/ref is unavailable. Do not remove the branch guard or retry
against another branch. The Action checks out its captured SHA, verifies HEAD,
and initializes only recursive `ISSSTELEON` gitlinks; unrelated `dev-data` is not
required to deploy.
Local validation, review scope and a proposed disposable-environment trial are in
[INTEGRATION.md](INTEGRATION.md). Do not use existing installations for fault injection.
The checkout follows the dispatched WorkingNarrative commit and every recursive
gitlink. Source export rejects mismatching submodule checkouts. Builds include
WebApp, WebApi, Core, Persistance, Extraction, indicadores_kit, models and other
application trees at those pins. No `submodule update --remote` is used.
An authorized operator can also use the [workflow dispatch API](https://docs.gitea.com/api/operations/actions-dispatch-workflow/)
with `ref` naming the stable workflow branch and both inputs, for example
`{"ref":"dev","inputs":{"puerto":"18083","rama":"staging"}}`.
This submits a real deployment. Review the selected workflow, target branch and
environment first. Local validation did not exercise the Gitea UI or runner.
See [INTEGRATION.md](INTEGRATION.md) for the controlled trial; do not use existing
installations for fault injection.
## Four distinct operations
+6 -2
View File
@@ -354,8 +354,10 @@ def update(api, record, helper, root, base, *, verify_restore=False):
for sha in record['gitlinks'].values())):
raise RuntimeError('installation status or Git provenance is invalid; manual inspection required')
project, port = record['project'], record['port']
metadata = getattr(api, 'request_metadata', lambda root: {})(root)
revision = api.git(root, 'rev-parse', 'HEAD').strip()
expected = api.git(root, 'ls-tree', 'HEAD', 'ISSSTELEON').split()[2]
getattr(api, 'verify_target_revision', lambda revision: None)(revision)
expected = api.git(root, 'ls-tree', revision, 'ISSSTELEON').split()[2]
old_ids = api.verify_existing_containers(record, base, helper)
phase = 'preparing'
current = None
@@ -387,7 +389,7 @@ def update(api, record, helper, root, base, *, verify_restore=False):
raise RuntimeError('installation containers changed during verification')
operation_step = 'record verified no-op'
api.host_action(helper, 'save', project, json.dumps(dict(
record, result='unchanged', verification='complete')))
record, **metadata, result='unchanged', verification='complete')))
print(f'Unchanged {project} on port {port} at {revision}; verification complete')
return
manifest = {}
@@ -418,6 +420,7 @@ def update(api, record, helper, root, base, *, verify_restore=False):
operation = uuid.uuid4().hex
current = dict(record, status='updating', operation_id=operation, phase='quiescing',
target_revision=revision, target_images=images, target_gitlinks=manifest,
target_branch=metadata.get('branch'),
migrations='none-pending', recalculation='not-started')
def save():
@@ -485,6 +488,7 @@ def update(api, record, helper, root, base, *, verify_restore=False):
{'data': '/data', 'contract': contract, 'before': backup['state'], 'derived': True}, data)
current.update(status='installed', revision=revision, gitlinks=manifest, images=images,
phase='complete', result='updated', recalculation='complete', verification='complete')
current.update(metadata)
current.pop('error', None)
save()
print(f'Updated {project} on port {port} at {revision}')
+136 -4
View File
@@ -56,6 +56,127 @@ def git(repo, *args, binary=False):
return run(['git', '-C', repo, *args], binary=binary)
def dispatch_metadata(root=ROOT):
"""Validate the event identity and its immutable checked-out commit."""
ref = os.environ.get('DISPATCH_REF', '')
name = os.environ.get('DISPATCH_REF_NAME', '')
sha = os.environ.get('DISPATCH_SHA', '')
if (os.environ.get('DISPATCH_REPOSITORY') != 'ISSSTELEON/WorkingNarrative'
or os.environ.get('DISPATCH_SERVER', '').rstrip('/') != 'http://10.0.10.41:3000'
or os.environ.get('DISPATCH_REF_TYPE') != 'branch'
or not name or ref != 'refs/heads/' + name
or not re.fullmatch(r'[0-9a-f]{40}', sha)):
raise ValueError('invalid deployment event identity or branch reference')
run(['git', 'check-ref-format', ref])
if git(root, 'rev-parse', 'HEAD').strip() != sha:
raise RuntimeError('checkout does not match the dispatched SHA')
return {'workflow_ref': ref, 'workflow_sha': sha}
_target_request = None
def validate_branch(branch):
if (not branch or branch.startswith(('refs/', '-')) or branch == '@'
or re.fullmatch(r'[0-9a-fA-F]{40}', branch)):
raise ValueError('target must be a branch name')
run(['git', 'check-ref-format', 'refs/heads/' + branch])
return branch
def verify_target_revision(revision):
if _target_request is not None and revision != _target_request[1]:
raise RuntimeError('application checkout changed during deployment preparation')
def request_metadata(root=ROOT):
if _target_request is None:
return {}
branch, sha = _target_request
metadata = dispatch_metadata(ROOT)
if git(root, 'rev-parse', 'HEAD').strip() != sha:
raise RuntimeError('application checkout does not match resolved branch commit')
return dict(metadata, branch=branch)
def deploy_branch(port, branch, workflow_root=ROOT, base=BASE):
"""Fetch one official branch and deploy its fixed commit using this installer."""
global _target_request
validate_port(port)
validate_branch(branch)
dispatch_metadata(workflow_root)
official = 'http://10.0.10.41:3000/ISSSTELEON/WorkingNarrative.git'
if git(workflow_root, 'remote', 'get-url', 'origin').strip() not in (official, official.removesuffix('.git')):
raise RuntimeError('workflow checkout origin is not the official repository')
target_ref = 'refs/deploy/' + uuid.uuid4().hex
try:
git(workflow_root, 'fetch', '--no-tags', 'origin',
'+refs/heads/' + branch + ':' + target_ref)
sha = git(workflow_root, 'rev-parse', '--verify', target_ref + '^{commit}').strip()
if not re.fullmatch(r'[0-9a-f]{40}', sha):
raise RuntimeError('remote branch did not resolve to a full commit SHA')
with tempfile.TemporaryDirectory(prefix='isssteleon-source-') as tmp:
source = Path(tmp)
run(['git', 'init', '--quiet', source])
git(source, 'fetch', '--no-tags', str(workflow_root), target_ref)
git(source, 'checkout', '--quiet', '--detach', sha)
_target_request = (branch, sha)
request_metadata(source)
print('Deployment source:', json.dumps({'branch': branch, 'revision': sha}, sort_keys=True))
checkout_pinned(source)
install_auto(port, source, base)
finally:
_target_request = None
git(workflow_root, 'update-ref', '-d', target_ref)
SUBMODULE_ORIGINS = {
'ISSSTELEON': 'ISSSTELEON',
'ISSSTELEON/WebApp': 'WebApp',
'ISSSTELEON/WebApi': 'WebApi',
'ISSSTELEON/models': 'models',
'ISSSTELEON/indicadores_kit': 'indicadores_kit',
}
def checkout_pinned(root=ROOT):
"""Initialize only recognized institutional gitlinks at the captured revision."""
request_metadata(root)
def visit(repo, prefix, selected=None):
entries = git(repo, 'ls-tree', '-rz', '--full-tree', 'HEAD', binary=True)
for entry in entries.split(b'\0'):
if not entry:
continue
meta, raw_path = entry.split(b'\t', 1)
mode, _, sha = meta.decode().split()
if mode != '160000':
continue
path = os.fsdecode(raw_path)
if selected is not None and path != selected:
continue
full = f'{prefix}/{path}' if prefix else path
if full not in SUBMODULE_ORIGINS or path in ('', '.', '..') or '..' in Path(path).parts:
raise RuntimeError(f'unsupported application gitlink: {full}')
config = git(repo, 'config', '-f', '.gitmodules', '--get-regexp', r'^submodule\..*\.path$')
matches = [line.split(None, 1)[0][len('submodule.'):-len('.path')]
for line in config.splitlines() if len(line.split(None, 1)) == 2
and line.split(None, 1)[1] == path]
if len(matches) != 1 or not re.fullmatch(r'[A-Za-z0-9_-]+', matches[0]):
raise RuntimeError(f'invalid submodule mapping: {full}')
name = matches[0]
origin = 'ssh://git@10.0.10.41:2222/ISSSTELEON/' + SUBMODULE_ORIGINS[full] + '.git'
if git(repo, 'config', '-f', '.gitmodules', '--get', f'submodule.{name}.url').strip() != origin:
raise RuntimeError(f'untrusted submodule origin: {full}')
git(repo, '-c', f'submodule.{name}.url={origin}', 'submodule', 'update', '--init', '--checkout', '--', path)
child = repo / path
if git(child, 'rev-parse', 'HEAD').strip() != sha:
raise RuntimeError(f'gitlink checkout mismatch: {full}')
visit(child, full)
visit(root, '', 'ISSSTELEON')
print('Pinned application gitlinks:', json.dumps(pinned_manifest(root / 'ISSSTELEON',
git(root, 'ls-tree', 'HEAD', 'ISSSTELEON').split()[2]), sort_keys=True))
def committed_trees(repo, revision, prefix=''):
"""Walk exact recursive gitlinks and reject mismatching checked-out commits."""
actual = git(repo, 'rev-parse', 'HEAD').strip()
@@ -220,7 +341,9 @@ def verify_services(cmd, port, timeout=300):
def install(instance, port_text, operation, root=ROOT, base=BASE, helper=None):
project, port = validate(instance, port_text, operation)
revision = git(root, 'rev-parse', 'HEAD').strip()
expected = git(root, 'ls-tree', 'HEAD', 'ISSSTELEON').split()[2]
metadata = request_metadata(root)
verify_target_revision(revision)
expected = git(root, 'ls-tree', revision, 'ISSSTELEON').split()[2]
owns_helper = helper is None
if owns_helper:
helper = start_helper(base)
@@ -229,7 +352,8 @@ def install(instance, port_text, operation, root=ROOT, base=BASE, helper=None):
with tempfile.TemporaryDirectory(prefix='isssteleon-deploy-') as tmp:
directory = Path(tmp)
source, deploy, data = directory / 'codigo', directory / 'deploy', base / project / 'data'
record = {'project': project, 'port': port, 'revision': revision, 'status': 'preparing'}
record = {'project': project, 'port': port, 'revision': revision, 'status': 'preparing',
**metadata}
def save():
host_action(helper, 'save', project, json.dumps(record))
cmd = None
@@ -390,11 +514,19 @@ def install_auto(port, root=ROOT, base=BASE, *, check_record=None):
def main():
parser = argparse.ArgumentParser()
parser.add_argument('command', choices=['validate', 'install', 'validate-auto', 'install-auto'])
parser.add_argument('command', choices=['validate', 'install', 'validate-auto', 'install-auto', 'validate-dispatch', 'deploy-branch'])
parser.add_argument('arguments', nargs='*')
args = parser.parse_args()
try:
if args.command in ('validate-auto', 'install-auto'):
if args.command == 'validate-dispatch':
if args.arguments:
raise ValueError('validate-dispatch takes no arguments')
print('Workflow event:', json.dumps(dispatch_metadata(), sort_keys=True))
elif args.command == 'deploy-branch':
if len(args.arguments) != 2:
raise ValueError('deploy-branch requires port and branch')
deploy_branch(*args.arguments)
elif args.command in ('validate-auto', 'install-auto'):
if len(args.arguments) != 1:
raise ValueError('automatic commands require exactly one port')
port_text = args.arguments[0]
+56
View File
@@ -0,0 +1,56 @@
#!/usr/bin/env python3
"""Report sanitized checkout URL comparisons without contacting a remote."""
import json
import os
import subprocess
from urllib.parse import urlsplit
OFFICIAL = 'http://10.0.10.41:3000/ISSSTELEON/WorkingNarrative.git'
SSH = 'ssh://git@10.0.10.41:2222/ISSSTELEON/WorkingNarrative.git'
SERVER = 'http://10.0.10.41:3000'
REPOSITORY = 'ISSSTELEON/WorkingNarrative'
def describe(value):
"""Return fixed labels and comparisons, never any part of the input."""
try:
parsed = urlsplit(value)
scheme = parsed.scheme if parsed.scheme in ('http', 'https', 'ssh') else 'other'
return {'exact_http': value == OFFICIAL,
'exact_http_without_git': value == OFFICIAL.removesuffix('.git'), 'exact_ssh': value == SSH,
'scheme': scheme, 'official_host': parsed.hostname == '10.0.10.41',
'official_http_port': parsed.port == 3000,
'official_ssh_port': parsed.port == 2222,
'repository_path': parsed.path == '/ISSSTELEON/WorkingNarrative.git',
'repository_path_without_git': parsed.path == '/ISSSTELEON/WorkingNarrative',
'userinfo_present': parsed.username is not None or parsed.password is not None,
'query_or_fragment': bool(parsed.query or parsed.fragment)}
except ValueError:
return {'invalid_url': True}
def git_values(*args):
result = subprocess.run(['git', *args], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
text=True, encoding='utf-8', errors='replace', check=False)
return result.stdout.splitlines() if result.returncode == 0 else []
def main():
literal = git_values('config', '--get-all', 'remote.origin.url')
effective = git_values('remote', 'get-url', '--all', 'origin')
github = os.environ.get('GITHUB_SERVER_URL', '')
gitea = os.environ.get('GITEA_SERVER_URL', '')
result = {'literal_origin': [describe(url) for url in literal],
'effective_origin': [describe(url) for url in effective],
'origin_rewritten': literal != effective,
'github_server_is_official': github.rstrip('/') == SERVER,
'gitea_server_is_official': gitea.rstrip('/') == SERVER,
'server_variables_equal': bool(github and gitea) and github.rstrip('/') == gitea.rstrip('/'),
'event_server_is_official': os.environ.get('DISPATCH_SERVER', '').rstrip('/') == SERVER,
'event_repository_is_official': os.environ.get('DISPATCH_REPOSITORY') == REPOSITORY}
print('Checkout origin diagnostic:', json.dumps(result, sort_keys=True))
if __name__ == '__main__':
main()
+24
View File
@@ -88,6 +88,28 @@ class AutomaticDeploymentTests(unittest.TestCase):
self.assertEqual(before, {str(p.relative_to(self.root)): p.read_bytes() for p in self.root.rglob('*')
if p.is_file() and p.name != 'installation.json'})
def test_selected_branch_updates_legacy_record(self):
"""Fail if updating an older record loses the selected branch or retained data."""
before = data_guard.storage_state(self.root / 'data', self.contract)
with patch.object(dev, 'request_metadata', return_value={'branch': 'staging',
'workflow_ref': 'refs/heads/dev', 'workflow_sha': 'f' * 40}):
self.execute()
record = host.read_record(self.root)
self.assertEqual(record['branch'], 'staging')
self.assertEqual(record['revision'], self.runtime.revision)
self.assertEqual((record['workflow_ref'], record['workflow_sha']), ('refs/heads/dev', 'f' * 40))
data_guard.verify_state(self.root / 'data', self.contract, before, derived=True)
def test_different_branch_same_commit_records_verified_noop(self):
"""Fail if selecting another branch at the same SHA rebuilds or leaves stale provenance."""
self.select_same_revision()
with patch.object(dev, 'request_metadata', return_value={'branch': 'feature/demo',
'workflow_ref': 'refs/heads/feature/demo', 'workflow_sha': self.runtime.revision}):
self.execute()
record = host.read_record(self.root)
self.assertEqual((record['result'], record['branch']), ('unchanged', 'feature/demo'))
self.assertFalse(any('build' in args or 'stop' in args for args in self.runtime.calls))
def test_same_revision_rejects_mismatching_gitlinks(self):
"""Fail if the outer SHA alone can hide inconsistent installed recursive gitlinks."""
self.select_same_revision()
@@ -236,6 +258,7 @@ class AutomaticDeploymentTests(unittest.TestCase):
patch.object(dev, 'git', side_effect=lambda repo, *args: revision if args[0] == 'rev-parse' else
'160000 commit ' + pin + '\tISSSTELEON'), \
patch.object(dev, 'export_tree', side_effect=export), \
patch.object(dev, 'request_metadata', return_value={'branch': 'main', 'workflow_ref': 'refs/heads/dev', 'workflow_sha': 'f' * 40}), \
patch.object(dev, 'copy_to_host', side_effect=copy_to_host), \
patch.object(dev, 'reserve', side_effect=lambda helper, project, port: host.reserve(base, project, port)), \
patch.object(conservative, 'guard'), patch.object(conservative, 'verify_api'), \
@@ -247,6 +270,7 @@ class AutomaticDeploymentTests(unittest.TestCase):
self.assertEqual((record['status'], record['result'], record['phase'], record['revision']),
('installed', 'installed', 'complete', revision))
self.assertEqual(record['gitlinks'], {'ISSSTELEON': pin})
self.assertEqual((record['branch'], record['workflow_sha']), ('main', 'f' * 40))
self.assertEqual(record['images'], [c[c.index('-t') + 1] for c in calls if c[:2] == ['docker', 'build']])
self.assertEqual(finish.call_count, 1)
self.assertEqual(verify.call_count, 1)
+9 -11
View File
@@ -10,20 +10,18 @@ import unittest
class GeneralWorkflowTests(unittest.TestCase):
def test_dispatch_uses_only_port_and_exact_dev_checkout(self):
"""Fail if deployment accepts unpinned source or bypasses the dev-only dispatch guard."""
def test_dispatch_separates_workflow_and_target_branch(self):
"""Fail if the central workflow omits the independent target branch or event validation."""
text = (Path(__file__).resolve().parents[1] / 'workflows' / 'deploy-dev.yml').read_text()
inputs = text.split(' inputs:\n', 1)[1].split('\njobs:', 1)[0]
self.assertEqual(re.findall(r'^ (\w+):', inputs, re.M), ['puerto'])
for boundary in ('test "$DISPATCH_REF" = refs/heads/dev', 'ref: ${{ github.sha }}',
'test "$(git rev-parse HEAD)" = "$DISPATCH_SHA"',
'dev.py validate-auto "$PORT"',
'git submodule update --init --recursive ISSSTELEON',
'dev.py install-auto "$PORT"'):
self.assertEqual(re.findall(r'^ (\w+):', inputs, re.M), ['puerto', 'rama'])
for boundary in ('${{ gitea.ref }}', '${{ gitea.ref_name }}', '${{ gitea.ref_type }}',
'ref: ${{ gitea.sha }}', 'dev.py validate-dispatch',
'dev.py validate-auto "$PORT"', 'dev.py deploy-branch "$PORT" "$TARGET_BRANCH"',
'default: dev'):
self.assertIn(boundary, text)
self.assertLess(text.index('refs/heads/dev'), text.index('actions/checkout'))
self.assertLess(text.index('git rev-parse HEAD'), text.index('validate-auto'))
self.assertLess(text.index('validate-auto'), text.index('git submodule update'))
self.assertLess(text.index('validate-dispatch'), text.index('deploy-branch'))
self.assertNotIn('refs/heads/dev', text)
self.assertNotIn('--remote', text)
def test_general_path_has_no_laboratory_identity_or_reset_fallback(self):
+201
View File
@@ -0,0 +1,201 @@
"""Validate branch events with synthetic contexts and no deployment or network."""
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
from unittest.mock import patch
import dev
class DispatchTests(unittest.TestCase):
def event(self, name='dev'):
"""Create a synthetic institutional workflow event for a full commit."""
return {'DISPATCH_REF': 'refs/heads/' + name, 'DISPATCH_REF_NAME': name,
'DISPATCH_REF_TYPE': 'branch', 'DISPATCH_SHA': 'a' * 40,
'DISPATCH_REPOSITORY': 'ISSSTELEON/WorkingNarrative',
'DISPATCH_SERVER': 'http://10.0.10.41:3000'}
def test_branch_names_and_immutable_sha(self):
"""Fail if valid selected branches do not retain the event SHA and full name."""
for name in ('dev', 'main', 'staging', 'feature/dashboard-unificado'):
with self.subTest(name=name), patch.dict(os.environ, self.event(name)), \
patch.object(dev, 'git', return_value='a' * 40):
self.assertEqual(dev.dispatch_metadata(Path('.'))['workflow_ref'], 'refs/heads/' + name)
self.assertEqual(dev.dispatch_metadata(Path('.'))['workflow_sha'], 'a' * 40)
def test_invalid_context_and_changed_checkout(self):
"""Fail if tags, invalid refs, another repository or mismatched SHAs can deploy."""
changes = ({'DISPATCH_REF_TYPE': 'tag'}, {'DISPATCH_REF': 'refs/tags/dev'},
{'DISPATCH_REPOSITORY': 'other/repo'}, {'DISPATCH_SERVER': 'http://example.com'},
{'DISPATCH_SHA': 'abc'}, {'DISPATCH_REF_NAME': 'other'})
for change in changes:
with self.subTest(change=change), patch.dict(os.environ, self.event() | change), \
patch.object(dev, 'git', return_value='a' * 40):
with self.assertRaises(ValueError):
dev.dispatch_metadata(Path('.'))
with patch.dict(os.environ, self.event('bad..name')), patch.object(dev, 'git', return_value='a' * 40):
with self.assertRaises(subprocess.CalledProcessError):
dev.dispatch_metadata(Path('.'))
with patch.dict(os.environ, self.event()), patch.object(dev, 'git', return_value='b' * 40):
with self.assertRaises(RuntimeError):
dev.dispatch_metadata(Path('.'))
def test_submodule_origin_checked_before_fetch(self):
"""Fail if a selected commit can fetch its application from an external origin."""
calls = []
def fake_git(repo, *args, **kwargs):
calls.append(args)
if args[0] == 'ls-tree':
return b'160000 commit ' + b'b' * 40 + b'\tISSSTELEON\0'
if '--get-regexp' in args:
return 'submodule.ISSSTELEON.path ISSSTELEON\n'
if '--get' in args:
return 'https://example.com/other.git\n'
raise AssertionError(args)
with patch.object(dev, 'request_metadata'), patch.object(dev, 'git', side_effect=fake_git):
with self.assertRaisesRegex(RuntimeError, 'untrusted submodule origin'):
dev.checkout_pinned(Path('.'))
self.assertFalse(any('update' in args for args in calls))
def test_target_branch_validation(self):
"""Fail if refs, hashes or invalid names can replace a branch selection."""
for branch in ('dev', 'staging', 'feature/dashboard-unificado'):
self.assertEqual(dev.validate_branch(branch), branch)
for branch in ('', 'refs/tags/release', '-bad', '@', 'a' * 40, 'bad..name'):
with self.subTest(branch=branch):
with self.assertRaises((ValueError, subprocess.CalledProcessError)):
dev.validate_branch(branch)
def test_effective_origin_accepts_only_exact_institutional_http_urls(self):
"""Reject deceptive or rewritten origins before fetch while accepting checkout's HTTP URL."""
official = 'http://10.0.10.41:3000/ISSSTELEON/WorkingNarrative'
for url, accepted in ((official, True), (official + '.git', True),
(official + '.git.evil', False),
(official.replace('10.0.10.41', '10.0.10.41.evil'), False),
(official.replace('http://', 'http://user:secret@'), False),
(official.replace('http://', 'https://'), False),
('http://example.com/ISSSTELEON/WorkingNarrative', False)):
with self.subTest(url=url):
def fake_git(repo, *args, **kwargs):
if args[:2] == ('remote', 'get-url'):
return url
if args[0] == 'fetch':
raise subprocess.CalledProcessError(1, args)
return ''
with patch.object(dev, 'dispatch_metadata'), patch.object(dev, 'git', side_effect=fake_git) as git, \
patch.object(dev, 'install_auto') as install:
with self.assertRaises(subprocess.CalledProcessError if accepted else RuntimeError):
dev.deploy_branch('18083', 'staging', Path('/central'))
self.assertEqual(any(call.args[1:2] == ('fetch',) for call in git.call_args_list), accepted)
install.assert_not_called()
def test_external_git_rewrite_is_rejected_before_fetch(self):
"""Fail if an official literal origin rewritten to another host reaches fetch."""
with tempfile.TemporaryDirectory() as tmp:
subprocess.run(['git', 'init', '-q', tmp], check=True)
subprocess.run(['git', '-C', tmp, 'remote', 'add', 'origin',
'http://10.0.10.41:3000/ISSSTELEON/WorkingNarrative'], check=True)
env = {'GIT_CONFIG_COUNT': '1', 'GIT_CONFIG_KEY_0': 'url.http://example.com/.insteadOf',
'GIT_CONFIG_VALUE_0': 'http://10.0.10.41:3000/'}
with patch.dict(os.environ, env), patch.object(dev, 'dispatch_metadata'), \
patch.object(dev, 'install_auto') as install:
with self.assertRaisesRegex(RuntimeError, 'origin is not the official repository'):
dev.deploy_branch('18083', 'staging', Path(tmp))
install.assert_not_called()
def test_central_installer_uses_resolved_application_tree(self):
"""Fail if a target without a workflow or with an old installer controls execution."""
for branch in ('dev', 'staging', 'feature/demo'):
with self.subTest(branch=branch):
calls = []
workflow_root = Path('/central')
target_sha = 'b' * 40
def fake_git(repo, *args, **kwargs):
calls.append((repo, args))
if args[:2] == ('remote', 'get-url'):
return 'http://10.0.10.41:3000/ISSSTELEON/WorkingNarrative.git'
if args[:2] == ('rev-parse', '--verify'):
return target_sha
if args[:2] == ('rev-parse', 'HEAD'):
return target_sha
return ''
observed = []
def install(port, source, base):
observed.append((port, source, dev.request_metadata(source)))
self.assertNotEqual(source, workflow_root)
with patch.object(dev, 'dispatch_metadata', return_value={
'workflow_ref': 'refs/heads/dev', 'workflow_sha': 'a' * 40}), \
patch.object(dev, 'git', side_effect=fake_git), \
patch.object(dev, 'run'), patch.object(dev, 'checkout_pinned') as checkout, \
patch.object(dev, 'install_auto', side_effect=install):
dev.deploy_branch('18083', branch, workflow_root, Path('/base'))
self.assertEqual(observed[0][2], {'branch': branch, 'workflow_ref': 'refs/heads/dev',
'workflow_sha': 'a' * 40})
self.assertTrue(any(args[0] == 'fetch' and '+refs/heads/' + branch + ':' in args[-1]
for _, args in calls))
checkout.assert_called_once_with(observed[0][1])
def test_real_git_snapshot_is_separate_from_workflow(self):
"""Fail if a moving branch or target deployment script replaces the central installer."""
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
remote, central = root / 'remote', root / 'central'
remote.mkdir()
central.mkdir()
def command(repo, *args, input=None):
return subprocess.run(['git', '-C', str(repo), *args], input=input,
text=True, capture_output=True, check=True).stdout.strip()
command(remote, 'init', '-q')
command(remote, 'config', 'user.email', 'fixture@example.invalid')
command(remote, 'config', 'user.name', 'Fixture')
(remote / '.gitea/deploy').mkdir(parents=True)
(remote / '.gitea/deploy/dev.py').write_text('untrusted target installer')
command(remote, 'add', '.gitea/deploy/dev.py')
command(remote, 'commit', '-qm', 'target with old installer and no workflow')
original = command(remote, 'rev-parse', 'HEAD')
command(remote, 'branch', 'staging')
(remote / '.gitea/deploy/dev.py').write_text('later branch tip')
command(remote, 'commit', '-qam', 'later commit')
newer = command(remote, 'rev-parse', 'HEAD')
command(central, 'init', '-q')
command(central, 'remote', 'add', 'origin', 'http://10.0.10.41:3000/ISSSTELEON/WorkingNarrative.git')
actual_git = dev.git
def routed_git(repo, *args, **kwargs):
if repo == central and args[:3] == ('fetch', '--no-tags', 'origin'):
result = actual_git(repo, 'fetch', '--no-tags', str(remote), *args[3:], **kwargs)
command(remote, 'update-ref', 'refs/heads/staging', newer)
return result
return actual_git(repo, *args, **kwargs)
def inspect(port, source, base):
self.assertEqual(command(source, 'rev-parse', 'HEAD'), original)
self.assertEqual((source / '.gitea/deploy/dev.py').read_text(), 'untrusted target installer')
self.assertFalse((source / '.gitea/workflows/deploy-dev.yml').exists())
self.assertEqual(dev.request_metadata(source)['branch'], 'staging')
with patch.object(dev, 'dispatch_metadata', return_value={
'workflow_ref': 'refs/heads/dev', 'workflow_sha': 'a' * 40}), \
patch.object(dev, 'git', side_effect=routed_git), \
patch.object(dev, 'checkout_pinned'), patch.object(dev, 'install_auto', side_effect=inspect) as install:
dev.deploy_branch('18083', 'staging', central, root / 'base')
install.assert_called_once()
self.assertEqual(command(remote, 'rev-parse', 'refs/heads/staging'), newer)
def test_nonexistent_branch_does_not_start_deployment(self):
"""Fail if an absent remote branch falls back to another commit or starts deployment."""
def fake_git(repo, *args, **kwargs):
if args[:2] == ('remote', 'get-url'):
return 'http://10.0.10.41:3000/ISSSTELEON/WorkingNarrative.git'
if args[0] == 'fetch':
raise subprocess.CalledProcessError(1, args)
return ''
with patch.object(dev, 'dispatch_metadata'), patch.object(dev, 'git', side_effect=fake_git), \
patch.object(dev, 'install_auto') as install:
with self.assertRaises(subprocess.CalledProcessError):
dev.deploy_branch('18083', 'missing', Path('/central'))
install.assert_not_called()
if __name__ == '__main__':
unittest.main()
+50
View File
@@ -0,0 +1,50 @@
"""Exercise sanitized origin diagnostics using temporary Git repositories."""
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
import origin_diagnostic as diagnostic
class OriginDiagnosticTests(unittest.TestCase):
def test_url_classification_never_returns_input(self):
"""Fail if credentials or deceptive URLs appear in the diagnostic output."""
for url in ('http://secret:password@10.0.10.41:3000/ISSSTELEON/WorkingNarrative.git',
'http://10.0.10.41.evil:3000/ISSSTELEON/WorkingNarrative.git',
'http://10.0.10.41:3000/ISSSTELEON/WorkingNarrative.git.evil'):
with self.subTest(url=url):
result = diagnostic.describe(url)
self.assertFalse(result['exact_http'])
self.assertNotIn(url, json.dumps(result))
self.assertNotIn('password', json.dumps(result))
self.assertTrue(diagnostic.describe(diagnostic.OFFICIAL)['exact_http'])
self.assertTrue(diagnostic.describe(diagnostic.SSH)['exact_ssh'])
def test_real_git_rewrite_is_detected_without_disclosing_credentials(self):
"""Fail if Git URL rewriting is missed or a configured credential is logged."""
with tempfile.TemporaryDirectory() as tmp:
subprocess.run(['git', 'init', '-q', tmp], check=True)
subprocess.run(['git', '-C', tmp, 'remote', 'add', 'origin', diagnostic.SSH], check=True)
env = os.environ.copy()
env.update({'GIT_CONFIG_COUNT': '1',
'GIT_CONFIG_KEY_0': 'url.http://secret:password@10.0.10.41:3000/ISSSTELEON/.insteadOf',
'GIT_CONFIG_VALUE_0': 'ssh://git@10.0.10.41:2222/ISSSTELEON/',
'DISPATCH_SERVER': diagnostic.SERVER, 'DISPATCH_REPOSITORY': diagnostic.REPOSITORY})
result = subprocess.run([sys.executable, '-B', str(Path(diagnostic.__file__).resolve())],
cwd=tmp, env=env, text=True, capture_output=True, check=True)
self.assertNotIn('secret', result.stdout + result.stderr)
self.assertNotIn('password', result.stdout + result.stderr)
data = json.loads(result.stdout.split(': ', 1)[1])
self.assertTrue(data['literal_origin'][0]['exact_ssh'])
self.assertTrue(data['effective_origin'][0]['userinfo_present'])
self.assertTrue(data['origin_rewritten'])
self.assertTrue(data['event_repository_is_official'])
if __name__ == '__main__':
unittest.main()
+18 -10
View File
@@ -7,29 +7,37 @@ on:
description: Public WebApp port; create a new instance or conservatively update its existing data
required: true
type: string
rama:
description: WorkingNarrative branch to deploy
required: true
default: dev
type: string
jobs:
deploy:
runs-on: ubuntu-latest
env:
PORT: ${{ inputs.puerto }}
DISPATCH_REF: ${{ github.ref }}
DISPATCH_SHA: ${{ github.sha }}
TARGET_BRANCH: ${{ inputs.rama }}
DISPATCH_REF: ${{ gitea.ref }}
DISPATCH_REF_NAME: ${{ gitea.ref_name }}
DISPATCH_REF_TYPE: ${{ gitea.ref_type }}
DISPATCH_SHA: ${{ gitea.sha }}
DISPATCH_REPOSITORY: ${{ gitea.repository }}
DISPATCH_SERVER: ${{ gitea.server_url }}
GIT_CONFIG_COUNT: 1
GIT_CONFIG_KEY_0: url.${{ github.server_url }}/ISSSTELEON/.insteadOf
GIT_CONFIG_VALUE_0: ssh://git@10.0.10.41:2222/ISSSTELEON/
steps:
- name: Require dev branch
run: test "$DISPATCH_REF" = refs/heads/dev
- uses: actions/checkout@v4
with:
fetch-depth: 0
ref: ${{ github.sha }}
ref: ${{ gitea.sha }}
- name: Verify dispatched revision
run: test "$(git rev-parse HEAD)" = "$DISPATCH_SHA"
run: python3 -B .gitea/deploy/dev.py validate-dispatch
- name: Diagnose checkout origin
run: python3 -B .gitea/deploy/origin_diagnostic.py
- name: Validate request
run: python3 -B .gitea/deploy/dev.py validate-auto "$PORT"
- name: Checkout pinned submodules
run: git submodule update --init --recursive ISSSTELEON
- name: Install or conservatively update instance
run: python3 -B .gitea/deploy/dev.py install-auto "$PORT"
- name: Resolve branch and install or conservatively update instance
run: python3 -B .gitea/deploy/dev.py deploy-branch "$PORT" "$TARGET_BRANCH"
@@ -0,0 +1,77 @@
name: deploy-terminal-release
on:
workflow_dispatch:
inputs:
tag:
description: Published release tag
required: true
type: string
puerto:
description: Public WebApp port
required: true
default: '18090'
type: string
puerto_api:
description: Internal loopback WebApi port
required: true
default: '28090'
type: string
jobs:
resolve:
runs-on: ubuntu-latest
env:
RELEASE_OUTPUT: release-output/release-source.tar.gz
REQUESTED_TAG: ${{ inputs.tag }}
REQUESTED_PORT: ${{ inputs.puerto }}
REQUESTED_API_PORT: ${{ inputs.puerto_api }}
RELEASE_TOKEN: ${{ gitea.token }}
GIT_CONFIG_COUNT: 1
GIT_CONFIG_KEY_0: url.${{ gitea.server_url }}/ISSSTELEON/.insteadOf
GIT_CONFIG_VALUE_0: ssh://git@10.0.10.41:2222/ISSSTELEON/
DISPATCH_REF: ${{ gitea.ref }}
DISPATCH_REF_NAME: ${{ gitea.ref_name }}
DISPATCH_REF_TYPE: ${{ gitea.ref_type }}
DISPATCH_SHA: ${{ gitea.sha }}
DISPATCH_REPOSITORY: ${{ gitea.repository }}
DISPATCH_SERVER: ${{ gitea.server_url }}
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
ref: ${{ gitea.sha }}
- name: Prepare release bundle
run: |
mkdir release-output
python3 -B .gitea/deploy-terminal/resolve.py
cp .gitea/deploy-terminal/{install.py,activate.py,verify.py,remote.py,bundle.py,source.py,README.md} release-output/
- name: Install, activate and verify native services
env:
NATIVE_ACCOUNT: ${{ vars.NATIVE_ACCOUNT }}
NATIVE_SSH_PORT: ${{ vars.NATIVE_SSH_PORT }}
NATIVE_HOSTNAME: ${{ vars.NATIVE_HOSTNAME }}
NATIVE_PARENT: ${{ vars.NATIVE_PARENT }}
NATIVE_SSH_KEY: ${{ secrets.NATIVE_SSH_KEY }}
NATIVE_KNOWN_HOSTS: ${{ secrets.NATIVE_KNOWN_HOSTS }}
run: |
set -eu
: "${NATIVE_ACCOUNT:?Missing NATIVE_ACCOUNT}"
: "${NATIVE_SSH_PORT:?Missing NATIVE_SSH_PORT}"
: "${NATIVE_HOSTNAME:?Missing NATIVE_HOSTNAME}"
: "${NATIVE_PARENT:?Missing NATIVE_PARENT}"
: "${REQUESTED_API_PORT:?Missing puerto_api}"
: "${NATIVE_SSH_KEY:?Missing NATIVE_SSH_KEY}"
: "${NATIVE_KNOWN_HOSTS:?Missing NATIVE_KNOWN_HOSTS}"
umask 077
scratch=$(mktemp -d)
trap 'rm -f "$scratch/key" "$scratch/known_hosts"; rmdir "$scratch"' EXIT
printf '%s\n' "$NATIVE_SSH_KEY" > "$scratch/key"
printf '%s\n' "$NATIVE_KNOWN_HOSTS" > "$scratch/known_hosts"
checksum=$(python3 -c 'import json; print(json.load(open("release-output/release-record.json"))["bundle_sha256"])')
python3 -B release-output/remote.py \
--bundle-dir release-output --bundle-sha256 "$checksum" \
--host 10.0.10.41 --ssh-port "$NATIVE_SSH_PORT" \
--account "$NATIVE_ACCOUNT" --expected-hostname "$NATIVE_HOSTNAME" \
--parent "$NATIVE_PARENT" --api-port "$REQUESTED_API_PORT" \
--identity "$scratch/key" --known-hosts "$scratch/known_hosts"
+3
View File
@@ -0,0 +1,3 @@
graphify-out
.claude/
samples/
+24 -9
View File
@@ -104,14 +104,14 @@ ISSSTELEON/ (outer) this WorkingNarrative repo: AGENTS.md, reference PD
├── models/ submodule: train/predict interface, cohorts, registry, OCR jobs
├── WebApi/ submodule: Flask API (also holds `webapi.orquestacion`, the Hamilton-based ETL graph)
├── WebApp/ submodule: Angular 22 + Material
└── docker-compose.yml webapi (gunicorn, :5050) + webapp (nginx, :8080)
└── docker-compose.yml webapi (gunicorn, :5050) + webapp (nginx, :8080) + indicadores + notebooks (isolated notebook runner)
```
Commands below are given relative to the inner `ISSSTELEON/` checkout (where
actual development happens) unless noted otherwise; `../` reaches this outer
repo's own files (`../e2e/`, `../docs_desarrollo-2.pdf`, etc.).
Dependencies (uv path deps): WebApi → Persistance, models[export], Extraction ·
Dependencies (uv path deps): WebApi → Persistance, models[notebooks], Extraction ·
models → Persistance, Extraction · Persistance → Core · Extraction → (no
internal deps). Each Python package has its own `uv` env: `cd <pkg> && uv run pytest -q`.
@@ -123,11 +123,22 @@ Databases: four independent ones (`CACU_`, `CAMA_`, `TEA_`,
## 3. Git state of the local working tree
- **`dev` is where work happens**, in this repo and in every submodule
(`WebApi`, `WebApp`, `models`, `indicadores_kit`), all on the `ISSSTELEON`
org Gitea: each piece of work is a branch off `dev`, merged back by a pull
request (rule 10). Other branches are not used for new work. In
`indicadores_kit`, `origin` is our org copy; `upstream` is the external
fork (read-only).
(`WebApi`, `WebApp`, `models`), all on the `ISSSTELEON` org Gitea: each
piece of work is a branch off `dev`, merged back by a pull request
(rule 10). Other branches are not used for new work. `indicadores_kit`
is no longer a submodule: its jobs live in `Transformation/`, the WebApi
and `models` (kit exit, 2026-11-15); the repo stays on Gitea for its
notebooks.
- **Changes flow `dev` → `staging` → `main`.** Changes are made on `dev`
(through branches off it), then passed on to `staging`, and finally to
`main`, which is what is handed off for installation. `staging` and
`main` are never worked on directly, so `dev` must always contain both;
the pending alignment is in `docs/ledgers/open-items.md`.
- When SSH to Gitea is refused, the repos can still be read over HTTP
without credentials (read-only):
`git fetch http://10.0.10.41:3000/ISSSTELEON/<repo>.git '+refs/heads/*:refs/remotes/origin/*'`
(`<repo>`: `WorkingNarrative`, `ISSSTELEON`, `WebApi`, `WebApp`, `models`).
Pushing still needs SSH or a token.
- This file lives outside the submodule, in the outer WorkingNarrative repo
(`ISSSTELEON/../AGENTS.md`) — versioned there instead of the prior
gitignored-local-notes setup, so it has real history and isn't lost on a
@@ -143,7 +154,10 @@ Databases: four independent ones (`CACU_`, `CAMA_`, `TEA_`,
one baseline generated from the models, verified upgrade/downgrade/upgrade
on SQLite, MySQL 8, PostgreSQL 16 and SQL Server 2022; older revisions are
gone, so a database stamped with them must start fresh):
- tea `a3e1c7b90d12`, cacu `b4f2d8c01e23`, cama `c5a3e9d12f34`, governance `d6b4f0e23a45` -> `e7c5a1f34b56`
- tea `a3e1c7b90d12` -> `f2b6d1e8c934` -> `6d772e9a342f` and `a7d3c9e5b160` -> `b9e4d2c71a05` (the join);
cacu `b4f2d8c01e23` -> `f89e1f081998`; cama `c5a3e9d12f34` -> `f82b64f43abd` (`cat_sistema_fuente`,
`cat_mapeo`); governance `d6b4f0e23a45` -> `e7c5a1f34b56`. The TEA chain and the join verified
upgrade/downgrade/upgrade on SQLite only.
---
@@ -177,8 +191,9 @@ Read these only when a task points there (its `area/*` label or its **Context**
| What | Where |
|---|---|
| What each component contains | `docs/architecture/<area>.md`, named after the `area/*` label: `webapi.md` (import pipeline), `extraction.md` (documents, EEG), `models.md` (OCR jobs, governance, model versioning), `indicadores-kit.md` (indicator computation), `other.md` |
| What each component contains | `docs/architecture/<area>.md`, named after the `area/*` label: `webapi.md` (import pipeline), `extraction.md` (documents, EEG), `models.md` (OCR jobs, governance, model versioning), `indicadores-kit.md` (the retired kit; measures now live in `Transformation/`, see `webapi.md`), `other.md` |
| Live testing against real infrastructure | `docs/operations/`: `local-dashboard.md`, `fork-source.md`, `mysql-tunnel.md`, `docker-engines.md`, `seed-pipeline-verify.md`, `browser.md`, `dev-data-ingest.md` |
| Plans and decisions | `plans/` |
| What the contract promises against what exists | `docs/scope-status.md` |
| How to test and run each package | `docs/testing.md` |
| History of past sessions | `docs/history/sessions.md` (the original §6, §7, §8.1, §9 and §10 of this file) |
+107 -30
View File
@@ -7,45 +7,122 @@ Moved from `AGENTS.md` on 2026-11-03.
Package `Extraction/extraction/`:
- `readers/` — `DocumentReader` + `@register_reader`; `PdfReader` (text
layer, Tesseract on pages without one, embedded image detection),
`ImageReader` (PNG/JPG/multi-page TIFF). `combine_pages` builds one PDF
from pages of several PDFs.
`ImageReader` (PNG/JPG/multi-page TIFF), `TextReader` (fallback: plain
text, one line per newline). `combine_pages` builds one PDF from pages of
several PDFs.
- Text layer: glyphs drawn several times a fraction of a point apart
(fake bold) are deduplicated (`dedupe_chars`); every line keeps its
words with their horizontal extent (`document.Line.words`).
- OCR: a page that is mostly one scanned image is OCRed unless its text
layer is substantial (a scanner may stamp a header over the scan); a
page read with low confidence is retried at the orientation Tesseract's
OSD detects. OCR lines carry word positions too.
- `segmentation.py` — `Segmenter` subclasses: `auto`, `document`, `pages`
(N per record), `key` (new record when the patient id changes; pages
without id continue the previous record).
- `nlp/` — `FieldSpec` (kind, labels, choices, pattern, scan_free_text,
multiline); extractors `LabeledValueExtractor` (captions, multi-field
lines, value under the label, fuzzy OCR-tolerant labels),
`PatternExtractor`, `FreeTextMentionExtractor` (catalog terms in
narrative, NegEx-style negation). Vocabulary of captions and clinical
terms in `nlp/vocabulary.py` (extend there, no code changes).
- `records.py` — `DocumentExtractor` and `RecordMerger` (same patient across
multiline); extractors `LabeledValueExtractor`, `PatternExtractor`,
`FreeTextMentionExtractor` (catalog terms in narrative, NegEx-style
negation). Vocabulary of captions and clinical terms in
`nlp/vocabulary.py` (extend there, no code changes); schema descriptions
also become captions, without a leading item code or what follows a
colon.
- Layout handling, all general (no form-specific rules): several captions
on one line; captions on one row with their values on the next, read
per column from word positions; item numbers (`3.-`, `b)`) belong to the
caption they precede and end the value before them; a value ends at a
wide horizontal gap once it has started; abbreviated captions (`Fech.`)
and dropped connectors (`de`, `del`) still match; a caption may run on a
few words before its colon; a label right after a connector is the tail
of a longer caption naming something else; an integer field never reads
a date.
- `nlp/discovery.py::discover_captions` — captions no `FieldSpec` claims,
found anywhere a known label could be (several per line, numbered,
heading a column) and read by the same extractor through temporary
specs.
- `template.py` — lines in the top or bottom margin that repeat (digits
exact, letters OCR-tolerant) on documents of two or more different
patients are the issuer's letterhead or footer; `DocumentExtractor`
re-extracts the affected records without them. A header repeated only
across one patient's documents is kept.
- `records.py` — `DocumentExtractor` and `RecordMerger` (same key across
pages/files, most confident value wins, confident disagreements become
`FieldConflict`). `ExtractedRecord.discovered` also carries every caption
no known `FieldSpec` claimed (`nlp/discovery.py::discover_captions`).
- `readers/text.py` — `TextReader`, the fallback in `FALLBACK_READERS`:
content that's neither a PDF nor an image, read as plain text (one page,
one line per newline) as long as it decodes as one, instead of being
rejected as an unsupported format.
`FieldConflict`). `extract(..., source_fields=, record_keys=)`: values a
structured source hands over per document (trusted over the page,
including the key) and the record each document joins (documents sharing
one merge; others stay apart even for the same patient).
`ExtractedRecord.discovered` carries the captions no spec claimed.
- WebApi side: `connectors/document.py` + `schemas/field_specs.py` (field
specs derived from the target schema). Each row carries `documento` (the
record's pages as one PDF), mappable to a file column. Corrections from
the UI travel as `overrides`. Results cached per worker for repeated calls.
A `document` source's `payload` may carry `sql` (a connection, `table` or
`query`, `column`, `key_column`) instead of `files`: one document per
row, the named column read as its bytes (a `varbinary(max)` PDF) or, via
`TextReader`, as plain text — the same connector and extraction either way.
record's pages as one PDF), mappable to a file column, and every
discovered caption as a column of its own. Corrections from the UI travel
as `overrides`; `include_pattern`/`exclude_pattern` keep or leave out
documents by their text; unreadable documents are listed in `skipped`
instead of failing the batch. Results cached per worker.
- Documents stored in columns of any tabular source (SQL table or query,
CSV, Excel, JSON): `connectors/document_columns.py::DocumentColumns`
(document columns; `name_by`, `group_by` and `fields` as a column, a
list of columns or a derived rule). Cells may hold the file as binary,
hex or base64 text (`document_bytes`). Used by a `document` source's
`sql` payload and by any import source's `documents` (see webapi.md).
- `schemas/catalog_matching.py` + `services/catalog_commit_service.py`:
a discovered caption is fuzzy-matched (`rapidfuzz`) against the project's
catalog (`core/catalogos/<proyecto>.toml`); a close enough etiqueta reuses
that `resultado_id`, otherwise one is minted
(`indicadores_kit.registry.catalogos.add_resultado`) and synced. Written
straight into `procedimiento`/`observacion` (no staging row for these),
tagged with the sentinel `fuente_tabla` `catalogo_abierto` so it reads
apart from every staging-derived row.
opt-in per source (`catalog_fallback: true`). A discovered caption is
fuzzy-matched (`rapidfuzz`) against the project's catalog
(`core/catalogos/<proyecto>.toml`); only captions the catalog already
knows are written, straight into `procedimiento`/`observacion`, tagged
with the sentinel `fuente_tabla` `catalogo_abierto`. The import path never
mints catalog entries (the catalog is versioned with the code);
unmatched captions are counted, and the import report lists unused
captions without their values (webapi.md).
- WebApp: `DocumentReviewDialog` (records, value, confidence, method,
source line and page, conflicts, image thumbnails, editable values).
- Limits: NLP is rule-based (no trained model); images are located and
shown, not classified, and only stored inside the record's PDF.
source line and page, conflicts, image thumbnails, editable values,
document filters; each value's assertion when it isn't affirmed, the
other candidates as one-click picks, a warning on off-topic records).
- Narrative layer (2026-11-13), all in `Extraction/` (`README.md` there has
the method and references for VAR-04/VARM-05):
- `nlp/context.py`: ConText/NegEx assertions (negated, hypothetical,
historical, uncertain, presumed) with form-style answers after a mention
(`Término: NO`) and a caption without its answer read as asserting
nothing; sections from standalone headings (clinical, description,
result, history, reference text), a caption with content qualifying only
its line. Labels' values are only qualified by clinical and history
sections, so a footer date under an interpretation guide still counts.
- `FieldSpec` gained `anchors` (a generic answer like "POSITIVO" needs its
concept before it), `severity` (most severe affirmed value wins),
`negated_value` ("sin actividad epileptiforme" -> 0) and `unit`
(`MeasurementExtractor`, ranges give their midpoint). Vocabulary for all
of them, EEG terms (ACNS), narrative BI-RADS, Bethesda/LAST terms and
section headings and triggers is in `nlp/vocabulary.py`.
- `ocr_fold`: OCR look-alikes collapsed on both sides, as a fallback for
labels and choices on OCR lines only.
- Subject check: `DocumentExtractor(subject=, foreign=)` from
`vocabulary.SUBJECTS` keyed by table name (`__table__.name`, e.g.
`citologiacervical`). Only positive evidence gates: a record naming a
foreign subject and not its own fills nothing; values held back from an
off-topic segment come back if its merged record is on topic.
- Every candidate is kept (`ExtractedRecord.candidates`) with features
(no document text); `nlp/ranking.py` picks one: `HeuristicRanker`
(confidence, with hypothetical and off-topic vetoed) or `LearnedRanker`
(online logistic regression, AdaGrad + L2, blended with the heuristic
until `TRUST_EXAMPLES`; the rules' vetoes hold until then).
- `models/io/extraction_ranker.py` versions each domain's ranker as
`<domain>-extraccion` (DEV version per batch, five routines, saved
model). WebApi learns in line: `commit_sources` ->
`review_learning.learn_from_reviews` (background, one worker) from
records with `overrides` (corrected fields plus the rest as accepted).
`python -m webapi.nlp evaluate|train` scores against / trains from an
answer key (leave-one-document-out estimate first).
- The connector fills the entity's `*_nlp_version` column with
`extraction <version> + extraccion:<n>`; the review report carries
`alternatives`, `on_topic` and `nlp_version`.
- Development set: six real CaCu documents (cytology forms, HPV PCR
reports, scanned biopsies) kept outside every repository; answer key in
the session scratch only. Rules alone went from P 0.65 / R 0.85 to
1.00 / 1.00 on them, and the leave-one-out ranker estimate is 1.00; both
are fit on the same documents the rules were adjusted to.
- Limits: images are located and shown, not classified, and only stored
inside the record's PDF; the template rule needs at least two patients'
documents in the batch.
### 5.4 EEG (TEA)
+5 -1
View File
@@ -1,6 +1,10 @@
# indicadores-kit
Moved from `AGENTS.md` on 2026-11-03.
Moved from `AGENTS.md` on 2026-11-03. **Retired on 2026-11-15:** the kit is no longer a submodule or a
dependency. Its measures are dbt semantic models in `Transformation/`, answered on request by the WebApi as FHIR
MeasureReports (`webapi/kpis.py`, `webapi/fhir/`); its silver load, reference tables and follow-up list are in
`webapi/orchestration/` and `webapi/follow_up/`; its cohorts are in `models/cohorts/`. What follows describes the
division of labor that still holds and the kit as it was.
### 5.6a Indicator computation — division of labor (clarified by the owner, 2026-10-19)
+103 -16
View File
@@ -14,19 +14,106 @@ Moved from `AGENTS.md` on 2026-11-03.
### 5.5 Model versioning and cohorts (ML/MLD/EL)
- Governance DB tables (`Core/core/governance/`): ExtractionRun,
CohortVersion, CohortMember, CohortExclusion, CohortExclusionCount,
ModelVersion, ModelArtifact, ModelPrediction.
- `models/models/registry.py` — `ModelRegistry`: register, attach reports,
upload artifacts (checksummed, ONNX validated), status derived
(desarrollo/candidata/produccion/retirada), `checks()` gates promotion
(ML-02, ML-03, MLD-01, MLD-01b, MLD-03, ML-01b), retire, lineage, compare.
- `models/models/cohort.py` — `CohortBuilder`, `ExclusionCriterion`,
`@register_cohort_builder`. **No concrete builders exist**: clinical
criteria are not defined in the requirements document, so production
promotion is impossible until a scenario is registered.
- `models/models/prediction.py` — `PredictionService` persists predictions
tagged with the active version.
- Routes `/governance/model-versions*`, `/governance/artifacts/<id>/download`,
`/governance/cohort-scenarios`, `/governance/cohort-versions`. WebApp
model-version detail dialog and cohort build menu.
Versions, runs and their files live in MLflow; the cohorts a model trains on
are the kit's builds (`cohorte_armado`) or dbt's, exported to Parquet files.
- `models/models/io/tracking.py`: `TrainingRun`, one MLflow run per training.
It links the cohort build (ML-03), tags DEV/PROD (ML-02) and the git commit,
saves the model (`log_model`, `modelo_sha`; PROD refuses a class defined in a
notebook) and records each routine around training while it runs
(`log_routine(kind, record)` → `rutinas/<KIND>.json`, counts and settings,
never rows). `ROUTINE_KINDS` are the five of §5 of the requirements:
MUESTREO, DATOS_FALTANTES, METODO_ANALITICO, BALANCE_CLASES,
CONFIANZA_SALIDA (`Core/core/governance/enums.py::ArtifactKind`, plus
OTRO for any other file the run keeps). `run_files`/`run_file` list and
download a run's files; a folder downloads as a zip.
- `models/models/io/registry.py`: `registry`. Status is derived
(desarrollo/candidata/produccion/retirada); `checks()` gates promotion:
ML-02, ML-03, MLD-01 (metrics, technical report), MLD-01b, MLD-03, **ML-01a
(all five routine records, written by the run) and ML-01b (the saved
model)**. Only what the training run itself wrote counts: nothing can be
uploaded to a version. `lineage()` returns every file of the run and the
routine records; `artifact()` downloads one (ML-01b).
- `models/models/cacu/cin2_logistic/model.py`: Hamilton nodes `sampling`,
`missing_data`, `analytic_method`, `class_balance`, `output_confidence`
(and `routines`, which gathers them) record what this training did:
the temporal split, missing predictors as the `(none)` category,
coefficients, class counts (no reweighting) and a calibration table.
- Routes: `/governance/model-versions*` (list, register, reports, lineage,
checks, promote, retire) and
`GET /governance/model-versions/<d>/<s>/<v>/artifacts/<path>` (download).
WebApp version dialog: checklist, cohort, the five routines (recorded or
missing, each viewable), the run's files as downloads, reports, and
"Probar en un notebook".
- Removed 2026-11-13: uploading a file of any kind to a version (it let a
hand-picked file satisfy ML-01b), and the ONNX checkpoint support with it
(`ONNX_CHECKPOINT`, `inspect_onnx_metadata`, the `export` extra). Nothing
produced an ONNX file and predictions never used one.
### 5.6 Notebooks run on the server (ML-01a, ML-04, ML-05)
A Jupyter notebook uploaded from the WebApp runs against one exported cohort
build, isolated from the server, for development experiments.
- `models/models/pipelines/experiment.py`: `start` creates an MLflow run in
`<domain>-<scenario>/experimentos`, tagged with the notebook's name and
content hash, the build's file (`cohort_reference`), the chosen version and
the code version, and stores the notebook without outputs. `execute` hands
the job to an executor, then stores the page (`report/<name>.html`), what
was imported (`importado.json`) and, if it failed, `error.txt`; the run is
tagged `sandbox: contenedor|local`. Status: en_curso, terminado, fallido,
interrumpido (running past `NOTEBOOK_JOB_TIMEOUT` + 30 min).
- `models/models/io/notebook_jobs.py`: the job folder
(`<NOTEBOOK_JOBS_DIR>/<run_id>/`: `notebook.ipynb`, a copy of the build's
file `cohorte.parquet`, the chosen version's saved model `model/`,
`job.json`), assembled aside and renamed into place, and handed to
`NOTEBOOK_RUNNER_UID`. `run_job` runs it on the `python3` kernel with an
environment built from the job alone: the build's file, `MODEL_PATH`, an
MLflow store inside the job (`mlflow.db`, `artefactos/`), every
`*_DATABASE_URL` set to `sqlite://`, HOME and temp folders inside the job;
writes `page.html` and `result.json`. Executors (`EXECUTORS`,
`register_executor`): `local` runs it in the API's process (development,
unisolated); `contenedor` leaves it for the runner and waits
(`NOTEBOOK_JOB_TIMEOUT`, 6 h). `NOTEBOOK_EXECUTOR` picks one; the default is
`contenedor` when `NOTEBOOK_JOBS_DIR` is set. `serve` (`python -m models
notebooks serve`) is the runner's loop; a job is claimed by creating
`en_curso/` in it.
- `models/models/io/notebook_import.py`: copies what the notebook trained
into the platform's MLflow. Only `<domain>-<scenario>` experiments of the
job's domain; each run becomes a new DEV run with the real cohort tags,
`notebook.run_id`, the code version and a recomputed `modelo_sha`
(`kit.armado_id` and the notebook's own `modelo_sha` are dropped); versions
come across as DEV, never with an alias. The store is opened from a copy,
files are walked without following links and must sit inside the job
(`read_job_file`, `inside`), and `NOTEBOOK_MAX_IMPORT_MB` (500) caps them.
All of it exists because the trusted side reads files an untrusted
notebook wrote.
- `models/models/notebook.py`: the API inside a notebook. `experiment()` →
`.cohort()`, `.lineage()`, `.model()` (the job's copy, `MODEL_PATH`),
`.training_run()` (a DEV `TrainingRun` linked to the build),
`.register(run)`.
- `models/models/io/rendering.py`: renderers as classes (`RENDERERS`,
`register_renderer`): `quarto`, and `jupyter` (`nbclient` + `nbconvert`,
the `notebooks` extra, which WebApi installs). `NOTEBOOK_RENDERER` picks
one; otherwise Quarto if installed, else Jupyter. `NOTEBOOK_CELL_TIMEOUT`
(1800 s per cell).
- `models/models/io/storage.py`: `exported_builds(root, domain)` and
`build_file(root, url, source, build)`, read from the files alone.
- Deployment: service `notebooks` in `docker-compose.yml` and
`dist/docker-compose.yml`, the webapi image with command `notebooks`
(`WebApi/docker-entrypoint.sh`): `network_mode: none`, `read_only`, tmpfs
`/tmp`, user 10001, `cap_drop: ALL`, `no-new-privileges`, memory/CPU/PID
limits, only the jobs volume at `/trabajos`. webapi mounts the same volume
at the same path (the import checks paths as the runner wrote them) with
`NOTEBOOK_JOBS_DIR=/trabajos` and `NOTEBOOK_RUNNER_UID=10001`.
- WebApi (`webapi/blueprints/governance.py`): `GET /governance/cohort-files`,
`GET|POST /governance/experiments` (multipart `file`, `domain`, `scenario`,
`url`, `source`, `build`, `version?`; 202, executed in a thread pool,
`WEBAPI_NOTEBOOK_WORKERS`, default 1),
`GET /governance/experiments/<run_id>`, `.../page` (served with
`Content-Security-Policy: sandbox`), `.../artifacts/<path>`.
- WebApp: Gobernanza tab "Notebooks" (`experiments-panel`, polls while a run
is in progress, flags "Sin aislar" runs) and `notebook-run-dialog` (also
opened from a version).
- Only `.ipynb` (nbformat 4) is accepted. Open items in
`docs/ledgers/open-items.md`.
+37
View File
@@ -23,4 +23,41 @@ Moved from `AGENTS.md` on 2026-11-03.
`merge_duplicates` (opt-in, `merge_duplicates: true` on `/imports/commit`)
combines rows of different sources sharing a natural key **before**
validation (first source wins, disagreements reported as warnings).
- **SQL sources** — `server.host` tolerates pasted forms (`host\instance`,
`host,port`, `host:port`, JDBC/URI strings); a named instance without a
port is left for the server to resolve. A user query is wrapped as a
derived table, so a trailing `ORDER BY` that no TOP/LIMIT/OFFSET needs is
dropped (SQL Server refuses it there). Every preview lists, in
`document_columns`, the columns whose cells hold files.
- **Mapping beyond one-to-one** — an import source may carry, besides
`column_mapping` and `defaults`:
- `derived`: `{field: rule}` computed from source columns
(`imports/mapping/derived.py`; one `Derivation` class per operation plus
`@register_derivation`): `column`, `concat`, `template`, `split`,
`coalesce`, `extract`, `map`, with an optional `case`. Short forms: a
column name or a list of columns. `GET /imports/derivations` describes
them, and the WebApp builds its forms from it.
- `documents`: columns holding documents (`DocumentColumns`, see
extraction.md), with `group_by`, `name_by`, `fields`, `file_field` and
the extraction settings. Values the mapping takes from the row's own
columns are trusted over the page; then mapping and `derived` run again
over each record's namespace (the rows' columns plus every field and
caption its documents print), and extracted fields fill what's left.
Rows without documents pass through mapped.
- `catalog_fallback: true` to opt in to the catalog path (extraction.md).
- Order: mapping and `derived` (one field can't be fed by both), document
extraction, then `defaults` for anything still empty.
- **Previews** — `POST /imports/mapped-preview` (`{source, limit}`: rows as
they would be written); `POST /imports/sources/document/columns` (a source
with `documents`: its columns plus the documents' fields and captions, as
a preview with suggestions); `POST /imports/sources/document/extract`
also takes `{source}` to review a mapping's documents.
- **Import report (Bitácora de cargas)** — `imports/audit.py`, counts and
shapes only, never record values. Per source it also lists the captions
its documents print that nothing used (`etiquetas_sin_usar`, captions
with how many records print them, from `WEBAPI_REPORT_MIN_COUNT` up;
`etiquetas_sin_usar_poco_frecuentes` counts the rest).
- Routes in `webapi/blueprints/imports.py`; `GET /api` lists every route.
- WebApp: the flow editor's "Reglas" tab (`connect/components/mapping-rules`)
sets document columns, derived fields and the catalog fallback, and shows
the mapped preview.
+19
View File
@@ -2892,3 +2892,22 @@ code, given it adds a service to operate/secure? Lean toward only doing
this if MLflow's web UI becomes independently useful for the team (e.g.
browsing experiments/artifacts outside this app), not for the code
reduction alone.
## 11. Indicator recompute moved from polling to a filesystem watch, 2026-11-13
`WebApi/webapi/indicadores_vivos.py`'s loop used to just sleep for
`INDICADORES_INTERVALO_S` (default 20s) between checks of the
`pendiente/<dominio>` marker directory. Replaced the sleep with a
`watchdog` observer on that directory: any marker write now wakes the loop
immediately (verified in a standalone smoke test: pickup in well under a
second against a 100s fallback interval), and `INDICADORES_INTERVALO_S`
stays only as a safety net for a missed or coalesced filesystem event, not
the normal reaction time. `ColaDeRecalculo`'s marker/state semantics
(`solicitar`/`tomar`/`atender`, the coalescing of requests that arrive
mid-run) are unchanged; only how the loop wakes up moved. `watchdog` added
as a WebApi dependency (`uv add watchdog`, pure Python, inotify on Linux).
This is the live mechanism G-DBT-3 (`docs/ledgers/grooming.md`) describes
as "it drops a marker and the `indicadores` service runs the domain's
cycle" — that description still holds; only the wake-up trigger inside it
changed, not the cycle itself.
+28
View File
@@ -62,3 +62,31 @@ Something went wrong or was surprising while doing a task. Format and plan codes
- **Decides:** owner.
- **Decision:** 2026-11-05, owner: no past-date rebuilds for now, drop it from the export; a dbt snapshot may
replace it in the future.
### I-DBT-3. `cin2_logistic.predictors()` crashes the whole training run on a cohort member with a biopsy but no citología — high · open
- **What happens:** `predictors()` builds each member's index sample from `citologia` rows only
(`model.py`, lines ~61-68): `sample = cohort[(cohort["tipo"] == "citologia") & (cohort["fecha"] ==
cohort["fecha_indice"])]`, grouped by `pac_id`. For a cohort that includes a member with a `biopsia`
row but no `citologia` row at all, `sample` comes back empty; the following
`cohort.merge(sample, left_on="pac_id", right_index=True)` degenerates, and the resulting frame's
implicit index ends up also named `pac_id` on top of the `pac_id` column already there. The later
`pivot_table(index="pac_id", columns="tipo", values="valor_codigo", ...)` then raises
`ValueError: 'pac_id' is both an index level and a column label, which is ambiguous`, which is
unhandled and kills the whole run — not just that member's row.
- **Evidence:** `docker compose ... run --rm entrenar` against a CaCu cohort containing one member with
a `BiopsiaCervical` row (imported through the "documents in columns" connector) and no
`CitologiaCervical` row for that patient. Full traceback bottoms out at
`models/models/cacu/cin2_logistic/model.py:68`, in `predictors`, inside the `pivot_table` call.
- **Consequence:** a cohort build with even one biopsy-only member (plausible: direct referral,
partial/migrated history, a document-column import that only carries pathology results) blocks
`entrenar` entirely for every member, not just that one. The model can't be trained at all until the
offending member is removed from the cohort or the code tolerates the empty-sample case.
- **Proposal:** make the empty-`sample` case produce `MISSING` predictors for that member instead of a
malformed frame, e.g. reset the index after the merge (`results = cohort.merge(sample, left_on="pac_id",
right_index=True).reset_index(drop=True)`) before the `pivot_table` call, or build `wide` from an
explicit left-join against `members["pac_id"]` so a member with zero sample rows still gets a row of
`MISSING` rather than disappearing and corrupting the frame's index naming. Add a unit test with a
cohort containing one biopsy-only, no-citología member to pin this down.
- **Decides:** owner (models package).
- **Decision:**
+43
View File
@@ -293,3 +293,46 @@ Proposals that come up while doing a task and aren't resolved inside it. Each on
from the indicator catalog and the gold YAML; one Hamilton node per indicator reads that declaration,
as a MetricFlow `ratio` metric would.
- **Issue:** #162
## G-GEN-1. Source terminology as catalog tables, editable from the UI
- **Where:** `Core/core/catalogos/<dominio>.toml` (`codigos_hospital`, `etiquetas_fuente`, `alias`), the silver
load's enum maps, `WebApi/webapi/orchestration/reference/source_mapping.py` (the mapping's rules) and
`observacion_clinica.valor_fuente`.
- **What happens:** how a lab provider or a medical-record header writes our codes lives in the catalog's TOML
and in code. A provider change (new captions, spellings or test codes) needs a commit, a release and a deploy,
and a deploy would overwrite any change made outside git.
- **What it conflicts with:** rule 4 (two new tables); rule 2 (versioning has to work on every engine, so SQL
Server's temporal tables can only be an add-on).
- **Proposal:**
1. Our codes (`cat_estudio`, `cat_resultado`, `cat_valor`) stay in the TOML, reviewed in git.
2. How each source writes them moves to two tables, the database being their system of record:
`cat_sistema_fuente` (who sends the data, by `fuente_tabla` and validity dates) and `cat_mapeo` (FHIR's
ConceptMap: `clase` estudio, etiqueta or valor; the form and its normalized form; target; validity;
`registrado_por`, `registrado_en`, `motivo`). Append-only; a deploy only inserts missing seed rows.
3. The mapping is a partial, non-injective function `(system, resultado_id, normalized form, date) -> valor_id`
into `cat_valor`. `source_mapping.check_function` already enforces it on the TOML; the UI and the API
apply it on every save. `source_mapping.resolve` is the remap's rule: no mapping or two disagreeing
mappings give no code, and the observation goes back to the out-of-catalog queue.
4. A remap step on every cycle and on demand rewrites only `valor_id` where the code changes, under a
`carga` of its own (`conocida_en` keeps reports cut before it reproducible). A new caption or study code
needs a re-extraction or a reload instead.
5. A queue screen (source text with no code), a mappings screen per system, a curator role, and a
`ConceptMap` endpoint.
6. Versioning: validity dates in the table (what the pipeline reads, every engine); in production SQL Server,
system-versioned temporal tables on both tables for the edit audit, a SQL Server-only revision that's a
no-op elsewhere.
- **Open questions:** where a report records the mappings it used (`toml_sha`, `huella` or `parametros`);
mappings per system only or also global; whether the temporal tables are in scope now.
- **Evidence:** draft and SQLite demo in `mock/borradores/catalogo-mapeo/` (`PROPUESTA.md`, `01_tablas.sql`,
`02_demo.py`): seeding from the TOML changes 0 stored observations; a new lab's 5 unmapped spellings land in
the queue and, once mapped and remapped, reach dbt's timeline, the stratifiers and the invasive-cancer event
unchanged.
- **Found in:** #163 (CaMa values read from reports), 2026-11-13.
- **Status:** approved by the owner on 2026-11-13 and implemented on `feature/163-source-terminology` (every
repository rebased on `dev`): ISSSTELEON `66c4ba5` (Core tables), `74eb5a4` (a revision per domain),
`14dff24` (`SourceMappingRepository`), `d6e2c68` (dbt's `vigencias_sin_traslape` on `cat_mapeo`),
`72d092d` (pointers); WebApi `64d3d72` (`source_mapping`: `check_function`, `resolve`), `73cbf0c` (seeding in
the `catalogs` step, `register` checking the function on write). Layers 1 (write check), 2 (`UNIQUE` and
check constraints) and 3 (dbt test) are in; pandera is left for a bulk import of mappings. Still open: loads
read the TOML's aliases, not `cat_mapeo`; the remap step; the UI screens; the `ConceptMap` endpoint;
migrations verified on SQLite only.
+116 -3
View File
@@ -11,7 +11,120 @@ Moved from `AGENTS.md` §5.7 on 2026-11-03. Each item can become an issue.
- No authentication/authorization on WebApi; SQL credentials travel from the
browser on each call (mitigated by `SqlSourcePolicy`).
- Cross-field validation rules not implemented in the import schemas.
- No trained NLP model (options discussed: pretrained Spanish clinical
model as an extra `FieldExtractor`, plus learning from review corrections;
needs real anonymized reports to evaluate).
- Document NLP (narrative layer and learned ranker, see
`docs/architecture/extraction.md`), still open:
- Only measured on six real CaCu documents, the same ones the rules were
adjusted on; a held-out set (ideally 30+ per report type, with an answer
key written by someone else) is needed for an honest score. EEG,
mammography and breast biopsy vocabulary has never seen a real report.
- The ranker trained on those six lives only in a scratch MLflow store;
on the server it starts empty until `python -m webapi.nlp train` is run
with a key, or reviewers correct imports.
- `<domain>-extraccion` versions can't pass ML-03 (no cohort: they learn
from documents), so they can't be promoted; extraction uses the latest
DEV version. Needs a decision on how governance treats this model.
- Learning runs in one background thread per WebApi process; with several
gunicorn workers two batches can continue the same version and both
register, the second not including the first's examples.
- A correction teaches only if made in the review dialog before
committing (it travels as `overrides`); fixing a value later in the
database teaches nothing.
- No pretrained Spanish clinical model; it would be one more
`FieldExtractor` whose candidates the ranker weighs, once a held-out
set exists to show it helps.
- Colposcopy (Reid, Swede) has no columns, so it stays as text.
- Possible DICOM connector for mammograms (`pydicom`, fits `mast_dicom_blob`).
- A source may hold a biopsy and the cytology that led to it as separate
orders with nothing linking them (no shared id in the rows or in the
documents). The CaCu confirmation indicator only counts the biopsy a
cytology originated (`BiopsiaCervical.cit_id`), so such biopsies read as
"sin biopsia aún". Option: a general import rule that fills a link with
the same patient's latest record of the parent kind dated on or before
the child's date; needs a decision on the rule and its time window.
- Which printed date counts as a cytology's sampling date is a per-source
mapping choice (request or reception date), not code.
- `documents.group_by` takes the source's own columns (or rules over
them), not values read from the documents.
- A user query starting with `WITH` can't be wrapped as a derived table on
SQL Server (`connectors/sql.py::_text_subquery`).
- Compose ports and the `ng serve` proxy target are fixed in
`docker-compose.yml` and `WebApp/proxy.conf.json`; neither reads an env
var yet.
- The template-line rule (`Extraction/extraction/template.py`) needs at
least two patients' documents in one batch; a single document still
reads its letterhead.
- Branch alignment, as of 2026-11-13: `dev` was pushed in all six repos
and contains `staging` and `main` everywhere, except that
`WorkingNarrative`'s `main` keeps one merge commit with identical content.
`staging` and `main` are behind `dev` until the next promotion. SSH to
Gitea refuses the local key; pushes went over HTTP with the API token.
- Notebooks run in the `notebooks` container (no network, read-only system,
uid 10001, no capabilities, only the jobs volume), and what they train is
imported by trusted code (`models.io.notebook_import`). Still open:
- The app has no login, so anyone who reaches it can upload a notebook,
and its page (which may print cohort rows) is readable by anyone.
- The container was validated with `docker compose config` and tested as a
separate process, not yet started as a real container.
- Local development (`NOTEBOOK_EXECUTOR=local`, the default without
`NOTEBOOK_JOBS_DIR`) runs notebooks unisolated in the API's process; runs
say so (`sandbox: local`, "Sin aislar" in the WebApp).
- A WebApi worker that restarts while waiting leaves its run "en curso"
until it shows as "interrumpido" (job timeout + 30 min) and its job
folder behind; nothing picks the result up again.
- A version registered over `POST /governance/model-versions` has no routine
records or saved model, so it fails ML-01a/ML-01b and can't be promoted;
production versions come only from training code in `models`.
- ML-01b is met by downloading a run's files; there is no portable model
export (ONNX support was removed 2026-11-13 as unused).
- The notebook tab needs exported cohort builds on the server
(`python -m models cohorts export ...`), and the WebApi image must be
rebuilt to get the Jupyter libraries (`models[notebooks]`).
- `cin2_logistic`'s routine records (`model.py`) are the only real ones;
any new model has to add its own five, or it can't be promoted.
### TEA redesign (#163, branch `feature/163-tea-redesign` off `refactor/kit-exit`), 2026-11-12
Left open by the implementation of `plans/kit-exit/tea-redesign.md` (all but the WebApp):
- §12.6 not done: CaCu's risk as `RiskAssessment`, imports as `transaction` Bundles with `AuditEvent` and
`Provenance`, OCR jobs as `Task`, and CaCu's follow-up list as `EpisodeOfCare`. The old routes stay; removing
them, and `/<domain>/indicadores`, needs the owner (§12.9).
- §12.2: suppression (`data-absent-reason: masked`) and confidence intervals wait for #73.
- The new Alembic revision (`f2b6d1e8c934`) was checked upgrade/downgrade/upgrade on SQLite only; MySQL,
PostgreSQL and SQL Server untested (rule 7). `dbt build --select tea` passed on SQLite only; the SQL Server 2016
VM and `e2e/sqlserver2016` (piece 11 of `tea-port.md`) not run. `tea_meses_cumplidos` has a separate `floor` path
for the other engines, untested there.
- Assumptions to confirm: the metric references live in dbt's var `tea` (an ephemeral model), not a seed, because
the cycle doesn't run `dbt seed`; effect texts and electrode positions are in `WebApi/webapi/fhir/tea_eeg.toml`.
An EEG without any criterion written is `SIN_ANALIZAR`, a third category of M29 (the §10 question). M25's units are
all the period's children, its event the first F84.0 note. M29 counts the cohort's children only. ADOS-2 items are
the 28 of the old staging (the plan says 29 but its own total of 76 columns has 28); labels of B13 to B18 and D5
wait for the manuals. Codes are the project's: no LOINC or SNOMED until confirmed (§12.9).
- `fhir.resources` (8.3, R4B models) added to WebApi's dev group to validate responses in tests: needs the owner's
approval as a new dependency (§12.9).
- Patient routes (`EpisodeOfCare`, `$resumen-tea`) are registered only in DEV with the `simulado` tag; alterations
stay hidden until `TEA_ALTERACIONES_VALIDADAS=1`.
### Kit exit integrated on `dev` (branch `feature/kit-exit-integration`), 2026-11-15
Left open by bringing `feature/163-source-terminology`, `feature/163-tea-redesign` and the CaMa dashboard's
presentation onto one branch:
- `cat_mapeo` is seeded by the `catalogs` step but no load reads it yet: the CaMa silver load still takes captions
and aliases from the catalog's TOML (`webapi/orchestration/reference/catalogs.py`); the remap step, the mappings
screens and the `ConceptMap` endpoint of G-GEN-1 are not built.
- The follow-up list exists for CaCu only (`webapi/follow_up/`); the CaMa follow-up tab shows the unavailable state
until a CaMa list is served. Angel's CaMa follow-up and Análisis endpoints (`dashboard-test`) read the kit and a
synthetic reader, so they were not merged.
- The three CaMa measures Angel added to the kit (`deteccion_histopatologica`, `dias_resultado_diagnostico`,
`histopatologia_birads`, #161) were not ported; the dbt CaMa measures and the invasive-cancer stratifiers are what
the page draws. Re-expressing them in dbt is a separate task.
- `feature/cacu-pim-vigilancia` (models as a Hamilton dataflow, the CIN2+ prevalence-incidence scenario) is
deferred: it predates the cohort move into `models/cohorts` and needs rebasing on the new `dev`.
- The webapi image compiles dbt's manifest for SQLite at build time and, on another engine, at start-up against the
configured databases (`webapi.dbt_manifest`); the start-up path was not exercised against a real MySQL,
PostgreSQL or SQL Server here, and Docker was unavailable on the machine that built the branch.
- TEA's alterations stay hidden until `TEA_ALTERACIONES_VALIDADAS=1`; `fhir.resources` in the WebApi's dev group
still needs the owner's word; suppression and intervals are #73's.
- A risk batch stays `preliminary` until `python -m webapi.orchestration confirm-risks`; the risk route serves
only final batches.
+68
View File
@@ -0,0 +1,68 @@
# What is promised, what we have, what is missing
Checked on 2026-11-13 against `Alcance_proyecto.pdf` (modules and the
deliverables list) and `docs_desarrollo-2.pdf` (requirement IDs), reading
the code rather than the notes. Hand-off is 2026-11-30. Status: **done**,
**partial** or **missing**. Items that depend on the client's data or
clinical decisions say so; they need negotiating, not just code.
## Contract deliverables
| Deliverable | Status | What exists / what is missing |
|---|---|---|
| Structured, integrated, cleaned database apart from the source systems | **done** | Four engine-agnostic databases (CaCu, CaMa, TEA, governance), versioned cohort builds. |
| Data integration layer through web services (APIs) | **done** | "Conectar datos": SQL, Excel/CSV, PDF tables, clinical documents, EEG, documents stored in columns; validation, merge, import log. |
| NLP modules | **partial** | Field extraction from forms and free text: captions and layout, ConText/NegEx assertions, sections, anchors, severity, measurements, OCR tolerance, subject check, review dialog; a learned candidate ranker that learns from review corrections (`<domain>-extraccion`); `python -m webapi.nlp evaluate/train`. Missing: a held-out evaluation set; EEG, mammography and breast biopsy vocabulary tested on real reports; colposcopy (Reid, Swede) has no columns. |
| Breast cancer (CaMa) risk model | **missing** | `models/cama` holds only its package docstring. Needs data and outcome definition from the client. |
| TEA diagnostic model from EEG alterations | **missing** | EDF files are read and validated (amendment done) and the report's EEG findings can be extracted; no signal features, no model. Needs data. |
| CaCu progression risk model | **done (one scenario)** | `cin2_logistic`: routines recorded, estimate, risks stored with model provenance. Risk cut-offs (immediate / priority / scheduled) undefined, so the risk-band indicator is hidden. |
| CaCu survival model (OS/DFS, Kaplan-Meier at 1/3/5 years) | **missing** | Only a draft survival chart contract in the indicators kit. Needs follow-up and death data. |
| Interactive dashboards with each module's indicators | **partial** | Indicator pages per domain; no PDF/XLS export of indicators (only the import log downloads), no heatmap, no single combined view. |
| User manual | **partial** | `dist/MANUAL.md` covers installation, operation and the import flow; not every screen. |
| Technical manual | **partial** | Preliminary design specification PDF, package READMEs (`Extraction/README.md` documents the NLP method and references), architecture notes; no final consolidated document. |
| Project closure letter | n/a | Administrative. |
## Modules
| Module | Status | Notes |
|---|---|---|
| M00 Configuración: login, 2FA, password change, lockout, access, profiles, users | **missing** | No authentication at all; the biggest security gap (anyone who reaches the app can import data and run notebooks). |
| M00 Parametrización, catálogos generales | **partial** | Catalogs and parameters exist as versioned files (`core/catalogos/*.toml`, `parametros.toml`); no screens to edit them. |
| M01 CaMa: BI-RADS indicators | **done** | BI-RADS 4/5, confirmation, biopsies, time to diagnosis. |
| M01 CaMa: risk calculator, heatmap, PDF/XLS reports, individual profiles, model | **missing** | Risk band only as a proposal. |
| M01 CaMa: mammogram images | **partial** | Images embedded in reports are located and stored; no DICOM connector. |
| M02 TEA: % with/without EEG, evaluation, confirmation, screening-to-diagnosis | **done** | |
| M02 TEA: % normal vs abnormal EEG, correlation with severity | **missing** | The extraction to fill `eeg_anormalidad_presente` and the conclusion category now exists; the indicators don't. |
| M02 TEA: EEG model | **missing** | |
| M03 CaCu: cytology distribution, histopathology confirmation, screening-to-diagnosis time, risk model | **done** | |
| M03 CaCu: diagnosis-to-treatment time, survival, cut-offs, incidence/prevalence against state data, individual profiles | **missing** | |
| M04 Integrated dashboard with PDF/XLS | **partial** | Per-domain pages only. |
## Requirements document
| IDs | Status | Notes |
|---|---|---|
| VAR-01..03, VARM-01..04a | **done** | OCR with confidence, status, main and alternative method, review flag. |
| VAR-04, VARM-05 (document the extraction method) | **done** | `Extraction/README.md`: method and references; the evaluation command. A held-out score is still missing. |
| VAR-07, VAR-08, VAR-09 | **done** | Transformation descriptions, source and dates at load, results persisted. |
| IND-01..03 | **done** | |
| EL-01..07 | **done** | Versioned builds with hash, per-criterion exclusion counts. |
| ML-01a, ML-01b | **done** | Five routine records written by training; run files downloadable. |
| ML-02, ML-03 | **done** | DEV/PROD tags; cohort link. The extraction ranker can't meet ML-03 (no cohort), so it can't be promoted: decision pending. |
| ML-04, ML-05 | **done, unverified** | Read-only access; notebooks isolated in the `notebooks` container, never started as a real container. |
| MLD-01, MLD-01b | **done** | Promotion checks for technical and clinical validation reports. |
| MLD-03 (weights and OR/HR shown) | **partial** | Coefficients recorded in the METODO_ANALITICO routine; not shown on screen, the check only asks for a report link. |
| MLD-4, MLD-5 | **done** | Estimates carry their version and are stored with it. |
| TRIPOD 20b/20c | **partial** | EDA report covers part of it. |
## What code alone can still close before 2026-11-30
1. Minimal login, users and profiles (or a documented plan).
2. PDF/XLS export of the indicator pages.
3. Coefficients and OR on the model version screen (MLD-03).
4. A user manual for every screen.
5. Run the notebook container for real; rebuild the WebApi image.
Everything else on the missing list (CaMa and TEA models, survival, risk
cut-offs, incidence against state data, a held-out NLP set) needs data or
clinical decisions from the client and should be raised as a dependency.
+4 -4
View File
@@ -5,10 +5,10 @@ Moved from `AGENTS.md` §4 on 2026-11-03.
```bash
(cd Core && uv run pytest -q) # 18 (2 skip)
(cd Persistance && uv run pytest -q) # 18 (1 skip)
(cd Extraction && uv run pytest -q) # 31 (OCR tests need tesseract + spa data)
(cd models && uv run pytest -q) # 41
(cd WebApi && uv sync --extra sql-drivers && uv run pytest -q) # 417 passed, 7 skipped (MySQL live tests; includes webapi.orquestacion's own suite, test_orquestacion_*.py — folded in from the former standalone Orquestacion/ package, 2026-10-31)
(cd WebApp && npx ng test --watch=false && npx ng build) # 1235 (a few vendored indicadores specs time out under heavy load; pass alone)
(cd Extraction && uv run pytest -q) # 83 (OCR tests need tesseract + spa and osd data)
(cd models && uv run pytest -q) # 180 (real Jupyter kernels and a runner process in tests/pipelines/test_experiment.py)
(cd WebApi && uv sync --extra sql-drivers && uv run pytest -q) # 497 passed, 7 skipped (MySQL live tests; includes webapi.orquestacion's own suite, test_orquestacion_*.py — folded in from the former standalone Orquestacion/ package, 2026-10-31)
(cd WebApp && npx ng test --watch=false && npx ng build) # 1248 (a few specs, mostly indicadores, time out under heavy load; pass alone)
```
If a package's `.venv` has stale absolute paths baked into its entry-point
+26
View File
@@ -0,0 +1,26 @@
# TEA FHIR synthetic browser check
Run from a WorkingNarrative checkout whose ISSSTELEON and WebApp gitlinks include the local TEA changes. The script creates a temporary SQLite database from `WebApi/tests/staging/tea.py`; it never imports production data. `DEV_REVISION` enables the simulated patient routes. It serves the Angular build and the real Flask API on a temporary loopback port and closes them after the check.
Prerequisites: Python 3.12, uv, Node and npm, a Chromium-compatible browser, and Playwright available to Node. Install the WebApi dev dependencies and build WebApp. Generate the dbt manifest from this exact Transformation tree:
```sh
cd ISSSTELEON/Transformation
uv run dbt compile --profiles-dir . --profile tea
cd ../WebApi
uv sync --locked
cd ../WebApp
npm ci
npm run build
cd ../..
```
Set `PLAYWRIGHT_PATH` to the installed Playwright module and `BROWSER_PATH` to the browser executable when the defaults in `verify.cjs` do not exist. Then run:
```sh
ISSSTELEON/WebApi/.venv/bin/python e2e/tea-fhir/serve_and_verify.py
```
On Windows use `ISSSTELEON\WebApi\.venv\Scripts\python.exe`. The harness supplies a Windows-only `fcntl` stub that raises if locking is used; it does not verify lock behaviour. `DBT_MANIFEST` is set to `Transformation/target/manifest.json` in the harness before Flask starts. For the API outside the harness, the file must be available inside the API environment at the path set in `DBT_MANIFEST`, and the cycle must create the definitions and event views in the domain database. Migrations alone do not do this. The WebApi image compiles the manifest from `Transformation` while it builds and sets `DBT_MANIFEST` to it (SQLite's SQL); the `indicadores` service runs the cycle after each import.
The browser check covers M28, history, filters, paging, the patient's identity, ADOS-2 and EEG, returning with focus, a partial record and a simulated FHIR 404. Patient selection races and absent/masked values are covered by the focused Angular tests. No EEG alteration validation switch is enabled.
+49
View File
@@ -0,0 +1,49 @@
import os
import subprocess
import sys
import tempfile
import threading
import types
from pathlib import Path
root = Path(__file__).resolve().parents[2]
api = root / 'ISSSTELEON' / 'WebApi'
sys.path[:0] = [str(api), str(api / 'tests')]
if os.name == 'nt':
fcntl = types.ModuleType('fcntl')
def unavailable(*args):
raise RuntimeError('fcntl locking is unavailable in this Windows test')
fcntl.flock, fcntl.LOCK_EX, fcntl.LOCK_UN = unavailable, 2, 8
sys.modules['fcntl'] = fcntl
os.environ['DEV_REVISION'] = 'pruebas'
os.environ['DBT_MANIFEST'] = str(root / 'ISSSTELEON' / 'Transformation' / 'target' / 'manifest.json')
os.environ['MLFLOW_DISABLE_AGENT_HINT'] = '1'
from conftest import base_de
from flask import send_from_directory
from werkzeug.serving import make_server
from webapi import create_app
with tempfile.TemporaryDirectory(prefix='tea-e2e-') as directory:
base = base_de('tea', Path(directory))
base.run('catalogs', 'load', 'views', 'registry', 'definitions', 'event_models', allow_undecided=True)
app = create_app()
static = root / 'ISSSTELEON' / 'WebApp' / 'dist' / 'WebApp' / 'browser'
@app.get('/indicadores/tea')
def page():
return send_from_directory(static, 'index.html')
@app.get('/<path:filename>')
def assets(filename):
return send_from_directory(static, filename)
server = make_server('127.0.0.1', 0, app)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
subprocess.run(['node', str(root / 'e2e' / 'tea-fhir' / 'verify.cjs'), str(server.server_port)], check=True, timeout=90)
finally:
server.shutdown()
thread.join()
base.motor.dispose()
from persistance.db import get_tea_engine
get_tea_engine().dispose()
+70
View File
@@ -0,0 +1,70 @@
const { chromium } = require(process.env.PLAYWRIGHT_PATH || 'C:/Users/angel/.cache/codex-runtimes/codex-primary-runtime/dependencies/node/node_modules/playwright');
(async () => {
const browser = await chromium.launch({ executablePath: process.env.BROWSER_PATH || 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe', headless: true });
try {
const page = await browser.newPage();
const root = `http://127.0.0.1:${process.argv[2]}`;
await page.goto(`${root}/indicadores/tea`);
const m28 = page.locator('article').filter({ has: page.getByRole('heading', { name: 'Casos por estatus' }) });
await m28.getByText('6', { exact: true }).waitFor();
for (const [name, count] of [['Solo M-CHAT','2'], ['Hasta evaluación psicológica','1'], ['Hasta evaluación neuropediátrica','1'], ['Con EEG','2']]) {
const row = m28.locator('dl div').filter({ hasText: name });
if (await row.locator('dd').innerText() !== count) throw new Error(`M28 ${name}`);
}
console.log('M28: 6 casos y cuatro etapas');
await page.getByRole('button', { name: 'Histórico' }).click();
await page.getByRole('heading', { name: 'Casos por estatus' }).first().waitFor();
if (await page.locator('article').count() !== 3) throw new Error('Histórico no devolvió tres periodos');
await page.getByRole('button', { name: 'Seguimiento', exact: true }).click();
await page.getByLabel('Fecha de corte').fill('2025-12-31');
await page.getByRole('button', { name: 'Aplicar filtros' }).click();
await page.getByText('6 episodios', { exact: true }).waitFor();
await page.getByRole('button', { name: 'Siguiente' }).click();
await page.getByText('Página 2', { exact: true }).waitFor();
if (await page.locator('tbody tr').count() !== 1) throw new Error('Paginación incorrecta');
await page.getByRole('button', { name: 'Anterior' }).click();
await page.getByText('Página 1', { exact: true }).waitFor();
await page.getByLabel('Edad al M-CHAT').selectOption('16_23');
await page.locator('select[name=status]').selectOption('finished');
await page.getByRole('button', { name: 'Aplicar filtros' }).click();
await page.getByText('1 episodios', { exact: true }).waitFor();
const button = page.getByRole('button', { name: 'Abrir ficha' });
const patient = await button.getAttribute('data-patient');
await button.click();
await page.getByRole('heading', { name: 'Ficha del paciente' }).waitFor();
await page.getByLabel('Ficha del paciente').getByText(patient, { exact: true }).waitFor();
await page.getByText('Fecha: 2025-05-20').waitFor();
await page.getByText('Calidad: Buena').waitFor();
await page.getByText('Puntaje de severidad (CSS)', { exact: true }).waitFor();
await page.getByRole('button', { name: 'Volver a Seguimiento' }).click();
if (await page.getByLabel('Edad al M-CHAT').inputValue() !== '16_23') throw new Error('Filtro perdido');
await page.waitForFunction(() => document.activeElement?.getAttribute('data-patient') !== null);
console.log('Histórico, filtros, paginación, ficha correcta y retorno con foco');
await page.locator('select[name=status]').selectOption('active');
await page.getByLabel('Edad al M-CHAT').selectOption('');
await page.getByRole('button', { name: 'Aplicar filtros' }).click();
await page.getByText('4 episodios', { exact: true }).waitFor();
const ids = await page.locator('button[data-patient]').evaluateAll(nodes => nodes.map(n => n.getAttribute('data-patient')));
let partial = null;
for (const id of ids) {
const res = await page.request.get(`${root}/tea/fhir/Patient/${id}/$resumen-tea`);
const body = await res.json();
if (!body.entry.some(e => e.resource.resourceType === 'DiagnosticReport')) { partial = id; break; }
}
if (!partial) throw new Error('No se encontró ficha parcial');
await page.locator(`button[data-patient="${partial}"]`).click();
await page.getByText('Sin información de EEG.').waitFor();
await page.getByRole('button', { name: 'Volver a Seguimiento' }).click();
await page.locator('input[name=cssMin]').fill('100');
await page.getByRole('button', { name: 'Aplicar filtros' }).click();
await page.getByText('No hay episodios para la selección.').waitFor();
await page.locator('input[name=cssMin]').fill('');
await page.getByRole('button', { name: 'Aplicar filtros' }).click();
await page.getByText('4 episodios', { exact: true }).waitFor();
await page.route('**/tea/fhir/Patient/*/$resumen-tea', route => route.fulfill({ status: 404, contentType: 'application/fhir+json', body: JSON.stringify({ resourceType: 'OperationOutcome', issue: [{ code: 'not-found', diagnostics: 'Paciente no encontrado' }] }) }));
await page.locator(`button[data-patient="${partial}"]`).click();
await page.getByRole('alert').getByText('Paciente no encontrado').waitFor();
console.log('Ficha parcial y OperationOutcome 404');
} finally { await browser.close(); }
})().catch(error => { console.error(error); process.exit(1); });
+46
View File
@@ -0,0 +1,46 @@
# Settings for the manual deployment (docker-compose.yml in this folder). Docker
# Compose reads it for the values below, and the webapi and indicadores
# containers receive it as their environment.
# --- Project ---
# Prefix of every container, network, volume and image. Change it (and the
# ports) to run a second copy next to this one.
COMPOSE_PROJECT_NAME=isssteleon-manual
# --- Published ports ---
# Address the ports bind to: 0.0.0.0 for every interface, 127.0.0.1 for this
# machine only.
BIND_ADDRESS=0.0.0.0
# The application (nginx: pages and proxy to the API). Open this one.
WEBAPP_PORT=5210
# The API, direct.
WEBAPI_PORT=5211
# The simulated hospital's MySQL (user/password hospital/hospital).
HOSPITAL_PORT=5212
# --- Simulated hospital contents ---
# Patients generated per project, the generator's seed and reference date.
N=200
N_CACU=300
N_CAMA=300
SEMILLA=7
REFERENCIA=2026-01-01
TEA_ALTERACIONES_VALIDADAS=1
# --- Patient-level views ---
# Any value turns on the routes that return one patient's data (the follow-up
# lists, TEA's patient summary). They exist for simulated data only: leave it
# unset on a platform that holds real patients.
DEV_REVISION=manual-deploy
# --- Platform (same variables as ISSSTELEON/.env.example) ---
# Target databases. Unset, each is a SQLite file in this project's
# webapi_data volume.
# CACU_DATABASE_URL=mysql+pymysql://isss_app:CHANGE_ME@db-host:3306/isss_cacu
# CAMA_DATABASE_URL=mysql+pymysql://isss_app:CHANGE_ME@db-host:3306/isss_cama
# TEA_DATABASE_URL=mysql+pymysql://isss_app:CHANGE_ME@db-host:3306/isss_tea
# GOVERNANCE_DATABASE_URL=mysql+pymysql://isss_app:CHANGE_ME@db-host:3306/isss_governance
# WEBAPI_MAX_UPLOAD_MB=200
# WEBAPI_WORKERS=2
# WEBAPI_TIMEOUT=600
# EXTRACTION_OCR_LANG=spa+eng
+1
View File
@@ -0,0 +1 @@
documentos/
+134
View File
@@ -0,0 +1,134 @@
# Manual deployment
The whole platform plus the simulated hospital in one Compose project, built
from the two checkouts next to this folder (`../ISSSTELEON` and `../dev-data`).
Everything here is simulated data.
Run every command from this folder.
## What it starts
| Service | What it is | Published on |
|---|---|---|
| `webapp` | the Angular app behind nginx, which also proxies the API | `WEBAPP_PORT` |
| `webapi`, `indicadores` | the Flask API and the indicator recomputation | `WEBAPI_PORT` |
| `hospital` | MySQL playing the hospital system (`hospital`, `hospital_cacu`, `hospital_cama`) | `HOSPITAL_PORT` |
| `poblar`, `poblar-cacu`, `poblar-cama` | one-shot jobs that generate the hospital's data on `up` | |
| `load` | one-shot job that imports the hospital into the platform | |
| `documentos` | one-shot job that writes the test PDFs | |
Ports, bind address and project name come from `.env`. Change
`COMPOSE_PROJECT_NAME` and the three ports to run a second copy on the same
machine.
## Bring it up and load it
```sh
docker compose up --build -d # platform and hospital; the hospital is populated
docker compose run --rm --build load # import the hospital into the platform
```
`load` prints one line per table (`leídas, nuevas, actualizadas, rechazadas`);
every `rechazadas` should be 0. It needs an empty platform: the hospital's ids
travel with the rows, so a second load is refused without writing anything.
To load again, run `docker compose down -v` first.
```sh
docker compose down # stop, keep the data
docker compose down -v # stop and delete this project's data
```
## Indicators
The measures are defined in dbt (`../ISSSTELEON/Transformation`). The `webapi`
image compiles them into a manifest while it builds and sets `DBT_MANIFEST` to
it; without that variable the API has no measure routes and the pages answer
"No fue posible cargar los indicadores". Check it with:
```sh
curl -s -o /dev/null -w '%{http_code}\n' http://localhost:5210/tea/fhir/Measure # 200
```
After `load`, the `indicadores` service recomputes each project on its own
(it polls every 20 seconds, and a project takes from seconds to a few
minutes). Until it finishes, the pages have no figures. Its state per project:
```sh
curl -s http://localhost:5210/reportes/indicadores # "estado": "ok" when done
docker compose logs -f indicadores
```
A platform that was loaded before the image had the manifest keeps its data
but has nothing computed. Rebuild and ask for the recomputation, once per
project:
```sh
docker compose up --build -d
for p in cacu cama tea; do curl -s -X POST "http://localhost:5210/$p/fhir/Measure/\$recalcular"; done
```
Things to know:
- **The manifest's SQL is SQLite's**, the default engine here. With
`*_DATABASE_URL` on another engine, compile the manifest with that dbt
target (`../ISSSTELEON/Transformation/profiles.yml`), mount it in `webapi`
and `indicadores`, and set `DBT_MANIFEST` to its path.
- **Patient-level pages need `DEV_REVISION`** (set in `.env`): the follow-up
lists and TEA's patient summary are served only with it, because they are
meant for simulated data.
- **A change in `Transformation` needs a rebuild** (`up --build -d`) and a
recomputation, as above.
## Generate the test documents
```sh
docker compose run --rm --build documentos
```
It writes PDFs of the same patients the hospital holds into `./documentos`
(ignored by git). It doesn't need the platform or the hospital to be up: the
documents come from the same generator, seed (`SEMILLA`) and reference date
(`REFERENCIA`) as the hospital's rows, so a patient key in a PDF is a patient
key in the hospital.
| Folder | Documents | How many |
|---|---|---|
| `documentos/cacu/` | CaCu records, one per cytology (`CACU-0002-C1`), 3 to 7 pages: order, cover, cytology form and, when the history has them, HPV result, colposcopy note, pathology report and the note that resolves the cytology | the first `N_DOCUMENTOS_CACU` patients (20) |
| `documentos/tea/` | the ADOS-2 score summary of the psychological evaluation, one page per child with module 1, 2 or 3 (`N-0001-ADOS2`) | all `N` children (200) |
Each record has its own folder:
- CaCu: `<key>_limpio.pdf` (text), `<key>_escaneado.pdf` (every page an
image, no text layer, to exercise OCR), the page images and field masks,
and `ground_truth.json` / `.csv` with each field's value and its box in
both PDFs.
- TEA: `<key>.pdf` with selectable text, not scanned, and its `ground_truth`.
`indice.json` in each folder lists the records.
Things to know:
- **CaCu is heavy by design.** Every page is rasterised and degraded: 12
patients took 28 seconds and 35 MB for 76 pages on the development machine.
Twenty patients give around 30 records; all 300 give 442 records and 1,800
pages, so expect several minutes and close to 1 GB. Raise it for one run
with `N_DOCUMENTOS_CACU=300 docker compose run --rm --build documentos`.
- **Module 3 is rare.** With seed 7 the first child with ADOS-2 module 3 is
number 247, so a hospital of 200 children has none. To see one, generate
with `N=250` or more; those documents have no row in a 200-child hospital.
- **What matches the hospital.** Patient key, dates, cytology and HPV results,
biopsy grade, ICD-10 codes and each ADOS-2 item score are the hospital's.
Names, doctors, vital signs and the wording of notes exist only in the
documents. The ADOS-2 totals add only the items of the child's module; the
platform adds every item the hospital row has, so its totals can be higher.
- **The files belong to root**, because the container writes them. Delete the
folder with `sudo rm -rf documentos`.
- Nothing here loads these PDFs into the platform; `load` only imports the
hospital's tables.
The same documents without Docker, from `../dev-data`:
```sh
uv run python -m dev_data documentos cacu --referencia 2026-01-01 --salida datos/expedientes
uv run python -m dev_data documentos tea --referencia 2026-01-01 --salida datos/ados2
```
+80
View File
@@ -0,0 +1,80 @@
# Manual deployment of the whole platform plus the simulated hospital, built
# from the two checkouts next to this folder (../ISSSTELEON and ../dev-data).
# Ports, bind address and project name come from .env, so several copies can
# run on one machine without touching each other or the other deployments.
#
# docker compose up --build -d # platform + hospital, hospital populated
# docker compose run --rm --build load # import the hospital into the platform
# docker compose run --rm --build documentos # write the test PDFs to ./documentos
# docker compose down # stop, keep the data
# docker compose down -v # stop and delete this project's data
#
# Run from this folder. `load` needs an empty platform: the hospital's ids
# travel with the rows, so a second load is refused without writing anything.
# To load again, `down -v` first. README.md has the whole walkthrough.
include:
- path:
- ../ISSSTELEON/docker-compose.yml
- platform.override.yml
project_directory: ../ISSSTELEON
env_file: .env
- path:
- ../dev-data/compose.prueba.yml
- hospital.override.yml
project_directory: ../dev-data
env_file: .env
services:
# One-shot: imports the three projects through the platform's import API.
# Inside the project network the API is the webapp proxy and the hospital
# is reached by service name, as the webapi container sees it.
load:
build:
context: ..
dockerfile: dev-data/Dockerfile
profiles: [load]
depends_on:
webapi:
condition: service_healthy
webapp:
condition: service_started
poblar:
condition: service_completed_successfully
poblar-cacu:
condition: service_completed_successfully
poblar-cama:
condition: service_completed_successfully
entrypoint: ["sh", "-c"]
command:
- |
set -eu
for pair in cacu:hospital_cacu cama:hospital_cama tea:hospital; do
project="$${pair%%:*}"
database="$${pair#*:}"
echo "== $$project"
uv run --frozen --no-dev python -m dev_data cargar "$$project" \
--api http://webapp \
--hospital "mysql+pymysql://hospital:hospital@hospital:3306/$$database"
done
# One-shot: writes the test PDFs of the same patients the hospital holds
# (same seed and reference date) into ./documentos. It needs neither the
# platform nor the hospital. CaCu pages are rasterised and degraded, which
# is slow and large, so its count is separate from the hospital's.
documentos:
build:
context: ..
dockerfile: dev-data/Dockerfile
profiles: [documentos]
volumes:
- ./documentos:/documentos
entrypoint: ["sh", "-c"]
command:
- |
set -eu
uv run --frozen --no-dev python -m dev_data documentos cacu \
--n "${N_DOCUMENTOS_CACU:-20}" --semilla "${SEMILLA:-7}" --referencia "${REFERENCIA:-2026-01-01}" \
--salida /documentos/cacu
uv run --frozen --no-dev python -m dev_data documentos tea \
--n "${N:-200}" --semilla "${SEMILLA:-7}" --referencia "${REFERENCIA:-2026-01-01}" \
--salida /documentos/tea
+16
View File
@@ -0,0 +1,16 @@
# Applied over ../dev-data/compose.prueba.yml. The platform reaches the
# hospital by service name; the published port is only for inspecting it
# from outside with a MySQL client.
services:
hospital:
ports: !override
- "${BIND_ADDRESS:-0.0.0.0}:${HOSPITAL_PORT:-29505}:3306"
# Without their profile the populate jobs run on every `up`. They leave a
# hospital that already has rows alone.
poblar:
profiles: !reset []
poblar-cacu:
profiles: !reset []
poblar-cama:
profiles: !reset []
+25
View File
@@ -0,0 +1,25 @@
# Applied over ../ISSSTELEON/docker-compose.yml. Paths here resolve from
# ../ISSSTELEON.
#
# Images are tagged per project so a build here doesn't replace the
# isssteleon/*:dev images other deployments run. The containers read
# manual-deploy/.env instead of ISSSTELEON/.env, so a .env left in the source
# tree never points this stack at another deployment's databases.
x-api: &api
image: ${COMPOSE_PROJECT_NAME}/webapi:local
env_file: !override
- ../manual-deploy/.env
services:
webapi:
<<: *api
ports: !override
- "${BIND_ADDRESS:-0.0.0.0}:${WEBAPI_PORT:-25050}:5000"
indicadores:
<<: *api
webapp:
image: ${COMPOSE_PROJECT_NAME}/webapp:local
ports: !override
- "${BIND_ADDRESS:-0.0.0.0}:${WEBAPP_PORT:-28080}:80"
@@ -0,0 +1,306 @@
# TEA redesign: what was added, and the state machines in the code
Implementation of `WorkingNarrative/plans/kit-exit/tea-redesign.md` (all but the WebApp), 2026-11-12.
- **Where:** `/home/admon/alberto/WorkingNarrative/ISSSTELEON`, branch `feature/163-tea-redesign` in ISSSTELEON,
WebApi, models and indicadores_kit, cut from `refactor/kit-exit` (the plan builds on its dbt semantic layer and
measure engine, which `dev` doesn't have). WebApp untouched.
- **State:** nothing committed (AGENTS.md rule 1). Open items are recorded in
`WorkingNarrative/docs/ledgers/open-items.md`, which is modified in the outer repo, on `main`.
- **Size:** ISSSTELEON 13 files changed (+528 −1385) plus 30 new; WebApi 37 changed (+475 −793) plus 18 new;
models 2; indicadores_kit 2.
---
## 1. Additions and changes, by layer
### 1.1 Bronze: TEA staging (Core, Persistance)
| File | Change |
|---|---|
| `Core/core/tea/models.py` | Rewritten: 8 tables instead of 10, 76 columns instead of 275. `pacientes`, `ordenes_estudio`, `mchat`, `ados2` (28 items, constant `ADOS2_ITEMS`), `evaluacion_neuropediatrica`, `eeg` (EDF, channels, duration, sleep, 5 quality criteria), `eeg_metrica`, `eeg_metrica_electrodo` |
| `Core/core/tea/enums.py` | Trimmed to `TipoEstudio` (ADOS2, NEUROPEDIATRIA, EEG) with aliases, `ModuloAdos2`, `ClasificacionAdos2` with aliases, `MetricaEeg`, `ELECTRODOS_10_20` |
| `Core/spec/tablas_TEA.md` | Data dictionary rewritten for the 8 tables (Spanish, as before) |
| `Core/core/catalogos/tea.toml` | Rewritten: studies `mchat`, `ados2` (module, algorithm, CSS, classification, 28 items with labels), `evaluacion_neuropediatrica` (ICD-10), `eeg` (sleep, channels, duration, 5 criteria, 5 metrics), `orden` |
| `Core/tests/test_models.py` | TEA's table set |
| `Persistance/persistance/tea/alembic/versions/f2b6d1e8c934_tea_staging_by_study.py` | **New revision** after the baseline: creates the 6 new tables, drops the 8 old ones, drops the unused columns of `pacientes` and `ordenes_estudio` (keeping their rows) and maps the old study codes to the new ones; downgrade restores everything with generic types. Round trip checked on SQLite; `alembic check` clean |
| `Persistance/persistance/tea/__init__.py` | Repositories for the 8 tables |
| `Persistance/persistance/edges/silver/procedures.py` | An observation whose procedure isn't in silver is skipped and counted (it used to raise `KeyError`) |
| `Persistance/persistance/edges/gold/history.py` | `group_counts`: a stored answer's units per group (for M30) |
### 1.2 Import (WebApi)
| File | Change |
|---|---|
| `webapi/imports/schemas/tea/` | New: `mchat.py`, `ados2.py`, `evaluacion_neuropediatrica.py` (ICD-10 with or without the dot), `eeg.py`, `eeg_metrica.py`, `eeg_metrica_electrodo.py`. `pacientes.py` and `ordenes_estudio.py` rewritten. The 8 old schemas deleted |
| `webapi/imports/schemas/coercion.py` | `Bounded(kind, low, high)`: numbers out of range are a validation error (M-CHAT 0–20, CSS 1–10, items 0–3, channels) |
| `webapi/imports/schemas/registry.py` | TEA's 8 targets (`tea.Mchat`, `tea.Ados2`, `tea.EvaluacionNeuropediatrica`, `tea.Eeg`, `tea.EegMetrica`, `tea.EegMetricaElectrodo`, …) |
| `webapi/imports/connectors/edf.py` | Shaped for `tea.Eeg`: lab id, patient, date, channels, duration and the file |
### 1.3 Silver (WebApi orchestration)
| File | Change |
|---|---|
| `webapi/orchestration/silver/tea.py` | **New**: TEA's `DESDE_STAGING`: order → `orden` of the study it asks for; M-CHAT → `toma`; ADOS-2 and note → `encuentro`; EEG → `toma`; metric → observation on its EEG's `toma`; electrode value → `parte` of the EEG |
| `webapi/orchestration/silver/procedures.py` | Two generic additions to `DeStaging`: `juntas` (columns from another staging row by key, null-filled when missing) and `observa_en` (observations on another row's procedure); result templates can name content columns (`eeg.{metrica}`) |
| `webapi/orchestration/tables/tea.py` | **New**: TEA's `TablasKit` and `COHORTES` |
| `tables/__init__.py`, `orchestration/__main__.py`, `recomputation.py`, `webapi/__init__.py` | `tea` added to the domain lists; the KPI and FHIR blueprints registered for TEA |
| `webapi/orchestration/reference/parametros.toml` | The 18 TEA keys of §7.2 removed; `tea.cohorte.ventanas` set to the page's windows (16–23, 24–29, 30–36) |
### 1.4 dbt (Transformation)
| File | Change |
|---|---|
| `dbt_project.yml` | Var `tea`: ages, `dias_por_mes`, `ventanas`, `cie_tea: [F840]`, `alteracion_z`, quality thresholds and the metric reference ranges (placeholders until validated) |
| `macros/tea.sql` | **New**: `tea_meses_cumplidos` (per engine), `tea_grupo_edad`, `tea_criterio_bueno`, `tea_despues` (no `GREATEST` on SQL Server 2016) |
| `models/tea/silver/tea_linea_de_tiempo.yml` | 29 sources → 5 (mchat, ados2, evaluacion_neuropediatrica, eeg, orden) |
| `models/tea/silver/` (ephemeral, new) | `tea_mchat`, `tea_ados2`, `tea_ados2_reactivos`, `tea_neuropediatria`, `tea_eegs`, `tea_eeg_referencias`, `tea_eeg_metricas`, `tea_eeg_electrodos`, `tea_cohorte`, `tea_hitos` (each child's step dates and when they became known) |
| `models/tea/gold/eventos/` (views, new) | `tea_pasos` (M28), `tea_diagnosticos` (M23, M24, M21, M22), `tea_casos` (M26, M27, M25), `tea_eegs_periodo` (M29), `tea_alteraciones` (M30), each with its semantic model and metrics |
| `models/tea/gold/seguimiento/` (views, new) | `tea_seguimiento`, `tea_paciente_ados2`, `tea_paciente_eegs`, `tea_paciente_eeg_metricas`, `tea_paciente_eeg_electrodos`, marked `lee_la_webapi` so the cycle creates them |
### 1.5 The ten measures
| Measure | Event model | Scoring | Construct |
|---|---|---|---|
| M28 `casos_por_estado` | `tea_pasos` | composition (C2) | status at the period's end |
| M23 `pacientes_evaluados` | `tea_diagnosticos` | composition, admits CONFIRMADO and EN_PROCESO | status at the period's end |
| M24 `confirmacion_diagnostico` | `tea_diagnosticos` | proportion with `denominator-exclusion` (SIN_TEA) | status + `grupo_edad` column stratum |
| M21 / M22 `diagnosticados_con/sin_eeg` | `tea_diagnosticos` | proportion | status + EEG reached (or not) by the period's end + stratum |
| M26 / M27 / M25 day counts | `tea_casos` | continuous variable | status; a value only if the interval ended by the period's end |
| M29 `calidad_eeg` | `tea_eegs_periodo` | composition by exam | events in the period |
| M30 `resultado_eeg` | `tea_alteraciones` | proportion + one group per alteration | several groups |
### 1.6 Measure engine (WebApi)
| File | Change |
|---|---|
| `webapi/metrics.py` | `StatusAtEnd` (`meta.poblacion`): each unit that entered by the period's end and hadn't left before its start, with its highest-order row dated by the end and known by the cut-offs; `ReachedByEnd` (`meta.al_fin`); column stratum (`tipo: columna`); `Group` (`meta.grupos`) answered one by one and stored by group; exclusion count (`meta.exclusion`); `meta` kept on the definition |
| `webapi/compositions.py`, `webapi/durations.py` | Take `StatusAtEnd`; a duration's value must have ended before the period's end |
| `webapi/orchestration/semantic_layer.py` | The publication catalog lists M30's groups and the exclusion population; the cycle creates the `lee_la_webapi` views |
### 1.7 FHIR R4 (WebApi, new package `webapi/fhir/`)
| File | What it serves |
|---|---|
| `common.py` | `application/fhir+json`, `OperationOutcome`, searchset with `self`/`next`/`previous`, `_count` (≤200) and `_offset`, the `simulado` tag, canonical URLs |
| `measures.py` | `Measure` from each metric's meta (title, description, scoring, populations with their dbt metric, strata, period types, figures, category labels and colors); `MeasureReport` with an absolute canonical, `group.code`, codings, C2 as `cohort` with categories as a stratifier (`stratum.component` with strata), several groups, exclusion, durations with `measure-population-exclusion`. FHIR ids use `-` instead of `_` |
| `terminology.py`, `tea_eeg.toml` | `CodeSystem`s: the domain's catalog, stages, diagnostic results, EEG quality, metrics with their effect texts, 10-20 electrodes, age groups; `ValueSet/tea-alteracion` |
| `tea.py` | Seguimiento as `EpisodeOfCare` (+ `CarePlan`, `Patient`, M-CHAT, `Condition`, EEG `Procedure` + `DiagnosticReport` + quality observations); metric and electrode observations; ADOS-2 with components; the `$resumen-tea` collection |
| `__init__.py` | `/<domain>/fhir/`: `metadata`, `Measure`, `Measure/<id>`, `$evaluate-measure`, `MeasureReport` search (`periodo`, or `tipo-periodo` + `period=ge/le`), `POST Measure/$recalcular`, `CodeSystem`; for TEA in DEV: `EpisodeOfCare` (filters `status`, `date`, `etapa`, `fecha-etapa`, `grupo-edad`, `mchat`, `css`, `resultado-eeg`, `alteracion`; `_include`), `EpisodeOfCare/$resumen-eeg`, `Patient/<pseudonym>/$resumen-tea`, `ValueSet/tea-alteracion` |
- **Alterations:** hidden until `TEA_ALTERACIONES_VALIDADAS=1`. That covers M30, the alteration filter, the normal/abnormal split and the metric and electrode observations.
- **Old routes:** `/<domain>/indicadores` stays as it is.
### 1.8 Tests (WebApi)
| File | What it covers |
|---|---|
| `tests/staging/tea.py` | **New** fixture: seven children, one per rule of the chain |
| `tests/test_tea_measures.py` | **New**, 48 cases: the ten measures by month and semester, event and knowledge cut-offs, M30 read back from the history |
| `tests/test_fhir_tea.py` | **New**, 19 cases: every response checked against FHIR models |
| `tests/test_fhir_measures.py` | **New**: CaCu's and CaMa's measures in FHIR |
| `conftest.py`, `test_orquestacion_*`, `test_imports_*`, `test_new_sources.py`, `test_schemas*.py`, `test_source_ids.py` | TEA added to the cycle tests and moved to the new tables |
| `pyproject.toml`, `uv.lock` | `fhir.resources` 8.3 in the dev group (needs the owner's approval) |
Results:
- WebApi: 404 passed, 10 failed (tesseract and the SQL Server driver are missing; the same 10 fail without these changes).
- Core: 18 passed. Persistance: 48 passed.
- `dbt build --select tea` passes on SQLite.
### 1.9 Removed
- `models/models/tea/` (empty stub).
- `indicadores_kit/scripts/equivalencia_tea.py` (it imported kit code that no longer exists) and its README mentions.
- The sentence in `models/cohorts/cama/screening.py` that cited the retired TEA cohort.
- The 8 old TEA import schemas and the §7.2 parameters.
---
## 2. State machines, as the code implements them
Nothing stores a state: each state is derived from dated facts at a date. For the measures that date is the
period's end, under the question's event and knowledge cut-offs; for Seguimiento and the summary it's the cut-off
(by default, today).
### 2.1 A child's screening
**Source:** `models/tea/silver/tea_cohorte.sql`, `tea_hitos.sql`, `gold/eventos/tea_pasos.sql`; `webapi/metrics.py`
(`StatusAtEnd`); `webapi/fhir/tea.py` (`Episode`).
```mermaid
stateDiagram-v2
[*] --> FUERA_DE_COHORTE: first M-CHAT outside 16–36 months
[*] --> SOLO_MCHAT: first M-CHAT at 16–36 months, or no birth date
SOLO_MCHAT --> PSICOLOGIA: first ADOS-2
PSICOLOGIA --> NEUROPEDIATRIA: first neuropediatrics note (any diagnosis)
NEUROPEDIATRIA --> EEG: first good-quality EEG
EEG --> COMPLETADO: end of the period of that EEG
FUERA_DE_COHORTE --> [*]
COMPLETADO --> [*]
```
| Rule | In the code |
|---|---|
| Who enters | `tea_cohorte.en_cohorte = 1`: completed months at the first M-CHAT (days / 30.4375, rounded to one decimal, truncated) between 16 and 36, or unknown age (`grupo_edad = 'sin_dato'`) |
| Steps go in order | `tea_despues(previous, own)`: a step is dated by the later of its first fact and the previous step, and is null without the previous one. An EEG before the note counts from the note's date |
| What was known at a date | `tea_versiones`: one version of the child per load that brought one of its facts. `tea_cohorte` and `tea_hitos` have one row per child and version, built from the facts known by it, so the first M-CHAT, ADOS-2, note and good EEG are the first known then. The engine takes each child's latest version by the knowledge cut-off (`meta.version_conocida`) |
| Entry and exit | `ingreso` = first M-CHAT; `salida` = the EEG step (null if never reached) |
| Who a period counts | `ingreso < period end` and not (`salida` before the period's start, dated by the event cut-off and known by the knowledge cut-off) |
| A period's category | The highest-order step (`paso_orden` 1–4) dated before the period's end and known by the cut-offs |
| No exit | Without a good EEG in the chain (no ADOS-2, no note, only bad EEGs) the child stays in every period |
| Seguimiento | `Episode`: stage = furthest step dated by the cut-off, `fecha_etapa` its date, `pendientes` the rest. `EpisodeOfCare.status` is `finished` once the EEG step is reached by the cut-off, `active` before. The `date=ge…` window leaves out episodes finished before it |
Stage codes in the code: `SOLO_MCHAT`, `PSICOLOGIA`, `NEUROPEDIATRIA`, `EEG` (the page's codes). `COMPLETADO` and
`FUERA_DE_COHORTE` are never stored: the first is "not counted after the period of the exit", the second
"filtered out by `en_cohorte`".
### 2.2 The diagnostic result
**Source:** `tea_neuropediatria.sql` (`es_tea`: ICD-10 without the dot, exactly in `cie_tea`), `tea_hitos.sql`
(`fecha_tea`, `fecha_sin_tea`), `gold/eventos/tea_diagnosticos.sql`; `Episode.diagnosis`.
```mermaid
stateDiagram-v2
[*] --> EN_PROCESO: first M-CHAT
EN_PROCESO --> SIN_TEA: first note without F84.0
EN_PROCESO --> CONFIRMADO: first note with F84.0
SIN_TEA --> CONFIRMADO: a later note with F84.0
```
| State | Order | Counted in |
|---|---|---|
| `EN_PROCESO` | 1 | M23 (in process), M24 denominator |
| `SIN_TEA` | 2 | M24 `denominator-exclusion`; out of M23; still in the screening |
| `CONFIRMADO` | 3 | M23, M24 numerator and denominator, base of M21/M22, event of M25 |
- **Highest order wins:** at each date the state is the one of highest order, so `CONFIRMADO` is final. A note without F84.0 after it changes nothing.
- **Within the chain:** a note counts from the psychology step on, so a F84.0 note without the ADOS-2 leaves the child in process (child 5 in the fixture). F84 without its subcode is `SIN_TEA`.
- **Seguimiento:** `diagnostico_tea` is `true` with a F84.0 note by the cut-off, `false` with notes but none with F84.0, and `null` without a note.
### 2.3 One EEG's quality
**Source:** `tea_eegs.sql`, `tea_paciente_eegs.sql` (`<criterion>_bueno` per criterion), thresholds in var
`tea.calidad`.
```mermaid
stateDiagram-v2
[*] --> SIN_ANALIZAR: loaded, no criterion written
SIN_ANALIZAR --> BUENO: every criterion within its threshold
SIN_ANALIZAR --> MALO: some criterion missing or over its threshold
BUENO --> MALO: re-analysis or new thresholds
MALO --> BUENO: re-analysis or new thresholds
```
| State | `valido` | Feeds |
|---|---|---|
| `SIN_ANALIZAR` | 0 | M29 (third category); moves nothing else |
| `BUENO` | 1 | M29; may become the study EEG and complete the chain |
| `MALO` | 0 | M29; no result, its alterations don't count |
- **Recomputed, never stored:** the quality is recomputed from the criteria on every answer, so new thresholds in var `tea` move EEGs between `BUENO` and `MALO`.
- **A missing criterion counts as bad** once any criterion has been written.
### 2.4 A child's study EEG
**Source:** `tea_hitos.primer_bueno` (for the measures), `Episode.study_eeg` (for Seguimiento and the summary, at the
cut-off).
```mermaid
stateDiagram-v2
[*] --> SIN_EEG
SIN_EEG --> SOLO_MALOS: a bad or unanalysed EEG
SIN_EEG --> CON_EEG_DEL_ESTUDIO: a good EEG
SOLO_MALOS --> CON_EEG_DEL_ESTUDIO: a good EEG
CON_EEG_DEL_ESTUDIO --> CON_EEG_DEL_ESTUDIO: any later EEG (ignored)
```
| State | Shown | Alterations |
|---|---|---|
| `SIN_EEG` | No EEG | None |
| `SOLO_MALOS` | The latest EEG, `conclusionCode` MALO and «no es válido para el estudio» | None |
| `CON_EEG_DEL_ESTUDIO` | The first good EEG (two on the same day: the first written) | That EEG's, once each; M30 counts it in its period |
- **Not tied to the chain:** the study EEG is the first good EEG whether or not the chain reached it. Child 5 has a study EEG and M30 counts it, but its chain never reaches the EEG step.
- **Same event as the chain's end only when the note is there:** entering `CON_EEG_DEL_ESTUDIO` moves the screening (§2.1) to `EEG` only if the neuropediatrics note already exists; otherwise the EEG step is dated by the note when it arrives.
### 2.5 A metric of the EEG
**Source:** `tea_eeg_metricas.sql`: age group at the EEG, reference range from `tea_eeg_referencias` (var
`tea.referencias`), mean = middle of the range, SD = a quarter of its width.
```mermaid
stateDiagram-v2
[*] --> no_evaluable: null value, or no reference for the age
[*] --> normal: |z| < alteracion_z
[*] --> aumentado: z ≥ alteracion_z
[*] --> disminuido: z ≤ −alteracion_z
```
- **Used in:** `tea_alteraciones` (M30 and its groups), `Episode.alterations`, and the metric observations (`interpretation` H, L or N, or `dataAbsentReason` for `no_evaluable`).
- **Only a good EEG counts:** a bad EEG's metrics are stored but never read as alterations.
### 2.6 Showing the alterations
**Source:** `webapi/fhir/tea.py` (`alterations_validated`); the M30 metric's `meta.requiere_validacion`.
```mermaid
stateDiagram-v2
[*] --> PROVISIONAL
PROVISIONAL --> VALIDADO: TEA_ALTERACIONES_VALIDADAS=1
VALIDADO --> PROVISIONAL: variable removed
```
| State | FHIR answers |
|---|---|
| `PROVISIONAL` | No M30 (`Measure` 404); `alteracion` filter refused (403); `$resumen-eeg` gives only `con_eeg_valido` / `sin_eeg_valido`; `resultado-eeg` only `valido` / `sin-eeg-valido`; no metric or electrode observations |
| `VALIDADO` | Everything: M30, the filter, `normales`/`anormales`/`por_alteracion`, metrics and electrodes |
In the code it's an environment variable, so it can go back to `PROVISIONAL`. The plan wants that to need the domain
expert, which is a process rule, not a code one.
### 2.7 A measure's answer for a period
**Source:** `webapi/metrics.py` (`key_of`, `answer`), `persistance/edges/gold/history.py` (`find`, `record`,
`counts`, `group_counts`).
```mermaid
stateDiagram-v2
[*] --> SIN_RESPUESTA
SIN_RESPUESTA --> RESPONDIDA: first question (computed and recorded)
RESPONDIDA --> RESPONDIDA: same key again (read from the history)
RESPONDIDA --> SIN_RESPUESTA: a new load (new knowledge cut-off) or a new definition
```
- **The key:** measure, version, metric, period, both cut-offs, rule values and strata, hashed with SHA-256.
- **An old cut-off keeps its answer:** asked as of an earlier load, a child is read in the version known then, so a
later load with earlier-dated facts doesn't change it.
- **Why a new load means a new answer:** by default the knowledge cut-off is the start of the last load, so a new load is a new key. A change to dbt's models or to var `tea` changes the model's checksum or version, and so the answer.
- **The old answer stays** in the history.
### 2.8 One staging row through the silver load
**Source:** `webapi/orchestration/silver/procedures.py`, `persistance/edges/silver/procedures.py`.
```mermaid
stateDiagram-v2
[*] --> DESCARTADA: study code outside the catalog
[*] --> NUEVO: logical key not in silver
[*] --> HUERFANO: no patient and no parent (e.g. electrode without its metric)
NUEVO --> SIN_CAMBIO: same row loaded again
SIN_CAMBIO --> CAMBIADO: a column or observation changed
CAMBIADO --> SIN_CAMBIO: loaded again without changes
```
- **Counted in `carga`:** new, changed and unchanged procedures; discards and orphans by reason.
- **`observa_en` rows** (EEG metrics) give no procedure of their own: their observations go on the EEG's `toma`, and are skipped and logged when that EEG isn't in silver.
### 2.9 Where the code differs from the plan's §13
- **The first good EEG.** In §13.4 the study EEG and the one that completes the chain are the same event. In the
code the study EEG is the first good one overall, while the chain's EEG step is dated by the later of it and the
note. A child with a good EEG but no ADOS-2 has a study EEG (M30, the summary) but never leaves the screening,
and its note doesn't confirm it either: it stays in process.
- **`SIN_ANALIZAR` in M29.** It shows as its own category; this was the open question in §10.
- **The alteration switch.** It is an environment variable and can go back to `PROVISIONAL`.
- **Without a birth date.** The child is in the cohort with `sin_dato`, as §5 says, whereas the §13.1 diagram only
draws «16 to 36 months».
+671
View File
@@ -0,0 +1,671 @@
# TEA redesign: a trimmed schema, the new definitions and the unused indicators removed
Proposal, 2026-11-10, for the owner. It replaces the parts of [`tea-port.md`](tea-port.md) that port the kit's TEA
as it is: the ten staging tables, the five measures M21 to M25 with their October definitions, and R01. Nothing here
is implemented yet.
The target is what the TEA page shows today in the WebApp and the mock API: indicators M21 to M30, the period
summary, Histórico, Seguimiento and the patient summary. Their definitions are the team's (#indicadores-tea,
10 Nov 2026). Everything the page doesn't need is dropped, from staging to gold.
---
## 1. The definitions this design serves
- **The cohort** is the children whose first M-CHAT was at 16 to 36 completed months (owner, 2026-11-11).
- **A period counts every cohort child who is in the screening during it**: entered by the period's end (first M-CHAT
on or before it) and not finished before the period's start, whether or not anything of theirs happened in the
period.
- **A child leaves after completing the chain** (owner, 2026-11-11). The period of their good-quality EEG is the last
one that counts them, with stage EEG; from the next period on they're no longer pending and don't appear.
- **A child who never gets a good EEG stays in the screening** (owner, 2026-11-11): one with a neuropediatrics note
without F84.0, one who stops coming back, one who ages past 36 months. They're counted in every period from their
entry on, so M22 and the in-process counts of M23 and M28 grow with them.
- **Each child's stage in a period is the furthest step reached by the period's end**: the steps dated on or before
it and known at the report's cut-off. Steps go in order (M-CHAT, psychology note (ADOS-2), neuropediatrics note,
good-quality EEG) and each needs the previous one. A child can be in process in one period and further on in a
later one.
- Example, by month: ADOS-2 in September, nothing in October, good EEG in December. September and October count the
child at the psychology stage (a neuropediatrics note in November would make November's stage neuropediatrics);
December counts them at EEG; from January on they no longer appear.
- These rules hold for M28, M23, M24, M21 and M22. M29 and M30 count the EEG of the period instead (table below).
- **The day counts (M26, M27, M25) take the period's children whose interval ended on or before the period's end**
(owner, 2026-11-11). A child's days repeat in every period that counts them; the others count as without event.
- **Only a good-quality EEG counts as an EEG**, everywhere except M29. An EEG is bad when any of its quality criteria
is; a bad EEG has no result and its alterations don't count.
- **A patient's alterations are those of their first good-quality EEG** (owner, 2026-11-11). Later EEGs, good or
bad, don't change them. Each alteration counts once per patient; a patient can have several, so the alterations
don't add up. The first good EEG is also the one that completes the chain.
- **The age group is the age at the patient's first M-CHAT** (owner, 2026-11-10): from `pac_fecha_nacimiento` to
that date, in completed months (days / 30.4375, rounded to one decimal, then truncated, as the kit does), placed in
the page's windows: 16 to 23, 24 to 29 and 30 to 36 months. It is one value per patient, the same in every period
they are counted in, and it also decides who is in the cohort. The EEG reference ranges are the exception: they take the age at the EEG date.
| Measure | Contract | Unit | What it counts | EEG analysis |
|---|---|---|---|---|
| M28 `casos_por_estado` | C2 | patient | The cohort children entered by the period's end, by their stage at that end | Yes: the EEG stage counts only a graded, good EEG |
| M21 `diagnosticados_con_eeg` | C1 | patient | Of the confirmed (F84.0 by neuropediatrics), those with a good EEG; stratified by age group | Yes: a good EEG is the numerator |
| M22 `diagnosticados_sin_eeg` | C1 | patient | The complement of M21 | Yes: the complement of M21 |
| M23 `pacientes_evaluados` | C2 | patient | Confirmed, and in process (no neuropediatrics note yet); a note without F84.0 doesn't count | Indirectly: who is counted (a child leaves after their first good EEG) |
| M24 `confirmacion_diagnostico` | C1 | patient | Confirmed out of confirmed plus in process; stratified by age group | Indirectly: who is counted |
| M26 `dias_mchat_ados2` | C3r | patient | Days from the M-CHAT to the psychology note | Indirectly: who is counted |
| M27 `dias_ados2_diagnostico` | C3r | patient | Days from the psychology note to the neuropediatrics note | Indirectly: who is counted |
| M25 `dias_mchat_diagnostico` | C3r | patient | Days from the M-CHAT to the F84.0 note | Indirectly: who is counted |
| M29 `calidad_eeg` | C2 | exam | The period's EEG, good or bad | Yes: the quality rating |
| M30 `resultado_eeg` | C1 | patient | Of the patients whose first good EEG falls in the period, those with any alteration in it; one group per alteration | Yes: the quality and the alterations |
The out-of-protocol rule (M-CHAT of 2 or less, or ADOS-2 «no espectro») and the 30 days between ADOS-2 and EEG are
gone.
These definitions hold over the earlier ones of #128 to #131 (owner, 2026-11-10). A confirmation is F84.0 exactly:
F84 without the subcode doesn't count, so `cie_tea` is `[F840]`.
### What depends on the EEG analysis
The EEG analysis reads each EDF and writes its quality criteria, channels, duration, sleep, metrics and electrode
values back to bronze. Whatever reads a good EEG, or its metrics, waits for it; those rows are tagged **[EEG
analysis]** below.
- **Stored by it:** in `eeg`, `eeg_con_sueno`, `eeg_canales`, `eeg_duracion_min` and the five criteria; all of
`eeg_metrica` and `eeg_metrica_electrodo` (§2), and their silver observations (§3).
- **Derived from it:** the EEG's quality and validity (`tea_eegs`), its metrics against the references
(`tea_eeg_metricas`) (§4), and the gold models that use them: `tea_pasos` (the EEG step), `tea_eegs_periodo` and
`tea_alteraciones` (§5).
- **Measures:** M29 and M30 directly; M28, M21 and M22 through the EEG stage; M23, M24, M25, M26 and M27 through who
is counted, since a child leaves after their first good EEG (the table's last column).
- **Seguimiento and the patient summary (§6):** `etapa`, `fecha_etapa`, `pendientes`, `fecha_eeg`, `calidad_eeg`,
`alteraciones_eeg` and `alteraciones`, the EEG summary and its alteration filter; the summary's quality panel,
alterations and map.
- **FHIR (§12.3):** the quality, metric and electrode `Observation`s, and the report's `conclusionCode`.
What doesn't: the M-CHAT, the ADOS-2, the neuropediatrics note and the orders, and the age group.
---
## 2. Bronze: TEA staging (Core, Alembic)
Eight tables replace the current ten; 76 columns instead of 275. Each study table holds one kind of study, so the
instrument and specialty columns go. Prefixes follow the schema's convention.
| Table | Columns |
|---|---|
| `pacientes` | `pac_id` PK, `pac_id_hospital`, `pac_fecha_nacimiento` |
| `ordenes_estudio` | `ord_id` PK, `ord_pac_id`, `ord_id_hospital` (bounded, indexed: the merge key), `ord_tipo_estudio` (`ADOS2`, `NEUROPEDIATRIA`, `EEG`), `ord_fecha` |
| `mchat` | `mch_id` PK, `mch_pac_id`, `mch_ord_id` (usually null), `mch_fecha`, `mch_puntaje` (0 to 20) |
| `ados2` | `ado_id` PK, `ado_pac_id`, `ado_ord_id`, `ado_fecha`, `ado_modulo`, `ado_algoritmo`, `ado_css` (1 to 10), `ado_clasificacion`, and the 29 item columns `ado_sa_a2` … `ado_sa_b18`, `ado_rrb_a3` … `ado_rrb_d5` (0 to 3) |
| `evaluacion_neuropediatrica` | `neu_id` PK, `neu_pac_id`, `neu_ord_id`, `neu_fecha`, `neu_cie_codigo` |
| `eeg` | `eeg_id` PK, `eeg_pac_id`, `eeg_ord_id`, `eeg_id_registro_laboratorio` (bounded, indexed), `eeg_fecha_estudio`, `eeg_con_sueno`, `eeg_canales`, `eeg_duracion_min`, `eeg_canales_amplitud`, `eeg_canales_alta_frecuencia`, `eeg_canales_correlacion`, `eeg_canales_sin_senal`, `eeg_ruido_linea_db`, `eeg_estudio` (`FileBlob`, the EDF) **[EEG analysis]** |
| `eeg_metrica` | `met_id` PK, `met_eeg_id`, `met_codigo` (`RITMO_POSTERIOR`, `HUSOS_SUENO_N2`, `HUSOS_SUENO_N3`, `PICOS_PAROXISTICOS`, `GRADIENTE_ANTEROPOSTERIOR`), `met_valor` (null: not evaluable) **[EEG analysis]** |
| `eeg_metrica_electrodo` | `mel_id` PK, `mel_met_id`, `mel_electrodo`, `mel_valor` **[EEG analysis]** |
Notes:
- The ADOS-2 domain subtotals and total aren't stored: they're sums of the items' algorithm scores, which is what the
WebApp checks. `ado_algoritmo` is new: within a module it depends on the language level (item A1), which no
column holds.
- `eeg_utilizable` goes: a valid EEG is a good one, and quality comes from the five criteria. The EEG processing
(EDF to criteria, metrics and electrode values) writes `eeg_canales`, `eeg_duracion_min`, the criteria and the two
metric tables; nothing downstream opens the EDF.
- Only measured values are stored. The z-score and the state of a metric come from reference ranges by age group,
which are still pending medical review (§5).
---
## 3. Silver: the generic tables (Python load, `webapi/orchestration/silver/tea.py`)
Eight `DeStaging` instead of ten, into `procedimiento` and `observacion_clinica`:
| Bronze | `procedimiento` (study, class, parent) | `observacion_clinica` |
|---|---|---|
| `pacientes` | `persona` (`sexo` null) | |
| `ordenes_estudio` | `orden`, study from `ord_tipo_estudio` | |
| `mchat` | `mchat`, `toma`, its order if any | `mchat.puntaje` |
| `ados2` | `ados2`, `encuentro`, its order | `ados2.modulo`, `ados2.algoritmo`, `ados2.clasificacion`, `ados2.css`, `ados2.sa_a2` … `ados2.rrb_d5` |
| `evaluacion_neuropediatrica` | `evaluacion_neuropediatrica`, `encuentro`, its order | `evaluacion_neuropediatrica.diagnostico` (ICD-10, `F840`) |
| `eeg` | `eeg`, `toma`, its order | `eeg.con_sueno`, `eeg.canales`, `eeg.duracion_min`, `eeg.calidad_amplitud`, `eeg.calidad_alta_frecuencia`, `eeg.calidad_correlacion`, `eeg.calidad_sin_senal`, `eeg.calidad_linea` **[EEG analysis]** |
| `eeg_metrica` | results of the EEG `toma` | `eeg.ritmo_posterior`, `eeg.husos_sueno_n2`, `eeg.husos_sueno_n3`, `eeg.picos_paroxisticos`, `eeg.gradiente_anteroposterior` **[EEG analysis]** |
| `eeg_metrica_electrodo` | `eeg`, `parte` per electrode (`codigo_fuente` = the electrode), parent the EEG | `eeg.<metrica>` **[EEG analysis]** |
- The catalog (`core/catalogos/tea.toml`) holds these studies and results; each ADOS-2 item's label and domain live in
`cat_resultado`, so the patient summary takes them from there.
- `tea_linea_de_tiempo.yml` goes from 29 sources to five: `mchat`, `ados2`, `evaluacion_neuropediatrica`, `eeg` and
`orden`.
---
## 4. dbt silver (`models/tea/silver/`, ephemeral)
| Model | Grain | Columns |
|---|---|---|
| `tea_mchat` | M-CHAT | `procedimiento_id`, `pac_id`, `fecha_mchat`, `puntaje`, `carga_id` |
| `tea_ados2` | ADOS-2 | `fecha_ados2`, `modulo`, `algoritmo`, `css`, `clasificacion`, `carga_id` |
| `tea_ados2_reactivos` | ADOS-2 × item | `dominio`, `reactivo`, `puntaje`, `puntaje_algoritmo` |
| `tea_neuropediatria` | note | `fecha_nota`, `cie_codigo`, `es_tea` (in `cie_tea`), `carga_id` |
| `tea_eegs` | EEG | `fecha_eeg`, `con_sueno`, `canales`, `duracion_min`, the five criteria, `calidad` (`BUENO` or `MALO`), `valido` **[EEG analysis]** |
| `tea_eeg_metricas` | EEG × metric | `valor`, age group at the EEG, `ref_min`, `ref_max`, `valor_z`, `estado` **[EEG analysis]** |
---
## 5. dbt gold (`models/tea/gold/eventos/`) and rules
| Event model | Grain | Measures |
|---|---|---|
| `tea_pasos` | patient × step reached, with `paso_orden`, `fecha`, `conocida_en`, `es_tea`, `grupo_edad` | M28, M23, M24, M21, M22 **[EEG analysis]** |
| `tea_casos` | patient: the date and `conocida_en` of each step | M26, M27, M25 |
| `tea_eegs_periodo` | EEG (`basis: examen`) | M29 **[EEG analysis]** |
| `tea_alteraciones` | patient with a good EEG: their first good EEG's date, `conocida_en` and one flag per alteration found in it | M30 **[EEG analysis]** |
The age group is a stratum, as in CaCu: M21, M22 and M24 publish `TOTAL` with one `grupo_edad` per patient (age at the first M-CHAT, §1) in
`measure_report_unidad_estrato` (breakdown and filter), which is the shape the WebApp already reads
(`estrato=grupo_edad`). The windows are the page's: 16 to 23, 24 to 29 and 30 to 36 months. A child outside them is not
in the cohort and isn't counted; `SIN_DATO` is left for a child without a birth date. This settles the groups-versus-strata question of `tea-port.md`.
Two constructs the engine doesn't have yet:
- **Status at the period's end.** The population is every unit that entered on or before the period's end and
hadn't left before its start (its last step dated before the period), not the units with an event inside the
period; the category is the furthest step dated on or before that end.
CaMa's measures count events dated inside the period, and `elige: mas_grave` chooses only among the period's
rows.
- **Several groups in one measure**, for M30 only: one group per alteration. The alterations can't be a stratum:
`measure_report_unidad_estrato` holds one value per unit, and a patient can have several. The API turns the groups
into the stratified rows the WebApp reads (`estrato=alteracion`, figure `fig_c1_barras_alteracion`).
Rules, as var `tea` in `dbt_project.yml`: `ventanas` (the page's three windows; the kit's 24 to 30 and 31 to 36 go),
`edad_min_meses`, `edad_max_meses`, `dias_por_mes`,
`cie_tea: [F840]`, `alteracion_z: 2` and the quality thresholds. Seeds: the metric references by age group, the
electrode positions and the effect texts.
---
## 6. Seguimiento and the patient summary
As CaCu's (R5): views the WebApi reads, materialized as views because they leave dbt.
- `tea_seguimiento`, one row per patient, with dates so the WebApi applies the window and the cut-off: `grupo_edad` (at the
first M-CHAT), `fecha_eeg` and `calidad_eeg` (the study's EEG, see below), `mchat`, `css_ados2`, `modulo_ados2`,
`alteraciones_eeg` and `alteraciones` (both from the first good EEG, as M30), `etapa`,
`fecha_etapa` (the date of the step that set the stage), `diagnostico_tea` (from `neu_cie_codigo`, not from the CSS
as the mock fakes it) and `pendientes`.
- Every EEG column of the list is about the EEG the study uses, the same one as M30 and the patient summary (owner,
2026-11-11): the first good-quality EEG, with `calidad_eeg` `bueno`. A patient without one shows their latest EEG
with `calidad_eeg` `malo`, no result and no alterations; a patient without any EEG shows none. `ultimo_eeg` becomes
`fecha_eeg`, as it's no longer always the latest.
- The list can be filtered by the stage date (owner, 2026-11-11): `etapa_desde` and `etapa_hasta`, inclusive, on
`fecha_etapa`, combined with the other filters (`etapa`, age group, M-CHAT, CSS, EEG result, alteration).
- The patient summary reads `tea_ados2`, `tea_ados2_reactivos`, `tea_eegs`, `tea_eeg_metricas` and the electrode
values; the WebApp draws the region z-scores and the map from the electrode values (§12.3).
- The summary shows the EEG the study uses: the patient's first good-quality EEG (owner, 2026-11-11), with its date,
quality criteria, alterations and maps, the same EEG M30 and Seguimiento's alterations read. A patient without a
good EEG has no EEG in the study; the summary keeps showing their latest EEG with the warning that it isn't valid
(owner, 2026-11-11).
- Until the metric reference ranges, effect texts and quality thresholds are validated by the domain expert, every
alteration stays hidden (owner, 2026-11-11): M30, Seguimiento's alteration columns, filter and EEG summary, and the
summary's alterations panel and map. The quality (M29, the quality panel) and the stages still show. The
electrode values are stored either way (§2), so the map comes back with the validation.
---
## 7. Removing the unused indicators
The page shows M21 to M30 and nothing else. Everything below is removed, not ported.
### 7.1 Indicators
| What | Where | Action |
|---|---|---|
| K01 to K08, M02, M04, M05, M10, M12, M12b, M15, M17, M18, M19 (18 TOMLs, already retired) | `indicadores_kit/tea/retirados/` | Not converted to dbt (R4b) and not carried into Transformation; deleted with the kit (R7) |
| R01 `riesgo_banda` (proposal) and the TEA screening cohort it reads | `indicadores_kit/tea/propuestas/r01_riesgo_banda/`, `tea/cohortes/tamizaje.py`, `cohorte_tamizaje.toml` | Dropped. Its predictors (APGAR, NICU, maternal history, hearing test) leave staging with this design |
| The kit's M21 to M25 as they are (CSS-based M21 and M22, M23 by sex, M24 over notes, M25 over the evaluation's date) | `indicadores_kit/tea/familias/` | Not ported: rewritten from §1. Their `casos.toml` don't apply |
| TEA risk prediction | WebApi `POST /tea/predict`; mock `respuestas/tea/predict.POST.json`; `models/models/tea` | Out of scope while no TEA model is planned; the WebApp doesn't call it |
### 7.2 Parameters that go with them
Not carried from `parametros.toml` into var `tea` (D10):
| Key | Used only by |
|---|---|
| `tea.riesgos.horizonte_banda` | R01 |
| `tea.cohorte.plazo_ados2_eeg_dias` | the 30-day rule, removed |
| `tea.poblacion.css_min_tea` | the kit's M21 and M22 |
| `tea.diagnostico.instrumentos_mchat` | the kit's M25; M-CHAT now has its own table |
| `tea.instrumentos.informantes_ramos`, `tea.instrumentos.informantes_otros`, `tea.ramos.areas` | RAMOS (M12) |
| `tea.atencion.plazo_referencia_evaluacion_dias` | K01 |
| `tea.parto.apgar_corte` | M17 |
| `tea.antecedentes_maternos.*` (four rules) | the maternal history load |
| `tea.catalogos.sexo`, `.resultado_mchat`, `.interpretacion_ramos`, `.grado_hipoacusia`, `.apgar_5min` | M02 and M23 by sex, M05, M12, M15, M17 |
Kept: `tea.cohorte.edad_min_meses`, `edad_max_meses`, `dias_por_mes`, `ventanas` (with the page's windows), `tea.diagnostico.cie_tea`,
`tea.supresion.activa`, `tea.presentacion.*`, `tea.catalogos.sin_dato`, `tea.observacion.inicio_datos`.
### 7.3 WebApp leftovers
The retired ids survive only in test data: `indicadores.synthetic-fixtures.ts` (18 entries), and the specs
`indicador-catalog-card.spec.ts` (K05), `indicadores-search.spec.ts` (M02) and `indicadores-page.spec.ts` (K01,
M02). In the two single-indicator specs they become current ids (M29, M24). The synthetic TEA catalog keeps its
shapes under neutral ids and titles (`TEA_SINT_01` to `TEA_SINT_18`): with the real M21 to M30 the page starts the
TEA summary's KPI requests, which the navigation and page specs don't expect, and those specs test the generic
page. Done on the mock's branch `features/tea-plan-sync` (§11.5).
### 7.4 Plan and issues
| Item | Action |
|---|---|
| R4b.19 [#100](http://10.0.10.41:3000/ISSSTELEON/WorkingNarrative/issues/100) (TEA `r01_riesgo_banda`) | Close as not planned |
| R3.3 [#81](http://10.0.10.41:3000/ISSSTELEON/WorkingNarrative/issues/81) (TEA screening cohort) | Close as not planned |
| R4b.14 to R4b.18 (#95 to #99) | Retitle to the new M21 to M25; drop "equality against the kit's snapshot" from their Done when |
| [#128](http://10.0.10.41:3000/ISSSTELEON/WorkingNarrative/issues/128) to [#131](http://10.0.10.41:3000/ISSSTELEON/WorkingNarrative/issues/131) (kit fixes to M21 to M25) | Close as superseded by §1: they change kit code that isn't ported, and the owner chose the 10 Nov definitions over theirs, F84 without the subcode included |
| [#163](http://10.0.10.41:3000/ISSSTELEON/WorkingNarrative/issues/163) (TEA port to dbt's semantic layer) | Rewrite from this plan: eight `DeStaging`, ten measures, hand-written cases instead of `kit_oracle_tea.json` |
| R1.1 [#48](http://10.0.10.41:3000/ISSSTELEON/WorkingNarrative/issues/48) (parameters from YAML) | Exclude the `[tea.*]` keys of §7.2 from its equality check against the kit's `def_parametro` |
| New | One issue each for M26 to M30, Seguimiento and the patient summary |
| `plans/kit-exit/oracle/kit_tea.json` and its use in `tea-port.md` (piece 8) | Retired: the new definitions are proven with hand-written cases, not against the kit |
---
## 8. Order
1. Owner approvals (§9), then the bronze revision, import schemas and catalog.
2. Silver load, table map, domain lists and synthetic staging (as `tea-port.md` pieces 1 to 4, with §3).
3. dbt silver and var `tea`; `dbt build --select tea` on SQLite and on the SQL Server 2016 VM.
4. M29 (no new construct), then M26, M27 and M25.
5. Status at the period's end: M28 and M23.
6. The `grupo_edad` stratum: M24, M21 and M22.
7. Several groups per measure: M30.
8. `tea_seguimiento` and the patient summary views, and their WebApi endpoints; the WebApp changes of §11.
9. The removals of §7 that aren't already done by not porting: parameters, WebApp test data, issues.
## 9. Approvals
| What | `AGENTS.md` rule |
|---|---|
| New TEA staging tables and columns, and dropping the current ones | 4 |
| A new Alembic revision instead of the baseline (or a new baseline) | 3 |
| Dropping R01 and the TEA screening cohort | owner |
## 10. Open questions
None left for the owner (decided 2026-11-11: §1 for the children who never finish and the day counts, §2 and §6 for
the electrode values, §6 for the unvalidated references and the patient without a good EEG, §11.1 for the period
picker). For the domain expert: the reference ranges, effect texts and quality thresholds (§6), and the LOINC and
SNOMED codes marked *to confirm* (§12.3).
Arising from the state machines (§13.3), for the EEG analysis: how an EEG still waiting for its analysis
(`SIN_ANALIZAR`) shows in M29 (a third category, or left out until analysed).
---
## 11. WebApp: what changes from `dev`
The TEA page the plan serves is the WebApp of the mock: branch `features/tea-mock` at `ca511ff` (10 Nov; the remote
still has `53edec8`). Against WebApp `dev` (`f4d2a3e`, 30 Oct, the commit ISSSTELEON `dev` pins) it is 21 commits
ahead and one behind, about 63 files, +3,000 and -1,150 lines, mostly under `src/app/features/indicadores/`. §11.6
has the branches it has to meet on the way to `dev`.
### 11.1 Changes for every domain
| Change | Files |
|---|---|
| One period at a time: the multi-period selector of Resumen becomes a single-period select, for CaCu and CaMa too | `indicador-period-filters.*`, `indicadores-page.*` |
| A graphic-indicator selector with an «Ir» link replaces the floating navigation panel (also closes #5) | `indicadores-page.*`; `indicadores-navegacion-panel.*` removed |
| Highlight buttons for the groups and categories of a figure | `indicadores-highlight.ts`, `indicador-figure-card.*`, `indicador-figure-panel.ts` |
| A C1 donut by stratum | `indicadores-c1-donut.ts` |
| Catalog items can name the tabs that show them (`vistas`); C1 cards can carry their own explanatory line (`c1Info`); C2 cards keep their category counts (`categorias`) | `indicadores.models.ts`, `indicadores-kpi.ts` |
| `alteracion` admitted as a stratum next to `grupo_edad`, `estatus_seguimiento` and `citologia_alto_grado` | `indicadores.service.ts` |
| The follow-up query grows the fields `grupo_edad`, `mchat`, `css`, `etapa`, `alteracion` | `cacu-seguimiento.models.ts` |
The single-period select stays TEA-only (owner, 2026-11-11): CaCu and CaMa keep the multi-period picker.
### 11.2 TEA only
| Feature | Files |
|---|---|
| Tabs Resumen, Histórico, Seguimiento, Datos y definiciones | `indicadores-page.ts` (`TEA_SECTIONS`) |
| Histórico: each indicator over time, with custom periods chosen by year | `indicadores-historico.ts`, `indicadores-historico-figures.ts`, `indicadores-historico-periodos.ts` |
| The period summary paragraph, built from the hidden KPI cards | `tea-resumen-periodo.ts`, `indicadores-kpi.ts` (`KPI_RESUMEN_TEA`) |
| C2 donut with groups drawn both rings at once; one-ring donut for C2 without groups | `indicadores-tea-c2.ts` |
| M30's figure: one bar per alteration, shares that don't add up (`fig_c1_barras_alteracion`) | `indicadores-tea-alteraciones.ts` (new, untracked) |
| Seguimiento: filters by EEG result, age group, M-CHAT band, CSS band, stage and alteration; EEG summary of all matching patients; stage and pending steps per patient | `tea-seguimiento.service.ts`, `indicadores-tracking.*` |
| Patient summary: ADOS-2 with domains and items, EEG quality by criteria (good or bad), alterations with reference, z-score and effects, topographic map per alteration | `tea-paciente-resumen.*` |
### 11.3 What the backend must serve for it
| Route | Contract |
|---|---|
| `GET /tea/indicadores` | The ten ids of §1, with `estratos` (`grupo_edad` for M21, M22, M24; `alteracion` for M30), `figuras` (`fig_c1_barras_edad`, `fig_c1_barras_apiladas_edad`, `fig_c1_barras_alteracion`, `fig_c2_barras`, `fig_c2_donas`, `fig_c3r_caja`), `tipos_periodo` and `vistas` |
| `GET /tea/indicadores/<id>/datos` | `?periodos=` with several periods (Histórico) and `?estrato=grupo_edad` or `alteracion`; C2 categories with label and color; M29 and M30 as in §1 |
| `GET /tea/indicadores/<id>/metadatos` | As CaCu's |
| `GET /tea/seguimiento` | `meses`, `corte`, `page`, `page_size`, `alteraciones_eeg`, `grupo_edad`, `mchat_min`/`mchat_max`, `css_min`/`css_max`, `etapa`, `alteracion`; each item with the fields of §6; `tipos_alteracion` and `resumen_eeg` (`normales`, `anormales`, `sin_eeg_valido`, `por_alteracion`) |
| `GET /tea/seguimiento/<id_seudonimo>` | `ados2` (module, algorithm, domains with items, total, classification, CSS, level) and `eeg` (date, duration, channels, quality and criteria, alterations, maps on shared axes); the pseudonym resolved as in #168 |
### 11.4 Mock-only parts to replace
- The TEA Seguimiento and the patient summary accept only `simulado: true`, as CaCu's list does. WebApi `dev` now
registers the follow-up and patient-risk routes in every environment (`0cbe390`, 9 Nov), so the WebApp's
`simulado` guard is what keeps real data out; lifting it needs the owner's OK.
- «Datos de ejemplo» badges on the EEG quality and alterations panels, and «TEA (mock)» comments: the alterations
are hidden until the reference ranges and effects are validated (§6), and the badges go then.
- The retired ids in the WebApp's test data (§7.3).
### 11.5 Not in the WebApp yet
Done in the mock (mock `features/tea-historico`, ISSSTELEON and WebApp `features/tea-mock`): everything in this list
except the last two items, plus the indicator generator on the cohort rule of §1 (first good EEG, a bad EEG repeated,
leaving after the period of the good one) and the indicator texts.
- **The patient summary's EEG.** The mock builds the summary from the latest EEG (`ultimo_eeg` in
`generar_tea_detalle.py`); it changes to the first good EEG (§6), and the panel says which EEG it is and its date.
- **Seguimiento's EEG columns.** `ultimo_eeg` is renamed `fecha_eeg` and holds the study's EEG (§6), in
`tea-seguimiento.service.ts` (type and validation), `indicadores-tracking.html` (the «Último EEG» header becomes
«EEG del estudio») and the mock's list and generator.
- **Seguimiento: the stage date.** A `fecha_etapa` column and a date-range filter on it (`etapa_desde`, `etapa_hasta`),
in `tea-seguimiento.service.ts` (type, validation, query), `indicadores-tracking.*` (column, filter) and the
mock's list.
- **The cohort rule of §1.** The period summary still says «tuvieron algún paso del tamizaje… según su etapa a la
fecha de corte», and the mock generator (`generar_tea_casos.py`, `cohorte()`) counts the children with a step in
the period at their stage at the cut-off. Both change to the children in the screening during the period, at their
stage at its end, leaving after the period of their good EEG.
- **The single-period select, TEA only.** The mock WebApp gives every domain one period at a time; CaCu and CaMa get
their multi-period picker back (§11.1).
- **Alterations hidden until validated.** M30, Seguimiento's alteration columns, filter and EEG summary, and the
summary's alterations panel and map stay hidden behind one switch until the references are validated (§6).
### 11.6 Branches on the way to `dev`
Checked 2026-11-11 against the Gitea remotes.
| Branch | Where it stands | What it means for TEA |
|---|---|---|
| WebApp `dev` (`f4d2a3e`) | One commit the mock lacks: the bitácora page, self-hosted fonts and icons, install-package fixes (reportes, governance, connect) | Merging it into the TEA branch conflicts only in `src/styles.scss` |
| `features/cama-mock` (`502fc96`, 9 Nov) | Built on `features/tea-mock` at `53edec8`, plus 22 commits: CaMa on TEA's tabs, the domain menu in the header, the institutional look, general filters in one compact row, search and «Fijar indicador» only from five indicators, cards with a value without «Disponible» | It holds the TEA page except `ca511ff`. Merging `ca511ff` into it conflicts in `cacu-seguimiento.models.ts`, `indicadores-kpi.ts` and `indicadores.service.ts`; eleven more shared files merge cleanly. It also conflicts with `dev` in `src/styles.scss` |
| `refactor/kit-exit` (`62cdb25`, 8 Nov) | `dev` plus three commits: a separate KPIs page (`/kpis`) that draws CaCu's measures from FHIR `MeasureReport` bundles | No file in common with the TEA branch, but the contract clashes (§11.7) |
Order: push `ca511ff`, merge it into `features/cama-mock` (three conflicts), bring `dev` in (`styles.scss`), and merge
the result into `dev` by pull request.
### 11.7 The contract gap with `refactor/kit-exit`
The TEA page reads the kit's serving contract: `GET /<domain>/indicadores` as a catalog (title, contract, figures,
strata), `/indicadores/<id>/datos` with rows per period and stratum, and `/metadatos`. The WebApi on
`refactor/kit-exit` (`c430a5b`) serves only `GET /<domain>/indicadores`, as a list of measures (`id`, `url`,
`version`, `scoring`), and `GET /<domain>/indicadores/<measure_id>`, a FHIR `MeasureReport`. The same URL means two
different things, and nothing serves `/datos` or `/metadatos`, for TEA, CaCu or CaMa.
One of the two has to give, and it's the owner's decision (#132 point 3 asks for one generic contract):
1. **The pages read `MeasureReport`**, as `/kpis` does: the Resumen, Histórico and strata code reads FHIR groups and
stratifiers. The catalog fields the page needs (titles, figures, strata, `vistas`, colors, notes) come from the
measures' `meta` in dbt. Largest WebApp change; one contract.
2. **The WebApi adds the page's contract over the measures**: `/datos` and `/metadatos` built from the dbt measures,
and the catalog under a URL that doesn't clash with the measure list. No WebApp change; two contracts.
Planned: option 1 (owner, 2026-11-11). The WebApi side is §12. On the WebApp side, the indicator page (Resumen,
Histórico, the KPI cards and the period summary) reads `Measure` and `MeasureReport` the way `/kpis` already does,
and §11.3's `/datos` and `/metadatos` go. Seguimiento and the patient summary move to FHIR too (§12.4, §12.5).
---
## 12. WebApi: answering in FHIR
Every route the TEA page reads, and the rest of the WebApi, gets its FHIR R4 equivalent. Reference: the WebApi on
`refactor/kit-exit` (`c430a5b`), which already answers each measure as a `Bundle` of `MeasureReport`s
(`webapi/kpis.py`, `metrics.py`, `compositions.py`, `durations.py`). Codes marked *to confirm* need the domain
expert: LOINC or SNOMED where one exists, the project's code system otherwise.
### 12.1 Conventions for every route
| Point | Today | FHIR |
|---|---|---|
| Base | Routes under `/<domain>/…`, `/reportes`, `/imports`, `/governance` | One FHIR endpoint per domain database: `/<domain>/fhir/`, FHIR R4 (4.0.1), JSON, `application/fhir+json` |
| What the server offers | `GET /api` lists routes | `GET /<domain>/fhir/metadata`: a `CapabilityStatement` with the resources, search parameters and operations below |
| Errors | `{"error": "…"}` | `OperationOutcome` (severity, code, Spanish `diagnostics`), same HTTP statuses |
| Lists and paging | `items` with `paginacion` (`page`, `page_size`, `total_items`, `total_pages`) | `Bundle` `searchset` with `total` and `link` (`self`, `next`, `previous`); `_count` (at most 200) and the server's paging links |
| Patient identity | `id_seudonimo` in the body; `pac_id` in the CaCu risk route | `Patient.id` is the salted pseudonym everywhere; `pac_id` and `pac_id_hospital` never leave; references are `Patient/<pseudonym>`, resolved as in #168 |
| Simulated data | `simulado: true` in the body | A `meta.tag` on every resource (system `https://isssteleon.org/fhir/CodeSystem/etiqueta`, code `simulado`); the WebApp guard reads the tag |
| Catalogs | `cat_estudio`, `cat_resultado`, `cat_valor`, the TOML catalogs | `CodeSystem` and `ValueSet` resources under `https://isssteleon.org/fhir/`, generated from `core/catalogos/tea.toml`; external systems where they apply: ICD-10 (`http://hl7.org/fhir/sid/icd-10`), observation interpretation (`H`, `L`, `N`), `data-absent-reason` |
| Extensions | Three, for cut-offs and the history entry | Each one with a `StructureDefinition` published under `https://isssteleon.org/fhir/StructureDefinition/` |
| Checking | Shape checks in the WebApp | Every response checked against FHIR R4 in the WebApi tests, with a FHIR model library or the HL7 validator (a new dependency: owner's approval) |
### 12.2 Measures
| Today | FHIR |
|---|---|
| `GET /<domain>/indicadores`: `{id, url, version, scoring}` | `GET /<domain>/fhir/Measure`: a `Bundle` of `Measure` resources, replacing the page's catalog and `/metadatos`. Title, description, scoring, `group` with each population's `description` (what #2 asks), `stratifier` definitions, `improvementNotation`, and extensions for figures, `vistas`, period types, category labels and colors. Built from each metric's `meta` in dbt |
| `GET /<domain>/indicadores/<measure_id>?periodos=…` | One period: `GET /<domain>/fhir/Measure/<id>/$evaluate-measure?periodStart=…&periodEnd=…` (the standard operation), returning one `MeasureReport`. Several periods (Histórico): `GET /<domain>/fhir/MeasureReport?measure=<canonical>&period=…`, a `searchset` with one report per period. `corte_evento` and `corte_conocimiento` stay as custom parameters of both |
| `GET /reportes/indicadores` (stored reports) | `GET /<domain>/fhir/MeasureReport` with `measure`, `period` and `date` search; the history entry stays an extension |
| `POST /reportes/indicadores/<dominio>/recalcular` | `POST /<domain>/fhir/Measure/$recalcular`, a custom operation returning an `OperationOutcome` |
| Domains in the `kpis_blueprint` loop | `tea` added (`tea-port.md` piece 3), with TEA's metrics in the manifest |
The `MeasureReport` itself:
| Point | Today | Change |
|---|---|---|
| `measure` | `tea/M21_…\|0.3.0`, not a URL | An absolute canonical (`https://isssteleon.org/fhir/Measure/<measure_id>\|<version>`), the same one the `Measure` carries |
| Scoring of a C2 | `composition`, which isn't a FHIR scoring | `cohort`: the units counted as the initial population, with the categories as a stratifier |
| Groups | One group, identified only by `id` | `group.code` on each, and several groups per report where the measure has them (M30: `TOTAL` plus one per alteration) |
| Stratifier and stratum identity | `code: [{text}]`, `value: {text}` | Codings: the stratifier's code (`grupo_edad`, the C2's category), and each value with its catalog system, code and display |
| C2 with strata | Each stratum's counts summed across categories | `stratum.component` holds the category inside each stratum value, so a breakdown by both survives |
| Suppression | Absent | Suppressed counts and scores carry no value and the `data-absent-reason` extension (`masked`); depends on #73 |
| Confidence interval | Absent | Lower and upper bounds as extensions of `measureScore`; depends on #73 |
| Proportion score | A fraction, without unit | Kept as a fraction (0 to 1), stated in the `Measure`; the WebApp multiplies for display |
| Exclusions | Not reported | `denominator-exclusion` with its count where the measure excludes (M24's neuropediatrics notes without F84.0) |
| Durations | Median with `q1` and `q3` extensions | Kept; the excluded (no value at the cut-off) as their own population count |
The engine, for TEA's definitions. These are §5's constructs; the engine that answers them is this WebApi code, not dbt.
| Construct | Today | Change |
|---|---|---|
| Age stratum | Kinds `edad_al_inicio_del_periodo`, `linea_de_tiempo_al_inicio_del_periodo`, `del_elegido` | A kind that reads a column of the event model (`grupo_edad`, the age at the first M-CHAT, §1). Age at the period's start contradicts §1 |
| Status at the period's end (M28, M23, M24, M21, M22) | Units with a fact dated inside the period | A population rule in `meta`: units entered on or before the period's end and not left before its start; the category is the furthest step dated on or before that end |
| Several groups (M30) | `MeasureDefinition.group` is one string | A list of groups, each with its filter, answered and serialized one by one |
| Unit of M29 | `basis` of the existing measures | `examen` (oro has no `estudio`) |
### 12.3 TEA's clinical data as FHIR resources
What Seguimiento and the patient summary show, read from silver (§3), each kind of fact as its resource:
| TEA fact | Resource | Content |
|---|---|---|
| Child | `Patient` | `id` the pseudonym; `birthDate` at month precision; no identifiers, no name |
| Order | `ServiceRequest` | `code` the study (ADOS-2, neuropediatrics, EEG); `authoredOn`; `subject` |
| M-CHAT | `Observation` | `code` M-CHAT-R/F total (LOINC *to confirm*); `valueInteger` 0 to 20; `effectiveDateTime`; `basedOn` its order if any |
| ADOS-2 | `Observation` | `code` ADOS-2 (*to confirm*); `component`s for module, algorithm, CSS, classification, the two domain totals and the 29 items (item codes in the project's `CodeSystem`, labels and domains there); `effectiveDateTime`; `basedOn` |
| Neuropediatrics note | `Encounter` and `Condition` | The visit (`serviceType` neuropediatrics, `period`); its diagnosis as a `Condition` (`code` ICD-10, `F840` for TEA, `encounter`, `recordedDate`) |
| EEG | `Procedure` and `DiagnosticReport` | The recording as a `Procedure` (`code` electroencephalography, SNOMED *to confirm*); its result as a `DiagnosticReport` (`effectiveDateTime`, `result` the observations below, `conclusionCode` good or bad quality). The EDF as a `Media` with its `Binary`, served only where the file may leave |
| EEG quality criteria | `Observation` | One per criterion (`valueInteger` channels or `valueQuantity` dB), `interpretation` good or bad; members of the report **[EEG analysis]** |
| EEG metric (alteration) | `Observation` | One per metric: `valueQuantity` with its unit; `referenceRange` for the child's age group at the EEG; `interpretation` `H` (aumentado), `L` (disminuido) or `N`; `dataAbsentReason` when it can't be evaluated (no sleep). The z-score as a `component`. Effect texts live in the `CodeSystem` of the metrics, not in each observation **[EEG analysis]** |
| Electrode values | `Observation` | One per metric, a `component` per electrode (`code` the 10-20 electrode, `valueQuantity` the z-score). The WebApp draws the map and the regions from them (#132); `mapas` and `ejes_mapa` leave the API **[EEG analysis]** |
### 12.4 Seguimiento
The follow-up list is each child's screening as an `EpisodeOfCare`, which already has the cohort's entry and exit:
| Field today | FHIR |
|---|---|
| The row | `EpisodeOfCare`: `patient`, `period.start` the first M-CHAT, `period.end` the first good EEG, `status` `active` while pending and `finished` after it |
| `etapa`, `fecha_etapa` | `type` the stage (project `CodeSystem`), and an extension with the stage's date |
| `pendientes` | A `CarePlan` per episode, one `activity` per step with its `status` (`completed`, `not-started`) and date |
| `grupo_edad`, `mchat`, `css_ados2`, `modulo_ados2`, `diagnostico_tea`, `fecha_eeg`, `calidad_eeg`, `alteraciones_eeg`, `alteraciones` | Included resources (`_include`): the `Patient`, the M-CHAT and ADOS-2 `Observation`s, the `Condition` and the EEG `DiagnosticReport` with its metrics; the age group as an extension of the episode |
| Filters | Search parameters on `EpisodeOfCare`: `status`, `date` (the window and the cut-off), `etapa`, `fecha-etapa` (`ge`, `le`: the stage-date filter of §6), `grupo-edad`, `mchat`, `css`, `resultado-eeg`, `alteracion`; each declared as a `SearchParameter` |
| `resumen_eeg`, `tipos_alteracion` | `GET /tea/fhir/EpisodeOfCare/$resumen-eeg` with the same filters, returning `Parameters` (normal, abnormal, without a valid EEG, count per alteration); the alteration types are the metrics' `ValueSet` |
`GET /tea/fhir/EpisodeOfCare?…&_include=…` replaces `GET /tea/seguimiento`. CaCu's follow-up list (`/cacu/seguimiento`)
moves to the same shape.
### 12.5 The patient summary
`GET /tea/fhir/Patient/<pseudonym>/$resumen-tea` replaces `GET /tea/seguimiento/<id_seudonimo>`: a `Bundle` of type
`collection` with the `Patient`, the ADOS-2 `Observation` and the EEG the study uses (the first good one, §6) as its
`DiagnosticReport` with the quality, metric and electrode `Observation`s. A patient without a good EEG gets their latest
one, with `conclusionCode` bad quality. The ADOS-2 domain bars, the CSS level and the map are drawn by the WebApp from
those resources.
### 12.6 The rest of the WebApi
| Route family | FHIR |
|---|---|
| `GET /cacu/pacientes/<pac_id>/riesgo` | `RiskAssessment` (`subject` the pseudonym, `prediction` one per horizon with `probabilityDecimal` and `whenRange`, `basis` the observations used, `method` the model version); cohort membership as a `Group` (the build) with the patient as a member |
| `POST /<domain>/predict` | `POST /<domain>/fhir/RiskAssessment/$predict`, returning a `RiskAssessment`. Out for TEA (§7.1) |
| `GET /reportes/importaciones`, `/importaciones/descarga` | `AuditEvent` per import (who, when, what, outcome) and `Provenance` on the resources it wrote; the download as a `Binary` |
| `POST /imports/commit` | The rows written as a `transaction` `Bundle` of the resources above; uploaded documents as `DocumentReference` with their `Binary`. `POST /imports/validate` maps to `$validate` |
| `/imports/connectors`, `/targets`, `/sources/…` (previews, SQL browsing, PDF regions) | Not FHIR: tooling for the import screen, kept as an admin API outside `/<domain>/fhir/` |
| `GET /data/<target>` | Not FHIR: raw staging rows. Kept as admin, or removed once imports are checked through the resources |
| `/governance/model-versions/…` | Not FHIR (no resource fits a model registry); admin API. A model version used in a prediction is cited from `RiskAssessment.method` |
| `/governance/ocr/…` | OCR jobs as `Task` (`status`, `input` the document, `output` the rows); corrections stay admin |
| `GET /health` | Unchanged, outside FHIR |
### 12.7 What it means for the WebApp
Every reader changes with its route: the indicator page and `/kpis` read `Measure` and `MeasureReport` (§11.7);
Seguimiento reads `EpisodeOfCare` bundles with their includes and paging links; the patient summary reads the
`$resumen-tea` bundle and draws the ADOS-2 bars and the EEG map itself; CaCu's patient record reads `RiskAssessment`;
errors arrive as `OperationOutcome`; the `simulado` guard reads `meta.tag`. §11.3 and §11.5 describe the page as it
reads today; this section is where it ends.
### 12.8 Order
1. Conventions: the `/<domain>/fhir/` base, `CapabilityStatement`, `OperationOutcome`, the `simulado` tag, the
`CodeSystem`s, and response checking in the tests.
2. Measures: `Measure`, `$evaluate-measure`, the `MeasureReport` search, canonical URLs, codings, `cohort` for C2,
`stratum.component`.
3. The engine constructs for TEA (column stratum, status at the period's end, several groups), with TEA's measures.
4. TEA's clinical resources (§12.3), then Seguimiento as `EpisodeOfCare` and the patient summary operation.
5. Suppression and intervals, with #73.
6. The rest (§12.6): `RiskAssessment`, `AuditEvent` and `Provenance`, imports as `transaction`, OCR `Task`s.
Each step changes what the WebApp, `/kpis` and the CaCu and CaMa answers receive: their readers and the frozen answers
of `tests/test_*_measures.py` move with it.
### 12.9 Approvals
| What | `AGENTS.md` rule |
|---|---|
| A FHIR model or validation library in the WebApi | new dependency |
| Routes moved under `/<domain>/fhir/` and the old ones removed | owner |
| Codes from LOINC and SNOMED (licensing of SNOMED in Mexico) | owner and domain expert |
---
## 13. State machines
The rules of §1 and §6 define these machines. The stored data are dated facts (M-CHAT, ADOS-2, notes, EEG and their
analysis); every state below is derived from them at a date: the end of a period for the measures, the cut-off for
Seguimiento. Nothing stores a state, so a late fact moves the state back in time when it's loaded.
### 13.1 A child's screening
```mermaid
stateDiagram-v2
[*] --> FUERA_DE_COHORTE: first M-CHAT outside 16 to 36 months
[*] --> MCHAT: first M-CHAT at 16 to 36 months
MCHAT --> PSICOLOGIA: psychology note (ADOS-2)
PSICOLOGIA --> NEUROPEDIATRIA: neuropediatrics note
NEUROPEDIATRIA --> EEG: first good-quality EEG
EEG --> COMPLETADO: end of the period of that EEG
FUERA_DE_COHORTE --> [*]
COMPLETADO --> [*]
```
| From | Event (dated fact) | To |
|---|---|---|
| (start) | First M-CHAT at 16 to 36 completed months | `MCHAT` |
| (start) | First M-CHAT outside that range | `FUERA_DE_COHORTE`: never counted |
| `MCHAT` | Psychology note (ADOS-2) | `PSICOLOGIA` |
| `PSICOLOGIA` | Neuropediatrics note, with any diagnosis | `NEUROPEDIATRIA` |
| `NEUROPEDIATRIA` | First good-quality EEG | `EEG` |
| `EEG` | The end of the period of that EEG | `COMPLETADO`: no longer counted |
- Steps go in order; a fact whose previous step is missing doesn't move the child (an EEG before the
neuropediatrics note leaves them where they are until the note arrives).
- A bad EEG, an EEG still waiting for analysis (§13.3), a later EEG and a second note don't move the child.
- Without a good EEG a child never leaves (§1): `MCHAT`, `PSICOLOGIA` and `NEUROPEDIATRIA` have no exit.
- **How a period reads it:** a child is counted in a period when their state at its end is `MCHAT`, `PSICOLOGIA`,
`NEUROPEDIATRIA` or `EEG` and they weren't `COMPLETADO` at its start; the category of M28 is that state.
- **Seguimiento:** `etapa` is the state at the cut-off, `fecha_etapa` the date of the fact that set it, `pendientes`
the steps after it. In FHIR it's the `EpisodeOfCare` (`active` until `COMPLETADO`, then `finished`) with its
`CarePlan` (§12.4).
### 13.2 The diagnostic result
```mermaid
stateDiagram-v2
[*] --> EN_PROCESO: in the screening, no neuropediatrics note
EN_PROCESO --> CONFIRMADO: note with F84.0
EN_PROCESO --> SIN_TEA: note without F84.0
SIN_TEA --> CONFIRMADO: a later note with F84.0
```
| State | Meaning | Counted in |
|---|---|---|
| `EN_PROCESO` | No neuropediatrics note by the date | M23 (in process), M24 denominator |
| `CONFIRMADO` | Some neuropediatrics note with F84.0 by the date | M23 (confirmed), M24 numerator and denominator, M21 and M22 base, M25 |
| `SIN_TEA` | Notes, none with F84.0 | M24 exclusions; out of M23; still in the screening (§13.1) |
`CONFIRMADO` is final: a later note without F84.0 doesn't undo it. It runs beside §13.1, not after it: the
neuropediatrics note moves both.
### 13.3 One EEG study
```mermaid
stateDiagram-v2
[*] --> SIN_ANALIZAR: EDF or report loaded
SIN_ANALIZAR --> BUENO: analysis, every criterion good
SIN_ANALIZAR --> MALO: analysis, some criterion bad
BUENO --> [*]
MALO --> [*]
```
| State | Meaning | What it feeds **[EEG analysis]** |
|---|---|---|
| `SIN_ANALIZAR` | Loaded, criteria not written yet | M29 can't grade it; it doesn't move §13.1 or §13.4 |
| `BUENO` | Every quality criterion within its threshold | M29 (good); may become the study EEG (§13.4) |
| `MALO` | Some criterion out of its threshold | M29 (bad); no result, no alterations |
A new analysis of the same EEG (new thresholds) can move it between `BUENO` and `MALO`; the states above it are
derived again on the next answer. How `SIN_ANALIZAR` shows in M29 is open (§10).
### 13.4 The patient's study EEG
```mermaid
stateDiagram-v2
[*] --> SIN_EEG
SIN_EEG --> SOLO_MALOS: a bad EEG
SIN_EEG --> CON_EEG_DEL_ESTUDIO: a good EEG
SOLO_MALOS --> CON_EEG_DEL_ESTUDIO: a good EEG
CON_EEG_DEL_ESTUDIO --> CON_EEG_DEL_ESTUDIO: any later EEG (ignored)
```
| State | Shown in Seguimiento and the summary | Alterations |
|---|---|---|
| `SIN_EEG` | No EEG | None |
| `SOLO_MALOS` | The latest EEG, `calidad_eeg` `malo`, marked not valid | None |
| `CON_EEG_DEL_ESTUDIO` | The first good EEG, `calidad_eeg` `bueno` | That EEG's, once per alteration; M30 counts it in its period |
Entering `CON_EEG_DEL_ESTUDIO` is the same event that moves §13.1 to `EEG`, when the neuropediatrics note is there.
### 13.5 Showing the alterations
```mermaid
stateDiagram-v2
[*] --> PROVISIONAL
PROVISIONAL --> VALIDADO: domain expert validates references, effects and thresholds
```
| State | Shown |
|---|---|
| `PROVISIONAL` | Quality (M29, the quality panel) and the stages; every alteration hidden (§6) |
| `VALIDADO` | Everything, without the «Datos de ejemplo» badges |
A change to the references after validation goes back through the domain expert; the switch doesn't return to
`PROVISIONAL` on its own.
### 13.6 A measure's answer for a period
```mermaid
stateDiagram-v2
[*] --> SIN_RESPUESTA
SIN_RESPUESTA --> RESPONDIDA: first request after a load
RESPONDIDA --> RESPONDIDA: same question again (read from the history)
RESPONDIDA --> SIN_RESPUESTA: a new load (new knowledge cut-off)
```
The WebApi answers each measure and period on request and keeps the answer by its knowledge cut-off (the start of
the last load, §12.2). A new load opens a new cut-off: the next request computes again, and the old answer stays in
the history. A change to dbt's models or to var `tea` is a new definition and also computes again.