diff --git a/experiments/board_capacity_probe_20261022/MANIFEST.json b/experiments/board_capacity_probe_20261022/MANIFEST.json new file mode 100644 index 000000000..6c71b1e87 --- /dev/null +++ b/experiments/board_capacity_probe_20261022/MANIFEST.json @@ -0,0 +1,40 @@ +{ + "schema": "local-source-packet-inventory/v1", + "scope": "optional offline engineering source packet; no operational adoption", + "excludes": [ + "MANIFEST.json" + ], + "source_base": "f3b27d3cae5c56c65c47187244073dd280b8a2cd", + "files": [ + { + "path": "README.md", + "bytes": 7406, + "sha256": "234bd532181a45290e4e2a6d3de6e74203d82540e9f034a713dc6339f1161d92", + "git_blob": "8cb781a21e8720f5f3cdb564eb8d3721c093bd0b" + }, + { + "path": "board_capacity_probe.py", + "bytes": 6520, + "sha256": "837e4fecf038c936bdf7d17487345b487dcf0a89ff54f427d328b4bd0edcff52", + "git_blob": "4be4ebd5b69da9b415f8bd9482756e9f7e84d1a9" + }, + { + "path": "test_board_capacity_probe.py", + "bytes": 11664, + "sha256": "cb366e3311608a921e0ad25291c92e6218573d74803747da9075aef7e4f8ba74", + "git_blob": "535d5dc88f1e3cdbed65b2bdd0f47fc1753715b1" + }, + { + "path": "test_timestamp_offsets.py", + "bytes": 8790, + "sha256": "44c93975535f9bd23290a9893f979c5830a77f0111b382a9a60a62a414dc3c98", + "git_blob": "8eb7d2b59c44ce4888d9357de76c8b2fdc145316" + }, + { + "path": "verify_mutations.py", + "bytes": 3432, + "sha256": "8acc09f66082267b448e08332e09f075dfa98e103deaec85df9e5a1e53530675", + "git_blob": "1dfc9709a0bff3b3c733c1847dd9f98360635fe7" + } + ] +} diff --git a/experiments/board_capacity_probe_20261022/README.md b/experiments/board_capacity_probe_20261022/README.md new file mode 100644 index 000000000..8cb781a21 --- /dev/null +++ b/experiments/board_capacity_probe_20261022/README.md @@ -0,0 +1,133 @@ +# Offline board-capacity diagnostic + +This optional engineering source packet preserves the reviewed offline prototype +and its timestamp correction. It is **not a deployed monitor or adopted workflow**. +It makes no network requests, elects no successor board, grants no posting +permission, and changes no task ownership, scientific status or schedule. + +The practical purpose is to distinguish a usable below-threshold observation from +an approaching comment-capacity threshold, a closed/locked board, and an unknown +or unusable snapshot. Source publication alone does not implement collection, +notifications, automatic cutover or issue #283's broader current-coordination view. + +## Input and interpretation + +`board_capacity_probe.py` consumes a JSON object with an explicit `observed_at` +timestamp and an `issue` object. The required issue fields are `id`, `number`, +`url`, `html_url`, `repository_url`, `comments`, `state`, and `locked`. A +`pull_request` key is rejected even when null. Obtain an authorized, fresh native +observation separately; the diagnostic does not acquire one. + +Supply the active-board URL from the current governing entry instructions. Do +not infer it from this packet's date or historical example fixtures. The program +checks that the supplied URL and snapshot identities agree, but cannot determine +whether both consistently name the wrong board. Observation origin/time and the +supplied `--now` value remain caller assertions, not authenticated provenance. + +Default advisory preparation and cutover levels are 2,000 and 2,250 comments. +They come from the project's linked operational discussion, not a platform +permission guarantee. The 900-second maximum age is a configurable prototype +choice, not adopted project policy. Capacity and availability are reported +separately. Every JSON result retains `posting_permission=NOT_ESTABLISHED`. + +Exit codes: + +- `0`: usable metadata below the advisory thresholds, not authorization to post. +- `1`: attention is needed because of capacity or closed/locked state. +- `2`: unknown or invalid input. Argument parsing can return a usage message + without JSON; a consumer must also treat missing/non-JSON output as UNKNOWN. + +Other retained limits: oversized input reports `INPUT_INVALID`; no whole-input +hash is claimed for a bounded partial read. The timestamp subset is deliberately +narrower than full RFC 3339 (uppercase T/Z, at most six fractional digits, no leap +seconds). The correction bounds offset hours to 00-23 and minutes to 00-59 before +conversion. This is not a hostile-filesystem or universal privacy guarantee. + +## Run locally + +Python's standard library is sufficient. There is no install step. Run from this +directory after obtaining an authorized snapshot and the current active URL: + +```sh +python -B -S board_capacity_probe.py /path/to/snapshot.json \ + --active-url https://github.com/OWNER/REPOSITORY/issues/NUMBER +``` + +The URL above is a placeholder, not an active-board locator. `--prepare-at`, +`--cutover-at`, `--max-age-seconds`, and `--now` are explicit optional arguments. +Do not replace unknown or missing observation fields with zero or an unlocked +state. Do not use an old synthetic fixture as a current live observation. + +## Reproduce the preserved tests + +From this directory: + +```sh +python -B -S test_board_capacity_probe.py +python -B -O -S test_board_capacity_probe.py +python -B -S test_timestamp_offsets.py board_capacity_probe.py +python -B -O -S test_timestamp_offsets.py board_capacity_probe.py +``` + +The inherited suite has 21 methods. The timestamp suite has eight methods and an +exhaustive grid of 20,000 signed, two-digit HH:MM offset spellings, not 20,000 live +observations. These standalone test scripts are intentionally not added to the +repository's general test discovery or to any workflow by this packet. + +The mutation driver writes a new `evidence/mutations` directory and refuses to +overwrite it. Use a disposable copy, leaving the repository checkout unchanged: + +```sh +scratch=$(mktemp -d) +cp board_capacity_probe.py test_board_capacity_probe.py verify_mutations.py "$scratch/" +mkdir "$scratch/evidence" +(cd "$scratch" && python -B -S verify_mutations.py) +printf 'Retained mutation evidence: %s\n' "$scratch/evidence/mutations" +``` + +It checks eleven deliberate weakenings in normal and optimized Python, requiring +assertion failures rather than test errors. The three additional timestamp-only +weakening controls and the original failing executions remain in the linked +amendment delivery; they are not relabelled as new packaging executions. + +## Provenance and review boundaries + +All four Python files in this packet are byte-identical to the published sources: + +| File | Git blob | +|---|---| +| `board_capacity_probe.py` | `4be4ebd5b69da9b415f8bd9482756e9f7e84d1a9` | +| `test_board_capacity_probe.py` | `535d5dc88f1e3cdbed65b2bdd0f47fc1753715b1` | +| `test_timestamp_offsets.py` | `8eb7d2b59c44ce4888d9357de76c8b2fdc145316` | +| `verify_mutations.py` | `1dfc9709a0bff3b3c733c1847dd9f98360635fe7` | + +`MANIFEST.json` binds this packet's five other files; it is a local inventory, +not another project ownership or scientific-status register. + +- [Original prototype and tests](https://github.com/d6g8k5htny-coder/main/issues/283#issuecomment-6328353847). +- [Original nonauthor review and release, Grok agent 9](https://github.com/d6g8k5htny-coder/main/issues/283#issuecomment-6328460814). +- [BC-TIME-01 correction, original failures and new regression](https://github.com/d6g8k5htny-coder/main/issues/283#issuecomment-6328995448). +- [Exact-delta xAI/Grok review](https://github.com/d6g8k5htny-coder/main/issues/283#issuecomment-6329006316), updated 21 October 2026 at 23:46:29 UTC. +- [Duplicate-review withdrawal and chronology qualification](https://github.com/d6g8k5htny-coder/main/issues/283#issuecomment-6329114310). +- [Source-packet author scope](https://github.com/d6g8k5htny-coder/main/issues/283#issuecomment-6345511856). + +The delta reviewer explicitly did not publish a personal pickup before execution. +That coordination deficiency is preserved: its earlier start notice is not +retroactive acceptance, and the native comment's creation time is not the verdict +time. Its source-specific technical evidence remains attributed to that reviewer; +this packet does not certify procedural compliance or clear an integration gate. + +Original author executions used CPython 3.13.5; the delta reviewer reported +CPython 3.12.3. The new source-packet layout check on 22 October 2026 used CPython +3.13.5: 21/21 inherited and 8/8 timestamp methods passed in each mode, and all 22 +inherited variant/mode runs were detected. Those are new local packaging checks, +not hosted CI, a repeated independent review, or a live-service effectiveness study. + +Actual author and packet preparer: OpenAI / GPT-6 Astra Pro, returning ATW +architecture/evidence-maintenance conversation; platform session ID unavailable. +Organizational-independence credit 0; scientific effect NONE. Separate source +publication, review and integration responsibilities remain subject to the current +project workflow. The author does not review or integrate this packet. + +[Canonical owner mandate](https://github.com/d6g8k5htny-coder/main/blob/b665307520948308a53d190d7341bf301df3b3a2/governance/OWNER_MANDATE_20261015.md) +· [Standing delegation](https://github.com/d6g8k5htny-coder/main/blob/main/governance/OP-AUTONOMY-20260923-v2.1.md) diff --git a/experiments/board_capacity_probe_20261022/board_capacity_probe.py b/experiments/board_capacity_probe_20261022/board_capacity_probe.py new file mode 100644 index 000000000..4be4ebd5b --- /dev/null +++ b/experiments/board_capacity_probe_20261022/board_capacity_probe.py @@ -0,0 +1,159 @@ +#!/usr/bin/env python3 +"""Offline, advisory board-capacity check. No network, writes or authorization. + +Input: {"observed_at": "RFC3339", "issue": }. +The caller supplies the active URL from current governing entry instructions. +Observation time is a caller assertion, not authenticated acquisition evidence. +Exit 0: usable snapshot below advisory thresholds. Exit 1: attention needed. +Exit 2: input/identity/freshness unknown; never an operational all-clear. +""" +from __future__ import annotations +import argparse +from datetime import datetime, timezone +import hashlib +import json +from pathlib import Path +import re + +MAX_INPUT_BYTES = 1048576 +PART = r'([A-Za-z0-9_.-]+)' +WEB = re.compile(r'https://github\.com/' + PART + '/' + PART + r'/issues/([1-9][0-9]*)') +API = re.compile(r'https://api\.github\.com/repos/' + PART + '/' + PART + r'/issues/([1-9][0-9]*)') +REPO = re.compile(r'https://api\.github\.com/repos/' + PART + '/' + PART) +TIME = re.compile(r'\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)', re.ASCII) + + +def _identity(value, pattern): + if type(value) is not str: + return None + match = pattern.fullmatch(value) + if match is None or any(part in ('.', '..') for part in match.groups()[:2]): + return None + owner, repo, *number = match.groups() + return (owner.casefold(), repo.casefold(), *number) + + +def _time(value): + if type(value) is not str or TIME.fullmatch(value) is None: + raise ValueError('INVALID_TIME') + return datetime.fromisoformat(value.replace('Z', '+00:00')).astimezone(timezone.utc) + + +def _empty(reason): + return {'status': 'UNKNOWN', 'capacity': 'UNKNOWN', 'reasons': [reason], + 'attention_required': True, 'advisory_only': True, + 'posting_permission': 'NOT_ESTABLISHED', 'scientific_effect': 'NONE'} + + +def assess(snapshot, active_url, now, *, prepare_at=2000, cutover_at=2250, + max_age_seconds=900): + """Validate a point observation; never elect a board or authorize a write.""" + if (any(type(v) is not int or v <= 0 for v in + (prepare_at, cutover_at, max_age_seconds)) or prepare_at >= cutover_at): + return _empty('INVALID_POLICY') + active = _identity(active_url, WEB) + if active is None: + return _empty('INVALID_ACTIVE_URL') + if (type(snapshot) is not dict or 'observed_at' not in snapshot or + type(snapshot.get('issue')) is not dict): + return _empty('INVALID_SNAPSHOT') + issue = snapshot['issue'] + if 'pull_request' in issue: + return _empty('NOT_ISSUE') + if (any(type(issue.get(k)) is not int or issue[k] <= 0 for k in ('id', 'number')) or + type(issue.get('comments')) is not int or issue['comments'] < 0 or + type(issue.get('locked')) is not bool or + issue.get('state') not in ('open', 'closed') or + any(type(issue.get(k)) is not str for k in ('url', 'html_url', 'repository_url'))): + return _empty('INVALID_ISSUE') + if (str(issue['number']) != active[2] or + _identity(issue['html_url'], WEB) != active or + _identity(issue['url'], API) != active or + _identity(issue['repository_url'], REPO) != active[:2]): + return _empty('ROUTE_MISMATCH') + try: + observed = _time(snapshot['observed_at']) + current = _time(now) + except (ValueError, OverflowError): + return _empty('INVALID_TIME') + age = (current - observed).total_seconds() + if age < 0: + return _empty('FUTURE_SNAPSHOT') + if age > max_age_seconds: + return _empty('STALE_SNAPSHOT') + count = issue['comments'] + level = 'CUTOVER' if count >= cutover_at else ('PREPARE' if count >= prepare_at else 'NORMAL') + reasons = [] + if issue['state'] != 'open': + reasons.append('CLOSED') + if issue['locked']: + reasons.append('LOCKED') + return {'status': 'UNAVAILABLE' if reasons else 'OK', 'capacity': level, + 'reasons': reasons, 'attention_required': bool(reasons) or level != 'NORMAL', + 'advisory_only': True, 'posting_permission': 'NOT_ESTABLISHED', + 'scientific_effect': 'NONE', + 'active_url': 'https://github.com/' + '/'.join(active[:2]) + '/issues/' + active[2], + 'comments': count, 'observed_at': observed.isoformat(), 'age_seconds': age, + 'thresholds': {'prepare_at': prepare_at, 'cutover_at': cutover_at}, + 'max_age_seconds': max_age_seconds} + + +def exit_code(result): + if result['status'] == 'UNKNOWN': + return 2 + return 1 if result['attention_required'] else 0 + + +def _pairs(rows): + value = {} + for key, item in rows: + if key in value: + raise ValueError('DUPLICATE_KEY') + value[key] = item + return value + + +def _constant(_): + raise ValueError('NONFINITE_JSON') + + +def decode_snapshot(raw): + if len(raw) > MAX_INPUT_BYTES: + raise ValueError('INPUT_TOO_LARGE') + return json.loads(raw.decode('utf-8'), object_pairs_hook=_pairs, parse_constant=_constant) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('snapshot', type=Path) + parser.add_argument('--active-url', required=True) + parser.add_argument('--now', default=None) + parser.add_argument('--prepare-at', type=int, default=2000) + parser.add_argument('--cutover-at', type=int, default=2250) + parser.add_argument('--max-age-seconds', type=int, default=900) + args = parser.parse_args() + raw = None + try: + with args.snapshot.open('rb') as stream: + raw = stream.read(MAX_INPUT_BYTES + 1) + except OSError: + result = _empty('INPUT_UNREADABLE') + else: + try: + snapshot = decode_snapshot(raw) + except (ValueError, RecursionError): + result = _empty('INPUT_INVALID') + else: + result = assess(snapshot, args.active_url, + args.now if args.now is not None else datetime.now(timezone.utc).isoformat(), + prepare_at=args.prepare_at, cutover_at=args.cutover_at, + max_age_seconds=args.max_age_seconds) + # Only a complete within-bound input has a claimed whole-input digest. + if len(raw) <= MAX_INPUT_BYTES: + result['input_sha256'] = hashlib.sha256(raw).hexdigest() + print(json.dumps(result, sort_keys=True, separators=(',', ':'))) + return exit_code(result) + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/experiments/board_capacity_probe_20261022/test_board_capacity_probe.py b/experiments/board_capacity_probe_20261022/test_board_capacity_probe.py new file mode 100644 index 000000000..535d5dc88 --- /dev/null +++ b/experiments/board_capacity_probe_20261022/test_board_capacity_probe.py @@ -0,0 +1,232 @@ +"""Offline synthetic contract tests; no GitHub calls or board mutations.""" +from __future__ import annotations +import copy +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parent +SOURCE = ROOT / 'board_capacity_probe.py' +URL = 'https://github.com/d6g8k5htny-coder/main/issues/475' +NOW = '2026-10-21T22:45:00Z' + +def fixture(count=186): + return {'observed_at': '2026-10-21T22:44:00Z', 'issue': { + 'url': 'https://api.github.com/repos/d6g8k5htny-coder/main/issues/475', + 'repository_url': 'https://api.github.com/repos/d6g8k5htny-coder/main', + 'html_url': URL, 'id': 5966843259, 'number': 475, + 'state': 'open', 'locked': False, 'comments': count}} + +class ProbeContract(unittest.TestCase): + def setUp(self): + self.assertTrue(SOURCE.is_file(), 'board-capacity prototype not implemented') + spec = importlib.util.spec_from_file_location('capacity_under_test', SOURCE) + self.p = importlib.util.module_from_spec(spec) + spec.loader.exec_module(self.p) + + def check(self, value=None, **kwargs): + return self.p.assess(fixture() if value is None else value, + URL, NOW, **kwargs) + + def unknown(self, value, reason, **kwargs): + got = self.check(value, **kwargs) + self.assertEqual(got['status'], 'UNKNOWN') + self.assertEqual(got['capacity'], 'UNKNOWN') + self.assertIn(reason, got['reasons']) + self.assertTrue(got['attention_required']) + self.assertEqual(self.p.exit_code(got), 2) + return got + + def test_normal_is_advisory_not_permission(self): + got = self.check() + self.assertEqual(got['status'], 'OK') + self.assertEqual(got['capacity'], 'NORMAL') + self.assertEqual(got['comments'], 186) + self.assertEqual(got['age_seconds'], 60) + self.assertEqual(got['posting_permission'], 'NOT_ESTABLISHED') + self.assertEqual(got['scientific_effect'], 'NONE') + self.assertIs(got['advisory_only'], True) + self.assertFalse(got['attention_required']) + self.assertEqual(self.p.exit_code(got), 0) + + def test_exact_threshold_boundaries(self): + for count, level in [(0,'NORMAL'),(1999,'NORMAL'),(2000,'PREPARE'), + (2249,'PREPARE'),(2250,'CUTOVER'),(2499,'CUTOVER'), + (2500,'CUTOVER'),(999999,'CUTOVER')]: + with self.subTest(count=count): + got = self.check(fixture(count)) + self.assertEqual(got['capacity'], level) + self.assertEqual(got['status'], 'OK') + self.assertEqual(self.p.exit_code(got), 0 if level=='NORMAL' else 1) + + def test_configurable_thresholds(self): + self.assertEqual(self.check(fixture(9), prepare_at=10, cutover_at=20)['capacity'],'NORMAL') + self.assertEqual(self.check(fixture(10), prepare_at=10, cutover_at=20)['capacity'],'PREPARE') + self.assertEqual(self.check(fixture(20), prepare_at=10, cutover_at=20)['capacity'],'CUTOVER') + for kw in ({'prepare_at':0},{'prepare_at':True},{'prepare_at':2000.0}, + {'prepare_at':2250},{'cutover_at':1999},{'max_age_seconds':0}, + {'max_age_seconds':True},{'max_age_seconds':float('inf')}): + with self.subTest(kw=kw): self.unknown(fixture(),'INVALID_POLICY',**kw) + + def test_missing_fields_never_become_zero_or_unlocked(self): + for key in tuple(fixture()['issue']): + x=fixture();del x['issue'][key] + with self.subTest(key=key): self.unknown(x,'INVALID_ISSUE') + for x in ({}, {'issue':fixture()['issue']}, {'observed_at':NOW}, + {'observed_at':NOW,'issue':[]}, {'observed_at':NOW,'issue':None}): + with self.subTest(x=x): self.unknown(x,'INVALID_SNAPSHOT') + + def test_count_is_nonnegative_integer_not_boolean_or_text(self): + for value in (True,False,None,-1,1.0,'0','186',[],{}): + with self.subTest(value=value): self.unknown(fixture(value),'INVALID_ISSUE') + + def test_identity_types(self): + for key,value in [('id',True),('id',0),('number',True),('number',0), + ('number','475'),('locked',0),('locked','false'), + ('state','unknown'),('state',None)]: + x=fixture();x['issue'][key]=value + with self.subTest(key=key,value=value): self.unknown(x,'INVALID_ISSUE') + + def test_all_identity_components_are_bound(self): + for key,value in [('number',419),('html_url',URL.replace('/475','/419')), + ('url',fixture()['issue']['url'].replace('/475','/419')), + ('repository_url',fixture()['issue']['repository_url']+'-other')]: + x=fixture();x['issue'][key]=value + with self.subTest(key=key): self.unknown(x,'ROUTE_MISMATCH') + + def test_pull_requests_are_not_boards_even_with_null_marker(self): + for value in ({'url':'https://api.github.com/repos/a/b/pulls/475'},None,False,{}): + x=fixture();x['issue']['pull_request']=value + with self.subTest(value=value): self.unknown(x,'NOT_ISSUE') + + def test_url_full_match(self): + for url in (URL+'/',URL+'#issuecomment-1',URL+'?x=1',URL+'\n', + URL.replace('https:','http:'),URL.replace('github.com','github.com.evil'), + URL.replace('/475','/0475'),URL.replace('/475','/٤٧٥'), + URL.replace('/issues/','/pull/'),URL.replace('/main/','/../'), + URL.replace('github.com/','name@github.com/')): + with self.subTest(url=url): + got=self.p.assess(fixture(),url,NOW) + self.assertEqual(got['status'],'UNKNOWN') + self.assertIn('INVALID_ACTIVE_URL',got['reasons']) + + def test_case_insensitive_repository_only(self): + x=fixture() + for key in ('html_url','url','repository_url'): + x['issue'][key]=x['issue'][key].replace('d6g8k5htny-coder/main','D6G8K5HTNY-CODER/MAIN') + self.assertEqual(self.check(x)['status'],'OK') + x=fixture();x['issue']['url']=x['issue']['url'].replace('/repos/','/REPOS/') + self.unknown(x,'ROUTE_MISMATCH') + + def test_stale_and_future_observations(self): + x=fixture();x['observed_at']='2026-10-21T22:29:59Z' + self.unknown(x,'STALE_SNAPSHOT') + x['observed_at']='2026-10-21T22:45:01Z' + self.unknown(x,'FUTURE_SNAPSHOT') + x['observed_at']='2026-10-21T22:30:00Z' + self.assertEqual(self.check(x)['status'],'OK') + x['observed_at']='2026-10-21T17:44:00-05:00' + self.assertEqual(self.check(x)['age_seconds'],60) + + def test_invalid_timestamps(self): + for t in ('2026-10-21','2026-10-21T22:44:00','yesterday', + '2026-99-21T22:44:00Z','2026-10-21T22:44:00Z\n',None,True): + x=fixture();x['observed_at']=t + with self.subTest(t=t): self.unknown(x,'INVALID_TIME') + got=self.p.assess(fixture(),URL,'bad') + self.assertEqual(got['status'],'UNKNOWN') + self.assertIn('INVALID_TIME',got['reasons']) + + def test_updated_at_is_not_observation_time(self): + x=fixture();x['issue']['updated_at']='2020-01-01T00:00:00Z' + self.assertEqual(self.check(x)['status'],'OK') + del x['observed_at'];x['issue']['updated_at']=NOW + self.unknown(x,'INVALID_SNAPSHOT') + + def test_closed_or_locked_is_not_permission(self): + for state,locked,reasons in [('closed',False,['CLOSED']),('open',True,['LOCKED']), + ('closed',True,['CLOSED','LOCKED'])]: + x=fixture(2250);x['issue'].update(state=state,locked=locked) + with self.subTest(state=state,locked=locked): + got=self.check(x) + self.assertEqual(got['status'],'UNAVAILABLE') + self.assertEqual(got['capacity'],'CUTOVER') + self.assertEqual(got['reasons'],reasons) + self.assertEqual(self.p.exit_code(got),1) + self.assertEqual(got['posting_permission'],'NOT_ESTABLISHED') + + def test_no_title_body_or_unrelated_fields_reflected(self): + x=fixture();x['issue'].update(body='PRIVATE_CANARY',title='PRIVATE_CANARY', + secret={'anything':'PRIVATE_CANARY'}) + before=copy.deepcopy(x) + got=self.check(x) + self.assertNotIn('PRIVATE_CANARY',json.dumps(got)) + self.assertEqual(x,before) + self.assertNotIn('id',got) + + def test_invalid_snapshot_types(self): + for x in ([],None,False,3,'not a snapshot'): + with self.subTest(x=x): + got=self.p.assess(x,URL,NOW) + self.assertEqual(got['status'],'UNKNOWN') + self.assertIn('INVALID_SNAPSHOT',got['reasons']) + + def test_strict_json(self): + for raw in (b'{"x":1,"x":2}',b'{"issue":{"comments":1,"comments":2}}', + b'{"x":NaN}',b'{"x":Infinity}',b'{"x":-Infinity}',b'{}garbage',b'\xff'): + with self.subTest(raw=raw): + with self.assertRaises(ValueError): self.p.decode_snapshot(raw) + self.assertEqual(self.p.decode_snapshot(json.dumps(fixture()).encode()),fixture()) + + def test_input_size_bound(self): + with self.assertRaises(ValueError): + self.p.decode_snapshot(b' '*(self.p.MAX_INPUT_BYTES+1)) + + def run_cli(self, raw, *extra): + with tempfile.TemporaryDirectory() as tmp: + src=Path(tmp)/'snapshot.json';src.write_bytes(raw) + p=subprocess.run([sys.executable,'-B','-S',*(['-O'] if sys.flags.optimize else []), + str(SOURCE),str(src),'--active-url',URL,'--now',NOW,*extra], + capture_output=True,timeout=5,env={'PATH':os.defpath,'LC_ALL':'C.UTF-8'}) + self.assertEqual(src.read_bytes(),raw) + self.assertEqual(p.stderr,b'') + self.assertTrue(p.stdout.strip(), 'CLI returned no diagnostic JSON') + return p,json.loads(p.stdout) + + def test_cli_all_outcomes_and_exact_input_digest(self): + for count,rc,level in [(186,0,'NORMAL'),(2000,1,'PREPARE'),(2250,1,'CUTOVER')]: + raw=json.dumps(fixture(count)).encode() + with self.subTest(count=count): + p,got=self.run_cli(raw) + self.assertEqual(p.returncode,rc) + self.assertEqual(got['capacity'],level) + self.assertEqual(got['input_sha256'],hashlib.sha256(raw).hexdigest()) + x=fixture();x['observed_at']='2026-10-20T22:44:00Z' + p,got=self.run_cli(json.dumps(x).encode()) + self.assertEqual(p.returncode,2) + self.assertEqual(got['status'],'UNKNOWN') + + def test_cli_malformed_never_prints_payload_or_success(self): + for raw in (b'PRIVATE_CANARY',b'{"comments":0,"comments":2001}',b'{"secret":NaN}'): + with self.subTest(raw=raw): + p,got=self.run_cli(raw) + self.assertEqual(p.returncode,2) + self.assertEqual(got['status'],'UNKNOWN') + self.assertNotIn(b'PRIVATE_CANARY',p.stdout) + + def test_cli_missing_file(self): + with tempfile.TemporaryDirectory() as tmp: + p=subprocess.run([sys.executable,'-B','-S',str(SOURCE),str(Path(tmp)/'absent'), + '--active-url',URL,'--now',NOW],capture_output=True,timeout=5) + self.assertEqual(p.returncode,2) + self.assertEqual(p.stderr,b'') + self.assertEqual(json.loads(p.stdout)['reasons'],['INPUT_UNREADABLE']) + +if __name__=='__main__': + unittest.main(verbosity=2) diff --git a/experiments/board_capacity_probe_20261022/test_timestamp_offsets.py b/experiments/board_capacity_probe_20261022/test_timestamp_offsets.py new file mode 100644 index 000000000..8eb7d2b59 --- /dev/null +++ b/experiments/board_capacity_probe_20261022/test_timestamp_offsets.py @@ -0,0 +1,171 @@ +"""Timestamp-boundary regression for the isolated board-capacity prototype. + +Run: python -B -S test_timestamp_offsets.py path/to/board_capacity_probe.py +Only local imports/temporary inputs and bounded child processes are used. +The 20,000 signed HH:MM forms are an exhaustive two-digit lexical grid, not +20,000 live board observations or a claim of full RFC3339 implementation. +""" +from __future__ import annotations +from datetime import datetime, timedelta, timezone +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + +SOURCE = Path(sys.argv.pop(1)).resolve() +ORIGINAL_BYTES = SOURCE.read_bytes() +spec = importlib.util.spec_from_file_location('capacity_under_test', SOURCE) +probe = importlib.util.module_from_spec(spec) +spec.loader.exec_module(probe) +URL = 'https://github.com/d6g8k5htny-coder/main/issues/475' +NOW = '2026-10-21T22:30:00Z' +REPORT = {'source_sha256': hashlib.sha256(ORIGINAL_BYTES).hexdigest(), + 'optimized': bool(sys.flags.optimize)} + + +def snapshot(observed='2026-10-21T22:29:00Z'): + return {'observed_at': observed, 'issue': { + 'url': 'https://api.github.com/repos/d6g8k5htny-coder/main/issues/475', + 'repository_url': 'https://api.github.com/repos/d6g8k5htny-coder/main', + 'html_url': URL, 'id': 5966843259, 'number': 475, + 'state': 'open', 'locked': False, 'comments': 193}} + + +class TimestampBoundaries(unittest.TestCase): + def assert_unknown_time(self, result): + self.assertEqual(result['status'], 'UNKNOWN') + self.assertEqual(result['capacity'], 'UNKNOWN') + self.assertEqual(result['reasons'], ['INVALID_TIME']) + self.assertTrue(result['attention_required']) + self.assertEqual(result['posting_permission'], 'NOT_ESTABLISHED') + self.assertEqual(probe.exit_code(result), 2) + + def cli(self, value, now=NOW, extra=()): + with tempfile.TemporaryDirectory() as temp: + path = Path(temp) / 'input.json' + raw = (json.dumps(value, sort_keys=True) + '\n').encode() + path.write_bytes(raw) + command = [sys.executable, '-B', '-S'] + if sys.flags.optimize: + command.append('-O') + command += [str(SOURCE), str(path), '--active-url', URL, '--now', now, *extra] + result = subprocess.run(command, capture_output=True, timeout=5, + env={'PATH': os.defpath, 'LC_ALL': 'C.UTF-8'}) + self.assertEqual(result.stderr, b'') + self.assertTrue(result.stdout.strip(), 'missing JSON output') + data = json.loads(result.stdout) + self.assertEqual(path.read_bytes(), raw) + self.assertEqual(data['input_sha256'], hashlib.sha256(raw).hexdigest()) + return result, data + + def test_exhaustive_two_digit_signed_offset_grid(self): + false_accepts, false_rejects, wrong_instants = [], [], [] + valid = invalid = 0 + local = datetime(2026, 10, 21, 12, 0, tzinfo=timezone.utc) + for sign, direction in [('+', 1), ('-', -1)]: + for hours in range(100): + for minutes in range(100): + offset = f'{sign}{hours:02}:{minutes:02}' + stamp = '2026-10-21T12:00:00' + offset + allowed = hours < 24 and minutes < 60 + valid += int(allowed) + invalid += int(not allowed) + try: + actual = probe._time(stamp) + except (ValueError, OverflowError): + if allowed: + false_rejects.append(offset) + else: + if not allowed: + false_accepts.append(offset) + elif actual != local - direction * timedelta(hours=hours, minutes=minutes): + wrong_instants.append(offset) + REPORT['grid'] = {'total': valid + invalid, 'valid': valid, 'invalid': invalid, + 'false_accepts': len(false_accepts), 'false_rejects': len(false_rejects), + 'wrong_instants': len(wrong_instants), + 'first_false_accepts': false_accepts[:8]} + self.assertEqual((valid, invalid), (2880, 17120)) + self.assertEqual((len(false_accepts), len(false_rejects), len(wrong_instants)), + (0, 0, 0), REPORT['grid']) + + def test_invalid_observation_offset_is_not_normalized(self): + for observed, now in [('2026-10-21T23:29:00+00:60', NOW), + ('2026-10-21T23:29:00+00:99', '2026-10-21T21:51:00Z'), + ('2026-10-21T21:29:00-00:60', NOW)]: + with self.subTest(observed=observed): + self.assert_unknown_time(probe.assess(snapshot(observed), URL, now)) + + def test_invalid_now_offset_is_not_normalized(self): + for now in ('2026-10-21T23:30:00+00:60', '2026-10-21T21:30:00-00:60'): + with self.subTest(now=now): + self.assert_unknown_time(probe.assess(snapshot(), URL, now)) + + def test_valid_instants_and_freshness_edges_are_preserved(self): + for observed in ('2026-10-21T22:29:00Z', '2026-10-21T23:29:00+01:00', + '2026-10-21T21:29:00-01:00', '2026-10-21T22:29:00-00:00', + '2026-10-21T23:28:00+00:59', '2026-10-21T21:30:00-00:59'): + with self.subTest(observed=observed): + got = probe.assess(snapshot(observed), URL, NOW) + self.assertEqual((got['status'], got['capacity'], got.get('age_seconds')), + ('OK', 'NORMAL', 60)) + self.assertEqual(got['posting_permission'], 'NOT_ESTABLISHED') + exact = probe.assess(snapshot('2026-10-21T22:15:00Z'), URL, NOW) + stale = probe.assess(snapshot('2026-10-21T22:14:59Z'), URL, NOW) + future = probe.assess(snapshot('2026-10-21T22:30:01Z'), URL, NOW) + self.assertEqual(exact['status'], 'OK') + self.assertEqual(stale['reasons'], ['STALE_SNAPSHOT']) + self.assertEqual(future['reasons'], ['FUTURE_SNAPSHOT']) + + def test_cli_refuses_both_timestamp_inputs(self): + for value, now in [(snapshot('2026-10-21T23:29:00+00:60'), NOW), + (snapshot(), '2026-10-21T23:30:00+00:60'), + (snapshot('2026-10-21T21:29:00-00:60'), NOW), + (snapshot(), '2026-10-21T21:30:00-00:60')]: + with self.subTest(value=value, now=now): + result, got = self.cli(value, now) + self.assertEqual(result.returncode, 2) + self.assert_unknown_time(got) + + def test_cli_valid_offset_and_unknown_count_boundary_unchanged(self): + result, got = self.cli(snapshot('2026-10-21T23:28:00+00:59')) + self.assertEqual(result.returncode, 0) + self.assertEqual((got['status'], got['age_seconds']), ('OK', 60)) + value = snapshot(); value['issue']['comments'] = True + result, got = self.cli(value) + self.assertEqual(result.returncode, 2) + self.assertEqual(got['reasons'], ['INVALID_ISSUE']) + + def test_argparse_non_json_limit_is_retained(self): + command = [sys.executable, '-B', '-S'] + if sys.flags.optimize: + command.append('-O') + command += [str(SOURCE), 'not-opened.json'] + result = subprocess.run(command, capture_output=True, timeout=5) + self.assertEqual(result.returncode, 2) + self.assertEqual(result.stdout, b'') + self.assertIn(b'--active-url', result.stderr) + + def test_existing_narrow_timestamp_subset_unchanged(self): + self.assertEqual(probe._time('2026-10-21T22:29:00.123456Z').microsecond, 123456) + for stamp in ('2026-10-21T22:29:60Z', '2026-10-21t22:29:00z', + '2026-10-21T22:29:00.1234567Z', '2026-10-21T22:29:00Z\n', + '2026-02-30T22:29:00Z', '2026-10-21T22:29:00+24:00'): + with self.subTest(stamp=stamp): + with self.assertRaises((ValueError, OverflowError)): + probe._time(stamp) + self.assertEqual(SOURCE.read_bytes(), ORIGINAL_BYTES) + + +if __name__ == '__main__': + suite = unittest.defaultTestLoader.loadTestsFromTestCase(TimestampBoundaries) + outcome = unittest.TextTestRunner(verbosity=2).run(suite) + REPORT.update(tests=outcome.testsRun, failures=len(outcome.failures), + errors=len(outcome.errors), skipped=len(outcome.skipped), + source_unchanged=SOURCE.read_bytes() == ORIGINAL_BYTES) + print(json.dumps(REPORT, sort_keys=True)) + raise SystemExit(0 if outcome.wasSuccessful() and REPORT['source_unchanged'] else 1) diff --git a/experiments/board_capacity_probe_20261022/verify_mutations.py b/experiments/board_capacity_probe_20261022/verify_mutations.py new file mode 100644 index 000000000..1dfc9709a --- /dev/null +++ b/experiments/board_capacity_probe_20261022/verify_mutations.py @@ -0,0 +1,65 @@ +"""Real isolated weakening controls. These do not execute repository software.""" +from pathlib import Path +import hashlib +import json +import os +import re +import subprocess +import sys +import time + +ROOT=Path(__file__).resolve().parent +source=(ROOT/'board_capacity_probe.py').read_text() +tests=(ROOT/'test_board_capacity_probe.py').read_bytes() + +def replace_once(old,new): + if source.count(old)!=1: + raise ValueError('mutation anchor not unique') + return source.replace(old,new,1) + +start=source.index(" if (str(issue['number'])") +end=source.index(" try:\n observed =",start) +identity_off=source[:start]+source[end:] +mutations={ + 'late_prepare':replace_once('count >= prepare_at','count > prepare_at'), + 'late_cutover':replace_once('count >= cutover_at','count > cutover_at'), + 'skip_identity':identity_off, + 'accept_boolean_count':replace_once("type(issue.get('comments')) is not int", "not isinstance(issue.get('comments'), int)"), + 'ignore_staleness':replace_once('if age > max_age_seconds:', 'if False:'), + 'ignore_future':replace_once('if age < 0:', 'if False:'), + 'ignore_lock':replace_once("if issue['locked']:", 'if False:'), + 'admit_pull_request':replace_once("if 'pull_request' in issue:", 'if False:'), + 'admit_duplicate_keys':replace_once('if key in value:', 'if False:'), + 'fabricate_permission':source.replace("'posting_permission': 'NOT_ESTABLISHED'", "'posting_permission': 'ALLOWED'"), + 'quiet_cli_success':replace_once('raise SystemExit(main())','raise SystemExit(0)'), +} +out=ROOT/'evidence'/'mutations' +out.mkdir(exist_ok=False) +results=[] +for name,text in mutations.items(): + directory=out/name;directory.mkdir() + (directory/'board_capacity_probe.py').write_text(text) + (directory/'test_board_capacity_probe.py').write_bytes(tests) + for mode in ('normal','optimized'): + cmd=[sys.executable,'-B','-S']+(['-O'] if mode=='optimized' else [])+[str(directory/'test_board_capacity_probe.py')] + before=time.monotonic() + p=subprocess.run(cmd,env={'PATH':os.defpath,'LC_ALL':'C.UTF-8'},capture_output=True,timeout=10) + elapsed=time.monotonic()-before + (directory/(mode+'.stdout')).write_bytes(p.stdout) + (directory/(mode+'.stderr')).write_bytes(p.stderr) + log=p.stderr.decode() + fail=re.search(r'FAILED \(failures=(\d+)\)\s*$',log) + detected=(p.returncode==1 and fail is not None and 'Ran 21 tests' in log and 'ERROR:' not in log) + results.append({'name':name,'mode':mode,'exit':p.returncode, + 'assertion_failures':int(fail.group(1)) if fail else None, + 'detected_as_assertions':detected,'elapsed_seconds':elapsed, + 'source_sha256':hashlib.sha256(text.encode()).hexdigest(), + 'stdout_sha256':hashlib.sha256(p.stdout).hexdigest(), + 'stderr_sha256':hashlib.sha256(p.stderr).hexdigest()}) +report={'source_sha256':hashlib.sha256(source.encode()).hexdigest(), + 'tests_sha256':hashlib.sha256(tests).hexdigest(), 'cases':results, + 'passed':all(row['detected_as_assertions'] for row in results)} +(out/'REPORT.json').write_text(json.dumps(report,indent=2)+'\n') +print(json.dumps({'passed':report['passed'],'runs':len(results), + 'normal_failures':{r['name']:r['assertion_failures'] for r in results if r['mode']=='normal'}},indent=2)) +raise SystemExit(0 if report['passed'] else 1)