feat(corporate): exact task claim and manual plan inventory execution slice
Deploy Canina / deploy (push) Successful in 2m31s

This commit is contained in:
Canina Hermes committed 2026-10-31 18:45:30 +00:00
1 parent 216e05ba25
commit 8c4faf8820
42 files changed
+5717 -4

No files matched your search

+214
View File
@@ -0,0 +1,214 @@
#!/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)
@@ -0,0 +1,64 @@
"""Disposable Nest/PostgreSQL test driver, never a Stage/production command."""
import json
import os
from pathlib import Path
import sys
import tempfile
import corporate_runtime as r
import corporate_plan_inventory as p
def run():
base, roadmap, month, parent = sys.argv[1:]
if not base.startswith('http://127.0.0.1:'):
raise ValueError('Loopback integration only')
os.environ['PLAN_TEST_EXECUTOR'] = 'executor'
os.environ['PLAN_TEST_REVIEWER'] = 'independent-plan-reviewer'
executor = r.Client(base + '/api/admin/hermes', 'PLAN_TEST_EXECUTOR')
reviewer = r.Client(base + '/api/admin/hermes', 'PLAN_TEST_REVIEWER')
# Existing integration Nest fixture intentionally omits the deployment prefix.
executor.base = reviewer.base = base + '/admin/hermes'
with tempfile.TemporaryDirectory(dir=os.environ.get('TMPDIR')) as tmp:
store = r.Store(tmp)
store.put(Path(p.__file__).read_bytes())
prepared = p.prepare(executor, store, roadmap, month, parent, 'plan-prerequisite')
child = prepared['prerequisite']['id']
assert p.prepare(executor, store, roadmap, month, parent, 'plan-prerequisite')['prerequisite']['id'] == child
execution = p.execute(executor, store, child, 'plan-run')
evidence = execution['evidence']
# Authentic backend identity separation, not a mocked QA result.
try:
p.review(executor, store, child, evidence['id'], 'self-review-denied')
except ValueError as error:
assert '409' in str(error)
else:
raise AssertionError('Self review accepted')
reviewer.call('tasks/' + child + '/reviews', {'evidenceId': evidence['id'], 'passed': False,
'findings': 'Engineering rejection recovery exercise',
'verification': {'artifactUri': evidence['artifactUri'], 'sha256': evidence['sha256'],
'method': 'manual engineering recovery test', 'result': 'rejected for recovery exercise'}}, 'plan-reject')
assert executor.call('tasks/' + parent)['status'] == 'BLOCKED'
corrected = p.execute(executor, store, child, 'plan-corrected-run')
evidence = corrected['evidence']
p.review(reviewer, store, child, evidence['id'], 'plan-independent-review')
# Backend deliberately leaves the original action blocked after rejection;
# completing an inventory must not silently advance that business action.
report = p.report(executor, store, child, 'plan-pmo')
original = executor.call('tasks/' + parent)
completed = executor.call('tasks/' + child)
assert original['status'] == 'BLOCKED' and not original['evidence'] and not original['reviews']
assert completed['status'] == 'DONE'
assert completed['reviews'][0]['reviewer'] != completed['evidence'][0]['executor']
assert any(t['id'] == child for t in report['report']['snapshot']['tasks'])
assert 'observed BLOCKED/unexecuted' in report['report']['summary']
assert completed['rejectionCount'] == 1 and completed['executionCount'] == 2
assert len(completed['reviews']) == 2
assert executor.call('runtime')['mode'] == 'MANUAL_DORMANT'
print(json.dumps({'childId': child, 'parentId': parent, 'originalStatus': original['status'],
'reportId': report['report']['id'], 'sha256': evidence['sha256'],
'independentQA': True, 'selfReviewDenied': True, 'persistedPMOReadback': True}))
if __name__ == '__main__': run()
+124
View File
@@ -0,0 +1,124 @@
import contextlib
import io
import tempfile
import unittest
from unittest.mock import Mock
import corporate_runtime as r
import corporate_plan_inventory as p
class PlanInventory(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.store = r.Store(self.tmp.name)
digest = self.store.put(b'engineering fixture, not clinical evidence')
self.source = {'id': 'source', 'url': 'https://example.org/source', 'sha256': digest, 'retrievedAt': '2026-01-01T00:00:00Z'}
self.lineage = {'version': 1, 'roadmapId': 'road', 'researchId': 'research', 'month': '2026-01', 'goalId': 'goal', 'department': 'CONTENT_SEO', 'actionType': 'BLOG_NEW', 'dueCycle': '2026-01-01', 'sourceIds': ['source']}
self.task = {'id': 'parent', 'title': 'Engineering test only', 'description': 'Write article later', 'goalId': 'goal', 'department': 'CONTENT_SEO', 'actionType': 'BLOG_NEW', 'dueCycle': '2026-01-01', 'status': 'TODO', 'logs': [{'step': 'PLANNED', 'payload': self.lineage}]}
self.plan = {'roadmapId': 'road', 'month': '2026-01', 'researchId': 'research', 'tasks': [self.task]}
self.client = Mock()
self.client.research.return_value = {'id': 'research', 'sources': [self.source]}
self.client.call.side_effect = lambda path, *args: self.plan if path.startswith('monthly-plans/') else {'id': 'child'}
def test_prepare_persists_exact_instruction_no_parent_evidence(self):
result = p.prepare(self.client, self.store, 'road', '2026-01', 'parent', 'key')
body = self.client.call.call_args.args[1]
self.assertEqual(body['parentId'], 'parent')
self.assertEqual(body['actionType'], 'RESEARCH')
op = r.json.loads(body['description'])
self.assertEqual(op['instruction']['description'], self.task['description'])
self.assertEqual(op['instruction']['lineage'], self.lineage)
self.assertEqual(result['originalActionStatus'], 'TODO')
self.assertEqual(result['prerequisite']['id'], 'child')
self.assertEqual([x.args[0] for x in self.client.call.call_args_list], ['monthly-plans/road?month=2026-01', 'tasks'])
def test_invalid_lineage_future_and_missing_bytes_fail_before_write(self):
for mutate in [lambda: self.lineage.update(actionType='RESEARCH'), lambda: self.task.update(dueCycle='2999-01-01'), lambda: self.source.update(sha256='0'*64), lambda: self.lineage.update(sourceIds=['absent']), lambda: self.task.update(status='DONE')]:
with self.subTest(mutate=mutate):
self.setUp()
mutate()
with self.assertRaises(ValueError): p.prepare(self.client, self.store, 'road', '2026-01', 'parent', 'key')
self.assertFalse(any(c.args[0] == 'tasks' for c in self.client.call.call_args_list))
def test_snapshot_rejects_instruction_drift_and_uses_only_selected_sources(self):
instruction = p.instruction(self.plan, 'parent')
op = {'operation': p.OPERATION, 'instruction': instruction}
child = {'id': 'child', 'parentId': 'parent', 'actionType': 'RESEARCH', 'description': r.canonical(op).decode(), 'department': 'CONTENT_SEO', 'goalId': 'goal', 'dueCycle': '2026-01-01'}
snapshot = p.snapshot(self.client, self.store, child)
self.assertEqual(snapshot['sources'][0]['id'], 'source')
self.task['description'] = 'Changed instruction'
with self.assertRaises(ValueError): p.snapshot(self.client, self.store, child)
def test_execute_targets_child_and_submits_exact_snapshot(self):
instruction = p.instruction(self.plan, 'parent')
child = {'id': 'child', 'parentId': 'parent', 'actionType': 'RESEARCH', 'description': r.canonical({'operation': p.OPERATION, 'instruction': instruction}).decode(), 'department': 'CONTENT_SEO', 'goalId': 'goal', 'dueCycle': '2026-01-01', 'claimToken': 'lease'}
def call(path, *args):
if path.startswith('monthly-plans/'): return self.plan
if path == 'tasks/child': return child
if path == 'claims': return {'task': child}
return {'id': 'evidence'}
self.client.call.side_effect = call
result = p.execute(self.client, self.store, 'child', 'run')
claim = next(c for c in self.client.call.call_args_list if c.args[0] == 'claims')
self.assertEqual(claim.args[1]['taskId'], 'child')
evidence = self.client.call.call_args.args[1]
self.assertEqual(r.json.loads(self.store.get(evidence['sha256']))['originalActionPending'], True)
self.assertEqual(result['evidence']['id'], 'evidence')
def test_ambiguous_evidence_response_preserves_replay_handle_before_post(self):
inst = p.instruction(self.plan, 'parent')
child = {'id': '618a6800-d241-41e2-b093-969164c83cfa', 'parentId': 'parent', 'actionType': 'RESEARCH',
'description': r.canonical({'operation': p.OPERATION, 'instruction': inst}).decode(),
'department': 'CONTENT_SEO', 'goalId': 'goal', 'dueCycle': '2026-01-01', 'claimToken': 'lease'}
sent = []
self.client.checkpoint.side_effect = lambda store, key, path, body: store.put(r.canonical({'path': path, 'body': body, 'key': key}))
def call(path, *args):
if path.startswith('monthly-plans/'): return self.plan
if path.startswith('tasks/') and not path.endswith('/evidence'): return child
if path == 'claims': return {'task': child}
sent.append((path, *args))
raise TimeoutError('ambiguous response')
self.client.call.side_effect = call
output = io.StringIO()
with contextlib.redirect_stderr(output), self.assertRaises(TimeoutError):
p.execute(self.client, self.store, child['id'], 'stable')
digest = output.getvalue().strip().split()[-1]
saved = r.json.loads(self.store.get(digest))
self.assertEqual(saved, {'path': sent[0][0], 'body': sent[0][1], 'key': sent[0][2]})
replay = object.__new__(r.Client)
replay.call = Mock(return_value={'id': 'already-persisted'})
self.assertEqual(replay.replay(self.store, digest), {'id': 'already-persisted'})
replay.call.assert_called_once_with(*sent[0])
self.assertNotIn('lease', output.getvalue())
def test_qa_exact_bytes_and_report_require_persisted_done(self):
with self.assertRaises(ValueError): p.report(self.client, self.store, 'child', 'report')
def test_qa_rejects_hash_consistent_but_wrong_snapshot(self):
inst = p.instruction(self.plan, 'parent')
digest = self.store.put(b'wrong but content-addressed bytes')
child = {'id': 'child', 'status': 'TEST', 'parentId': 'parent', 'actionType': 'RESEARCH',
'department': 'CONTENT_SEO', 'goalId': 'goal', 'dueCycle': '2026-01-01',
'description': r.canonical({'operation': p.OPERATION, 'instruction': inst}).decode(),
'evidence': [{'id': 'evidence', 'sha256': digest, 'artifactUri': 'urn:sha256:' + digest}]}
self.client.call.side_effect = lambda path, *args: child if path == 'tasks/child' else self.plan
with self.assertRaisesRegex(ValueError, 'verification failed'):
p.review(self.client, self.store, 'child', 'evidence', 'review')
self.assertFalse(any(c.args[0].endswith('/reviews') for c in self.client.call.call_args_list))
def test_exact_qa_submission_keeps_original_action_disclosure(self):
inst = p.instruction(self.plan, 'parent')
child = {'id': 'child', 'status': 'TEST', 'parentId': 'parent', 'actionType': 'RESEARCH',
'department': 'CONTENT_SEO', 'goalId': 'goal', 'dueCycle': '2026-01-01',
'description': r.canonical({'operation': p.OPERATION, 'instruction': inst}).decode()}
self.client.call.side_effect = lambda path, *args: child if path == 'tasks/child' else self.plan
digest = self.store.put(r.canonical(p.snapshot(self.client, self.store, child)))
child['evidence'] = [{'id': 'evidence', 'sha256': digest, 'artifactUri': 'urn:sha256:' + digest}]
p.review(self.client, self.store, 'child', 'evidence', 'review')
body = self.client.call.call_args.args[1]
self.assertTrue(body['passed'])
self.assertTrue(r.json.loads(body['verification']['result'])['originalActionPending'])
if __name__ == '__main__': unittest.main()