@aarwitz/tapp 0.17.26 → 0.18.0

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.
@@ -130,7 +130,7 @@ function openBrowser(url) {
130
130
  function publicJob(job, { hosted = false } = {}) {
131
131
  return {
132
132
  id: job.id, operation: job.operation, status: job.status, repositoryId: job.repositoryId || null,
133
- createdAt: job.createdAt, completedAt: job.completedAt || null, progress: job.progress.slice(-80),
133
+ createdAt: job.createdAt, completedAt: job.completedAt || null, progress: job.progress.slice(-80), frame: !!job.latestFrame,
134
134
  result: hosted ? hostedPayload(job.result) : job.result || null,
135
135
  error: job.error || null,
136
136
  };
@@ -324,8 +324,11 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
324
324
  const job = { id: crypto.randomBytes(10).toString("hex"), operation, repositoryId, status: "running", createdAt: new Date().toISOString(), progress: [] };
325
325
  const progress = (entry) => {
326
326
  const normalized = typeof entry === "string" ? { text: entry } : entry || {};
327
- job.progress.push({ at: new Date().toISOString(), phase: normalized.phase || operation, text: String(normalized.text || "").slice(-1200), ...(normalized.current ? { current: normalized.current, total: normalized.total } : {}) });
327
+ job.progress.push({ at: new Date().toISOString(), phase: normalized.phase || operation, text: String(normalized.text || "").slice(-1200), ...(normalized.current ? { current: normalized.current, total: normalized.total } : {}), ...(normalized.screen ? { screen: String(normalized.screen).slice(0, 200) } : {}) });
328
328
  if (job.progress.length > 200) job.progress.splice(0, job.progress.length - 200);
329
+ // The engine names the screenshot it just wrote; the Studio device panel polls it as the
330
+ // exploration feed. Only engine-supplied paths ever land here, never client input.
331
+ if (normalized.screenshot && path.isAbsolute(normalized.screenshot)) job.latestFrame = normalized.screenshot;
329
332
  };
330
333
  jobs.set(job.id, job);
331
334
  activeMutation = job;
@@ -436,6 +439,15 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
436
439
  json(response, 200, publicJob(job, { hosted }));
437
440
  return;
438
441
  }
442
+ const jobFrameMatch = url.pathname.match(/^\/api\/jobs\/([a-f0-9]{20})\/frame$/);
443
+ if (request.method === "GET" && jobFrameMatch) {
444
+ const job = jobs.get(jobFrameMatch[1]);
445
+ if (!job?.latestFrame || !fs.existsSync(job.latestFrame)) { json(response, 404, { error: "No exploration frame yet" }); return; }
446
+ const data = fs.readFileSync(job.latestFrame);
447
+ response.writeHead(200, { "content-type": job.latestFrame.endsWith(".jpg") || job.latestFrame.endsWith(".jpeg") ? "image/jpeg" : "image/png", "content-length": data.length, "cache-control": "no-store", "x-content-type-options": "nosniff" });
448
+ response.end(data);
449
+ return;
450
+ }
439
451
  const captureMatch = url.pathname.match(/^\/evidence\/captures\/([A-Za-z0-9._-]{1,128})(?:\/(.*))?$/);
440
452
  if (request.method === "GET" && captureMatch) {
441
453
  const file = capturePath(captureMatch[1], captureMatch[2] || "report.html");
@@ -592,7 +604,7 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
592
604
  maxActions: runtime.maxActions, timeout: runtime.timeout, maxContracts: runtime.maxContracts,
593
605
  testEmail: runtime.testEmail, testPassword: runtime.testPassword,
594
606
  runExploration: engine.runInitExploration,
595
- onProgress: (entry) => progress({ phase: "explore", text: `${entry.action || 0}/${entry.max || runtime.maxActions} actions · ${entry.states || 0} states` }),
607
+ onProgress: (entry) => progress({ phase: "explore", text: entry.narrative || `${entry.action || 0}/${entry.max || runtime.maxActions} actions · ${entry.states || 0} states`, current: entry.action || 0, total: entry.max || runtime.maxActions, screen: entry.screen, screenshot: entry.screenshot }),
596
608
  onStatus: (text) => progress({ phase: "runtime", text }),
597
609
  });
598
610
  }
@@ -0,0 +1,2 @@
1
+ export function passiveUrlRisk(value: string): string | null;
2
+ export function resolveObservationUrl(base: string, pagePath?: string): string;
@@ -0,0 +1,25 @@
1
+ // Shared passive-navigation policy. GET is not proof that an endpoint is safe:
2
+ // avoid recognizable action/signed links and report the resulting coverage gap.
3
+ export function passiveUrlRisk(value) {
4
+ let url;
5
+ try { url = new URL(value); } catch { return "invalid-url"; }
6
+ let pathname;
7
+ try { pathname = decodeURIComponent(url.pathname); } catch { return "invalid-url"; }
8
+ if (!/^https?:$/.test(url.protocol) || url.username || url.password) return "invalid-url";
9
+ if (/(?:^|\/)(?:logout|log-out|signout|sign-out|unsubscribe|delete|remove|cancel|refund|activate|accept|confirm)(?:\/|$)/i.test(pathname)) return "possible-action-link";
10
+ for (const key of url.searchParams.keys()) {
11
+ if (/^(?:token|access_token|id_token|signature|sig|code|action|do|delete|remove|refund|unsubscribe|confirm)$/i.test(key)) return "signed-or-action-link";
12
+ }
13
+ return null;
14
+ }
15
+
16
+ export function resolveObservationUrl(base, pagePath = "") {
17
+ const origin = new URL(base);
18
+ if (typeof pagePath !== "string" || pagePath.length > 2000 || (pagePath && (!pagePath.startsWith("/") || pagePath.startsWith("//") || /[\\\u0000-\u0020\u007f]/.test(pagePath)))) {
19
+ throw new Error("Choose a page path on this website, such as /contact; do not supply another website or an action link");
20
+ }
21
+ const url = new URL(pagePath || origin.href, origin);
22
+ if (url.origin !== origin.origin || passiveUrlRisk(url.href)) throw new Error("Passive checks cannot open signed or potentially state-changing links. Choose an ordinary page on this website");
23
+ url.hash = "";
24
+ return url.href;
25
+ }
@@ -0,0 +1,36 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { randomUUID } from "node:crypto";
4
+ import { readProductProject } from "./product-operations.js";
5
+ import { BUSINESS_WORKFLOW_PATH, emptyBusinessWorkflows, normalizeBusinessWorkflows, discoverBusinessWorkflows, planBusinessWorkflow, businessWorkflowCoverage } from "./business-workflows.js";
6
+
7
+ function fileFor(projectDir) {
8
+ const root=fs.realpathSync(projectDir || process.cwd());
9
+ const directory=path.join(root,".tapp");
10
+ if(fs.existsSync(directory) && !fs.realpathSync(directory).startsWith(root+path.sep))throw new Error("Workflow artifacts must remain inside the project");
11
+ const file=path.join(root,BUSINESS_WORKFLOW_PATH);
12
+ if(fs.existsSync(file) && !fs.realpathSync(file).startsWith(root+path.sep))throw new Error("Workflow map must remain inside the project");
13
+ return file;
14
+ }
15
+ export function readBusinessWorkflowProject({projectDir=process.cwd(),connection={}}={}) {
16
+ const file=fileFor(projectDir);
17
+ const document=fs.existsSync(file)?normalizeBusinessWorkflows(JSON.parse(fs.readFileSync(file,"utf8"))):emptyBusinessWorkflows();
18
+ const project=readProductProject({projectDir});
19
+ return {document,inventory:discoverBusinessWorkflows(project,connection),
20
+ plans:document.workflows.map(workflow=>planBusinessWorkflow(document,workflow.id,project,connection)),
21
+ coverage:businessWorkflowCoverage(document,project,connection),
22
+ note:"Local map inspection does not import hosted execution evidence. Continue using repository Flows, Scenarios and release gates for local execution."};
23
+ }
24
+ export function saveBusinessWorkflowProject({projectDir=process.cwd(),document,confirm=false}) {
25
+ const file=fileFor(projectDir);
26
+ const prior=fs.existsSync(file)?normalizeBusinessWorkflows(JSON.parse(fs.readFileSync(file,"utf8"))):emptyBusinessWorkflows();
27
+ const next=normalizeBusinessWorkflows(document);
28
+ if(next.revision!==prior.revision)throw new Error("Workflow map changed; read the current revision before saving");
29
+ if(!confirm && next.workflows.some(workflow=>workflow.decision==="confirmed"))throw new Error("Use --confirm only after reviewing the listed outcomes and checks");
30
+ next.revision++;
31
+ fs.mkdirSync(path.dirname(file),{recursive:true});
32
+ const temporary=`${file}.${randomUUID()}.tmp`;
33
+ try {fs.writeFileSync(temporary,JSON.stringify(next,null,2)+"\n",{flag:"wx",mode:0o600});fs.renameSync(temporary,file);}
34
+ finally {if(fs.existsSync(temporary))fs.unlinkSync(temporary);}
35
+ return {path:file,document:next};
36
+ }
@@ -0,0 +1,47 @@
1
+ // Reusable orchestration over existing execution adapters, with no new assertion engine.
2
+ export async function runBusinessWorkflow({ plan, runId, preflight, runFlow, runCapability, onProgress = async () => {} }) {
3
+ if (!plan?.ready || !/^[a-zA-Z0-9_-]{8,120}$/.test(runId)) throw new Error("A ready workflow plan and unique run ID are required");
4
+ // Validate all artifacts/accounts before the first external mutation.
5
+ await preflight(plan);
6
+ const steps = [];
7
+ let failed = false;
8
+ let started = false;
9
+ const deadline = Date.now() + 15 * 60 * 1000;
10
+ const execute = async step => {
11
+ let result;
12
+ try {
13
+ await onProgress({ phase:step.phase,text:step.title });
14
+ if (step.kind === "flow") {
15
+ const remaining = Math.floor((deadline - Date.now()) / 1000);
16
+ if (remaining < 30) throw new Error("Workflow time budget exhausted");
17
+ result = await runFlow(step,runId,Math.min(120,remaining));
18
+ } else if (step.kind === "capability") {
19
+ if (step.phase !== "cleanup" && Date.now() >= deadline) throw new Error("Workflow time budget exhausted");
20
+ result = await runCapability(step,runId);
21
+ } else throw new Error("This step has no supported execution adapter");
22
+ const ok = step.kind === "flow" ? result.passed === true
23
+ : result.status === "observed" && (step.phase !== "verify" || (result.assertions?.length > 0 && result.assertions.every(assertion => assertion.matched === true)));
24
+ const inconclusive=step.kind === "flow" && (result.timedOut === true || ![0,1].includes(result.exitCode));
25
+ return { id:step.id,title:step.title,phase:step.phase,status:inconclusive ? "inconclusive" : ok ? (["prepare","cleanup"].includes(step.phase) ? "acknowledged" : "observed") : "failed",result };
26
+ } catch(error) { return {id:step.id,title:step.title,phase:step.phase,status:"inconclusive",message:error.message || "Execution failed"}; }
27
+ };
28
+ try {
29
+ for (const step of plan.steps.filter(step => step.phase !== "cleanup")) {
30
+ if (failed) {steps.push({id:step.id,title:step.title,phase:step.phase,status:"not-run"});continue;}
31
+ started = true;
32
+ const result = await execute(step);
33
+ steps.push(result);
34
+ failed = !["observed","acknowledged"].includes(result.status);
35
+ }
36
+ } finally {
37
+ // A setup request can mutate before failing. Always attempt the reviewed cleanup.
38
+ for (const step of plan.steps.filter(step => step.phase === "cleanup")) {
39
+ steps.push(started ? await execute(step) : {id:step.id,title:step.title,phase:step.phase,status:"not-run"});
40
+ }
41
+ }
42
+ const status = steps.some(step => step.status === "inconclusive") ? "inconclusive"
43
+ : steps.some(step => step.status === "failed") ? "failed"
44
+ : steps.some(step => step.status === "not-run") ? "inconclusive" : "observed";
45
+ return {kind:"tapp-business-workflow-run",workflowId:plan.workflowId,revision:plan.revision,bindingFingerprint:plan.bindingFingerprint,
46
+ runId,status,steps,scope:plan.scope,completedAt:new Date().toISOString()};
47
+ }
@@ -0,0 +1,50 @@
1
+ export interface BusinessStep {
2
+ id: string; title: string; outcome: string; kind: 'flow'|'capability'|'contract'|'manual';
3
+ ref?: string; actor?: string; targetId?: string;
4
+ }
5
+ export interface BusinessWorkflow {
6
+ id: string; title: string; outcome: string; priority: 'critical'|'high'|'normal';
7
+ decision: 'proposed'|'confirmed'|'deferred'; steps: BusinessStep[];
8
+ }
9
+ export interface BusinessWorkflows {
10
+ kind: 'tapp-business-workflows'; schemaVersion: 1; revision: number; description: string; workflows: BusinessWorkflow[];
11
+ }
12
+ export interface WorkflowProject {
13
+ targets?: Array<{id:string;name?:string;platform:string}>;
14
+ flows?: Array<{path:string;name?:string;platform?:string;sha256?:string}>;
15
+ actors?: Array<{name:string;status?:string}>;
16
+ map?: {nodes?:Array<{id:string;name?:string;stateLabel?:string}>}|null;
17
+ model?: {artifacts?:{contracts?:Array<{path:string;name:string}>};criticalJourneys?:Array<{contract:string;businessValue?:string}>}|null;
18
+ }
19
+ export interface WorkflowConnection {
20
+ environment?:string; configuration?:unknown; accessRevision?:string;
21
+ actors?:Array<{name:string;status?:string}>;
22
+ capabilities?:Array<{name:string;phase:string;status:string}>;
23
+ }
24
+ export interface WorkflowRun {
25
+ operationId?:string; workflowId:string; revision:number; bindingFingerprint:string;
26
+ status:string; steps?:Array<{id:string;status:string}>; completedAt?:string;
27
+ }
28
+ export interface WorkflowPlan {
29
+ kind: 'tapp-business-workflow-plan'; workflowId:string; revision:number; title:string; outcome:string;
30
+ bindingFingerprint:string; ready:boolean;
31
+ steps:Array<BusinessStep & {phase:string;sha256?:string;platform?:string;missing:string[]}>;
32
+ blockers:Array<{code:string;stepId?:string;message:string}>;
33
+ correlationVariable:string; requiresCorrelation:boolean; scope:string;
34
+ }
35
+ export const BUSINESS_WORKFLOW_PATH: string;
36
+ export function workflowFingerprint(value:unknown):string;
37
+ export function emptyBusinessWorkflows():BusinessWorkflows;
38
+ export function validateBusinessWorkflows(document:unknown):string[];
39
+ export function normalizeBusinessWorkflows(document:unknown):BusinessWorkflows;
40
+ export function discoverBusinessWorkflows(project?:WorkflowProject,connection?:WorkflowConnection):{
41
+ targets:NonNullable<WorkflowProject['targets']>; actors:NonNullable<WorkflowConnection['actors']>;
42
+ flows:NonNullable<WorkflowProject['flows']>; contracts:Array<{path:string;name:string}>;
43
+ capabilities:NonNullable<WorkflowConnection['capabilities']>;
44
+ surfaces:Array<{id:string;name:string;basis:string}>; proposals:BusinessWorkflow[]; questions:string[]; scope:string;
45
+ };
46
+ export function planBusinessWorkflow(document:BusinessWorkflows,workflowId:string,project?:WorkflowProject,connection?:WorkflowConnection):WorkflowPlan;
47
+ export function businessWorkflowCoverage(document:BusinessWorkflows,project?:WorkflowProject,connection?:WorkflowConnection,runs?:WorkflowRun[]):{
48
+ kind:string; revision:number; counts:Record<string,number>; scope:string;
49
+ workflows:Array<{id:string;title:string;priority:string;status:string;blockers:WorkflowPlan['blockers'];steps:Array<{id:string;title:string;outcome:string;status:string}>;lastRun?:WorkflowRun}>;
50
+ };
@@ -0,0 +1,169 @@
1
+ // One portable workflow definition above existing Flows, contracts and backend hooks.
2
+ // Discovery proposes scope; only recorded execution can supply observations.
3
+ import { createHash } from "node:crypto";
4
+
5
+ export const BUSINESS_WORKFLOW_PATH = ".tapp/business-workflows.json";
6
+ const idPattern = /^[a-zA-Z][a-zA-Z0-9_-]{0,79}$/;
7
+ const flowPattern = /^\.tapp\/flows\/[a-zA-Z0-9_-]+\.(yml|yaml|json)$/;
8
+ const object = value => value && typeof value === "object" && !Array.isArray(value);
9
+ const text = (value, max = 1000) => typeof value === "string" && value.trim().length > 0 && value.length <= max;
10
+ function canonical(value) {
11
+ if (Array.isArray(value)) return value.map(canonical);
12
+ return object(value) ? Object.fromEntries(Object.keys(value).sort().map(key => [key, canonical(value[key])])) : value;
13
+ }
14
+ export function workflowFingerprint(value) {
15
+ return createHash("sha256").update(JSON.stringify(canonical(value))).digest("hex");
16
+ }
17
+ export function emptyBusinessWorkflows() {
18
+ return { kind: "tapp-business-workflows", schemaVersion: 1, revision: 0, description: "", workflows: [] };
19
+ }
20
+ export function validateBusinessWorkflows(document) {
21
+ const errors = [];
22
+ if (!object(document)) return ["Workflow map must be an object"];
23
+ if (document.kind !== "tapp-business-workflows" || document.schemaVersion !== 1) errors.push("Unsupported workflow map format");
24
+ if (!Number.isSafeInteger(document.revision) || document.revision < 0) errors.push("Invalid map revision");
25
+ if (typeof document.description !== "string" || document.description.length > 2000) errors.push("Business description must be at most 2000 characters");
26
+ if (!Array.isArray(document.workflows) || document.workflows.length > 30) return [...errors, "Use at most 30 workflows"];
27
+ const ids = new Set();
28
+ for (const workflow of document.workflows) {
29
+ if (!object(workflow)) { errors.push("Invalid workflow"); continue; }
30
+ if (!text(workflow.id,80) || !idPattern.test(workflow.id) || ids.has(workflow.id)) errors.push("Workflow IDs must be unique names");
31
+ ids.add(workflow.id);
32
+ if (!text(workflow.title, 160) || !text(workflow.outcome)) errors.push(`${workflow.id}: describe the workflow and expected business outcome`);
33
+ if (!["critical", "high", "normal"].includes(workflow.priority)) errors.push(`${workflow.id}: invalid priority`);
34
+ if (!["proposed", "confirmed", "deferred"].includes(workflow.decision)) errors.push(`${workflow.id}: invalid review decision`);
35
+ if (!Array.isArray(workflow.steps) || !workflow.steps.length || workflow.steps.length > 20) { errors.push(`${workflow.id}: use 1–20 steps`); continue; }
36
+ const steps = new Set();
37
+ for (const step of workflow.steps) {
38
+ if (!object(step)) { errors.push(`${workflow.id}: invalid step`); continue; }
39
+ if (!text(step.id,80) || !idPattern.test(step.id) || steps.has(step.id)) errors.push(`${workflow.id}: step IDs must be unique names`);
40
+ steps.add(step.id);
41
+ if (!text(step.title, 160) || !text(step.outcome)) errors.push(`${workflow.id}/${step.id}: describe the step and expected outcome`);
42
+ if (!["flow", "capability", "contract", "manual"].includes(step.kind)) errors.push(`${step.id}: invalid proof type`);
43
+ if (step.kind !== "manual" && !text(step.ref, 500)) errors.push(`${step.id}: select a proof reference`);
44
+ if (step.kind === "flow" && !flowPattern.test(step.ref)) errors.push(`${step.id}: select a saved .tapp/flows artifact`);
45
+ if (step.actor !== undefined && !idPattern.test(step.actor)) errors.push(`${step.id}: invalid account name`);
46
+ if (step.targetId !== undefined && !text(step.targetId, 300)) errors.push(`${step.id}: invalid target`);
47
+ }
48
+ }
49
+ if (Buffer.byteLength(JSON.stringify(document)) > 64000) errors.push("Workflow map must be 64 KB or smaller");
50
+ return errors;
51
+ }
52
+
53
+ // Copy only declarative fields. Caller-provided evidence, verification status and
54
+ // approval metadata can never be smuggled into a persisted definition.
55
+ export function normalizeBusinessWorkflows(document) {
56
+ const errors = validateBusinessWorkflows(document);
57
+ if (errors.length) throw new Error(errors.join("; "));
58
+ return { kind: "tapp-business-workflows", schemaVersion: 1, revision: document.revision,
59
+ description: document.description.trim(), workflows: document.workflows.map(workflow => ({
60
+ id: workflow.id, title: workflow.title.trim(), outcome: workflow.outcome.trim(), priority: workflow.priority,
61
+ decision: workflow.decision,
62
+ steps: workflow.steps.map(step => ({ id: step.id, title: step.title.trim(), outcome: step.outcome.trim(), kind: step.kind,
63
+ ...(step.ref ? { ref: step.ref } : {}), ...(step.actor ? { actor: step.actor } : {}), ...(step.targetId ? { targetId: step.targetId } : {}) })),
64
+ })) };
65
+ }
66
+
67
+ export function discoverBusinessWorkflows(project = {}, connection = {}) {
68
+ const targets = project.targets || [];
69
+ const sole = targets.length === 1 ? targets[0] : null;
70
+ const flows = project.flows || [];
71
+ const contracts = project.model?.artifacts?.contracts || [];
72
+ const actors = connection.actors || project.actors || [];
73
+ const capabilities = connection.capabilities || [];
74
+ const surfaces = (project.map?.nodes || []).slice(0, 100).map(node => ({ id: String(node.id), name: String(node.stateLabel || node.name || "Observed screen"), basis: "runtime-observed" }));
75
+ const proposals = [];
76
+ for (const contract of contracts.slice(0, 15)) proposals.push({
77
+ id: `journey_${workflowFingerprint(contract.path).slice(0, 16)}`, title: contract.name,
78
+ outcome: (project.model?.criticalJourneys || []).find(journey => journey.contract === contract.name)?.businessValue || `Check the assertions in ${contract.name}`,
79
+ priority: "high", decision: "proposed",
80
+ steps: [{ id: "contract", title: contract.name, outcome: "The existing reviewed contract's assertions hold on the selected target.", kind: "contract", ref: contract.path }],
81
+ });
82
+ for (const flow of flows.slice(0, 15)) proposals.push({
83
+ id: `journey_${workflowFingerprint(flow.path).slice(0, 16)}`, title: flow.name || flow.path,
84
+ outcome: "Confirm which business outcome this recorded flow is intended to protect.", priority: "normal", decision: "proposed",
85
+ steps: [{ id: "flow", title: flow.name || "Recorded flow", outcome: "The recorded flow's explicit assertions hold.", kind: "flow", ref: flow.path,
86
+ ...(sole ? { targetId: sole.id } : {}) }],
87
+ });
88
+ for (const surface of surfaces.slice(0, Math.max(0, 30 - proposals.length))) proposals.push({
89
+ id: `surface_${workflowFingerprint(surface.id).slice(0, 16)}`, title: `Check ${surface.name}`.slice(0,160),
90
+ outcome: "Confirm the business outcome and relevant failure cases for this observed surface.", priority: "normal", decision: "proposed",
91
+ steps: [{ id: "outcome", title: surface.name.slice(0,160), outcome: "Define what must happen here and how to observe the result.", kind: "manual" }],
92
+ });
93
+ return { targets, actors, flows, contracts, capabilities, surfaces, proposals,
94
+ questions: ["What outcome matters most to your business?", "Who takes part, and what should each person see?", "What must happen after submission, including failures or cancellation?"],
95
+ scope: "Proposals come from available artifacts and observed screens. They are not a complete inventory of your business; confirm omitted systems, roles and exception paths." };
96
+ }
97
+
98
+ export function planBusinessWorkflow(document, workflowId, project = {}, connection = {}) {
99
+ const map = normalizeBusinessWorkflows(document);
100
+ const workflow = map.workflows.find(item => item.id === workflowId);
101
+ if (!workflow) throw new Error("Workflow not found");
102
+ const inventory = discoverBusinessWorkflows(project, connection);
103
+ const blockers = [];
104
+ if (workflow.decision !== "confirmed") blockers.push({ code: "review-required", message: "Confirm the workflow's outcomes and steps before running it." });
105
+ if (connection.environment !== "test") blockers.push({ code: "test-environment-required", message: "Select a suitable test environment in app connections before automatic workflow execution. The label alone does not create a sandbox." });
106
+ let lastPhase = -1;
107
+ const steps = workflow.steps.map(step => {
108
+ const missing = [];
109
+ let phase = "exercise";
110
+ let sha256;
111
+ let target;
112
+ if (step.kind === "manual") missing.push("Record a flow, connect a verifier, or attach an existing contract for this outcome.");
113
+ if (step.kind === "contract") {
114
+ if (!inventory.contracts.some(item => item.path === step.ref)) missing.push("The referenced contract is unavailable.");
115
+ missing.push("Run this contract through the existing repository release gate; automatic business workflow execution currently supports web Flows and backend capabilities.");
116
+ }
117
+ if (step.kind === "flow") {
118
+ const flow = inventory.flows.find(item => item.path === step.ref);
119
+ sha256 = flow?.sha256;
120
+ if (!flow) missing.push("Record or import this flow first.");
121
+ if (!/^[a-f0-9]{64}$/.test(sha256 || "")) missing.push("Refresh project inspection to fingerprint this saved flow.");
122
+ target = inventory.targets.find(item => item.id === step.targetId);
123
+ if (!target) missing.push("Choose an available application target.");
124
+ else if (target.platform !== "web" || (flow?.platform && flow.platform !== "web")) missing.push("Automatic business workflow execution currently requires a web target; native flows remain available through their existing tools.");
125
+ if (!step.actor) missing.push("Choose the account for this step, or explicitly choose public access.");
126
+ else if (step.actor !== "public" && !inventory.actors.some(actor => actor.name === step.actor && actor.status === "configured")) missing.push(`Connect the ${step.actor} account needed for this step.`);
127
+ }
128
+ if (step.kind === "capability") {
129
+ const capability = inventory.capabilities.find(item => item.name === step.ref);
130
+ phase = capability?.phase || "verify";
131
+ if (!capability || capability.status !== "configured") missing.push(`Connect the ${step.ref} backend capability.`);
132
+ }
133
+ const phaseOrder = { prepare: 0, exercise: 1, verify: 2, cleanup: 3 }[phase];
134
+ if (phaseOrder === undefined || phaseOrder < lastPhase) missing.push("Order steps as preparation, app activity, backend verification, then cleanup.");
135
+ lastPhase = phaseOrder ?? lastPhase;
136
+ for (const message of missing) blockers.push({ code: "step-setup-required", stepId: step.id, message });
137
+ return { ...step, phase, ...(sha256 ? { sha256 } : {}), ...(target ? { platform: target.platform } : {}), missing };
138
+ });
139
+ const hasBackendVerification = steps.some(step => step.kind === "capability" && step.phase === "verify");
140
+ if (!steps.some(step => step.kind === "flow" || (step.kind === "capability" && step.phase === "verify"))) {
141
+ blockers.push({code:"verification-required",message:"Include an app flow or backend verification; setup acknowledgements alone cannot check a workflow."});
142
+ }
143
+ if (steps.some(step => step.kind === "capability" && step.phase === "prepare") && !steps.some(step => step.kind === "capability" && step.phase === "cleanup")) {
144
+ blockers.push({ code: "cleanup-required", message: "Add a cleanup capability for the prepared test data." });
145
+ }
146
+ const bindingFingerprint = workflowFingerprint({ workflow, targets: inventory.targets, flows: inventory.flows,
147
+ configuration: connection.configuration || {}, accessRevision:connection.accessRevision || "", actors: inventory.actors, capabilities: inventory.capabilities });
148
+ return { kind: "tapp-business-workflow-plan", workflowId, revision: map.revision, title: workflow.title,
149
+ outcome: workflow.outcome, bindingFingerprint, ready: !blockers.length, steps, blockers,
150
+ correlationVariable: "TEST_RUN_ID", requiresCorrelation: hasBackendVerification,
151
+ scope: "Runs only the confirmed steps and their explicit assertions. Success is an observation of those checks, not a release verdict or proof of complete business coverage." };
152
+ }
153
+
154
+ export function businessWorkflowCoverage(document, project = {}, connection = {}, runs = []) {
155
+ const map = normalizeBusinessWorkflows(document);
156
+ const workflows = map.workflows.map(workflow => {
157
+ const plan = planBusinessWorkflow(map, workflow.id, project, connection);
158
+ const run = runs.find(item => item.workflowId === workflow.id && item.revision === map.revision && item.bindingFingerprint === plan.bindingFingerprint);
159
+ const status = workflow.decision === "deferred" ? "deferred" : workflow.decision !== "confirmed" ? "needs-confirmation"
160
+ : !plan.ready ? "blocked" : !run ? "unverified" : run.status === "observed" ? "observed" : run.status === "failed" ? "failed" : "inconclusive";
161
+ return { id: workflow.id, title: workflow.title, priority: workflow.priority, status, blockers: plan.blockers,
162
+ steps: plan.steps.map(step => ({ id: step.id, title: step.title, outcome: step.outcome,
163
+ status: step.missing.length ? "blocked" : run?.steps?.find(item => item.id === step.id)?.status || "unverified" })),
164
+ ...(run ? { lastRun: run } : {}) };
165
+ });
166
+ return { kind: "tapp-business-workflow-coverage", revision: map.revision, workflows,
167
+ counts: Object.fromEntries(["needs-confirmation", "blocked", "unverified", "observed", "failed", "inconclusive", "deferred"].map(status => [status, workflows.filter(item => item.status === status).length])),
168
+ scope: "Coverage of the explicitly listed workflows only. Unlisted workflows, roles, surfaces and failure cases remain unknown. Previous runs describe their recorded time and environment; they do not establish current health." };
169
+ }
@@ -0,0 +1,16 @@
1
+ export interface EnvironmentConfiguration {
2
+ url?: string;
3
+ environment?: 'test' | 'production' | 'unknown';
4
+ defaultActor?: string;
5
+ actors?: Record<string, { role?: string; credentials: Record<'email' | 'password', { env: string }> }>;
6
+ capabilities?: Record<string, { phase: 'prepare' | 'verify' | 'cleanup'; description?: string; origin?: string; path: string; method?: 'GET' | 'POST'; headers?: Record<string, { env: string }>; status?: number; expect?: Record<string, string | number | boolean> }>;
7
+ }
8
+ export function validateEnvironmentConfiguration(config: unknown): string[];
9
+ export function environmentReadiness(config?: EnvironmentConfiguration, bindings?: string[]): {
10
+ actors: Array<{name:string;role:string;status:string;missingBindings:string[];authenticated:boolean}>;
11
+ capabilities: Array<{name:string;phase:string;description:string;status:string;missingBindings:string[];verified:boolean}>;
12
+ defaultActor: string | null; environment: string; isolation: string; message:string;
13
+ };
14
+ export function selectEnvironmentActor(config: EnvironmentConfiguration, requested?: string): ({name:string} & NonNullable<EnvironmentConfiguration['actors']>[string]) | null;
15
+
16
+ export function isCredentialBinding(name: string): boolean;
@@ -0,0 +1,78 @@
1
+ // Shared capability contract. Provider-specific code belongs behind named hooks.
2
+ // Configuration describes authority; only runtime results establish outcomes.
3
+ export const environmentPhases = ["prepare", "verify", "cleanup"];
4
+ const namePattern = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;
5
+ const bindingPattern = /^[A-Z_][A-Z0-9_]{0,127}$/;
6
+ export function isCredentialBinding(name) {
7
+ return bindingPattern.test(name || "") && !/^(?:HOME|PATH|USER|LOGNAME|SHELL|TMPDIR|TEMP|TMP|PYTHONPATH|JAVA_HOME|NODE_OPTIONS|NODE_PATH|LD_.*|DYLD_.*|HTTP_PROXY|HTTPS_PROXY|ALL_PROXY|NO_PROXY|TAPP_HOME|TAPP_BROWSER_PROXY_SERVER|TAPP_ENFORCE_PUBLIC_EGRESS|FLOW_LOG|TAPP_FLOW_EVIDENCE_DIR)$/i.test(name);
8
+ }
9
+
10
+ export function environmentReadiness(configuration = {}, availableBindings = []) {
11
+ const present = new Set(availableBindings);
12
+ const actors = Object.entries(configuration.actors || {}).map(([name, actor]) => {
13
+ const missing = Object.values(actor.credentials || {}).map(binding => binding.env).filter(name => !present.has(name));
14
+ return { name, role: actor.role || name, status: missing.length ? "needs-credentials" : "configured", missingBindings: missing, authenticated: false };
15
+ });
16
+ const capabilities = Object.entries(configuration.capabilities || {}).map(([name, capability]) => {
17
+ const missing = Object.values(capability.headers || {}).map(binding => binding.env).filter(name => !present.has(name));
18
+ return { name, phase: capability.phase, description: capability.description || name, status: missing.length ? "needs-credentials" : "configured", missingBindings: missing, verified: false };
19
+ });
20
+ return { actors, capabilities, defaultActor: configuration.defaultActor || (actors.length === 1 ? actors[0].name : null),
21
+ environment: configuration.environment || "unknown", isolation: "not-verified",
22
+ message: "Configured access is reusable. Successful login and backend outcomes are established by execution, not configuration." };
23
+ }
24
+
25
+ export function validateEnvironmentConfiguration(config) {
26
+ const errors = [];
27
+ if (!config || typeof config !== "object" || Array.isArray(config)) return ["Environment must be an object"];
28
+ for (const key of Object.keys(config)) if (!["url", "environment", "defaultActor", "actors", "capabilities"].includes(key)) errors.push(`Unsupported environment field: ${key}`);
29
+ if (config.url) {
30
+ try { const url = new URL(config.url); if (url.protocol !== "https:" || url.username || url.password || url.search || url.hash) throw new Error(); }
31
+ catch { errors.push("App URL must use HTTPS without credentials, query parameters, or a fragment"); }
32
+ }
33
+ if (!["test", "production", "unknown"].includes(config.environment || "unknown")) errors.push("Environment must be test, production, or unknown");
34
+ for (const section of ["actors", "capabilities"]) {
35
+ if (config[section] && (typeof config[section] !== "object" || Array.isArray(config[section]))) errors.push(`${section} must be an object`);
36
+ if (Object.keys(config[section] || {}).length > 30) errors.push(`Too many ${section}`);
37
+ }
38
+ for (const [name, actor] of Object.entries(config.actors || {})) {
39
+ if (!namePattern.test(name) || !actor || typeof actor !== "object" || Array.isArray(actor)) { errors.push("Invalid actor"); continue; }
40
+ if(actor.role !== undefined && (typeof actor.role !== "string" || actor.role.length > 120))errors.push("Actor role must be a short name");
41
+ for (const key of Object.keys(actor)) if (!["role", "credentials"].includes(key)) errors.push(`Unsupported actor field: ${key}`);
42
+ for (const key of ["email", "password"]) if (!isCredentialBinding(actor.credentials?.[key]?.env)) errors.push(`Actor ${name} needs a ${key} binding`);
43
+ for (const [key, binding] of Object.entries(actor.credentials || {})) {
44
+ if (!["email", "password"].includes(key) || !binding || Object.keys(binding).some(key => key !== "env")) errors.push("Actors contain email/password binding names only");
45
+ }
46
+ }
47
+ if (config.defaultActor && !config.actors?.[config.defaultActor]) errors.push("Default actor is not configured");
48
+ for (const [name, hook] of Object.entries(config.capabilities || {})) {
49
+ if (!namePattern.test(name) || !hook || typeof hook !== "object") { errors.push("Invalid capability"); continue; }
50
+ if(hook.description !== undefined && (typeof hook.description !== "string" || hook.description.length > 500))errors.push("Capability description must be short text");
51
+ for (const key of Object.keys(hook)) if (!["phase", "description", "origin", "path", "method", "headers", "status", "expect"].includes(key)) errors.push(`Unsupported capability field: ${key}`);
52
+ if (hook.origin) {
53
+ try { const origin = new URL(hook.origin); if(origin.protocol !== "https:" || origin.origin !== hook.origin)throw new Error(); }
54
+ catch {errors.push(`Capability ${name} needs an HTTPS origin without a path or credentials`);}
55
+ }
56
+ if (!environmentPhases.includes(hook.phase)) errors.push(`Capability ${name} needs prepare, verify, or cleanup phase`);
57
+ if (!/^\/(?!\/)[^?#\\]*$/.test(hook.path || "")) errors.push(`Capability ${name} needs a same-origin path`);
58
+ if (!["GET", "POST"].includes(hook.method || "POST")) errors.push("Hook method must be GET or POST");
59
+ if (hook.phase !== "verify" && hook.method === "GET") errors.push("Preparation and cleanup must use POST");
60
+ if (hook.status !== undefined && (!Number.isInteger(hook.status) || hook.status < 200 || hook.status > 299)) errors.push("Expected status must be 2xx");
61
+ for (const [header, binding] of Object.entries(hook.headers || {})) {
62
+ if (!/^(authorization|x-[a-z0-9-]+)$/i.test(header) || !isCredentialBinding(binding?.env) || Object.keys(binding).some(key => key !== "env")) errors.push("Hook headers must contain authorized credential binding names");
63
+ }
64
+ if (hook.expect !== undefined && (!hook.expect || typeof hook.expect !== "object" || Array.isArray(hook.expect))) errors.push("Expected JSON fields must be an object");
65
+ for (const [field, value] of Object.entries(hook.expect || {})) {
66
+ if (!/^[A-Za-z][A-Za-z0-9_.]{0,127}$/.test(field) || !["string", "number", "boolean"].includes(typeof value)) errors.push("Expected fields must be scalar JSON paths");
67
+ }
68
+ if (hook.phase === "verify" && !Object.keys(hook.expect || {}).length) errors.push(`Verification ${name} must assert at least one JSON field`);
69
+ }
70
+ return errors;
71
+ }
72
+
73
+ export function selectEnvironmentActor(configuration, requested) {
74
+ const names = Object.keys(configuration.actors || {});
75
+ const name = requested || configuration.defaultActor || (names.length === 1 ? names[0] : null);
76
+ if (name && !configuration.actors?.[name]) throw new Error(`Actor '${name}' is not configured`);
77
+ return name ? { name, ...configuration.actors[name] } : null;
78
+ }