#!/usr/bin/env python3
"""Reproduce pinned runtime evidence; requires installed repository dependencies and Node 24.
Usage: python3 evidence-probe.py /path/to/repository
Creates isolated git archives under /tmp; never changes repository source or environment files.
"""
import os, sys, subprocess, tempfile, pathlib, hashlib
repo=pathlib.Path(sys.argv[1]).resolve()
out=pathlib.Path(tempfile.mkdtemp(prefix='evidence-22816-'))
def run(args, cwd=None):
    print('$ ' + ' '.join(map(str,args)), flush=True)
    subprocess.run(list(map(str,args)), cwd=cwd, check=True)
print('Host: Linux; shell: /bin/bash -ilc; Node:', subprocess.check_output(['node','--version'],text=True).strip(), flush=True)
print('No viewport: no render path. Synthetic tokens only; no OAuth validity claim.', flush=True)
probe=out/'runtime.mts'
probe.write_text('// Issue 22816 runtime probe. Runs the real DesktopShellEnvironment layer against a\n// real bash login shell whose profile exports a SYNTHETIC token. Never reads real\n// credentials; prints only yes/no for the token.\n//\n// Usage: node --experimental-import-meta-resolve /tmp/triage-22816/probe.mts <worktree>\nimport { execFileSync } from "node:child_process";\nimport { mkdtempSync, rmSync, writeFileSync } from "node:fs";\nimport { tmpdir } from "node:os";\nimport { join } from "node:path";\nimport { pathToFileURL } from "node:url";\n\nconst worktree = process.argv[2] ?? "/home/ubuntu/wt/issue-22816";\nconst parent = pathToFileURL(join(worktree, "apps/desktop/package.json")).href;\nconst load = (specifier: string) => import(import.meta.resolve(specifier, parent));\n\nconst Effect = await load("effect/Effect");\nconst Layer = await load("effect/Layer");\nconst Logger = await load("effect/Logger");\nconst NodeServices = await load("@effect/platform-node/NodeServices");\nconst DesktopEnvironment = await import(\n  pathToFileURL(join(worktree, "apps/desktop/src/app/DesktopEnvironment.ts")).href\n);\nconst DesktopShellEnvironment = await import(\n  pathToFileURL(join(worktree, "apps/desktop/src/shell/DesktopShellEnvironment.ts")).href\n);\n\nconst mode = process.argv[3] ?? "missing-present";\nconst SYNTHETIC = "synthetic-token-22816";\nconst home = mkdtempSync(join(tmpdir(), "probe-22816-"));\nwriteFileSync(join(home, ".bash_profile"), mode.endsWith("absent") ? "unset CLAUDE_CODE_OAUTH_TOKEN\\n" : `export CLAUDE_CODE_OAUTH_TOKEN="${SYNTHETIC}"\\n`);\n\n// A Dock-like launch: no profile exports, minimal PATH, no inherited token.\nconst env: NodeJS.ProcessEnv = { HOME: home, SHELL: "/bin/bash", PATH: "/usr/bin:/bin" };\n\nif (mode.startsWith("inherited")) env.CLAUDE_CODE_OAUTH_TOKEN = "synthetic-inherited-22816";\nif (mode.startsWith("empty")) env.CLAUDE_CODE_OAUTH_TOKEN = "";\n\nconst loginShellSees =\n  execFileSync("/bin/bash", ["-ilc", \'test "$CLAUDE_CODE_OAUTH_TOKEN" = \' + SYNTHETIC + " && echo yes || echo no"], {\n    env,\n    encoding: "utf8",\n    stdio: ["ignore", "pipe", "ignore"],\n  }).trim().split("\\n").at(-1);\n\nconst previous = process.env;\nprocess.env = env;\nlet installed: boolean;\ntry {\n  installed = await Effect.runPromise(\n    Effect.gen(function* () {\n      const shell = yield* DesktopShellEnvironment.DesktopShellEnvironment;\n      return yield* shell.installIntoProcess;\n    }).pipe(\n      Effect.provide(\n        DesktopShellEnvironment.layer.pipe(\n          Layer.provide(\n            Layer.mergeAll(\n              Layer.succeed(\n                DesktopEnvironment.DesktopEnvironment,\n                DesktopEnvironment.DesktopEnvironment.of({ platform: process.platform }),\n              ),\n              NodeServices.layer,\n            ),\n          ),\n        ),\n      ),\n      Effect.provide(Logger.layer([])),\n    ),\n  );\n} finally {\n  process.env = previous;\n  rmSync(home, { recursive: true, force: true });\n}\n\nconsole.log(`source: ${worktree}`);\nconsole.log(`platform: ${process.platform} shell: /bin/bash -ilc`);\nconsole.log(`login shell sees token: ${loginShellSees}`);\nconsole.log(`PATH hydration succeeded: ${installed && typeof env.PATH === "string" ? "yes" : "no"}`);\nconsole.log(`env token after install: ${env.CLAUDE_CODE_OAUTH_TOKEN === SYNTHETIC ? "set (synthetic)" : env.CLAUDE_CODE_OAUTH_TOKEN === undefined ? "unset" : env.CLAUDE_CODE_OAUTH_TOKEN === "synthetic-inherited-22816" ? "inherited (synthetic)" : "empty"}`);\n\nconst expected = mode.startsWith("inherited") ? "synthetic-inherited-22816" : mode.endsWith("absent") ? undefined : SYNTHETIC;\nconsole.log(`fixture: ${mode}; desired-behavior assertion: ${env.CLAUDE_CODE_OAUTH_TOKEN === expected ? "PASS" : "FAIL (regression)"}`);\nconst baselineExpected = mode.startsWith("inherited") ? "synthetic-inherited-22816" : mode.startsWith("empty") ? "" : undefined;\nconst revisionExpected = process.argv[4] === "base" ? baselineExpected : expected;\nif (env.CLAUDE_CODE_OAUTH_TOKEN !== revisionExpected) throw new Error("unexpected revision behavior");\n\n')
for label,rev in [('base','8acbefefc5'),('head','58ad1b79bf')]:
    sha=subprocess.check_output(['git','-C',str(repo),'rev-parse',rev],text=True).strip()
    dst=out/label; dst.mkdir()
    print('\nREVISION',label,sha,flush=True)
    blob=subprocess.check_output(['git','-C',str(repo),'rev-parse',sha+':apps/desktop/src/shell/DesktopShellEnvironment.ts'],text=True).strip()
    print('Production git blob:',blob,flush=True)
    archive=subprocess.Popen(['git','-C',str(repo),'archive',sha],stdout=subprocess.PIPE)
    subprocess.run(['tar','-x','-C',str(dst)],stdin=archive.stdout,check=True)
    archive.stdout.close(); assert archive.wait()==0
    # Mirror dependency links, redirecting every workspace target into this revision.
    for folder in [repo,*list((repo/'apps').iterdir()),*list((repo/'packages').iterdir())]:
        nm=folder/'node_modules'
        if not nm.is_dir(): continue
        target=dst/folder.relative_to(repo)/'node_modules'; target.mkdir(parents=True,exist_ok=True)
        for item in nm.iterdir():
            if item.name.startswith('@') and item.is_dir():
                (target/item.name).mkdir(exist_ok=True)
                entries=list(item.iterdir())
            else: entries=[item]
            for entry in entries:
                resolved=entry.resolve(); dest=target/entry.relative_to(nm)
                try:
                    rel=resolved.relative_to(repo)
                    source=resolved if 'node_modules' in rel.parts else dst/rel
                except ValueError: source=resolved
                dest.symlink_to(source,target_is_directory=source.is_dir())
    actual=subprocess.check_output(['git','hash-object',str(dst/'apps/desktop/src/shell/DesktopShellEnvironment.ts')],text=True).strip()
    assert actual==blob
    print('Archived source blob verified; workspace package links point into archive.',flush=True)
    run(['node','--experimental-import-meta-resolve','--input-type=module','-e',"console.log('shared shell resolved:', import.meta.resolve('@t3tools/shared/shell', process.argv[1]))",(dst/'apps/desktop/package.json').as_uri()])
    for row,mode in [('R1','missing-present'),('R2','inherited-present'),('R3','missing-absent'),('R4','inherited-absent'),('R5','empty-present')]:
        print(row,flush=True)
        run(['node','--experimental-import-meta-resolve',probe,dst,mode,label])
    if label=='head':
        run([dst/'node_modules/.bin/vp','test','run','apps/desktop/src/shell/DesktopShellEnvironment.test.ts'],cwd=dst)
print('R8: cannot-verify desktop-macos (Linux cannot prove Dock/zsh/provider card).',flush=True)
print('No rendering changes; no browser/server; no source edits/commit/push/PR/delegation.',flush=True)
