"use strict";
// src/test_story_state_tracker.ts
// v1.17.0 — StoryStateTracker regression.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
const fs = __importStar(require("fs"));
const os = __importStar(require("os"));
const path = __importStar(require("path"));
const StoryStateTracker_1 = require("./orchestrator/story/StoryStateTracker");
function assert(cond, msg) {
    if (!cond)
        throw new Error(`assertion failed: ${msg}`);
}
function mkStoryFile(content) {
    const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'story-state-'));
    const file = path.join(dir, '1.1.story.md');
    fs.writeFileSync(file, content, 'utf-8');
    return file;
}
function rm(p) {
    try {
        fs.rmSync(path.dirname(p), { recursive: true, force: true });
    }
    catch { /* */ }
}
const SAMPLE = `# Story 1.1 — [BUG] Fix the gateway

**Status:** InProgress

## Acceptance Criteria
- [ ] SIGTERM exits within 5s
- [ ] stale state cleanup
- [x] tests added
- [ ] documented in changelog

## Description

Short description here.

## Change Log

- 2026-05-22 dev: started

`;
function scenarioCheckAC() {
    const file = mkStoryFile(SAMPLE);
    try {
        assert((0, StoryStateTracker_1.countOpenACs)(file) === 3, `3 open initially, got ${(0, StoryStateTracker_1.countOpenACs)(file)}`);
        assert((0, StoryStateTracker_1.countTotalACs)(file) === 4, `4 total, got ${(0, StoryStateTracker_1.countTotalACs)(file)}`);
        // Check AC 0 (first open one)
        assert((0, StoryStateTracker_1.checkAC)(file, 0), 'check AC 0 ok');
        assert((0, StoryStateTracker_1.countOpenACs)(file) === 2, 'now 2 open');
        const after = fs.readFileSync(file, 'utf-8');
        assert(after.includes('- [x] SIGTERM exits within 5s'), 'AC 0 marked checked');
        assert(after.includes('- [ ] stale state cleanup'), 'AC 1 still open');
        // Idempotent — checking already-checked AC succeeds without error.
        assert((0, StoryStateTracker_1.checkAC)(file, 0), 'idempotent re-check');
        assert((0, StoryStateTracker_1.countOpenACs)(file) === 2, 'still 2 open after re-check');
        // Out of range
        assert(!(0, StoryStateTracker_1.checkAC)(file, 99), 'out-of-range returns false');
        // Other content preserved
        const final = fs.readFileSync(file, 'utf-8');
        assert(final.includes('## Change Log'), 'change log section intact');
        assert(final.includes('Short description here.'), 'description intact');
    }
    finally {
        rm(file);
    }
    console.log('✅ scenario 1: checkAC toggles by index, idempotent, preserves other content');
}
function scenarioAppendDevAgentRecord() {
    const file = mkStoryFile(SAMPLE);
    try {
        (0, StoryStateTracker_1.appendDevAgentRecord)(file, {
            iter: 1,
            persona: 'builder',
            summary: 'Patched Gateway.shutdown to close Express before bot.stop().',
            test_cmd: 'npm run test:daemon-sigterm',
            test_passed: true,
            duration_ms: 4520,
        });
        const content = fs.readFileSync(file, 'utf-8');
        assert(content.includes('## Dev Agent Record'), 'heading created');
        assert(content.includes('### Iteration 1 — builder'), 'iteration block');
        assert(content.includes('npm run test:daemon-sigterm'), 'test cmd recorded');
        assert(content.includes('✓ pass'), 'test pass marker');
        assert(content.includes('Duration: 4.5s'), 'duration formatted');
        // Append a second entry
        (0, StoryStateTracker_1.appendDevAgentRecord)(file, {
            iter: 2,
            persona: 'sentinel',
            summary: 'QA gate: code review pass.',
        });
        const after = fs.readFileSync(file, 'utf-8');
        assert(after.includes('### Iteration 2 — sentinel'), 'second entry appended');
        // Both entries present
        assert((after.match(/### Iteration /g) || []).length === 2, 'two entries present');
    }
    finally {
        rm(file);
    }
    console.log('✅ scenario 2: appendDevAgentRecord creates heading + multiple entries');
}
function scenarioAppendFileList() {
    const file = mkStoryFile(SAMPLE);
    try {
        (0, StoryStateTracker_1.appendFileList)(file, ['src/Gateway.ts', 'src/cli/StatusCommand.ts']);
        let content = fs.readFileSync(file, 'utf-8');
        assert(content.includes('## File List'), 'heading created');
        assert(content.includes('- src/Gateway.ts'), 'first path');
        assert(content.includes('- src/cli/StatusCommand.ts'), 'second path');
        // Dedup on append
        (0, StoryStateTracker_1.appendFileList)(file, ['src/Gateway.ts', 'src/test_gateway.ts']);
        content = fs.readFileSync(file, 'utf-8');
        const gatewayCount = (content.match(/- src\/Gateway\.ts/g) || []).length;
        assert(gatewayCount === 1, `dedup: Gateway.ts appears once, got ${gatewayCount}`);
        assert(content.includes('- src/test_gateway.ts'), 'new path appended');
    }
    finally {
        rm(file);
    }
    console.log('✅ scenario 3: appendFileList dedupes existing entries');
}
function scenarioTransitionStatus() {
    const file = mkStoryFile(SAMPLE);
    try {
        // dev → InReview from InProgress: allowed
        const r1 = (0, StoryStateTracker_1.transitionStatus)(file, 'InProgress', 'InReview', 'dev');
        assert(r1.ok, `dev: InProgress→InReview ok, error: ${r1.error}`);
        const content = fs.readFileSync(file, 'utf-8');
        assert(content.includes('**Status:** InReview'), 'status updated in file');
        // dev → Done from InReview: forbidden (qa/po only)
        const r2 = (0, StoryStateTracker_1.transitionStatus)(file, 'InReview', 'Done', 'dev');
        assert(!r2.ok, 'dev: InReview→Done refused');
        assert(r2.error?.includes('transition_forbidden'), `expected transition_forbidden, got ${r2.error}`);
        // qa → Done allowed
        const r3 = (0, StoryStateTracker_1.transitionStatus)(file, 'InReview', 'Done', 'qa');
        assert(r3.ok, `qa: InReview→Done ok, error: ${r3.error}`);
    }
    finally {
        rm(file);
    }
    console.log('✅ scenario 4: transitionStatus respects role gating');
}
try {
    scenarioCheckAC();
    scenarioAppendDevAgentRecord();
    scenarioAppendFileList();
    scenarioTransitionStatus();
    console.log('TEST_STORY_STATE_TRACKER_OK');
}
catch (err) {
    console.error('TEST_STORY_STATE_TRACKER_FAIL', err);
    process.exit(1);
}
