opencode-plugin-flow 4.1.6 → 4.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -86,7 +86,7 @@ When reviewing a findings report, verify findings adversarially:
86
86
  - Downgrade or reject findings that do not survive refutation.
87
87
 
88
88
  Approve only on evidence actually inspected. A review is a claim of coverage, not a courtesy stamp.
89
- `;var j=`---
89
+ `;var q=`---
90
90
  name: flow-review
91
91
  description: Review Flow work in the v4 runtime: inspect feature or final-session changes, classify findings, and return featureReview or finalReview payloads for flow_feature_complete.
92
92
  ---
@@ -105,6 +105,9 @@ recorded.
105
105
  - Identify whether this is a feature review or final review.
106
106
  - Read the approved plan fields relevant to the work: \`requirements\`, \`decisions\`, feature \`targets\`, feature \`validation\`, and dependencies.
107
107
  - Inspect the actual diff, changed files, tests, and validation output. Do not review only the completion summary.
108
+ - Load \`flow-test\` for validation-heavy, regression-sensitive, browser/UI, or
109
+ unclear coverage reviews. If it is unavailable, record a coverage gap and
110
+ treat missing validation evidence as a gap or blocker based on user impact.
108
111
  - Load \`references/review-rubric.md\` for severity, depth, and payload shape.
109
112
 
110
113
  ## Feature Review Depth
@@ -153,9 +156,13 @@ Use \`status: "failed"\` when any blocking finding remains. Advisory findings ma
153
156
  \`finalReview\` payload.
154
157
 
155
158
  Never approve to unblock completion, fix findings in the review pass, or vouch for validation you did not inspect.
156
- `;var xt=["Use Flow review mode. Call `flow_status` before loading review skills. If Flow setup reports stale/unavailable skills or the skill loader reports that `flow-review` is unavailable, continue with the bundled review instructions below as advisory review only. Do not present advisory review as Flow-gated `featureReview` or `finalReview` evidence.","","## Bundled Flow review fallback","","## Bundled flow-review/SKILL.md",j,"## Bundled flow-review/references/review-rubric.md",U].join(`
159
+ `;var pe=["## Bundled flow-review/SKILL.md",q,"## Bundled flow-review/references/review-rubric.md",U].join(`
157
160
 
158
- `),pe="Call `flow_status` first. If the result includes `setup.skills`, report the setup status and do not load Flow skills in this startup.";function L(e,a){return`${pe} Otherwise load the \`${e}\` skill and ${a}`}var Rt={"flow-reviewer":{mode:"subagent",hidden:!0,description:"Internal read-only reviewer for Flow-guided work.",prompt:xt,permission:{edit:"deny",bash:"deny",task:{"*":"deny"},"flow_*":"deny",flow_status:"allow"}},"flow-evidence-worker":{mode:"subagent",hidden:!0,description:"Internal read-only evidence worker for Flow planning and execution support.",prompt:"Use Flow evidence mode. Inspect only the assigned slice, do not edit files, do not call state-changing Flow tools, and return coverage, evidence inspected, confidence-tagged findings or facts, gaps, and manager follow-ups.",permission:{edit:"deny",bash:"deny",task:{"*":"deny"},"flow_*":"deny",flow_status:"allow"}},"flow-validation-worker":{mode:"subagent",hidden:!0,description:"Internal validation worker for Flow check selection and command evidence.",prompt:"Use Flow validation mode. Run only manager-specified commands or propose focused checks, do not edit files, do not call state-changing Flow tools, and report exact command, status, raw outcome summary, coverage, confidence, gaps, and manager follow-ups.",permission:{edit:"deny",bash:"ask",task:{"*":"deny"},"flow_*":"deny",flow_status:"allow"}},"flow-audit-worker":{mode:"subagent",hidden:!0,description:"Internal read-only audit worker for refuted or surviving finding candidates.",prompt:"Use Flow audit mode. Inspect only the assigned slice, actively refute candidate findings before reporting them, do not edit files, do not call state-changing Flow tools, and return coverage, evidence, guards checked, confidence, gaps, and manager follow-ups.",permission:{edit:"deny",bash:"ask",task:{"*":"deny"},"flow_*":"deny",flow_status:"allow"}},"flow-candidate-worker":{mode:"subagent",hidden:!0,description:"Internal candidate implementation worker for isolated Flow worktrees or exact non-overlapping path ownership.",prompt:"Use Flow candidate-implementation mode only when the manager assigned an isolated worktree or exact non-overlapping path ownership. Do not edit .flow/**, do not call state-changing Flow tools, do not complete Flow state, and return changed or proposed patch, verification run, coverage, confidence, merge risks, and manager follow-ups.",permission:{edit:"ask",bash:"ask",task:{"*":"deny"},"flow_*":"deny",flow_status:"allow"}},"flow-verifier-worker":{mode:"subagent",hidden:!0,description:"Internal verifier worker for checking Flow worker claims against cited evidence.",prompt:"Use Flow verifier mode. Verify only the assigned claims against the provided sources, commands, counts, or current docs. Do not generate new scope, do not edit files, do not call state-changing Flow tools, and return supported, partly-supported, unsupported, or source-not-found per claim with evidence, confidence, gaps, and manager follow-ups.",permission:{edit:"deny",bash:"ask",task:{"*":"deny"},"flow_*":"deny",flow_status:"allow"}}},X={"flow-auto":{description:"Drive Flow skills against the minimal runtime ledger",template:L("flow","drive the Flow loop until completion or a real blocker: $ARGUMENTS")},"flow-plan":{description:"Create or approve a Flow plan",template:L("flow-plan","plan: $ARGUMENTS")},"flow-run":{description:"Run one approved Flow feature",template:L("flow-run","execute the next approved feature. $ARGUMENTS")},"flow-review":{description:"Run a read-only Flow review",agent:"flow-reviewer",subtask:!0,template:`${pe} If setup is clear, load \`flow-review\`; if loading fails because the skill is unavailable, use the bundled review fallback as advisory review only. Review: $ARGUMENTS`},"flow-status":{description:"Inspect the active Flow session",template:"Call flow_status and report the session state and next action."}};function Ft(){return{agent:Object.fromEntries(Object.entries(Rt).map(([e,a])=>{let t=a.permission?{...a.permission,...a.permission.task?{task:{...a.permission.task}}:{}}:void 0;return[e,{...a,...t?{permission:t}:{}}]})),command:Object.fromEntries(Object.entries(X).map(([e,a])=>[e,{...a}]))}}function fe(e){let a=Ft();e.agent={...e.agent??{},...a.agent},e.command={...e.command??{},...a.command}}import{createHash as Mt}from"node:crypto";import{mkdir as Vt,readdir as Ir,readFile as Bt,rm as Pr,writeFile as q}from"node:fs/promises";import{createRequire as Jt}from"node:module";import{dirname as Gt,join as P,normalize as Kt,sep as Lt}from"node:path";var me=`# Flow worker handoff contract
161
+ `),_t=["Use Flow review mode. Call `flow_status` first. Do not call the native skill tool for `flow-review`; the canonical Flow review instructions and rubric are already embedded below. If Flow setup reports stale/unavailable skills, continue as advisory review only and do not present advisory review as Flow-gated `featureReview` or `finalReview` evidence.","","## Bundled Flow review instructions","",pe].join(`
162
+
163
+ `),fe="Call `flow_status` first. If the result includes `setup.skills`, report the setup status and do not load Flow skills in this startup.";function Q(e,a){return`${fe} Otherwise load the \`${e}\` skill and ${a}`}var St=[fe,"Otherwise run the bundled Flow review instructions below. Do not call the native skill tool for `flow-review`; the full review skill and rubric are embedded in this command. Review: $ARGUMENTS","",pe].join(`
164
+
165
+ `),It={"flow-reviewer":{mode:"subagent",hidden:!0,description:"Internal read-only reviewer for Flow-guided work.",prompt:_t,permission:{edit:"deny",bash:"deny",task:{"*":"deny"},"flow_*":"deny",flow_status:"allow"}},"flow-evidence-worker":{mode:"subagent",hidden:!0,description:"Internal read-only evidence worker for Flow planning and execution support.",prompt:"Use Flow evidence mode. Inspect only the assigned slice, do not edit files, do not call state-changing Flow tools, and return coverage, evidence inspected, confidence-tagged findings or facts, gaps, and manager follow-ups.",permission:{edit:"deny",bash:"deny",task:{"*":"deny"},"flow_*":"deny",flow_status:"allow"}},"flow-validation-worker":{mode:"subagent",hidden:!0,description:"Internal validation worker for Flow check selection and command evidence.",prompt:"Use Flow validation mode. Run only manager-specified commands or propose focused checks, do not edit files, do not call state-changing Flow tools, and report exact command, status, raw outcome summary, coverage, confidence, gaps, and manager follow-ups.",permission:{edit:"deny",bash:"ask",task:{"*":"deny"},"flow_*":"deny",flow_status:"allow"}},"flow-audit-worker":{mode:"subagent",hidden:!0,description:"Internal read-only audit worker for refuted or surviving finding candidates.",prompt:"Use Flow audit mode. Inspect only the assigned slice, actively refute candidate findings before reporting them, do not edit files, do not call state-changing Flow tools, and return coverage, evidence, guards checked, confidence, gaps, and manager follow-ups.",permission:{edit:"deny",bash:"ask",task:{"*":"deny"},"flow_*":"deny",flow_status:"allow"}},"flow-candidate-worker":{mode:"subagent",hidden:!0,description:"Internal candidate implementation worker for isolated Flow worktrees or exact non-overlapping path ownership.",prompt:"Use Flow candidate-implementation mode only when the manager assigned an isolated worktree or exact non-overlapping path ownership. Do not edit .flow/**, do not call state-changing Flow tools, do not complete Flow state, and return changed or proposed patch, verification run, coverage, confidence, merge risks, and manager follow-ups.",permission:{edit:"ask",bash:"ask",task:{"*":"deny"},"flow_*":"deny",flow_status:"allow"}},"flow-verifier-worker":{mode:"subagent",hidden:!0,description:"Internal verifier worker for checking Flow worker claims against cited evidence.",prompt:"Use Flow verifier mode. Verify only the assigned claims against the provided sources, commands, counts, or current docs. Do not generate new scope, do not edit files, do not call state-changing Flow tools, and return supported, partly-supported, unsupported, or source-not-found per claim with evidence, confidence, gaps, and manager follow-ups.",permission:{edit:"deny",bash:"ask",task:{"*":"deny"},"flow_*":"deny",flow_status:"allow"}}},j={"flow-auto":{description:"Drive Flow skills against the minimal runtime ledger",template:Q("flow","drive the Flow loop until completion or a real blocker: $ARGUMENTS")},"flow-plan":{description:"Create or approve a Flow plan",template:Q("flow-plan","plan: $ARGUMENTS")},"flow-run":{description:"Run one approved Flow feature",template:Q("flow-run","execute the next approved feature. $ARGUMENTS")},"flow-review":{description:"Run a read-only Flow review",agent:"flow-reviewer",subtask:!0,template:St},"flow-status":{description:"Inspect the active Flow session",template:"Call flow_status and report the session state and next action."}};function Pt(){return{agent:Object.fromEntries(Object.entries(It).map(([e,a])=>{let t=a.permission?{...a.permission,...a.permission.task?{task:{...a.permission.task}}:{}}:void 0;return[e,{...a,...t?{permission:t}:{}}]})),command:Object.fromEntries(Object.entries(j).map(([e,a])=>[e,{...a}]))}}function me(e){let a=Pt();e.agent={...e.agent??{},...a.agent},e.command={...e.command??{},...a.command}}import{createHash as Kt}from"node:crypto";import{mkdir as Qt,readdir as Wr,readFile as Ht,rm as $r,writeFile as E}from"node:fs/promises";import{createRequire as Xt}from"node:module";import{dirname as Yt,join as P,normalize as Zt,sep as ea}from"node:path";var he=`# Flow worker handoff contract
159
166
 
160
167
  Flow managers merge only the worker's final response. Treat that response as the
161
168
  worker report of record: it must include the assigned scope, what was actually
@@ -274,7 +281,7 @@ live-verified | test-verified | type-check-only | not-verified
274
281
 
275
282
  The manager must inspect and validate any candidate patch before recording Flow
276
283
  completion.
277
- `;var he=`# Parallel orchestration
284
+ `;var ge=`# Parallel orchestration
278
285
 
279
286
  Use fan-out when Flow work is broad enough that independent workers can gather
280
287
  evidence faster than one linear pass. The manager still owns the Flow session:
@@ -403,7 +410,7 @@ Start a follow-up wave when first-wave handoffs reveal:
403
410
 
404
411
  Do not recurse by default. If a worker says it needs another worker, the manager
405
412
  decides whether that is a second wave and writes the next bounded prompt.
406
- `;var ge='# Recovery playbook\n\nUse this when a Flow tool returns `status: "error"`, a blocker, or a `nextAction` that conflicts with memory.\n\n## First response\n\n1. Re-anchor with `flow_status`.\n2. Read the returned `summary`, `recovery`, `lastError`, and active feature.\n3. Fix the cause, then retry the smallest valid Flow action.\n\n## Common cases\n\n- `missing_session`: start with `flow_plan_save` using the user\'s goal.\n- `missing_goal`: ask for a concrete goal before planning.\n- `Approved plans cannot be changed`: use `flow_feature_reset` when only affected features need another pass; otherwise close and start a new goal.\n- `No feature is currently running`: call `flow_run_start` before completing.\n- `already in progress`: finish, reset, or block the active feature before starting another.\n- `Completion requires recorded validation evidence`: run real validation and include at least one passing `validationRun`.\n- `Completion requires all recorded validation to pass`: fix failures and rerun. Do not relabel failed checks as passed.\n- `Non-final feature completion requires targeted validation`: use `validationScope: "targeted"` for ordinary features.\n- `Final feature completion requires broad validation`: run the project-level gate and use `validationScope: "broad"`.\n- `Completion requires a passing featureReview`: run or request a real review and include a passing `featureReview` only when there are no blocking findings.\n- `Final feature completion requires a finalReview`: perform final review and include `finalReview`.\n- `Final review depth must match the plan policy`: use `reviewDepth` equal to the approved plan\'s `finalReviewPolicy`; valid final-review values are `broad` and `detailed`.\n- `Cannot close ... unfinished features`: complete, reset, defer, or abandon honestly. Do not mark completed while work remains.\n\n## Reset guidance\n\nUse `flow_feature_reset` when the active or completed work was built on the wrong assumption, validation revealed a design issue, dependencies need to be rerun, or dependent features must be invalidated. Resetting a feature also resets its dependents.\n\n## Closure guidance\n\nUse `flow_session_close`:\n\n- `completed`: only after all planned features are complete.\n- `deferred`: the user intentionally postpones unfinished work.\n- `abandoned`: the session should be archived without claiming delivery.\n\nAfter closure, the active `.flow/session.json` is removed and the archived JSON is stored under `.flow/history/`.\n';var ve=`# Verification gates
413
+ `;var ve='# Recovery playbook\n\nUse this when a Flow tool returns `status: "error"`, a blocker, or a `nextAction` that conflicts with memory.\n\n## First response\n\n1. Re-anchor with `flow_status`.\n2. Read the returned `summary`, `recovery`, `lastError`, and active feature.\n3. Fix the cause, then retry the smallest valid Flow action.\n\n## Common cases\n\n- `missing_session`: start with `flow_plan_save` using the user\'s goal.\n- `missing_goal`: ask for a concrete goal before planning.\n- `Approved plans cannot be changed`: use `flow_feature_reset` when only affected features need another pass; otherwise close and start a new goal.\n- `No feature is currently running`: call `flow_run_start` before completing.\n- `already in progress`: finish, reset, or block the active feature before starting another.\n- `Completion requires recorded validation evidence`: run real validation and include at least one passing `validationRun`.\n- `Completion requires all recorded validation to pass`: fix failures and rerun. Do not relabel failed checks as passed.\n- `Non-final feature completion requires targeted validation`: use `validationScope: "targeted"` for ordinary features.\n- `Final feature completion requires broad validation`: run the project-level gate and use `validationScope: "broad"`.\n- `Completion requires a passing featureReview`: run or request a real review and include a passing `featureReview` only when there are no blocking findings.\n- `Final feature completion requires a finalReview`: perform final review and include `finalReview`.\n- `Final review depth must match the plan policy`: use `reviewDepth` equal to the approved plan\'s `finalReviewPolicy`; valid final-review values are `broad` and `detailed`.\n- `Cannot close ... unfinished features`: complete, reset, defer, or abandon honestly. Do not mark completed while work remains.\n\n## Reset guidance\n\nUse `flow_feature_reset` when the active or completed work was built on the wrong assumption, validation revealed a design issue, dependencies need to be rerun, or dependent features must be invalidated. Resetting a feature also resets its dependents.\n\n## Closure guidance\n\nUse `flow_session_close`:\n\n- `completed`: only after all planned features are complete.\n- `deferred`: the user intentionally postpones unfinished work.\n- `abandoned`: the session should be archived without claiming delivery.\n\nAfter closure, the active `.flow/session.json` is removed and the archived JSON is stored under `.flow/history/`.\n';var we=`# Verification gates
407
414
 
408
415
  Verification is how Flow keeps parallel work from turning into parallel
409
416
  guesswork. Worker handoffs are candidate evidence; the manager decides what can
@@ -493,9 +500,9 @@ Before presenting or recording the result:
493
500
 
494
501
  \`Status: success\` only says the worker believes its slice is done. The manager
495
502
  still checks coverage and evidence before trusting the result.
496
- `;var we=`---
503
+ `;var ye=`---
497
504
  name: flow
498
- description: Main Flow loop for skills-first OpenCode work. Use when a user asks for Flow-guided planning, autonomous execution, resumable implementation, session status, or end-to-end delivery with validation and review gates.
505
+ description: Run the end-to-end Flow loop for skills-first OpenCode work. Use when a user asks for Flow-guided planning through implementation, resumable autonomous delivery, session status, or completion with validation and review gates.
499
506
  ---
500
507
 
501
508
  # Flow
@@ -509,13 +516,17 @@ Use Flow as a minimal state ledger, not as a framework. Skills provide judgment;
509
516
  load Flow skills in this startup. A just-synced skill can be on disk while
510
517
  unavailable to the running OpenCode process.
511
518
  2. If there is no active session and the user gave a goal, load \`flow-plan\`, save a plan with \`flow_plan_save\`, then approve it with \`flow_plan_approve\` only after explicit user approval or prior authorization for autonomous implementation. If there is no goal, ask for one.
512
- 3. Load \`flow-run\`, call \`flow_run_start\`, implement exactly one feature, validate it, and prepare a \`flow_feature_complete\` payload.
519
+ 3. Load \`flow-run\`, call \`flow_run_start\`, implement exactly one feature, validate it, and prepare a \`flow_feature_complete\` payload. For validation-heavy, regression-sensitive, or browser/UI work, use \`flow-test\` to choose and summarize evidence before completion.
513
520
  4. Load \`flow-review\` for the required feature review. The reviewer reports a \`featureReview\` payload; the manager records it inside \`flow_feature_complete\`.
514
521
  5. On the final feature, run broad validation and include \`finalReview\` in the same \`flow_feature_complete\` call. Its \`reviewDepth\` must match the plan's \`finalReviewPolicy\`.
515
522
  6. After all features are complete, archive the session with \`flow_session_close\` using \`kind: "completed"\`.
516
523
 
517
524
  Use \`references/parallel-orchestration.md\` for broad read-only discovery, audit, validation, review, verification, or candidate implementation waves. Hidden Flow workers are injected by plugin config; invoke the named worker when it is available. Its \`references/handoff-format.md\` and \`references/verification-gates.md\` companions define the worker contracts. The manager owns every \`flow_*\` state change.
518
525
 
526
+ Do not commit, push, amend, rebase, publish, or mutate releases during the
527
+ autonomous Flow loop. Load \`flow-commit\` only when the user explicitly asks for
528
+ commit preparation or commit creation.
529
+
519
530
  ## Skill Availability
520
531
 
521
532
  If \`flow_status\` returns \`setup.skills\`, report that setup status and stop
@@ -523,9 +534,10 @@ loading Flow skills in the current OpenCode startup. Missing, incomplete, or
523
534
  outdated managed skills require a sync/restart cycle before their instructions
524
535
  can be trusted by the running process.
525
536
 
526
- If optional helper skills such as \`flow-deslop\` or \`flow-ui-quality\` are
527
- unavailable, continue only with explicit coverage gaps. Do not copy their
528
- rubrics into another skill and do not claim their quality checks were completed.
537
+ If optional helper skills such as \`flow-test\`, \`flow-deslop\`, or
538
+ \`flow-ui-quality\` are unavailable, continue only with explicit coverage gaps. Do
539
+ not copy their rubrics into another skill and do not claim their quality checks
540
+ were completed.
529
541
 
530
542
  ## Runtime Surface
531
543
 
@@ -560,7 +572,121 @@ Planning and running require loaded Flow tools; do not simulate plan approval or
560
572
  - Unknown runtime error: read \`summary\` and \`recovery\`; see \`references/recovery-playbook.md\` for common cases.
561
573
 
562
574
  Never fabricate validation output, backfill review approval you did not perform, or close as \`deferred\`/\`abandoned\` merely to avoid an unfinished-work blocker.
563
- `;var ye=`# Safe refactor workflow
575
+ `;var be=`---
576
+ name: flow-commit
577
+ description: Prepare safe Git commits and commit messages. Use only when the user asks to inspect, stage, validate, write a commit message, or create a commit; preserves unrelated work and never pushes, amends, rebases, or publishes without explicit authorization.
578
+ ---
579
+
580
+ # Flow Commit
581
+
582
+ Use this skill only when the user asks to prepare or create a commit, write a
583
+ commit message, stage intended work, or validate staged changes before
584
+ committing. It is not part of the autonomous Flow loop and must not be loaded
585
+ automatically by \`flow\`, \`flow-run\`, or \`flow_feature_complete\`.
586
+
587
+ When a Flow session exists, a commit never substitutes for Flow completion. The
588
+ manager still records validation and review evidence through
589
+ \`flow_feature_complete\` before claiming a Flow feature is done. Default to commit
590
+ preparation only after \`flow_feature_complete\` has recorded the relevant
591
+ completion evidence. If the user explicitly asks for a WIP commit, preserve
592
+ failing or incomplete validation context in the message.
593
+
594
+ ## Boundaries
595
+
596
+ - Preserve unrelated user work.
597
+ - Stage explicit paths or hunks only. Do not default to \`git add .\` or
598
+ \`git add -A\`.
599
+ - Do not commit \`.flow/**\` state unless the maintainer explicitly asks to
600
+ archive those exact files.
601
+ - Do not push, amend, rebase, squash, reset, force-push, tag, release, publish,
602
+ or mutate remote state unless the user explicitly authorizes that exact
603
+ operation.
604
+ - Stop before committing secrets, local config, credentials, private keys,
605
+ generated release artifacts, or suspicious environment files.
606
+ - Stop when validation fails unless the user explicitly wants an unfinished WIP
607
+ commit and the commit message says so.
608
+
609
+ ## Inspect
610
+
611
+ Start with the worktree and intent:
612
+
613
+ 1. Run \`git status --short\`.
614
+ 2. Inspect unstaged and staged changes separately with \`git diff\` and
615
+ \`git diff --cached\`.
616
+ 3. Inspect untracked files before deciding whether they belong.
617
+ 4. Group changes by intent, feature, and risk. Prefer one coherent commit over
618
+ one large mixed commit.
619
+ 5. Identify exclusions: unrelated files, local notes, \`.flow/**\`, generated
620
+ artifacts, logs, caches, credentials, and temporary outputs.
621
+
622
+ If the commit boundary is unclear, propose the boundary and ask before staging.
623
+
624
+ ## Stage
625
+
626
+ Stage only the intended boundary:
627
+
628
+ - Use explicit file paths for whole-file staging.
629
+ - Use patch staging for mixed-intent files.
630
+ - Re-run \`git status --short\` and \`git diff --cached --stat\` after staging.
631
+ - Review the full staged diff before validation and commit.
632
+
633
+ Never undo or rewrite user changes to make staging easier. If a file contains
634
+ mixed user and agent work, either stage selected hunks or ask for direction.
635
+
636
+ ## Screen and Validate
637
+
638
+ Before commit creation, check the staged diff for:
639
+
640
+ - Secrets, tokens, private keys, credentials, cookies, and unredacted personal
641
+ data.
642
+ - \`.env\`, local config, machine-specific paths, and editor files.
643
+ - \`.flow/**\` state.
644
+ - Generated artifacts that are not normally versioned.
645
+ - Package or version metadata drift unrelated to the requested change.
646
+
647
+ When this repository-local contribution preflight exists, defer to it for staged
648
+ and outgoing validation instead of duplicating its checks:
649
+
650
+ \`\`\`bash
651
+ .agents/skills/flow-contribution-check/scripts/preflight.sh commit
652
+ \`\`\`
653
+
654
+ Run it after staging and rerun it after any staging change. The preflight
655
+ validates staged or outgoing work; it does not choose commit boundaries or write
656
+ commit messages. If the script is absent, use the repository's documented commit
657
+ preflight from package scripts, AGENTS/docs, or CI guidance.
658
+
659
+ Use the repository's documented broad validation gate when a full local check is
660
+ appropriate, such as package scripts, AGENTS/docs, or CI guidance. Use narrower
661
+ tests only when the user has asked for a lighter pass or when the change is
662
+ intentionally not ready for the broad gate.
663
+
664
+ ## Message
665
+
666
+ Propose a commit message that reflects the staged diff:
667
+
668
+ - Subject: imperative, specific, and scoped.
669
+ - Body when useful: context, changed areas, validation run, and remaining risk.
670
+ - Do not mention unstaged or excluded work as if it were included.
671
+ - Include WIP or failing-validation context only when the user explicitly chose
672
+ that path.
673
+
674
+ ## Create Commit
675
+
676
+ Create the commit only after the user explicitly asks for commit creation or has
677
+ already authorized it in the current request.
678
+
679
+ Before running \`git commit\`, report:
680
+
681
+ - Staged paths.
682
+ - Excluded dirty or untracked paths.
683
+ - Validation command and result.
684
+ - Proposed message.
685
+ - Any risks or gaps.
686
+
687
+ After a successful commit, report the commit hash and leave push or release
688
+ actions for a separate explicit request.
689
+ `;var ke=`# Safe refactor workflow
564
690
 
565
691
  Refactoring is a behavior-preserving sequence of small changes. This workflow keeps cleanup from becoming an unreviewable rewrite.
566
692
 
@@ -602,7 +728,7 @@ Weak evidence includes:
602
728
  - Public contracts and compatibility shims remain intact or were explicitly planned.
603
729
  - Deleted code is actually unreachable or obsolete.
604
730
  - Validation can catch a realistic mistake in the refactor.
605
- `;var be=`# Deslop smell rubric
731
+ `;var xe=`# Deslop smell rubric
606
732
 
607
733
  Use this rubric to turn vague cleanup instincts into reviewable findings.
608
734
 
@@ -636,9 +762,9 @@ class; severity; location; evidence read; refutation checked; why it matters; sa
636
762
  \`\`\`
637
763
 
638
764
  Rate as blocking only when the smell materially raises defect risk, blocks planned work, hides behavior, or makes the success claim unverifiable. Style-only cleanup is advisory.
639
- `;var ke=`---
765
+ `;var Fe=`---
640
766
  name: flow-deslop
641
- description: Flow guidance for evidence-backed code smell cleanup, AI-slop removal, overengineering reduction, maintainability refactors, and behavior-preserving cleanup. Use when planning, executing, or reviewing broad cleanup/refactor work, code smell findings, duplicated or bloated code, speculative abstractions, dead code, or agent-introduced mess.
767
+ description: Clean up and refactor code with evidence-backed code-smell analysis. Use for AI-slop removal, overengineering reduction, maintainability refactors, behavior-preserving cleanup, duplicated or bloated code, speculative abstractions, dead code, or broad cleanup/refactor review.
642
768
  ---
643
769
 
644
770
  # Flow deslop
@@ -678,7 +804,7 @@ For each claimed smell removal, verify:
678
804
  - **blast radius** — public contracts and downstream callers still work.
679
805
 
680
806
  Never approve cleanup because it "looks cleaner" without evidence. Tests passing is necessary but not sufficient when the refactor changes structure across files.
681
- `;var xe=`# Parallel discovery
807
+ `;var Re=`# Parallel discovery
682
808
 
683
809
  Use this only after a serial orientation pass has identified the repo shape and the likely slices. Workers are read-only evidence gatherers; the planner owns the plan.
684
810
 
@@ -744,7 +870,7 @@ Convert only evidence-backed work into plan fields:
744
870
  - feature \`validation\`: checks expected to prove the feature.
745
871
 
746
872
  If workers disagree, inspect the source artifact yourself. If a candidate finding lacks a concrete citation or refutation pass, make it a review-first deliverable rather than a fix feature.
747
- `;var Re=`# Planning examples
873
+ `;var _e=`# Planning examples
748
874
 
749
875
  ## Rate limiting feature set
750
876
 
@@ -829,7 +955,7 @@ Better plan:
829
955
  - Validation that only says "manual testing".
830
956
  - Targets that name the entire repo.
831
957
  - Features with hidden dependencies instead of \`dependsOn\`.
832
- `;var Fe=`---
958
+ `;var Se=`---
833
959
  name: flow-plan
834
960
  description: Plan Flow work for the v4 skills-first runtime: inspect the repo, decompose a user goal into right-sized features, save a draft with flow_plan_save, and approve it with flow_plan_approve.
835
961
  ---
@@ -844,6 +970,9 @@ If \`flow_plan_save\` or \`flow_plan_approve\` is unavailable, stop and tell the
844
970
 
845
971
  - Read the files, docs, tests, package scripts, and local conventions that determine the work.
846
972
  - For broad discovery, read \`references/parallel-discovery.md\` after a serial orientation pass. Use \`../flow/references/parallel-orchestration.md\` when discovery needs multiple workers, and apply its coverage gate before fan-out.
973
+ - For complex validation, regression-sensitive changes, browser/UI workflows,
974
+ or uncertain test strategy, load \`flow-test\`. If it is unavailable, record a
975
+ planning gap and keep validation claims conservative.
847
976
  - For cleanup/refactor goals, load \`flow-deslop\`. If it is unavailable, record
848
977
  a planning gap and keep cleanup claims conservative.
849
978
  - For UI/frontend goals, load \`flow-ui-quality\`. If it is unavailable, record a
@@ -886,14 +1015,17 @@ Use only \`finalReviewPolicy: "broad"\` or \`"detailed"\`. These are the canonic
886
1015
  - Split by dependency order: foundations before callers, schema before consumers, implementation before docs when docs depend on behavior.
887
1016
  - Avoid "misc cleanup" features. Tie cleanup to evidence and targets.
888
1017
  - Keep feature ids stable once the plan is approved.
889
- - Put scope boundaries in \`targets\` and expected checks in \`validation\`.
1018
+ - Put scope boundaries in \`targets\` and expected checks in \`validation\`. Each
1019
+ validation entry should name the expected test level, such as targeted unit,
1020
+ integration, browser/e2e, package/build, docs/static, cleanup preservation, or
1021
+ broad project gate.
890
1022
 
891
1023
  ## Approval
892
1024
 
893
1025
  After saving, summarize the plan to the user. Call \`flow_plan_approve\` only after explicit user approval, unless the user already authorized autonomous implementation. Approved plans are immutable; changing them later requires reset/closure rather than silent edits.
894
1026
 
895
1027
  See \`references/planning-examples.md\` for payload examples and decomposition anti-patterns.
896
- `;var _e=`# Audit findings rubric
1028
+ `;var Ie=`# Audit findings rubric
897
1029
 
898
1030
  What counts as a valid finding when the feature's deliverable is a findings report: a codebase audit, a review-first feature, or any report whose findings a later feature will fix. The commands you run are still governed by \`validation-rubric.md\`; this rubric governs the findings themselves.
899
1031
 
@@ -946,7 +1078,7 @@ follow-up order — correctness and persisted/user-input surfaces first
946
1078
  \`\`\`
947
1079
 
948
1080
  Never: promote a hypothesis to blocking severity; cite a line you did not read in context; rate severity against a deployment model the product does not have; pad the report to look thorough — six verified findings outrank nine where three die on first contact.
949
- `;var Se=`# Validation evidence rubric
1081
+ `;var Pe=`# Validation evidence rubric
950
1082
 
951
1083
  Use this before recording \`flow_feature_complete\`.
952
1084
 
@@ -1003,7 +1135,7 @@ Broad validation usually means the repo's full check command, full relevant test
1003
1135
  - If validation needs external access, missing credentials, or ambiguous user input, record \`status: "needs_input"\` with an honest \`outcome\`.
1004
1136
 
1005
1137
  Never trim failing output, relabel a failed command as passed, or use "not run" as completion evidence.
1006
- `;var Ie=`---
1138
+ `;var Ce=`---
1007
1139
  name: flow-run
1008
1140
  description: Execute one approved Flow feature in the v4 runtime: start a feature with flow_run_start, make scoped changes, gather real validation evidence, obtain review payloads, and complete with flow_feature_complete.
1009
1141
  ---
@@ -1029,9 +1161,18 @@ If \`flow_run_start\` is unavailable, stop and tell the user to check that \`ope
1029
1161
  - Keep edits scoped to the active feature. If new scope appears, stop and replan or defer it to another feature.
1030
1162
  - Preserve unrelated user changes in the worktree.
1031
1163
  - When a wrong assumption invalidates the feature, use \`flow_feature_reset\`; do not pile patches onto a bad path.
1164
+ - Do not stage, commit, push, amend, rebase, publish, or mutate releases as part
1165
+ of feature execution. If the user explicitly asks for commit preparation, load
1166
+ \`flow-commit\` only after \`flow_feature_complete\` has been recorded, unless the
1167
+ user explicitly asks for a WIP commit path. Keep Git boundaries separate from
1168
+ Flow state recording.
1032
1169
 
1033
1170
  ## Validate
1034
1171
 
1172
+ - For complex validation, regression-sensitive changes, browser/UI workflows,
1173
+ failure-prone checks, unclear coverage, route QA, exploratory QA, or
1174
+ \`validationRun\` summarization, load \`flow-test\`. If it is unavailable, record
1175
+ the coverage gap and keep validation claims conservative.
1035
1176
  - Read \`references/validation-rubric.md\` before completing.
1036
1177
  - Run the strongest practical checks for the changed behavior.
1037
1178
  - Record concrete command names, status, and observed results. "Tests pass" is not evidence.
@@ -1058,8 +1199,9 @@ and records it.
1058
1199
 
1059
1200
  If \`flow_status\` reports \`setup.skills\` or \`flow-review\` cannot be loaded, do
1060
1201
  not record a Flow-gated \`featureReview\` or \`finalReview\`. You may perform an
1061
- advisory review using available context or bundled reviewer fallback text, then
1062
- complete with \`status: "needs_input"\` if review evidence is required to proceed.
1202
+ advisory review using available context or the bundled review fallback provided
1203
+ by plugin config, then complete with \`status: "needs_input"\` if review evidence
1204
+ is required to proceed.
1063
1205
 
1064
1206
  For the final feature, also obtain a \`finalReview\` payload whose \`reviewDepth\` equals the approved plan's \`finalReviewPolicy\`.
1065
1207
 
@@ -1080,7 +1222,131 @@ Complete with:
1080
1222
  \`\`\`
1081
1223
 
1082
1224
  If genuinely blocked, call \`flow_feature_complete\` with \`status: "needs_input"\` and an \`outcome\` that explains the blocker and next step. Never fabricate validation or review evidence to force progress.
1083
- `;var Pe=`# UI quality rubric
1225
+ `;var Ae=`---
1226
+ name: flow-test
1227
+ description: Test, validate, make test plans, triage failures, and gather Flow validation evidence. Use when selecting checks, running tests, running browser QA for UI changes, classifying failures, or preparing validationRun evidence for flow_feature_complete.
1228
+ ---
1229
+
1230
+ # Flow Test
1231
+
1232
+ Use this skill to decide and gather validation evidence. It produces validation
1233
+ evidence only: the manager still owns \`flow_feature_complete\`, review payloads,
1234
+ plan approval, session closure, and every other Flow state change.
1235
+
1236
+ Do not mutate \`.flow/**\`, approve plans, complete features, close sessions, or
1237
+ substitute for \`flow-review\`. If Flow tools are unavailable, this skill can still
1238
+ produce an advisory validation plan or test summary, but it cannot record Flow
1239
+ state.
1240
+
1241
+ ## Inputs
1242
+
1243
+ Start from the smallest concrete surface:
1244
+
1245
+ - The approved feature \`summary\`, \`targets\`, and \`validation\` entries when a
1246
+ Flow session exists.
1247
+ - The actual diff, changed files, package scripts, docs, and test conventions.
1248
+ - Recent command output from this session or from a trusted worker handoff.
1249
+ - Any user-stated acceptance criteria, browser target, fixture, or environment
1250
+ constraint.
1251
+
1252
+ Prefer repository scripts and local conventions over invented commands. If a
1253
+ command has not been run in this session or directly reported by a trusted
1254
+ worker with raw outcome, recommend it instead of claiming it passed.
1255
+
1256
+ ## Select Coverage
1257
+
1258
+ Choose checks from changed-surface risk, not from habit:
1259
+
1260
+ - **Targeted behavior**: unit, integration, CLI, route, or component tests that
1261
+ exercise the changed behavior and would fail without the fix.
1262
+ - **Integration and persistence**: database, filesystem, API, adapter, lock, or
1263
+ serialization paths touched by the feature.
1264
+ - **Browser or e2e**: user-visible workflows, responsive states, accessibility
1265
+ basics, form flows, and screenshots when a local target and browser tooling
1266
+ are available.
1267
+ - **Package and build shape**: typecheck, lint, build, generated distribution,
1268
+ or schema checks when public contracts, bundling, or package exports changed.
1269
+ - **Docs and mechanical edits**: markdown rendering, link/path sanity, spelling
1270
+ of commands, or the narrowest project check when behavior is unchanged.
1271
+ - **Cleanup/refactor**: behavior-preservation tests plus the relevant broad
1272
+ check; formatting alone is not evidence of preserved behavior.
1273
+ - **Final feature**: the repository's broad gate, full relevant suite, build, or
1274
+ equivalent release gate before \`validationScope: "broad"\` is recorded.
1275
+
1276
+ If the planned coverage is weaker than the risk, say so explicitly and list the
1277
+ missing evidence.
1278
+
1279
+ ## Run Discipline
1280
+
1281
+ For each check:
1282
+
1283
+ 1. State the hypothesis: what behavior or contract the check is expected to
1284
+ prove.
1285
+ 2. Run the command or manual workflow when the environment allows it.
1286
+ 3. Record exact command, status, and observed result.
1287
+ 4. If it fails, classify the failure before editing:
1288
+ - product failure
1289
+ - test failure
1290
+ - environment failure
1291
+ - pre-existing failure
1292
+ - flake
1293
+ - unrelated failure
1294
+ 5. Before a fix attempt, write a short failure hypothesis that names the likely
1295
+ cause and the file or behavior to inspect.
1296
+ 6. After a fix, rerun the failing check and one appropriate regression check.
1297
+
1298
+ Do not trim failure output so far that the manager cannot understand the
1299
+ failure. Do redact secrets and credentials.
1300
+
1301
+ ## Browser and Exploratory QA
1302
+
1303
+ For meaningful UI or browser workflow changes, browser evidence is expected when
1304
+ a local target can run:
1305
+
1306
+ - Open the relevant route or story with the available browser tooling.
1307
+ - Exercise the main changed workflow, not only page load.
1308
+ - Check desktop and mobile breakpoints when responsive behavior is in scope.
1309
+ - Capture screenshots or describe the viewport, route, steps, and observed
1310
+ result.
1311
+ - Inspect visible error states, empty states, long labels, focus behavior, and
1312
+ console or network failures when the tooling exposes them.
1313
+
1314
+ Browser claims are evidence requirements, not guaranteed coverage. If browser
1315
+ tooling, credentials, seed data, or a local server is unavailable, record the
1316
+ gap and provide the next-best evidence such as component tests, build output, or
1317
+ static inspection.
1318
+
1319
+ Exploratory QA should be scenario-based. Name the user path, the state varied,
1320
+ and the expected outcome. Do not replace automated evidence with exploratory QA
1321
+ when a practical automated check exists.
1322
+
1323
+ ## Output
1324
+
1325
+ Return a concise validation summary and a \`validationRun\` array that the manager
1326
+ can record through \`flow_feature_complete\` if it accepts the evidence:
1327
+
1328
+ \`\`\`json
1329
+ {
1330
+ "validationRun": [
1331
+ {
1332
+ "command": "bun test tests/foo.test.ts",
1333
+ "status": "passed",
1334
+ "summary": "3 pass; covered foo creation, duplicate rejection, and reset behavior"
1335
+ }
1336
+ ],
1337
+ "testSummary": "Targeted behavior and package shape passed. Browser evidence was not applicable.",
1338
+ "gaps": []
1339
+ }
1340
+ \`\`\`
1341
+
1342
+ Only passing checks belong in \`validationRun\` for completion. Failed, skipped,
1343
+ or unavailable checks belong in \`testSummary\`, \`gaps\`, or a blocker outcome.
1344
+ Each summary must state what behavior, file set, route, command, or state was
1345
+ covered. Static inspection alone is a gap for behavioral changes.
1346
+
1347
+ Never relabel a failed command as passed, invent output, or use "not run" as
1348
+ completion evidence.
1349
+ `;var Te=`# UI quality rubric
1084
1350
 
1085
1351
  Use this rubric for frontend planning, implementation, and review.
1086
1352
 
@@ -1124,7 +1390,7 @@ class; severity; location or screenshot area; evidence inspected; user impact; f
1124
1390
  \`\`\`
1125
1391
 
1126
1392
  Blocking UI findings are issues that prevent task completion, hide required information, break accessibility basics, create incoherent layout at supported sizes, or make the visual success claim unverifiable.
1127
- `;var Ae=`# Visual verification workflow
1393
+ `;var Ue=`# Visual verification workflow
1128
1394
 
1129
1395
  Use this workflow when UI changes can be run locally. Flow execution may create visual evidence; Flow review usually assesses recorded evidence because the reviewer is read-only.
1130
1396
 
@@ -1164,9 +1430,9 @@ Record the reason and use the strongest available substitute:
1164
1430
  - code inspection against existing component patterns.
1165
1431
 
1166
1432
  Do not claim visual polish was verified if no visual artifact was inspected.
1167
- `;var Ce=`---
1433
+ `;var qe=`---
1168
1434
  name: flow-ui-quality
1169
- description: Flow guidance for UX/UI design, frontend polish, visual quality review, responsive and accessible interfaces, and avoiding generic AI-generated UI. Use when planning, executing, or reviewing frontend pages, components, dashboards, visual redesigns, interaction states, screenshots, or browser-verified UI work.
1435
+ description: Review and improve frontend UI quality for Flow work. Use for UX/UI design, frontend polish, visual quality review, responsive and accessible interfaces, interaction states, screenshots, browser-verified UI work, and avoiding generic AI-generated UI.
1170
1436
  ---
1171
1437
 
1172
1438
  # Flow UI quality
@@ -1192,6 +1458,9 @@ Use this skill when Flow work changes what a user sees or how they interact with
1192
1458
  ## Verify visually
1193
1459
 
1194
1460
  - For meaningful UI changes, run the app and capture screenshots when a local browser target is available.
1461
+ - For browser-driven QA, route selection, failure classification, and
1462
+ \`validationRun\` summaries, load \`flow-test\`. Keep visual judgment, design
1463
+ quality, and screenshot assessment in \`flow-ui-quality\`.
1195
1464
  - Check desktop and mobile breakpoints, not only the viewport you developed in.
1196
1465
  - Verify text does not overlap, truncate unintentionally, or escape controls; long labels and empty/error states must fit.
1197
1466
  - Compare against provided screenshots, design references, or the stated product intent. List meaningful differences and fix the ones that violate the goal.
@@ -1209,12 +1478,12 @@ Approve only when the interface is both useful and inspectable:
1209
1478
  - Screenshot/browser evidence supports the claim whenever feasible.
1210
1479
 
1211
1480
  Never approve a UI change based only on code shape. If users will judge it visually, Flow evidence should include visual inspection.
1212
- `;var Y=[{name:"flow",files:[{relativePath:"SKILL.md",content:we},{relativePath:"references/recovery-playbook.md",content:ge},{relativePath:"references/parallel-orchestration.md",content:he},{relativePath:"references/handoff-format.md",content:me},{relativePath:"references/verification-gates.md",content:ve}]},{name:"flow-plan",files:[{relativePath:"SKILL.md",content:Fe},{relativePath:"references/planning-examples.md",content:Re},{relativePath:"references/parallel-discovery.md",content:xe}]},{name:"flow-run",files:[{relativePath:"SKILL.md",content:Ie},{relativePath:"references/validation-rubric.md",content:Se},{relativePath:"references/audit-rubric.md",content:_e}]},{name:"flow-review",files:[{relativePath:"SKILL.md",content:j},{relativePath:"references/review-rubric.md",content:U}]},{name:"flow-deslop",files:[{relativePath:"SKILL.md",content:ke},{relativePath:"references/smell-rubric.md",content:be},{relativePath:"references/refactor-workflow.md",content:ye}]},{name:"flow-ui-quality",files:[{relativePath:"SKILL.md",content:Ce},{relativePath:"references/ui-rubric.md",content:Pe},{relativePath:"references/visual-verification.md",content:Ae}]}];var Xt=".flow-skill-version",v=null;function Q(){return process.env.HOME??process.env.USERPROFILE??""}function Ue(e=Q()){return P(e,".config","opencode","skills")}function je(e){return Mt("sha256").update(e).digest("hex")}function H(e,a){return[`version=${a}`,...e.files.map((t)=>`file=${t.relativePath} sha256=${je(t.content)}`),""].join(`
1213
- `)}async function Z(e){try{return await Bt(e,"utf8")}catch(a){if(a.code==="ENOENT")return null;throw a}}function Yt(e){let a=new Map;if(!e)return a;for(let t of e.split(/\r?\n/)){let r=/^file=(.+) sha256=([a-f0-9]{64})$/.exec(t)??/^file=(.+)=sha256:([a-f0-9]{64})$/.exec(t);if(r?.[1]&&r[2])a.set(r[1],r[2]);let n=/^hash=sha256:([a-f0-9]{64})$/.exec(t);if(n?.[1]&&!a.has("SKILL.md"))a.set("SKILL.md",n[1])}return a}function Te(e,a){let t=Kt(P(e,...a.split("/")));if(t!==e&&t.startsWith(`${e}${Lt}`))return t;throw Error(`Unsafe skill file path '${a}'.`)}async function Ht(e,a,t){let r=P(t,e.name),n=P(r,Xt),i=await Z(n),s=Yt(i);if(await Z(P(r,"SKILL.md"))!==null&&i===null)return{name:e.name,action:"skipped_foreign"};let p=!1,de=!1;for(let R of e.files){let I=Te(r,R.relativePath),T=await Z(I);if(T===R.content)continue;p=!0;let ue=s.get(R.relativePath);if(T!==null&&(ue?je(T)!==ue:i!==null))await q(`${I}.backup`,T,"utf8"),de=!0}if(!p&&i===H(e,a))return{name:e.name,action:"unchanged"};if(!p)return await q(n,H(e,a),"utf8"),{name:e.name,action:"marker_updated"};let yt=i!==null;for(let R of e.files){let I=Te(r,R.relativePath);await Vt(Gt(I),{recursive:!0}),await q(I,R.content,"utf8")}return await q(n,H(e,a),"utf8"),{name:e.name,action:de?"updated_with_backup":yt?"updated":"installed"}}function qe(){return Y.map((e)=>e.name)}function Zt(e,a,t){let r=t.filter((c)=>["installed","updated","updated_with_backup"].includes(c.action)).map((c)=>c.name),n=t.filter((c)=>c.action==="skipped_foreign").map((c)=>c.name),i=n.length>0?"action_required":r.length>0?"restart_required":"ok",s=i==="restart_required"?`Flow installed or updated skills during this startup (${r.join(", ")}). Restart OpenCode before loading Flow skills.`:i==="action_required"?`Flow found user-owned skill folders for managed skills (${n.join(", ")}). Run ${Ee(e)} for repair guidance.`:"Flow skills are synced.";return{status:i,version:e,root:a,checkedAt:new Date().toISOString(),expectedSkills:qe(),results:t,changedSkills:r,actionRequiredSkills:n,restartRequired:i==="restart_required",summary:s}}function Qt(e,a,t){let r=t instanceof Error?t.message:String(t);return{status:"error",version:e,root:a,checkedAt:new Date().toISOString(),expectedSkills:qe(),results:[],changedSkills:[],actionRequiredSkills:[],restartRequired:!1,summary:`Flow skill sync failed: ${r}`,error:r}}function Ee(e){return`npx -y opencode-plugin-flow@${e} doctor`}function ee(e=v){if(!e||e.status==="ok")return null;return{status:e.status==="error"?"sync_failed":e.status,summary:e.summary,version:e.version,root:e.root,...e.changedSkills.length>0?{changed:e.changedSkills}:{},...e.actionRequiredSkills.length>0?{actionRequired:e.actionRequiredSkills}:{},...e.error?{error:e.error}:{}}}function E(e=v){let a=ee(e);if(!a)return null;return["Flow setup warning:",a.summary,`Skills root: ${a.root}`,`Use \`${Ee(a.version)}\` for details.`].join(`
1214
- `)}function Oe(){if(process.env.npm_package_version)return process.env.npm_package_version;try{let e=Jt(import.meta.url);for(let a of["../package.json","../../package.json"])try{let t=e(a);if(t.version)return t.version}catch{}}catch{}return"0.0.0"}async function ea(e,a=Q()){let t=Ue(a);return Promise.all(Y.map((r)=>Ht(r,e,t)))}async function Ne(e,a,t=Q()){let r=Ue(t);try{let n=await ea(e,t);v=Zt(e,r,n);let i=n.filter((s)=>s.action==="installed"||s.action==="updated"||s.action==="updated_with_backup");if(i.length>0)a("info",`Flow synced skills (${i.map((s)=>`${s.name}:${s.action}`).join(", ")}). Restart OpenCode if skills were just installed.`);if(v.status==="action_required")a("warn",v.summary)}catch(n){v=Qt(e,r,n),a("warn",v.summary)}}import{randomUUID as ca}from"node:crypto";import{mkdir as W,open as Ve,readFile as Ke,rename as la,rm as M,writeFile as Be}from"node:fs/promises";import{homedir as da}from"node:os";import{dirname as Je,isAbsolute as $r,join as F,parse as ua,resolve as Le}from"node:path";import{setTimeout as pa}from"node:timers/promises";function ta(e){let a=[],t=0;while(t<e.length){let r=e[t];if(r==="{"){a.push({isObject:!0,keys:new Set,awaitingKey:!0}),t+=1;continue}if(r==="["){a.push({isObject:!1,keys:new Set,awaitingKey:!1}),t+=1;continue}if(r==="}"||r==="]"){a.pop(),t+=1;continue}if(r===","){let n=a.at(-1);if(n?.isObject)n.awaitingKey=!0;t+=1;continue}if(r===":"){let n=a.at(-1);if(n?.isObject)n.awaitingKey=!1;t+=1;continue}if(r==='"'){let n=t+1;while(n<e.length){if(e[n]==="\\"){n+=2;continue}if(e[n]==='"')break;n+=1}let i=a.at(-1);if(i?.isObject&&i.awaitingKey){let s=JSON.parse(e.slice(t,n+1));if(i.keys.has(s))return s;i.keys.add(s)}t=n+1;continue}t+=1}return null}function De(e,a){if(e.trim().length===0)return{ok:!1,error:`${a} is empty.`};let t;try{t=JSON.parse(e)}catch(n){return{ok:!1,error:n instanceof Error?`${a} is not valid JSON: ${n.message}`:`${a} is not valid JSON.`}}if(t===null||typeof t!=="object"||Array.isArray(t))return{ok:!1,error:`${a} must be a JSON object.`};let r=ta(e);if(r)return{ok:!1,error:`${a} has duplicate key '${r}'.`};return{ok:!0,value:t}}import{z as o}from"zod";var w=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,A="Feature ids must be lowercase kebab-case",ze=o.enum(["pending","in_progress","completed","blocked"]),aa=o.enum(["planning","ready","running","blocked","completed"]),ra=o.enum(["passed","failed"]),na=o.enum(["passed","failed"]),te=o.enum(["targeted","broad"]),oe=o.enum(["broad","detailed"]),oa=o.object({summary:o.string().min(1),severity:o.enum(["blocking","advisory"]).default("blocking")}).strict(),O=o.object({status:ra,summary:o.string().min(1),blockingFindings:o.array(oa).default([])}).strict(),ae=O.extend({reviewDepth:oe}).strict(),re=o.object({command:o.string().min(1),status:na,summary:o.string().min(1)}).strict(),ne=o.object({path:o.string().min(1)}).strict(),$e=o.object({id:o.string().regex(w,A),title:o.string().min(1),summary:o.string().min(1),status:ze.default("pending"),targets:o.array(o.string().min(1)).default([]),validation:o.array(o.string().min(1)).default([]),dependsOn:o.array(o.string().regex(w)).default([])}).strict(),We=o.object({summary:o.string().min(1),overview:o.string().min(1),requirements:o.array(o.string().min(1)).default([]),decisions:o.array(o.string().min(1)).default([]),finalReviewPolicy:oe.default("detailed"),features:o.array($e).min(1)}).strict(),N=We.omit({features:!0}).extend({finalReviewPolicy:oe.optional(),features:o.array($e.omit({status:!0}).extend({status:ze.optional(),targets:o.array(o.string().min(1)).optional(),validation:o.array(o.string().min(1)).optional(),dependsOn:o.array(o.string().regex(w)).optional()}).strict()).min(1)}),Me=o.object({kind:o.enum(["completed","blocked","needs_input","replan_required"]).default("completed"),summary:o.string().min(1).optional(),resolutionHint:o.string().min(1).optional()}).strict(),ia=o.object({kind:o.enum(["blocked","needs_input","replan_required"]).default("needs_input"),summary:o.string().min(1),resolutionHint:o.string().min(1).optional()}).strict(),D=o.discriminatedUnion("status",[o.object({status:o.literal("ok"),featureId:o.string().regex(w,A),summary:o.string().min(1),artifactsChanged:o.array(ne).default([]),validationRun:o.array(re).default([]),validationScope:te,featureReview:O,finalReview:ae.optional(),outcome:Me.optional()}).strict(),o.object({status:o.literal("needs_input"),featureId:o.string().regex(w,A),summary:o.string().min(1),artifactsChanged:o.array(ne).default([]),validationRun:o.array(re).default([]),validationScope:te.optional(),featureReview:O.optional(),finalReview:ae.optional(),outcome:ia}).strict()]).superRefine((e,a)=>{if(e.status==="ok"&&e.outcome?.kind&&e.outcome.kind!=="completed")a.addIssue({code:"custom",path:["outcome","kind"],message:'ok worker results must use outcome.kind "completed".'})}),sa=o.object({featureId:o.string().regex(w,A),status:o.enum(["completed","blocked","needs_input"]),summary:o.string().min(1),recordedAt:o.string().min(1),artifactsChanged:o.array(ne).default([]),validationRun:o.array(re).default([]),validationScope:te.optional(),featureReview:O.optional(),finalReview:ae.optional(),outcome:Me.optional()}).strict(),z=o.object({version:o.literal(2),id:o.string().min(1),goal:o.string().min(1),status:aa,approval:o.enum(["pending","approved"]),plan:We.nullable(),activeFeatureId:o.string().regex(w,A).nullable(),history:o.array(sa).default([]),closure:o.object({kind:o.enum(["completed","deferred","abandoned"]),summary:o.string().min(1),recordedAt:o.string().min(1)}).strict().nullable(),lastError:o.object({tool:o.string().min(1),summary:o.string().min(1),recovery:o.string().min(1).optional(),recordedAt:o.string().min(1)}).strict().nullable().default(null),timestamps:o.object({createdAt:o.string().min(1),updatedAt:o.string().min(1),completedAt:o.string().min(1).nullable()}).strict()}).strict();class V extends Error{code="INVALID_FLOW_WORKSPACE_ROOT";constructor(e){super(e);this.name="InvalidFlowWorkspaceRootError"}}function ie(e){let a=e?.trim();if(!a)return null;let t=Le(a);return ua(t).root===t?null:t}function B(e){let a=ie(e);if(!a)throw new V("Flow requires a non-root workspace path.");if(a===Le(process.env.HOME??da()))throw new V("Flow refuses to use $HOME itself as a mutable workspace root.");return a}function Xe(e){let a=ie(e.worktree)??ie(e.directory);if(!a)throw new V("Flow could not resolve a workspace root from tool context.");return B(a)}function J(e){return F(e,".flow")}function se(e){return F(J(e),"session.json")}function Ye(e){return F(J(e),"history")}function fa(e,a){if(!/^[a-zA-Z0-9_-]+$/.test(a))throw Error("Invalid session id.");return F(Ye(e),`${a}.json`)}async function He(e,a){await W(Je(e),{recursive:!0});let t=`${e}.${process.pid}.${ca()}.tmp`,r=await Ve(t,"w");try{await r.writeFile(a,"utf8"),await r.sync()}catch(i){throw await r.close(),await M(t,{force:!0}),i}await r.close();try{await la(t,e)}catch(i){throw await M(t,{force:!0}),i}let n=await Ve(Je(e),"r");try{await n.sync()}finally{await n.close()}}var $=new Map,ma=30000,ha=25;async function ga(e){let a=J(e),t=F(a,"session.lock"),r=Date.now();while(!0)try{return await W(t,{recursive:!1}),async()=>{await M(t,{recursive:!0,force:!0})}}catch(n){let i=n.code;if(i==="ENOENT"){await W(a,{recursive:!0});continue}if(i!=="EEXIST")throw n;if(Date.now()-r>ma)throw Error(`Timed out waiting for Flow session lock at ${t}.`);await pa(ha)}}async function Ze(e,a){let t=$.get(e)??Promise.resolve(),r=()=>{},n=new Promise((c)=>{r=c}),i=t.catch(()=>{return}).then(()=>n);$.set(e,i);let s=null;try{return await t.catch(()=>{return}),s=await ga(e),await a()}finally{try{await s?.()}finally{if(r(),$.get(e)===i)$.delete(e)}}}async function C(e){let a=B(e),t;try{t=await Ke(se(a),"utf8")}catch(n){if(n.code==="ENOENT")return null;throw n}let r=De(t,"Flow session file");if(!r.ok)throw Error(r.error);return z.parse(r.value)}async function y(e,a){let t=B(e),r=z.parse(a);return await He(se(t),`${JSON.stringify(r,null,2)}
1215
- `),await Qe(t),r}async function ce(e,a){let t=B(e);await W(Ye(t),{recursive:!0}),await He(fa(t,a.id),`${JSON.stringify(z.parse(a),null,2)}
1216
- `),await M(se(t),{force:!0}),await Qe(t)}var Ge=["session.json","history/","session.lock/",".gitignore",""].join(`
1217
- `);async function Qe(e){let a=F(J(e),".gitignore");try{if((await Ke(a,"utf8")).trim()==="session.lock/")await Be(a,Ge,"utf8")}catch(t){if(t.code!=="ENOENT")throw t;await Be(a,Ge,"utf8")}}function et(e){return async(a)=>{fe(a)}}function G(e){let a=e?.client,t=a?.app?.log;return(r,n)=>{if(typeof t!=="function")return;try{t.call(a?.app,{body:{service:"opencode-plugin-flow",level:r,message:n}})}catch{}}}import{z as f}from"zod";import{randomUUID as wa}from"node:crypto";var va=null;function h(){return va?.()??new Date().toISOString()}function u(e){return{ok:!0,value:e}}function l(e,a,t){return{ok:!1,message:e,...a?{recovery:a}:{},...t?{session:t}:{}}}function ya(e){let a=N.parse(e);return{summary:a.summary,overview:a.overview,requirements:a.requirements??[],decisions:a.decisions??[],finalReviewPolicy:a.finalReviewPolicy??"detailed",features:a.features.map((t)=>({id:t.id,title:t.title,summary:t.summary,status:"pending",targets:t.targets??[],validation:t.validation??[],dependsOn:t.dependsOn??[]}))}}function ba(e){let a=new Set;for(let s of e.features){if(a.has(s.id))return`Duplicate feature id '${s.id}'.`;a.add(s.id)}for(let s of e.features)for(let c of s.dependsOn){if(!a.has(c))return`Feature '${s.id}' depends on unknown feature '${c}'.`;if(c===s.id)return`Feature '${s.id}' cannot depend on itself.`}let t=new Set,r=new Set,n=new Map(e.features.map((s)=>[s.id,s]));function i(s){if(r.has(s))return!1;if(t.has(s))return!0;t.add(s);for(let c of n.get(s)?.dependsOn??[])if(i(c))return!0;return t.delete(s),r.add(s),!1}return e.features.some((s)=>i(s.id))?"Feature dependencies contain a cycle.":null}function K(e){let a=h();return{version:2,id:wa(),goal:e,status:"planning",approval:"pending",plan:null,activeFeatureId:null,history:[],closure:null,lastError:null,timestamps:{createdAt:a,updatedAt:a,completedAt:null}}}function b(e){return{...e,timestamps:{...e.timestamps,updatedAt:h()}}}function rt(e,a){if(e.approval==="approved"||e.status!=="planning")return l("Approved plans cannot be changed. Reset or start a new session.");let t=ya(a),r=ba(t);if(r)return l(r);return u(b({...e,status:"planning",approval:"pending",plan:t,activeFeatureId:null,history:[],closure:null,lastError:null,timestamps:{...e.timestamps,completedAt:null}}))}function nt(e){if(!e.plan)return l("There is no draft plan to approve.");if(e.approval==="approved"&&e.status==="ready")return u(e);if(e.status!=="planning")return l("Only planning sessions can be approved.");return u(b({...e,approval:"approved",status:"ready"}))}function tt(e,a){return e.status==="pending"&&e.dependsOn.every((t)=>a.has(t))}function ka(e,a){let t=new Set(e.filter((i)=>i.status==="completed").map((i)=>i.id)),r=new Map(e.map((i)=>[i.id,i]));if(a){let i=r.get(a);if(!i)return l(`Feature '${a}' is not in the plan.`);if(i.status==="completed")return l(`Feature '${a}' is already completed.`);if(i.status!=="pending")return l(`Feature '${a}' is ${i.status} and must be reset before it can run.`);if(!tt(i,t))return l(`Feature '${a}' has incomplete dependencies.`);return u(i)}let n=e.find((i)=>tt(i,t));return n?u(n):l("No runnable feature is available.")}function le(e,a,t){return e.map((r)=>r.id===a?{...r,status:t}:r.status==="in_progress"&&t==="in_progress"?{...r,status:"pending"}:r)}function ot(e,a){if(e.status==="completed")return l("This Flow session is already completed.");if(!e.plan||e.approval!=="approved")return l("There is no approved plan to run.");if(e.status==="blocked")return l("Blocked features must be reset before rerun.","Call flow_feature_reset for the blocked feature, then start it again.");if(e.activeFeatureId){if(!a||a===e.activeFeatureId){let i=e.plan.features.find((s)=>s.id===e.activeFeatureId);if(i)return u({session:e,feature:i})}return l(`Feature '${e.activeFeatureId}' is already in progress.`)}let t=ka(e.plan.features,a);if(!t.ok)return t;let r={...e.plan,features:le(e.plan.features,t.value.id,"in_progress")},n=b({...e,status:"running",plan:r,activeFeatureId:t.value.id,lastError:null});return u({session:n,feature:n.plan?.features.find((i)=>i.id===t.value.id)??t.value})}function at(e){return e.status==="passed"&&e.blockingFindings.length===0}function xa(e,a){if(!e.plan)return!1;return e.plan.features.every((t)=>t.id===a||t.status==="completed")}function g(e,a,t,r){return l(t,r,{...e,lastError:{tool:a,summary:t,recovery:r,recordedAt:h()}})}function Ra(e,a){let t=xa(e,a.featureId);if(a.validationRun.length===0)return g(e,"flow_feature_complete","Completion requires recorded validation evidence.","Run the targeted or broad validation command and record the result.");if(!a.validationRun.every((r)=>r.status==="passed"))return g(e,"flow_feature_complete","Completion requires all recorded validation to pass.","Fix failures, rerun validation, then complete the feature.");if(!t&&a.validationScope!=="targeted")return g(e,"flow_feature_complete","Non-final feature completion requires targeted validation.","Record validationScope: targeted for ordinary feature completion.");if(t&&a.validationScope!=="broad")return g(e,"flow_feature_complete","Final feature completion requires broad validation.","Run the project-level gate and record validationScope: broad.");if(!at(a.featureReview))return g(e,"flow_feature_complete","Completion requires a passing featureReview with no blocking findings.","Fix or acknowledge the review findings before completing.");if(t){if(!a.finalReview)return g(e,"flow_feature_complete","Final feature completion requires a finalReview.","Run final review and include the finalReview payload.");if(!at(a.finalReview))return g(e,"flow_feature_complete","Final completion requires a passing finalReview.","Resolve final review findings before completing the session.");let r=e.plan?.finalReviewPolicy??"detailed";if(a.finalReview.reviewDepth!==r)return g(e,"flow_feature_complete",`Final review depth must match the plan policy '${r}'.`,"Record a finalReview whose reviewDepth matches the approved plan.")}return u(void 0)}function it(e,a){if(!e.plan||e.status!=="running"||!e.activeFeatureId)return l("No feature is currently running.");let t=D.parse(a);if(t.featureId!==e.activeFeatureId)return l(`Worker result feature '${t.featureId}' does not match active feature '${e.activeFeatureId}'.`);if(t.status==="needs_input"){let p={featureId:t.featureId,status:"needs_input",summary:t.summary,recordedAt:h(),artifactsChanged:t.artifactsChanged,validationRun:t.validationRun,validationScope:t.validationScope,featureReview:t.featureReview,finalReview:t.finalReview,outcome:t.outcome};return u(b({...e,status:"blocked",activeFeatureId:null,plan:{...e.plan,features:le(e.plan.features,t.featureId,"blocked")},history:[...e.history,p]}))}let r=Ra(e,t);if(!r.ok)return r;let n={featureId:t.featureId,status:"completed",summary:t.summary,recordedAt:h(),artifactsChanged:t.artifactsChanged,validationRun:t.validationRun,validationScope:t.validationScope,featureReview:t.featureReview,finalReview:t.finalReview,outcome:t.outcome},i=le(e.plan.features,t.featureId,"completed"),s=i.every((p)=>p.status==="completed"),c=h();return u(b({...e,status:s?"completed":"ready",activeFeatureId:null,plan:{...e.plan,features:i},history:[...e.history,n],closure:s?{kind:"completed",summary:t.summary,recordedAt:c}:null,lastError:null,timestamps:{...e.timestamps,completedAt:s?c:e.timestamps.completedAt}}))}function Fa(e,a){let t=new Set([a]),r=!0;while(r){r=!1;for(let n of e){if(t.has(n.id))continue;if(n.dependsOn.some((i)=>t.has(i)))t.add(n.id),r=!0}}return t}function st(e,a){if(!e.plan)return l("There is no active plan to reset.");if(!e.plan.features.some((s)=>s.id===a))return l(`Feature '${a}' is not in the plan.`);let t=Fa(e.plan.features,a),r=e.activeFeatureId&&t.has(e.activeFeatureId)?null:e.activeFeatureId,n=e.plan.features.map((s)=>t.has(s.id)?{...s,status:"pending"}:s),i=e.approval!=="approved"?"planning":r?"running":n.some((s)=>s.status==="blocked")?"blocked":"ready";return u(b({...e,status:i,activeFeatureId:r,plan:{...e.plan,features:n},closure:null,lastError:null,timestamps:{...e.timestamps,completedAt:null}}))}function ct(e,a,t){if(a==="completed"){if(!e.plan||e.approval!=="approved")return l("Cannot close a Flow session as completed without an approved plan.");let n=e.plan.features.filter((i)=>i.status!=="completed");if(n.length>0)return l("Cannot close a Flow session as completed with unfinished features.",`Unfinished features: ${n.map((i)=>i.id).join(", ")}`);if(e.status!=="completed")return l("Cannot close a Flow session as completed before final completion gates pass.")}let r=h();return u(b({...e,status:a==="completed"?"completed":e.status,activeFeatureId:null,closure:{kind:a,summary:t??`Session closed as ${a}.`,recordedAt:r},timestamps:{...e.timestamps,completedAt:a==="completed"?r:e.timestamps.completedAt}}))}function k(e){if(!e)return{status:"missing_session",summary:"No active Flow session exists.",nextAction:"Start with /flow-plan <goal>."};let a=e.plan?.features??[],t=a.filter((s)=>s.status==="completed"),r=e.history.at(-1)??null,n=e.status==="blocked"?r:null,i=e.activeFeatureId?a.find((s)=>s.id===e.activeFeatureId):null;return{status:e.status,summary:e.closure?.summary??e.lastError?.summary??n?.summary??e.plan?.summary??"Flow session is active.",nextAction:_a(e),session:{id:e.id,goal:e.goal,status:e.status,approval:e.approval,activeFeature:i??null,progress:{completed:t.length,total:a.length},features:a,closure:e.closure,lastError:e.lastError,latestHistoryEntry:r,historyCount:e.history.length,timestamps:e.timestamps}}}function _a(e){if(!e.plan)return"Save a plan with flow_plan_save.";if(e.approval!=="approved")return"Approve the plan.";if(e.status==="ready")return"Start the next feature.";if(e.status==="running")return"Complete or reset the active feature.";if(e.status==="blocked")return"Reset the blocked feature or close the session.";if(e.status==="completed")return"Close/archive the session or start a new goal.";return"Inspect session state."}var Sa=f.object({goal:f.string().trim().min(1).optional(),plan:N.optional()}).strict(),Ia=f.object({featureId:f.string().min(1).optional()}).strict(),Pa=f.object({featureId:f.string().min(1)}).strict(),Aa=f.object({kind:f.enum(["completed","deferred","abandoned"]),summary:f.string().trim().min(1).optional()}).strict();function _(e){return{status:"error",summary:e.message,...e.recovery?{recovery:e.recovery}:{}}}async function S(e,a){return Ze(e,async()=>a(await C(e)))}async function lt(e){return k(await C(e))}async function dt(e,a){let t=Sa.parse(a??{});return S(e,async(r)=>{let n=t.goal??r?.goal;if(!n)return{status:"missing_goal",summary:"Provide a goal before saving a Flow plan.",nextAction:"/flow-plan <goal>"};if(r?.status==="completed")await ce(e,r);let i=r?.status==="completed"?K(n):r??K(n);if(i.goal!==n){if(i.approval==="approved")return{status:"error",summary:"An approved Flow session already exists for a different goal. Close it before starting a new one."}}let s=i.goal===n?i:K(n),c=t.plan?rt(s,t.plan):{ok:!0,value:s};if(!c.ok)return _(c);let p=await y(e,c.value);return{...k(p),status:"ok",summary:t.plan?"Flow plan saved.":"Flow session ready."}})}async function ut(e){return S(e,async(a)=>{if(!a)return{status:"missing_session",summary:"No active Flow session exists.",nextAction:"/flow-plan <goal>"};let t=nt(a);if(!t.ok)return _(t);let r=await y(e,t.value);return{...k(r),status:"ok",summary:"Flow plan approved."}})}async function pt(e,a){let t=Ia.parse(a??{});return S(e,async(r)=>{if(!r)return{status:"missing_session",summary:"No active Flow session exists.",nextAction:"/flow-plan <goal>"};let n=ot(r,t.featureId);if(!n.ok)return _(n);let i=await y(e,n.value.session);return{...k(i),status:"ok",summary:`Started feature '${n.value.feature.id}'.`,feature:n.value.feature}})}async function ft(e,a){let t=D.parse(a??{});return S(e,async(r)=>{if(!r)return{status:"missing_session",summary:"No active Flow session exists.",nextAction:"/flow-plan <goal>"};let n=it(r,t);if(!n.ok){if(n.session)await y(e,n.session);return _(n)}let i=await y(e,n.value);return{...k(i),status:"ok",summary:"Feature result recorded."}})}async function mt(e,a){let t=Pa.parse(a??{});return S(e,async(r)=>{if(!r)return{status:"missing_session",summary:"No active Flow session exists.",nextAction:"/flow-plan <goal>"};let n=st(r,t.featureId);if(!n.ok)return _(n);let i=await y(e,n.value);return{...k(i),status:"ok",summary:`Feature '${t.featureId}' reset.`}})}async function ht(e,a){let t=Aa.parse(a??{});return S(e,async(r)=>{if(!r)return{status:"missing_session",summary:"No active Flow session exists.",nextAction:"/flow-plan <goal>"};let n=ct(r,t.kind,t.summary);if(!n.ok)return _(n);return await ce(e,n.value),{status:"ok",summary:`Flow session closed as ${t.kind}.`,archivedSessionId:n.value.id,closure:n.value.closure}})}import{tool as m}from"@opencode-ai/plugin";var d=m.schema;function gt(e){return JSON.stringify(e,null,2)}function Ca(e){return gt({status:"error",summary:e instanceof Error?e.message:String(e)})}async function x(e,a){try{return gt(await a(Xe(e)))}catch(t){return Ca(t)}}async function Ta(e){let a=await lt(e),t=ee();if(!t)return a;return{...a,setup:{skills:t}}}function vt(e){return G(e)("info","Creating minimal Flow v4 tool surface."),{flow_status:m({description:"Show the active Flow session and next action",args:{},execute:(a,t)=>x(t,Ta)}),flow_plan_save:m({description:"Create or update a draft Flow plan for the active goal",args:{goal:d.string().optional(),plan:d.any().optional()},execute:(a,t)=>x(t,(r)=>dt(r,a))}),flow_plan_approve:m({description:"Approve the current draft Flow plan",args:{},execute:(a,t)=>x(t,ut)}),flow_run_start:m({description:"Start the next runnable approved Flow feature",args:{featureId:d.string().optional()},execute:(a,t)=>x(t,(r)=>pt(r,a))}),flow_feature_complete:m({description:"Record a completed or blocked active feature with validation and review evidence",args:{status:d.enum(["ok","needs_input"]),featureId:d.string(),summary:d.string(),artifactsChanged:d.array(d.object({path:d.string()})).optional(),validationRun:d.array(d.object({command:d.string(),status:d.enum(["passed","failed"]),summary:d.string()})).optional(),validationScope:d.enum(["targeted","broad"]).optional(),featureReview:d.any().optional(),finalReview:d.any().optional(),outcome:d.any().optional()},execute:(a,t)=>x(t,(r)=>ft(r,a))}),flow_feature_reset:m({description:"Reset one feature and its dependents to pending",args:{featureId:d.string()},execute:(a,t)=>x(t,(r)=>mt(r,a))}),flow_session_close:m({description:"Close and archive the active Flow session",args:{kind:d.enum(["completed","deferred","abandoned"]),summary:d.string().optional()},execute:(a,t)=>x(t,(r)=>ht(r,a))})}}async function wt(e){let a=e.worktree??e.directory;if(!a)return null;try{let t=await C(a);if(!t)return null;return["Flow session facts:",`- goal: ${t.goal}`,`- status: ${t.status}`,`- approval: ${t.approval}`,`- active feature: ${t.activeFeatureId??"none"}`,`- progress: ${t.plan?.features.filter((r)=>r.status==="completed").length??0}/${t.plan?.features.length??0}`,"Call flow_status before any Flow action."].join(`
1218
- `)}catch{return null}}function Ua(e){return async(a,t)=>{let r=E();if(r)t.system.push(r);let n=await wt(e);if(n)t.system.push(n)}}function ja(){let e=new Set(Object.keys(X));return async(a,t)=>{let r=a.command.replace(/^\/+/,"");if(!e.has(r))return;let n=E();if(!n)return;t.parts.push({type:"text",text:n,synthetic:!0})}}var qa=async(e)=>{let a=G(e);return a("info","Flow v4 plugin initialized."),await Ne(Oe(),a),{config:et(e),tool:vt(e),"command.execute.before":ja(),"experimental.chat.system.transform":Ua(e),"experimental.session.compacting":async(t,r)=>{let n=E();if(n)r.context=[...r.context??[],n];let i=await wt(e);if(!i)return;r.context=[...r.context??[],i]}}},Ea=qa;export{Ea as default};
1219
-
1220
- //# debugId=352FAA7A055D2E0864756E2164756E21
1481
+ `;var H=[{name:"flow",files:[{relativePath:"SKILL.md",content:ye},{relativePath:"references/recovery-playbook.md",content:ve},{relativePath:"references/parallel-orchestration.md",content:ge},{relativePath:"references/handoff-format.md",content:he},{relativePath:"references/verification-gates.md",content:we}]},{name:"flow-plan",files:[{relativePath:"SKILL.md",content:Se},{relativePath:"references/planning-examples.md",content:_e},{relativePath:"references/parallel-discovery.md",content:Re}]},{name:"flow-run",files:[{relativePath:"SKILL.md",content:Ce},{relativePath:"references/validation-rubric.md",content:Pe},{relativePath:"references/audit-rubric.md",content:Ie}]},{name:"flow-test",files:[{relativePath:"SKILL.md",content:Ae}]},{name:"flow-review",files:[{relativePath:"SKILL.md",content:q},{relativePath:"references/review-rubric.md",content:U}]},{name:"flow-deslop",files:[{relativePath:"SKILL.md",content:Fe},{relativePath:"references/smell-rubric.md",content:xe},{relativePath:"references/refactor-workflow.md",content:ke}]},{name:"flow-ui-quality",files:[{relativePath:"SKILL.md",content:qe},{relativePath:"references/ui-rubric.md",content:Te},{relativePath:"references/visual-verification.md",content:Ue}]},{name:"flow-commit",files:[{relativePath:"SKILL.md",content:be}]}];var ta=".flow-skill-version",v=null;function Z(){return process.env.HOME??process.env.USERPROFILE??""}function Ee(e=Z()){return P(e,".config","opencode","skills")}function Oe(e){return Kt("sha256").update(e).digest("hex")}function X(e,a){return[`version=${a}`,...e.files.map((t)=>`file=${t.relativePath} sha256=${Oe(t.content)}`),""].join(`
1482
+ `)}async function Y(e){try{return await Ht(e,"utf8")}catch(a){if(a.code==="ENOENT")return null;throw a}}function aa(e){let a=new Map;if(!e)return a;for(let t of e.split(/\r?\n/)){let r=/^file=(.+) sha256=([a-f0-9]{64})$/.exec(t)??/^file=(.+)=sha256:([a-f0-9]{64})$/.exec(t);if(r?.[1]&&r[2])a.set(r[1],r[2]);let o=/^hash=sha256:([a-f0-9]{64})$/.exec(t);if(o?.[1]&&!a.has("SKILL.md"))a.set("SKILL.md",o[1])}return a}function je(e,a){let t=Zt(P(e,...a.split("/")));if(t!==e&&t.startsWith(`${e}${ea}`))return t;throw Error(`Unsafe skill file path '${a}'.`)}async function ra(e,a,t){let r=P(t,e.name),o=P(r,ta),i=await Y(o),s=aa(i);if(await Y(P(r,"SKILL.md"))!==null&&i===null)return{name:e.name,action:"skipped_foreign"};let p=!1,de=!1;for(let F of e.files){let I=je(r,F.relativePath),T=await Y(I);if(T===F.content)continue;p=!0;let ue=s.get(F.relativePath);if(T!==null&&(ue?Oe(T)!==ue:i!==null))await E(`${I}.backup`,T,"utf8"),de=!0}if(!p&&i===X(e,a))return{name:e.name,action:"unchanged"};if(!p)return await E(o,X(e,a),"utf8"),{name:e.name,action:"marker_updated"};let xt=i!==null;for(let F of e.files){let I=je(r,F.relativePath);await Qt(Yt(I),{recursive:!0}),await E(I,F.content,"utf8")}return await E(o,X(e,a),"utf8"),{name:e.name,action:de?"updated_with_backup":xt?"updated":"installed"}}function De(){return H.map((e)=>e.name)}function oa(e,a,t){let r=t.filter((c)=>["installed","updated","updated_with_backup"].includes(c.action)).map((c)=>c.name),o=t.filter((c)=>c.action==="skipped_foreign").map((c)=>c.name),i=o.length>0?"action_required":r.length>0?"restart_required":"ok",s=i==="restart_required"?`Flow installed or updated skills during this startup (${r.join(", ")}). Restart OpenCode before loading Flow skills.`:i==="action_required"?`Flow found user-owned skill folders for managed skills (${o.join(", ")}). Run ${Ne(e)} for repair guidance.`:"Flow skills are synced.";return{status:i,version:e,root:a,checkedAt:new Date().toISOString(),expectedSkills:De(),results:t,changedSkills:r,actionRequiredSkills:o,restartRequired:i==="restart_required",summary:s}}function na(e,a,t){let r=t instanceof Error?t.message:String(t);return{status:"error",version:e,root:a,checkedAt:new Date().toISOString(),expectedSkills:De(),results:[],changedSkills:[],actionRequiredSkills:[],restartRequired:!1,summary:`Flow skill sync failed: ${r}`,error:r}}function Ne(e){return`npx -y opencode-plugin-flow@${e} doctor`}function ee(e=v){if(!e||e.status==="ok")return null;return{status:e.status==="error"?"sync_failed":e.status,summary:e.summary,version:e.version,root:e.root,...e.changedSkills.length>0?{changed:e.changedSkills}:{},...e.actionRequiredSkills.length>0?{actionRequired:e.actionRequiredSkills}:{},...e.error?{error:e.error}:{}}}function O(e=v){let a=ee(e);if(!a)return null;return["Flow setup warning:",a.summary,`Skills root: ${a.root}`,`Use \`${Ne(a.version)}\` for details.`].join(`
1483
+ `)}function ze(){if(process.env.npm_package_version)return process.env.npm_package_version;try{let e=Xt(import.meta.url);for(let a of["../package.json","../../package.json"])try{let t=e(a);if(t.version)return t.version}catch{}}catch{}return"0.0.0"}async function ia(e,a=Z()){let t=Ee(a);return Promise.all(H.map((r)=>ra(r,e,t)))}async function We(e,a,t=Z()){let r=Ee(t);try{let o=await ia(e,t);v=oa(e,r,o);let i=o.filter((s)=>s.action==="installed"||s.action==="updated"||s.action==="updated_with_backup");if(i.length>0)a("info",`Flow synced skills (${i.map((s)=>`${s.name}:${s.action}`).join(", ")}). Restart OpenCode if skills were just installed.`);if(v.status==="action_required")a("warn",v.summary)}catch(o){v=na(e,r,o),a("warn",v.summary)}}import{randomUUID as ma}from"node:crypto";import{mkdir as B,open as Je,readFile as He,rename as ha,rm as M,writeFile as Le}from"node:fs/promises";import{homedir as ga}from"node:os";import{dirname as Ke,isAbsolute as Zr,join as R,parse as va,resolve as Xe}from"node:path";import{setTimeout as wa}from"node:timers/promises";function sa(e){let a=[],t=0;while(t<e.length){let r=e[t];if(r==="{"){a.push({isObject:!0,keys:new Set,awaitingKey:!0}),t+=1;continue}if(r==="["){a.push({isObject:!1,keys:new Set,awaitingKey:!1}),t+=1;continue}if(r==="}"||r==="]"){a.pop(),t+=1;continue}if(r===","){let o=a.at(-1);if(o?.isObject)o.awaitingKey=!0;t+=1;continue}if(r===":"){let o=a.at(-1);if(o?.isObject)o.awaitingKey=!1;t+=1;continue}if(r==='"'){let o=t+1;while(o<e.length){if(e[o]==="\\"){o+=2;continue}if(e[o]==='"')break;o+=1}let i=a.at(-1);if(i?.isObject&&i.awaitingKey){let s=JSON.parse(e.slice(t,o+1));if(i.keys.has(s))return s;i.keys.add(s)}t=o+1;continue}t+=1}return null}function $e(e,a){if(e.trim().length===0)return{ok:!1,error:`${a} is empty.`};let t;try{t=JSON.parse(e)}catch(o){return{ok:!1,error:o instanceof Error?`${a} is not valid JSON: ${o.message}`:`${a} is not valid JSON.`}}if(t===null||typeof t!=="object"||Array.isArray(t))return{ok:!1,error:`${a} must be a JSON object.`};let r=sa(e);if(r)return{ok:!1,error:`${a} has duplicate key '${r}'.`};return{ok:!0,value:t}}import{z as n}from"zod";var w=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,C="Feature ids must be lowercase kebab-case",Be=n.enum(["pending","in_progress","completed","blocked"]),ca=n.enum(["planning","ready","running","blocked","completed"]),la=n.enum(["passed","failed"]),da=n.enum(["passed","failed"]),te=n.enum(["targeted","broad"]),ne=n.enum(["broad","detailed"]),ua=n.object({summary:n.string().min(1),severity:n.enum(["blocking","advisory"]).default("blocking")}).strict(),D=n.object({status:la,summary:n.string().min(1),blockingFindings:n.array(ua).default([])}).strict(),ae=D.extend({reviewDepth:ne}).strict(),re=n.object({command:n.string().min(1),status:da,summary:n.string().min(1)}).strict(),oe=n.object({path:n.string().min(1)}).strict(),Me=n.object({id:n.string().regex(w,C),title:n.string().min(1),summary:n.string().min(1),status:Be.default("pending"),targets:n.array(n.string().min(1)).default([]),validation:n.array(n.string().min(1)).default([]),dependsOn:n.array(n.string().regex(w)).default([])}).strict(),Ge=n.object({summary:n.string().min(1),overview:n.string().min(1),requirements:n.array(n.string().min(1)).default([]),decisions:n.array(n.string().min(1)).default([]),finalReviewPolicy:ne.default("detailed"),features:n.array(Me).min(1)}).strict(),N=Ge.omit({features:!0}).extend({finalReviewPolicy:ne.optional(),features:n.array(Me.omit({status:!0}).extend({status:Be.optional(),targets:n.array(n.string().min(1)).optional(),validation:n.array(n.string().min(1)).optional(),dependsOn:n.array(n.string().regex(w)).optional()}).strict()).min(1)}),Ve=n.object({kind:n.enum(["completed","blocked","needs_input","replan_required"]).default("completed"),summary:n.string().min(1).optional(),resolutionHint:n.string().min(1).optional()}).strict(),pa=n.object({kind:n.enum(["blocked","needs_input","replan_required"]).default("needs_input"),summary:n.string().min(1),resolutionHint:n.string().min(1).optional()}).strict(),z=n.discriminatedUnion("status",[n.object({status:n.literal("ok"),featureId:n.string().regex(w,C),summary:n.string().min(1),artifactsChanged:n.array(oe).default([]),validationRun:n.array(re).default([]),validationScope:te,featureReview:D,finalReview:ae.optional(),outcome:Ve.optional()}).strict(),n.object({status:n.literal("needs_input"),featureId:n.string().regex(w,C),summary:n.string().min(1),artifactsChanged:n.array(oe).default([]),validationRun:n.array(re).default([]),validationScope:te.optional(),featureReview:D.optional(),finalReview:ae.optional(),outcome:pa}).strict()]).superRefine((e,a)=>{if(e.status==="ok"&&e.outcome?.kind&&e.outcome.kind!=="completed")a.addIssue({code:"custom",path:["outcome","kind"],message:'ok worker results must use outcome.kind "completed".'})}),fa=n.object({featureId:n.string().regex(w,C),status:n.enum(["completed","blocked","needs_input"]),summary:n.string().min(1),recordedAt:n.string().min(1),artifactsChanged:n.array(oe).default([]),validationRun:n.array(re).default([]),validationScope:te.optional(),featureReview:D.optional(),finalReview:ae.optional(),outcome:Ve.optional()}).strict(),W=n.object({version:n.literal(2),id:n.string().min(1),goal:n.string().min(1),status:ca,approval:n.enum(["pending","approved"]),plan:Ge.nullable(),activeFeatureId:n.string().regex(w,C).nullable(),history:n.array(fa).default([]),closure:n.object({kind:n.enum(["completed","deferred","abandoned"]),summary:n.string().min(1),recordedAt:n.string().min(1)}).strict().nullable(),lastError:n.object({tool:n.string().min(1),summary:n.string().min(1),recovery:n.string().min(1).optional(),recordedAt:n.string().min(1)}).strict().nullable().default(null),timestamps:n.object({createdAt:n.string().min(1),updatedAt:n.string().min(1),completedAt:n.string().min(1).nullable()}).strict()}).strict();class G extends Error{code="INVALID_FLOW_WORKSPACE_ROOT";constructor(e){super(e);this.name="InvalidFlowWorkspaceRootError"}}function ie(e){let a=e?.trim();if(!a)return null;let t=Xe(a);return va(t).root===t?null:t}function V(e){let a=ie(e);if(!a)throw new G("Flow requires a non-root workspace path.");if(a===Xe(process.env.HOME??ga()))throw new G("Flow refuses to use $HOME itself as a mutable workspace root.");return a}function Ye(e){let a=ie(e.worktree)??ie(e.directory);if(!a)throw new G("Flow could not resolve a workspace root from tool context.");return V(a)}function J(e){return R(e,".flow")}function se(e){return R(J(e),"session.json")}function Ze(e){return R(J(e),"history")}function ya(e,a){if(!/^[a-zA-Z0-9_-]+$/.test(a))throw Error("Invalid session id.");return R(Ze(e),`${a}.json`)}async function et(e,a){await B(Ke(e),{recursive:!0});let t=`${e}.${process.pid}.${ma()}.tmp`,r=await Je(t,"w");try{await r.writeFile(a,"utf8"),await r.sync()}catch(i){throw await r.close(),await M(t,{force:!0}),i}await r.close();try{await ha(t,e)}catch(i){throw await M(t,{force:!0}),i}let o=await Je(Ke(e),"r");try{await o.sync()}finally{await o.close()}}var $=new Map,ba=30000,ka=25;async function xa(e){let a=J(e),t=R(a,"session.lock"),r=Date.now();while(!0)try{return await B(t,{recursive:!1}),async()=>{await M(t,{recursive:!0,force:!0})}}catch(o){let i=o.code;if(i==="ENOENT"){await B(a,{recursive:!0});continue}if(i!=="EEXIST")throw o;if(Date.now()-r>ba)throw Error(`Timed out waiting for Flow session lock at ${t}.`);await wa(ka)}}async function tt(e,a){let t=$.get(e)??Promise.resolve(),r=()=>{},o=new Promise((c)=>{r=c}),i=t.catch(()=>{return}).then(()=>o);$.set(e,i);let s=null;try{return await t.catch(()=>{return}),s=await xa(e),await a()}finally{try{await s?.()}finally{if(r(),$.get(e)===i)$.delete(e)}}}async function A(e){let a=V(e),t;try{t=await He(se(a),"utf8")}catch(o){if(o.code==="ENOENT")return null;throw o}let r=$e(t,"Flow session file");if(!r.ok)throw Error(r.error);return W.parse(r.value)}async function y(e,a){let t=V(e),r=W.parse(a);return await et(se(t),`${JSON.stringify(r,null,2)}
1484
+ `),await at(t),r}async function ce(e,a){let t=V(e);await B(Ze(t),{recursive:!0}),await et(ya(t,a.id),`${JSON.stringify(W.parse(a),null,2)}
1485
+ `),await M(se(t),{force:!0}),await at(t)}var Qe=["session.json","history/","session.lock/",".gitignore",""].join(`
1486
+ `);async function at(e){let a=R(J(e),".gitignore");try{if((await He(a,"utf8")).trim()==="session.lock/")await Le(a,Qe,"utf8")}catch(t){if(t.code!=="ENOENT")throw t;await Le(a,Qe,"utf8")}}function rt(e){return async(a)=>{me(a)}}function L(e){let a=e?.client,t=a?.app?.log;return(r,o)=>{if(typeof t!=="function")return;try{t.call(a?.app,{body:{service:"opencode-plugin-flow",level:r,message:o}})}catch{}}}import{z as f}from"zod";import{randomUUID as Ra}from"node:crypto";var Fa=null;function h(){return Fa?.()??new Date().toISOString()}function u(e){return{ok:!0,value:e}}function l(e,a,t){return{ok:!1,message:e,...a?{recovery:a}:{},...t?{session:t}:{}}}function _a(e){let a=N.parse(e);return{summary:a.summary,overview:a.overview,requirements:a.requirements??[],decisions:a.decisions??[],finalReviewPolicy:a.finalReviewPolicy??"detailed",features:a.features.map((t)=>({id:t.id,title:t.title,summary:t.summary,status:"pending",targets:t.targets??[],validation:t.validation??[],dependsOn:t.dependsOn??[]}))}}function Sa(e){let a=new Set;for(let s of e.features){if(a.has(s.id))return`Duplicate feature id '${s.id}'.`;a.add(s.id)}for(let s of e.features)for(let c of s.dependsOn){if(!a.has(c))return`Feature '${s.id}' depends on unknown feature '${c}'.`;if(c===s.id)return`Feature '${s.id}' cannot depend on itself.`}let t=new Set,r=new Set,o=new Map(e.features.map((s)=>[s.id,s]));function i(s){if(r.has(s))return!1;if(t.has(s))return!0;t.add(s);for(let c of o.get(s)?.dependsOn??[])if(i(c))return!0;return t.delete(s),r.add(s),!1}return e.features.some((s)=>i(s.id))?"Feature dependencies contain a cycle.":null}function K(e){let a=h();return{version:2,id:Ra(),goal:e,status:"planning",approval:"pending",plan:null,activeFeatureId:null,history:[],closure:null,lastError:null,timestamps:{createdAt:a,updatedAt:a,completedAt:null}}}function b(e){return{...e,timestamps:{...e.timestamps,updatedAt:h()}}}function it(e,a){if(e.approval==="approved"||e.status!=="planning")return l("Approved plans cannot be changed. Reset or start a new session.");let t=_a(a),r=Sa(t);if(r)return l(r);return u(b({...e,status:"planning",approval:"pending",plan:t,activeFeatureId:null,history:[],closure:null,lastError:null,timestamps:{...e.timestamps,completedAt:null}}))}function st(e){if(!e.plan)return l("There is no draft plan to approve.");if(e.approval==="approved"&&e.status==="ready")return u(e);if(e.status!=="planning")return l("Only planning sessions can be approved.");return u(b({...e,approval:"approved",status:"ready"}))}function ot(e,a){return e.status==="pending"&&e.dependsOn.every((t)=>a.has(t))}function Ia(e,a){let t=new Set(e.filter((i)=>i.status==="completed").map((i)=>i.id)),r=new Map(e.map((i)=>[i.id,i]));if(a){let i=r.get(a);if(!i)return l(`Feature '${a}' is not in the plan.`);if(i.status==="completed")return l(`Feature '${a}' is already completed.`);if(i.status!=="pending")return l(`Feature '${a}' is ${i.status} and must be reset before it can run.`);if(!ot(i,t))return l(`Feature '${a}' has incomplete dependencies.`);return u(i)}let o=e.find((i)=>ot(i,t));return o?u(o):l("No runnable feature is available.")}function le(e,a,t){return e.map((r)=>r.id===a?{...r,status:t}:r.status==="in_progress"&&t==="in_progress"?{...r,status:"pending"}:r)}function ct(e,a){if(e.status==="completed")return l("This Flow session is already completed.");if(!e.plan||e.approval!=="approved")return l("There is no approved plan to run.");if(e.status==="blocked")return l("Blocked features must be reset before rerun.","Call flow_feature_reset for the blocked feature, then start it again.");if(e.activeFeatureId){if(!a||a===e.activeFeatureId){let i=e.plan.features.find((s)=>s.id===e.activeFeatureId);if(i)return u({session:e,feature:i})}return l(`Feature '${e.activeFeatureId}' is already in progress.`)}let t=Ia(e.plan.features,a);if(!t.ok)return t;let r={...e.plan,features:le(e.plan.features,t.value.id,"in_progress")},o=b({...e,status:"running",plan:r,activeFeatureId:t.value.id,lastError:null});return u({session:o,feature:o.plan?.features.find((i)=>i.id===t.value.id)??t.value})}function nt(e){return e.status==="passed"&&e.blockingFindings.length===0}function Pa(e,a){if(!e.plan)return!1;return e.plan.features.every((t)=>t.id===a||t.status==="completed")}function g(e,a,t,r){return l(t,r,{...e,lastError:{tool:a,summary:t,recovery:r,recordedAt:h()}})}function Ca(e,a){let t=Pa(e,a.featureId);if(a.validationRun.length===0)return g(e,"flow_feature_complete","Completion requires recorded validation evidence.","Run the targeted or broad validation command and record the result.");if(!a.validationRun.every((r)=>r.status==="passed"))return g(e,"flow_feature_complete","Completion requires all recorded validation to pass.","Fix failures, rerun validation, then complete the feature.");if(!t&&a.validationScope!=="targeted")return g(e,"flow_feature_complete","Non-final feature completion requires targeted validation.","Record validationScope: targeted for ordinary feature completion.");if(t&&a.validationScope!=="broad")return g(e,"flow_feature_complete","Final feature completion requires broad validation.","Run the project-level gate and record validationScope: broad.");if(!nt(a.featureReview))return g(e,"flow_feature_complete","Completion requires a passing featureReview with no blocking findings.","Fix or acknowledge the review findings before completing.");if(t){if(!a.finalReview)return g(e,"flow_feature_complete","Final feature completion requires a finalReview.","Run final review and include the finalReview payload.");if(!nt(a.finalReview))return g(e,"flow_feature_complete","Final completion requires a passing finalReview.","Resolve final review findings before completing the session.");let r=e.plan?.finalReviewPolicy??"detailed";if(a.finalReview.reviewDepth!==r)return g(e,"flow_feature_complete",`Final review depth must match the plan policy '${r}'.`,"Record a finalReview whose reviewDepth matches the approved plan.")}return u(void 0)}function lt(e,a){if(!e.plan||e.status!=="running"||!e.activeFeatureId)return l("No feature is currently running.");let t=z.parse(a);if(t.featureId!==e.activeFeatureId)return l(`Worker result feature '${t.featureId}' does not match active feature '${e.activeFeatureId}'.`);if(t.status==="needs_input"){let p={featureId:t.featureId,status:"needs_input",summary:t.summary,recordedAt:h(),artifactsChanged:t.artifactsChanged,validationRun:t.validationRun,validationScope:t.validationScope,featureReview:t.featureReview,finalReview:t.finalReview,outcome:t.outcome};return u(b({...e,status:"blocked",activeFeatureId:null,plan:{...e.plan,features:le(e.plan.features,t.featureId,"blocked")},history:[...e.history,p]}))}let r=Ca(e,t);if(!r.ok)return r;let o={featureId:t.featureId,status:"completed",summary:t.summary,recordedAt:h(),artifactsChanged:t.artifactsChanged,validationRun:t.validationRun,validationScope:t.validationScope,featureReview:t.featureReview,finalReview:t.finalReview,outcome:t.outcome},i=le(e.plan.features,t.featureId,"completed"),s=i.every((p)=>p.status==="completed"),c=h();return u(b({...e,status:s?"completed":"ready",activeFeatureId:null,plan:{...e.plan,features:i},history:[...e.history,o],closure:s?{kind:"completed",summary:t.summary,recordedAt:c}:null,lastError:null,timestamps:{...e.timestamps,completedAt:s?c:e.timestamps.completedAt}}))}function Aa(e,a){let t=new Set([a]),r=!0;while(r){r=!1;for(let o of e){if(t.has(o.id))continue;if(o.dependsOn.some((i)=>t.has(i)))t.add(o.id),r=!0}}return t}function dt(e,a){if(!e.plan)return l("There is no active plan to reset.");if(!e.plan.features.some((s)=>s.id===a))return l(`Feature '${a}' is not in the plan.`);let t=Aa(e.plan.features,a),r=e.activeFeatureId&&t.has(e.activeFeatureId)?null:e.activeFeatureId,o=e.plan.features.map((s)=>t.has(s.id)?{...s,status:"pending"}:s),i=e.approval!=="approved"?"planning":r?"running":o.some((s)=>s.status==="blocked")?"blocked":"ready";return u(b({...e,status:i,activeFeatureId:r,plan:{...e.plan,features:o},closure:null,lastError:null,timestamps:{...e.timestamps,completedAt:null}}))}function ut(e,a,t){if(a==="completed"){if(!e.plan||e.approval!=="approved")return l("Cannot close a Flow session as completed without an approved plan.");let o=e.plan.features.filter((i)=>i.status!=="completed");if(o.length>0)return l("Cannot close a Flow session as completed with unfinished features.",`Unfinished features: ${o.map((i)=>i.id).join(", ")}`);if(e.status!=="completed")return l("Cannot close a Flow session as completed before final completion gates pass.")}let r=h();return u(b({...e,status:a==="completed"?"completed":e.status,activeFeatureId:null,closure:{kind:a,summary:t??`Session closed as ${a}.`,recordedAt:r},timestamps:{...e.timestamps,completedAt:a==="completed"?r:e.timestamps.completedAt}}))}function k(e){if(!e)return{status:"missing_session",summary:"No active Flow session exists.",nextAction:"Start with /flow-plan <goal>."};let a=e.plan?.features??[],t=a.filter((s)=>s.status==="completed"),r=e.history.at(-1)??null,o=e.status==="blocked"?r:null,i=e.activeFeatureId?a.find((s)=>s.id===e.activeFeatureId):null;return{status:e.status,summary:e.closure?.summary??e.lastError?.summary??o?.summary??e.plan?.summary??"Flow session is active.",nextAction:Ta(e),session:{id:e.id,goal:e.goal,status:e.status,approval:e.approval,activeFeature:i??null,progress:{completed:t.length,total:a.length},features:a,closure:e.closure,lastError:e.lastError,latestHistoryEntry:r,historyCount:e.history.length,timestamps:e.timestamps}}}function Ta(e){if(!e.plan)return"Save a plan with flow_plan_save.";if(e.approval!=="approved")return"Approve the plan.";if(e.status==="ready")return"Start the next feature.";if(e.status==="running")return"Complete or reset the active feature.";if(e.status==="blocked")return"Reset the blocked feature or close the session.";if(e.status==="completed")return"Close/archive the session or start a new goal.";return"Inspect session state."}var Ua=f.object({goal:f.string().trim().min(1).optional(),plan:N.optional()}).strict(),qa=f.object({featureId:f.string().min(1).optional()}).strict(),ja=f.object({featureId:f.string().min(1)}).strict(),Ea=f.object({kind:f.enum(["completed","deferred","abandoned"]),summary:f.string().trim().min(1).optional()}).strict();function _(e){return{status:"error",summary:e.message,...e.recovery?{recovery:e.recovery}:{}}}async function S(e,a){return tt(e,async()=>a(await A(e)))}async function pt(e){return k(await A(e))}async function ft(e,a){let t=Ua.parse(a??{});return S(e,async(r)=>{let o=t.goal??r?.goal;if(!o)return{status:"missing_goal",summary:"Provide a goal before saving a Flow plan.",nextAction:"/flow-plan <goal>"};if(r?.status==="completed")await ce(e,r);let i=r?.status==="completed"?K(o):r??K(o);if(i.goal!==o){if(i.approval==="approved")return{status:"error",summary:"An approved Flow session already exists for a different goal. Close it before starting a new one."}}let s=i.goal===o?i:K(o),c=t.plan?it(s,t.plan):{ok:!0,value:s};if(!c.ok)return _(c);let p=await y(e,c.value);return{...k(p),status:"ok",summary:t.plan?"Flow plan saved.":"Flow session ready."}})}async function mt(e){return S(e,async(a)=>{if(!a)return{status:"missing_session",summary:"No active Flow session exists.",nextAction:"/flow-plan <goal>"};let t=st(a);if(!t.ok)return _(t);let r=await y(e,t.value);return{...k(r),status:"ok",summary:"Flow plan approved."}})}async function ht(e,a){let t=qa.parse(a??{});return S(e,async(r)=>{if(!r)return{status:"missing_session",summary:"No active Flow session exists.",nextAction:"/flow-plan <goal>"};let o=ct(r,t.featureId);if(!o.ok)return _(o);let i=await y(e,o.value.session);return{...k(i),status:"ok",summary:`Started feature '${o.value.feature.id}'.`,feature:o.value.feature}})}async function gt(e,a){let t=z.parse(a??{});return S(e,async(r)=>{if(!r)return{status:"missing_session",summary:"No active Flow session exists.",nextAction:"/flow-plan <goal>"};let o=lt(r,t);if(!o.ok){if(o.session)await y(e,o.session);return _(o)}let i=await y(e,o.value);return{...k(i),status:"ok",summary:"Feature result recorded."}})}async function vt(e,a){let t=ja.parse(a??{});return S(e,async(r)=>{if(!r)return{status:"missing_session",summary:"No active Flow session exists.",nextAction:"/flow-plan <goal>"};let o=dt(r,t.featureId);if(!o.ok)return _(o);let i=await y(e,o.value);return{...k(i),status:"ok",summary:`Feature '${t.featureId}' reset.`}})}async function wt(e,a){let t=Ea.parse(a??{});return S(e,async(r)=>{if(!r)return{status:"missing_session",summary:"No active Flow session exists.",nextAction:"/flow-plan <goal>"};let o=ut(r,t.kind,t.summary);if(!o.ok)return _(o);return await ce(e,o.value),{status:"ok",summary:`Flow session closed as ${t.kind}.`,archivedSessionId:o.value.id,closure:o.value.closure}})}import{tool as m}from"@opencode-ai/plugin";var d=m.schema;function yt(e){return JSON.stringify(e,null,2)}function Oa(e){return yt({status:"error",summary:e instanceof Error?e.message:String(e)})}async function x(e,a){try{return yt(await a(Ye(e)))}catch(t){return Oa(t)}}async function Da(e){let a=await pt(e),t=ee();if(!t)return a;return{...a,setup:{skills:t}}}function bt(e){return L(e)("info","Creating minimal Flow v4 tool surface."),{flow_status:m({description:"Show the active Flow session and next action",args:{},execute:(a,t)=>x(t,Da)}),flow_plan_save:m({description:"Create or update a draft Flow plan for the active goal",args:{goal:d.string().optional(),plan:d.any().optional()},execute:(a,t)=>x(t,(r)=>ft(r,a))}),flow_plan_approve:m({description:"Approve the current draft Flow plan",args:{},execute:(a,t)=>x(t,mt)}),flow_run_start:m({description:"Start the next runnable approved Flow feature",args:{featureId:d.string().optional()},execute:(a,t)=>x(t,(r)=>ht(r,a))}),flow_feature_complete:m({description:"Record a completed or blocked active feature with validation and review evidence",args:{status:d.enum(["ok","needs_input"]),featureId:d.string(),summary:d.string(),artifactsChanged:d.array(d.object({path:d.string()})).optional(),validationRun:d.array(d.object({command:d.string(),status:d.enum(["passed","failed"]),summary:d.string()})).optional(),validationScope:d.enum(["targeted","broad"]).optional(),featureReview:d.any().optional(),finalReview:d.any().optional(),outcome:d.any().optional()},execute:(a,t)=>x(t,(r)=>gt(r,a))}),flow_feature_reset:m({description:"Reset one feature and its dependents to pending",args:{featureId:d.string()},execute:(a,t)=>x(t,(r)=>vt(r,a))}),flow_session_close:m({description:"Close and archive the active Flow session",args:{kind:d.enum(["completed","deferred","abandoned"]),summary:d.string().optional()},execute:(a,t)=>x(t,(r)=>wt(r,a))})}}async function kt(e){let a=e.worktree??e.directory;if(!a)return null;try{let t=await A(a);if(!t)return null;return["Flow session facts:",`- goal: ${t.goal}`,`- status: ${t.status}`,`- approval: ${t.approval}`,`- active feature: ${t.activeFeatureId??"none"}`,`- progress: ${t.plan?.features.filter((r)=>r.status==="completed").length??0}/${t.plan?.features.length??0}`,"Call flow_status before any Flow action."].join(`
1487
+ `)}catch{return null}}function Na(e){return async(a,t)=>{let r=O();if(r)t.system.push(r);let o=await kt(e);if(o)t.system.push(o)}}function za(e){return e in j}function Wa(e,a){return j[e].template.replaceAll("$ARGUMENTS",a)}function $a(e,a){let t=e.parts,r=t[0];if(t.length===1&&r?.type==="subtask"){r.prompt=a;return}t.splice(0,t.length,{type:"text",text:a,synthetic:!0})}function Ba(){return async(e,a)=>{let t=e.command.replace(/^\/+/,"");if(!za(t))return;let r=O();$a(a,r??Wa(t,e.arguments))}}var Ma=async(e)=>{let a=L(e);return a("info","Flow v4 plugin initialized."),await We(ze(),a),{config:rt(e),tool:bt(e),"command.execute.before":Ba(),"experimental.chat.system.transform":Na(e),"experimental.session.compacting":async(t,r)=>{let o=O();if(o)r.context=[...r.context??[],o];let i=await kt(e);if(!i)return;r.context=[...r.context??[],i]}}},Ga=Ma;export{Ga as default};
1488
+
1489
+ //# debugId=9EBCD1F72682C69264756E2164756E21