opencode-plugin-flow 4.1.7 → 4.1.9

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
@@ -1,164 +1,4 @@
1
- var U=`# Review rubric
2
-
3
- Use this to decide whether a \`featureReview\` or \`finalReview\` payload may pass.
4
-
5
- ## Finding classes
6
-
7
- - **correctness**: wrong result, broken state transition, bad edge case, race, data loss, or crash.
8
- - **contract**: public API, CLI, config, persisted data, or documented behavior changed without plan approval.
9
- - **security/privacy**: unsafe input handling, secret exposure, permission bypass, or insecure default.
10
- - **test-coverage**: behavioral change lacks a check strong enough for the risk.
11
- - **maintainability**: complexity or coupling creates concrete future-change risk.
12
- - **ui/accessibility**: user cannot complete the workflow, layout breaks, accessibility basics fail, or visual claims lack evidence.
13
-
14
- ## Severity
15
-
16
- - **blocking**: must fail the review. Includes incorrect behavior, data loss, security risk, unverifiable completion claims, missing validation for behavioral work, or unresolved scope drift.
17
- - **advisory**: worth noting but does not block the current goal.
18
-
19
- If unsure whether a finding is real, read more or downgrade it. Do not promote guesses to blockers.
20
-
21
- ## Feature review checklist
22
-
23
- - The work matches the active feature's \`summary\`, \`targets\`, and dependencies.
24
- - Plan \`requirements\` and \`decisions\` are still honored.
25
- - Changed files were read, not just summarized.
26
- - Validation evidence covers the behavior touched.
27
- - New tests or manual checks would fail or visibly differ without the change where practical.
28
- - No unrelated scope slipped in.
29
- - Public contracts and downstream callers still work.
30
-
31
- ## Final review checklist
32
-
33
- - Every feature is complete and together they satisfy the original goal.
34
- - Broad validation ran and passed.
35
- - The final \`reviewDepth\` equals the approved \`finalReviewPolicy\`; the only final-review enum values are \`broad\` and \`detailed\`.
36
- - Feature-level reviews have no unresolved blocking findings.
37
- - Docs, commands, package metadata, and release surfaces match the delivered behavior.
38
- - Remaining gaps are explicit and do not contradict \`kind: "completed"\`.
39
-
40
- ## Payloads
41
-
42
- Feature review:
43
-
44
- \`\`\`json
45
- {
46
- "status": "passed",
47
- "summary": "Reviewed changed runtime files and focused tests; validation covers the new gate.",
48
- "blockingFindings": []
49
- }
50
- \`\`\`
51
-
52
- Failed feature review:
53
-
54
- \`\`\`json
55
- {
56
- "status": "failed",
57
- "summary": "Validation does not exercise the changed persistence path.",
58
- "blockingFindings": [
59
- {
60
- "summary": "No test covers archive removal of .flow/session.json after close.",
61
- "severity": "blocking"
62
- }
63
- ]
64
- }
65
- \`\`\`
66
-
67
- Final review:
68
-
69
- \`\`\`json
70
- {
71
- "status": "passed",
72
- "summary": "Reviewed plan scope, all changed files, broad validation, and release metadata.",
73
- "blockingFindings": [],
74
- "reviewDepth": "detailed"
75
- }
76
- \`\`\`
77
-
78
- ## Audit report reviews
79
-
80
- When reviewing a findings report, verify findings adversarially:
81
-
82
- - Check the cited file and surrounding code.
83
- - Trace mitigating paths before accepting blocking severity.
84
- - Confirm the deployment model used for severity.
85
- - Dedupe overlapping findings.
86
- - Downgrade or reject findings that do not survive refutation.
87
-
88
- Approve only on evidence actually inspected. A review is a claim of coverage, not a courtesy stamp.
89
- `;var j=`---
90
- name: flow-review
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
- ---
93
-
94
- # Flow Review
95
-
96
- Use this skill for review. The reviewer is usually read-only and does not mutate Flow state. The manager records the returned review payload inside \`flow_feature_complete\`.
97
-
98
- If Flow tools, required Flow skills, or required references are unavailable or
99
- stale, perform an advisory review and say that no Flow-gated review payload was
100
- recorded.
101
-
102
- ## Start
103
-
104
- - Call \`flow_status\` when available.
105
- - Identify whether this is a feature review or final review.
106
- - Read the approved plan fields relevant to the work: \`requirements\`, \`decisions\`, feature \`targets\`, feature \`validation\`, and dependencies.
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.
111
- - Load \`references/review-rubric.md\` for severity, depth, and payload shape.
112
-
113
- ## Feature Review Depth
114
-
115
- - **quick**: docs, comments, config-only changes, or mechanical changes fully covered by tooling.
116
- - **standard**: default feature review. Read every changed file and relevant tests.
117
- - **detailed**: risky behavior, persistence, security, cross-module refactors, migrations, releases, or weak validation.
118
-
119
- \`quick\` and \`standard\` are feature-review depth descriptions only. Final reviews use \`reviewDepth: "broad"\` or \`"detailed"\` to match the plan's \`finalReviewPolicy\`; these runtime enum values are the canonical final-review terms. Claim only the depth actually performed. Missing evidence is a finding, not a nuisance.
120
-
121
- ## Output
122
-
123
- For a feature review, return:
124
-
125
- \`\`\`json
126
- {
127
- "status": "passed",
128
- "summary": "what was reviewed and why it is acceptable",
129
- "blockingFindings": []
130
- }
131
- \`\`\`
132
-
133
- For a final review, return:
134
-
135
- \`\`\`json
136
- {
137
- "status": "passed",
138
- "summary": "session-level review summary",
139
- "blockingFindings": [],
140
- "reviewDepth": "detailed"
141
- }
142
- \`\`\`
143
-
144
- Use \`status: "failed"\` when any blocking finding remains. Advisory findings may be included in the prose summary, but \`blockingFindings\` contains only blockers.
145
-
146
- ## Special cases
147
-
148
- - Cleanup/refactor: load \`flow-deslop\`; verify the smell was real, refutation paths were checked, and behavior was preserved. If unavailable, record a coverage gap instead of approving cleanup claims.
149
- - UI/frontend: load \`flow-ui-quality\`; verify state coverage and visual evidence when a local target was available. If unavailable, record a coverage gap and do not claim visual polish was verified.
150
- - Audit reports: use \`flow-run/references/audit-rubric.md\`; findings must survive refutation before they can drive fix features.
151
- - Large reviews: use \`../flow/references/parallel-orchestration.md\` for
152
- read-only slices by changed-file group, risk lens, or validation surface.
153
- Use the named review, audit, evidence, or validation agents from that
154
- reference instead of generic subagents. Apply its handoff format and
155
- verification gates; only the manager returns the final \`featureReview\` or
156
- \`finalReview\` payload.
157
-
158
- Never approve to unblock completion, fix findings in the review pass, or vouch for validation you did not inspect.
159
- `;var Ft=["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(`
160
-
161
- `),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 _t={"flow-reviewer":{mode:"subagent",hidden:!0,description:"Internal read-only reviewer for Flow-guided work.",prompt:Ft,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"}}},Q={"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 It(){return{agent:Object.fromEntries(Object.entries(_t).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(Q).map(([e,a])=>[e,{...a}]))}}function fe(e){let a=It();e.agent={...e.agent??{},...a.agent},e.command={...e.command??{},...a.command}}import{createHash as Jt}from"node:crypto";import{mkdir as Kt,readdir as Er,readFile as Lt,rm as Or,writeFile as q}from"node:fs/promises";import{createRequire as Qt}from"node:module";import{dirname as Xt,join as P,normalize as Yt,sep as Ht}from"node:path";var me=`# Flow worker handoff contract
1
+ var R=`# Flow worker handoff contract
162
2
 
163
3
  Flow managers merge only the worker's final response. Treat that response as the
164
4
  worker report of record: it must include the assigned scope, what was actually
@@ -277,7 +117,7 @@ live-verified | test-verified | type-check-only | not-verified
277
117
 
278
118
  The manager must inspect and validate any candidate patch before recording Flow
279
119
  completion.
280
- `;var he=`# Parallel orchestration
120
+ `;var S=`# Parallel orchestration
281
121
 
282
122
  Use fan-out when Flow work is broad enough that independent workers can gather
283
123
  evidence faster than one linear pass. The manager still owns the Flow session:
@@ -406,7 +246,7 @@ Start a follow-up wave when first-wave handoffs reveal:
406
246
 
407
247
  Do not recurse by default. If a worker says it needs another worker, the manager
408
248
  decides whether that is a second wave and writes the next bounded prompt.
409
- `;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
249
+ `;var G='# 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 _=`# Verification gates
410
250
 
411
251
  Verification is how Flow keeps parallel work from turning into parallel
412
252
  guesswork. Worker handoffs are candidate evidence; the manager decides what can
@@ -496,7 +336,7 @@ Before presenting or recording the result:
496
336
 
497
337
  \`Status: success\` only says the worker believes its slice is done. The manager
498
338
  still checks coverage and evidence before trusting the result.
499
- `;var we=`---
339
+ `;var V=`---
500
340
  name: flow
501
341
  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.
502
342
  ---
@@ -568,297 +408,65 @@ Planning and running require loaded Flow tools; do not simulate plan approval or
568
408
  - Unknown runtime error: read \`summary\` and \`recovery\`; see \`references/recovery-playbook.md\` for common cases.
569
409
 
570
410
  Never fabricate validation output, backfill review approval you did not perform, or close as \`deferred\`/\`abandoned\` merely to avoid an unfinished-work blocker.
571
- `;var ye=`---
572
- name: flow-commit
573
- 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.
574
- ---
411
+ `;var j=`# Parallel discovery
575
412
 
576
- # Flow Commit
577
-
578
- Use this skill only when the user asks to prepare or create a commit, write a
579
- commit message, stage intended work, or validate staged changes before
580
- committing. It is not part of the autonomous Flow loop and must not be loaded
581
- automatically by \`flow\`, \`flow-run\`, or \`flow_feature_complete\`.
413
+ 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.
582
414
 
583
- When a Flow session exists, a commit never substitutes for Flow completion. The
584
- manager still records validation and review evidence through
585
- \`flow_feature_complete\` before claiming a Flow feature is done. Default to commit
586
- preparation only after \`flow_feature_complete\` has recorded the relevant
587
- completion evidence. If the user explicitly asks for a WIP commit, preserve
588
- failing or incomplete validation context in the message.
415
+ For broad waves, also load \`../../flow/references/parallel-orchestration.md\`.
416
+ Use its pre-fan-out coverage gate and
417
+ \`../../flow/references/handoff-format.md\` response shapes.
589
418
 
590
- ## Boundaries
419
+ ## Good slices
591
420
 
592
- - Preserve unrelated user work.
593
- - Stage explicit paths or hunks only. Do not default to \`git add .\` or
594
- \`git add -A\`.
595
- - Do not commit \`.flow/**\` state unless the maintainer explicitly asks to
596
- archive those exact files.
597
- - Do not push, amend, rebase, squash, reset, force-push, tag, release, publish,
598
- or mutate remote state unless the user explicitly authorizes that exact
599
- operation.
600
- - Stop before committing secrets, local config, credentials, private keys,
601
- generated release artifacts, or suspicious environment files.
602
- - Stop when validation fails unless the user explicitly wants an unfinished WIP
603
- commit and the commit message says so.
421
+ - Independent modules or packages.
422
+ - Frontend route and backend endpoint pairs.
423
+ - Test, CI, and release surfaces.
424
+ - Risk lenses such as security, persistence, accessibility, migration, or performance.
425
+ - Documentation and operator-contract checks.
604
426
 
605
- ## Inspect
427
+ ## Flow repo default slices
606
428
 
607
- Start with the worktree and intent:
429
+ For this repository, good first-wave slices are:
608
430
 
609
- 1. Run \`git status --short\`.
610
- 2. Inspect unstaged and staged changes separately with \`git diff\` and
611
- \`git diff --cached\`.
612
- 3. Inspect untracked files before deciding whether they belong.
613
- 4. Group changes by intent, feature, and risk. Prefer one coherent commit over
614
- one large mixed commit.
615
- 5. Identify exclusions: unrelated files, local notes, \`.flow/**\`, generated
616
- artifacts, logs, caches, credentials, and temporary outputs.
431
+ - Runtime gates: \`src/runtime/schema.ts\`, \`src/runtime/transitions.ts\`,
432
+ \`src/runtime/api.ts\`, and \`tests/runtime-gates.test.ts\`.
433
+ - Workspace persistence: \`src/runtime/workspace.ts\`,
434
+ \`src/runtime/json/strict-object.ts\`, and
435
+ \`tests/workspace-persistence.test.ts\`.
436
+ - OpenCode adapter surface: \`src/adapters/opencode/**\`, \`src/config-shared.ts\`,
437
+ \`src/config.ts\`, \`src/index.ts\`, and surface tests.
438
+ - Distribution and synced skills: \`src/distribution/**\`, \`src/cli.ts\`,
439
+ \`skills/**\`, and distribution tests.
440
+ - CI, package, and release contract: \`.github/workflows/**\`, \`package.json\`,
441
+ \`bun.lock\`, \`README.md\`, and \`CHANGELOG.md\`.
442
+ - Docs and operator contract: \`docs/**\`, \`README.md\`, and skill references.
617
443
 
618
- If the commit boundary is unclear, propose the boundary and ask before staging.
444
+ ## Coverage gate
619
445
 
620
- ## Stage
446
+ Before spawning workers, state the total discovery scope and one line per slice.
447
+ For countable scopes, confirm that slice counts add back to the total and that
448
+ there are no overlaps, gaps, or empty slices. If the scope is not countable,
449
+ state the completeness rule, such as "all changed files plus callers."
621
450
 
622
- Stage only the intended boundary:
451
+ ## Worker prompt
623
452
 
624
- - Use explicit file paths for whole-file staging.
625
- - Use patch staging for mixed-intent files.
626
- - Re-run \`git status --short\` and \`git diff --cached --stat\` after staging.
627
- - Review the full staged diff before validation and commit.
453
+ \`\`\`text
454
+ Inspect <slice> for <goal>. Read-only. Do not edit files or call Flow tools.
455
+ Return the evidence/review/validation/audit handoff shape from ../../flow/references/handoff-format.md.
456
+ \`\`\`
628
457
 
629
- Never undo or rewrite user changes to make staging easier. If a file contains
630
- mixed user and agent work, either stage selected hunks or ask for direction.
458
+ For validation-oriented discovery:
631
459
 
632
- ## Screen and Validate
460
+ \`\`\`text
461
+ Inspect <slice> for validation risk. Read-only. Do not edit files or call Flow
462
+ tools. You may report commands that should be run, and include raw output only
463
+ for commands you actually ran. Return the evidence/review/validation/audit
464
+ handoff shape from ../../flow/references/handoff-format.md.
465
+ \`\`\`
633
466
 
634
- Before commit creation, check the staged diff for:
467
+ ## Synthesis
635
468
 
636
- - Secrets, tokens, private keys, credentials, cookies, and unredacted personal
637
- data.
638
- - \`.env\`, local config, machine-specific paths, and editor files.
639
- - \`.flow/**\` state.
640
- - Generated artifacts that are not normally versioned.
641
- - Package or version metadata drift unrelated to the requested change.
642
-
643
- When this repository-local contribution preflight exists, defer to it for staged
644
- and outgoing validation instead of duplicating its checks:
645
-
646
- \`\`\`bash
647
- .agents/skills/flow-contribution-check/scripts/preflight.sh commit
648
- \`\`\`
649
-
650
- Run it after staging and rerun it after any staging change. The preflight
651
- validates staged or outgoing work; it does not choose commit boundaries or write
652
- commit messages. If the script is absent, use the repository's documented commit
653
- preflight from package scripts, AGENTS/docs, or CI guidance.
654
-
655
- Use the repository's documented broad validation gate when a full local check is
656
- appropriate, such as package scripts, AGENTS/docs, or CI guidance. Use narrower
657
- tests only when the user has asked for a lighter pass or when the change is
658
- intentionally not ready for the broad gate.
659
-
660
- ## Message
661
-
662
- Propose a commit message that reflects the staged diff:
663
-
664
- - Subject: imperative, specific, and scoped.
665
- - Body when useful: context, changed areas, validation run, and remaining risk.
666
- - Do not mention unstaged or excluded work as if it were included.
667
- - Include WIP or failing-validation context only when the user explicitly chose
668
- that path.
669
-
670
- ## Create Commit
671
-
672
- Create the commit only after the user explicitly asks for commit creation or has
673
- already authorized it in the current request.
674
-
675
- Before running \`git commit\`, report:
676
-
677
- - Staged paths.
678
- - Excluded dirty or untracked paths.
679
- - Validation command and result.
680
- - Proposed message.
681
- - Any risks or gaps.
682
-
683
- After a successful commit, report the commit hash and leave push or release
684
- actions for a separate explicit request.
685
- `;var be=`# Safe refactor workflow
686
-
687
- Refactoring is a behavior-preserving sequence of small changes. This workflow keeps cleanup from becoming an unreviewable rewrite.
688
-
689
- ## Before editing
690
-
691
- - Define the invariant: what behavior, API, schema, command, state path, or visual output must remain unchanged.
692
- - Locate callers and tests before changing the target. If there is no test coverage, add or run the narrowest check that proves current behavior.
693
- - Identify the smallest reversible move: remove dead code, rename, extract, inline, move, consolidate, or split phase.
694
- - Choose a validation command that can fail for the behavior you might break.
695
-
696
- ## During editing
697
-
698
- - Make one structural move at a time, then re-run the relevant check when risk is non-trivial.
699
- - Prefer deleting or inlining a useless layer before introducing a new one.
700
- - Keep names domain-specific. Generic names like \`manager\`, \`processor\`, \`utils\`, and \`helper\` are suspect unless the repo already owns that vocabulary.
701
- - Avoid mixed commits inside a feature: no unrelated formatting, package churn, comment rewrites, or style sweeps.
702
- - If the refactor uncovers a behavior bug, stop and replan unless the approved feature already includes fixing that bug.
703
-
704
- ## Validation evidence
705
-
706
- Good cleanup evidence includes:
707
-
708
- - focused tests for behavior touched by the refactor.
709
- - typecheck/lint/build output for mechanical structure changes.
710
- - before/after references for deleted exports, commands, generated files, and docs when static search is not enough.
711
- - broad validation when shared abstractions, public APIs, persistence, or cross-feature integration changed.
712
-
713
- Weak evidence includes:
714
-
715
- - "No tests needed" for behavior-adjacent refactors.
716
- - tests that were edited to match the new shape but do not prove the old behavior.
717
- - scanner metrics without human inspection.
718
- - green tests after changing unrelated surfaces not covered by those tests.
719
-
720
- ## Review checklist
721
-
722
- - Every changed artifact maps to the approved cleanup scope.
723
- - The new structure has fewer reasons to change, not just fewer lines.
724
- - Public contracts and compatibility shims remain intact or were explicitly planned.
725
- - Deleted code is actually unreachable or obsolete.
726
- - Validation can catch a realistic mistake in the refactor.
727
- `;var ke=`# Deslop smell rubric
728
-
729
- Use this rubric to turn vague cleanup instincts into reviewable findings.
730
-
731
- ## Actionable smell classes
732
-
733
- - **duplication** — repeated logic or conditionals that must change together. Confirm whether small repetition is clearer than abstraction.
734
- - **bloat** — long function, large class/module, or oversized component whose responsibilities are mixed enough to hide behavior.
735
- - **speculative generality** — unused extension points, factories, options, interfaces, or configuration added for imagined futures.
736
- - **dead code** — unreachable branches, unused exports, stale flags, abandoned helpers, obsolete tests, or comments describing code that no longer exists.
737
- - **primitive obsession** — stringly typed modes, loosely shaped objects, or magic literals that obscure a domain constraint already present elsewhere.
738
- - **shotgun surgery** — one conceptual change requires scattered edits across unrelated modules.
739
- - **feature envy / misplaced responsibility** — code repeatedly reaches into another module's internals instead of using the owning boundary.
740
- - **message chains / excessive delegation** — call chains or wrappers that add no policy and make behavior harder to locate.
741
- - **agent slop** — verbose scaffolding, duplicate defensive branches, generic helper layers, temporary flags, commented-out code, debug output, or invented patterns that do not match the repo.
742
- - **test-oracle slop** — tests that assert implementation trivia, snapshots of noisy markup, or mocks that make broken behavior pass.
743
-
744
- ## Non-smells until proven
745
-
746
- - Repetition that makes two workflows intentionally independent.
747
- - Framework-required shape, generated code, migration history, compatibility shims, or public API affordances.
748
- - Verbose guards protecting data loss, security, lifecycle ordering, or error observability.
749
- - Logging/metrics that operators or tests rely on.
750
- - Local style differences already accepted by the repo and not hurting changeability.
751
-
752
- ## Finding shape
753
-
754
- Each blocking cleanup finding should carry:
755
-
756
- \`\`\`text
757
- class; severity; location; evidence read; refutation checked; why it matters; safe fix shape; validation command
758
- \`\`\`
759
-
760
- 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.
761
- `;var xe=`---
762
- name: flow-deslop
763
- 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.
764
- ---
765
-
766
- # Flow deslop
767
-
768
- Use this skill when the Flow work is about improving code quality rather than adding a new user-visible feature. The job is to make the code easier to change without changing behavior unless the approved plan explicitly says behavior changes.
769
-
770
- ## Ground the cleanup
771
-
772
- - Start from concrete evidence: duplicated code, unnecessary abstraction, long or tangled functions, dead branches, confusing ownership, repeated conditionals, excessive coupling, or validation gaps that hide maintainability risk.
773
- - Load \`references/smell-rubric.md\` when classifying findings or deciding what is worth fixing.
774
- - Load \`references/refactor-workflow.md\` before implementing or reviewing non-trivial cleanup.
775
- - Treat scanner output, metrics, and model impressions as candidates only. A smell becomes actionable after reading the surrounding code, callers, tests, and relevant contracts.
776
- - Record cleanup context in existing Flow plan fields: \`requirements\`, \`decisions\`, feature \`targets\`, and feature \`validation\`. Do not invent new Flow payload fields.
777
-
778
- ## Plan cleanup work
779
-
780
- - Prefer one feature per validated cleanup theme with a clear validation story. "Clean the whole repo" starts with a review-first feature that produces evidence-backed findings, then fix features for confirmed clusters.
781
- - Keep refactors small and behavior-preserving. If a cleanup requires behavior change, surface it as product scope and replan.
782
- - State what will not be cleaned. Broad cleanup without boundaries invites churn and makes review impossible.
783
- - Choose validation before editing: focused tests for affected behavior, typecheck/lint for mechanical changes, and a broad gate when cleanup spans shared abstractions.
784
-
785
- ## Execute cleanup safely
786
-
787
- - Preserve public APIs, persisted data, command names, tool names, and observable behavior unless the approved plan explicitly changes them.
788
- - Prefer removal, consolidation, naming, and local extraction before new abstractions. New abstractions must reduce real duplication or clarify an existing boundary.
789
- - Delete dead code only after checking references, exports, generated entrypoints, docs, tests, and runtime/distribution paths that static search may miss.
790
- - Keep every change tied to a finding or plan target. Opportunistic style edits are out of scope.
791
-
792
- ## Review cleanup claims
793
-
794
- For each claimed smell removal, verify:
795
-
796
- - **location** — the changed code and the original smell were actually read.
797
- - **impact** — the change reduces duplication, coupling, complexity, or future-change risk in a concrete way.
798
- - **refutation checked** — apparent smell was not intentional compatibility, performance, generated code, framework convention, or a safety guard.
799
- - **behavior preserved** — tests or other evidence cover the behavior touched.
800
- - **blast radius** — public contracts and downstream callers still work.
801
-
802
- Never approve cleanup because it "looks cleaner" without evidence. Tests passing is necessary but not sufficient when the refactor changes structure across files.
803
- `;var Re=`# Parallel discovery
804
-
805
- 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.
806
-
807
- For broad waves, also load \`../../flow/references/parallel-orchestration.md\`.
808
- Use its pre-fan-out coverage gate and
809
- \`../../flow/references/handoff-format.md\` response shapes.
810
-
811
- ## Good slices
812
-
813
- - Independent modules or packages.
814
- - Frontend route and backend endpoint pairs.
815
- - Test, CI, and release surfaces.
816
- - Risk lenses such as security, persistence, accessibility, migration, or performance.
817
- - Documentation and operator-contract checks.
818
-
819
- ## Flow repo default slices
820
-
821
- For this repository, good first-wave slices are:
822
-
823
- - Runtime gates: \`src/runtime/schema.ts\`, \`src/runtime/transitions.ts\`,
824
- \`src/runtime/api.ts\`, and \`tests/runtime-gates.test.ts\`.
825
- - Workspace persistence: \`src/runtime/workspace.ts\`,
826
- \`src/runtime/json/strict-object.ts\`, and
827
- \`tests/workspace-persistence.test.ts\`.
828
- - OpenCode adapter surface: \`src/adapters/opencode/**\`, \`src/config-shared.ts\`,
829
- \`src/config.ts\`, \`src/index.ts\`, and surface tests.
830
- - Distribution and synced skills: \`src/distribution/**\`, \`src/cli.ts\`,
831
- \`skills/**\`, and distribution tests.
832
- - CI, package, and release contract: \`.github/workflows/**\`, \`package.json\`,
833
- \`bun.lock\`, \`README.md\`, and \`CHANGELOG.md\`.
834
- - Docs and operator contract: \`docs/**\`, \`README.md\`, and skill references.
835
-
836
- ## Coverage gate
837
-
838
- Before spawning workers, state the total discovery scope and one line per slice.
839
- For countable scopes, confirm that slice counts add back to the total and that
840
- there are no overlaps, gaps, or empty slices. If the scope is not countable,
841
- state the completeness rule, such as "all changed files plus callers."
842
-
843
- ## Worker prompt
844
-
845
- \`\`\`text
846
- Inspect <slice> for <goal>. Read-only. Do not edit files or call Flow tools.
847
- Return the evidence/review/validation/audit handoff shape from ../../flow/references/handoff-format.md.
848
- \`\`\`
849
-
850
- For validation-oriented discovery:
851
-
852
- \`\`\`text
853
- Inspect <slice> for validation risk. Read-only. Do not edit files or call Flow
854
- tools. You may report commands that should be run, and include raw output only
855
- for commands you actually ran. Return the evidence/review/validation/audit
856
- handoff shape from ../../flow/references/handoff-format.md.
857
- \`\`\`
858
-
859
- ## Synthesis
860
-
861
- Convert only evidence-backed work into plan fields:
469
+ Convert only evidence-backed work into plan fields:
862
470
 
863
471
  - \`requirements\`: user promises and externally visible acceptance criteria.
864
472
  - \`decisions\`: architecture boundaries, rejected approaches, and scope cuts.
@@ -866,7 +474,7 @@ Convert only evidence-backed work into plan fields:
866
474
  - feature \`validation\`: checks expected to prove the feature.
867
475
 
868
476
  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.
869
- `;var Fe=`# Planning examples
477
+ `;var q=`# Planning examples
870
478
 
871
479
  ## Rate limiting feature set
872
480
 
@@ -951,7 +559,7 @@ Better plan:
951
559
  - Validation that only says "manual testing".
952
560
  - Targets that name the entire repo.
953
561
  - Features with hidden dependencies instead of \`dependsOn\`.
954
- `;var _e=`---
562
+ `;var E=`---
955
563
  name: flow-plan
956
564
  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.
957
565
  ---
@@ -1016,12 +624,170 @@ Use only \`finalReviewPolicy: "broad"\` or \`"detailed"\`. These are the canonic
1016
624
  integration, browser/e2e, package/build, docs/static, cleanup preservation, or
1017
625
  broad project gate.
1018
626
 
1019
- ## Approval
627
+ ## Approval
628
+
629
+ 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.
630
+
631
+ See \`references/planning-examples.md\` for payload examples and decomposition anti-patterns.
632
+ `;var I=`# Review rubric
633
+
634
+ Use this to decide whether a \`featureReview\` or \`finalReview\` payload may pass.
635
+
636
+ ## Finding classes
637
+
638
+ - **correctness**: wrong result, broken state transition, bad edge case, race, data loss, or crash.
639
+ - **contract**: public API, CLI, config, persisted data, or documented behavior changed without plan approval.
640
+ - **security/privacy**: unsafe input handling, secret exposure, permission bypass, or insecure default.
641
+ - **test-coverage**: behavioral change lacks a check strong enough for the risk.
642
+ - **maintainability**: complexity or coupling creates concrete future-change risk.
643
+ - **ui/accessibility**: user cannot complete the workflow, layout breaks, accessibility basics fail, or visual claims lack evidence.
644
+
645
+ ## Severity
646
+
647
+ - **blocking**: must fail the review. Includes incorrect behavior, data loss, security risk, unverifiable completion claims, missing validation for behavioral work, or unresolved scope drift.
648
+ - **advisory**: worth noting but does not block the current goal.
649
+
650
+ If unsure whether a finding is real, read more or downgrade it. Do not promote guesses to blockers.
651
+
652
+ ## Feature review checklist
653
+
654
+ - The work matches the active feature's \`summary\`, \`targets\`, and dependencies.
655
+ - Plan \`requirements\` and \`decisions\` are still honored.
656
+ - Changed files were read, not just summarized.
657
+ - Validation evidence covers the behavior touched.
658
+ - New tests or manual checks would fail or visibly differ without the change where practical.
659
+ - No unrelated scope slipped in.
660
+ - Public contracts and downstream callers still work.
661
+
662
+ ## Final review checklist
663
+
664
+ - Every feature is complete and together they satisfy the original goal.
665
+ - Broad validation ran and passed.
666
+ - The final \`reviewDepth\` equals the approved \`finalReviewPolicy\`; the only final-review enum values are \`broad\` and \`detailed\`.
667
+ - Feature-level reviews have no unresolved blocking findings.
668
+ - Docs, commands, package metadata, and release surfaces match the delivered behavior.
669
+ - Remaining gaps are explicit and do not contradict \`kind: "completed"\`.
670
+
671
+ ## Payloads
672
+
673
+ Feature review:
674
+
675
+ \`\`\`json
676
+ {
677
+ "status": "passed",
678
+ "summary": "Reviewed changed runtime files and focused tests; validation covers the new gate.",
679
+ "blockingFindings": []
680
+ }
681
+ \`\`\`
682
+
683
+ Failed feature review:
684
+
685
+ \`\`\`json
686
+ {
687
+ "status": "failed",
688
+ "summary": "Validation does not exercise the changed persistence path.",
689
+ "blockingFindings": [
690
+ {
691
+ "summary": "No test covers archive removal of .flow/session.json after close.",
692
+ "severity": "blocking"
693
+ }
694
+ ]
695
+ }
696
+ \`\`\`
697
+
698
+ Final review:
699
+
700
+ \`\`\`json
701
+ {
702
+ "status": "passed",
703
+ "summary": "Reviewed plan scope, all changed files, broad validation, and release metadata.",
704
+ "blockingFindings": [],
705
+ "reviewDepth": "detailed"
706
+ }
707
+ \`\`\`
708
+
709
+ ## Audit report reviews
710
+
711
+ When reviewing a findings report, verify findings adversarially:
712
+
713
+ - Check the cited file and surrounding code.
714
+ - Trace mitigating paths before accepting blocking severity.
715
+ - Confirm the deployment model used for severity.
716
+ - Dedupe overlapping findings.
717
+ - Downgrade or reject findings that do not survive refutation.
718
+
719
+ Approve only on evidence actually inspected. A review is a claim of coverage, not a courtesy stamp.
720
+ `;var C=`---
721
+ name: flow-review
722
+ 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.
723
+ ---
724
+
725
+ # Flow Review
726
+
727
+ Use this skill for review. The reviewer is usually read-only and does not mutate Flow state. The manager records the returned review payload inside \`flow_feature_complete\`.
728
+
729
+ If Flow tools, required Flow skills, or required references are unavailable or
730
+ stale, perform an advisory review and say that no Flow-gated review payload was
731
+ recorded.
732
+
733
+ ## Start
734
+
735
+ - Call \`flow_status\` when available.
736
+ - Identify whether this is a feature review or final review.
737
+ - Read the approved plan fields relevant to the work: \`requirements\`, \`decisions\`, feature \`targets\`, feature \`validation\`, and dependencies.
738
+ - Inspect the actual diff, changed files, tests, and validation output. Do not review only the completion summary.
739
+ - Load \`flow-test\` for validation-heavy, regression-sensitive, browser/UI, or
740
+ unclear coverage reviews. If it is unavailable, record a coverage gap and
741
+ treat missing validation evidence as a gap or blocker based on user impact.
742
+ - Load \`references/review-rubric.md\` for severity, depth, and payload shape.
743
+
744
+ ## Feature Review Depth
745
+
746
+ - **quick**: docs, comments, config-only changes, or mechanical changes fully covered by tooling.
747
+ - **standard**: default feature review. Read every changed file and relevant tests.
748
+ - **detailed**: risky behavior, persistence, security, cross-module refactors, migrations, releases, or weak validation.
749
+
750
+ \`quick\` and \`standard\` are feature-review depth descriptions only. Final reviews use \`reviewDepth: "broad"\` or \`"detailed"\` to match the plan's \`finalReviewPolicy\`; these runtime enum values are the canonical final-review terms. Claim only the depth actually performed. Missing evidence is a finding, not a nuisance.
751
+
752
+ ## Output
753
+
754
+ For a feature review, return:
755
+
756
+ \`\`\`json
757
+ {
758
+ "status": "passed",
759
+ "summary": "what was reviewed and why it is acceptable",
760
+ "blockingFindings": []
761
+ }
762
+ \`\`\`
763
+
764
+ For a final review, return:
765
+
766
+ \`\`\`json
767
+ {
768
+ "status": "passed",
769
+ "summary": "session-level review summary",
770
+ "blockingFindings": [],
771
+ "reviewDepth": "detailed"
772
+ }
773
+ \`\`\`
774
+
775
+ Use \`status: "failed"\` when any blocking finding remains. Advisory findings may be included in the prose summary, but \`blockingFindings\` contains only blockers.
1020
776
 
1021
- 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.
777
+ ## Special cases
1022
778
 
1023
- See \`references/planning-examples.md\` for payload examples and decomposition anti-patterns.
1024
- `;var Ie=`# Audit findings rubric
779
+ - Cleanup/refactor: load \`flow-deslop\`; verify the smell was real, refutation paths were checked, and behavior was preserved. If unavailable, record a coverage gap instead of approving cleanup claims.
780
+ - UI/frontend: load \`flow-ui-quality\`; verify state coverage and visual evidence when a local target was available. If unavailable, record a coverage gap and do not claim visual polish was verified.
781
+ - Audit reports: use \`flow-run/references/audit-rubric.md\`; findings must survive refutation before they can drive fix features.
782
+ - Large reviews: use \`../flow/references/parallel-orchestration.md\` for
783
+ read-only slices by changed-file group, risk lens, or validation surface.
784
+ Use the named review, audit, evidence, or validation agents from that
785
+ reference instead of generic subagents. Apply its handoff format and
786
+ verification gates; only the manager returns the final \`featureReview\` or
787
+ \`finalReview\` payload.
788
+
789
+ Never approve to unblock completion, fix findings in the review pass, or vouch for validation you did not inspect.
790
+ `;var z=`# Audit findings rubric
1025
791
 
1026
792
  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.
1027
793
 
@@ -1074,7 +840,7 @@ follow-up order — correctness and persisted/user-input surfaces first
1074
840
  \`\`\`
1075
841
 
1076
842
  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.
1077
- `;var Se=`# Validation evidence rubric
843
+ `;var N=`# Validation evidence rubric
1078
844
 
1079
845
  Use this before recording \`flow_feature_complete\`.
1080
846
 
@@ -1131,7 +897,7 @@ Broad validation usually means the repo's full check command, full relevant test
1131
897
  - If validation needs external access, missing credentials, or ambiguous user input, record \`status: "needs_input"\` with an honest \`outcome\`.
1132
898
 
1133
899
  Never trim failing output, relabel a failed command as passed, or use "not run" as completion evidence.
1134
- `;var Pe=`---
900
+ `;var $=`---
1135
901
  name: flow-run
1136
902
  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.
1137
903
  ---
@@ -1218,7 +984,247 @@ Complete with:
1218
984
  \`\`\`
1219
985
 
1220
986
  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.
987
+ `;function K(e){return e.map((a)=>`## Bundled ${a.label}
988
+
989
+ ${a.content}`).join(`
990
+
991
+ `)}var Se=K([{label:"flow-review/SKILL.md",content:C},{label:"flow-review/references/review-rubric.md",content:I}]),Nt=K([{label:"flow-plan/SKILL.md",content:E},{label:"flow-plan/references/planning-examples.md",content:q},{label:"flow-plan/references/parallel-discovery.md",content:j},{label:"flow/references/parallel-orchestration.md",content:S},{label:"flow/references/handoff-format.md",content:R},{label:"flow/references/verification-gates.md",content:_}]),$t=K([{label:"flow-run/SKILL.md",content:$},{label:"flow-run/references/validation-rubric.md",content:N},{label:"flow-run/references/audit-rubric.md",content:z},{label:"flow/references/parallel-orchestration.md",content:S},{label:"flow/references/handoff-format.md",content:R},{label:"flow/references/verification-gates.md",content:_},{label:"flow-review/SKILL.md",content:C},{label:"flow-review/references/review-rubric.md",content:I}]),Ot=K([{label:"flow/SKILL.md",content:V},{label:"flow/references/recovery-playbook.md",content:G},{label:"flow/references/parallel-orchestration.md",content:S},{label:"flow/references/handoff-format.md",content:R},{label:"flow/references/verification-gates.md",content:_},{label:"flow-plan/SKILL.md",content:E},{label:"flow-plan/references/planning-examples.md",content:q},{label:"flow-plan/references/parallel-discovery.md",content:j},{label:"flow-run/SKILL.md",content:$},{label:"flow-run/references/validation-rubric.md",content:N},{label:"flow-run/references/audit-rubric.md",content:z},{label:"flow-review/SKILL.md",content:C},{label:"flow-review/references/review-rubric.md",content:I}]),Wt=["Call `flow_status` first. If the result includes `setup.skills`, report the setup status and continue with the bundled public Flow command instructions below.","Do not call native Flow skills for `flow`, `flow-plan`, `flow-run`, or `flow-review` from public Flow commands. In bundled sections, `load` means read and use the corresponding bundled section in this command, and missing native public Flow skills are not blockers.","Optional helper skills (`flow-test`, `flow-deslop`, `flow-ui-quality`, and user-triggered `flow-commit`) are not bundled fallbacks. If one is unavailable, record the coverage gap exactly as the bundled instructions require."].join(" ");function Q(e,a,t){return[Wt,`Run the bundled ${e} instructions below. ${a}`,"",t].join(`
992
+
993
+ `)}var Dt=Q("Flow auto","Drive the Flow loop until completion or a real blocker: $ARGUMENTS",Ot),Bt=Q("Flow plan","Plan: $ARGUMENTS",Nt),Jt=Q("Flow run","Execute the next approved feature. $ARGUMENTS",$t),Gt=Q("Flow review","Review: $ARGUMENTS",Se),Vt=["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","",Se].join(`
994
+
995
+ `),Kt="Call flow_status and report the session state and next action.",Qt=Vt,O={"flow-auto":Dt,"flow-plan":Bt,"flow-run":Jt,"flow-review":Gt,"flow-status":Kt},Xt={"flow-reviewer":{mode:"subagent",hidden:!0,description:"Internal read-only reviewer for Flow-guided work.",prompt:Qt,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:O["flow-auto"]},"flow-plan":{description:"Create or approve a Flow plan",template:O["flow-plan"]},"flow-run":{description:"Run one approved Flow feature",template:O["flow-run"]},"flow-review":{description:"Run a read-only Flow review",agent:"flow-reviewer",subtask:!0,template:O["flow-review"]},"flow-status":{description:"Inspect the active Flow session",template:O["flow-status"]}};function Yt(){return{agent:Object.fromEntries(Object.entries(Xt).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 _e(e){let a=Yt();e.agent={...e.agent??{},...a.agent},e.command={...e.command??{},...a.command}}import{createHash as oa}from"node:crypto";import{mkdir as na,readdir as co,readFile as sa,rm as lo,writeFile as Y}from"node:fs/promises";import{createRequire as ia}from"node:module";import{dirname as ca,join as W,normalize as la,sep as da}from"node:path";var Ie=`---
996
+ name: flow-commit
997
+ 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.
998
+ ---
999
+
1000
+ # Flow Commit
1001
+
1002
+ Use this skill only when the user asks to prepare or create a commit, write a
1003
+ commit message, stage intended work, or validate staged changes before
1004
+ committing. It is not part of the autonomous Flow loop and must not be loaded
1005
+ automatically by \`flow\`, \`flow-run\`, or \`flow_feature_complete\`.
1006
+
1007
+ When a Flow session exists, a commit never substitutes for Flow completion. The
1008
+ manager still records validation and review evidence through
1009
+ \`flow_feature_complete\` before claiming a Flow feature is done. Default to commit
1010
+ preparation only after \`flow_feature_complete\` has recorded the relevant
1011
+ completion evidence. If the user explicitly asks for a WIP commit, preserve
1012
+ failing or incomplete validation context in the message.
1013
+
1014
+ ## Boundaries
1015
+
1016
+ - Preserve unrelated user work.
1017
+ - Stage explicit paths or hunks only. Do not default to \`git add .\` or
1018
+ \`git add -A\`.
1019
+ - Do not commit \`.flow/**\` state unless the maintainer explicitly asks to
1020
+ archive those exact files.
1021
+ - Do not push, amend, rebase, squash, reset, force-push, tag, release, publish,
1022
+ or mutate remote state unless the user explicitly authorizes that exact
1023
+ operation.
1024
+ - Stop before committing secrets, local config, credentials, private keys,
1025
+ generated release artifacts, or suspicious environment files.
1026
+ - Stop when validation fails unless the user explicitly wants an unfinished WIP
1027
+ commit and the commit message says so.
1028
+
1029
+ ## Inspect
1030
+
1031
+ Start with the worktree and intent:
1032
+
1033
+ 1. Run \`git status --short\`.
1034
+ 2. Inspect unstaged and staged changes separately with \`git diff\` and
1035
+ \`git diff --cached\`.
1036
+ 3. Inspect untracked files before deciding whether they belong.
1037
+ 4. Group changes by intent, feature, and risk. Prefer one coherent commit over
1038
+ one large mixed commit.
1039
+ 5. Identify exclusions: unrelated files, local notes, \`.flow/**\`, generated
1040
+ artifacts, logs, caches, credentials, and temporary outputs.
1041
+
1042
+ If the commit boundary is unclear, propose the boundary and ask before staging.
1043
+
1044
+ ## Stage
1045
+
1046
+ Stage only the intended boundary:
1047
+
1048
+ - Use explicit file paths for whole-file staging.
1049
+ - Use patch staging for mixed-intent files.
1050
+ - Re-run \`git status --short\` and \`git diff --cached --stat\` after staging.
1051
+ - Review the full staged diff before validation and commit.
1052
+
1053
+ Never undo or rewrite user changes to make staging easier. If a file contains
1054
+ mixed user and agent work, either stage selected hunks or ask for direction.
1055
+
1056
+ ## Screen and Validate
1057
+
1058
+ Before commit creation, check the staged diff for:
1059
+
1060
+ - Secrets, tokens, private keys, credentials, cookies, and unredacted personal
1061
+ data.
1062
+ - \`.env\`, local config, machine-specific paths, and editor files.
1063
+ - \`.flow/**\` state.
1064
+ - Generated artifacts that are not normally versioned.
1065
+ - Package or version metadata drift unrelated to the requested change.
1066
+
1067
+ When this repository-local contribution preflight exists, defer to it for staged
1068
+ and outgoing validation instead of duplicating its checks:
1069
+
1070
+ \`\`\`bash
1071
+ .agents/skills/flow-contribution-check/scripts/preflight.sh commit
1072
+ \`\`\`
1073
+
1074
+ Run it after staging and rerun it after any staging change. The preflight
1075
+ validates staged or outgoing work; it does not choose commit boundaries or write
1076
+ commit messages. If the script is absent, use the repository's documented commit
1077
+ preflight from package scripts, AGENTS/docs, or CI guidance.
1078
+
1079
+ Use the repository's documented broad validation gate when a full local check is
1080
+ appropriate, such as package scripts, AGENTS/docs, or CI guidance. Use narrower
1081
+ tests only when the user has asked for a lighter pass or when the change is
1082
+ intentionally not ready for the broad gate.
1083
+
1084
+ ## Message
1085
+
1086
+ Propose a commit message that reflects the staged diff:
1087
+
1088
+ - Subject: imperative, specific, and scoped.
1089
+ - Body when useful: context, changed areas, validation run, and remaining risk.
1090
+ - Do not mention unstaged or excluded work as if it were included.
1091
+ - Include WIP or failing-validation context only when the user explicitly chose
1092
+ that path.
1093
+
1094
+ ## Create Commit
1095
+
1096
+ Create the commit only after the user explicitly asks for commit creation or has
1097
+ already authorized it in the current request.
1098
+
1099
+ Before running \`git commit\`, report:
1100
+
1101
+ - Staged paths.
1102
+ - Excluded dirty or untracked paths.
1103
+ - Validation command and result.
1104
+ - Proposed message.
1105
+ - Any risks or gaps.
1106
+
1107
+ After a successful commit, report the commit hash and leave push or release
1108
+ actions for a separate explicit request.
1109
+ `;var Ce=`# Safe refactor workflow
1110
+
1111
+ Refactoring is a behavior-preserving sequence of small changes. This workflow keeps cleanup from becoming an unreviewable rewrite.
1112
+
1113
+ ## Before editing
1114
+
1115
+ - Define the invariant: what behavior, API, schema, command, state path, or visual output must remain unchanged.
1116
+ - Locate callers and tests before changing the target. If there is no test coverage, add or run the narrowest check that proves current behavior.
1117
+ - Identify the smallest reversible move: remove dead code, rename, extract, inline, move, consolidate, or split phase.
1118
+ - Choose a validation command that can fail for the behavior you might break.
1119
+
1120
+ ## During editing
1121
+
1122
+ - Make one structural move at a time, then re-run the relevant check when risk is non-trivial.
1123
+ - Prefer deleting or inlining a useless layer before introducing a new one.
1124
+ - Keep names domain-specific. Generic names like \`manager\`, \`processor\`, \`utils\`, and \`helper\` are suspect unless the repo already owns that vocabulary.
1125
+ - Avoid mixed commits inside a feature: no unrelated formatting, package churn, comment rewrites, or style sweeps.
1126
+ - If the refactor uncovers a behavior bug, stop and replan unless the approved feature already includes fixing that bug.
1127
+
1128
+ ## Validation evidence
1129
+
1130
+ Good cleanup evidence includes:
1131
+
1132
+ - focused tests for behavior touched by the refactor.
1133
+ - typecheck/lint/build output for mechanical structure changes.
1134
+ - before/after references for deleted exports, commands, generated files, and docs when static search is not enough.
1135
+ - broad validation when shared abstractions, public APIs, persistence, or cross-feature integration changed.
1136
+
1137
+ Weak evidence includes:
1138
+
1139
+ - "No tests needed" for behavior-adjacent refactors.
1140
+ - tests that were edited to match the new shape but do not prove the old behavior.
1141
+ - scanner metrics without human inspection.
1142
+ - green tests after changing unrelated surfaces not covered by those tests.
1143
+
1144
+ ## Review checklist
1145
+
1146
+ - Every changed artifact maps to the approved cleanup scope.
1147
+ - The new structure has fewer reasons to change, not just fewer lines.
1148
+ - Public contracts and compatibility shims remain intact or were explicitly planned.
1149
+ - Deleted code is actually unreachable or obsolete.
1150
+ - Validation can catch a realistic mistake in the refactor.
1151
+ `;var Pe=`# Deslop smell rubric
1152
+
1153
+ Use this rubric to turn vague cleanup instincts into reviewable findings.
1154
+
1155
+ ## Actionable smell classes
1156
+
1157
+ - **duplication** — repeated logic or conditionals that must change together. Confirm whether small repetition is clearer than abstraction.
1158
+ - **bloat** — long function, large class/module, or oversized component whose responsibilities are mixed enough to hide behavior.
1159
+ - **speculative generality** — unused extension points, factories, options, interfaces, or configuration added for imagined futures.
1160
+ - **dead code** — unreachable branches, unused exports, stale flags, abandoned helpers, obsolete tests, or comments describing code that no longer exists.
1161
+ - **primitive obsession** — stringly typed modes, loosely shaped objects, or magic literals that obscure a domain constraint already present elsewhere.
1162
+ - **shotgun surgery** — one conceptual change requires scattered edits across unrelated modules.
1163
+ - **feature envy / misplaced responsibility** — code repeatedly reaches into another module's internals instead of using the owning boundary.
1164
+ - **message chains / excessive delegation** — call chains or wrappers that add no policy and make behavior harder to locate.
1165
+ - **agent slop** — verbose scaffolding, duplicate defensive branches, generic helper layers, temporary flags, commented-out code, debug output, or invented patterns that do not match the repo.
1166
+ - **test-oracle slop** — tests that assert implementation trivia, snapshots of noisy markup, or mocks that make broken behavior pass.
1167
+
1168
+ ## Non-smells until proven
1169
+
1170
+ - Repetition that makes two workflows intentionally independent.
1171
+ - Framework-required shape, generated code, migration history, compatibility shims, or public API affordances.
1172
+ - Verbose guards protecting data loss, security, lifecycle ordering, or error observability.
1173
+ - Logging/metrics that operators or tests rely on.
1174
+ - Local style differences already accepted by the repo and not hurting changeability.
1175
+
1176
+ ## Finding shape
1177
+
1178
+ Each blocking cleanup finding should carry:
1179
+
1180
+ \`\`\`text
1181
+ class; severity; location; evidence read; refutation checked; why it matters; safe fix shape; validation command
1182
+ \`\`\`
1183
+
1184
+ 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.
1221
1185
  `;var Ae=`---
1186
+ name: flow-deslop
1187
+ 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.
1188
+ ---
1189
+
1190
+ # Flow deslop
1191
+
1192
+ Use this skill when the Flow work is about improving code quality rather than adding a new user-visible feature. The job is to make the code easier to change without changing behavior unless the approved plan explicitly says behavior changes.
1193
+
1194
+ ## Ground the cleanup
1195
+
1196
+ - Start from concrete evidence: duplicated code, unnecessary abstraction, long or tangled functions, dead branches, confusing ownership, repeated conditionals, excessive coupling, or validation gaps that hide maintainability risk.
1197
+ - Load \`references/smell-rubric.md\` when classifying findings or deciding what is worth fixing.
1198
+ - Load \`references/refactor-workflow.md\` before implementing or reviewing non-trivial cleanup.
1199
+ - Treat scanner output, metrics, and model impressions as candidates only. A smell becomes actionable after reading the surrounding code, callers, tests, and relevant contracts.
1200
+ - Record cleanup context in existing Flow plan fields: \`requirements\`, \`decisions\`, feature \`targets\`, and feature \`validation\`. Do not invent new Flow payload fields.
1201
+
1202
+ ## Plan cleanup work
1203
+
1204
+ - Prefer one feature per validated cleanup theme with a clear validation story. "Clean the whole repo" starts with a review-first feature that produces evidence-backed findings, then fix features for confirmed clusters.
1205
+ - Keep refactors small and behavior-preserving. If a cleanup requires behavior change, surface it as product scope and replan.
1206
+ - State what will not be cleaned. Broad cleanup without boundaries invites churn and makes review impossible.
1207
+ - Choose validation before editing: focused tests for affected behavior, typecheck/lint for mechanical changes, and a broad gate when cleanup spans shared abstractions.
1208
+
1209
+ ## Execute cleanup safely
1210
+
1211
+ - Preserve public APIs, persisted data, command names, tool names, and observable behavior unless the approved plan explicitly changes them.
1212
+ - Prefer removal, consolidation, naming, and local extraction before new abstractions. New abstractions must reduce real duplication or clarify an existing boundary.
1213
+ - Delete dead code only after checking references, exports, generated entrypoints, docs, tests, and runtime/distribution paths that static search may miss.
1214
+ - Keep every change tied to a finding or plan target. Opportunistic style edits are out of scope.
1215
+
1216
+ ## Review cleanup claims
1217
+
1218
+ For each claimed smell removal, verify:
1219
+
1220
+ - **location** — the changed code and the original smell were actually read.
1221
+ - **impact** — the change reduces duplication, coupling, complexity, or future-change risk in a concrete way.
1222
+ - **refutation checked** — apparent smell was not intentional compatibility, performance, generated code, framework convention, or a safety guard.
1223
+ - **behavior preserved** — tests or other evidence cover the behavior touched.
1224
+ - **blast radius** — public contracts and downstream callers still work.
1225
+
1226
+ Never approve cleanup because it "looks cleaner" without evidence. Tests passing is necessary but not sufficient when the refactor changes structure across files.
1227
+ `;var Te=`---
1222
1228
  name: flow-test
1223
1229
  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.
1224
1230
  ---
@@ -1342,7 +1348,7 @@ covered. Static inspection alone is a gap for behavioral changes.
1342
1348
 
1343
1349
  Never relabel a failed command as passed, invent output, or use "not run" as
1344
1350
  completion evidence.
1345
- `;var Ce=`# UI quality rubric
1351
+ `;var Ue=`# UI quality rubric
1346
1352
 
1347
1353
  Use this rubric for frontend planning, implementation, and review.
1348
1354
 
@@ -1386,7 +1392,7 @@ class; severity; location or screenshot area; evidence inspected; user impact; f
1386
1392
  \`\`\`
1387
1393
 
1388
1394
  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.
1389
- `;var Te=`# Visual verification workflow
1395
+ `;var je=`# Visual verification workflow
1390
1396
 
1391
1397
  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.
1392
1398
 
@@ -1426,7 +1432,7 @@ Record the reason and use the strongest available substitute:
1426
1432
  - code inspection against existing component patterns.
1427
1433
 
1428
1434
  Do not claim visual polish was verified if no visual artifact was inspected.
1429
- `;var Ue=`---
1435
+ `;var qe=`---
1430
1436
  name: flow-ui-quality
1431
1437
  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.
1432
1438
  ---
@@ -1474,12 +1480,14 @@ Approve only when the interface is both useful and inspectable:
1474
1480
  - Screenshot/browser evidence supports the claim whenever feasible.
1475
1481
 
1476
1482
  Never approve a UI change based only on code shape. If users will judge it visually, Flow evidence should include visual inspection.
1477
- `;var X=[{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:_e},{relativePath:"references/planning-examples.md",content:Fe},{relativePath:"references/parallel-discovery.md",content:Re}]},{name:"flow-run",files:[{relativePath:"SKILL.md",content:Pe},{relativePath:"references/validation-rubric.md",content:Se},{relativePath:"references/audit-rubric.md",content:Ie}]},{name:"flow-test",files:[{relativePath:"SKILL.md",content:Ae}]},{name:"flow-review",files:[{relativePath:"SKILL.md",content:j},{relativePath:"references/review-rubric.md",content:U}]},{name:"flow-deslop",files:[{relativePath:"SKILL.md",content:xe},{relativePath:"references/smell-rubric.md",content:ke},{relativePath:"references/refactor-workflow.md",content:be}]},{name:"flow-ui-quality",files:[{relativePath:"SKILL.md",content:Ue},{relativePath:"references/ui-rubric.md",content:Ce},{relativePath:"references/visual-verification.md",content:Te}]},{name:"flow-commit",files:[{relativePath:"SKILL.md",content:ye}]}];var Zt=".flow-skill-version",v=null;function Z(){return process.env.HOME??process.env.USERPROFILE??""}function qe(e=Z()){return P(e,".config","opencode","skills")}function Ee(e){return Jt("sha256").update(e).digest("hex")}function Y(e,a){return[`version=${a}`,...e.files.map((t)=>`file=${t.relativePath} sha256=${Ee(t.content)}`),""].join(`
1478
- `)}async function H(e){try{return await Lt(e,"utf8")}catch(a){if(a.code==="ENOENT")return null;throw a}}function ea(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=Yt(P(e,...a.split("/")));if(t!==e&&t.startsWith(`${e}${Ht}`))return t;throw Error(`Unsafe skill file path '${a}'.`)}async function ta(e,a,t){let r=P(t,e.name),o=P(r,Zt),i=await H(o),s=ea(i);if(await H(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 S=je(r,R.relativePath),T=await H(S);if(T===R.content)continue;p=!0;let ue=s.get(R.relativePath);if(T!==null&&(ue?Ee(T)!==ue:i!==null))await q(`${S}.backup`,T,"utf8"),de=!0}if(!p&&i===Y(e,a))return{name:e.name,action:"unchanged"};if(!p)return await q(o,Y(e,a),"utf8"),{name:e.name,action:"marker_updated"};let kt=i!==null;for(let R of e.files){let S=je(r,R.relativePath);await Kt(Xt(S),{recursive:!0}),await q(S,R.content,"utf8")}return await q(o,Y(e,a),"utf8"),{name:e.name,action:de?"updated_with_backup":kt?"updated":"installed"}}function Oe(){return X.map((e)=>e.name)}function aa(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 ${De(e)} for repair guidance.`:"Flow skills are synced.";return{status:i,version:e,root:a,checkedAt:new Date().toISOString(),expectedSkills:Oe(),results:t,changedSkills:r,actionRequiredSkills:o,restartRequired:i==="restart_required",summary:s}}function ra(e,a,t){let r=t instanceof Error?t.message:String(t);return{status:"error",version:e,root:a,checkedAt:new Date().toISOString(),expectedSkills:Oe(),results:[],changedSkills:[],actionRequiredSkills:[],restartRequired:!1,summary:`Flow skill sync failed: ${r}`,error:r}}function De(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 \`${De(a.version)}\` for details.`].join(`
1479
- `)}function Ne(){if(process.env.npm_package_version)return process.env.npm_package_version;try{let e=Qt(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 oa(e,a=Z()){let t=qe(a);return Promise.all(X.map((r)=>ta(r,e,t)))}async function ze(e,a,t=Z()){let r=qe(t);try{let o=await oa(e,t);v=aa(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=ra(e,r,o),a("warn",v.summary)}}import{randomUUID as pa}from"node:crypto";import{mkdir as $,open as Ge,readFile as Qe,rename as fa,rm as B,writeFile as Je}from"node:fs/promises";import{homedir as ma}from"node:os";import{dirname as Ke,isAbsolute as Lr,join as F,parse as ha,resolve as Xe}from"node:path";import{setTimeout as ga}from"node:timers/promises";function na(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 We(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=na(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]+)*$/,A="Feature ids must be lowercase kebab-case",$e=n.enum(["pending","in_progress","completed","blocked"]),ia=n.enum(["planning","ready","running","blocked","completed"]),sa=n.enum(["passed","failed"]),ca=n.enum(["passed","failed"]),te=n.enum(["targeted","broad"]),ne=n.enum(["broad","detailed"]),la=n.object({summary:n.string().min(1),severity:n.enum(["blocking","advisory"]).default("blocking")}).strict(),O=n.object({status:sa,summary:n.string().min(1),blockingFindings:n.array(la).default([])}).strict(),ae=O.extend({reviewDepth:ne}).strict(),re=n.object({command:n.string().min(1),status:ca,summary:n.string().min(1)}).strict(),oe=n.object({path:n.string().min(1)}).strict(),Be=n.object({id:n.string().regex(w,A),title:n.string().min(1),summary:n.string().min(1),status:$e.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(),Ve=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(Be).min(1)}).strict(),D=Ve.omit({features:!0}).extend({finalReviewPolicy:ne.optional(),features:n.array(Be.omit({status:!0}).extend({status:$e.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)}),Me=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(),da=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(),N=n.discriminatedUnion("status",[n.object({status:n.literal("ok"),featureId:n.string().regex(w,A),summary:n.string().min(1),artifactsChanged:n.array(oe).default([]),validationRun:n.array(re).default([]),validationScope:te,featureReview:O,finalReview:ae.optional(),outcome:Me.optional()}).strict(),n.object({status:n.literal("needs_input"),featureId:n.string().regex(w,A),summary:n.string().min(1),artifactsChanged:n.array(oe).default([]),validationRun:n.array(re).default([]),validationScope:te.optional(),featureReview:O.optional(),finalReview:ae.optional(),outcome:da}).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".'})}),ua=n.object({featureId:n.string().regex(w,A),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:O.optional(),finalReview:ae.optional(),outcome:Me.optional()}).strict(),z=n.object({version:n.literal(2),id:n.string().min(1),goal:n.string().min(1),status:ia,approval:n.enum(["pending","approved"]),plan:Ve.nullable(),activeFeatureId:n.string().regex(w,A).nullable(),history:n.array(ua).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 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=Xe(a);return ha(t).root===t?null:t}function M(e){let a=ie(e);if(!a)throw new V("Flow requires a non-root workspace path.");if(a===Xe(process.env.HOME??ma()))throw new V("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 V("Flow could not resolve a workspace root from tool context.");return M(a)}function G(e){return F(e,".flow")}function se(e){return F(G(e),"session.json")}function He(e){return F(G(e),"history")}function va(e,a){if(!/^[a-zA-Z0-9_-]+$/.test(a))throw Error("Invalid session id.");return F(He(e),`${a}.json`)}async function Ze(e,a){await $(Ke(e),{recursive:!0});let t=`${e}.${process.pid}.${pa()}.tmp`,r=await Ge(t,"w");try{await r.writeFile(a,"utf8"),await r.sync()}catch(i){throw await r.close(),await B(t,{force:!0}),i}await r.close();try{await fa(t,e)}catch(i){throw await B(t,{force:!0}),i}let o=await Ge(Ke(e),"r");try{await o.sync()}finally{await o.close()}}var W=new Map,wa=30000,ya=25;async function ba(e){let a=G(e),t=F(a,"session.lock"),r=Date.now();while(!0)try{return await $(t,{recursive:!1}),async()=>{await B(t,{recursive:!0,force:!0})}}catch(o){let i=o.code;if(i==="ENOENT"){await $(a,{recursive:!0});continue}if(i!=="EEXIST")throw o;if(Date.now()-r>wa)throw Error(`Timed out waiting for Flow session lock at ${t}.`);await ga(ya)}}async function et(e,a){let t=W.get(e)??Promise.resolve(),r=()=>{},o=new Promise((c)=>{r=c}),i=t.catch(()=>{return}).then(()=>o);W.set(e,i);let s=null;try{return await t.catch(()=>{return}),s=await ba(e),await a()}finally{try{await s?.()}finally{if(r(),W.get(e)===i)W.delete(e)}}}async function C(e){let a=M(e),t;try{t=await Qe(se(a),"utf8")}catch(o){if(o.code==="ENOENT")return null;throw o}let r=We(t,"Flow session file");if(!r.ok)throw Error(r.error);return z.parse(r.value)}async function y(e,a){let t=M(e),r=z.parse(a);return await Ze(se(t),`${JSON.stringify(r,null,2)}
1480
- `),await tt(t),r}async function ce(e,a){let t=M(e);await $(He(t),{recursive:!0}),await Ze(va(t,a.id),`${JSON.stringify(z.parse(a),null,2)}
1481
- `),await B(se(t),{force:!0}),await tt(t)}var Le=["session.json","history/","session.lock/",".gitignore",""].join(`
1482
- `);async function tt(e){let a=F(G(e),".gitignore");try{if((await Qe(a,"utf8")).trim()==="session.lock/")await Je(a,Le,"utf8")}catch(t){if(t.code!=="ENOENT")throw t;await Je(a,Le,"utf8")}}function at(e){return async(a)=>{fe(a)}}function J(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 xa}from"node:crypto";var ka=null;function h(){return ka?.()??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 Ra(e){let a=D.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 Fa(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:xa(),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 nt(e,a){if(e.approval==="approved"||e.status!=="planning")return l("Approved plans cannot be changed. Reset or start a new session.");let t=Ra(a),r=Fa(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 it(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 rt(e,a){return e.status==="pending"&&e.dependsOn.every((t)=>a.has(t))}function _a(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(!rt(i,t))return l(`Feature '${a}' has incomplete dependencies.`);return u(i)}let o=e.find((i)=>rt(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 st(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=_a(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 ot(e){return e.status==="passed"&&e.blockingFindings.length===0}function Ia(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 Sa(e,a){let t=Ia(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(!ot(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(!ot(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 ct(e,a){if(!e.plan||e.status!=="running"||!e.activeFeatureId)return l("No feature is currently running.");let t=N.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=Sa(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 Pa(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 lt(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=Pa(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 dt(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:Aa(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 Aa(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 Ca=f.object({goal:f.string().trim().min(1).optional(),plan:D.optional()}).strict(),Ta=f.object({featureId:f.string().min(1).optional()}).strict(),Ua=f.object({featureId:f.string().min(1)}).strict(),ja=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 I(e,a){return et(e,async()=>a(await C(e)))}async function ut(e){return k(await C(e))}async function pt(e,a){let t=Ca.parse(a??{});return I(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?nt(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 ft(e){return I(e,async(a)=>{if(!a)return{status:"missing_session",summary:"No active Flow session exists.",nextAction:"/flow-plan <goal>"};let t=it(a);if(!t.ok)return _(t);let r=await y(e,t.value);return{...k(r),status:"ok",summary:"Flow plan approved."}})}async function mt(e,a){let t=Ta.parse(a??{});return I(e,async(r)=>{if(!r)return{status:"missing_session",summary:"No active Flow session exists.",nextAction:"/flow-plan <goal>"};let o=st(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 ht(e,a){let t=N.parse(a??{});return I(e,async(r)=>{if(!r)return{status:"missing_session",summary:"No active Flow session exists.",nextAction:"/flow-plan <goal>"};let o=ct(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 gt(e,a){let t=Ua.parse(a??{});return I(e,async(r)=>{if(!r)return{status:"missing_session",summary:"No active Flow session exists.",nextAction:"/flow-plan <goal>"};let o=lt(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 vt(e,a){let t=ja.parse(a??{});return I(e,async(r)=>{if(!r)return{status:"missing_session",summary:"No active Flow session exists.",nextAction:"/flow-plan <goal>"};let o=dt(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 wt(e){return JSON.stringify(e,null,2)}function qa(e){return wt({status:"error",summary:e instanceof Error?e.message:String(e)})}async function x(e,a){try{return wt(await a(Ye(e)))}catch(t){return qa(t)}}async function Ea(e){let a=await ut(e),t=ee();if(!t)return a;return{...a,setup:{skills:t}}}function yt(e){return J(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,Ea)}),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)=>pt(r,a))}),flow_plan_approve:m({description:"Approve the current draft Flow plan",args:{},execute:(a,t)=>x(t,ft)}),flow_run_start:m({description:"Start the next runnable approved Flow feature",args:{featureId:d.string().optional()},execute:(a,t)=>x(t,(r)=>mt(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)=>ht(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)=>gt(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)=>vt(r,a))})}}async function bt(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(`
1483
- `)}catch{return null}}function Oa(e){return async(a,t)=>{let r=E();if(r)t.system.push(r);let o=await bt(e);if(o)t.system.push(o)}}function Da(){let e=new Set(Object.keys(Q));return async(a,t)=>{let r=a.command.replace(/^\/+/,"");if(!e.has(r))return;let o=E();if(!o)return;t.parts.push({type:"text",text:o,synthetic:!0})}}var Na=async(e)=>{let a=J(e);return a("info","Flow v4 plugin initialized."),await ze(Ne(),a),{config:at(e),tool:yt(e),"command.execute.before":Da(),"experimental.chat.system.transform":Oa(e),"experimental.session.compacting":async(t,r)=>{let o=E();if(o)r.context=[...r.context??[],o];let i=await bt(e);if(!i)return;r.context=[...r.context??[],i]}}},za=Na;export{za as default};
1484
-
1485
- //# debugId=58DD13EF10CCB89B64756E2164756E21
1483
+ `;var le=[{name:"flow",files:[{relativePath:"SKILL.md",content:V},{relativePath:"references/recovery-playbook.md",content:G},{relativePath:"references/parallel-orchestration.md",content:S},{relativePath:"references/handoff-format.md",content:R},{relativePath:"references/verification-gates.md",content:_}]},{name:"flow-plan",files:[{relativePath:"SKILL.md",content:E},{relativePath:"references/planning-examples.md",content:q},{relativePath:"references/parallel-discovery.md",content:j}]},{name:"flow-run",files:[{relativePath:"SKILL.md",content:$},{relativePath:"references/validation-rubric.md",content:N},{relativePath:"references/audit-rubric.md",content:z}]},{name:"flow-test",files:[{relativePath:"SKILL.md",content:Te}]},{name:"flow-review",files:[{relativePath:"SKILL.md",content:C},{relativePath:"references/review-rubric.md",content:I}]},{name:"flow-deslop",files:[{relativePath:"SKILL.md",content:Ae},{relativePath:"references/smell-rubric.md",content:Pe},{relativePath:"references/refactor-workflow.md",content:Ce}]},{name:"flow-ui-quality",files:[{relativePath:"SKILL.md",content:qe},{relativePath:"references/ui-rubric.md",content:Ue},{relativePath:"references/visual-verification.md",content:je}]},{name:"flow-commit",files:[{relativePath:"SKILL.md",content:Ie}]}];var ua=".flow-skill-version",v=null;function pe(){return process.env.HOME??process.env.USERPROFILE??""}function ze(e=pe()){return W(e,".config","opencode","skills")}function Ne(e){return oa("sha256").update(e).digest("hex")}function de(e,a){return[`version=${a}`,...e.files.map((t)=>`file=${t.relativePath} sha256=${Ne(t.content)}`),""].join(`
1484
+ `)}async function ue(e){try{return await sa(e,"utf8")}catch(a){if(a.code==="ENOENT")return null;throw a}}function pa(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 Ee(e,a){let t=la(W(e,...a.split("/")));if(t!==e&&t.startsWith(`${e}${da}`))return t;throw Error(`Unsafe skill file path '${a}'.`)}async function fa(e,a,t){let r=W(t,e.name),o=W(r,ua),s=await ue(o),i=pa(s);if(await ue(W(r,"SKILL.md"))!==null&&s===null)return{name:e.name,action:"skipped_foreign"};let p=!1,Fe=!1;for(let F of e.files){let U=Ee(r,F.relativePath),J=await ue(U);if(J===F.content)continue;p=!0;let Re=i.get(F.relativePath);if(J!==null&&(Re?Ne(J)!==Re:s!==null))await Y(`${U}.backup`,J,"utf8"),Fe=!0}if(!p&&s===de(e,a))return{name:e.name,action:"unchanged"};if(!p)return await Y(o,de(e,a),"utf8"),{name:e.name,action:"marker_updated"};let Ft=s!==null;for(let F of e.files){let U=Ee(r,F.relativePath);await na(ca(U),{recursive:!0}),await Y(U,F.content,"utf8")}return await Y(o,de(e,a),"utf8"),{name:e.name,action:Fe?"updated_with_backup":Ft?"updated":"installed"}}function $e(){return le.map((e)=>e.name)}function ma(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),s=o.length>0?"action_required":r.length>0?"restart_required":"ok",i=s==="restart_required"?`Flow installed or updated skills during this startup (${r.join(", ")}). Restart OpenCode before loading Flow skills.`:s==="action_required"?`Flow found user-owned skill folders for managed skills (${o.join(", ")}). Run ${Oe(e)} for repair guidance.`:"Flow skills are synced.";return{status:s,version:e,root:a,checkedAt:new Date().toISOString(),expectedSkills:$e(),results:t,changedSkills:r,actionRequiredSkills:o,restartRequired:s==="restart_required",summary:i}}function ha(e,a,t){let r=t instanceof Error?t.message:String(t);return{status:"error",version:e,root:a,checkedAt:new Date().toISOString(),expectedSkills:$e(),results:[],changedSkills:[],actionRequiredSkills:[],restartRequired:!1,summary:`Flow skill sync failed: ${r}`,error:r}}function Oe(e){return`npx -y opencode-plugin-flow@${e} doctor`}function fe(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 M(e=v){let a=fe(e);if(!a)return null;return["Flow setup warning:",a.summary,`Skills root: ${a.root}`,`Use \`${Oe(a.version)}\` for details.`].join(`
1485
+ `)}function We(){if(process.env.npm_package_version)return process.env.npm_package_version;try{let e=ia(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 ga(e,a=pe()){let t=ze(a);return Promise.all(le.map((r)=>fa(r,e,t)))}async function De(e,a,t=pe()){let r=ze(t);try{let o=await ga(e,t);v=ma(e,r,o);let s=o.filter((i)=>i.action==="installed"||i.action==="updated"||i.action==="updated_with_backup");if(s.length>0)a("info",`Flow synced skills (${s.map((i)=>`${i.name}:${i.action}`).join(", ")}). Restart OpenCode if skills were just installed.`);if(v.status==="action_required")a("warn",v.summary)}catch(o){v=ha(e,r,o),a("warn",v.summary)}}import{randomUUID as Ra}from"node:crypto";import{mkdir as ae,open as Qe,readFile as He,rename as Sa,rm as re,writeFile as Xe}from"node:fs/promises";import{homedir as _a}from"node:os";import{dirname as Ye,isAbsolute as xo,join as P,parse as Ia,resolve as Ze}from"node:path";import{setTimeout as Ca}from"node:timers/promises";function va(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 s=a.at(-1);if(s?.isObject&&s.awaitingKey){let i=JSON.parse(e.slice(t,o+1));if(s.keys.has(i))return i;s.keys.add(i)}t=o+1;continue}t+=1}return null}function Be(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=va(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]+)*$/,D="Feature ids must be lowercase kebab-case",Je=n.enum(["pending","in_progress","completed","blocked"]),wa=n.enum(["planning","ready","running","blocked","completed"]),ya=n.enum(["passed","failed"]),ba=n.enum(["passed","failed"]),me=n.enum(["targeted","broad"]),we=n.enum(["broad","detailed"]),ka=n.object({summary:n.string().min(1),severity:n.enum(["blocking","advisory"]).default("blocking")}).strict(),H=n.object({status:ya,summary:n.string().min(1),blockingFindings:n.array(ka).default([])}).strict(),he=H.extend({reviewDepth:we}).strict(),ge=n.object({command:n.string().min(1),status:ba,summary:n.string().min(1)}).strict(),ve=n.object({path:n.string().min(1)}).strict(),Ge=n.object({id:n.string().regex(w,D),title:n.string().min(1),summary:n.string().min(1),status:Je.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(),Ve=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:we.default("detailed"),features:n.array(Ge).min(1)}).strict(),Z=Ve.omit({features:!0}).extend({finalReviewPolicy:we.optional(),features:n.array(Ge.omit({status:!0}).extend({status:Je.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)}),Ke=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(),xa=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(),L=n.discriminatedUnion("status",[n.object({status:n.literal("ok"),featureId:n.string().regex(w,D),summary:n.string().min(1),artifactsChanged:n.array(ve).default([]),validationRun:n.array(ge).default([]),validationScope:me,featureReview:H,finalReview:he.optional(),outcome:Ke.optional()}).strict(),n.object({status:n.literal("needs_input"),featureId:n.string().regex(w,D),summary:n.string().min(1),artifactsChanged:n.array(ve).default([]),validationRun:n.array(ge).default([]),validationScope:me.optional(),featureReview:H.optional(),finalReview:he.optional(),outcome:xa}).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,D),status:n.enum(["completed","blocked","needs_input"]),summary:n.string().min(1),recordedAt:n.string().min(1),artifactsChanged:n.array(ve).default([]),validationRun:n.array(ge).default([]),validationScope:me.optional(),featureReview:H.optional(),finalReview:he.optional(),outcome:Ke.optional()}).strict(),ee=n.object({version:n.literal(2),id:n.string().min(1),goal:n.string().min(1),status:wa,approval:n.enum(["pending","approved"]),plan:Ve.nullable(),activeFeatureId:n.string().regex(w,D).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 oe extends Error{code="INVALID_FLOW_WORKSPACE_ROOT";constructor(e){super(e);this.name="InvalidFlowWorkspaceRootError"}}function ye(e){let a=e?.trim();if(!a)return null;let t=Ze(a);return Ia(t).root===t?null:t}function ne(e){let a=ye(e);if(!a)throw new oe("Flow requires a non-root workspace path.");if(a===Ze(process.env.HOME??_a()))throw new oe("Flow refuses to use $HOME itself as a mutable workspace root.");return a}function Le(e){let a=ye(e.worktree)??ye(e.directory);if(!a)throw new oe("Flow could not resolve a workspace root from tool context.");return ne(a)}function se(e){return P(e,".flow")}function be(e){return P(se(e),"session.json")}function et(e){return P(se(e),"history")}function Pa(e,a){if(!/^[a-zA-Z0-9_-]+$/.test(a))throw Error("Invalid session id.");return P(et(e),`${a}.json`)}async function tt(e,a){await ae(Ye(e),{recursive:!0});let t=`${e}.${process.pid}.${Ra()}.tmp`,r=await Qe(t,"w");try{await r.writeFile(a,"utf8"),await r.sync()}catch(s){throw await r.close(),await re(t,{force:!0}),s}await r.close();try{await Sa(t,e)}catch(s){throw await re(t,{force:!0}),s}let o=await Qe(Ye(e),"r");try{await o.sync()}finally{await o.close()}}var te=new Map,Aa=30000,Ta=25;async function Ua(e){let a=se(e),t=P(a,"session.lock"),r=Date.now();while(!0)try{return await ae(t,{recursive:!1}),async()=>{await re(t,{recursive:!0,force:!0})}}catch(o){let s=o.code;if(s==="ENOENT"){await ae(a,{recursive:!0});continue}if(s!=="EEXIST")throw o;if(Date.now()-r>Aa)throw Error(`Timed out waiting for Flow session lock at ${t}.`);await Ca(Ta)}}async function at(e,a){let t=te.get(e)??Promise.resolve(),r=()=>{},o=new Promise((c)=>{r=c}),s=t.catch(()=>{return}).then(()=>o);te.set(e,s);let i=null;try{return await t.catch(()=>{return}),i=await Ua(e),await a()}finally{try{await i?.()}finally{if(r(),te.get(e)===s)te.delete(e)}}}async function B(e){let a=ne(e),t;try{t=await He(be(a),"utf8")}catch(o){if(o.code==="ENOENT")return null;throw o}let r=Be(t,"Flow session file");if(!r.ok)throw Error(r.error);return ee.parse(r.value)}async function y(e,a){let t=ne(e),r=ee.parse(a);return await tt(be(t),`${JSON.stringify(r,null,2)}
1486
+ `),await rt(t),r}async function ke(e,a){let t=ne(e);await ae(et(t),{recursive:!0}),await tt(Pa(t,a.id),`${JSON.stringify(ee.parse(a),null,2)}
1487
+ `),await re(be(t),{force:!0}),await rt(t)}var Me=["session.json","history/","session.lock/",".gitignore",""].join(`
1488
+ `);async function rt(e){let a=P(se(e),".gitignore");try{if((await He(a,"utf8")).trim()==="session.lock/")await Xe(a,Me,"utf8")}catch(t){if(t.code!=="ENOENT")throw t;await Xe(a,Me,"utf8")}}function ot(e){return async(a)=>{_e(a)}}function ie(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 qa}from"node:crypto";var ja=null;function h(){return ja?.()??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 Ea(e){let a=Z.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 za(e){let a=new Set;for(let i of e.features){if(a.has(i.id))return`Duplicate feature id '${i.id}'.`;a.add(i.id)}for(let i of e.features)for(let c of i.dependsOn){if(!a.has(c))return`Feature '${i.id}' depends on unknown feature '${c}'.`;if(c===i.id)return`Feature '${i.id}' cannot depend on itself.`}let t=new Set,r=new Set,o=new Map(e.features.map((i)=>[i.id,i]));function s(i){if(r.has(i))return!1;if(t.has(i))return!0;t.add(i);for(let c of o.get(i)?.dependsOn??[])if(s(c))return!0;return t.delete(i),r.add(i),!1}return e.features.some((i)=>s(i.id))?"Feature dependencies contain a cycle.":null}function ce(e){let a=h();return{version:2,id:qa(),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=Ea(a),r=za(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 ct(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 nt(e,a){return e.status==="pending"&&e.dependsOn.every((t)=>a.has(t))}function Na(e,a){let t=new Set(e.filter((s)=>s.status==="completed").map((s)=>s.id)),r=new Map(e.map((s)=>[s.id,s]));if(a){let s=r.get(a);if(!s)return l(`Feature '${a}' is not in the plan.`);if(s.status==="completed")return l(`Feature '${a}' is already completed.`);if(s.status!=="pending")return l(`Feature '${a}' is ${s.status} and must be reset before it can run.`);if(!nt(s,t))return l(`Feature '${a}' has incomplete dependencies.`);return u(s)}let o=e.find((s)=>nt(s,t));return o?u(o):l("No runnable feature is available.")}function xe(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 lt(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 s=e.plan.features.find((i)=>i.id===e.activeFeatureId);if(s)return u({session:e,feature:s})}return l(`Feature '${e.activeFeatureId}' is already in progress.`)}let t=Na(e.plan.features,a);if(!t.ok)return t;let r={...e.plan,features:xe(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((s)=>s.id===t.value.id)??t.value})}function st(e){return e.status==="passed"&&e.blockingFindings.length===0}function $a(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 Oa(e,a){let t=$a(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(!st(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(!st(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 dt(e,a){if(!e.plan||e.status!=="running"||!e.activeFeatureId)return l("No feature is currently running.");let t=L.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:xe(e.plan.features,t.featureId,"blocked")},history:[...e.history,p]}))}let r=Oa(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},s=xe(e.plan.features,t.featureId,"completed"),i=s.every((p)=>p.status==="completed"),c=h();return u(b({...e,status:i?"completed":"ready",activeFeatureId:null,plan:{...e.plan,features:s},history:[...e.history,o],closure:i?{kind:"completed",summary:t.summary,recordedAt:c}:null,lastError:null,timestamps:{...e.timestamps,completedAt:i?c:e.timestamps.completedAt}}))}function Wa(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((s)=>t.has(s)))t.add(o.id),r=!0}}return t}function ut(e,a){if(!e.plan)return l("There is no active plan to reset.");if(!e.plan.features.some((i)=>i.id===a))return l(`Feature '${a}' is not in the plan.`);let t=Wa(e.plan.features,a),r=e.activeFeatureId&&t.has(e.activeFeatureId)?null:e.activeFeatureId,o=e.plan.features.map((i)=>t.has(i.id)?{...i,status:"pending"}:i),s=e.approval!=="approved"?"planning":r?"running":o.some((i)=>i.status==="blocked")?"blocked":"ready";return u(b({...e,status:s,activeFeatureId:r,plan:{...e.plan,features:o},closure:null,lastError:null,timestamps:{...e.timestamps,completedAt:null}}))}function pt(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((s)=>s.status!=="completed");if(o.length>0)return l("Cannot close a Flow session as completed with unfinished features.",`Unfinished features: ${o.map((s)=>s.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((i)=>i.status==="completed"),r=e.history.at(-1)??null,o=e.status==="blocked"?r:null,s=e.activeFeatureId?a.find((i)=>i.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:Da(e),session:{id:e.id,goal:e.goal,status:e.status,approval:e.approval,activeFeature:s??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 Da(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 Ba=f.object({goal:f.string().trim().min(1).optional(),plan:Z.optional()}).strict(),Ja=f.object({featureId:f.string().min(1).optional()}).strict(),Ga=f.object({featureId:f.string().min(1)}).strict(),Va=f.object({kind:f.enum(["completed","deferred","abandoned"]),summary:f.string().trim().min(1).optional()}).strict();function A(e){return{status:"error",summary:e.message,...e.recovery?{recovery:e.recovery}:{}}}async function T(e,a){return at(e,async()=>a(await B(e)))}async function ft(e){return k(await B(e))}async function mt(e,a){let t=Ba.parse(a??{});return T(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 ke(e,r);let s=r?.status==="completed"?ce(o):r??ce(o);if(s.goal!==o){if(s.approval==="approved")return{status:"error",summary:"An approved Flow session already exists for a different goal. Close it before starting a new one."}}let i=s.goal===o?s:ce(o),c=t.plan?it(i,t.plan):{ok:!0,value:i};if(!c.ok)return A(c);let p=await y(e,c.value);return{...k(p),status:"ok",summary:t.plan?"Flow plan saved.":"Flow session ready."}})}async function ht(e){return T(e,async(a)=>{if(!a)return{status:"missing_session",summary:"No active Flow session exists.",nextAction:"/flow-plan <goal>"};let t=ct(a);if(!t.ok)return A(t);let r=await y(e,t.value);return{...k(r),status:"ok",summary:"Flow plan approved."}})}async function gt(e,a){let t=Ja.parse(a??{});return T(e,async(r)=>{if(!r)return{status:"missing_session",summary:"No active Flow session exists.",nextAction:"/flow-plan <goal>"};let o=lt(r,t.featureId);if(!o.ok)return A(o);let s=await y(e,o.value.session);return{...k(s),status:"ok",summary:`Started feature '${o.value.feature.id}'.`,feature:o.value.feature}})}async function vt(e,a){let t=L.parse(a??{});return T(e,async(r)=>{if(!r)return{status:"missing_session",summary:"No active Flow session exists.",nextAction:"/flow-plan <goal>"};let o=dt(r,t);if(!o.ok){if(o.session)await y(e,o.session);return A(o)}let s=await y(e,o.value);return{...k(s),status:"ok",summary:"Feature result recorded."}})}async function wt(e,a){let t=Ga.parse(a??{});return T(e,async(r)=>{if(!r)return{status:"missing_session",summary:"No active Flow session exists.",nextAction:"/flow-plan <goal>"};let o=ut(r,t.featureId);if(!o.ok)return A(o);let s=await y(e,o.value);return{...k(s),status:"ok",summary:`Feature '${t.featureId}' reset.`}})}async function yt(e,a){let t=Va.parse(a??{});return T(e,async(r)=>{if(!r)return{status:"missing_session",summary:"No active Flow session exists.",nextAction:"/flow-plan <goal>"};let o=pt(r,t.kind,t.summary);if(!o.ok)return A(o);return await ke(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 bt(e){return JSON.stringify(e,null,2)}function Ka(e){return bt({status:"error",summary:e instanceof Error?e.message:String(e)})}async function x(e,a){try{return bt(await a(Le(e)))}catch(t){return Ka(t)}}async function Qa(e){let a=await ft(e),t=fe();if(!t)return a;return{...a,setup:{skills:t}}}function kt(e){return ie(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,Qa)}),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)=>mt(r,a))}),flow_plan_approve:m({description:"Approve the current draft Flow plan",args:{},execute:(a,t)=>x(t,ht)}),flow_run_start:m({description:"Start the next runnable approved Flow feature",args:{featureId:d.string().optional()},execute:(a,t)=>x(t,(r)=>gt(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)=>vt(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)=>wt(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)=>yt(r,a))})}}async function xt(e){let a=e.worktree??e.directory;if(!a)return null;try{let t=await B(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(`
1489
+ `)}catch{return null}}function Xa(e){return async(a,t)=>{let r=M();if(r)t.system.push(r);let o=await xt(e);if(o)t.system.push(o)}}function Ya(e){return e in X}function Ma(e,a){return X[e].template.replaceAll("$ARGUMENTS",a)}function Ha(e,a){let t=Ma(e,a),r=M();if(!r||e==="flow-status")return t;return[r,t].join(`
1490
+
1491
+ `)}function Za(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 La(){return async(e,a)=>{let t=e.command.replace(/^\/+/,"");if(!Ya(t))return;Za(a,Ha(t,e.arguments))}}var er=async(e)=>{let a=ie(e);return a("info","Flow v4 plugin initialized."),await De(We(),a),{config:ot(e),tool:kt(e),"command.execute.before":La(),"experimental.chat.system.transform":Xa(e),"experimental.session.compacting":async(t,r)=>{let o=M();if(o)r.context=[...r.context??[],o];let s=await xt(e);if(!s)return;r.context=[...r.context??[],s]}}},tr=er;export{tr as default};
1492
+
1493
+ //# debugId=40E22779C7F63F5464756E2164756E21