forgeos 0.1.0-alpha.70 → 0.1.0-alpha.71

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.
Files changed (41) hide show
  1. package/.agents/skills/forge-agent-fabric/SKILL.md +10 -1
  2. package/AGENTS.md +1 -1
  3. package/CHANGELOG.md +6 -0
  4. package/docs/agent-fabric-programs.md +151 -168
  5. package/docs/agent-fabric.md +4 -6
  6. package/docs/architecture/agent-fabric/WORKFLOW_PROGRAM_V2_ADR.md +81 -41
  7. package/docs/architecture/agent-fabric/WORKFLOW_PROGRAM_V2_CORRECTIONS.md +39 -0
  8. package/docs/architecture/agent-fabric/WORKFLOW_PROGRAM_V2_CORRECTIONS_EVIDENCE.md +53 -0
  9. package/docs/architecture/agent-fabric/WORKFLOW_PROGRAM_V2_EVIDENCE.md +49 -109
  10. package/docs/architecture/agent-fabric/WORKFLOW_PROGRAM_V2_PLAN.md +463 -423
  11. package/examples/agent-fabric-v2/README.md +16 -0
  12. package/examples/agent-fabric-v2/item-child.workflow.ts +11 -0
  13. package/examples/agent-fabric-v2/map-child.workflow.ts +10 -0
  14. package/examples/agent-fabric-v2/migrate.workflow.ts +1 -1
  15. package/examples/agent-fabric-v2/run-ui-fixture.ts +48 -0
  16. package/examples/agent-fabric-v2/ui-audit.workflow.ts +28 -0
  17. package/examples/agent-fabric-v2/ui-fixture-worker.cjs +36 -0
  18. package/examples/agent-fabric-v2/visual-population.json +13 -0
  19. package/package.json +3 -1
  20. package/src/forge/_generated/releaseManifest.json +1 -1
  21. package/src/forge/_generated/releaseManifest.ts +3 -3
  22. package/src/forge/agent-fabric/codex-sdk-worker.ts +2 -0
  23. package/src/forge/agent-fabric/program-api.ts +37 -0
  24. package/src/forge/agent-fabric/program-contract.ts +89 -35
  25. package/src/forge/agent-fabric/program-dsl.ts +45 -31
  26. package/src/forge/agent-fabric/program-evidence.ts +22 -0
  27. package/src/forge/agent-fabric/program-image.ts +15 -0
  28. package/src/forge/agent-fabric/program-lock.ts +50 -0
  29. package/src/forge/agent-fabric/program-owner.ts +16 -0
  30. package/src/forge/agent-fabric/program-scheduler.ts +38 -0
  31. package/src/forge/agent-fabric/program-service.ts +275 -101
  32. package/src/forge/agent-fabric/program-store.ts +80 -55
  33. package/src/forge/agent-fabric/program-structure.ts +65 -0
  34. package/src/forge/agent-fabric/program-types.ts +21 -9
  35. package/src/forge/agent-fabric/program-view.ts +12 -0
  36. package/src/forge/agent-fabric/program-worker.ts +24 -7
  37. package/src/forge/agent-memory/mcp.ts +3 -3
  38. package/src/forge/cli/fabric.ts +2 -2
  39. package/src/forge/cli/main.ts +2 -0
  40. package/src/forge/cli/parse.ts +1 -1
  41. package/src/forge/version.ts +1 -1
@@ -166,4 +166,13 @@ Validate source against the owner registry before dispatch. Every mutation needs
166
166
  requestId; subsequent mutations pin expectedVersion. Never treat data-only completed as
167
167
  acceptance-ready or infer authority to apply from a worker's report. Preserve uncertain
168
168
  outcomes and reconcile observed effects before resume. Fenced replan uses a global barrier;
169
- SDK output caching is disabled. Publication still requires the user's task authorization.
169
+ Same-run completed output reuse happens before worker preparation; cross-run SDK caching is absent.
170
+ Use operatorVersion 2, explicit Blocks/results, after/sequence and waiting semantics; no legacy migration is required.
171
+ For scoped UI acceptance require item/final owner checks, current evidence and full final obligations.
172
+ Use program-history/program-explain/program-artifact-get/program-diff for inspection.
173
+ When avoiding LLM spending set FORGE_FABRIC_TEST_MODE=1 and use deterministic adapters/SDK stubs.
174
+ Publication still requires the user's task authorization.
175
+
176
+ ## Workflow correction contract R2.2
177
+
178
+ Program subworkflows inherit ancestor activity quotas and cancellation; input is explicit. Owner visualCases binds route/viewport/state/dimensions to each population member; do not promise exhaustive UI coverage beyond that catalog. Capture obligations apply by assessment scope. New program runs use program-runs-v3/format 3 with immutable linked journal; no migration of old runs. program-explain includes graph nodes, observed instances and Mermaid. Typed refs/output(operation) improve authoring, while owner schemas remain authoritative. See docs/agent-fabric-programs.md and WORKFLOW_PROGRAM_V2_CORRECTIONS.md in the Forge source. For deterministic validation keep FORGE_FABRIC_TEST_MODE=1; do not launch real providers without explicit user authority.
package/AGENTS.md CHANGED
@@ -1,4 +1,4 @@
1
- // @forge-generated generator=0.1.0-alpha.70 input=c9c2b146d0cb312a96b8d2ba635c2e26634645a24895b1d003e2f65ae17a3e02 content=721818a6f9a664aa898092d4aa5cd68cbbd8ad6e150c7d3ad3ef785a2e3fcf53
1
+ // @forge-generated generator=0.1.0-alpha.71 input=c1757bb141bbcdd4d235a6d1af230b3a767ec7e4354f7fc3afb49fd46e893f06 content=721818a6f9a664aa898092d4aa5cd68cbbd8ad6e150c7d3ad3ef785a2e3fcf53
2
2
  # AGENTS.md
3
3
 
4
4
  <!-- forge-generated:start -->
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # forgeos
2
2
 
3
+ ## 0.1.0-alpha.71
4
+
5
+ ### Patch Changes
6
+
7
+ - Complete Agent Fabric workflow R2.2 with typed authoring, inherited subworkflow quotas and cancellation, shared owner scheduling, crash-recoverable leases, compact durable history, scoped evidence and visual case validation. Ship workflow templates, graph explanations and deterministic coverage. Validate the real Codex adapter with one bounded read-only smoke; retain explicit limits on local durability and model cost.
8
+
3
9
  ## 0.1.0-alpha.70
4
10
 
5
11
  ### Patch Changes
@@ -1,168 +1,151 @@
1
- # Agent Fabric program workflows v2
2
-
3
- Program workflows are an opt-in interpreter hosted by the existing authenticated local
4
- project owner. Version-1 managed runs and accompanied task records retain their original
5
- commands, persistence and meaning. No existing run is automatically converted.
6
-
7
- Author a `WorkflowProgramV2` JSON value, or supply finite TypeScript source with named
8
- imports from `forgeos/agent-fabric/workflows`. The static lowerer accepts const data,
9
- literal arrays/objects, constructors and spreads of already lowered const data objects.
10
- It rejects arbitrary imports, loops, closures, accessors, computed properties, array
11
- spreads, runtime I/O and malformed syntax. Workflow source is never executed.
12
-
13
- The shipped example is `examples/agent-fabric-v2/`. Its file-conversion reviewers are
14
- deterministic command fixtures; configure a real distinct reviewer and project checks
15
- for coding acceptance. See the architecture ADR for normative boundaries.
16
-
17
- ## Owner configuration and commands
18
-
19
- The owner reads `.forge/fabric-programs.json`, with versioned `schemas`, `executors`,
20
- `policies`, `acceptance`, `populations` and optional child `programs` registries.
21
- Requests cannot replace that registry. Each run pins its registry and external contracts.
22
- An author chooses registered references, not weaker review, coverage or effect authority.
23
-
24
- Keep `forge fabric serve` alive. Every mutation uses a unique `requestId`; subsequent
25
- mutations also require `runId` and `expectedVersion`. A repeated identical request is
26
- idempotent; changed contents under that request ID conflict. After a version conflict,
27
- read current status and use a new request ID for a changed decision.
28
-
29
- | CLI action | Meaning |
30
- | --- | --- |
31
- | `program-validate --file request.json` | Lower and validate without dispatch |
32
- | `program-start --file request.json` | Persist baseline, input and program before scheduling |
33
- | `program-status --run-id ID` | Read authoritative state |
34
- | `program-wait --file request.json` | Bounded wait using `{runId,cursor,waitMs}` |
35
- | `program-pause`, `program-resume` | Stop new dispatch / explicitly resume settled work |
36
- | `program-signal` | Persist an authorized event with target, generation, type and correlation |
37
- | `program-replan` | New program with barrier/additive/fenced modes |
38
- | `program-cancel` | Request cancellation; unobserved effects stay uncertain |
39
- | `program-reconcile` | Record observed failure or reconcile publication |
40
- | `program-apply` | Apply a gated candidate to local scoped files |
41
-
42
- Use `--file request.json --json` for mutations. Start accepts `{requestId,source,input}`
43
- or `{requestId,program,input}`. MCP exposes the same actions as
44
- `fabric_program_*`, using `{request: BODY}` for mutations and `{runId}` for status.
45
- Both transports use the same owner, state store and capability boundaries.
46
- The shared authenticated HTTP owner limits each request body to 40 KiB. Keep source and
47
- input below that transport bound; the offline lowerer's separate source cap is 256 KiB.
48
-
49
- ## Operators and contracts
50
-
51
- `value`, `agent`, `command`, `map`, `branch`, `loop`, `repair`, `compose`, `gate`,
52
- `subworkflow` and `waitEvent` are finite primitives. Explicit output references infer
53
- dependencies; parent/body cycles are rejected before dispatch. Branches mark the other
54
- arm skipped. Child programs inherit policy/acceptance and global attempt/deadline limits.
55
- Loops require bounded rounds and a progress/termination decision. Each materialized
56
- operation has a stable invocation ID, generation and input/semantic digests.
57
-
58
- Schemas use a bounded JSON Schema subset: types, enum/const, properties, required,
59
- additionalProperties, items, array/string/numeric bounds and anyOf. Unsupported keywords
60
- are rejected. Conservative static inference checks known field, child-input, branch-merge
61
- and result types. Unknown shapes still require runtime validation. A completed process
62
- does not imply a valid output or approval: review payloads distinguish approved,
63
- changes_requested and inconclusive from operational failure.
64
-
65
- `repair@v1` is a built-in deterministic recipe. `implement-first` edits before assessment;
66
- `assess-first` can approve with zero edits. Every assessment reviews/checks the same
67
- candidate, with a distinct readonly reviewer and registered command checks. Candidate,
68
- feedback, phase, implementation/assessment/infrastructure counters and measured progress
69
- are checkpointed. Resume cannot replenish exhausted budgets. Nonaccepted recipes keep
70
- diagnostic output and stop their consumers; later values cannot mask rejection.
71
-
72
- `map` requires finite unique NFC keys, bounded concurrency, a seal and explicit completion:
73
- all-required, partial or quorum. All-required discovery must match the owner population.
74
- Coverage alone does not prove work was accepted: a separate closed collection ledger
75
- binds each item's accepted assessment and candidate contribution. Population gates require
76
- that ledger and retain every item's deltas/producers in the final candidate. Empty work
77
- requires explicit allowNoWork in both population and acceptance contracts.
78
-
79
- The initial inventory adapter enumerates files under captured `inventoryRoots` and optional
80
- extensions. It is a concrete file inventory, not a semantic proof that a glob found all
81
- components. Semantic populations require owner-supplied evidence and exact baseline pinning.
82
- Exclusions require an inventory member and a reason. Population changes require a successor
83
- run with a new captured contract; current replan cannot replace external contracts.
84
-
85
- ## Candidate acceptance and application
86
-
87
- Candidates are immutable snapshot identities with ordered producer-specific deltas and
88
- parents. A shared ancestor is composed once; equal patches from independent producers
89
- are not silently deduplicated. Independent overlaps require resolution. Beforeimages,
90
- captured environment context, source types and scopes are checked before local writes.
91
-
92
- `completed` means a data program reached its typed result without a final acceptance gate.
93
- It is a re-openable computation checkpoint; it does not authorize application. Replan and
94
- resume are explicit owner decisions and the earlier state remains in immutable history.
95
- `acceptance-ready` requires an owner-issued gate and `acceptedCandidate`. A declared
96
- accepted result cannot bypass that gate or point to another candidate. Uncertain/active
97
- attempts block completion and application. `applied` and `canceled` require explicit successor
98
- runs for new work. No lifecycle state asserts human or production acceptance.
99
-
100
- `program-apply` requires current version, gate and authorization provenance. The owner
101
- commits ApplyIntent with candidate/program/contract digests, semantic version, seals and
102
- expected files before the first write. Signals received during application stay
103
- pending-after-apply. Publication checks each beforeimage, checks cancellation before each
104
- write, and stores observed completion. Multiple files are not one filesystem transaction.
105
- An interrupted/partial/divergent publication becomes apply-uncertain; it never silently retries.
106
-
107
- Publication reconciliation accepts `publication: true` only after observing all expected
108
- files. `publication: "retry"` requires authorization and the complete original baseline;
109
- it clears the old intent and pauses for explicit resume/revalidation. Partial or divergent
110
- files are preserved. Worker reconciliation requires attemptId, `resolution: "failed"`
111
- and an observed reason; parent uncertainty is reconciled after its worker attempts.
112
-
113
- ## Durability, replan, effects and reuse
114
-
115
- Each run has one checksummed authoritative atomic record in
116
- `.forge/local/agent-fabric/program-runs`. Immutable artifacts and full stateRefs are fsynced
117
- before referencing transitions. Every historical transition points to the exact state,
118
- including prior programs, generations, decisions and counters. Store.history and artifact
119
- get APIs inspect that history. Locks use linked complete owner files and guarded dead-owner
120
- reclamation. Recovery marks incomplete dispatch/application uncertain and does not start work.
121
- Process-crash/replay behavior is tested. Directory fsync/power-loss durability across every
122
- filesystem is not asserted. Archive/GC is manual; preserving evidence consumes disk.
123
-
124
- Barrier replan requires settled work. Additive replan preserves all existing templates;
125
- after the previous scheduler cycle settles, controls and final gates are recomputed for
126
- the new semantic version. Fenced replan is owner opt-in: affected operations/dependents
127
- receive monotonic generations; running attempts become uncertain and receive abort requests.
128
- It currently uses a **global scheduling barrier**. Unaffected running work may finish, but
129
- resume waits for the scheduler to settle and uncertainty to be reconciled. Removed historical
130
- operations are retired/skipped after observation; history is retained. This is not arbitrary
131
- live replacement with independent branch schedulers.
132
-
133
- Commands use explicit argv, resolved/hashed actual executables, scrubbed environment,
134
- frozen clone inputs and optional locked dependencies with scripts ignored. They are
135
- cooperative OS processes, not a network/filesystem sandbox. Strong disabled-network claims
136
- are refused for commands. Codex workers use readonly/workspace-write sandbox, disabled
137
- network and inherited MCP isolation. captureScope is distinct from write authority, allowing
138
- readonly programs without granting source writes. Generated paths cannot conceal captured
139
- source; external scratch is separate from candidate files. Cancellation does not prove a
140
- process tree stopped; unknown outcomes require observation.
141
-
142
- Outputs are not reused by default. `cache: "workspace"` is an owner declaration for command
143
- executors whose complete relevant inputs are their captured workspace/data, observed binary,
144
- dependency tree and environment. External/network/time/global filesystem inputs invalidate
145
- that declaration unless separately closed by an adapter. Compatible completed outputs receive
146
- explicit reuse receipts. SDK output reuse is disabled because effective global instructions,
147
- plugins and model inputs are not yet fully attested. Prompt caching is a separate provider feature.
148
-
149
- Recommended initial concurrency is four. Hard caps: concurrency32, depth32, items10000,
150
- attempts10000, operations20000, output4MiB, state32MiB and20 plan revisions. Expression/DSL
151
- expansion is bounded before concatenation/cloning. A dispatch reserve leaves record space
152
- for recovery. These are limits, not measured performance claims at maximum scale.
153
-
154
- ## Verification and remaining scope
155
-
156
- Tests cover finite lowering, output/generation/counter contracts, 80-item coverage, fabricated
157
- receipts, no-work, events, cache attestation, recovery, additive/fenced races, real commands,
158
- two-file composition, three same-file corrections, diamond ancestry, identical independent
159
- patch conflicts, application idempotency, beforeimage preservation and authenticated transport.
160
- The opt-in SDK pilot script performs a real readonly typed activity and records its bounded
161
- evidence separately. It is excluded from normal CI to avoid account/model usage.
162
-
163
- This alpha implements the bounded v2 foundation and conservative online controls. It does
164
- not establish complete F6/F7 product acceptance, semantic inventory adapters, extensible recipe
165
- registries, external effects exactly-once, streaming discovery, automatic GC, SDK output cache,
166
- high-concurrency scale, a live independent-branch scheduler or Claude product superiority.
167
- The benchmark harness labels its procedural comparison as a reference model, never as a
168
- measured Claude run. Production/EasyGrow/native-hook/App-closed acceptance remains separate.
1
+ # Agent Fabric program workflows
2
+
3
+ Current dev architecture: finite typed TypeScript → JSON IR (schemaVersion 2/operatorVersion 2) → exclusive local owner → activity scheduler → candidates/evidence → final assessment → gate → separate apply. There is no legacy interpreter or migration requirement. Start new runs after semantic upgrades. Normative architecture: `architecture/agent-fabric/WORKFLOW_PROGRAM_V2_ADR.md`; requirements and evidence are adjacent documents.
4
+
5
+ ## R2.2 correction contract
6
+
7
+ Correction plan: `architecture/agent-fabric/WORKFLOW_PROGRAM_V2_CORRECTIONS.md`. Subworkflows inherit activity scopes, cancellation, dependencies, item identity and lexical loop state. Their `workflowInput()` is the explicit child input. Policy/acceptance cannot change; population is inherited and cannot be replaced. Prefer passing item data explicitly for portable child programs; static schemas remain authoritative.
8
+
9
+ The owner/store share one PID/token hardlink lease protocol, including recovery of dead reclaim guards. A live guard is never removed. Unknown process liveness stays conservative. No exactly-once external guarantee is added.
10
+
11
+ `ProgramExecutor.inputSchema` optionally validates activity input before preparation/dispatch, alongside conservative preflight inference. Output schemas remain mandatory. Typed author refs support `executorRef<Input,Output>` and `programRef<Input,Output>`; `schemaRef<Output>` types events. `output(operation)` retains output types, `field` checks typed keys, and typed map bodies retain collection result item types. `output("id")` remains schema-validated at preflight/runtime. Generics are author annotations, not inferred from registry files and not authority to weaken a schema. `WorkflowExpression`, `WorkflowValue`, `WorkflowResolved`, `WorkflowBody`, `WorkflowCollection`, `WorkflowActivityOptions` are exported type helpers. No second interpreter is introduced.
12
+
13
+ ```ts
14
+ const inspect = agent("inspect", {
15
+ executor: executorRef<{path:string},{ok:boolean}>("inspect", "v2"),
16
+ input: {path: "src/a.ts"}
17
+ });
18
+ const ok = field(output(inspect), "ok"); // WorkflowExpression<boolean>
19
+ ```
20
+
21
+ ### Visual population
22
+
23
+ An owner population may declare `visualCases`, exactly one case per member:
24
+
25
+ ```json
26
+ {"itemKey":"checkout-mobile-error","route":"/checkout","viewport":"mobile","state":"error","width":390,"height":844}
27
+ ```
28
+
29
+ Route/viewport/state tuples and member keys must be unique; excluded members remain cataloged but are not assessed. Every observed capture must match its owner tuple and dimensions. AssessmentContext carries the current expected cases to capture/review workers. Final capture requirements recapture every active case. Item capture requirements come only from item obligations; final-only obligations do not force local screenshots. Without visualCases, coverage is per member, not an inferred matrix. Receipt metadata and valid image headers do not prove that the pixels depict the declared route/state. The WebP header parser currently accepts VP8X only.
30
+
31
+ Capture blobs commit before result; all receipts of one attempt commit atomically with the observed attempt result. Invalid batches leave no accepted partial receipts. Orphan blobs may remain until explicit maintenance; no GC is implied.
32
+
33
+ ### Storage and inspection
34
+
35
+ New runs use `.forge/local/agent-fabric/program-runs-v3`. Format 3 envelopes contain snapshot/journal pointers and CAS receipts, not duplicate full snapshots/history arrays. Each immutable journal node links its predecessor; history verifies the chain and historical snapshot identities. Snapshot and journal commit before atomic envelope publication. Old directories are preserved but unused; no checkpoint migration. Identical internal mutations do not write another checkpoint; authenticated request receipts still commit. Dispatch keeps a 24 MiB snapshot reserve and 90,000-transition reserve for recovery.
36
+
37
+ `program-explain.graph` returns `nodes`, observed `instances`, `mermaid`, and graph semantics. The diagram shows static dependencies, including control completion edges; dynamic map/loop expansions are separate instances. Mermaid labels are escaped. Storage metrics split actual written bytes into snapshot/journal/envelope/artifact categories, including temp files; full state snapshots still grow with the run. Profiling does not establish model speed or quality.
38
+
39
+ Reusable examples: `examples/agent-fabric-v2/map-child.workflow.ts`, `item-child.workflow.ts`, and `visual-population.json` (owner baseline digest required).
40
+
41
+ ## Start and inspect
42
+
43
+ The owner reads `.forge/fabric-programs.json`: versioned schemas, executors, policies, acceptance, populations and optional child programs. Authors select references; requests cannot substitute a weaker owner registry. Keep `forge fabric serve` alive. New dispatch/apply checks current owner authorization; immutable historical facts retain their pinned definitions.
44
+
45
+ `forge fabric program-validate --file request.json --json` accepts `{source}` or `{program}`. Start adds `{requestId,input}`. CLI mutations use request files and `{runId,requestId,expectedVersion,...}`. The HTTP owner bounds requests at 40 KiB; offline source lowering caps at 256 KiB. Every control uses CAS and idempotency; use a new requestId when changing a decision after a conflict.
46
+
47
+ | Action | Request/meaning |
48
+ |---|---|
49
+ | program-validate | source/program, no dispatch |
50
+ | program-start | requestId, source/program, input |
51
+ | program-status | --run-id ID, authoritative state |
52
+ | program-wait | runId, cursor, waitMs; bounded long poll |
53
+ | program-pause | stop new dispatch; active work is observed |
54
+ | program-resume | continue settled work without replenishing budgets |
55
+ | program-signal | signalId, target, generation, type, correlation, payload, authorization, optional subject/expiresAt |
56
+ | program-replan | source/program, mode barrier/additive/fenced |
57
+ | program-cancel | request cancellation; unknown effects remain uncertain |
58
+ | program-reconcile | attemptId or operationId, resolution failed, observed reason; publication reconciliation is separate |
59
+ | program-apply | current gated result and authorization; scoped local files |
60
+ | program-history | --run-id ID, journal/stateRefs |
61
+ | program-explain | --run-id ID, scopes/queue/scheduler/storage/guarantees |
62
+ | program-artifact-get | runId, ref; optional binary:true/maxBytes; bounded reachable artifact only |
63
+ | program-diff | runId and proposed source/program, graph changes |
64
+
65
+ MCP exposes the same 15 actions as `fabric_program_*`. Status/history/explain accept `{runId}`; other actions use `{request:BODY}`. Both use the same authenticated owner and store. Apply is not automatic.
66
+
67
+ ## Complete author API: 50 constructors
68
+
69
+ Import from `forgeos/agent-fabric/workflows`. Functions create finite IR data; they do not dispatch during authoring. `WorkflowDefinition`, `WorkflowOptions`, `WorkflowRef`, `WorkflowOperation` are exported author types. Normal TS compilation and static lowerer both support `as const`/`satisfies`; lowerer never evaluates callbacks, arbitrary imports or runtime I/O. JSON authors get identical owner validation.
70
+
71
+ `defineWorkflow({id,version,operatorVersion:2,mode,inputSchema,outputSchema,policy,acceptance,population?,steps,result})` defines the root. Mode data returns typed data; candidate mode requires a gate for acceptance-ready. Schema subset supports bounded objects/arrays/scalars, properties/required/additionalProperties, enum/const, numeric/string/array bounds and anyOf; unsupported keywords reject.
72
+
73
+ Seven reference constructors share `(id,version)` and have separate nominal kinds: `schemaRef`, `executorRef`, `policyRef`, `acceptanceRef`, `populationRef`, `recipeRef`, `programRef`.
74
+
75
+ All 13 operators use `(id,options)`, with optional common `after:string[]` and label. `after` is control dependency, not an operator. Reference dependencies are also inferred; independent roots run concurrently. IDs are lexical and cycles reject before dispatch. Multi-step Blocks require `{steps,result}`; a single operation is shorthand.
76
+
77
+ | Operator | Main options and result |
78
+ |---|---|
79
+ | value | value; pure data |
80
+ | agent | executor, input?, candidate?, writeScope?; typed worker data |
81
+ | command | same activity contract; registered command executor |
82
+ | map | items,key,body,completion,coverage?,quorum?,concurrency?,order?; sealed collection with item outcomes |
83
+ | branch | condition,then,else Blocks; selected result, unused arm skipped |
84
+ | loop | initialState,maxRounds,body,next,until; final state, bounded progress |
85
+ | repair | recipe,implement,review,checks,evidence?,assessmentScope?,entryMode,initialCandidate,writeScope,maxRepairRounds,maxAssessmentAttempts,maxInfrastructureAttempts,progressPolicy; accepted or explicit nonacceptance result |
86
+ | compose | candidates,onConflict:needs-resolution; integrated candidate; conflicts block |
87
+ | gate | candidate,coverage?,authorization?; owner-issued current receipt |
88
+ | subworkflow | program,input; child result under inherited limits/contracts |
89
+ | waitEvent | type,correlation,schema,subject?,timeoutMs?; one authorized event payload |
90
+ | sequence | steps,result; serial required children |
91
+ | parallel | steps,result,onFailure:collect-all/cancel-siblings; required children with diagnostics |
92
+
93
+ All 29 expressions:
94
+
95
+ | Expression | Meaning |
96
+ |---|---|
97
+ | workflowInput() | typed input |
98
+ | item() | current map item, including nested loop |
99
+ | loopState() | current loop state |
100
+ | output(id) | data result of lexical invocation; activity envelope is unwrapped |
101
+ | field(value,key) | bounded object field |
102
+ | literal(value) | literal data, no nested expression interpretation |
103
+ | object(record) | evaluate object entries |
104
+ | array(...values) | evaluate array entries |
105
+ | eq(a,b) | canonical data equality |
106
+ | and(...values) | boolean conjunction |
107
+ | or(...values) | boolean disjunction |
108
+ | not(value) | boolean negation |
109
+ | concat(...arrays) | bounded concatenation |
110
+ | filter(values,key,equals) | field equality selection |
111
+ | unique(values,key) | first unique field values |
112
+ | sort(values,key) | UTF-8 field ordering |
113
+ | take(values,count) | bounded prefix |
114
+ | length(value) | collection/string length |
115
+ | population() | owner population contract |
116
+ | acceptance() | owner acceptance contract |
117
+ | candidateFromBaseline(entry?) | owner baseline candidate; entry bounds item context |
118
+ | outputCandidate(id) | candidate from completed activity/composition |
119
+ | acceptedCandidate(id) | accepted repair candidate with owner receipt |
120
+ | acceptedCandidates(id) | accepted candidate collection |
121
+ | coverageFor(contract,discovered) | validate discovered items against owner catalog; issue receipt |
122
+ | coverageReceipt(id) | collection coverage receipt |
123
+ | acceptanceWriteScope(id) | inherited acceptance write scope |
124
+ | approvedChecksFor(entry) | owner-approved checks for work entry |
125
+ | acceptanceChecks(id) | checks inherited from the acceptance contract |
126
+
127
+ ## Recovery and scopes
128
+
129
+ Owner activity capacity is four; run and ancestor map quotas can narrow it. Parent controls do not hold activity slots. Queue admission shares the absolute run deadline. Completed intact same-run outputs are reused before workspace/adapter preparation, including mocked/real SDK output records. This is distinct from cross-run cache, which is absent. Corrupt artifacts block and do not trigger silent redispatch.
130
+
131
+ Waiting is its own state. Independent siblings continue and survive resume. Events persist before consumption; target/generation/type/correlation/subject/schema/expiry bind their use. A live owner wakes on authorized event or deadline. After restart use explicit resume. Paused stays paused. Completed data is not acceptance-ready. Unobserved cancellation/dispatch stays uncertain and retains reservations through restart until observation/reconciliation. Exactly-once external effects are not promised.
132
+
133
+ Barrier replan recomputes changed branches and dependents, preserving compatible intact facts. Additive keeps existing templates. Fenced replacement requires owner opt-in and a global barrier; this is not independent live local fencing. Repair persists intent/counters before dispatch and never refunds exhausted budgets on resume.
134
+
135
+ ## UI and candidate acceptance
136
+
137
+ Owner contracts declare `requiredChecksByScope:{item,final}`, `assessmentBindings` and obligations `{id,scope,criteria,requiredEvidence?}`. Review/check/capture receive AssessmentContext with candidateRef, obligationIds, environmentRef, itemKey and evidenceRefs. Evidence files are readonly inputs. Registered capture commands return JSON `evidenceArtifacts:[{path,itemKey,buildDigest,environmentRef,mime,width,height,route,viewport,state}]`; path must be in bounded scratch storage. Owner stores immutable bytes and issues capture receipts. Invalid/missing/stale evidence blocks; it does not become a UI defect requiring implementation.
138
+
139
+ Assess-first means a correct UI produces zero edits. Review approval alone is insufficient: findings must be empty, checks passed, all obligations covered, current candidate/env/evidence bound and distinct observed reviewer attempt. Final assessment after compose recaptures the complete population and can reject an item previously approved locally. Conflicts need resolution; no automatic resolution recipe is implemented.
140
+
141
+ Map keys normalize NFC before uniqueness, encode path segments once and order by UTF-8. Completion is all-required/partial/quorum; quorum is `{minAccepted:K}`, explicit and only closes when outcomes settle. Owner must authorize partial/quorum; such a result cannot alone satisfy all-required final obligations. Envelope item outcome is distinct from arbitrary user data (including a user field named status).
142
+
143
+ If `requireHumanApproval:true`, add a wait subject `{candidate: acceptedCandidate(finalId), contract: acceptance()}` and give `output(waitId)` as gate authorization. The authenticated host supplies provenance and approved payload, not a worker. A declined/expired/fabricated approval does not authorize gate/apply.
144
+
145
+ Apply commits an immutable intent before the first write, pins candidate/contract/semantic version/seals and checks beforeimages. Multiple files are not an atomic filesystem transaction. Divergent/partial writes become apply-uncertain. Reconciliation with `publication:true` requires observed complete files; retry requires authorization and complete original baseline, then explicit resume/revalidation. Source files remain untouched until apply.
146
+
147
+ ## Runnable examples and no-LLM verification
148
+
149
+ `examples/agent-fabric-v2/ui-audit.workflow.ts` is the complete UI plan. `run-ui-fixture.ts` builds 20 local HTML pages with three known defects and registered deterministic discover/capture/review/implement/local/global-check commands. Test evidence: exactly three implementations, 43 captures including 20 fresh final captures, 21 final obligations, no apply and zero LLM calls. PNG fixtures verify transport/binding. Optional explicit browser path renders local HTML in headless Chromium/Edge; visual quality is still not model-evaluated.
150
+
151
+ Run `FORGE_FABRIC_TEST_MODE=1` using the shell's environment syntax, then `node bin/forge-bun.mjs run examples/agent-fabric-v2/run-ui-fixture.ts`. The test fuse refuses default real Codex factories; stubs remain supported. Runtime profiling: `node bin/forge-bun.mjs run scripts/benchmark-fabric-workflows.ts report.json`, fixed fan-out/fault/restart, no provider. Neither is a Claude/model-quality benchmark. Future extensions (cross-run cache, distributed owner, automatic GC/resolution, unlimited streaming/race, additional harnesses) remain out of this implementation.
@@ -9,12 +9,10 @@ Forge Agent Fabric is an experimental protocol-oriented execution layer for dyna
9
9
 
10
10
  ## Implementation status
11
11
 
12
- Status checked against local source `c8dfdf0c0c3cd6610bab68b4872ab9dcf8d4214c` on
13
- 2026-10-07. The [current status summary](./architecture/agent-fabric/CODEX_DYNAMIC_WORKFLOWS.md#estado-atual-verificado-em-2026-10-07)
14
- distinguishes implemented accompanied/managed modes, recorded pilot evidence and
15
- remaining acceptance work. Historical plans and their original checklists are not
16
- the current capability inventory. This refresh did not rerun the SDK pilot or establish
17
- publication of the inspected revision.
12
+ Workflow corrections R2.2: inherited subworkflow quotas/cancellation, shared recoverable leases, owner visual case catalogs, typed connections, compact linked journal and graph inspection. See [correction plan](architecture/agent-fabric/WORKFLOW_PROGRAM_V2_CORRECTIONS.md).
13
+
14
+ Current development workflow runtime adopts operatorVersion 2 directly, without a legacy interpreter or migration requirement. See [workflow API](./agent-fabric-programs.md), [normative architecture](./architecture/agent-fabric/WORKFLOW_PROGRAM_V2_ADR.md) and [current implementation evidence](./architecture/agent-fabric/WORKFLOW_PROGRAM_V2_EVIDENCE.md). This revision adds activity quotas, durable waiting/continuation, scoped item/final obligations and immutable capture evidence. Historical plans and SDK pilots are not proof of current model quality. This implementation was validated without real LLM calls.
15
+
18
16
 
19
17
  The Codex-accompanied task mode now records acceptance criteria, scoped source snapshots,
20
18
  independent review and checks in a persistent local task. Its dynamic workflow scheduler
@@ -1,41 +1,81 @@
1
- # Workflow program v2 implementation decisions
2
-
3
- Date: 2026-10-07. Scope: opt-in alpha foundation, additive to the existing v1 runtime.
4
- The user's implementation/release instruction authorizes this code release. Earlier
5
- historical adoption records and their acceptance claims retain their original scope.
6
-
7
- 1. The canonical program is a finite typed JSON IR. TypeScript is statically lowered
8
- using a restricted AST; the owner never executes authored source. This combines
9
- convenient script-like authoring with inspectable bounded orchestration.
10
- 2. Schemas, executors, policies, acceptance and population are trusted owner registries.
11
- Requests select references and cannot lower their own review or effect authority.
12
- Static inference is conservative; runtime validation remains mandatory.
13
- 3. The current local project owner hosts v1 and v2. A checksummed atomic record commits
14
- decisions and immutable artifacts, including full historical stateRefs. Recovery
15
- observes uncertainty before explicit resume. No power-loss or external exactly-once
16
- durability claim is made.
17
- 4. Discovery seals identity and coverage against an owner inventory. Accepted work has
18
- a separate collection ledger linking assessments and contributions to the final
19
- candidate. File inventory is implemented; semantic inventory adapters remain separate.
20
- 5. Repair is a finite built-in state machine with independent implementation,
21
- assessment and infrastructure budgets. Rejection or uncertainty stops consumers.
22
- Candidates preserve parents, producers and ordered deltas; equal independent patches
23
- conflict, and shared ancestry is applied once.
24
- 6. Only owner-issued gates authorize a candidate. ApplyIntent freezes the complete
25
- decision before writes. Local multi-file application is observable and reconciled,
26
- not one filesystem transaction. Partial application never retries automatically.
27
- 7. Barrier, additive and opt-in fenced replanning preserve history and generations.
28
- Fenced replanning uses a global scheduling barrier. Independent live branch
29
- replacement is deferred until a scheduler can enforce each branch's full closure.
30
- 8. Reuse defaults off. Declared command workspace caches require attested inputs.
31
- SDK output cache remains disabled until instructions/plugins/model inputs are closed.
32
- Commands are cooperative host processes; strong sandbox claims are rejected for them.
33
- 9. Initial authoring/runtime budgets are finite. A shared capacity wait rechecks the
34
- count after waking. Maximum-scale performance and archive/GC are not established.
35
- 10. The procedural benchmark is labelled as a reference scheduler, not Claude Code.
36
- Real SDK proof is a readonly typed activity. Full coding quality, integration
37
- acceptance, production delivery and product superiority require additional evidence.
38
-
39
- See [the executable contract](../../agent-fabric-programs.md),
40
- [reviewed design plan](WORKFLOW_PROGRAM_V2_PLAN.md) and
41
- [verification evidence](WORKFLOW_PROGRAM_V2_EVIDENCE.md).
1
+ # Agent Fabric workflow runtime: decisão normativa
2
+
3
+
4
+
5
+ Status: implementado em desenvolvimento, 2026-10-07. O usuário dispensou compatibilidade com Forge legado. Não há interpretador operatorVersion 1 nem migração automática de checkpoints antigos. Use runs novos ao trocar a semântica do runtime.
6
+
7
+
8
+
9
+ ## Autoria e estrutura
10
+
11
+
12
+
13
+ TypeScript finito com 50 construtores públicos produz JSON IR schemaVersion 2/operatorVersion 2. O lowerer não executa código: aceita imports nomeados do módulo Forge, const, dados finitos, spreads de objetos const, `as const`, `satisfies` e imports de tipos de autoria. Rejeita callbacks, acesso ao filesystem, chamadas arbitrárias e loops JavaScript. Tipos nominais distinguem refs de schemas, executores, políticas, aceitação, populações, receitas e programas. JSON IR também é aceito diretamente; ambos passam pelo mesmo validador owner e pelas mesmas verificações de tipos/esquemas.
14
+
15
+
16
+
17
+ O grafo inclui dependências de dados e `after`. Posição textual não ordena roots: `sequence` ordena filhos, `parallel` executa filhos requeridos com diagnóstico collect-all ou cancel-siblings. Blocks com vários filhos exigem `result`; shorthand de um filho é permitido. Branch, loop, map e subworkflow têm contextos léxicos explícitos. Loop retorna estado final. Map retorna envelope de coleção com itens identificados, outcome separado do dado, resultados, falhas e seal. IDs de membros usam NFC antes da unicidade, comparação UTF-8 e encoding único de segmentos. Coleções são finitas e seladas.
18
+
19
+
20
+
21
+ ## Owner, limites e recuperação
22
+
23
+
24
+
25
+ Um owner exclusivo por diretório de estado usa lease com PID/token/epoch. Um segundo owner vivo é rejeitado; morte permite recuperação conservadora. O scheduler limita atividades, não controles pais: owner 4, run por política e scopes ancestrais por map. Fairness round robin entre runs elegíveis. Fila é persistida antes da admissão; limite absoluto de run vale também na fila.
26
+
27
+
28
+
29
+ Intent/debit/reserva são persistidos antes de execute. Tentativa sem resultado observado é uncertain e retém sua reserva; restart reconstitui reservas. Timeout/cancel não prova término de árvore de processos. Worker sem confirmação de cancelamento não bloqueia close indefinidamente; permanece uncertain, sem redispatch ou apply. Reconciliação exige observação externa, não mera intenção de repetir. Resultado observado mas inválido é invalid_output e libera slot. A preparação cancelada não é despachada.
30
+
31
+
32
+
33
+ Completed íntegro do MESMO run é reutilizado antes de preparar workspace/adapter. Digests fecham executor, inputs, candidato, escopo e contratos pinados. Artifact perdido/corrompido bloqueia; não vira cache miss. Isso não é cache entre runs e não prova replay exatamente uma vez de efeitos externos. Repair checkpointa rounds/assessment/infra antes da fase; resume não repõe débitos.
34
+
35
+
36
+
37
+ Wait é waiting e não falha. Irmãos independentes continuam; eventos e deadlines absolutos acordam o scheduler enquanto o owner está vivo. Restart requer resume explícito. Eventos têm request CAS, identidade, target/generation/type/correlation, schema, proveniência, subject e expiry. Idempotência inclui subject/expiry. O host deve autenticar a origem da proveniência; texto vindo de worker não vira autorização humana.
38
+
39
+
40
+
41
+ Barrier replan invalida ramos alterados e dependentes, preservando intactos; additive preserva templates existentes. Fenced replan é opt-in e conservador: parada global e uncertain até observação. Não há fencing local distribuído. Política/contrato/executor atuais são conferidos novamente antes de NOVO dispatch e apply; fatos históricos continuam legíveis.
42
+
43
+
44
+
45
+ ## Candidatos e aceitação
46
+
47
+
48
+
49
+ Executor read não tem autoridade de alteração; isolated-write produz deltas com beforeimages em clones. Command é cooperativo; não se apresenta como sandbox forte. Codex usa sandbox e rede desabilitada; subprocessos/agentes internos não ganham garantia fictícia de quota agregada. Só owner registra CandidateRef, DeltaRef e receipts a partir de tentativas observadas.
50
+
51
+
52
+
53
+ Owner AcceptanceContract declara critérios, obrigações por item/final, checks distintos e bindings de assessments. Autor não omite checks mandatórios. AssessmentContext traz candidato, invocation/assessment IDs, obrigações, ambiente e EvidenceRefs. Capturas PNG/JPEG/WebP têm limites de bytes/dimensões/pixels, origem da tentativa, candidato/build/env/item/route/viewport/state. Consumidores recebem arquivos readonly; metadata só não prova render correto ou qualidade visual. Limites: 8 MiB/imagem, 32 MiB/lote, 100 imagens/lote.
54
+
55
+
56
+
57
+ Repair assess-first evita edição sem defeito. Aprovação exige findings vazios, checks passados e cobertura integral das obrigações. Report incompleto é inconclusive, sem edição. Infra/capture inválida é diferente de finding visual. Item assessment fecha o ledger local; compose integra candidatos compatíveis. Conflito para em needs-resolution, sem merge automático. Final assessment recaptura e verifica TODA a população sobre o candidato integrado atual; receipts locais antigos não substituem aceitação final.
58
+
59
+
60
+
61
+ Gate exige o mesmo candidato, contratos, geração, seal, cobertura e tentativas distintas observadas. Partial/quorum exigem permissão owner e não aprovam por si uma obrigação all-required. Quorum tem threshold explícito e espera todos os outcomes assentarem. Collect-all produz diagnóstico e não avalia result de scope requerido falho. Se aprovação humana for exigida, gate consome sinal autorizado bound ao candidato/contrato; decline/expiry/fabricação não aprovam. Apply é ação separada, com autorização, gate congelado, beforeimages e reconciliação de publicação incerta.
62
+
63
+
64
+
65
+ ## Persistência, inspeção e limites
66
+
67
+
68
+
69
+ R2.2: envelopes format 3 contêm ponteiros para snapshot e nó de journal imutáveis SHA256; nós encadeiam parentRef/version/runId. O histórico acumulado e o snapshot não são duplicados no envelope. Escrita atômica/fsync publica o envelope por último. Runs novos usam program-runs-v3, sem migração. Mutação interna sem mudança não escreve checkpoint; receipts autenticados continuam persistidos. Owner e store compartilham recuperação de reclaim abandonado. Transações são serializadas por run; definitions validadas são memoizadas pelo digest, sem dispensar verificação do envelope. History, explain, artifact-get e diff compartilham CLI/MCP/owner. Artifact-get só aceita refs alcançáveis pelo run; não lê paths livres.
70
+
71
+
72
+
73
+ A durabilidade é local, com owner vivo; não há promessa de serviço remoto/App fechado. Sem GC automático, cache cross-run, streaming ilimitado, race, código TS arbitrário, YAML nativo, múltiplos harnesses completos ou resolução automática. Nenhuma superioridade sobre Claude DW foi medida. Validação sem LLM é requisito: FORGE_FABRIC_TEST_MODE=1 recusa factories reais Codex; adapters determinísticos e SDK stubs são permitidos. Qualidade de modelo permanece fora da evidência.
74
+
75
+
76
+
77
+ ## Correções R2.2
78
+
79
+
80
+
81
+ Plano: WORKFLOW_PROGRAM_V2_CORRECTIONS.md. Subworkflow herda signal/scopes/item/estado lexical e não substitui população. visualCases vincula captura a rota/viewport/estado/dimensões esperados; requiredEvidence segue o escopo das obrigações. Receipt batch commit é atômico com o resultado observado. Ref/operation/expression generics preservam conexões de autoria; schemas owner continuam a autoridade. program-explain expõe grafo/Mermaid e instâncias separadas.
@@ -0,0 +1,39 @@
1
+ # Agent Fabric: plano de correção e acabamento R2.2
2
+
3
+ Objetivo: fechar os achados da revisão independente de 07/10/2026, mantendo TypeScript finito → IR → owner → scheduler → evidências → gate → apply. Sem compatibilidade legada e sem testes com LLM. Não é uma promessa de superioridade empírica sobre Claude DW.
4
+
5
+ ## 1. Contexto e capacidades de subworkflow
6
+
7
+ Herdar signal, scopes de atividades, dependências e identidade do item. Manter item e estado do loop como contexto lexical do chamador; workflowInput é o input explícito do filho. O filho não pode substituir policy, acceptance nem population do root. Verificar map concurrency=1 com várias atividades no filho, cancel-siblings, identidade de item e contratos herdados.
8
+
9
+ ## 2. Um protocolo de lease para owner e store
10
+
11
+ Unificar admissão por hardlink, identidade PID/token, assert antes de release e reclaim de titulares mortos. Recuperar guardas abandonados sem retirar leases vivos. Testes determinísticos cobrem guarda morta, guarda viva, owner morto, exclusão e identidade alterada. PID vivo desconhecido continua conservador; não prometer exatamente uma vez.
12
+
13
+ ## 3. Obrigações e cobertura visual
14
+
15
+ Derivar captura somente das obrigações aplicáveis ao assessment. Obrigações item se expandem para o item corrente ou toda a população no assessment final; obrigações final só se aplicam na fase final. Introduzir population.visualCases, um caso por member com itemKey, route, viewport, state, width e height esperados. Catálogo informado deve cobrir exatamente os members e ter tuplas únicas. Conferir receipt contra o catálogo antes de registrar. Captura final recobre todos os casos ativos. Sem catálogo visual, a garantia continua cobertura por item; não inferir todas as UIs. Header de imagem não prova renderização nem qualidade visual.
16
+
17
+ Agrupar registros de capturas com o resultado observado da tentativa em uma transação; blobs são persistidos antes dela. Falha deixa blobs órfãos, nunca evidência aceita parcialmente.
18
+
19
+ ## 4. Tipos de autoria
20
+
21
+ Adicionar generics de input/output nas refs, operações e expressões, output(operation), field com chaves verificadas e inputs tipados nos executores/subworkflows. Generics não substituem schemas do owner. Permitir inputSchema opcional no executor e validar antes de preparar/dispatch. O lowerer continua produzindo o mesmo IR, sem executar código. Testes de compilação devem demonstrar erros reais de tipo; exemplos devem baixar no mesmo lowerer.
22
+
23
+ ## 5. Persistência e perfil determinístico
24
+
25
+ Remover a duplicação do snapshot inteiro no envelope e a regravação do histórico acumulado em cada transação. Persistir snapshot e nó de journal imutáveis, com parentRef/version/runId; publicar por último envelope compacto de ponteiros e receipts CAS. Read valida integridade e checkpoint; history percorre e valida cadeia/versionamento. Artefato perdido/corrompido bloqueia. Sem migração: runs antigos devem ser recriados.
26
+
27
+ Medir todos os bytes efetivamente escritos, divididos em snapshot, journal, envelope e artifacts, com perfil fixo em 12/48/96 itens, fault+resume e zero chamadas a modelo. Relatar custo local e limites sem extrapolar throughput de LLM. Não agrupar intent/debit/dispatch de modo que enfraqueça recuperação.
28
+
29
+ ## 6. Autoria e inspeção
30
+
31
+ Expor grafo estático e Mermaid em program-explain, com tipos, dependências e estado; distinguir templates de expansões observadas. Adicionar template de map → subworkflow com input explícito e um exemplo de população visual desktop/mobile. Documentar diagnóstico, herança, tipos, persistência e limitações no guia público/ADR/skill do repo.
32
+
33
+ ## Entrega e aceitação
34
+
35
+ Executar generate, check, typecheck, testes determinísticos direcionados e verify framework com FORGE_FABRIC_TEST_MODE=1. Nenhum provider/LLM real, deploy ou publicação npm é necessário para esta correção. Registrar resultados e limites em relatório de entrega. Preservar alterações anteriores e restaurar apenas ruído gerado que já estava limpo antes desta rodada.
36
+
37
+ ## Estado final
38
+
39
+ Implementado e validado em desenvolvimento. Última suíte completa: 1679 aprovados, nenhuma falha, 4 skips condicionais existentes; 11 gates passaram. Evidência detalhada: WORKFLOW_PROGRAM_V2_CORRECTIONS_EVIDENCE.md. O runtime e a validação herdam o contexto lexical do filho; inferência mantém rejeição de campos inexistentes.