feat(ci): run one bounded unattended Stage editorial acceptance
Bounded Stage v4 credential acceptance window / acceptance-window (push) Failing after 12s

This commit is contained in:
Hermes Agent committed 2026-10-24 15:52:24 +00:00
1 parent b879687bc4
commit 32d7116ce7
7 files changed
+232 -53

No files matched your search

+5 -5
View File
@@ -2,14 +2,14 @@ name: Bounded Stage v4 credential acceptance window
on:
push:
branches:
- ci/v4-stage-acceptance
- ci/v4-stage-acceptance-timeout-860324e
jobs:
acceptance-window:
if: github.ref == 'refs/heads/ci/v4-stage-acceptance'
if: github.ref == 'refs/heads/ci/v4-stage-acceptance-timeout-860324e'
runs-on: canina
timeout-minutes: 12
steps:
- name: Open fixed Stage session and finally close (no model calls)
- name: Bounded Stage acceptance with guaranteed generation-fenced close
shell: bash
env:
BRANCH: ${{ github.ref_name }}
@@ -20,11 +20,11 @@ jobs:
run: |
set -euo pipefail
set +x
[[ "$BRANCH" == ci/v4-stage-acceptance && "$DEPLOY_SHA" =~ ^[a-f0-9]{40}$ && "$GITHUB_RUN_ATTEMPT" == 1 ]] || exit 2
[[ "$BRANCH" == ci/v4-stage-acceptance-timeout-860324e && "$DEPLOY_SHA" =~ ^[a-f0-9]{40}$ && "$GITHUB_RUN_ATTEMPT" == 1 ]] || exit 2
umask 077
scratch=$(mktemp -d)
trap 'rm -rf "$scratch"' EXIT
for file in ci-stage-acceptance.sh ci-stage-test-principal.sh; do
for file in ci-stage-acceptance.sh ci-stage-test-principal.sh stage-editorial-acceptance.py; do
wget --no-proxy -qO "$scratch/$file" "https://git.parsaaghayi.ir/parsa/canina/raw/commit/$DEPLOY_SHA/scripts/$file"
done
bash "$scratch/ci-stage-acceptance.sh"
+40 -27
View File
@@ -1,31 +1,44 @@
# Bounded Stage credential window (not full acceptance)
# Bounded unattended Stage acceptance
Activation: parent reviews this commit and pushes `ci/v4-stage-acceptance` once.
Only that exact branch activates `stage-v4-acceptance.yml`; develop/main pushes
cannot activate it. No deploy is performed. Workflow scripts are downloaded from
the triggering immutable SHA; the existing reviewed host principal entrypoint
is pinned separately to deployed Stage artifact
`f7055111648906a6a328c973c354c90bd559ef65`. Existing host worker verifies the actual
container artifact SHA before opening and requires the durable cleanup timer.
Parent review/activation only: push exact branch
`ci/v4-stage-acceptance-timeout-860324e` once. No push or model execution was
performed while preparing this branch. Do not merge this one-shot workflow into
develop. The previous session/branch must never be reused.
Fixed grant: `owner-authorized-stage-editorial`, session
`v4-ci-acceptance-20261024`, TTL 600 seconds. The driver waits 480 seconds for the
parent's authenticated HTTP acceptance, then closes in EXIT; partial/failed opens
also attempt close. Runner loss retains the already-reviewed durable host cleanup
journal/timer. CI reruns are rejected before opening. Do not push this branch
again or retry a failed paid orchestration attempt blindly.
Pinned deployed SHA: `860324e3a91b31c2b6d4e784e458f6d120582cb8`.
Fixed session: `v4-ci-timeout-860324e-20261024`, TTL600 seconds, acceptance
hard window480 seconds. Exact branch plus run_attempt1 required. Durable
exclusive session intent rejects subsequent opens even if the CI attempt field
is reset. EXIT always attempts existing generation-fenced close; durable timer
retains cleanup through runner/SSH loss. Nothing redesigns account provisioning.
The existing CLI performs real persisted-account HTTP login and writes its private
handle in the Stage backend at
`/app/private-stage-test/v4-ci-acceptance-20261024.json`. Never print/copy this
handle into CI artifacts or stdout; use its token only process-locally for actual
authenticated HTTP tests. This workflow does NOT execute orchestration, create a
proposal, approve Gate1, run a model, or claim domain acceptance.
The tracked host Python script requires the exact SHA's successful deploy log,
backend artifact and installed editorial package SHA. It reads the Stage private
login handle and existing PMO worker credential only into process memory; no
public bootstrap, secret stdout, direct DB access or Production writes.
Parent acceptance still required during the credential window: authenticated
recovery of stuck task `754d70d6-d4c5-4ebc-860b-c5c7584201a0` using its actual
runID; a new PMO proposal and independent Gate1 budget 20; runner as hermes;
artifact readback. Preserve the unknown prior 20. At most one additional bounded
attempt; stop on failure (including competitor timeout). No Gate2, Production,
cron, self-review, backend-role bypass or forged JWT. Read back cleanup after the
window; CI success proves credential-window lifecycle only, NOT acceptance.
It copies the exact topic and criteria from the unique FAILED v5 task starting
`4a109`, preserves all prior FAILED editorial ledgers (must total unknown60),
creates one fixed-request-id20 proposal through PMO transport, reviews Gate1 as
the independently authenticated temporary SUPER_ADMIN, queues via PMO, then runs
the installed runner once as hermes. Explicit owner authorization for this
bounded Stage test is required; this is not independent content QA.
Runner total330 seconds plus preflight/recovery stays within the480 bound;
profile cap120 and CLI30 headroom remain unchanged. If it stops in RUNNING,
the script waits for lease expiry and uses the existing narrow editorial-failure
HTTP contract, preserving unknown20. No retry or reconciliation/zero-cost claim.
Hard process/transport loss can prevent this failure fence; state then requires
read-back, not a new attempt. Account close still has durable600 backstop.
Success requires authenticated status VERIFYING, actual artifact bytes/digest
and task/deployed-SHA binding, PENDING_INDEPENDENT_QA, fresh reserved20 and
unchanged prior unknown60. No publication, image generation, Production changes,
cron, fabricated QA, fabricated cost or provider503 attribution.
Checks: `python3 scripts/test_stage_editorial_acceptance.py`,
`python3 scripts/test_ci_stage_acceptance.py`, existing cleanup tests and runner
tests. Transport fixtures exercise open/accept/finally-close and failure-close;
they are not live acceptance. Parent must review the SSH sudo streaming Python
execution boundary before activation. CI1454 was observed successful for the
pinned SHA; that observation is also rechecked by the script before model work.
+6 -7
View File
@@ -1,12 +1,12 @@
#!/usr/bin/env bash
# One bounded credential window only; no deploy, model call or orchestration mutation.
# One bounded Stage acceptance only; never deploy, retry, reconcile or publish.
set -euo pipefail
set +x
[[ $# == 0 && ${GITHUB_ACTIONS:-${GITEA_ACTIONS:-}} == true && ${BRANCH:-} == ci/v4-stage-acceptance && ${GITHUB_RUN_ATTEMPT:-} == 1 && ${DEPLOY_SHA:-} =~ ^[a-f0-9]{40}$ ]] || exit 2
[[ $# == 0 && ${GITHUB_ACTIONS:-${GITEA_ACTIONS:-}} == true && ${BRANCH:-} == ci/v4-stage-acceptance-timeout-860324e && ${GITHUB_RUN_ATTEMPT:-} == 1 && ${DEPLOY_SHA:-} =~ ^[a-f0-9]{40}$ ]] || exit 2
# Separate workflow source SHA from the immutable, already-deployed Stage artifact.
export DEPLOY_SHA=f7055111648906a6a328c973c354c90bd559ef65
export DEPLOY_SHA=860324e3a91b31c2b6d4e784e458f6d120582cb8
export STAGE_TEST_APPROVAL=owner-authorized-stage-editorial
export STAGE_TEST_SESSION=v4-ci-acceptance-20261024
export STAGE_TEST_SESSION=v4-ci-timeout-860324e-20261024
export STAGE_TEST_TTL_SECONDS=600
wrapper="$(dirname "${BASH_SOURCE[0]}")/ci-stage-test-principal.sh"
close() {
@@ -25,6 +25,5 @@ trap 'exit 130' INT
trap 'exit 143' TERM HUP
export STAGE_TEST_ACTION=open
bash "$wrapper"
printf 'Stage credential window opened; authenticated acceptance NOT performed by this workflow\n'
# Keep the reviewed principal available for parent HTTP tests; timer is a hard backstop.
sleep 480
export STAGE_TEST_ACTION=accept
bash "$wrapper"
+9 -4
View File
@@ -6,12 +6,12 @@ fail() { printf 'ERROR: %s\n' "$1" >&2; exit 2; }
[[ ${GITHUB_ACTIONS:-${GITEA_ACTIONS:-}} == true && $# == 0 ]] || fail 'CI-only Stage operation'
case ${BRANCH:-} in
develop) ;;
ci/v4-stage-acceptance)
[[ ${DEPLOY_SHA:-} == f7055111648906a6a328c973c354c90bd559ef65 && ${STAGE_TEST_SESSION:-} == v4-ci-acceptance-20261024 && ${STAGE_TEST_TTL_SECONDS:-} == 600 ]] || fail 'fixed acceptance scope required'
ci/v4-stage-acceptance-timeout-860324e)
[[ ${DEPLOY_SHA:-} == 860324e3a91b31c2b6d4e784e458f6d120582cb8 && ${STAGE_TEST_SESSION:-} == v4-ci-timeout-860324e-20261024 && ${STAGE_TEST_TTL_SECONDS:-} == 600 ]] || fail 'fixed acceptance scope required'
;;
*) fail 'Stage branch required; Production is blocked' ;;
esac
[[ ${STAGE_TEST_ACTION:-} != open || ${BRANCH:-} != ci/v4-stage-acceptance || ${GITHUB_RUN_ATTEMPT:-} == 1 ]] || fail 'acceptance reruns blocked'
[[ ${STAGE_TEST_ACTION:-} != open || ${BRANCH:-} != ci/v4-stage-acceptance-timeout-860324e || ${GITHUB_RUN_ATTEMPT:-} == 1 ]] || fail 'acceptance reruns blocked'
[[ ${DEPLOY_SHA:-} =~ ^[0-9a-f]{40}$ ]] || fail 'immutable DEPLOY_SHA required'
# Repository secret DEPLOY_KEY is the historical approved devops SSH credential.
# Never fall back to baked-in runner keys, agent forwarding or docker.sock.
@@ -25,6 +25,11 @@ printf '%s\n' "$DEPLOY_KNOWN_HOSTS" > "$scratch/known_hosts"
printf '%s\n' "$DEPLOY_KEY" > "$scratch/key"
unset DEPLOY_KEY DEPLOY_KNOWN_HOSTS
ssh-keygen -F '[87.248.133.138]:2234' -f "$scratch/known_hosts" >/dev/null || fail 'DEPLOY_KNOWN_HOSTS has no pinned deployment endpoint'
[[ ${STAGE_TEST_SESSION:-} =~ ^[a-z0-9-]{8,64}$ && ${STAGE_TEST_TTL_SECONDS:-} =~ ^[0-9]+$ && ${STAGE_TEST_ACTION:-} =~ ^(open|close)$ && ${STAGE_TEST_APPROVAL:-} == owner-authorized-stage-editorial ]] || fail 'explicit owner Stage test grant required'
[[ ${STAGE_TEST_SESSION:-} =~ ^[a-z0-9-]{8,64}$ && ${STAGE_TEST_TTL_SECONDS:-} =~ ^[0-9]+$ && ${STAGE_TEST_ACTION:-} =~ ^(open|close|accept)$ && ${STAGE_TEST_APPROVAL:-} == owner-authorized-stage-editorial ]] || fail 'explicit owner Stage test grant required'
[[ $STAGE_TEST_TTL_SECONDS -ge 60 && $STAGE_TEST_TTL_SECONDS -le 3600 ]] || exit 2
if [[ $STAGE_TEST_ACTION == accept ]]; then
[[ $BRANCH == ci/v4-stage-acceptance-timeout-860324e && $GITHUB_RUN_ATTEMPT == 1 ]] || fail 'acceptance scope required'
ssh -F /dev/null -T -p 2234 -i "$scratch/key" -o BatchMode=yes -o IdentitiesOnly=yes -o IdentityAgent=none -o StrictHostKeyChecking=yes -o UserKnownHostsFile="$scratch/known_hosts" -o GlobalKnownHostsFile=/dev/null -o ConnectTimeout=15 devops@87.248.133.138 "sudo -n timeout --signal=TERM --kill-after=10 480 python3 -" < "$(dirname "${BASH_SOURCE[0]}")/stage-editorial-acceptance.py"
exit $?
fi
ssh -F /dev/null -T -p 2234 -i "$scratch/key" -o BatchMode=yes -o IdentitiesOnly=yes -o IdentityAgent=none -o StrictHostKeyChecking=yes -o UserKnownHostsFile="$scratch/known_hosts" -o GlobalKnownHostsFile=/dev/null -o ConnectTimeout=15 devops@87.248.133.138 "sudo -n env CI=true STAGE_TEST_APPROVAL=owner-authorized-stage-editorial bash /opt/services/canina/releases/$DEPLOY_SHA/scripts/stage-test-principal-host.sh $DEPLOY_SHA $STAGE_TEST_SESSION $STAGE_TEST_TTL_SECONDS $STAGE_TEST_ACTION"
+115
View File
@@ -0,0 +1,115 @@
#!/usr/bin/env python3
"""Fixed owner-authorized Stage acceptance. No automatic retry or cost reconciliation."""
import hashlib
import json
import os
from pathlib import Path
import subprocess
import sys
import time
import urllib.request
import uuid
SHA='860324e3a91b31c2b6d4e784e458f6d120582cb8'
SESSION='v4-ci-timeout-860324e-20261024'
REQUEST='6e82f843-45e4-49e3-9164-11a6879e39ba'
def proposal(prior):
if prior.get('state')!='FAILED' or prior.get('version')!=5: raise ValueError('Prior must remain FAILED v5')
scope=prior['metadata']['scope']
prefix='editorial-research-to-brief-v1\nTopic: '
suffix='\nResearch and evidence-backed brief only. No publication, release, production changes or execution authorization.'
if not scope.startswith(prefix) or not scope.endswith(suffix): raise ValueError('Exact prior scope required')
return dict(requestId=REQUEST,pilotKind='editorial-research-to-brief-v1',operationMode='PREPARE',environment='staging',scope='EDITORIAL_RESEARCH_TO_BRIEF',researchTopic=scope[len(prefix):-len(suffix)],acceptanceCriteria=prior['metadata']['acceptanceCriteria'],commitSha=SHA,budgetLimitCents=20)
def command(args,timeout=15):
return subprocess.check_output(args,stderr=subprocess.DEVNULL,timeout=timeout)
def http(base,token,route,body=None,method=None):
req=urllib.request.Request(base+'/'+route,data=None if body is None else json.dumps(body).encode(),headers={'Authorization':'Bearer '+token,'Content-Type':'application/json'},method=method or ('GET' if body is None else 'POST'))
opener=urllib.request.build_opener(urllib.request.ProxyHandler({}),NoRedirect())
with opener.open(req,timeout=10) as r:
raw=r.read(262145)
if len(raw)>262144: raise ValueError('Response bound')
return json.loads(raw)
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self,req,fp,code,msg,headers,newurl): return None
def ci_success(log):
return SHA in log and 'Deployment for develop completed successfully!' in log and '🏁 Job succeeded' in log
def verify_artifact(status,task):
artifact=status.get('artifact')
if status['state']!='VERIFYING' or not artifact: raise ValueError('Acceptance incomplete')
if hashlib.sha256(artifact['bytes'].encode()).hexdigest()!=artifact['sha256']: raise ValueError('Digest mismatch')
binding=json.loads(artifact['bytes'])
if binding['taskId']!=task or binding['commitSha']!=SHA or status['qaStatus']!='PENDING_INDEPENDENT_QA': raise ValueError('Artifact binding mismatch')
return artifact
def main():
if os.getuid()!=0 or Path('/.dockerenv').exists(): raise ValueError('Host only')
logs=Path('/opt/services/git/gitea/gitea/gitea/actions_log/parsa/canina')
if not any(ci_success(p.read_text()) for p in logs.glob('*/*.log')): raise ValueError('Exact deployed SHA CI success required')
actual=command(['docker','exec','canino_backend_stage','cat','/app/STAGE_TEST_ARTIFACT_SHA']).decode().strip()
deployed=json.loads(command(['docker','exec','canina-hermes','cat','/opt/data/editorial-v4/deployment.json']))
if actual!=SHA or deployed.get('commitSha')!=SHA: raise ValueError('Deployment mismatch')
# Strict private backend IP; no public bootstrap endpoint or direct DB writes.
networks=json.loads(command(['docker','inspect','--format','{{json .NetworkSettings.Networks}}','canino_backend_stage']))
ip=networks['stage_hermes_inventory_backend']['IPAddress']
import ipaddress
if not ipaddress.ip_address(ip).is_private: raise ValueError('Private backend required')
base='http://'+ip+':3000/api'
handle=json.loads(command(['docker','exec','canino_backend_stage','cat','/app/private-stage-test/'+SESSION+'.json']))
if handle['user']['role']!='SUPER_ADMIN' or handle['user']['id']=='pmo': raise ValueError('Independent reviewer required')
admin=handle['accessToken']; del handle
worker=command(['docker','exec','--user','hermes','canina-hermes','cat','/opt/data/editorial-v4/credentials/editorial-pmo-token']).decode().strip()
a=lambda route,body=None,method=None:http(base,admin,'admin/orchestration/'+route,body,method)
w=lambda route,body=None:http(base,worker,'internal/prepare-worker/'+route,body)
tasks=a('tasks')
prior=[t for t in tasks if t['id'].startswith('4a109')]
if len(prior)!=1: raise ValueError('Exact prior task missing')
prior=a('tasks/'+prior[0]['id'])
# Preserve all old unknown costs and fence previous failed attempts.
failed=[t for t in tasks if t.get('key','').startswith('editorial-v1:') and t['state']=='FAILED']
frozen={t['id']:a('tasks/'+t['id'])['budgetLedger'] for t in failed}
unknown=sum(sum(x['amountCents'] for x in ledger) for ledger in frozen.values())
if unknown!=60: raise ValueError('Prior unknown reservation must be 60')
p=w('editorial-proposals',proposal(prior))
if p['state']!='GATE1_PENDING' or p['version']!=2: raise ValueError('Fresh proposal only; never replay execution')
task=p['taskId']; route='tasks/'+task
approved=a(route+'/gates/1/decide',{'decision':'APPROVED','expectedVersion':p['version'],'idempotencyKey':SESSION+':gate1','expiresAt':time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime(time.time()+450)),'notes':'Explicit owner-authorized bounded Stage acceptance only; no QA/publication/Production authority.'})
if approved['state']!='GATE1_APPROVED': raise ValueError('Gate1 required')
ready=w('editorial-queue',{'taskId':task,'expectedVersion':approved['version'],'idempotencyKey':SESSION+':queue'})
if ready['state']!='READY': raise ValueError('READY required')
# Exactly one process, as hermes. Installed runner has 120-second profile cap,
# CLI headroom30 and allowlisted timing evidence. Total330 fits window480.
code="import sys,json;sys.path.insert(0,'/opt/data/editorial-v4/runtime-package');import runner;from pathlib import Path;runner.run(Path('/opt/data'),sys.argv[1],total_seconds=330)"
try:
rc=subprocess.run(['docker','exec','--user','hermes','canina-hermes','python3','-c',code,task],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,timeout=430).returncode
except subprocess.TimeoutExpired:
# No second runner; read persisted state and fence only after its lease expires.
rc=1
status=w('editorial-proposals/'+task)
if status['state']=='RUNNING':
# Let last heartbeat lease expire, then fence the artifact-free unknown attempt.
time.sleep(31)
row=a(route)
runs=[r for r in row['runs'] if r['status']=='RUNNING']
if len(runs)!=1: raise ValueError('Ambiguous recovery')
a(route+'/editorial-failure',{'runId':runs[0]['id'],'expectedVersion':row['version'],'idempotencyKey':SESSION+':stopped','reason':'Bounded acceptance stopped; cost unknown and reservation retained; no retry.'})
status=w('editorial-proposals/'+task)
for old,ledger in frozen.items():
row=a('tasks/'+old)
if row['state']!='FAILED' or row['budgetLedger']!=ledger: raise ValueError('Prior fence changed')
row=a(route)
if sum(x['amountCents'] for x in row['budgetLedger'])!=20 or any(x['kind']=='RECONCILE' for x in row['budgetLedger']): raise ValueError('Reservation changed')
if rc: raise ValueError('Acceptance incomplete; fenced unknown20')
artifact=verify_artifact(status,task)
print(json.dumps({'taskId':task,'state':status['state'],'artifactSha256':artifact['sha256'],'qaStatus':status['qaStatus'],'priorUnknownReservedCents':60,'freshReservedCents':20,'commitSha':SHA}))
if __name__=='__main__':
try: main()
except Exception:
print('Stage acceptance stopped; no retry or cost reconciliation; read authenticated status',file=sys.stderr)
sys.exit(1)
+18 -10
View File
@@ -5,13 +5,13 @@ import tempfile
import unittest
ROOT = pathlib.Path(__file__).resolve().parent
SHA = 'f7055111648906a6a328c973c354c90bd559ef65'
SHA = '860324e3a91b31c2b6d4e784e458f6d120582cb8'
class AcceptanceTests(unittest.TestCase):
def run_driver(self, branch='ci/v4-stage-acceptance', fail_open=False, attempt='1'):
def run_driver(self, branch='ci/v4-stage-acceptance-timeout-860324e', fail_open=False, attempt='1', fail_accept=False):
with tempfile.TemporaryDirectory() as d:
p = pathlib.Path(d)
(p/'ssh').write_text('#!/bin/bash\nprintf "%s\\n" "${@: -1}" >> "$CALLS"\n[[ "$FAIL_OPEN" != true || "${@: -1}" != *" open" ]]\n')
(p/'ssh').write_text('#!/bin/bash\nprintf "%s\\n" "${@: -1}" >> "$CALLS"\n[[ "$FAIL_OPEN" != true || "${@: -1}" != *" open" ]] || exit 1\n[[ "$FAIL_ACCEPT" != true || "${@: -1}" != *"480 python3 -" ]]\n')
(p/'ssh-keygen').write_text('#!/bin/bash\nexit 0\n')
(p/'sleep').write_text('#!/bin/bash\n[[ "$1" == 480 ]]\n')
for name in ('ssh','ssh-keygen','sleep'):
@@ -19,7 +19,7 @@ class AcceptanceTests(unittest.TestCase):
env = dict(os.environ, PATH=d+':'+os.environ['PATH'], GITHUB_ACTIONS='true', BRANCH=branch,
GITHUB_RUN_ATTEMPT=attempt, DEPLOY_SHA='a'*40, DEPLOY_KEY='NEVER-PRINT-KEY',
DEPLOY_KNOWN_HOSTS='test-host-pin', CALLS=str(p/'calls'),
FAIL_OPEN=str(fail_open).lower())
FAIL_OPEN=str(fail_open).lower(), FAIL_ACCEPT=str(fail_accept).lower())
result = subprocess.run(['bash',str(ROOT/'ci-stage-acceptance.sh')],env=env,capture_output=True,text=True)
calls = (p/'calls').read_text().splitlines() if (p/'calls').exists() else []
self.assertNotIn('NEVER-PRINT-KEY',result.stdout+result.stderr)
@@ -28,8 +28,16 @@ class AcceptanceTests(unittest.TestCase):
def test_fixed_stage_open_then_finally_close(self):
result,calls = self.run_driver()
self.assertEqual(result.returncode,0,result.stderr)
prefix = 'sudo -n env CI=true STAGE_TEST_APPROVAL=owner-authorized-stage-editorial bash /opt/services/canina/releases/'+SHA+'/scripts/stage-test-principal-host.sh '+SHA+' v4-ci-acceptance-20261024 600 '
self.assertEqual(calls,[prefix+'open',prefix+'close'])
prefix = 'sudo -n env CI=true STAGE_TEST_APPROVAL=owner-authorized-stage-editorial bash /opt/services/canina/releases/'+SHA+'/scripts/stage-test-principal-host.sh '+SHA+' v4-ci-timeout-860324e-20261024 600 '
self.assertEqual(calls[0],prefix+'open')
self.assertIn('timeout --signal=TERM --kill-after=10 480 python3 -',calls[1])
self.assertEqual(calls[2],prefix+'close')
def test_failed_acceptance_still_closes(self):
result,calls = self.run_driver(fail_accept=True)
self.assertNotEqual(result.returncode,0)
self.assertEqual(len(calls),3)
self.assertTrue(calls[-1].endswith(' close'))
def test_failed_open_still_closes(self):
result,calls = self.run_driver(fail_open=True)
@@ -51,10 +59,10 @@ class AcceptanceTests(unittest.TestCase):
text = (ROOT/'ci-stage-test-principal.sh').read_text()
for value in ('StrictHostKeyChecking=yes','IdentitiesOnly=yes','IdentityAgent=none','GlobalKnownHostsFile=/dev/null'):
self.assertIn(value,text)
for branch,sha,session,ttl in [('main',SHA,'v4-ci-acceptance-20261024','600'),
('ci/v4-stage-acceptance','b'*40,'v4-ci-acceptance-20261024','600'),
('ci/v4-stage-acceptance',SHA,'different-session','600'),
('ci/v4-stage-acceptance',SHA,'v4-ci-acceptance-20261024','601')]:
for branch,sha,session,ttl in [('main',SHA,'v4-ci-timeout-860324e-20261024','600'),
('ci/v4-stage-acceptance-timeout-860324e','b'*40,'v4-ci-timeout-860324e-20261024','600'),
('ci/v4-stage-acceptance-timeout-860324e',SHA,'different-session','600'),
('ci/v4-stage-acceptance-timeout-860324e',SHA,'v4-ci-timeout-860324e-20261024','601')]:
env = dict(os.environ,GITHUB_ACTIONS='true',BRANCH=branch,DEPLOY_SHA=sha,
STAGE_TEST_SESSION=session,STAGE_TEST_TTL_SECONDS=ttl,STAGE_TEST_ACTION='open')
result = subprocess.run(['bash',str(ROOT/'ci-stage-test-principal.sh')],env=env,capture_output=True)
@@ -0,0 +1,39 @@
import importlib.util
from pathlib import Path
import unittest
p=Path(__file__).with_name('stage-editorial-acceptance.py')
spec=importlib.util.spec_from_file_location('acceptance',p)
assert spec is not None and spec.loader is not None
m=importlib.util.module_from_spec(spec)
if p.exists(): spec.loader.exec_module(m)
class AcceptanceTests(unittest.TestCase):
def test_prior_contract_copied_exactly(self):
prior={'state':'FAILED','version':5,'title':'Editorial research: Persian owner topic','metadata':{'scope':'editorial-research-to-brief-v1\nTopic: Persian owner topic\nResearch and evidence-backed brief only. No publication, release, production changes or execution authorization.','acceptanceCriteria':['Do not invent QA']}}
self.assertTrue(hasattr(m,'proposal'), 'missing bounded proposal builder')
body=m.proposal(prior)
self.assertEqual(body['researchTopic'],'Persian owner topic')
self.assertEqual(body['acceptanceCriteria'],prior['metadata']['acceptanceCriteria'])
self.assertEqual(body['budgetLimitCents'],20)
self.assertEqual(body['commitSha'],m.SHA)
def test_wrong_prior_state_denied(self):
self.assertTrue(hasattr(m,'proposal'), 'missing bounded proposal builder')
with self.assertRaises(ValueError): m.proposal({'state':'READY'})
class ArtifactTests(unittest.TestCase):
def test_digest_and_binding_must_match(self):
self.assertTrue(hasattr(m,'verify_artifact'), 'missing artifact verifier')
import json,hashlib
raw=json.dumps({'taskId':'task','commitSha':m.SHA,'brief':{'candidates':[]}})
status={'taskId':'task','state':'VERIFYING','qaStatus':'PENDING_INDEPENDENT_QA','artifact':{'bytes':raw,'sha256':hashlib.sha256(raw.encode()).hexdigest()}}
m.verify_artifact(status,'task')
status['artifact']['bytes']+=' '
with self.assertRaises(ValueError): m.verify_artifact(status,'task')
def test_ci_gate_requires_exact_sha_success(self):
self.assertTrue(hasattr(m,'ci_success'), 'missing CI exact SHA gate')
self.assertFalse(m.ci_success('Deployment for develop completed successfully!'))
self.assertFalse(m.ci_success(m.SHA+' Job failed'))
self.assertTrue(m.ci_success(m.SHA+' Deployment for develop completed successfully! 🏁 Job succeeded'))
if __name__=='__main__': unittest.main()