Reconcile and harden Development artifact retention

This commit is contained in:
Nick Beckley 2026-11-30 22:40:33 +00:00
parent ae321684ca
commit 8bc5410c78
9 changed files with 696 additions and 2 deletions

View File

@ -226,3 +226,62 @@ Clara's normal assistance-response workflow, retain its prior effort, and perfor
its authenticated persistence/reload acceptance checks. Never manually complete it
or resolve stage 53 to test the integration. Reconcile any existing receipt before
requesting deployment again; uncertain attempts are not automatically repeated.
## Development artifact retention (Atlas)
Successful activations now run Development-only housekeeping after releasing the
activation lock; housekeeping reacquires `/opt/plotdirector-dev/deployment.lock`
and refuses overlapping activation/cleanup. A concurrent activation safely skips
housekeeping with a warning. Failed and validation-only deployments do not prune.
Both the publisher and activation helper warn below 20% available storage.
Administrator commands (dry run is the default):
```sh
sudo -n /usr/local/sbin/housekeep-plotdirector-development
sudo -n /usr/local/sbin/housekeep-plotdirector-development --apply
```
The active release and three distinct most recent successfully activated previous
releases are protected using activation receipts and the current symlink/marker.
Older successful immutable installations lose only their runtime `app` payload;
manifests, SQL, qualification evidence and activation receipts remain. Named
rollback/restore packages and installations without successful receipts remain.
The retired `/srv/apps/plotdirector-dev/releases` publish artifacts and historical
`current-before-*` copies are pruned, keeping three newest valid installation
snapshots (including archive links). The legacy `current`, persistent data,
uploads, configuration and Data Protection paths must remain.
Only recognised published output is disposable. Source patches, repositories,
registered worktrees, evidence, unknown layouts, mounted content, process references
and recent content are preserved. `/srv/tmp/plotdirector-dev-publish-*` expires
after 48 hours; disposable `/srv/repos/.plotdirector-builds/*` after seven days,
measured against all descendant modification times. Other temporary/source paths
are deliberately outside automatic scope. Do not use historical ad hoc copy/rename
deployments; all activation must use the installed helper and its lock.
Pin additional packages using an exact absolute path in the root-owned
`/etc/plotdirector-development/retention-protected.json` paths array, or add a
`.retain` marker within an artifact. Pins take precedence over retention counts.
Housekeeping logs removed directories, allocated bytes by category and filesystem
available-space change. Unknown content is preserved for administrator review.
No Production hosts, backup retention, databases, or source worktrees are targeted.
Cleanup rechecks pins, processes, source/evidence, mounts, retention markers and
age immediately before each removal. Ancestor symlinks and same-device bind mounts
are rejected; removal uses directory descriptors without following symlinked
ancestors. Snapshot metadata must be regular files with valid runtime/dependency
JSON. Unreadable process protection or unavailable trusted Git inspection aborts
cleanup rather than guessing. Registered worktrees are inspected through Atlas's
root-owned `/usr/local/lib/atlas-security/git_snapshot.py` namespace reader; this is
an installation prerequisite. Pin configuration and its ancestors must be root-owned
and not group/world-writable. `.protect` markers are also recognised.
Source changes to `development.py` and `retention.py` require administrator install
into `/usr/local/lib/plotdirector-dev-deployment`. Initial provisioning includes the
retention module, administrator launcher and empty protected-path configuration;
existing installations must preserve their administrator pins. Install only reviewed
changed modules under the deployment lock. The installed publisher already has the
storage warning and additional Atlas security hardening: do not overwrite hardened
installed publisher/release modules from an older source snapshot. Reconcile those
security differences separately before any full reinstall. No new sudo rule is
needed for retention.

View File

@ -0,0 +1,111 @@
# Application repository reconciliation — 30 November 2026
## Origin and ownership
The five uncommitted retention files came from the completed Atlas chat “Recover
Atlas storage” (`01a22cba-996e-71f0-aebe-b12058142a9f`), not an unfinished CYJ task.
That authorised storage recovery installed Development retention and explicitly
left its source uncommitted for review. The original files' 13:57:58 modification
times agree with the completed operation. Its report is
`/home/nick/atlas-storage-recovery-20261130/report.json`.
Atlas chat history and live processes were checked: this reconciliation was the
only active interactive PlotDirector session; there was no automatic Codex child.
The controller's existing repository advisory lock was held throughout review,
testing and commit so that making Git clean could not dispatch a concurrent writer.
No existing work was discarded, branch changed, push performed or task claimed.
## Review and fixes
Preserved the activation hook, storage warning and documented retention policy.
Fixed ancestor symlink traversal, same-device bind mounts, case-insensitive nested
source/evidence protection, named restore packages, dangling retention markers,
receipt ordering across timezone offsets, snapshot metadata validation and stale
cleanup plans. Removal now anchors every parent with no-follow directory file
descriptors and uses Python's symlink-resistant recursive removal. Pins must be
trusted administrator configuration. Unavailable process or registered-worktree
protection fails closed. Git worktree metadata is inspected unprivileged in Atlas's
existing secret-free namespace; its fixed `/input` ownership exception applies
only within that isolated command and does not change host Git configuration.
Added missing initial-provisioning dependencies: retention module, administrator
launcher and empty pin configuration only when absent. Existing pins are preserved;
no new sudo authority was added. Added fixture regression tests for the protections,
apply/dry-run/idempotence and activation failure/validation behavior.
Installed only the reviewed retention module under the existing Development
activation lock. The previous module is backed up under
`/root/plotdirector-retention-reconciliation-20261130`. Its installed/source SHA256 is
`10679e53faba9620a97decd48dbdd8d5ef445e2a8946fec6ef9ae38dc85d8362`.
The hardened installed publisher/release modules were not overwritten.
No application deployment, database operation or real cleanup was performed.
## Verification
- `python3 -m unittest discover -s Tools/Deployment -p 'test_*.py'`: 110 tests passed.
- `dotnet build PlotLine.slnx`: passed, zero warnings and zero errors.
- `dotnet run --project PlotLine.Tests/PlotLine.Tests.csproj`: exit 0,
897 PASS lines, zero FAIL lines; build and harness ran serially.
- Node scene-create and Development acceptance helper tests: five passed.
- Timeline scene-drop browser test against the isolated Razor fixture: passed
themes, responsive layout, cancellation, confirmation, errors and restoration;
save transport was mocked, with no database writes.
- Python compilation, launcher shell syntax and `git diff --check`: passed.
- Installed administrator retention dry run: exit 0, 106 retained entries,
zero planned removals, zero cleanup performed. Storage: approximately 77% free
on `/srv`, 54% free on the Development root filesystem.
Logs are `/tmp/plotdirector-deployment-review-tests.log`,
`/tmp/plotdirector-reconciliation-build.log`,
`/tmp/plotdirector-reconciliation-regression.log`,
`/tmp/plotdirector-browser-unit-review-tests.log`,
`/tmp/plotdirector-timeline-browser-review-tests.log` and
`/tmp/plotdirector-retention-live-dry-run.log`.
## Eleven existing unpublished commits
All were authored on 29 November under the configured Nick Beckley identity.
The branch remains `codex/application-website-separation-20261127`; its remote
tracking tip was independently checked against origin at
`2725e5143f65ecfb3dd775295b38066f1b4b61a9`.
| Commit | Reviewed scope |
| --- | --- |
| a5f9a3da | Automatic controller claim ownership instructions |
| 7c313d98 | Application worker operating procedure |
| 8c273475 | Historical manuscript/Context audit documentation |
| b5672f20 | Timeline character/location confirmation dialogs and tests |
| 9133e520 | Isolated unattended Development builds and receipt capture |
| 299500f9 | Reusable authenticated Development acceptance fixtures |
| aa839d3b | Dedicated scene creation and workspace handoff |
| 6416a01c | Persisted scene current-focus handoff |
| cbb818a1 | Scene creation layout and contextual actions |
| 7dacca5c | Preserve unsaved changes after canceled validation |
| ae321684 | Verify scene purpose in the rendered acceptance workspace |
The history is coherent and the current combined application/tooling gates pass.
It is preserved as a feature branch for owner review, not merged or rebased.
No standing remote publication authority or enforced PR workflow was established,
so nothing was pushed. A full deployment-tool publication/reinstall also needs
separate reconciliation of Atlas's installed security hardening with its older
repository publisher/release source. Those installed protections remain in force;
this review does not certify overwriting them from this branch. The source is
locally verified, but an unconditional operational publication sign-off is withheld
for that specific reason. It does not prevent the configured controller using its
already-hardened installed tools on the clean local branch.
## Controlled handover
CYJ's read-only task query confirms task 65 “Reconcile remaining Writer and Context
panel backlog” is Ready, assigned to Application resource 7, without dependencies,
assistance, prior execution sessions or recorded effort. Its brief is findings-only.
The controller has a persistent `repository_conflict` history entry, so merely
committing cannot resume dispatch. The supported `acknowledge-recovery` command
requires the controller stopped and refuses a usable lease; it does not claim tasks
or bypass CYJ eligibility. Both controller workers were idle before handover.
After this commit and a clean check, use the documented stop/acknowledge/start
recovery under the held repository lock. Finish all interactive repository writes
before releasing that lock. Subsequently inspect controller/CYJ read-only for the
fresh automatic claim and the worker's explicit InProgress update. Record actual
handover evidence separately; this committed report does not assert future execution.

View File

@ -115,7 +115,17 @@ def main():
return
require(len(args) == 2 and args[0] in ('--validate', '--activate', '--rollback'),
'Usage: deploy-plotdirector-development --validate|--activate|--rollback <release-id>')
import retention
retention.preflight()
core.activate(args[1], validate=args[0] == '--validate', rollback=args[0] == '--rollback', profile=Development())
if args[0] != '--validate':
# Activation has completed and released its lock. Housekeeping reacquires the
# same lock and rechecks current; a competing deployment causes a safe skip.
try:
retention.run(apply=True)
except Exception as error:
print('WARNING Development retention skipped/failed: ' + type(error).__name__)
if __name__ == '__main__':

View File

@ -51,6 +51,12 @@ def main():
args = parser.parse_args()
require(socket.gethostname() == 'atlas' and os.geteuid() != 0, 'Run as the Atlas Development deployer')
os.umask(0o077)
for storage_path in ('/srv', '/opt/plotdirector-dev'):
storage = os.statvfs(storage_path)
available = storage.f_bavail / storage.f_blocks
if available < .20:
print(f'WARNING Development storage {storage_path}: {available:.1%} free (below 20%)', flush=True)
source = Path(args.source).resolve()
output = Path(args.output).resolve()
require(not output.exists(), 'Use a fresh output directory')

View File

@ -0,0 +1,3 @@
#!/bin/sh
# Administrator-only Development housekeeping; no additional sudo authority.
exec /usr/bin/env -i PATH=/usr/sbin:/usr/bin:/sbin:/bin LANG=C.UTF-8 /usr/bin/python3 -I /usr/local/lib/plotdirector-dev-deployment/retention.py "$@"

View File

@ -49,11 +49,14 @@ def main():
directory('/etc/plotdirector-development', mode=0o755)
write(dev.CONFIG, canonical(dev.FIXED), mode=0o600)
pins = Path('/etc/plotdirector-development/retention-protected.json')
if not pins.exists() and not pins.is_symlink():
write(pins, canonical({'paths': []}), mode=0o600)
write(dev.FIXED['database_config'], canonical(db), migrate_gid)
write(dev.FIXED['public_key'], Path(args.public_key).read_bytes(), mode=0o644)
lib = directory('/usr/local/lib/plotdirector-dev-deployment', mode=0o755)
tools = Path(__file__).resolve().parents[1]
for name in ('activate.py', 'release.py', 'receipt.py', 'transport.py', 'development.py'):
for name in ('activate.py', 'release.py', 'receipt.py', 'transport.py', 'development.py', 'retention.py'):
write(lib/name, (tools/name).read_bytes(), mode=0o644)
worker = directory(lib/'database', mode=0o755)
for source in Path(args.worker).rglob('*'):
@ -62,6 +65,7 @@ def main():
if source.is_dir():directory(target, mode=0o755)
else:write(target, source.read_bytes(), mode=0o644)
write('/usr/local/sbin/deploy-plotdirector-development', (tools/'deploy-plotdirector-development').read_bytes(), mode=0o755)
write('/usr/local/sbin/housekeep-plotdirector-development', (tools/'housekeep-plotdirector-development').read_bytes(), mode=0o755)
rule = b'%plotdirector-dev-deploy ALL=(root) NOPASSWD: /usr/local/sbin/deploy-plotdirector-development *\n'
staged = Path('/etc/sudoers.d/.plotdirector-development.pending')
write(staged, rule, mode=0o440)

View File

@ -0,0 +1,255 @@
#!/usr/bin/python3
"""Atlas Development artifact retention. Dry run by default; never traverses links."""
import argparse
from contextlib import contextmanager
from datetime import datetime
import errno
import stat
import subprocess
import fcntl
import json
import os
from pathlib import Path
import re
import shutil
import socket
import sys
import time
ROOT = Path('/opt/plotdirector-dev')
LEGACY = Path('/srv/apps/plotdirector-dev')
PINS = Path('/etc/plotdirector-development/retention-protected.json')
REPOSITORY = Path('/srv/repos/PlotDirector')
TEMPORARY = Path('/srv/tmp')
BUILDS = Path('/srv/repos/.plotdirector-builds')
# Only recognised published-output entries are disposable. Unknown entries fail closed.
ASSETS = {'runtimes','Help','Docs','Data','Content','wwwroot','cs','de','es','fr','it','ja','ko','pl','pt-BR','ru','tr','zh-Hans','zh-Hant','dotnet-tools.json','web.config','PlotLine','appsettings.json','appsettings.Development.json','deployment-manifest.json'}
SENSITIVE = {'.git','.retain','.protect','App_Data','uploads','DataProtectionKeys','source','evidence','acceptance'}
SOURCE_SUFFIXES = ('.patch','.tar','.tar.gz','.zip','.cs','.csproj','.sln','.slnx','.py','.sh','.razor','.cshtml','.fs','.fsproj','.vb','.vbproj','.sql','.props','.targets','.ps1','.tar.xz','.tar.bz2','.7z')
def overlaps(a,b):
return a == b or a in b.parents or b in a.parents
def success_keep(receipts, active):
ordered = sorted((d for d in receipts if d.get('status') == 'activated'), key=lambda d:datetime.fromisoformat(d['completed_utc'].replace('Z','+00:00')).timestamp(), reverse=True)
previous=[]
for d in ordered:
name=d['release']['id']
if name != active and name not in previous:previous.append(name)
return {active,*previous[:3]}, {d['release']['id'] for d in ordered}
def preflight():
for p in ('/srv',str(ROOT)):
v=os.statvfs(p); fraction=v.f_bavail/v.f_blocks
print(f'STORAGE {p} available={v.f_bavail*v.f_frsize} free={fraction:.1%}' + (' WARNING below 20%' if fraction<.2 else ''),flush=True)
def process_refs():
refs=[]
for p in Path('/proc').iterdir():
if not p.name.isdigit() or int(p.name)==os.getpid():continue
try:
for q in [p/'cwd',p/'exe',*(p/'fd').iterdir()]:
try:
dest=os.readlink(q)
if dest.startswith(('/srv/','/opt/plotdirector-dev/')):refs.append(Path(dest.removesuffix(' (deleted)')))
except OSError as error:
if error.errno not in (errno.ENOENT,errno.ESRCH):raise
for line in (p/'maps').read_text().splitlines():
fields=line.split(maxsplit=5)
if len(fields)==6 and fields[5].startswith(('/srv/','/opt/plotdirector-dev/')):refs.append(Path(fields[5].removesuffix(' (deleted)')))
args=(p/'cmdline').read_bytes().split(b'\0')
# Command arguments can reference an output directory before it is opened.
for arg in args:
s=arg.decode(errors='replace')
value=s.split('=',1)[-1]
if value.startswith(('/srv/','/opt/plotdirector-dev/')):refs.append(Path(value))
except OSError as error:
if error.errno not in (errno.ENOENT,errno.ESRCH):raise
continue
return [value for path in refs for value in (path,path.resolve())]
def marked(p):
return any((p/name).exists() or (p/name).is_symlink() for name in ('.retain','.protect'))
def linked_ancestor(p):
return any(q.is_symlink() for q in (p,*p.parents))
def valid_snapshot(p):
# Links may count among the protected snapshots, but are never deletion candidates.
try:
for name in ('PlotLine.dll','PlotLine.runtimeconfig.json','PlotLine.deps.json'):
info=(p/name).lstat()
if not stat.S_ISREG(info.st_mode) or (name.endswith('.json') and info.st_size>32*1024*1024):return False
with (p/'PlotLine.dll').open('rb') as stream:
if stream.read(2)!=b'MZ':return False
runtime=json.loads((p/'PlotLine.runtimeconfig.json').read_text())
deps=json.loads((p/'PlotLine.deps.json').read_text())
return isinstance(runtime.get('runtimeOptions'),dict) and isinstance(deps.get('targets'),dict)
except (OSError,ValueError,TypeError,AttributeError):return False
def read_pins():
# A publisher cannot change administrator pins or redirect their configuration.
for path in (PINS,*PINS.parents):
info=path.lstat()
if path.is_symlink() or info.st_uid!=0 or info.st_mode&0o022:
raise RuntimeError('Untrusted retention pin configuration')
if not stat.S_ISREG(PINS.lstat().st_mode):raise RuntimeError('Retention pins must be a regular file')
data=json.loads(PINS.read_text())
if not isinstance(data.get('paths'),list) or any(not isinstance(p,str) or not Path(p).is_absolute() or '..' in Path(p).parts for p in data['paths']):
raise RuntimeError('Retention pins require exact absolute paths')
return [value for p in data['paths'] for value in (Path(p),Path(p).resolve())]
def registered_worktrees():
# Reuse Atlas's installed secret-free Git inspection, not repository-controlled
# configuration under root. The public CLI does not allow `worktree`; its trusted
# underlying reader accepts this fixed metadata operation in the same namespace.
module=Path('/usr/local/lib/atlas-security/git_snapshot.py')
for path in (module,*module.parents):
info=path.lstat()
if path.is_symlink() or info.st_uid!=0 or info.st_mode&0o022:
raise RuntimeError('Trusted Git inspector unavailable')
code="import sys;sys.path.insert(0,'/usr/local/lib/atlas-security');from git_snapshot import read;sys.stdout.buffer.write(read(sys.argv[1],'-c','safe.directory=/input','worktree','list','--porcelain','-z'))"
listing=subprocess.check_output(['/usr/bin/python3','-I','-c',code,str(REPOSITORY)],text=True,timeout=40)
return [REPOSITORY if line[9:]=='/input' else Path(line[9:]) for line in listing.split('\0') if line.startswith('worktree ')]
def protections(active,legacy,root=None):
return [active,legacy/'current',legacy/'App_Data',legacy/'uploads',(root or ROOT)/'shared',*read_pins(),*registered_worktrees(),*process_refs()]
def mount_points():
def decode(value):
return re.sub(r'\\([0-7]{3})',lambda m:chr(int(m[1],8)),value)
return {Path(decode(line.split()[4])) for line in Path('/proc/self/mountinfo').read_text().splitlines()}
def inspect(p, published=True, age=0, bound=False):
"""Refuse repository/source, evidence, persistent files, links and mount boundaries."""
if linked_ancestor(p) or not p.is_dir():return 'link/non-directory or linked ancestor'
mounts=mount_points()
if p in mounts or os.path.ismount(p):return 'mount boundary'
if any((q/'.git').exists() or (q/'.git').is_symlink() for q in (p,*p.parents)):return 'repository/source ancestor'
if any(p/name in mounts for name in ('PlotLine.dll','PlotLine.runtimeconfig.json','PlotLine.deps.json')):return 'mount boundary'
if not valid_snapshot(p):return 'not a recognised application publish'
if re.search(r'rollback|restore|acceptance|retain|evidence|baseline',p.name,re.I):return 'named protected package'
entries=list(p.iterdir())
if published:
unknown=[x.name for x in entries if not (bound and x.is_symlink()) and x.name not in ASSETS and not x.name.endswith(('.dll','.pdb','.deps.json','.runtimeconfig.json','.staticwebassets.endpoints.json'))]
if unknown:return 'source/evidence/unknown entries: '+','.join(unknown[:4])
cutoff=time.time()-age
device=p.stat().st_dev
for base,dirs,files in os.walk(p,followlinks=False):
for name in dirs+files:
q=Path(base)/name;s=q.lstat()
if s.st_dev!=device or q in mounts or (name in dirs and os.path.ismount(q)):return 'mount boundary'
if name.casefold() in {'.retain','.protect'}:return 'retention marker'
if age and s.st_mtime>cutoff:return 'recent content'
if bound and q.is_symlink():
dest=q.resolve(strict=True)
if dest.is_relative_to(ROOT/'shared') or dest.is_relative_to(LEGACY/'current'):continue
return 'unexpected runtime binding'
if name.casefold() in {value.casefold() for value in SENSITIVE} or name.casefold().endswith(SOURCE_SUFFIXES):return 'source, pin, evidence or persistent content: '+name
if q.is_symlink():return 'contains symlink; preserve for review'
if age and p.stat().st_mtime>cutoff:return 'recent directory'
return None
def plan(root=None,legacy=None):
root=root or ROOT;legacy=legacy or LEGACY
active=(root/'current').resolve(strict=True)
if active.parent.parent!=root/'releases' or active.name!='app':raise RuntimeError('Unsafe active release target')
marker=json.loads((root/'active-deployment.json').read_text())
if marker['release']!=active.parent.name:raise RuntimeError('Active marker/symlink mismatch')
receipts=[json.loads(p.read_text()) for p in (root/'deployment-receipts').glob('*.json')]
keep,successful=success_keep(receipts,active.parent.name)
protected=protections(active,legacy,root)
candidates=[];retained=[]
def add(p,category,age=0):
reason=next(('referenced/protected' for ref in protected if overlaps(p,ref)),None)
if reason is None:reason=inspect(p,age=age)
if reason:retained.append((str(p),reason))
else:candidates.append((str(p),category))
for p in sorted((root/'releases').iterdir()):
if p.name in keep:retained.append((str(p),'active/recent successful release'));continue
if p.name not in successful:retained.append((str(p),'no success receipt; preserve'));continue
if re.search('rollback|restore|acceptance|baseline',p.name,re.I):retained.append((str(p),'named recovery package'));continue
# Keep manifest, SQL and qualification evidence; prune only the old runtime payload.
app=p/'app'
if not app.exists():continue
if p.is_symlink() or any(overlaps(p,r) for r in protected) or marked(p):
retained.append((str(p),'referenced/protected'));continue
reason=inspect(app,bound=True)
if reason:retained.append((str(p),reason))
else:candidates.append((str(app),'manifest-release-payload'))
# The legacy deployment system stopped in November; keep three newest valid snapshots,
# including archives linked onto the root filesystem. They are explicit recovery pins.
snaps=sorted(legacy.glob('current-before-*'),key=lambda p:(p.lstat().st_mtime,p.name),reverse=True)
valid=[p for p in snaps if valid_snapshot(p)]
for p in snaps:
if p in valid[:3]:retained.append((str(p),'three latest valid installation snapshots'))
else:add(p,'installation-snapshot')
if (legacy/'releases').is_dir() and not linked_ancestor(legacy/'releases'):
for p in sorted((legacy/'releases').iterdir()):add(p,'legacy-release')
for base,pattern,category,age in [(TEMPORARY,'plotdirector-dev-publish-*','temporary-publish',48*3600),(BUILDS,'*','build-package',7*86400)]:
for p in sorted(Path(base).glob(pattern)):
if p.is_dir():add(p,category,age)
return candidates,retained,active
def candidate_scope(p,category):
if not p.is_absolute() or linked_ancestor(p):return False
return {
'manifest-release-payload':p.name=='app' and p.parent.parent==ROOT/'releases',
'legacy-release':p.parent==LEGACY/'releases',
'installation-snapshot':p.parent==LEGACY and p.name.startswith('current-before-'),
'temporary-publish':p.parent==TEMPORARY and p.name.startswith('plotdirector-dev-publish-'),
'build-package':p.parent==BUILDS,
}.get(category,False)
@contextmanager
def directory_fd(path):
# Anchor removal through every ancestor without following a substituted link.
fd=os.open('/',os.O_RDONLY|os.O_DIRECTORY)
try:
for component in path.parts[1:]:
child=os.open(component,os.O_RDONLY|os.O_DIRECTORY|os.O_NOFOLLOW,dir_fd=fd)
os.close(fd);fd=child
yield fd
finally:os.close(fd)
def remove_candidate(p):
if not shutil.rmtree.avoids_symlink_attacks:raise RuntimeError('Symlink-safe removal unavailable')
identity=p.lstat()
with directory_fd(p.parent) as parent:
actual=os.stat(p.name,dir_fd=parent,follow_symlinks=False)
if (actual.st_dev,actual.st_ino)!=(identity.st_dev,identity.st_ino) or not stat.S_ISDIR(actual.st_mode):
raise RuntimeError('Candidate replaced during removal')
shutil.rmtree(p.name,dir_fd=parent)
def run(apply=False):
if socket.gethostname()!='atlas' or os.geteuid()!=0:raise RuntimeError('Atlas root only')
with (ROOT/'deployment.lock').open('r+') as lock:
fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
preflight()
candidates,retained,active=plan()
print(json.dumps({'retained_count':len(retained)} if apply else {'retained':retained}),flush=True)
before=shutil.disk_usage('/srv').free; totals={}; processed=0
for name,category in candidates:
p=Path(name)
if (ROOT/'current').resolve()!=active:raise RuntimeError('Active release changed')
if not candidate_scope(p,category):raise RuntimeError('Candidate outside approved physical scope')
# Pins, source, mounts, age, registered worktrees and processes may have
# changed since planning. Recheck immediately before any deletion.
protected=protections(active,LEGACY)
age={'temporary-publish':48*3600,'build-package':7*86400}.get(category,0)
reason=next(('referenced/protected' for ref in protected if overlaps(p,ref)),None)
if category=='manifest-release-payload' and marked(p.parent):reason='release retention marker'
reason=reason or inspect(p,age=age,bound=category=='manifest-release-payload')
if reason:
print('PRESERVE '+category+' '+name+' reason='+reason,flush=True);continue
blocks=sum(q.lstat().st_blocks*512 for base,dirs,files in os.walk(p) for q in [Path(base),*(Path(base)/n for n in files)])
print(('REMOVE ' if apply else 'WOULD REMOVE ')+category+' '+name+' bytes='+str(blocks),flush=True)
totals[category]=totals.get(category,0)+blocks
processed+=1
if apply:remove_candidate(p)
print(json.dumps({'apply':apply,'directories':processed,'planned_directories':len(candidates),'estimated_bytes':totals,'srv_available_increase':shutil.disk_usage('/srv').free-before}),flush=True)
preflight()
if __name__=='__main__':
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--apply',action='store_true');args=parser.parse_args()
run(args.apply)

View File

@ -4,6 +4,7 @@ from unittest.mock import patch
import activate
import development
import retention
from release import Refused
@ -44,13 +45,34 @@ class DevelopmentBoundaryTests(unittest.TestCase):
with self.subTest(operation=operation), \
patch.object(development.sys, 'argv', ['helper', '--'+operation, 'fixture']), \
patch.object(development.os, 'umask'), patch.object(development.signal, 'signal'), \
patch.object(development.signal, 'alarm'), patch.object(activate, 'activate') as run:
patch.object(development.signal, 'alarm'), patch.object(retention, 'preflight'), \
patch.object(retention, 'run') as prune, patch.object(activate, 'activate') as run:
development.main()
if operation == 'validate':prune.assert_not_called()
else:prune.assert_called_once_with(apply=True)
self.assertEqual(run.call_args.args, ('fixture',))
self.assertIsInstance(run.call_args.kwargs['profile'], development.Development)
self.assertEqual(run.call_args.kwargs['validate'], operation == 'validate')
self.assertEqual(run.call_args.kwargs['rollback'], operation == 'rollback')
def test_failed_activation_never_prunes(self):
with patch.object(development.sys, 'argv', ['helper', '--activate', 'fixture']), \
patch.object(development.os, 'umask'), patch.object(development.signal, 'signal'), \
patch.object(development.signal, 'alarm'), patch.object(retention, 'preflight'), \
patch.object(retention, 'run') as prune, patch.object(activate, 'activate', side_effect=Refused('fixture')):
with self.assertRaises(Refused):development.main()
prune.assert_not_called()
def test_cleanup_failure_does_not_reclassify_successful_activation(self):
with patch.object(development.sys, 'argv', ['helper', '--activate', 'fixture']), \
patch.object(development.os, 'umask'), patch.object(development.signal, 'signal'), \
patch.object(development.signal, 'alarm'), patch.object(retention, 'preflight'), \
patch.object(retention, 'run', side_effect=BlockingIOError()), \
patch.object(activate, 'activate') as run, patch('builtins.print') as report:
development.main()
run.assert_called_once()
report.assert_called_once_with('WARNING Development retention skipped/failed: BlockingIOError')
def test_implicit_activation_is_refused(self):
with patch.object(development.sys, 'argv', ['helper', 'fixture']), \
patch.object(development.os, 'umask'), patch.object(development.signal, 'signal'), \

View File

@ -0,0 +1,224 @@
import contextlib
import importlib.util
import io
import json
import os
from pathlib import Path
import tempfile
import time
import unittest
from unittest.mock import patch
from types import SimpleNamespace
spec=importlib.util.spec_from_file_location('retention',Path(__file__).with_name('retention.py'))
r=importlib.util.module_from_spec(spec);spec.loader.exec_module(r)
class RetentionTests(unittest.TestCase):
def artifact(self,root,name='publish'):
p=Path(root)/name;p.mkdir(parents=True)
(p/'PlotLine.dll').write_bytes(b'MZcompiled fixture')
(p/'PlotLine.runtimeconfig.json').write_text('{"runtimeOptions":{}}')
(p/'PlotLine.deps.json').write_text('{"targets":{}}')
return p
def receipt(self,name,index,status='activated'):
return {'status':status,'completed_utc':f'2026-11-30T10:00:{index:02d}+00:00','release':{'id':name}}
def test_active_and_three_distinct_successful_previous(self):
receipts=[self.receipt(name,i) for i,name in enumerate(['active','old','one','two','two','three'])]
receipts.append(self.receipt('failed',9,'failed'))
keep,successful=r.success_keep(receipts,'active')
self.assertEqual(keep,{'active','one','two','three'});self.assertNotIn('failed',successful)
def test_receipt_order_uses_instants_not_offset_string_order(self):
receipts=[self.receipt('one',1),self.receipt('two',2),self.receipt('three',3),self.receipt('four',4)]
receipts[0]['completed_utc']='2026-11-30T11:00:00+02:00'
self.assertEqual(r.success_keep(receipts,'active')[0],{'active','two','three','four'})
def test_source_and_repository_preserved(self):
for name in ['source-tracked.patch','source.cs','.git','acceptance']:
with self.subTest(name=name),tempfile.TemporaryDirectory() as d:
p=self.artifact(d);(p/name).touch();self.assertIsNotNone(r.inspect(p))
def test_unknown_files_preserved(self):
with tempfile.TemporaryDirectory() as d:
p=self.artifact(d);(p/'important.txt').touch();self.assertIsNotNone(r.inspect(p))
def test_case_insensitive_nested_evidence_and_sources_preserved(self):
for name in ['Evidence','Acceptance','SOURCE.CS','CHANGES.PATCH','schema.sql','view.cshtml','Uploads']:
with self.subTest(name=name),tempfile.TemporaryDirectory() as d:
p=self.artifact(d);(p/'Data').mkdir();(p/'Data'/name).touch()
self.assertIsNotNone(r.inspect(p))
def test_named_restore_package_preserved(self):
with tempfile.TemporaryDirectory() as d:
self.assertIsNotNone(r.inspect(self.artifact(d,'restore-candidate')))
def test_symlinks_not_followed(self):
with tempfile.TemporaryDirectory() as d:
p=self.artifact(d);(p/'Data').symlink_to('/etc');self.assertIsNotNone(r.inspect(p))
def test_symlinked_ancestor_preserved(self):
with tempfile.TemporaryDirectory() as d:
root=Path(d);p=self.artifact(root/'physical');(root/'alias').symlink_to(root/'physical')
self.assertIsNotNone(r.inspect(root/'alias'/p.name))
def test_publish_under_a_repository_is_preserved(self):
with tempfile.TemporaryDirectory() as d:
root=Path(d);(root/'.git').mkdir();p=self.artifact(root/'output')
self.assertIsNotNone(r.inspect(p))
def test_bind_mount_root_or_descendant_preserved_even_on_same_device(self):
with tempfile.TemporaryDirectory() as d:
p=self.artifact(d);(p/'Data').mkdir()
for mounted in [p,p/'Data',p/'PlotLine.dll']:
with self.subTest(mounted=mounted),patch.object(r,'mount_points',return_value={mounted}),patch.object(r.os.path,'ismount',return_value=False):
self.assertEqual(r.inspect(p),'mount boundary')
def test_bound_runtime_links_allowed_but_retain_marker_wins(self):
with tempfile.TemporaryDirectory() as d:
root=Path(d);shared=root/'shared';shared.mkdir();(shared/'data').mkdir()
p=self.artifact(root);(p/'App_Data').symlink_to(shared/'data')
with patch.object(r,'ROOT',root):
self.assertIsNone(r.inspect(p,bound=True))
(p/'.retain').symlink_to(shared/'data');self.assertIsNotNone(r.inspect(p,bound=True))
def test_recent_and_abandoned_outputs_use_all_descendant_times(self):
with tempfile.TemporaryDirectory() as d:
p=self.artifact(d);self.assertIsNone(r.inspect(p));self.assertIsNotNone(r.inspect(p,age=172800))
old=time.time()-200000
for f in [p,*p.iterdir()]:os.utime(f,(old,old))
self.assertIsNone(r.inspect(p,age=172800))
(p/'PlotLine.dll').touch();self.assertIsNotNone(r.inspect(p,age=172800))
def test_corrupt_or_incomplete_snapshots_do_not_count_as_valid(self):
with tempfile.TemporaryDirectory() as d:
p=self.artifact(d);self.assertTrue(r.valid_snapshot(p))
(p/'PlotLine.runtimeconfig.json').write_text('broken')
self.assertFalse(r.valid_snapshot(p));self.assertIsNotNone(r.inspect(p))
def test_snapshot_metadata_links_and_special_files_are_not_read(self):
for kind in ('link','fifo'):
with self.subTest(kind=kind),tempfile.TemporaryDirectory() as d:
p=self.artifact(d);meta=p/'PlotLine.runtimeconfig.json';meta.unlink()
if kind=='link':meta.symlink_to(p/'PlotLine.deps.json')
else:os.mkfifo(meta)
self.assertFalse(r.valid_snapshot(p))
self.assertIsNotNone(r.inspect(p))
def test_references_protect_ancestors_and_descendants(self):
p=Path('/releases/active');self.assertTrue(r.overlaps(p,p/'app/PlotLine.dll'))
self.assertTrue(r.overlaps(p,p.parent));self.assertFalse(r.overlaps(p,Path('/releases/active-old')))
@contextlib.contextmanager
def layout(self):
with tempfile.TemporaryDirectory() as d,contextlib.ExitStack() as stack:
base=Path(d);root=base/'runtime';legacy=base/'legacy';temporary=base/'tmp';builds=base/'builds'
for p in [root/'releases',root/'deployment-receipts',legacy/'releases',temporary,builds]:p.mkdir(parents=True,exist_ok=True)
for i,name in enumerate(['old','one','two','three','active']):
self.artifact(root/'releases'/name,'app')
(root/'releases'/name/'manifest.json').write_text('{"preserve":"metadata"}')
(root/'deployment-receipts'/(name+'.json')).write_text(json.dumps(self.receipt(name,i)))
(root/'deployment.lock').touch()
(root/'current').symlink_to(root/'releases/active/app')
(root/'active-deployment.json').write_text('{"release":"active"}')
for key,value in dict(ROOT=root,LEGACY=legacy,TEMPORARY=temporary,BUILDS=builds).items():stack.enter_context(patch.object(r,key,value))
for key in ('read_pins','registered_worktrees','process_refs'):stack.enter_context(patch.object(r,key,return_value=[]))
stack.enter_context(patch.object(r,'preflight'))
stack.enter_context(patch.object(r.socket,'gethostname',return_value='atlas'))
stack.enter_context(patch.object(r.os,'geteuid',return_value=0))
yield root,legacy,temporary,builds
def test_plan_preserves_active_three_previous_unknown_and_pinned_releases(self):
with self.layout() as (root,legacy,*_):
unknown=self.artifact(root/'releases'/'no-receipt','app')
candidates,retained,active=r.plan()
self.assertEqual(candidates,[(str(root/'releases/old/app'),'manifest-release-payload')])
self.assertTrue(unknown.exists());self.assertEqual(active,root/'releases/active/app')
with patch.object(r,'read_pins',return_value=[root/'releases/old']):self.assertEqual(r.plan()[0],[])
def test_plan_rejects_marker_mismatch(self):
with self.layout() as (root,*_):
(root/'active-deployment.json').write_text('{"release":"different"}')
with self.assertRaises(RuntimeError):r.plan()
def test_three_newest_valid_snapshots_preserved_and_archived_links_never_pruned(self):
with self.layout() as (_,legacy,*_):
snapshots=[self.artifact(legacy,'current-before-'+str(i)) for i in range(5)]
for i,p in enumerate(snapshots):os.utime(p,(100+i,100+i))
(snapshots[-1]/'PlotLine.runtimeconfig.json').write_text('broken')
link=legacy/'current-before-archive';link.symlink_to(snapshots[2])
candidates,retained,_=r.plan()
self.assertNotIn(str(link),[p for p,c in candidates])
self.assertNotIn(str(snapshots[-1]),[p for p,c in candidates])
valid_kept=[p for p,reason in retained if reason=='three latest valid installation snapshots']
self.assertEqual(len(valid_kept),3)
def test_dry_run_changes_nothing_and_apply_only_removes_payload(self):
with self.layout() as (root,*_),contextlib.redirect_stdout(io.StringIO()):
app=root/'releases/old/app';r.run();self.assertTrue(app.exists())
r.run(apply=True);self.assertFalse(app.exists())
self.assertTrue((root/'releases/old/manifest.json').exists())
self.assertTrue((root/'releases/active/app').exists())
r.run(apply=True) # idempotent
def test_source_or_pin_added_after_plan_is_preserved(self):
for kind in ('source','pin','process','mount'):
with self.subTest(kind=kind),self.layout() as (root,*_),contextlib.redirect_stdout(io.StringIO()):
original=r.plan
app=root/'releases/old/app'
def changed():
result=original()
if kind=='source':(app/'source.patch').write_text('keep')
elif kind=='pin':(app.parent/'.retain').touch()
elif kind=='process':r.process_refs.return_value=[app/'PlotLine.dll']
elif kind=='mount':r.mount_points=lambda:{app}
return result
# Keep mount patches scoped independently of the other fixture cases.
with patch.object(r,'mount_points',wraps=r.mount_points),patch.object(r,'plan',side_effect=changed):r.run(apply=True)
self.assertTrue(app.exists())
def test_scope_refuses_production_or_substituted_paths(self):
with self.layout() as (root,legacy,tmp,builds):
self.assertFalse(r.candidate_scope(Path('/srv/plotdirector/releases/old/app'),'manifest-release-payload'))
self.assertFalse(r.candidate_scope(root/'current','legacy-release'))
self.assertFalse(r.candidate_scope(tmp/'unrelated','temporary-publish'))
self.assertTrue(r.candidate_scope(builds/'known','build-package'))
def test_substituted_parent_cannot_redirect_removal(self):
with tempfile.TemporaryDirectory() as d:
base=Path(d);parent=base/'parent';app=self.artifact(parent);outside=self.artifact(base/'outside')
original=r.directory_fd
@contextlib.contextmanager
def substituted(path):
parent.rename(base/'saved');parent.symlink_to(outside.parent)
with original(path) as fd:yield fd
with patch.object(r,'directory_fd',substituted),self.assertRaises(OSError):r.remove_candidate(app)
self.assertTrue(outside.exists());self.assertTrue((base/'saved'/app.name).exists())
def test_pin_configuration_rejects_untrusted_ownership_and_relative_paths(self):
with tempfile.TemporaryDirectory() as d:
p=Path(d)/'pins.json';p.write_text('{"paths":["relative"]}')
# Root trust is checked before the content is used, independently of tests' uid.
with patch.object(r,'PINS',p),self.assertRaises(RuntimeError):r.read_pins()
trusted=SimpleNamespace(st_uid=0,st_mode=0o100600)
with patch.object(r,'PINS',p),patch.object(Path,'lstat',return_value=trusted),patch.object(Path,'is_symlink',return_value=False):
with self.assertRaisesRegex(RuntimeError,'exact absolute'):r.read_pins()
p.write_text('{"paths":["/srv/tmp/protected"]}')
self.assertIn(Path('/srv/tmp/protected'),r.read_pins())
def test_git_worktrees_use_fixed_isolated_metadata_reader(self):
trusted=SimpleNamespace(st_uid=0,st_mode=0o100644)
with patch.object(Path,'lstat',return_value=trusted),patch.object(Path,'is_symlink',return_value=False),patch.object(r.subprocess,'check_output',return_value='worktree /input\0HEAD hash\0\0worktree /srv/tmp/keep me\0') as command:
self.assertEqual(r.registered_worktrees(),[r.REPOSITORY,Path('/srv/tmp/keep me')])
args=command.call_args.args[0]
self.assertEqual(args[:3],['/usr/bin/python3','-I','-c'])
self.assertIn("'worktree','list','--porcelain','-z'",args[3])
def test_other_host_or_non_root_refused_before_planning(self):
for host,uid in [('web1',0),('atlas',1000)]:
with patch.object(r.socket,'gethostname',return_value=host),patch.object(r.os,'geteuid',return_value=uid),patch.object(r,'plan') as plan:
with self.assertRaises(RuntimeError):r.run(True)
plan.assert_not_called()
if __name__=='__main__':unittest.main()