mirror of
https://github.com/garrytan/gstack.git
synced 2026-11-20 15:13:47 +01:00
Merge oct8-autoplan-perms: no permission cards for /autoplan's own files after a background reviewer
This commit is contained in:
commit
2445fbcb93
16 files changed
+367
-88
No files matched your search
+5
-4
@@ -672,14 +672,15 @@ Resolve SNAPSHOT_TOOL once:
|
||||
bun -e 'console.log(require("fs").realpathSync(process.argv[1]))' "$HOME/.claude/skills/gstack/bin/gstack-autoplan-snapshot.ts"
|
||||
```
|
||||
|
||||
Fresh external RESTORE_PATH:
|
||||
Fresh RESTORE_PATH, beside its phase artifacts in the project's git-excluded `.gstack/tmp/autoplan/`:
|
||||
```bash
|
||||
SLUG=$(~/.claude/skills/gstack/bin/gstack-slug --get SLUG 2>/dev/null)
|
||||
GSTACK_STATE_ROOT=$(~/.claude/skills/gstack/bin/gstack-paths --get GSTACK_STATE_ROOT); : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}"
|
||||
mkdir -p "$GSTACK_STATE_ROOT/projects/$SLUG"
|
||||
_AP="$(git rev-parse --show-toplevel 2>/dev/null || pwd)/.gstack/tmp/autoplan"; mkdir -p "$_AP" && chmod 700 "$_AP"
|
||||
_EX=$(git rev-parse --git-path info/exclude 2>/dev/null) && mkdir -p "${_EX%/*}" && { grep -qxF /.gstack/tmp/ "$_EX" 2>/dev/null || echo /.gstack/tmp/ >> "$_EX"; }
|
||||
BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null | tr '/' '-')
|
||||
DATETIME=$(date +%Y%m%d-%H%M%S)
|
||||
echo "RESTORE_PATH=$GSTACK_STATE_ROOT/projects/$SLUG/${BRANCH}-autoplan-restore-${DATETIME}.md"
|
||||
echo "SLUG=$SLUG"
|
||||
echo "RESTORE_PATH=$_AP/${BRANCH}-autoplan-restore-${DATETIME}.md"
|
||||
```
|
||||
|
||||
Before scope/review:
|
||||
|
||||
@@ -201,14 +201,15 @@ Send phase announcements and the final approval request in the conversation.
|
||||
Resolve SNAPSHOT_TOOL once:
|
||||
{{AUTOPLAN_SNAPSHOT_TOOL}}
|
||||
|
||||
Fresh external RESTORE_PATH:
|
||||
Fresh RESTORE_PATH, beside its phase artifacts in the project's git-excluded `.gstack/tmp/autoplan/`:
|
||||
```bash
|
||||
{{SLUG_EVAL}}
|
||||
GSTACK_STATE_ROOT=$(~/.claude/skills/gstack/bin/gstack-paths --get GSTACK_STATE_ROOT); : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}"
|
||||
mkdir -p "$GSTACK_STATE_ROOT/projects/$SLUG"
|
||||
_AP="$(git rev-parse --show-toplevel 2>/dev/null || pwd)/.gstack/tmp/autoplan"; mkdir -p "$_AP" && chmod 700 "$_AP"
|
||||
_EX=$(git rev-parse --git-path info/exclude 2>/dev/null) && mkdir -p "${_EX%/*}" && { grep -qxF /.gstack/tmp/ "$_EX" 2>/dev/null || echo /.gstack/tmp/ >> "$_EX"; }
|
||||
BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null | tr '/' '-')
|
||||
DATETIME=$(date +%Y%m%d-%H%M%S)
|
||||
echo "RESTORE_PATH=$GSTACK_STATE_ROOT/projects/$SLUG/${BRANCH}-autoplan-restore-${DATETIME}.md"
|
||||
echo "SLUG=$SLUG"
|
||||
echo "RESTORE_PATH=$_AP/${BRANCH}-autoplan-restore-${DATETIME}.md"
|
||||
```
|
||||
|
||||
Before scope/review:
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
/**
|
||||
* /autoplan's own read-only inputs, approved without a permission card.
|
||||
*
|
||||
* Claude Code clears a skill's `allowed-tools` grant when the next turn starts,
|
||||
* and a background reviewer's completion notice starts one. The skill's hooks
|
||||
* stay registered for the session, so this hook re-approves exactly the files
|
||||
* /autoplan itself reads outside the working directory: its installed section
|
||||
* files, and the immutable phase artifacts in a project's `.gstack/tmp/autoplan/`
|
||||
* when the session started below the repository root. It never denies; anything
|
||||
* else keeps Claude Code's own permission check. Skill hooks do not run inside
|
||||
* subagents, so reviewer inputs live in the project, which needs no approval.
|
||||
*/
|
||||
import * as fs from 'node:fs';
|
||||
import * as path from 'node:path';
|
||||
import * as os from 'node:os';
|
||||
import { nativePathSpelling, sameNativePath } from '../../lib/claude-journal-records';
|
||||
import { resolveStateRoot } from '../../lib/state-root';
|
||||
|
||||
/** setup's `${GSTACK_USER_RENDER_DIR:-$GSTACK_STATE_ROOT/render/claude}`, realpath'd. */
|
||||
export function userRenderRoot(): string | undefined {
|
||||
const configured = process.env.GSTACK_USER_RENDER_DIR || path.join(resolveStateRoot(), 'render', 'claude');
|
||||
try { return fs.realpathSync(path.resolve(nativePathSpelling(configured))); } catch { return; }
|
||||
}
|
||||
|
||||
/** scripts/gen-skill-docs.ts rewriteSectionBase, which writes that render. */
|
||||
export function renderSectionBase(content: string, linkRoot: string): string {
|
||||
return content.replace(
|
||||
/~\/\.claude\/skills\/gstack\/([^\s)`"'*]+\/sections\/)/g,
|
||||
(_m, p1: string) => `${linkRoot}/${p1}`,
|
||||
);
|
||||
}
|
||||
|
||||
const ARTIFACT_DIR = /^autoplan-(ceo|design|dx|eng)-[^\\/]+$/;
|
||||
const artifactFiles = (phase: string) => ['methodology.md', 'methodology.json', 'native-prompt.md', 'snapshot.json',
|
||||
'source-implementation.md', `${phase}-implementation.md`, 'close-packet.md'];
|
||||
|
||||
/** True only for this installation's autoplan/sections/*.md, or an immutable artifact in
|
||||
* <repo>/.gstack/tmp/autoplan/autoplan-<phase>-*\/ where <repo> is the session's project directory or contains it. */
|
||||
export function ownedAutoplanRead(file: unknown, cwd: string, root: string): boolean {
|
||||
if (typeof file !== 'string') return false;
|
||||
try {
|
||||
const requested = nativePathSpelling(path.resolve(cwd, file.replace(/^~(?=[\\/]|$)/, () => os.homedir())));
|
||||
const base = path.basename(requested), directory = path.dirname(requested), actual = fs.realpathSync(requested);
|
||||
if (path.basename(directory) === 'sections' && path.basename(path.dirname(directory)) === 'autoplan') {
|
||||
const canonical = path.join(root, 'autoplan', 'sections', base);
|
||||
if (!/^[a-z0-9-]+\.md$/.test(base) || !fs.lstatSync(canonical).isFile()) return false;
|
||||
if (sameNativePath(actual, canonical)) return true;
|
||||
const render = userRenderRoot();
|
||||
return !!render && sameNativePath(actual, path.join(render, 'autoplan', 'sections', base)) &&
|
||||
fs.readFileSync(actual, 'utf8') === renderSectionBase(fs.readFileSync(canonical, 'utf8'), render);
|
||||
}
|
||||
const phase = ARTIFACT_DIR.exec(path.basename(directory))?.[1];
|
||||
if (!phase || !artifactFiles(phase).includes(base) || !sameNativePath(actual, requested)) return false;
|
||||
const stat = fs.lstatSync(requested), store = path.dirname(directory), owner = path.dirname(path.dirname(path.dirname(store)));
|
||||
const project = fs.realpathSync(nativePathSpelling(process.env.CLAUDE_PROJECT_DIR || cwd));
|
||||
return stat.isFile() && sameNativePath(store, path.join(owner, '.gstack', 'tmp', 'autoplan')) &&
|
||||
(sameNativePath(project, owner) || nativePathSpelling(project).startsWith(nativePathSpelling(owner) + path.sep)) &&
|
||||
(process.platform === 'win32' || (stat.mode & 0o777) === 0o444);
|
||||
} catch { return false; }
|
||||
}
|
||||
|
||||
export const OWNED_READ_APPROVAL = Object.freeze({ hookSpecificOutput: Object.freeze({ hookEventName: 'PreToolUse',
|
||||
permissionDecision: 'allow', permissionDecisionReason: '[autoplan] Reading an /autoplan section or phase artifact.' }) });
|
||||
|
||||
/** The guard's own verdict wins: only a parent Read the guard left without any output is approved. */
|
||||
export function approveOwnedRead(value: unknown, output: object, root: string): object {
|
||||
if (Object.keys(output).length || value === null || typeof value !== 'object') return output;
|
||||
const input = value as Record<string, any>;
|
||||
if (input.tool_name !== 'Read' || input.agent_id || typeof input.cwd !== 'string' ||
|
||||
!ownedAutoplanRead(input.tool_input?.file_path, input.cwd, root)) return output;
|
||||
return OWNED_READ_APPROVAL;
|
||||
}
|
||||
@@ -11,9 +11,9 @@ import { autoplanPhaseCompletions } from '../../lib/autoplan-phase-publication';
|
||||
import { nativePathSpelling, ownedNativePath, sameNativePath, type ClaudeParentPublicEvent } from '../../lib/claude-journal-records';
|
||||
import { ownedRecordLimit, ownedRetainedLimit, type JournalPrefix, type OwnedRead, type OwnedReadMeasure } from '../../lib/claude-owned-journal';
|
||||
import { readGuardJournal, textResult, DEDUP_REPLY } from './guard-journal';
|
||||
import { resolveStateRoot } from '../../lib/state-root';
|
||||
import { REASONS, reasonCode, reasonText, type Detail, type ReasonCode } from './guard-reasons';
|
||||
import { logGuardDecision } from './guard-log';
|
||||
import { approveOwnedRead, renderSectionBase, userRenderRoot } from './owned-read';
|
||||
|
||||
const PHASES = ['ceo', 'design', 'dx', 'eng', 'tasks'] as const;
|
||||
type Phase = typeof PHASES[number];
|
||||
@@ -129,20 +129,6 @@ function driver(file: unknown, cwd: string, root: string): Phase | undefined {
|
||||
return fail('foreign_install');
|
||||
}
|
||||
|
||||
/** setup's `${GSTACK_USER_RENDER_DIR:-$GSTACK_STATE_ROOT/render/claude}`, realpath'd. */
|
||||
function userRenderRoot(): string | undefined {
|
||||
const configured = process.env.GSTACK_USER_RENDER_DIR || path.join(resolveStateRoot(), 'render', 'claude');
|
||||
try { return fs.realpathSync(path.resolve(nativePathSpelling(configured))); } catch { return; }
|
||||
}
|
||||
|
||||
/** scripts/gen-skill-docs.ts rewriteSectionBase, which writes that render. */
|
||||
function renderSectionBase(content: string, linkRoot: string): string {
|
||||
return content.replace(
|
||||
/~\/\.claude\/skills\/gstack\/([^\s)`"'*]+\/sections\/)/g,
|
||||
(_m, p1: string) => `${linkRoot}/${p1}`,
|
||||
);
|
||||
}
|
||||
|
||||
interface Consumer { phase: Phase; content?: string; kind: 'Read' | 'Agent' }
|
||||
function artifactName(file: unknown, cwd: string, includeClose = false): Phase | undefined {
|
||||
if (typeof file !== 'string') return;
|
||||
@@ -688,6 +674,10 @@ export function ownedRead(journal: string, owners: string[], input: PublicationH
|
||||
* read. Claude Code's appends never fail a read; a changed prefix is `rewritten`.
|
||||
*/
|
||||
export async function runPublicationHook(value: unknown, root: string): Promise<object> {
|
||||
return approveOwnedRead(value, await guardOutput(value, root), root);
|
||||
}
|
||||
|
||||
async function guardOutput(value: unknown, root: string): Promise<object> {
|
||||
let version: string | undefined;
|
||||
try {
|
||||
if (!object(value) || value.hook_event_name !== 'PreToolUse' || typeof value.tool_name !== 'string') return denied('hook_input');
|
||||
|
||||
@@ -299,6 +299,36 @@ completion notice. Wait for that notice before closing the phase. A background
|
||||
reviewer keeps the invocation armed, so a typed message while it runs does not
|
||||
end `/autoplan`.
|
||||
|
||||
### Permission cards after a background reviewer
|
||||
|
||||
A skill's `allowed-tools` applies only to the turn that invoked it, and a
|
||||
background reviewer's completion notice starts a new turn. From then on Claude
|
||||
Code's normal permission rules apply, so Reads outside the session's working
|
||||
directory can show a card, and in Manual mode so do Bash commands that are not
|
||||
read-only. Skill hooks stay registered for the whole session but do not run
|
||||
inside subagents.
|
||||
|
||||
`/autoplan` therefore keeps its own files readable without a card:
|
||||
|
||||
- The restore point and every phase artifact (methodology, reviewer input,
|
||||
snapshots, close packet) live in the project's `.gstack/tmp/autoplan/`, which
|
||||
Step 1 adds to `.git/info/exclude`. Claude Code reads files in the working
|
||||
directory without a card, for `/autoplan` and for its reviewer subagents. A
|
||||
`git clean -x` deletes them, restore point included.
|
||||
- The publication hook approves `/autoplan`'s own Reads outside the working
|
||||
directory: this installation's `autoplan/sections/*.md`, and the immutable
|
||||
artifacts in `<repo>/.gstack/tmp/autoplan/` when the session started in a
|
||||
subdirectory of the repository. It approves nothing else, and never a call
|
||||
the guard denies.
|
||||
|
||||
A session started in a repository subdirectory still shows a card when a
|
||||
reviewer reads its input: subagents run without the skill's hook. Start the
|
||||
session at the repository root, or answer the card with "Yes, allow reading
|
||||
from ... during this session". In Manual mode, `/autoplan`'s Bash commands
|
||||
after the first background reviewer also show cards; auto mode, the default
|
||||
starting mode on current Claude Code for supported models, sends them to its
|
||||
classifier instead.
|
||||
|
||||
## Supported journal roots
|
||||
|
||||
The guard accepts exactly one root per journal file:
|
||||
|
||||
@@ -11,6 +11,7 @@ import { guardFixture, section, denial, codeOf, ROOT, type GuardFixture } from '
|
||||
import { ownedRead } from '../autoplan/bin/phase-publication-hook.ts';
|
||||
import { DEDUP_REPLY } from '../autoplan/bin/guard-journal';
|
||||
import { readOwnedClaudePublicTranscript, ownedRetainedLimit, OWNED_RETAINED_MAX_BYTES, type OwnedReadMeasure } from '../lib/claude-owned-journal';
|
||||
import { OWNED_READ_APPROVAL } from '../autoplan/bin/owned-read';
|
||||
|
||||
const RECORD = 32 * 1024, RETAINED = 64 * 1024;
|
||||
const fixtures: GuardFixture[] = [];
|
||||
@@ -52,7 +53,7 @@ const next = (f: GuardFixture) => { f.use('next', 'Read', { file_path: section('
|
||||
describe('A2: the guard decides on a journal larger than its shrunk bounds', () => {
|
||||
test('a published Phase 1 enters Phase 2; the same journal without the report is denied', async () => {
|
||||
const allowed = make(); allowed.publish(); const input = next(allowed); long(allowed);
|
||||
expect(await bounded(() => allowed.hook(input))).toEqual({});
|
||||
expect(await bounded(() => allowed.hook(input))).toEqual(OWNED_READ_APPROVAL);
|
||||
expect(allowed.log().at(-1)).toMatchObject({ decision: 'allow', disposition: 'allow', path: 'journal' });
|
||||
const unpublished = make(); const blocked = next(unpublished); long(unpublished);
|
||||
const output = await bounded(() => unpublished.hook(blocked));
|
||||
@@ -83,7 +84,7 @@ describe('A2: the guard decides on a journal larger than its shrunk bounds', ()
|
||||
|
||||
test('a run started by a typed request and the Skill tool (no /autoplan slash turn) binds its init', async () => {
|
||||
const f = make('ceo', { opening: 'skill' }); f.publish(); const input = next(f); long(f);
|
||||
expect(await bounded(() => f.hook(input))).toEqual({});
|
||||
expect(await bounded(() => f.hook(input))).toEqual(OWNED_READ_APPROVAL);
|
||||
const unpublished = make('ceo', { opening: 'skill' }); const blocked = next(unpublished); long(unpublished);
|
||||
expect(codeOf(await bounded(() => unpublished.hook(blocked)))).toBe('publication_missing');
|
||||
});
|
||||
@@ -129,7 +130,7 @@ describe('A2: append-tolerant reads with prefix identity', () => {
|
||||
const grown = fs.statSync(f.transcript).size;
|
||||
for (let i = 0; i < 50 && fs.statSync(f.transcript).size === grown; i++) await Bun.sleep(10);
|
||||
expect(fs.statSync(f.transcript).size).toBeGreaterThan(grown);
|
||||
expect(await f.hook(input)).toEqual({});
|
||||
expect(await f.hook(input)).toEqual(OWNED_READ_APPROVAL);
|
||||
} finally { appender.kill(); await appender.exited; }
|
||||
});
|
||||
|
||||
@@ -185,6 +186,6 @@ describe('A2: append-tolerant reads with prefix identity', () => {
|
||||
// A record still being written (no newline yet) is not evidence: the read ends at the last complete line.
|
||||
const partial = make(); partial.publish(); const current = next(partial); long(partial);
|
||||
fs.appendFileSync(partial.transcript, JSON.stringify({ type: 'assistant', sessionId: partial.sessionId }).slice(0, -2));
|
||||
expect(await bounded(() => partial.hook(current))).toEqual({});
|
||||
expect(await bounded(() => partial.hook(current))).toEqual(OWNED_READ_APPROVAL);
|
||||
});
|
||||
});
|
||||
@@ -11,6 +11,7 @@ import { randomUUID } from 'node:crypto';
|
||||
import { guardFixture, section, type GuardFixture } from './helpers/autoplan-guard-fixture';
|
||||
import { padBeforeCompactBoundary } from './helpers/journal-padding';
|
||||
import { readPlanCountTranscript } from '../lib/claude-public-transcript';
|
||||
import { OWNED_READ_APPROVAL } from '../autoplan/bin/owned-read';
|
||||
|
||||
const fixtures: GuardFixture[] = [];
|
||||
const prior = process.env.GSTACK_TRANSCRIPT_TEST_MAX_BYTES;
|
||||
@@ -44,7 +45,7 @@ test('a padded long-session journal: the counting reader refuses it, the guard l
|
||||
process.env.GSTACK_TRANSCRIPT_TEST_MAX_BYTES = String(256 * 1024);
|
||||
const counting = readPlanCountTranscript(path.join(f.cwd, 'config'), f.cwd);
|
||||
expect(counting).toMatchObject({ status: 'error', reason: 'too_large' });
|
||||
expect(await f.hook(f.input('next', 'Read', { file_path: section('design-phase.md') }))).toEqual({});
|
||||
expect(await f.hook(f.input('next', 'Read', { file_path: section('design-phase.md') }))).toEqual(OWNED_READ_APPROVAL);
|
||||
expect(f.log()).toEqual([expect.objectContaining({ decision: 'allow', disposition: 'allow', code: null, path: 'payload' })]);
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
/**
|
||||
* After a background reviewer's completion notice starts a new turn, Claude Code
|
||||
* no longer applies /autoplan's allowed-tools, so Reads outside the working
|
||||
* directory raise permission cards. /autoplan writes its phase artifacts in the
|
||||
* project's `.gstack/tmp/autoplan/`, and the publication hook (registered for
|
||||
* the whole session) approves exactly /autoplan's own files, leaving every other
|
||||
* Read, and every guard verdict, to Claude Code.
|
||||
*/
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
|
||||
import * as fs from 'node:fs';
|
||||
import * as path from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { initializePlan, prepareMethodology, createSnapshot, preparePhaseClose } from '../bin/gstack-autoplan-snapshot';
|
||||
import { runPublicationHook } from '../autoplan/bin/phase-publication-hook.ts';
|
||||
import { OWNED_READ_APPROVAL } from '../autoplan/bin/owned-read';
|
||||
import { guardFixture, section } from './helpers/autoplan-guard-fixture';
|
||||
|
||||
const ROOT = fs.realpathSync(path.join(import.meta.dir, '..'));
|
||||
const SHIM = path.join(ROOT, 'autoplan/bin/phase-publication-hook');
|
||||
const dirs: string[] = [];
|
||||
let logHome = '', previous: Record<string, string | undefined> = {};
|
||||
beforeAll(() => {
|
||||
logHome = fs.realpathSync(fs.mkdtempSync(path.join(tmpdir(), 'autoplan-owned-log-')));
|
||||
previous = { GSTACK_STATE_ROOT: process.env.GSTACK_STATE_ROOT, GSTACK_HOME: process.env.GSTACK_HOME, CLAUDE_PROJECT_DIR: process.env.CLAUDE_PROJECT_DIR };
|
||||
process.env.GSTACK_STATE_ROOT = logHome; process.env.GSTACK_HOME = logHome; delete process.env.CLAUDE_PROJECT_DIR;
|
||||
});
|
||||
afterAll(() => {
|
||||
for (const [k, v] of Object.entries(previous)) if (v === undefined) delete process.env[k]; else process.env[k] = v;
|
||||
fs.rmSync(logHome, { recursive: true, force: true });
|
||||
});
|
||||
afterEach(() => { for (const dir of dirs.splice(0)) fs.rmSync(dir, { recursive: true, force: true }); });
|
||||
const scratch = (prefix: string) => { const d = fs.realpathSync(fs.mkdtempSync(path.join(tmpdir(), prefix))); dirs.push(d); return d; };
|
||||
|
||||
/** A real Phase 1 close with the restore point and artifacts in `<repo>/.gstack/tmp/autoplan/`, as Step 1 places them. */
|
||||
function ceoClose() {
|
||||
const repo = scratch('autoplan-owned-repo-'), store = path.join(repo, '.gstack', 'tmp', 'autoplan'), session = path.join(repo, 'packages', 'app');
|
||||
fs.mkdirSync(store, { recursive: true }); fs.mkdirSync(session, { recursive: true });
|
||||
const source = path.join(repo, 'PLAN.md'), active = path.join(repo, 'active.md'), restore = path.join(store, 'main-autoplan-restore.md');
|
||||
fs.writeFileSync(source, '# Plan: greet\nAdd a greet command.\n');
|
||||
initializePlan(source, active, restore);
|
||||
const skill = path.join(repo, 'SKILL.md');
|
||||
fs.writeFileSync(skill, '---\nname: plan-ceo-review\n---\n## Review Sections\nApply every criterion.\n');
|
||||
const method = prepareMethodology('ceo', skill, restore).methodologyPath;
|
||||
const snapshot = createSnapshot('ceo', active, restore, method);
|
||||
fs.appendFileSync(active, '<!-- autoplan-accepted:ceo -->\nNone: retain the current behavior.\n<!-- /autoplan-accepted:ceo -->\n');
|
||||
return { repo, session, method, snapshot, packet: preparePhaseClose('ceo', active, snapshot.snapshotPath, restore, method).closePacketPath as string };
|
||||
}
|
||||
const read = (cwd: string, file: string, extra: object = {}) => ({ hook_event_name: 'PreToolUse', session_id: 'parent', cwd,
|
||||
transcript_path: path.join(cwd, 'no-config', 'projects', 'p', 'parent.jsonl'), tool_name: 'Read', tool_use_id: 'current',
|
||||
tool_input: { file_path: file }, ...extra });
|
||||
|
||||
describe('/autoplan owned reads after the skill turn', () => {
|
||||
test('the shipped hook approves the shared close section and the installed link spelling', () => {
|
||||
const home = scratch('autoplan-owned-home-'), cwd = scratch('autoplan-owned-cwd-');
|
||||
fs.mkdirSync(path.join(home, '.claude', 'skills'), { recursive: true });
|
||||
fs.symlinkSync(ROOT, path.join(home, '.claude', 'skills', 'gstack'), 'dir');
|
||||
for (const file of [path.join(ROOT, 'autoplan/sections/phase-close.md'), path.join(home, '.claude/skills/gstack/autoplan/sections/phase-close.md')]) {
|
||||
const child = spawnSync('bash', [SHIM], { input: JSON.stringify(read(cwd, file)), encoding: 'utf8', timeout: 8_000,
|
||||
env: { ...process.env, HOME: home, PATH: `${path.dirname(process.execPath)}:${process.env.PATH ?? ''}` } });
|
||||
expect(child.status).toBe(0);
|
||||
expect(JSON.parse(child.stdout)).toEqual(OWNED_READ_APPROVAL);
|
||||
}
|
||||
});
|
||||
|
||||
test('a session started below the repository root reads the close packet without a journal or a card', async () => {
|
||||
const c = ceoClose();
|
||||
expect(await runPublicationHook(read(c.session, c.packet), ROOT)).toEqual(OWNED_READ_APPROVAL);
|
||||
});
|
||||
|
||||
test('guarded phase artifacts and the next driver are approved once the guard verifies them', async () => {
|
||||
const f = guardFixture('ceo', { restoreInProject: true });
|
||||
try {
|
||||
const dir = path.dirname(f.snapshot.snapshotPath);
|
||||
const files = [f.method, path.join(path.dirname(f.method), 'methodology.json'), f.snapshot.snapshotPath,
|
||||
path.join(dir, 'snapshot.json'), path.join(dir, 'source-implementation.md'), path.join(dir, 'native-prompt.md'), f.packet.closePacketPath];
|
||||
for (const [i, file] of files.entries()) {
|
||||
f.use(`artifact-${i}`, 'Read', { file_path: file }); f.journal();
|
||||
expect({ file, output: await f.hook(f.input(`artifact-${i}`, 'Read', { file_path: file })) }).toEqual({ file, output: OWNED_READ_APPROVAL });
|
||||
f.readResult(`artifact-${i}`, file);
|
||||
}
|
||||
f.publish(); f.use('next', 'Read', { file_path: section('design-phase.md') }); f.journal();
|
||||
expect(await f.hook(f.input('next', 'Read', { file_path: section('design-phase.md') }))).toEqual(OWNED_READ_APPROVAL);
|
||||
// Six guarded artifact Reads and the Phase 2 entry, each a verified allow; the close packet is not a guarded Read.
|
||||
expect(f.log().map(e => [e.decision, e.disposition])).toEqual(Array(7).fill(['allow', 'allow']));
|
||||
} finally { f.cleanup(); }
|
||||
});
|
||||
|
||||
test('look-alikes and everything else keep Claude Code\'s own permission check', async () => {
|
||||
const c = ceoClose(), other = ceoClose();
|
||||
const foreign = scratch('autoplan-owned-foreign-');
|
||||
fs.mkdirSync(path.join(foreign, 'autoplan', 'sections'), { recursive: true });
|
||||
fs.copyFileSync(path.join(ROOT, 'autoplan/sections/phase-close.md'), path.join(foreign, 'autoplan/sections/phase-close.md'));
|
||||
const store = path.dirname(path.dirname(c.packet));
|
||||
const writable = path.join(store, 'autoplan-ceo-copy'), alias = path.join(store, 'autoplan-ceo-alias');
|
||||
fs.mkdirSync(writable); fs.copyFileSync(c.packet, path.join(writable, 'close-packet.md'));
|
||||
fs.chmodSync(path.join(writable, 'close-packet.md'), 0o644);
|
||||
fs.mkdirSync(alias); fs.symlinkSync(c.packet, path.join(alias, 'close-packet.md'));
|
||||
fs.writeFileSync(path.join(path.dirname(c.packet), 'notes.md'), 'not an artifact\n', { mode: 0o444 });
|
||||
for (const file of [
|
||||
other.packet,
|
||||
path.join(foreign, 'autoplan/sections/phase-close.md'),
|
||||
path.join(ROOT, 'autoplan/sections/../SKILL.md'),
|
||||
path.join(ROOT, 'autoplan/sections/manifest.json'),
|
||||
path.join(ROOT, 'package.json'),
|
||||
path.join(writable, 'close-packet.md'),
|
||||
path.join(alias, 'close-packet.md'),
|
||||
path.join(path.dirname(c.packet), 'notes.md'),
|
||||
path.join(c.repo, 'PLAN.md'),
|
||||
]) expect({ file, output: await runPublicationHook(read(c.session, file), ROOT) }).toEqual({ file, output: {} });
|
||||
expect(await runPublicationHook(read(c.session, c.packet, { agent_id: 'reviewer-child' }), ROOT)).toEqual({});
|
||||
expect(await runPublicationHook({ ...read(c.session, c.packet), tool_name: 'Bash', tool_input: { command: `cat ${c.packet}` } }, ROOT)).toEqual({});
|
||||
});
|
||||
|
||||
test('Step 1 puts the restore point in the repository\'s git-excluded store, from a subdirectory too', () => {
|
||||
const skill = fs.readFileSync(path.join(ROOT, 'autoplan/SKILL.md'), 'utf8');
|
||||
const start = skill.indexOf('```bash\n', skill.indexOf('Fresh RESTORE_PATH')) + 8;
|
||||
const block = skill.slice(start, skill.indexOf('\n```', start));
|
||||
const home = scratch('autoplan-owned-home-'), repo = scratch('autoplan-owned-git-'), session = path.join(repo, 'packages', 'app');
|
||||
fs.mkdirSync(path.join(home, '.claude', 'skills'), { recursive: true }); fs.mkdirSync(session, { recursive: true });
|
||||
fs.symlinkSync(ROOT, path.join(home, '.claude', 'skills', 'gstack'), 'dir');
|
||||
expect(spawnSync('git', ['init', '-q', '-b', 'main'], { cwd: repo, timeout: 10_000 }).status).toBe(0);
|
||||
const run = () => spawnSync('bash', ['-c', block], { cwd: session, encoding: 'utf8', timeout: 15_000, env: { ...process.env, HOME: home } });
|
||||
const first = run(), second = run();
|
||||
expect(first.status).toBe(0); expect(second.status).toBe(0);
|
||||
const restore = /^RESTORE_PATH=(.+)$/m.exec(first.stdout)?.[1] ?? '';
|
||||
expect(path.dirname(restore)).toBe(path.join(repo, '.gstack', 'tmp', 'autoplan'));
|
||||
expect(path.basename(restore)).toMatch(/-autoplan-restore-\d{8}-\d{6}\.md$/);
|
||||
expect(fs.readFileSync(path.join(repo, '.git', 'info', 'exclude'), 'utf8').split('\n').filter(l => l === '/.gstack/tmp/')).toHaveLength(1);
|
||||
expect(spawnSync('git', ['status', '--porcelain', '--untracked-files=all'], { cwd: repo, encoding: 'utf8', timeout: 10_000 }).stdout).toBe('');
|
||||
});
|
||||
|
||||
test('a guard denial is never turned into an approval', async () => {
|
||||
const cwd = scratch('autoplan-owned-deny-');
|
||||
const output: any = await runPublicationHook(read(cwd, path.join(ROOT, 'autoplan/sections/design-phase.md')), ROOT);
|
||||
expect(output.hookSpecificOutput.permissionDecision).toBe('deny');
|
||||
});
|
||||
});
|
||||
@@ -9,6 +9,7 @@ import { readOwnedClaudePublicTranscript, readPlanCountTranscript, transcriptRea
|
||||
import { prematureAutoplanPhaseEntry } from './helpers/autoplan-method-read-audit';
|
||||
import captured from './fixtures/autoplan-publication-boundary-361c.json';
|
||||
import consumption from './fixtures/autoplan-phase-consumption-491.json';
|
||||
import { OWNED_READ_APPROVAL, renderSectionBase } from '../autoplan/bin/owned-read';
|
||||
|
||||
const ROOT = fs.realpathSync(path.join(import.meta.dir, '..'));
|
||||
// Every guarded decision appends to the guard log; keep it out of the real state root.
|
||||
@@ -167,7 +168,7 @@ describe('Autoplan parent publication guard', () => {
|
||||
expect(await withNativeProjectDirectory(f.cwd, () => runPublicationHook(f.input, ROOT)))
|
||||
.toMatchObject({ hookSpecificOutput: { permissionDecisionReason: expect.stringContaining('Publish the filled Phase 3') } });
|
||||
f.events.pop(); f.message('Phase 3 complete.'); f.current(); f.journal();
|
||||
expect(await withNativeProjectDirectory(f.cwd, () => runPublicationHook(f.input, ROOT))).toEqual({});
|
||||
expect(await withNativeProjectDirectory(f.cwd, () => runPublicationHook(f.input, ROOT))).toEqual(OWNED_READ_APPROVAL);
|
||||
});
|
||||
|
||||
for (const phase of ['ceo', 'design', 'dx', 'eng'] as const)
|
||||
@@ -297,7 +298,7 @@ describe('Autoplan parent publication guard', () => {
|
||||
test('native project ownership survives a Bash cd through the installed skill link', async () => {
|
||||
const { f } = changedDirectory();
|
||||
expect(readOwnedClaudePublicTranscript(f.input.transcript_path, f.input.cwd, f.sessionId).transcript.status).toBe('missing');
|
||||
expect(await withNativeProjectDirectory(f.cwd, () => runPublicationHook(f.input, ROOT))).toEqual({});
|
||||
expect(await withNativeProjectDirectory(f.cwd, () => runPublicationHook(f.input, ROOT))).toEqual(OWNED_READ_APPROVAL);
|
||||
});
|
||||
|
||||
test('native project ownership still requires publication and permits same-phase repair after cd', async () => {
|
||||
@@ -305,7 +306,7 @@ describe('Autoplan parent publication guard', () => {
|
||||
const output: any = await withNativeProjectDirectory(f.cwd, () => runPublicationHook(f.input, ROOT));
|
||||
expect(output.hookSpecificOutput.permissionDecisionReason).toContain('Publish the filled Phase 1');
|
||||
const same = changedDirectory(false, 'ceo-phase.md');
|
||||
expect(await withNativeProjectDirectory(same.f.cwd, () => runPublicationHook(same.f.input, ROOT))).toEqual({});
|
||||
expect(await withNativeProjectDirectory(same.f.cwd, () => runPublicationHook(same.f.input, ROOT))).toEqual(OWNED_READ_APPROVAL);
|
||||
});
|
||||
|
||||
test('the literal init parser retains Windows drive and UNC identities', () => {
|
||||
@@ -357,7 +358,7 @@ describe('Autoplan parent publication guard', () => {
|
||||
expect(size).toBeGreaterThan(record);
|
||||
await withReadLimit(record, async () => {
|
||||
expect(readOwnedClaudePublicTranscript(f.input.transcript_path, f.input.cwd, f.sessionId).transcript.status).toBe('ready');
|
||||
expect(await withNativeProjectDirectory(f.cwd, () => runPublicationHook(f.input, ROOT))).toEqual({});
|
||||
expect(await withNativeProjectDirectory(f.cwd, () => runPublicationHook(f.input, ROOT))).toEqual(OWNED_READ_APPROVAL);
|
||||
});
|
||||
const output: any = await withReadLimit(record - 1, async () => {
|
||||
expect(readOwnedClaudePublicTranscript(f.input.transcript_path, f.input.cwd, f.sessionId).transcript.reason).toBe('too_large');
|
||||
@@ -404,7 +405,7 @@ describe('Autoplan parent publication guard', () => {
|
||||
// The same actual hook receives native separators in Windows CI.
|
||||
const f = fixture();
|
||||
f.message(); f.current(); f.journal();
|
||||
expect(await withNativeProjectDirectory(f.cwd, () => runPublicationHook(f.input, ROOT))).toEqual({});
|
||||
expect(await withNativeProjectDirectory(f.cwd, () => runPublicationHook(f.input, ROOT))).toEqual(OWNED_READ_APPROVAL);
|
||||
const command = f.events[0]!.input!.command as string;
|
||||
for (const suffix of ['; true', ' && true', ' | cat']) {
|
||||
f.events[0]!.input!.command = command + suffix; f.journal();
|
||||
@@ -420,7 +421,7 @@ describe('Autoplan parent publication guard', () => {
|
||||
|
||||
test('native project ownership preserves the absent-env same-directory adapter', async () => {
|
||||
const f = fixture(); f.message(); f.current(); f.journal();
|
||||
expect(await withNativeProjectDirectory(undefined, () => runPublicationHook(f.input, ROOT))).toEqual({});
|
||||
expect(await withNativeProjectDirectory(undefined, () => runPublicationHook(f.input, ROOT))).toEqual(OWNED_READ_APPROVAL);
|
||||
});
|
||||
|
||||
for (const project of ['absent', 'empty', 'relative', 'foreign', 'unnormalized'] as const) {
|
||||
@@ -801,7 +802,7 @@ describe('Autoplan parent publication guard', () => {
|
||||
await withNativeProjectDirectory(f.cwd, () => withPublicationClock(async () => {
|
||||
const started = performance.now();
|
||||
setTimeout(() => f.journal(), 1_950);
|
||||
expect(await runPublicationHook(f.input, ROOT)).toEqual({});
|
||||
expect(await runPublicationHook(f.input, ROOT)).toEqual(OWNED_READ_APPROVAL);
|
||||
expect(performance.now() - started).toBe(1_950);
|
||||
const decoded = readOwnedClaudePublicTranscript(f.input.transcript_path, f.cwd, f.sessionId);
|
||||
expect(decoded.transcript.status).toBe('ready');
|
||||
@@ -811,7 +812,7 @@ describe('Autoplan parent publication guard', () => {
|
||||
test('the actual owned native reader and asynchronous hook admit a flushed same-response report', async () => {
|
||||
const f = fixture(); f.message(); f.current();
|
||||
setTimeout(() => f.journal(), 100);
|
||||
expect(await runPublicationHook(f.input, ROOT)).toEqual({});
|
||||
expect(await runPublicationHook(f.input, ROOT)).toEqual(OWNED_READ_APPROVAL);
|
||||
const decoded = readOwnedClaudePublicTranscript(f.input.transcript_path, f.cwd, f.sessionId);
|
||||
expect(decoded.transcript.status).toBe('ready');
|
||||
const report = decoded.events.find(e => e.kind === 'message')!, current = decoded.events.find(e => e.kind === 'use' && e.toolUseId === 'next')!;
|
||||
@@ -836,7 +837,7 @@ describe('Autoplan parent publication guard', () => {
|
||||
});
|
||||
test('an in-flight Read can revisit an earlier established phase', async () => {
|
||||
const f = fixture('design', 'ceo'); f.journal();
|
||||
expect(await withNativeProjectDirectory(f.cwd, () => runPublicationHook(f.input, ROOT))).toEqual({});
|
||||
expect(await withNativeProjectDirectory(f.cwd, () => runPublicationHook(f.input, ROOT))).toEqual(OWNED_READ_APPROVAL);
|
||||
});
|
||||
// CEO-1 replaced the pending-Read rule: the payload stands in for an unflushed
|
||||
// current call, so a first Phase 1 entry is allowed from it (it needs no prior
|
||||
@@ -915,7 +916,7 @@ describe('Autoplan parent publication guard', () => {
|
||||
const decoded = readOwnedClaudePublicTranscript(f.input.transcript_path, f.cwd, f.sessionId);
|
||||
expect(decoded.events.filter(e => e.kind === 'user_turn')).toHaveLength(kind === 'human' || kind === 'no-end-turn' ? 2 : 1);
|
||||
const result: any = await runPublicationHook(f.input, ROOT);
|
||||
if (kind === 'human') expect(result).toEqual({});
|
||||
if (kind === 'human') expect(result).toEqual(OWNED_READ_APPROVAL);
|
||||
else expect(result.hookSpecificOutput?.permissionDecision).toBe('deny');
|
||||
});
|
||||
|
||||
@@ -932,7 +933,7 @@ describe('Autoplan parent publication guard', () => {
|
||||
const message: any = { ...current, uuid: randomUUID(), message: { role: 'assistant', content: [{ type: 'text', text: 'Phase 1 complete.' }] } };
|
||||
current.parentUuid = message.uuid; rows.splice(-1, 0, message);
|
||||
fs.writeFileSync(f.input.transcript_path, rows.map(x => JSON.stringify(x)).join('\n') + '\n');
|
||||
expect(await runPublicationHook(f.input, ROOT)).toEqual({});
|
||||
expect(await runPublicationHook(f.input, ROOT)).toEqual(OWNED_READ_APPROVAL);
|
||||
boundary.logicalParentUuid = randomUUID();
|
||||
fs.writeFileSync(f.input.transcript_path, rows.map(x => JSON.stringify(x)).join('\n') + '\n');
|
||||
expect(readOwnedClaudePublicTranscript(f.input.transcript_path, f.cwd, f.sessionId).events.some(e => e.kind === 'use' && e.toolUseId === 'next')).toBe(false);
|
||||
@@ -1229,7 +1230,7 @@ describe('Autoplan native journal roots and Windows spellings', () => {
|
||||
rows[0].parentUuid = chain.at(-1)!.uuid;
|
||||
rows.unshift(...(shape === 'stray-before' ? [attachment(f, null)] : []), ...chain); save();
|
||||
expect(status(f)).toBe('ready');
|
||||
expect(await hook(f)).toEqual({});
|
||||
expect(await hook(f)).toEqual(OWNED_READ_APPROVAL);
|
||||
});
|
||||
|
||||
test('an attachment root still requires the parent publication', async () => {
|
||||
@@ -1340,10 +1341,7 @@ describe('Autoplan phase entry through the gbrain :user render (#2569)', () => {
|
||||
const linkRoot = path.join(scratch(), 'render', 'claude');
|
||||
for (const name of [...sections, 'phase-close.md']) {
|
||||
const text = fs.readFileSync(path.join(ROOT, 'autoplan/sections', name), 'utf8');
|
||||
const hook = fs.readFileSync(path.join(ROOT, 'autoplan/bin/phase-publication-hook.ts'), 'utf8');
|
||||
const fn = hook.slice(hook.indexOf('function renderSectionBase('), hook.indexOf('\n}\n', hook.indexOf('function renderSectionBase(')) + 2);
|
||||
const ours = new Function(new Bun.Transpiler({ loader: 'ts' }).transformSync(fn) + '\nreturn renderSectionBase;')();
|
||||
expect(ours(text, linkRoot)).toBe(rewriteSectionBase(text, linkRoot));
|
||||
expect(renderSectionBase(text, linkRoot)).toBe(rewriteSectionBase(text, linkRoot));
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1452,7 +1450,7 @@ describe('Autoplan ownership in a linked git worktree session', () => {
|
||||
test('the repository root owns its linked worktree journal', async () => {
|
||||
const f = fixture(); f.message(); f.current(); f.journal();
|
||||
const root = repo(); pointer(f.cwd, admin(root, f.cwd));
|
||||
expect(await run(f, root)).toEqual({});
|
||||
expect(await run(f, root)).toEqual(OWNED_READ_APPROVAL);
|
||||
});
|
||||
|
||||
test('a linked worktree journal still requires the parent publication', async () => {
|
||||
@@ -1476,14 +1474,14 @@ describe('Autoplan ownership in a linked git worktree session', () => {
|
||||
// Exactly what git 2.55 `-c worktree.useRelativePaths=true worktree add` writes.
|
||||
fs.writeFileSync(path.join(entry, 'gitdir'), posix(path.relative(entry, path.join(f.cwd, '.git'))) + '\n');
|
||||
fs.writeFileSync(path.join(f.cwd, '.git'), `gitdir: ${posix(path.relative(f.cwd, entry))}\n`);
|
||||
expect(await run(f, root)).toEqual({});
|
||||
expect(await run(f, root)).toEqual(OWNED_READ_APPROVAL);
|
||||
});
|
||||
|
||||
test('an unrelated linked worktree leaves the exact project-directory owner unchanged', async () => {
|
||||
const f = fixture(); f.message(); f.current(); f.journal();
|
||||
const elsewhere = repo(); fs.mkdirSync(path.join(f.cwd, '.git', 'worktrees', 'session'), { recursive: true });
|
||||
fs.writeFileSync(path.join(f.cwd, '.git', 'worktrees', 'session', 'gitdir'), posix(path.join(elsewhere, '.git')) + '\n');
|
||||
expect(await run(f, f.cwd)).toEqual({});
|
||||
expect(await run(f, f.cwd)).toEqual(OWNED_READ_APPROVAL);
|
||||
});
|
||||
|
||||
for (const kind of ['no-link', 'worktree-file-only', 'admin-entry-only', 'other-repository',
|
||||
|
||||
@@ -5,6 +5,7 @@ import { tmpdir } from 'node:os';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { runPublicationHook } from '../autoplan/bin/phase-publication-hook.ts';
|
||||
import { OWNED_READ_APPROVAL } from '../autoplan/bin/owned-read';
|
||||
|
||||
const ROOT = path.join(import.meta.dir, '..');
|
||||
// Every guarded decision appends to the guard log; keep it out of the real state root.
|
||||
@@ -34,9 +35,11 @@ function run(bytes: string, shim = SHIM, env = process.env) {
|
||||
}
|
||||
|
||||
describe('Autoplan hook transport', () => {
|
||||
test('ordinary project and non-Read tools abstain without a parent journal', () => {
|
||||
test('ordinary project files and non-Read tools abstain without a parent journal; the close section is approved', () => {
|
||||
expect(run(JSON.stringify({ ...input, tool_name: 'Bash' })).output).toEqual({});
|
||||
expect(run(JSON.stringify({ ...input, tool_input: { file_path: path.join(ROOT, 'autoplan/sections/phase-close.md') } })).output).toEqual({});
|
||||
expect(run(JSON.stringify({ ...input, tool_input: { file_path: path.join(ROOT, 'package.json') } })).output).toEqual({});
|
||||
expect(run(JSON.stringify({ ...input, tool_input: { file_path: path.join(ROOT, 'autoplan/sections/phase-close.md') } })).output)
|
||||
.toEqual(OWNED_READ_APPROVAL);
|
||||
});
|
||||
test('invalid input fails closed with one nested native denial', () => {
|
||||
const { child, output } = run('{'); expect(child.status).toBe(0);
|
||||
|
||||
@@ -12,6 +12,7 @@ import { guardFixture, section, denial, codeOf, type GuardFixture } from './help
|
||||
import { AGENT_KEYS, CHECKED_CLAUDE_CODE, nativeToolInput, newerThanChecked } from '../autoplan/bin/phase-publication-hook.ts';
|
||||
import { nativePathSpelling } from '../lib/claude-public-transcript';
|
||||
import captured from './fixtures/claude-agent-payload-2.1.292.json';
|
||||
import { OWNED_READ_APPROVAL } from '../autoplan/bin/owned-read';
|
||||
|
||||
const fixtures: GuardFixture[] = [];
|
||||
afterEach(() => { for (const f of fixtures.splice(0)) f.cleanup(); });
|
||||
@@ -140,9 +141,9 @@ describe('Publication flush: a report counts only once a later journaled record
|
||||
|
||||
test('after the no-op publication message the transition is allowed on both paths', async () => {
|
||||
const f = make(); f.publish(); f.journal();
|
||||
expect(await f.hook(next(f))).toEqual({});
|
||||
expect(await f.hook(next(f))).toEqual(OWNED_READ_APPROVAL);
|
||||
f.use('next2', 'Read', { file_path: section('design-phase.md') }); f.journal();
|
||||
expect(await f.hook(next(f, 'next2'))).toEqual({});
|
||||
expect(await f.hook(next(f, 'next2'))).toEqual(OWNED_READ_APPROVAL);
|
||||
expect(f.log().map(e => e.path)).toEqual(['payload', 'journal']);
|
||||
});
|
||||
|
||||
@@ -160,7 +161,7 @@ describe('Publication flush: a report counts only once a later journaled record
|
||||
const f = make(); const m = f.nextMessage(); f.report(m);
|
||||
f.use('denied', 'Read', { file_path: section('design-phase.md') }, m);
|
||||
f.result('denied', { isError: true, content: '(code publication_unflushed, Claude Code 2.1.292)' }); f.journal();
|
||||
expect(await f.hook(next(f))).toEqual({});
|
||||
expect(await f.hook(next(f))).toEqual(OWNED_READ_APPROVAL);
|
||||
});
|
||||
|
||||
test('DX-3: an old-template close (report and next driver in one message) recovers after one denial, no restart', async () => {
|
||||
@@ -170,7 +171,7 @@ describe('Publication flush: a report counts only once a later journaled record
|
||||
expect(codeOf(first)).toBe('publication_unflushed');
|
||||
f.result('old', { isError: true, content: denial(first) });
|
||||
f.publish(); f.journal();
|
||||
expect(await f.hook(next(f, 'retry-after-publish'))).toEqual({});
|
||||
expect(await f.hook(next(f, 'retry-after-publish'))).toEqual(OWNED_READ_APPROVAL);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -184,7 +185,7 @@ describe('ENG-3: one batch rule on both paths', () => {
|
||||
if (order === 'sibling-done') f.readResult('s1', section('design-phase.md'), 1, 50);
|
||||
if (flushed === 'journal') f.use('s2', 'Read', designEntry(f, 51), m);
|
||||
f.journal();
|
||||
expect(await f.hook(f.input('s2', 'Read', designEntry(f, 51)))).toEqual({});
|
||||
expect(await f.hook(f.input('s2', 'Read', designEntry(f, 51)))).toEqual(OWNED_READ_APPROVAL);
|
||||
});
|
||||
|
||||
for (const flushed of ['journal', 'payload'] as const)
|
||||
@@ -231,7 +232,7 @@ describe('ENG-1: a background reviewer keeps the invocation armed', () => {
|
||||
f.add({ kind: 'end_turn', messageId: f.nextMessage() });
|
||||
f.add({ kind: 'typed', text: 'Thanks, something else now.' });
|
||||
f.journal();
|
||||
expect(await f.hook(f.input('next', 'Read', { file_path: section('design-phase.md') }))).toEqual({});
|
||||
expect(await f.hook(f.input('next', 'Read', { file_path: section('design-phase.md') }))).toEqual(OWNED_READ_APPROVAL);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -24,9 +24,12 @@ export interface Step {
|
||||
|
||||
/** A completed Phase `phase` (init, entry, close packet Read) with a reviewer snapshot for `phase`. */
|
||||
/** `opening: 'skill'` starts the run from a typed request and a Skill tool call instead of the /autoplan slash turn. */
|
||||
export function guardFixture(phase: Phase = 'ceo', opts: { methodologyLines?: number; version?: string; opening?: 'slash' | 'skill' } = {}) {
|
||||
/** `restoreInProject` puts the restore point and phase artifacts in the project's `.gstack/tmp/autoplan/`, where /autoplan writes them. */
|
||||
export function guardFixture(phase: Phase = 'ceo', opts: { methodologyLines?: number; version?: string; opening?: 'slash' | 'skill'; restoreInProject?: boolean } = {}) {
|
||||
const cwd = fs.realpathSync(fs.mkdtempSync(path.join(tmpdir(), 'autoplan-guard-replay-')));
|
||||
const source = path.join(cwd, 'source.md'), active = path.join(cwd, 'active.md'), restore = path.join(cwd, 'restore.md');
|
||||
const stateRoot = path.join(cwd, 'state'), restoreDir = opts.restoreInProject ? path.join(cwd, '.gstack', 'tmp', 'autoplan') : cwd;
|
||||
fs.mkdirSync(restoreDir, { recursive: true });
|
||||
const source = path.join(cwd, 'source.md'), active = path.join(cwd, 'active.md'), restore = path.join(restoreDir, 'restore.md');
|
||||
fs.writeFileSync(source, '# Current plan\nKeep documented behavior.\n');
|
||||
const init = initializePlan(source, active, restore);
|
||||
const skill = path.join(cwd, 'SKILL.md');
|
||||
@@ -38,7 +41,6 @@ export function guardFixture(phase: Phase = 'ceo', opts: { methodologyLines?: nu
|
||||
const packet = preparePhaseClose(phase, active, snapshot.snapshotPath, restore, method);
|
||||
const sessionId = randomUUID(), steps: Step[] = [];
|
||||
const transcript = path.join(cwd, 'config', 'projects', 'fixture', `${sessionId}.jsonl`);
|
||||
const stateRoot = path.join(cwd, 'state');
|
||||
let message = 0;
|
||||
const nextMessage = () => `msg_fixture${++message}`;
|
||||
const add = (step: Step) => { steps.push(step); return step; };
|
||||
|
||||
@@ -5,7 +5,9 @@
|
||||
* carries /autoplan's own PreToolUse hook block and allowed tools. Its body is
|
||||
* a minimal scripted phase boundary: init, Phase 1 entry, a prepared close
|
||||
* packet, the report published with the `true autoplan-published` no-op, then the
|
||||
* Phase 2 entry in a later message. Outcomes come from the guard decision log.
|
||||
* Phase 2 entry in a later message and the Phase 2 reviewer. The restore point
|
||||
* and phase artifacts live in the project's `.gstack/tmp/autoplan/`, as /autoplan
|
||||
* Step 1 places them. Outcomes come from the guard decision log and the journals.
|
||||
*/
|
||||
import * as fs from 'node:fs';
|
||||
import * as path from 'node:path';
|
||||
@@ -30,32 +32,40 @@ export interface GuardSession {
|
||||
readLog(): Array<Record<string, any>>;
|
||||
/** Content-bounded journal summary for a failure message: tool names, inputs' first keys, result heads. */
|
||||
journalSummary(): string[];
|
||||
/** Parent tool calls from the first background completion notice on, the notice count, and reviewers' successful Read paths. */
|
||||
noticeEvidence(): { notices: number; afterNotice: string[]; reviewerReads: string[] };
|
||||
cleanup(): void;
|
||||
}
|
||||
|
||||
export function prepareGuardSession(apiKey: string | undefined): GuardSession {
|
||||
const base = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'ap-guard-pty-')));
|
||||
const home = path.join(base, 'home'), config = path.join(home, '.claude'), project = path.join(base, 'project');
|
||||
const stateRoot = path.join(base, 'state'), artifacts = path.join(base, 'artifacts');
|
||||
const stateRoot = path.join(base, 'state'), artifacts = path.join(project, '.gstack', 'tmp', 'autoplan');
|
||||
for (const dir of [config, project, stateRoot, artifacts, path.join(config, 'skills')]) fs.mkdirSync(dir, { recursive: true });
|
||||
fs.symlinkSync(ROOT, path.join(config, 'skills', 'gstack'), 'dir');
|
||||
fs.writeFileSync(path.join(config, '.claude.json'), JSON.stringify(buildSeedConfig({ apiKey, trustedDirs: [project] })));
|
||||
|
||||
const source = path.join(project, 'PLAN.md'), active = path.join(artifacts, 'active.md'), restore = path.join(artifacts, 'restore.md');
|
||||
const source = path.join(project, 'PLAN.md'), active = path.join(project, 'ACTIVE.md'), restore = path.join(artifacts, 'restore.md');
|
||||
fs.writeFileSync(source, '# Plan: greet\nAdd a greet command that prints "hello".\n');
|
||||
// Stands in for the CEO review the scripted boundary skips: methodology,
|
||||
// checkpoint, accepted block and close packet, made after the model's own init.
|
||||
const review = path.join(artifacts, 'review-ceo.ts'), reviewSkill = path.join(artifacts, 'ceo-skill', 'SKILL.md');
|
||||
fs.mkdirSync(path.dirname(reviewSkill));
|
||||
fs.writeFileSync(reviewSkill, '---\nname: plan-ceo-review\n---\n## Review Sections\nApply every current review criterion.\n');
|
||||
// checkpoint, accepted block and close packet, made after the model's own init,
|
||||
// then the Phase 2 reviewer input, so no helper Bash runs after the first notice.
|
||||
const review = path.join(base, 'review.ts'), skills = path.join(base, 'review-skills');
|
||||
for (const name of ['plan-ceo-review', 'plan-design-review']) {
|
||||
fs.mkdirSync(path.join(skills, name), { recursive: true });
|
||||
fs.writeFileSync(path.join(skills, name, 'SKILL.md'), `---\nname: ${name}\n---\n## Review Sections\nApply every current review criterion.\n`);
|
||||
}
|
||||
fs.writeFileSync(review, `import { appendFileSync, writeFileSync } from 'node:fs';
|
||||
import { prepareMethodology, createSnapshot, preparePhaseClose } from ${JSON.stringify(path.join(ROOT, 'bin', 'gstack-autoplan-snapshot.ts'))};
|
||||
const [active, restore, skill] = ${JSON.stringify([active, restore, reviewSkill])};
|
||||
const method = prepareMethodology('ceo', skill, restore).methodologyPath;
|
||||
const [active, restore, skills, artifacts] = ${JSON.stringify([active, restore, skills, artifacts])};
|
||||
const method = prepareMethodology('ceo', skills + '/plan-ceo-review/SKILL.md', restore).methodologyPath;
|
||||
const snapshot = createSnapshot('ceo', active, restore, method), checkpoint = snapshot.snapshotPath;
|
||||
writeFileSync(${JSON.stringify(path.join(artifacts, 'dispatch.txt'))}, snapshot.nativeDispatchPrompt);
|
||||
writeFileSync(artifacts + '/dispatch-ceo.txt', snapshot.nativeDispatchPrompt);
|
||||
appendFileSync(active, '<!-- autoplan-accepted:ceo -->\\nNone: retain the current behavior.\\n<!-- /autoplan-accepted:ceo -->\\n');
|
||||
console.log(preparePhaseClose('ceo', active, checkpoint, restore, method).closePacketPath);
|
||||
const close = preparePhaseClose('ceo', active, checkpoint, restore, method).closePacketPath;
|
||||
const design = prepareMethodology('design', skills + '/plan-design-review/SKILL.md', restore).methodologyPath;
|
||||
writeFileSync(artifacts + '/dispatch-design.txt', createSnapshot('design', active, restore, design).nativeDispatchPrompt);
|
||||
console.log(close);
|
||||
`);
|
||||
|
||||
const tool = path.join(ROOT, 'bin', 'gstack-autoplan-snapshot.ts');
|
||||
@@ -65,15 +75,19 @@ console.log(preparePhaseClose('ceo', active, checkpoint, restore, method).closeP
|
||||
`1. Run this Bash command alone: bun "${tool}" init "${source}" "${active}" "${restore}"`,
|
||||
`2. Read the file ${path.join(sections, 'ceo-phase.md')} with offset 1 and limit 20.`,
|
||||
`3. Run this Bash command alone: bun "${review}"`,
|
||||
`4. Run this Bash command alone: cat "${path.join(artifacts, 'dispatch.txt')}"`,
|
||||
`4. Run this Bash command alone: cat "${path.join(artifacts, 'dispatch-ceo.txt')}"`,
|
||||
'5. Call the Agent tool once with these inputs: prompt = the exact, complete output of step 4 (every line, unchanged), ' +
|
||||
'description "CEO review", subagent_type "general-purpose", and run_in_background false. Include run_in_background even ' +
|
||||
'if the tool schema lacks it. If the agent runs in the background, wait for its completion notification.',
|
||||
'if the tool schema lacks it. If the agent runs in the background, end your turn and wait for its completion notification.',
|
||||
'6. Read the file whose path step 3 printed, completely (no offset or limit).',
|
||||
'7. In one message, write exactly this line as your own text: **Phase 1 complete.** and make exactly one tool call in that ' +
|
||||
'same message: the Bash command `true autoplan-published ceo`.',
|
||||
`8. In a later message, Read the file ${path.join(sections, 'design-phase.md')} with offset 1 and limit 20.`,
|
||||
'9. Reply with the single word DONE. If any tool call is denied, quote the denial text and stop.',
|
||||
`9. Run this Bash command alone: cat "${path.join(artifacts, 'dispatch-design.txt')}"`,
|
||||
'10. Call the Agent tool once with these inputs: prompt = the exact, complete output of step 9 (every line, unchanged), ' +
|
||||
'description "Design review", subagent_type "general-purpose". If the agent runs in the background, end your turn and wait ' +
|
||||
'for its completion notification.',
|
||||
'11. Reply with the single word DONE. If any tool call is denied, quote the denial text and stop.',
|
||||
].join('\n');
|
||||
const skillDir = path.join(project, '.claude', 'skills', GUARD_SKILL);
|
||||
fs.mkdirSync(skillDir, { recursive: true });
|
||||
@@ -96,6 +110,22 @@ console.log(preparePhaseClose('ceo', active, checkpoint, restore, method).closeP
|
||||
: b.type === 'text' ? `text ${String(b.text).slice(0, 80)}` : b.type);
|
||||
})));
|
||||
},
|
||||
noticeEvidence: () => {
|
||||
const projects = path.join(config, 'projects'), sub = `${path.sep}subagents${path.sep}`;
|
||||
const files = fs.existsSync(projects) ? fs.readdirSync(projects, { recursive: true }).map(String)
|
||||
.filter(f => f.endsWith('.jsonl')).map(f => path.join(projects, f)) : [];
|
||||
const rows = (file: string): any[] => fs.readFileSync(file, 'utf8').split('\n').filter(Boolean).map(line => JSON.parse(line));
|
||||
const blocks = (rs: any[], type: string): any[] => rs.flatMap(r => Array.isArray(r.message?.content) ? r.message.content.filter((b: any) => b.type === type) : []);
|
||||
const parent = files.filter(f => !f.includes(sub)).flatMap(rows);
|
||||
const notice = parent.findIndex(r => r.origin?.kind === 'task-notification');
|
||||
const afterNotice = notice < 0 ? [] : blocks(parent.slice(notice), 'tool_use')
|
||||
.map(b => `${b.name} ${b.input?.file_path ?? b.input?.command ?? b.input?.description ?? ''}`);
|
||||
const reviewerReads = files.filter(f => f.includes(sub)).flatMap(f => {
|
||||
const rs = rows(f), ok = new Set(blocks(rs, 'tool_result').filter(b => !b.is_error).map(b => b.tool_use_id));
|
||||
return blocks(rs, 'tool_use').filter(b => b.name === 'Read' && ok.has(b.id)).map(b => String(b.input?.file_path));
|
||||
});
|
||||
return { notices: parent.filter(r => r.origin?.kind === 'task-notification').length, afterNotice, reviewerReads };
|
||||
},
|
||||
readLog: () => fs.existsSync(log) ? fs.readFileSync(log, 'utf8').trim().split('\n').filter(Boolean).map(line => JSON.parse(line)) : [],
|
||||
cleanup: () => fs.rmSync(base, { recursive: true, force: true }),
|
||||
};
|
||||
|
||||
@@ -577,7 +577,7 @@ do not launch the downstream skill or open a browser.`,
|
||||
maxSkeletonBytes: 70_000, // Phase-specific outside coverage, native fallback, and harness guard.
|
||||
minUnionBytes: 85_000, // measured union 86,926
|
||||
mustContain: ['6 Decision Principles', 'TASTE DECISION', 'USER CHALLENGE', 'consensus', 'Restore Point'],
|
||||
maxSizeRatio: 1.1295, // Four validated outside invocations replace raw CLI calls; phases keep independent coverage. + Oct 7 wave B3: the Codex probe runs as a command (select-model capture lines, check-sandbox/probe-model/run-with-timeout subcommands) instead of being sourced; measured 114,297 / 101,979 = 1.1208 (2026-10-07). + Oct 7 wave CEO-28/DX-11: review prompts ask for a severity per finding and design proposals use the proposal gate; measured 114,533 / 101,979 = 1.1231 (2026-10-07). + Oct 7 wave guard (CEO-20): conditional `run_in_background` request plus the background-run recovery at each foreground dispatch site, and phase-close publishing each report with the `true autoplan-published <phase>` no-op before the next phase entry in a later message (CEO-1); measured 114,320 / 101,979 = 1.1210 (2026-10-07). Merged with the guard area: measured 115,149 / 101,979 = 1.1291 (2026-10-07).
|
||||
maxSizeRatio: 1.1305, // Four validated outside invocations replace raw CLI calls; phases keep independent coverage. + Oct 7 wave B3: the Codex probe runs as a command (select-model capture lines, check-sandbox/probe-model/run-with-timeout subcommands) instead of being sourced; measured 114,297 / 101,979 = 1.1208 (2026-10-07). + Oct 7 wave CEO-28/DX-11: review prompts ask for a severity per finding and design proposals use the proposal gate; measured 114,533 / 101,979 = 1.1231 (2026-10-07). + Oct 7 wave guard (CEO-20): conditional `run_in_background` request plus the background-run recovery at each foreground dispatch site, and phase-close publishing each report with the `true autoplan-published <phase>` no-op before the next phase entry in a later message (CEO-1); measured 114,320 / 101,979 = 1.1210 (2026-10-07). Merged with the guard area: measured 115,149 / 101,979 = 1.1291 (2026-10-07). + Oct 8 wave (permission cards after a background reviewer): Step 1 puts RESTORE_PATH, and so every phase artifact, in the project's git-excluded `.gstack/tmp/autoplan/`, which Claude Code reads without a card after the skill turn ends; measured 115,270 / 101,979 = 1.1303 (2026-10-08).
|
||||
},
|
||||
spec: {
|
||||
skill: 'spec',
|
||||
|
||||
@@ -86,11 +86,11 @@ export const E2E_TOUCHFILES: Record<string, string[]> = {
|
||||
// Real pinned-claude journals (SessionStart hook, /compact, --fork-session) through the /autoplan guard's reader.
|
||||
'autoplan-journal-drift': ['lib/claude-public-transcript.ts', 'lib/claude-journal-records.ts', 'lib/claude-owned-journal.ts', 'lib/claude-bin.ts', '.github/docker/Dockerfile.ci', 'test/skill-e2e-autoplan-journal-drift.test.ts'],
|
||||
// Live PTY phase boundary on the pinned Claude Code through /autoplan's own hook block (ENG-18).
|
||||
'autoplan-guard-pty': ['autoplan/bin/phase-publication-hook.ts', 'autoplan/bin/phase-publication-hook', 'autoplan/bin/guard-reasons.ts', 'autoplan/bin/guard-log.ts', 'autoplan/SKILL.md', 'autoplan/SKILL.md.tmpl', 'scripts/resolvers/composition.ts', 'lib/claude-public-transcript.ts', 'lib/claude-journal-records.ts', 'lib/claude-owned-journal.ts', 'autoplan/bin/guard-journal.ts', 'lib/autoplan-phase-publication.ts', 'lib/state-root.ts', 'bin/gstack-autoplan-snapshot.ts', '.github/docker/Dockerfile.ci', 'test/helpers/autoplan-guard-pty.ts', 'test/helpers/claude-pty-runner.ts', 'test/helpers/pty/**', 'test/helpers/hermetic-env.ts', 'test/helpers/auto-decision-state.ts', 'test/helpers/autoplan-artifact-digest.ts', 'test/helpers/autoplan-artifact-permission.ts', 'test/helpers/autoplan-artifact-recorder.ts', 'test/helpers/dx-selected-navigation.ts', 'test/helpers/eng-cache-writer-decision.ts', 'test/helpers/hermetic-skill-runtime.ts', 'test/helpers/native-auto-decide.ts', 'test/helpers/owned-claude-transcript.ts', 'test/helpers/plan-count-artifacts.ts', 'test/helpers/plan-count-file-permission.ts', 'test/helpers/plan-count-fixture.ts', 'test/helpers/plan-count-pending-exit.ts', 'test/helpers/plan-count-pending-question.ts', 'test/helpers/plan-count-transcript.ts', 'test/helpers/plan-floor-review.ts', 'test/helpers/plan-floor-target.ts', 'test/helpers/plan-scope-selection.ts', 'test/helpers/plan-seed-submission.ts', 'test/helpers/plan-skill-question-events.ts', 'test/helpers/plan-skill-question-hook-scope.ts', 'test/helpers/plan-skill-questions.ts', 'test/helpers/pty-screen.ts', 'test/helpers/pty-trust-dialog.ts', 'test/helpers/skill-census.ts', 'test/skill-e2e-autoplan-guard-pty.test.ts'],
|
||||
'autoplan-guard-pty': ['autoplan/bin/phase-publication-hook.ts', 'autoplan/bin/owned-read.ts', 'autoplan/bin/phase-publication-hook', 'autoplan/bin/guard-reasons.ts', 'autoplan/bin/guard-log.ts', 'autoplan/SKILL.md', 'autoplan/SKILL.md.tmpl', 'scripts/resolvers/composition.ts', 'lib/claude-public-transcript.ts', 'lib/claude-journal-records.ts', 'lib/claude-owned-journal.ts', 'autoplan/bin/guard-journal.ts', 'lib/autoplan-phase-publication.ts', 'lib/state-root.ts', 'bin/gstack-autoplan-snapshot.ts', '.github/docker/Dockerfile.ci', 'test/helpers/autoplan-guard-pty.ts', 'test/helpers/claude-pty-runner.ts', 'test/helpers/pty/**', 'test/helpers/hermetic-env.ts', 'test/helpers/auto-decision-state.ts', 'test/helpers/autoplan-artifact-digest.ts', 'test/helpers/autoplan-artifact-permission.ts', 'test/helpers/autoplan-artifact-recorder.ts', 'test/helpers/dx-selected-navigation.ts', 'test/helpers/eng-cache-writer-decision.ts', 'test/helpers/hermetic-skill-runtime.ts', 'test/helpers/native-auto-decide.ts', 'test/helpers/owned-claude-transcript.ts', 'test/helpers/plan-count-artifacts.ts', 'test/helpers/plan-count-file-permission.ts', 'test/helpers/plan-count-fixture.ts', 'test/helpers/plan-count-pending-exit.ts', 'test/helpers/plan-count-pending-question.ts', 'test/helpers/plan-count-transcript.ts', 'test/helpers/plan-floor-review.ts', 'test/helpers/plan-floor-target.ts', 'test/helpers/plan-scope-selection.ts', 'test/helpers/plan-seed-submission.ts', 'test/helpers/plan-skill-question-events.ts', 'test/helpers/plan-skill-question-hook-scope.ts', 'test/helpers/plan-skill-questions.ts', 'test/helpers/pty-screen.ts', 'test/helpers/pty-trust-dialog.ts', 'test/helpers/skill-census.ts', 'test/skill-e2e-autoplan-guard-pty.test.ts'],
|
||||
// A resumed session whose journal is padded past 100 MiB before its compact boundary enters Phase 1 through the guard (CEO-15).
|
||||
'autoplan-long-session': ['autoplan/bin/phase-publication-hook.ts', 'autoplan/bin/phase-publication-hook', 'autoplan/bin/guard-reasons.ts', 'autoplan/bin/guard-log.ts', 'autoplan/bin/guard-journal.ts', 'autoplan/SKILL.md', 'lib/claude-public-transcript.ts', 'lib/claude-journal-records.ts', 'lib/claude-owned-journal.ts', 'bin/gstack-autoplan-snapshot.ts', '.github/docker/Dockerfile.ci', 'test/helpers/autoplan-guard-pty.ts', 'test/helpers/journal-padding.ts', 'test/helpers/claude-pty-runner.ts', 'test/helpers/pty/**', 'test/helpers/auto-decision-state.ts', 'test/helpers/autoplan-artifact-digest.ts', 'test/helpers/autoplan-artifact-permission.ts', 'test/helpers/autoplan-artifact-recorder.ts', 'test/helpers/dx-selected-navigation.ts', 'test/helpers/eng-cache-writer-decision.ts', 'test/helpers/hermetic-skill-runtime.ts', 'test/helpers/native-auto-decide.ts', 'test/helpers/owned-claude-transcript.ts', 'test/helpers/plan-count-artifacts.ts', 'test/helpers/plan-count-file-permission.ts', 'test/helpers/plan-count-fixture.ts', 'test/helpers/plan-count-pending-exit.ts', 'test/helpers/plan-count-pending-question.ts', 'test/helpers/plan-count-transcript.ts', 'test/helpers/plan-floor-review.ts', 'test/helpers/plan-floor-target.ts', 'test/helpers/plan-scope-selection.ts', 'test/helpers/plan-seed-submission.ts', 'test/helpers/plan-skill-question-events.ts', 'test/helpers/plan-skill-question-hook-scope.ts', 'test/helpers/plan-skill-questions.ts', 'test/helpers/pty-screen.ts', 'test/helpers/pty-trust-dialog.ts', 'test/helpers/skill-census.ts', 'test/skill-e2e-autoplan-long-session.test.ts'],
|
||||
'autoplan-long-session': ['autoplan/bin/phase-publication-hook.ts', 'autoplan/bin/owned-read.ts', 'autoplan/bin/phase-publication-hook', 'autoplan/bin/guard-reasons.ts', 'autoplan/bin/guard-log.ts', 'autoplan/bin/guard-journal.ts', 'autoplan/SKILL.md', 'lib/claude-public-transcript.ts', 'lib/claude-journal-records.ts', 'lib/claude-owned-journal.ts', 'bin/gstack-autoplan-snapshot.ts', '.github/docker/Dockerfile.ci', 'test/helpers/autoplan-guard-pty.ts', 'test/helpers/journal-padding.ts', 'test/helpers/claude-pty-runner.ts', 'test/helpers/pty/**', 'test/helpers/auto-decision-state.ts', 'test/helpers/autoplan-artifact-digest.ts', 'test/helpers/autoplan-artifact-permission.ts', 'test/helpers/autoplan-artifact-recorder.ts', 'test/helpers/dx-selected-navigation.ts', 'test/helpers/eng-cache-writer-decision.ts', 'test/helpers/hermetic-skill-runtime.ts', 'test/helpers/native-auto-decide.ts', 'test/helpers/owned-claude-transcript.ts', 'test/helpers/plan-count-artifacts.ts', 'test/helpers/plan-count-file-permission.ts', 'test/helpers/plan-count-fixture.ts', 'test/helpers/plan-count-pending-exit.ts', 'test/helpers/plan-count-pending-question.ts', 'test/helpers/plan-count-transcript.ts', 'test/helpers/plan-floor-review.ts', 'test/helpers/plan-floor-target.ts', 'test/helpers/plan-scope-selection.ts', 'test/helpers/plan-seed-submission.ts', 'test/helpers/plan-skill-question-events.ts', 'test/helpers/plan-skill-question-hook-scope.ts', 'test/helpers/plan-skill-questions.ts', 'test/helpers/pty-screen.ts', 'test/helpers/pty-trust-dialog.ts', 'test/helpers/skill-census.ts', 'test/skill-e2e-autoplan-long-session.test.ts'],
|
||||
// Latest published Claude Code (not the pin): Agent/Read hook payloads vs their journal records, with the guard's own comparison.
|
||||
'autoplan-schema-canary': ['autoplan/bin/phase-publication-hook.ts', 'lib/claude-public-transcript.ts', 'lib/claude-journal-records.ts', 'lib/claude-owned-journal.ts', 'lib/claude-bin.ts', 'test/helpers/schema-canary.ts', 'test/skill-e2e-autoplan-schema-canary.test.ts'],
|
||||
'autoplan-schema-canary': ['autoplan/bin/phase-publication-hook.ts', 'autoplan/bin/owned-read.ts', 'lib/claude-public-transcript.ts', 'lib/claude-journal-records.ts', 'lib/claude-owned-journal.ts', 'lib/claude-bin.ts', 'test/helpers/schema-canary.ts', 'test/skill-e2e-autoplan-schema-canary.test.ts'],
|
||||
|
||||
// P4 first-run scaffold (activation lift) — the detection binary end-to-end
|
||||
// through the real runner, plus the script wiring that gates + maps it
|
||||
|
||||
@@ -4,12 +4,18 @@
|
||||
* On the pinned Claude Code, in an interactive PTY session with default
|
||||
* settings, a project skill carrying /autoplan's own hook block enters Phase 1,
|
||||
* dispatches the CEO reviewer, reads a prepared close packet, publishes the Phase 1 report in a message
|
||||
* whose only tool call is `true autoplan-published ceo`, and enters Phase 2 in a
|
||||
* later message. The reviewer dispatch sends run_in_background, which the
|
||||
* whose only tool call is `true autoplan-published ceo`, enters Phase 2 in a
|
||||
* later message and dispatches the Phase 2 reviewer. The reviewer dispatch sends run_in_background, which the
|
||||
* 2.1.29x default fork-subagent schema strips. Claude Code 2.1.29x can write a tool call to the journal only
|
||||
* after PreToolUse returns, so this is where the guard's payload path and its
|
||||
* flush rule meet the real CLI. The outcome is read from the guard decision
|
||||
* log, never the screen; the no-op must run without a permission prompt.
|
||||
* log, never the screen.
|
||||
*
|
||||
* The reviewer runs in the background, so its completion notice starts a new
|
||||
* turn and Claude Code stops applying the skill's allowed tools. Every later
|
||||
* Read of /autoplan's own files (the close packet and the Phase 2 reviewer's
|
||||
* input in the project's .gstack/tmp/autoplan/, the installed Phase 2 section)
|
||||
* must still raise no permission card.
|
||||
*/
|
||||
import { expect } from 'bun:test';
|
||||
import { describeIfSelected, testIfSelected } from './helpers/e2e-helpers';
|
||||
@@ -34,29 +40,34 @@ describeIfSelected('autoplan publication guard live PTY', ['autoplan-guard-pty']
|
||||
await Bun.sleep(1_000);
|
||||
const log = s.readLog();
|
||||
if (phase1Ms === null && log.length) phase1Ms = Math.round(performance.now() - started);
|
||||
// A permission card is recorded and approved; the no-op must never raise one (DX-13).
|
||||
// A permission card is recorded and approved so the run can finish; any card fails the case.
|
||||
const screen = await session.currentScreen();
|
||||
if (/Do you want to proceed\?/.test(screen) && /❯\s*1\.\s*Yes/.test(screen)) {
|
||||
prompts.push(screen);
|
||||
await selectPtyNumberedOption(session, 1);
|
||||
await Bun.sleep(1_500);
|
||||
}
|
||||
if (log.some(e => e.decision === 'deny') || log.length >= 3) break;
|
||||
if (log.some(e => e.decision === 'deny') || (log.length >= 4 && s.noticeEvidence().notices >= 2)) break;
|
||||
if (session.exited()) break;
|
||||
}
|
||||
await Bun.sleep(3_000);
|
||||
const log = s.readLog();
|
||||
const summary = { prompts: prompts.length, phase1Ms, totalMs: Math.round(performance.now() - started),
|
||||
const log = s.readLog(), evidence = s.noticeEvidence();
|
||||
const summary = { prompts: prompts.length, phase1Ms, totalMs: Math.round(performance.now() - started), evidence,
|
||||
decisions: log.map(e => ({ decision: e.decision, code: e.code, path: e.path, version: e.claude_code_version })) };
|
||||
console.log(`[autoplan-guard-pty] ${JSON.stringify(summary)}`);
|
||||
if (log.length !== 3 || log.some(e => e.decision === 'deny'))
|
||||
if (log.length !== 4 || log.some(e => e.decision === 'deny') || prompts.length)
|
||||
console.log(`[autoplan-guard-pty] journal:\n${s.journalSummary().join('\n')}\n[autoplan-guard-pty] screen:\n${session.visibleText().slice(-2_000)}`);
|
||||
for (const prompt of prompts) console.log(`[autoplan-guard-pty] permission card approved:\n${prompt}`);
|
||||
expect(prompts.filter(p => p.replace(/\s+/g, '').includes('autoplan-published'))).toEqual([]);
|
||||
expect(log.filter(e => e.decision === 'deny')).toEqual([]);
|
||||
// Phase 1 entry, the CEO reviewer dispatch (Cause A: run_in_background sent, stripped from the payload)
|
||||
// and the Phase 2 transition: three guarded allows, each verified (not an unverified allow).
|
||||
expect(log.map(e => [e.decision, e.disposition])).toEqual([['allow', 'allow'], ['allow', 'allow'], ['allow', 'allow']]);
|
||||
// Phase 1 entry, the CEO reviewer dispatch (Cause A: run_in_background sent, stripped from the payload),
|
||||
// the Phase 2 transition and the Phase 2 reviewer dispatch: four guarded allows, each verified.
|
||||
expect(log.map(e => [e.decision, e.disposition])).toEqual(Array(4).fill(['allow', 'allow']));
|
||||
// The CEO reviewer's notice started a new turn before the close packet, the Phase 2 entry and the Phase 2 dispatch.
|
||||
expect(evidence.afterNotice.filter(c => /^Read .*close-packet\.md$/.test(c))).not.toEqual([]);
|
||||
expect(evidence.afterNotice.filter(c => /^Read .*autoplan\/sections\/design-phase\.md$/.test(c))).not.toEqual([]);
|
||||
expect(evidence.afterNotice).toContain('Agent Design review');
|
||||
expect(evidence.reviewerReads.filter(f => /\.gstack\/tmp\/autoplan\/autoplan-design-[^/]+\/native-prompt\.md$/.test(f))).not.toEqual([]);
|
||||
expect(prompts).toEqual([]);
|
||||
} finally {
|
||||
await session.close();
|
||||
s.cleanup();
|
||||
|
||||
Reference in new issue
Block a user