215 lines
12 KiB
Python
215 lines
12 KiB
Python
#!/usr/bin/env python3
|
|
"""MANUAL_DORMANT: inspect stored plan sources; never execute its business action."""
|
|
import argparse
|
|
from datetime import date
|
|
import json
|
|
from pathlib import Path
|
|
import re
|
|
import corporate_runtime as r
|
|
|
|
OPERATION = 'planned_source_inventory_v1'
|
|
ACTIONS = {'BLOG_NEW', 'BLOG_UPDATE', 'CATALOG_ENRICH', 'WIKI_ENRICH', 'ENGINEERING'}
|
|
|
|
|
|
def checkpoint(client, store, key, path, body):
|
|
digest = client.checkpoint(store, key, path, body)
|
|
# Recovery handle must survive an ambiguous POST; never print body/capability.
|
|
import sys
|
|
print('Exact request checkpoint: ' + str(digest), file=sys.stderr)
|
|
return digest
|
|
|
|
|
|
def instruction(plan, task_id, allow_blocked=False):
|
|
tasks = [t for t in plan['tasks'] if t['id'] == task_id]
|
|
if len(tasks) != 1:
|
|
raise ValueError('Exact persisted planned task required')
|
|
task = tasks[0]
|
|
logs = [x for x in task['logs'] if x['step'] == 'PLANNED']
|
|
if len(logs) != 1:
|
|
raise ValueError('One unambiguous PLANNED event required')
|
|
lineage = logs[0]['payload']
|
|
if (lineage.get('version') != 1 or task['actionType'] not in ACTIONS
|
|
or task['status'] not in (('TODO', 'BLOCKED') if allow_blocked else ('TODO',))
|
|
or any(lineage.get(k) != task.get(k) for k in ('goalId', 'department', 'actionType', 'dueCycle'))
|
|
or any(lineage.get(k) != plan.get(k) for k in ('roadmapId', 'researchId', 'month'))):
|
|
raise ValueError('Stored plan lineage/action/status mismatch')
|
|
try:
|
|
due = date.fromisoformat(task['dueCycle'])
|
|
except (ValueError, TypeError):
|
|
raise ValueError('Dated instruction required') from None
|
|
if due.isoformat()[:7] != plan['month'] or due.isoformat() > r.now()[:10]:
|
|
raise ValueError('Planned prerequisite is not yet due')
|
|
ids = lineage.get('sourceIds')
|
|
if not isinstance(ids, list) or not ids or len(set(ids)) != len(ids):
|
|
raise ValueError('Explicit unique persisted sources required')
|
|
return json.loads(r.canonical({'taskId': task_id, 'title': task['title'],
|
|
'description': task['description'], 'lineage': lineage}))
|
|
|
|
|
|
def read_plan(client, roadmap_id, month):
|
|
# IDs are encoded as single URL components, never source-supplied routes.
|
|
return client.call('monthly-plans/' + r.quote(roadmap_id, safe='') + '?month=' + r.quote(month, safe=''))
|
|
|
|
|
|
def source_snapshot(client, store, inst):
|
|
lineage = inst['lineage']
|
|
research = client.research(lineage['researchId'])
|
|
if research['id'] != lineage['researchId']:
|
|
raise ValueError('Research identity mismatch')
|
|
sources = []
|
|
for source_id in sorted(lineage['sourceIds']):
|
|
matches = [s for s in research['sources'] if s['id'] == source_id]
|
|
if len(matches) != 1:
|
|
raise ValueError('Selected persisted source missing or ambiguous')
|
|
source = matches[0]
|
|
try:
|
|
raw = store.get(source['sha256'])
|
|
except (OSError, ValueError):
|
|
raise ValueError('Exact stored source bytes unavailable or corrupt') from None
|
|
sources.append({k: source[k] for k in ('id', 'url', 'sha256', 'retrievedAt')} | {'bytes': len(raw)})
|
|
return sources
|
|
|
|
|
|
def prepare(client, store, roadmap_id, month, task_id, key):
|
|
plan = read_plan(client, roadmap_id, month)
|
|
if plan['roadmapId'] != roadmap_id or plan['month'] != month:
|
|
raise ValueError('Plan identity mismatch')
|
|
inst = instruction(plan, task_id)
|
|
source_snapshot(client, store, inst) # fail before creating any child
|
|
lineage = inst['lineage']
|
|
body = {'title': 'Stored-source prerequisite: ' + inst['title'][:240],
|
|
'description': r.canonical({'operation': OPERATION, 'instruction': inst}).decode(),
|
|
'actionType': 'RESEARCH', 'parentId': task_id, 'goalId': lineage['goalId'],
|
|
'department': lineage['department'], 'dueCycle': lineage['dueCycle'], 'priority': 'MEDIUM'}
|
|
digest = checkpoint(client, store, key, 'tasks', body)
|
|
child = client.call('tasks', body, key)
|
|
return {'prerequisite': child, 'checkpointDigest': digest, 'originalActionStatus': 'TODO',
|
|
'disclosure': 'Source inventory only; original business action remains unexecuted'}
|
|
|
|
|
|
def snapshot(client, store, child):
|
|
try:
|
|
op = json.loads(child['description'])
|
|
if set(op) != {'operation', 'instruction'} or op['operation'] != OPERATION:
|
|
raise ValueError()
|
|
inst = op['instruction']
|
|
lineage = inst['lineage']
|
|
if (child['actionType'] != 'RESEARCH' or child['parentId'] != inst['taskId']
|
|
or any(child.get(k) != lineage[k] for k in ('goalId', 'department', 'dueCycle'))):
|
|
raise ValueError()
|
|
except (ValueError, KeyError, TypeError):
|
|
raise ValueError('Exact structured planned prerequisite required') from None
|
|
current = instruction(read_plan(client, lineage['roadmapId'], lineage['month']), inst['taskId'], allow_blocked=True)
|
|
if r.canonical(current) != r.canonical(inst):
|
|
raise ValueError('Original instruction changed; no evidence or QA submitted')
|
|
return {'operation': OPERATION, 'taskId': child['id'], 'instruction': inst,
|
|
'sources': source_snapshot(client, store, inst), 'originalActionPending': True,
|
|
'limitations': 'Stored-source inventory, not research synthesis, clinical validation or business execution'}
|
|
|
|
|
|
def execute(client, store, task_id, key):
|
|
child = client.call('tasks/' + r.quote(task_id, safe=''))
|
|
artifact = snapshot(client, store, child) # validate before claim
|
|
claimed = client.call('claims', {'taskId': task_id, 'department': child['department'], 'leaseSeconds': 300}, key + ':claim')['task']
|
|
if claimed is None:
|
|
raise ValueError('Exact prerequisite is not claimable; no fallback task consumed')
|
|
if claimed['id'] != task_id or claimed['description'] != child['description']:
|
|
raise ValueError('Claim mismatch; no evidence submitted')
|
|
# Re-read persisted lineage after claim; do not use a stale preflight snapshot.
|
|
artifact = snapshot(client, store, claimed)
|
|
raw = r.canonical(artifact)
|
|
digest = store.put(raw)
|
|
result = {'operation': OPERATION, 'finishedAt': r.now(), 'sha256': digest,
|
|
'sourceCount': len(artifact['sources']), 'bytes': len(raw), 'originalActionPending': True}
|
|
receipt = store.put(r.canonical(result))
|
|
body = {'claimToken': claimed['claimToken'], 'artifactUri': 'urn:sha256:' + digest, 'sha256': digest,
|
|
'summary': 'Exact persisted planned-source inventory prerequisite only; original action pending',
|
|
'tool': 'python:' + OPERATION, 'result': json.dumps(result)}
|
|
request_digest = checkpoint(client, store, key + ':evidence', 'tasks/' + task_id + '/evidence', body)
|
|
evidence = client.call('tasks/' + task_id + '/evidence', body, key + ':evidence')
|
|
return {'taskId': task_id, 'evidence': evidence, 'checkpointDigest': request_digest, 'toolReceiptDigest': receipt}
|
|
|
|
|
|
def review(client, store, task_id, evidence_id, key):
|
|
child = client.call('tasks/' + r.quote(task_id, safe=''))
|
|
evidence = next((e for e in child['evidence'] if e['id'] == evidence_id), None)
|
|
if not evidence or child['status'] != 'TEST':
|
|
raise ValueError('Persisted TEST evidence required')
|
|
raw = store.get(evidence['sha256'])
|
|
expected = snapshot(client, store, child)
|
|
if raw != r.canonical(expected) or evidence['artifactUri'] != 'urn:sha256:' + r.sha(raw):
|
|
raise ValueError('Exact planned source snapshot verification failed')
|
|
return client.call('tasks/' + task_id + '/reviews', {
|
|
'evidenceId': evidence_id, 'passed': True,
|
|
'findings': 'Reopened exact bytes and independently recomputed persisted plan instruction/source snapshot; original business action remains pending',
|
|
'verification': {'artifactUri': evidence['artifactUri'], 'sha256': r.sha(raw),
|
|
'method': 'independent stored plan + exact source byte recomputation',
|
|
'result': json.dumps({'verifiedAt': r.now(), 'sourceCount': len(expected['sources']), 'originalActionPending': True})}}, key)
|
|
|
|
|
|
def report(client, store, task_id, key):
|
|
child = client.call('tasks/' + r.quote(task_id, safe=''))
|
|
if child.get('status') != 'DONE' or not any(x.get('passed') for x in child.get('reviews', [])):
|
|
raise ValueError('Independent persisted completed QA required before PMO report')
|
|
artifact = snapshot(client, store, child)
|
|
parent = artifact['instruction']['taskId']
|
|
original = client.call('tasks/' + r.quote(parent, safe=''))
|
|
if original['status'] not in ('TODO', 'BLOCKED'):
|
|
raise ValueError('Original action advanced; reconcile PMO manually')
|
|
summary = ('Stored-source prerequisite ' + task_id + ' independently QA completed. Original ' +
|
|
artifact['instruction']['lineage']['actionType'] + ' task ' + parent +
|
|
' observed ' + original['status'] + '/unexecuted by this adapter. No publication, clinical validation or production effect measured.')
|
|
body = {'day': r.now()[:10], 'summary': summary}
|
|
request_digest = checkpoint(client, store, key, 'reports', body)
|
|
saved = client.call('reports', body, key)
|
|
page = 1
|
|
while True:
|
|
collection = client.call('reports?limit=100&page=' + str(page))
|
|
persisted = next((x for x in collection['data'] if x['id'] == saved['id']), None)
|
|
if persisted:
|
|
if persisted['summary'] != summary:
|
|
raise ValueError('PMO report readback mismatch')
|
|
return {'report': persisted, 'checkpointDigest': request_digest, 'originalActionPending': True}
|
|
if not collection['meta']['hasNextPage']:
|
|
raise ValueError('Persisted PMO report absent in readback')
|
|
page += 1
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('--api', default='http://127.0.0.1:3000/api/admin/hermes')
|
|
parser.add_argument('--allow-stage-https', action='store_true')
|
|
parser.add_argument('--store', required=True)
|
|
parser.add_argument('--key', required=True)
|
|
sub = parser.add_subparsers(dest='command', required=True)
|
|
cmd = sub.add_parser('prepare'); cmd.add_argument('roadmap_id'); cmd.add_argument('month'); cmd.add_argument('task_id')
|
|
for name in ('execute', 'qa', 'report'):
|
|
cmd = sub.add_parser(name); cmd.add_argument('task_id')
|
|
if name == 'qa': cmd.add_argument('evidence_id')
|
|
args = parser.parse_args()
|
|
for value in [args.task_id] + ([args.roadmap_id] if args.command == 'prepare' else []) + ([args.evidence_id] if args.command == 'qa' else []):
|
|
if not re.fullmatch(r'[a-f0-9-]{36}', value):
|
|
raise ValueError('UUID required')
|
|
client = r.Client(args.api, 'CORPORATE_QA_API_KEY' if args.command == 'qa' else 'CORPORATE_API_KEY', args.allow_stage_https)
|
|
store = r.Store(args.store)
|
|
if args.command == 'prepare': result = prepare(client, store, args.roadmap_id, args.month, args.task_id, args.key)
|
|
elif args.command == 'execute': result = execute(client, store, args.task_id, args.key)
|
|
elif args.command == 'qa': result = review(client, store, args.task_id, args.evidence_id, args.key)
|
|
else: result = report(client, store, args.task_id, args.key)
|
|
# create response has no lease; do not emit raw task claim capabilities.
|
|
def clean(value):
|
|
if isinstance(value, dict): return {k: clean(v) for k, v in value.items() if k != 'claimToken'}
|
|
if isinstance(value, list): return [clean(v) for v in value]
|
|
return value
|
|
print(json.dumps(clean(result), ensure_ascii=False))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
try:
|
|
main()
|
|
except Exception:
|
|
# Never reflect raw transport, input, token or response material.
|
|
import sys
|
|
print('Manual planned inventory failed; inspect secured checkpoint/API before retry', file=sys.stderr)
|
|
sys.exit(1)
|