@floless/app 0.126.1 → 0.126.2

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.
@@ -54612,7 +54612,7 @@ function appVersion() {
54612
54612
  return resolveVersion({
54613
54613
  isSea: isSea2(),
54614
54614
  sqVersionXml: readSqVersionXml(),
54615
- define: true ? "0.126.1" : void 0,
54615
+ define: true ? "0.126.2" : void 0,
54616
54616
  pkgVersion: readPkgVersion()
54617
54617
  });
54618
54618
  }
@@ -54628,7 +54628,7 @@ function resolveChannel(s) {
54628
54628
  function appChannel() {
54629
54629
  return resolveChannel({
54630
54630
  isSea: isSea2(),
54631
- define: true ? "0.126.1" : void 0,
54631
+ define: true ? "0.126.2" : void 0,
54632
54632
  // argv[1] is the entry the runtime actually loaded (…/dist/floless-server.cjs), which is what
54633
54633
  // carries the npx cache prefix. Absent under the SEA exe, which never reaches the npx branch.
54634
54634
  modulePath: process.argv[1]
@@ -59925,6 +59925,118 @@ function decodeSnapshots(inputs) {
59925
59925
  });
59926
59926
  }
59927
59927
 
59928
+ // request-instruction.ts
59929
+ function instructionFor(req) {
59930
+ if (req.type === "use-template" && req.template) {
59931
+ const t = req.template;
59932
+ const n = t.node || {};
59933
+ return `In floless app "${req.appId}", add a node from my saved template "${t.name}" (agent ${n.agent || n.kind || "unspecified \u2014 read the template from GET /api/templates"}${n.command ? " / " + n.command : ""}, config ${JSON.stringify(n.config || {})}). Edit the .flo, then run \`aware app compile\`.`;
59934
+ }
59935
+ if (req.type === "tweak") {
59936
+ const base = `In floless app "${req.appId}", change only node "${req.nodeId}": ${req.instruction}. Edit just that node in the .flo, then run \`aware app compile\`.`;
59937
+ return req.snapshots && req.snapshots.length ? `${base}
59938
+ Reference snapshots (read these for visual context): ${req.snapshots.join(", ")}` : base;
59939
+ }
59940
+ if (req.type === "ui-customize") {
59941
+ const scope = req.panelId ? ` (panel "${req.panelId}")` : "";
59942
+ return `Customize my floless.app dashboard${scope}: ${req.instruction}. Edit ~/.floless/ui/extensions.json per the floless-app-ui skill, then check it with \`aware agent invoke ui validate\`.`;
59943
+ }
59944
+ if (req.type === "rebake") {
59945
+ const where = req.inputName ? ` (input "${req.inputName}")` : "";
59946
+ const snaps = req.snapshots && req.snapshots.length ? `
59947
+ New drawing${req.snapshots.length > 1 ? "s" : ""} (read for the re-extraction): ${req.snapshots.join(", ")}` : "";
59948
+ return `In floless app "${req.appId}", re-read & re-bake${where} per the floless-app-rebake skill: ${req.instruction}${snaps}`;
59949
+ }
59950
+ if (req.type === "guide") {
59951
+ return `Walk me through the floless workflow "${req.appId}" \u2014 explain in plain English what it does and how to run it (set its inputs \u2192 Compile \u2192 \u25B6 Run). Use your floless-app-${req.appId} skill if one exists; otherwise read the workflow's own description and node notes from GET /api/app/${req.appId} and explain from those. This is a guided explanation \u2014 don't change anything.`;
59952
+ }
59953
+ if (req.type === "new-workflow") {
59954
+ return `Help me build a brand-new floless workflow from scratch, step by step, with your floless-app-new-workflow skill. Ask me what I want it to do, then before writing any node confirm the agents it needs are installed (offer to install a missing one from the catalogue, or to report a not-yet-existing agent as an idea). Author the .flo node by node, verifying each step is correct (plain-English descriptions, validate, compile, a real run), and finish by installing \u2192 Compile \u2192 \u25B6 Run so I can see it work and approve.`;
59955
+ }
59956
+ if (req.type === "revision-read") {
59957
+ const isInitialRead = !req.baseVersion || req.baseVersion <= 0;
59958
+ const snaps = req.snapshots && req.snapshots.length ? `
59959
+ ${isInitialRead ? "Initial" : "Revised"} drawing${req.snapshots.length > 1 ? "s" : ""} (read these): ${req.snapshots.join(", ")}` : "";
59960
+ const note = req.instruction ? `
59961
+ My note: ${req.instruction}` : "";
59962
+ const messageHint = isInitialRead ? "<plain-English what was read>" : "<plain-English what changed>";
59963
+ const post = `Only after the review checkpoint is complete, POST /api/projects/${req.project}/revision-read with { contract, message: "${messageHint}", requestId: "${req.id}" }. The server derives the base version + source provenance from this queued request. For a steel.takeoff/v1 contract it records a "revision-read" version and clears the request. For a steel.model/v2 model it answers 202 and STAGES the read for the user to review instead \u2014 the request stays open until they confirm it in the app, and the version appears then. Either way, do NOT DELETE the request yourself. If you can't read the set, POST /api/projects/${req.project}/revision-requests/${req.id}/fail with { error }.`;
59964
+ if ((req.appTemplateId || req.appId) === "vectorize") {
59965
+ if (isInitialRead) {
59966
+ return `In floless project "${req.project}" (app "${req.appId}"), an initial drawing was attached \u2014 trace it into this project as its first version (do NOT create a new project). Vectorize the drawing per the floless-app-vectorize skill into a drawing.vector/v1 contract: emit clean, editable 2D vector geometry (sheets \u2192 elements: lines / polylines / curves / text, each on its layer), NOT steel members or a takeoff. A vector PDF is read deterministically (exact geometry, no guessing); a photo, scan or hand sketch is traced by a fenced vision extraction that flags every uncertain stroke (low confidence) for the user's review. ${post}${snaps}${note}`;
59967
+ }
59968
+ return `In floless project "${req.project}" (app "${req.appId}"), a REVISED drawing was attached \u2014 re-read (vectorize) it into the SAME project as a new version (do NOT create a new project). Vectorize the drawing per the floless-app-vectorize skill into a drawing.vector/v1 contract: emit clean, editable 2D vector geometry (sheets \u2192 elements: lines / polylines / curves / text, each on its layer), NOT steel members or a takeoff. A vector PDF is read deterministically (exact geometry, no guessing); a photo, scan or hand sketch is traced by a fenced vision extraction that flags every uncertain stroke (low confidence) for the user's review. ${post}${snaps}${note}`;
59969
+ }
59970
+ if (req.contractType === STEEL_V2) {
59971
+ return `In floless project "${req.project}" (app "${req.appId}"), a REVISED drawing set was attached \u2014 re-read it into the SAME project as a new version (do NOT create a new project). This project holds a steel.model/v2 model, so compose a steel.model/v2 document, NOT a steel.takeoff/v1: members live in ONE root \`members[]\` array in WORLD MILLIMETRES (each with \`from\`/\`to\` as { x, y, z }), not per sheet in display pixels. Member ids are MODEL-GLOBAL \u2014 preserve the id of every member the revision still shows and mint a new one only for a genuinely new member; there is no sheet label to preserve alongside it. Where the drawing does not give an elevation, write \`{ unknown: true }\` for that z \u2014 never a substituted default, because a fabricated elevation moves steel. Record what each SHEET actually showed as evidence on that plan's \`memberObservations\` (with its \`binding.memberIds\`), and use \`plans[].memberRefs\` for members a sheet displays but never observed. COPY THE CURRENT MODEL'S ROOT \`grid\` THROUGH UNCHANGED into the document you post to /revision-read \u2014 never omit the key, because omitting it is not how you say "unchanged" and a read that drops it is refused. If the revised set genuinely shows the printed grid in a NEW place, write the new grid there instead: it is staged as a proposal the user accepts in the review, never a silent write. (The pre-read verb below still refuses a grid \u2014 that is a different endpoint.) Follow the floless-app-steel-takeoff skill's mandatory two-phase gate exactly as for v1: FIRST GET /api/contract/${req.appId}?project=${req.project} to read the CURRENT model and KEEP its ETag, do the deterministic PyMuPDF steel-filter pass only, send ONLY the pre-read blocks to PUT /api/projects/${req.project}/steel-prepass with { filter } and If-Match: <that ETag> \u2014 never the whole contract \u2014 then STOP and tell me to open Drawings \u2192 Steel Filter, review the facets, and Save. Do NOT read members, build the model, open 3D, or POST /revision-read until I explicitly come back after saving the filter. ${post}${snaps}${note}`;
59972
+ }
59973
+ if (isInitialRead) {
59974
+ return `In floless project "${req.project}" (app "${req.appId}"), an initial drawing set was attached \u2014 read it into this project as its first steel model version (do NOT create a new project). Follow the floless-app-steel-takeoff skill's mandatory two-phase gate. FIRST, GET /api/contract/${req.appId}?project=${req.project} and KEEP its ETag response header. A 404 "no contract for this app yet" here is NORMAL and not an error \u2014 a project created by dropping a drawing starts empty; it simply means this is the create case, so you will send If-None-Match: * instead of an ETag. (A project seeded from an existing model does return a contract and an ETag.) Then do the deterministic PyMuPDF steel-filter pass only: identify the framing-plan sheets, enumerate the drawing elements by layer/thickness/color into contract.filter.sheets/facets, write it back \u2014 if that GET returned NO contract this is the create case, so PUT the whole document to /api/contract/${req.appId}?project=${req.project} with If-None-Match: * ; if it DID return one, send only the pre-read blocks to PUT /api/projects/${req.project}/steel-prepass with { filter } and If-Match: <that ETag>. The prepass verb takes filter, datum and per-sheet { grid, datum_at, datum_ref, control2_at, control2_ref, elevation_in } and REFUSES members, connections and joints by name, so it cannot replace the model you are about to read. Either write is refused with 428 if it carries no precondition, and If-Match must be the exact ETag \u2014 If-Match: * is refused, because this verb patches the document you read. On 412 re-GET, re-apply your changes to the new document, and retry rather than repeating the same body. Then STOP and tell me to open Drawings \u2192 Steel Filter, review/narrow the steel facets, and Save. Do NOT read members, build the model, open 3D, or POST /revision-read until I explicitly come back after saving the filter. AFTER that saved-filter checkpoint, read members from the saved filter selection and compose the steel.takeoff/v1 contract. ${post}${snaps}${note}`;
59975
+ }
59976
+ return `In floless project "${req.project}" (app "${req.appId}"), a REVISED drawing set was attached \u2014 re-read it into the SAME project as a new version (do NOT create a new project). Follow the floless-app-steel-takeoff skill's mandatory two-phase gate. FIRST, GET /api/contract/${req.appId}?project=${req.project} to read the CURRENT contract, then do the deterministic PyMuPDF steel-filter pass only for the revised drawing set: identify the framing-plan sheets, enumerate drawing elements by layer/thickness/color into contract.filter.sheets/facets, preserve any compatible existing filter selections, send ONLY the pre-read blocks to PUT /api/projects/${req.project}/steel-prepass with { filter } and If-Match: <the ETag from the GET you just did> \u2014 never the whole contract, because this project already holds a model and a full PUT would replace its members without review. The verb takes filter, datum and per-sheet { grid, datum_at, datum_ref, control2_at, control2_ref, elevation_in } and refuses everything else by name. A write with no precondition is refused with 428, and If-Match must be the exact ETag \u2014 If-Match: * is refused, because this verb patches the document you read. On 412 re-GET, re-apply, and retry rather than repeating the same body. Then STOP and tell me to open Drawings \u2192 Steel Filter, review/narrow the steel facets, and Save. Do NOT read members, build the model, open 3D, or POST /revision-read until I explicitly come back after saving the filter. AFTER that saved-filter checkpoint, read members from the saved filter selection, compose the updated steel.takeoff/v1 contract, and PRESERVE each still-present member's id AND its sheet label (mint a NEW id only for a genuinely new member; drop the id of a member the revision deleted) so the version comparison matches members \u2014 do NOT renumber the whole model. ${post}${snaps}${note}`;
59977
+ }
59978
+ if (req.type === "tweak-contract") {
59979
+ const where = req.project ? `?project=${req.project}` : "";
59980
+ const scope = req.project ? `floless project "${req.project}" (app "${req.appId}")` : `floless app "${req.appId}"`;
59981
+ const detail = req.intent ? `
59982
+ This is an insert-a-detail request: intent "${req.intent}"${req.target && req.target.sheet ? ` on sheet "${req.target.sheet}"` : ""}${req.target && req.target.ids && req.target.ids.length ? `, target id(s) ${req.target.ids.join(", ")}` : ""}.` : "";
59983
+ const snaps = req.snapshots && req.snapshots.length ? `
59984
+ Screenshot${req.snapshots.length > 1 ? "s" : ""} (read these \u2014 they show which member or region "this" means): ${req.snapshots.join(", ")}` : "";
59985
+ return `In ${scope}, edit the steel contract per the floless-app-tweak-contract skill: ${req.instruction || "apply the requested change"}. GET /api/contract/${req.appId}${where} first and KEEP its ETag \u2014 the document's own \`type\` tells you which shape you are editing, and you write back that SAME shape. Apply the change, preserving every field you are not changing, then PUT the full document to /api/contract/${req.appId}${where} with If-Match: <that ETag> (If-None-Match: * only when the GET returned no ETag at all). A blind write is refused with 428; on 412 re-GET, re-apply your edit to the NEW document, and retry rather than repeating the same body. Writing a tweak is not approval \u2014 leave the approval gate to the user.${detail}${snaps}`;
59986
+ }
59987
+ if (req.type === "knowledge-organize") {
59988
+ const kb = `/api/projects/${req.project}/knowledge`;
59989
+ return `In floless project "${req.project}", organize the Project Knowledge Base with your floless-app-knowledge skill. Claim the pass with POST ${kb}/requests/${req.id}/start \u2014 it takes the organize lock and returns { baseRevision, generationId, wikiDir }. Read the source set from GET ${kb}/status (the rows it marks state:"organizing" ARE this pass's snapshot), read each source's bytes from that project's knowledge/blobs/<blobSha256>, and compile the project wiki INTO the returned wikiDir \u2014 never invent a path. Publish with POST ${kb}/requests/${req.id}/finish { generationId, lintSummary }; on any failure release the lock with POST ${kb}/requests/${req.id}/fail { error }. Do NOT DELETE this request and do NOT use /api/requests/${req.id} \u2014 finish/fail resolves it server-side. If finish returns { rerun: true } the sources changed mid-pass: POST ${kb}/organize once for a FRESH request, then run start \u2192 compile \u2192 finish on that new id exactly once.`;
59990
+ }
59991
+ if (req.type === "knowledge-adjust") {
59992
+ return `In floless project "${req.project}", reshape the Project Knowledge Base with your floless-app-knowledge skill: ${req.instruction || "apply the requested change"}. Edit the project's wiki notes accordingly, then re-organize so the published generation reflects the change.`;
59993
+ }
59994
+ return req.instruction ? String(req.instruction).trim() : "";
59995
+ }
59996
+ var REQUEST_SKILL = {
59997
+ "use-template": "floless-app-workflows",
59998
+ tweak: "floless-app-workflows",
59999
+ "ui-customize": "floless-app-ui",
60000
+ "tweak-contract": "floless-app-tweak-contract",
60001
+ rebake: "floless-app-rebake",
60002
+ "revision-read": "floless-app-steel-takeoff",
60003
+ // The guided-tour ask is picked up by onboarding; the instruction body names the
60004
+ // per-app floless-app-<appId> skill for depth when one exists.
60005
+ guide: "floless-app-onboarding",
60006
+ // Build-a-workflow-from-scratch: its own guide skill (interview → author → verify).
60007
+ "new-workflow": "floless-app-new-workflow",
60008
+ // Project Knowledge Base: one self-contained skill drives both the organize lifecycle and adjusts.
60009
+ "knowledge-organize": "floless-app-knowledge",
60010
+ "knowledge-adjust": "floless-app-knowledge"
60011
+ };
60012
+ function markerFor(req, base, body = instructionFor(req)) {
60013
+ if (!body) return "";
60014
+ let skill = REQUEST_SKILL[req.type] || "floless-app-workflows";
60015
+ if (req.type === "revision-read" && (req.appTemplateId || req.appId) === "vectorize") skill = "floless-app-vectorize";
60016
+ const clears = req.type === "revision-read" ? (req.appTemplateId || req.appId) === "steel-model" ? `apply it in two phases: first write the Steel Filter checkpoint through the steel-prepass verb and stop for user Save; only after that checkpoint use the route in the line below (that POST clears this request, or stages it for the user's review \u2014 either way do NOT DELETE it separately).` : `apply it via the route in the line below (that POST clears this request \u2014 do NOT DELETE it separately).` : req.type === "knowledge-organize" ? `drive it through the start \u2192 finish/fail lifecycle routes in the line below (finish or fail clears this request \u2014 do NOT DELETE it separately, that would strand the organize lock).` : `apply that request, then DELETE ${base}/api/requests/${req.id}.`;
60017
+ return `[floless-request type=${req.type} id=${req.id}] \u2014 queued from the FloLess Dashboard. Apply it with your ${skill} skill: fetch the authoritative spec from GET ${base}/api/requests, ${clears} Don't run the line below verbatim.`;
60018
+ }
60019
+ var selfOrigin = () => `http://127.0.0.1:${Number(process.env.PORT ?? 4317)}`;
60020
+ function withPrompt(r, base = selfOrigin()) {
60021
+ try {
60022
+ const prompt = instructionFor(r);
60023
+ return { ...r, prompt, marker: markerFor(r, base, prompt) };
60024
+ } catch (err2) {
60025
+ console.error(`[request-instruction] could not compose request ${r.id} (${r.type}):`, err2);
60026
+ return { ...r, prompt: r.instruction ? String(r.instruction).trim() : "", marker: "" };
60027
+ }
60028
+ }
60029
+ var NO_ENRICHMENTS = { appTemplateId: void 0, contractType: void 0, projectName: void 0 };
60030
+ function enrichedView(r, enrich, base = selfOrigin()) {
60031
+ let extra = {};
60032
+ try {
60033
+ extra = enrich(r);
60034
+ } catch (err2) {
60035
+ console.error(`[request-instruction] could not enrich request ${r.id} (${r.type}):`, err2);
60036
+ }
60037
+ return withPrompt({ ...r, ...NO_ENRICHMENTS, ...extra }, base);
60038
+ }
60039
+
59928
60040
  // connection-import.ts
59929
60041
  var import_node_fs27 = require("node:fs");
59930
60042
  var import_node_path25 = require("node:path");
@@ -62139,6 +62251,9 @@ function previewMigration(v1, ctx) {
62139
62251
  issues.push({ code: "legacy-provenance-assumed", severity: "decision", message: `${legacyProvenance} record(s) carry no recognised source.kind; their observations are recorded as 'auto-read' because a steel.takeoff/v1 document is by definition reader output, but that assumption must be confirmed before commit` });
62140
62252
  }
62141
62253
  const derivedFor = (sheet, key) => reg2.registrations.find((r) => r.sheet === sheet)?.derivedControls?.[key];
62254
+ const unanchoredOriginSheets = new Set(
62255
+ reg2.issues.filter((issue) => issue.code === "control-origin-unanchored" && issue.sheet).map((issue) => issue.sheet)
62256
+ );
62142
62257
  const plans = arr2(doc.plans).filter(isObj2).map((p) => {
62143
62258
  const sheet = str2(p.sheet) ?? "";
62144
62259
  const out = { sheet, viewKind: "plan", memberObservations: obsBySheet.get(sheet) ?? [] };
@@ -62159,6 +62274,9 @@ function previewMigration(v1, ctx) {
62159
62274
  if (Array.isArray(p[k])) out[k] = clone(p[k]);
62160
62275
  }
62161
62276
  const refPair = ([atKey, refKey]) => {
62277
+ if (unanchoredOriginSheets.has(sheet)) {
62278
+ return;
62279
+ }
62162
62280
  const parsed = intersectionRef(p[refKey]);
62163
62281
  const at = Array.isArray(p[atKey]) ? clone(p[atKey]) : null;
62164
62282
  const usable = parsed.state === "valid" || parsed.state === "absent" && refKey === "datum_ref";
@@ -64202,7 +64320,7 @@ function registerKnowledgeRoutes(app) {
64202
64320
  try {
64203
64321
  const project = getProject(req.params.id);
64204
64322
  if (!project) return reply.status(404).send({ ok: false, error: `unknown project: ${req.params.id}` });
64205
- const request = addRequest({ type: "knowledge-organize", project: project.id });
64323
+ const request = withPrompt({ ...addRequest({ type: "knowledge-organize", project: project.id }), appTemplateId: void 0, contractType: void 0 });
64206
64324
  return { ok: true, request };
64207
64325
  } catch (e) {
64208
64326
  if (e instanceof ProjectError) return reply.status(400).send({ ok: false, error: e.message });
@@ -64216,7 +64334,7 @@ function registerKnowledgeRoutes(app) {
64216
64334
  if (!project) return reply.status(404).send({ ok: false, error: `unknown project: ${req.params.id}` });
64217
64335
  const prompt = typeof req.body?.prompt === "string" ? req.body.prompt.trim() : "";
64218
64336
  if (!prompt) return reply.status(400).send({ ok: false, error: "prompt required" });
64219
- const request = addRequest({ type: "knowledge-adjust", project: project.id, instruction: prompt });
64337
+ const request = withPrompt({ ...addRequest({ type: "knowledge-adjust", project: project.id, instruction: prompt }), appTemplateId: void 0, contractType: void 0 });
64220
64338
  return { ok: true, request };
64221
64339
  } catch (e) {
64222
64340
  if (e instanceof ProjectError) return reply.status(400).send({ ok: false, error: e.message });
@@ -68918,13 +69036,12 @@ function revisionReadContractError(appId, contract) {
68918
69036
  }
68919
69037
 
68920
69038
  // revision-routes.ts
68921
- var requestView = (r) => r === null ? null : {
68922
- ...r,
68923
- appTemplateId: r.appId ? resolveTemplateId(r.appId) : void 0,
69039
+ var requestView = (r) => r === null ? null : enrichedView(r, (x) => ({
69040
+ appTemplateId: x.appId ? resolveTemplateId(x.appId) : void 0,
68924
69041
  // The project must BELONG to this app — `contractPath()` keys a project store by project id alone,
68925
69042
  // so a mismatched pair would report the other app's type and send the AI after its document.
68926
- contractType: r.type === "revision-read" && r.appId && r.project && getProject(r.project)?.app === r.appId ? storedContractType(r.appId, r.project) : void 0
68927
- };
69043
+ contractType: x.type === "revision-read" && x.appId && x.project && getProject(x.project)?.app === x.appId ? storedContractType(x.appId, x.project) : void 0
69044
+ }));
68928
69045
  function sweepOrphanedStaged() {
68929
69046
  for (const key of listStagedKeys()) {
68930
69047
  const rec = readStagedRecord(key);
@@ -74135,13 +74252,15 @@ function uniqueProjectExportFilename(projectId, preferred) {
74135
74252
 
74136
74253
  // workspace-approved-snapshot.ts
74137
74254
  var WorkspaceSnapshotError = class extends Error {
74138
- constructor(status, message, notReviewable) {
74255
+ constructor(status, message, notReviewable, version) {
74139
74256
  super(message);
74140
74257
  this.status = status;
74141
74258
  this.notReviewable = notReviewable;
74259
+ this.version = version;
74142
74260
  }
74143
74261
  status;
74144
74262
  notReviewable;
74263
+ version;
74145
74264
  };
74146
74265
  var NoApprovedVersionError = class extends WorkspaceSnapshotError {
74147
74266
  constructor() {
@@ -74156,7 +74275,7 @@ function approvedRows(projectId) {
74156
74275
  if (project.uuid) {
74157
74276
  const tainted = allRows.find((v) => v.gate === "model" && v.kind === "approve" && !v.approval);
74158
74277
  if (tainted) {
74159
- throw new WorkspaceSnapshotError(409, `project has no approved version: approved version ${tainted.n} has no approval proof`);
74278
+ throw new WorkspaceSnapshotError(409, `project has no approved version: approved version ${tainted.n} has no approval proof`, void 0, tainted.n);
74160
74279
  }
74161
74280
  }
74162
74281
  const projectTime = Date.parse(project.createdAt);
@@ -74215,7 +74334,7 @@ function currentApprovedSnapshot(projectId, version) {
74215
74334
  headDiverged: row.n !== latest.n
74216
74335
  };
74217
74336
  }
74218
- function approvedSnapshotForMetadata(projectId, surface) {
74337
+ function approvedSnapshotForMetadata(projectId, surface, onRefusal) {
74219
74338
  try {
74220
74339
  return currentApprovedSnapshot(projectId);
74221
74340
  } catch (error) {
@@ -74223,6 +74342,7 @@ function approvedSnapshotForMetadata(projectId, surface) {
74223
74342
  if (error instanceof WorkspaceSnapshotError && error.status === 404) throw error;
74224
74343
  if (error instanceof WorkspaceSnapshotError || error instanceof ContractPolicyError) {
74225
74344
  const status = error instanceof WorkspaceSnapshotError ? error.status : error.code;
74345
+ onRefusal?.(error);
74226
74346
  console.error(
74227
74347
  `${surface}: project ${projectId} has an approved version the gate refused to serve (${status}) \u2014 reporting no approved head. ${error.message}`
74228
74348
  );
@@ -85560,17 +85680,20 @@ async function startServer() {
85560
85680
  memo?.set(r.project, name);
85561
85681
  return name;
85562
85682
  };
85563
- const requestView2 = (r) => r === null ? null : { ...r, appTemplateId: r.appId ? resolveTemplateId(r.appId) : void 0, contractType: requestContractType(r), projectName: requestProjectName(r) };
85683
+ const requestView2 = (r) => r === null ? null : enrichedView(r, (x) => ({
85684
+ appTemplateId: x.appId ? resolveTemplateId(x.appId) : void 0,
85685
+ contractType: requestContractType(x),
85686
+ projectName: requestProjectName(x)
85687
+ }));
85564
85688
  const requestViews = (list) => {
85565
85689
  const root5 = templateIdResolver();
85566
85690
  const typeMemo = /* @__PURE__ */ new Map();
85567
85691
  const nameMemo = /* @__PURE__ */ new Map();
85568
- return list.map((r) => ({
85569
- ...r,
85570
- appTemplateId: r.appId ? root5(r.appId) : void 0,
85571
- contractType: requestContractType(r, typeMemo),
85572
- projectName: requestProjectName(r, nameMemo)
85573
- }));
85692
+ return list.map((r) => enrichedView(r, (x) => ({
85693
+ appTemplateId: x.appId ? root5(x.appId) : void 0,
85694
+ contractType: requestContractType(x, typeMemo),
85695
+ projectName: requestProjectName(x, nameMemo)
85696
+ })));
85574
85697
  };
85575
85698
  app.get("/api/projects", async () => ({ ok: true, projects: projectViews(listProjects()) }));
85576
85699
  app.post(
@@ -85989,12 +86112,35 @@ async function startServer() {
85989
86112
  const project = getProject(req.params.id);
85990
86113
  if (!project) return reply.status(404).send({ ok: false, error: `unknown project: ${req.params.id}` });
85991
86114
  return withLifecycleLock("project", project.id, () => {
85992
- const latest = approvedSnapshotForMetadata(project.id, "listing export sources");
86115
+ let defaultUnavailable = null;
86116
+ const recordRefusal = (error) => {
86117
+ const approved = listVersions(project.id).find((row) => row.gate === "model" && row.kind === "approve");
86118
+ defaultUnavailable = {
86119
+ reason: "refused",
86120
+ version: error instanceof WorkspaceSnapshotError ? error.version ?? approved?.n ?? null : approved?.n ?? null,
86121
+ message: error.message
86122
+ };
86123
+ };
86124
+ const latest = approvedSnapshotForMetadata(project.id, "listing export sources", recordRefusal);
86125
+ let approvedRows2 = [];
86126
+ if (!defaultUnavailable) {
86127
+ try {
86128
+ approvedRows2 = listApprovedVersionMetadata(project.id);
86129
+ } catch (error) {
86130
+ if (error instanceof WorkspaceSnapshotError || error instanceof ContractPolicyError) {
86131
+ recordRefusal(error);
86132
+ console.error(`listing export sources: project ${project.id} has approved history the gate refused to enumerate. ${error.message}`);
86133
+ } else {
86134
+ throw error;
86135
+ }
86136
+ }
86137
+ }
85993
86138
  return {
85994
86139
  ok: true,
85995
86140
  default: latest ? { kind: "latest-approved", version: latest.version.n, hash: latest.contractHash } : null,
86141
+ defaultUnavailable,
85996
86142
  working: { kind: "working", draft: true, etag: storeEtag(project.app, project.id), epoch: readWorkingRevisionManifest(project)?.epoch ?? null },
85997
- approved: listApprovedVersionMetadata(project.id).map((row) => ({ kind: "approved", version: row.n })),
86143
+ approved: approvedRows2.map((row) => ({ kind: "approved", version: row.n })),
85998
86144
  checkpoints: listProjectCheckpoints(project).map((saved) => ({ kind: "checkpoint", checkpointId: saved.id, hash: saved.draftHash, baseVersion: saved.base?.version ?? null }))
85999
86145
  };
86000
86146
  }, { label: "listing export sources" });
@@ -2,7 +2,7 @@
2
2
  name: floless-app-bridge
3
3
  description: This skill should be used when the user is driving the floless.app web UI (the local prompt-native front door at http://127.0.0.1:4317) and wants the terminal AI to act on what they did there — picking up queued Tweak requests, "use this template" requests, or the context of a node they selected/edited on the canvas. Use it when the user says things like "apply the tweak I just queued", "I clicked Tweak on the bom node — make that change", "pick up my floless request", "what queued requests are pending", or after they double-click/Tweak a node in the UI. ALSO use it the moment the user pastes a message that begins with a `[floless-request type=… id=…]` marker — that is a request copied from the FloLess Dashboard, NOT a literal instruction to run; resolve it via the API. It reads the floless.app local API, applies the change to the app's .flo, recompiles, and clears the request. Workspace approval, pending model changes, history/checkpoints, and export-source choices belong to floless-app-approval instead.
4
4
  metadata:
5
- version: 0.3.0
5
+ version: 0.3.1
6
6
  ---
7
7
 
8
8
  # floless.app ↔ terminal bridge
@@ -97,7 +97,7 @@ digraph { "GET /api/requests" -> "for each pending" -> "read app .flo + node" ->
97
97
  the user wants to choose which to apply (not just the oldest), use the `floless-app-queue` skill** —
98
98
  it lists the queue in plain English and asks which to process, then routes each pick to the owning
99
99
  authoring skill. Its §2 table is where the whole type→skill routing is written out in prose (the
100
- authority itself is `REQUEST_SKILL` in `web/aware.js`, which that table restates).
100
+ authority itself is `REQUEST_SKILL` in `server/request-instruction.ts`, which that table restates).
101
101
  2. **Locate the app source.** The editable `.flo` is the repo copy `demos/<appId>/<appId>.flo`
102
102
  (preferred — it's version-controlled); the installed copy is `~/.aware/apps/<appId>/<appId>.flo`.
103
103
  Edit the **repo** copy. `GET /api/app/<appId>` returns the parsed nodes + each node's
@@ -131,7 +131,7 @@ resolved by their own POST, and the marker the Dashboard copies says so in its o
131
131
  | `knowledge-organize` | `POST /api/projects/<project>/knowledge/requests/<id>/finish` (or `…/fail`) — after claiming the pass with `…/start` | the lock you took at `…/start` is only reclaimable after `LOCK_STALE_MS` (**10 minutes**), and the leftover `organize.json` leaves the Knowledge pane showing "Organizing…" with Organize **disabled indefinitely** |
132
132
 
133
133
  This is the same per-type rule the UI encodes in `markedInstruction()`'s `clears` branch
134
- (`web/aware.js`) — and the reason `clearAllRequests()` there refuses to include an organize in its
134
+ (`server/request-instruction.ts`) — and the reason `clearAllRequests()` in `web/aware.js` refuses to include an organize in its
135
135
  bulk clear. `floless-app-queue` §4 carries the same table.
136
136
 
137
137
  ## Guardrails
@@ -2,7 +2,7 @@
2
2
  name: floless-app-queue
3
3
  description: This skill should be used when the user has MULTIPLE floless.app requests queued from the Dashboard and wants to see them and choose which to process, rather than the AI just picking up the oldest one. Use it when the user says things like "what's in my floless queue", "list my queued floless requests", "show me the pending requests and let me pick", "I queued a few tweaks — which should I apply?", "let me choose what to process", or "pick from the floless queue". It lists the pending requests from GET /api/requests in plain language (type, which app/node/project, the instruction), asks the user which one(s) to apply, then hands each chosen request to the owning skill (floless-app-workflows / -tweak-contract / -ui / -rebake / -onboarding / -new-workflow / -steel-takeoff / -vectorize / -knowledge) which applies it and clears it. It is the interactive picker that sits in front of floless-app-bridge (which is the actual pull-apply-clear engine).
4
4
  metadata:
5
- version: 0.2.1
5
+ version: 0.2.2
6
6
  ---
7
7
 
8
8
  # floless.app queue picker
@@ -60,7 +60,7 @@ map to:
60
60
 
61
61
  The type union itself is `FlolessRequest` in `server/floless-store.ts` — a type in the union with no row
62
62
  above means this table is stale, and the union is right. The routing is `REQUEST_SKILL` in
63
- `web/aware.js`, with the `revision-read` app-aware override right below it; it now covers every member
63
+ `server/request-instruction.ts`, with the `revision-read` app-aware override in `markerFor()` below it; it now covers every member
64
64
  of the union, so if it and this table disagree, the code is right and this table is stale — say so.
65
65
 
66
66
  Note the count of screenshots for requests that carry `snapshots`. If a request has an unfamiliar
@@ -92,7 +92,7 @@ curl -s -X DELETE http://127.0.0.1:4317/api/requests/<id> # the UI's "requests
92
92
  | `knowledge-organize` | `POST /api/projects/<project>/knowledge/requests/<id>/finish` (or `…/fail`) — after claiming the pass with `…/start` | the lock you took at `…/start` is only reclaimable after `LOCK_STALE_MS` (**10 minutes**) — and the leftover `organize.json`, which only finish/fail removes, leaves the Knowledge pane showing "Organizing…" with Organize **disabled indefinitely**, so the user cannot even re-queue |
93
93
 
94
94
  Every other type is applied-then-`DELETE`d as above. This is the same per-type rule the UI encodes in
95
- `markedInstruction()`'s `clears` branch (`web/aware.js`) — check there if a type's ending is unclear.
95
+ `markerFor()`'s `clears` branch (`server/request-instruction.ts`) — check there if a type's ending is unclear.
96
96
 
97
97
  Process the picks in the order the user gave (or oldest-first if they said "all"). Re-run the
98
98
  owning skill's normal verification before reporting each one done.
package/dist/web/aware.js CHANGED
@@ -6772,194 +6772,32 @@
6772
6772
  saveFavs = function saveFavsNoop() { $favCount.textContent = state.favorites.length; };
6773
6773
 
6774
6774
  // ── reverse channel: record intent for the host AI, copy a paste-ready line ──
6775
- function instructionFor(req) {
6776
- // `t.node` guarded, not assumed: a template saved by an older build (or hand-edited in
6777
- // templates.json) can carry a name and no node, and reading `.agent` off undefined THREW out of
6778
- // renderRequests' .map(), so `$list.innerHTML` was never assigned and loadRequests' `catch {}`
6779
- // ate it — the chip kept counting requests over a list that had silently stopped rendering.
6780
- if (req.type === 'use-template' && req.template) {
6781
- const t = req.template;
6782
- const n = t.node || {};
6783
- return `In floless app "${req.appId}", add a node from my saved template "${t.name}" (agent ${n.agent || n.kind || 'unspecified — read the template from GET /api/templates'}${n.command ? ' / ' + n.command : ''}, config ${JSON.stringify(n.config || {})}). Edit the .flo, then run \`aware app compile\`.`;
6784
- }
6785
- if (req.type === 'tweak') {
6786
- const base = `In floless app "${req.appId}", change only node "${req.nodeId}": ${req.instruction}. Edit just that node in the .flo, then run \`aware app compile\`.`;
6787
- return req.snapshots && req.snapshots.length
6788
- ? `${base}\nReference snapshots (read these for visual context): ${req.snapshots.join(', ')}`
6789
- : base;
6790
- }
6791
- if (req.type === 'ui-customize') {
6792
- const scope = req.panelId ? ` (panel "${req.panelId}")` : '';
6793
- return `Customize my floless.app dashboard${scope}: ${req.instruction}. Edit ~/.floless/ui/extensions.json per the floless-app-ui skill, then check it with \`aware agent invoke ui validate\`.`;
6794
- }
6795
- if (req.type === 'rebake') {
6796
- const where = req.inputName ? ` (input "${req.inputName}")` : '';
6797
- const snaps = req.snapshots && req.snapshots.length
6798
- ? `\nNew drawing${req.snapshots.length > 1 ? 's' : ''} (read for the re-extraction): ${req.snapshots.join(', ')}`
6799
- : '';
6800
- return `In floless app "${req.appId}", re-read & re-bake${where} per the floless-app-rebake skill: ${req.instruction}${snaps}`;
6801
- }
6802
- if (req.type === 'guide') {
6803
- return `Walk me through the floless workflow "${req.appId}" — explain in plain English what it does and how to run it (set its inputs → Compile → ▶ Run). Use your floless-app-${req.appId} skill if one exists; otherwise read the workflow's own description and node notes from GET /api/app/${req.appId} and explain from those. This is a guided explanation — don't change anything.`;
6804
- }
6805
- if (req.type === 'new-workflow') {
6806
- return `Help me build a brand-new floless workflow from scratch, step by step, with your floless-app-new-workflow skill. Ask me what I want it to do, then before writing any node confirm the agents it needs are installed (offer to install a missing one from the catalogue, or to report a not-yet-existing agent as an idea). Author the .flo node by node, verifying each step is correct (plain-English descriptions, validate, compile, a real run), and finish by installing → Compile → ▶ Run so I can see it work and approve.`;
6807
- }
6808
- if (req.type === 'revision-read') {
6809
- const isInitialRead = !req.baseVersion || req.baseVersion <= 0;
6810
- const snaps = req.snapshots && req.snapshots.length
6811
- ? `\n${isInitialRead ? 'Initial' : 'Revised'} drawing${req.snapshots.length > 1 ? 's' : ''} (read these): ${req.snapshots.join(', ')}`
6812
- : '';
6813
- const note = req.instruction ? `\nMy note: ${req.instruction}` : '';
6814
- const messageHint = isInitialRead ? '<plain-English what was read>' : '<plain-English what changed>';
6815
- const post = `Only after the review checkpoint is complete, POST /api/projects/${req.project}/revision-read with { contract, message: "${messageHint}", requestId: "${req.id}" }. The server derives the base version + source provenance from this queued request. For a steel.takeoff/v1 contract it records a "revision-read" version and clears the request. For a steel.model/v2 model it answers 202 and STAGES the read for the user to review instead — the request stays open until they confirm it in the app, and the version appears then. Either way, do NOT DELETE the request yourself. If you can't read the set, POST /api/projects/${req.project}/revision-requests/${req.id}/fail with { error }.`;
6816
- // App-aware: the target contract shape differs per workspace app. A vectorize project holds a
6817
- // drawing.vector/v1 (clean editable 2D linework), NOT a steel takeoff — instructing the AI to
6818
- // read steel members would produce the wrong contract for the vector editor (spec §3.3g).
6819
- // The lineage ROOT, not the live id: these branches encode what CONTRACT SHAPE the app's
6820
- // document has, and a rename moves the id off the built-in they are written against. Sending a
6821
- // renamed vector project down the steel branch asks the AI for a steel.takeoff/v1 — the wrong
6822
- // document entirely. Falls back to appId for an older server that ships no templateId.
6823
- if ((req.appTemplateId || req.appId) === 'vectorize') {
6824
- if (isInitialRead) {
6825
- return `In floless project "${req.project}" (app "${req.appId}"), an initial drawing was attached — trace it into this project as its first version (do NOT create a new project). Vectorize the drawing per the floless-app-vectorize skill into a drawing.vector/v1 contract: emit clean, editable 2D vector geometry (sheets → elements: lines / polylines / curves / text, each on its layer), NOT steel members or a takeoff. A vector PDF is read deterministically (exact geometry, no guessing); a photo, scan or hand sketch is traced by a fenced vision extraction that flags every uncertain stroke (low confidence) for the user's review. ${post}${snaps}${note}`;
6826
- }
6827
- return `In floless project "${req.project}" (app "${req.appId}"), a REVISED drawing was attached — re-read (vectorize) it into the SAME project as a new version (do NOT create a new project). Vectorize the drawing per the floless-app-vectorize skill into a drawing.vector/v1 contract: emit clean, editable 2D vector geometry (sheets → elements: lines / polylines / curves / text, each on its layer), NOT steel members or a takeoff. A vector PDF is read deterministically (exact geometry, no guessing); a photo, scan or hand sketch is traced by a fenced vision extraction that flags every uncertain stroke (low confidence) for the user's review. ${post}${snaps}${note}`;
6828
- }
6829
- // A MIGRATED project holds steel.model/v2, and that changes the document the AI must compose —
6830
- // not merely its wording. The store only accepts v2, so asking for a v1 take-off would have the
6831
- // whole read refused at the gateway AFTER it was done, which is the most expensive place to find
6832
- // out. `contractType` is what the store actually holds today (see requestContractType); it is
6833
- // absent on an older server, and absent falls through to the v1 branches below, unchanged.
6834
- //
6835
- // A revision-read against a v2 project is always a RE-read: v2 is reached by migrating a project
6836
- // that already held a model, so there is no "initial" case to distinguish. What differs from v1 is
6837
- // structural and is spelled out rather than left to be inferred, because every one of these is a
6838
- // place a v1-shaped answer would look plausible: members live at the document ROOT in world
6839
- // millimetres rather than per sheet in display pixels; ids are model-global, so the v1 rule
6840
- // "preserve the id AND its sheet label" does not apply and a bare id is the identity; an elevation
6841
- // the drawing does not give is `{ unknown: true }`, never a substituted default, because a
6842
- // fabricated elevation silently relocates steel; and what each SHEET showed is recorded as
6843
- // evidence on that plan's `memberObservations` instead of by owning the member.
6844
- if (req.contractType === 'steel.model/v2') {
6845
- return `In floless project "${req.project}" (app "${req.appId}"), a REVISED drawing set was attached — re-read it into the SAME project as a new version (do NOT create a new project). This project holds a steel.model/v2 model, so compose a steel.model/v2 document, NOT a steel.takeoff/v1: members live in ONE root \`members[]\` array in WORLD MILLIMETRES (each with \`from\`/\`to\` as { x, y, z }), not per sheet in display pixels. Member ids are MODEL-GLOBAL — preserve the id of every member the revision still shows and mint a new one only for a genuinely new member; there is no sheet label to preserve alongside it. Where the drawing does not give an elevation, write \`{ unknown: true }\` for that z — never a substituted default, because a fabricated elevation moves steel. Record what each SHEET actually showed as evidence on that plan's \`memberObservations\` (with its \`binding.memberIds\`), and use \`plans[].memberRefs\` for members a sheet displays but never observed. COPY THE CURRENT MODEL'S ROOT \`grid\` THROUGH UNCHANGED into the document you post to /revision-read — never omit the key, because omitting it is not how you say "unchanged" and a read that drops it is refused. If the revised set genuinely shows the printed grid in a NEW place, write the new grid there instead: it is staged as a proposal the user accepts in the review, never a silent write. (The pre-read verb below still refuses a grid — that is a different endpoint.) Follow the floless-app-steel-takeoff skill's mandatory two-phase gate exactly as for v1: FIRST GET /api/contract/${req.appId}?project=${req.project} to read the CURRENT model and KEEP its ETag, do the deterministic PyMuPDF steel-filter pass only, send ONLY the pre-read blocks to PUT /api/projects/${req.project}/steel-prepass with { filter } and If-Match: <that ETag> — never the whole contract — then STOP and tell me to open Drawings → Steel Filter, review the facets, and Save. Do NOT read members, build the model, open 3D, or POST /revision-read until I explicitly come back after saving the filter. ${post}${snaps}${note}`;
6846
- }
6847
- if (isInitialRead) {
6848
- return `In floless project "${req.project}" (app "${req.appId}"), an initial drawing set was attached — read it into this project as its first steel model version (do NOT create a new project). Follow the floless-app-steel-takeoff skill's mandatory two-phase gate. FIRST, GET /api/contract/${req.appId}?project=${req.project} and KEEP its ETag response header. A 404 "no contract for this app yet" here is NORMAL and not an error — a project created by dropping a drawing starts empty; it simply means this is the create case, so you will send If-None-Match: * instead of an ETag. (A project seeded from an existing model does return a contract and an ETag.) Then do the deterministic PyMuPDF steel-filter pass only: identify the framing-plan sheets, enumerate the drawing elements by layer/thickness/color into contract.filter.sheets/facets, write it back — if that GET returned NO contract this is the create case, so PUT the whole document to /api/contract/${req.appId}?project=${req.project} with If-None-Match: * ; if it DID return one, send only the pre-read blocks to PUT /api/projects/${req.project}/steel-prepass with { filter } and If-Match: <that ETag>. The prepass verb takes filter, datum and per-sheet { grid, datum_at, datum_ref, control2_at, control2_ref, elevation_in } and REFUSES members, connections and joints by name, so it cannot replace the model you are about to read. Either write is refused with 428 if it carries no precondition, and If-Match must be the exact ETag — If-Match: * is refused, because this verb patches the document you read. On 412 re-GET, re-apply your changes to the new document, and retry rather than repeating the same body. Then STOP and tell me to open Drawings → Steel Filter, review/narrow the steel facets, and Save. Do NOT read members, build the model, open 3D, or POST /revision-read until I explicitly come back after saving the filter. AFTER that saved-filter checkpoint, read members from the saved filter selection and compose the steel.takeoff/v1 contract. ${post}${snaps}${note}`;
6849
- }
6850
- return `In floless project "${req.project}" (app "${req.appId}"), a REVISED drawing set was attached — re-read it into the SAME project as a new version (do NOT create a new project). Follow the floless-app-steel-takeoff skill's mandatory two-phase gate. FIRST, GET /api/contract/${req.appId}?project=${req.project} to read the CURRENT contract, then do the deterministic PyMuPDF steel-filter pass only for the revised drawing set: identify the framing-plan sheets, enumerate drawing elements by layer/thickness/color into contract.filter.sheets/facets, preserve any compatible existing filter selections, send ONLY the pre-read blocks to PUT /api/projects/${req.project}/steel-prepass with { filter } and If-Match: <the ETag from the GET you just did> — never the whole contract, because this project already holds a model and a full PUT would replace its members without review. The verb takes filter, datum and per-sheet { grid, datum_at, datum_ref, control2_at, control2_ref, elevation_in } and refuses everything else by name. A write with no precondition is refused with 428, and If-Match must be the exact ETag — If-Match: * is refused, because this verb patches the document you read. On 412 re-GET, re-apply, and retry rather than repeating the same body. Then STOP and tell me to open Drawings → Steel Filter, review/narrow the steel facets, and Save. Do NOT read members, build the model, open 3D, or POST /revision-read until I explicitly come back after saving the filter. AFTER that saved-filter checkpoint, read members from the saved filter selection, compose the updated steel.takeoff/v1 contract, and PRESERVE each still-present member's id AND its sheet label (mint a NEW id only for a genuinely new member; drop the id of a member the revision deleted) so the version comparison matches members — do NOT renumber the whole model. ${post}${snaps}${note}`;
6851
- }
6852
- // The steel-model editor's "Ask AI" box, and the SAME channel its "insert a detail" flow uses.
6853
- // Deliberately does NOT name a contract shape: this channel serves both steel.takeoff/v1 and
6854
- // steel.model/v2 projects, and the stored document's own `type` is the authoritative answer the
6855
- // AI reads in the GET below. Naming a shape here would send a v2 project's edit at a v1 take-off
6856
- // — the same failure `contractType` exists to prevent on revision-read, solved one rung cheaper
6857
- // because this verb re-writes the document it just read rather than composing a new one.
6858
- if (req.type === 'tweak-contract') {
6859
- const where = req.project ? `?project=${req.project}` : '';
6860
- const scope = req.project ? `floless project "${req.project}" (app "${req.appId}")` : `floless app "${req.appId}"`;
6861
- // The insert flow carries a machine-readable intent + target so the AI creates a new detail
6862
- // rather than editing a placed one (or vice versa) — absent on an ordinary Ask AI request.
6863
- const detail = req.intent
6864
- ? `\nThis is an insert-a-detail request: intent "${req.intent}"${req.target && req.target.sheet ? ` on sheet "${req.target.sheet}"` : ''}${req.target && req.target.ids && req.target.ids.length ? `, target id(s) ${req.target.ids.join(', ')}` : ''}.`
6865
- : '';
6866
- const snaps = req.snapshots && req.snapshots.length
6867
- ? `\nScreenshot${req.snapshots.length > 1 ? 's' : ''} (read these — they show which member or region "this" means): ${req.snapshots.join(', ')}`
6868
- : '';
6869
- return `In ${scope}, edit the steel contract per the floless-app-tweak-contract skill: ${req.instruction || 'apply the requested change'}. ` +
6870
- `GET /api/contract/${req.appId}${where} first and KEEP its ETag — the document's own \`type\` tells you which shape you are editing, and you write back that SAME shape. ` +
6871
- `Apply the change, preserving every field you are not changing, then PUT the full document to /api/contract/${req.appId}${where} with If-Match: <that ETag> ` +
6872
- `(If-None-Match: * only when the GET returned no ETag at all). A blind write is refused with 428; on 412 re-GET, re-apply your edit to the NEW document, and retry rather than repeating the same body. ` +
6873
- `Writing a tweak is not approval — leave the approval gate to the user.${detail}${snaps}`;
6874
- }
6875
- // The Knowledge step's Organize verb. The lifecycle is SERVER-owned: start claims the organize
6876
- // lock and mints the generation dir; finish publishes it and clears this request; fail releases
6877
- // the lock. Naming the exact project-scoped routes matters — /api/requests/<id> is NOT the
6878
- // completion path here, and a stray DELETE would strand the lock until its stale timeout.
6879
- if (req.type === 'knowledge-organize') {
6880
- const kb = `/api/projects/${req.project}/knowledge`;
6881
- return `In floless project "${req.project}", organize the Project Knowledge Base with your floless-app-knowledge skill. ` +
6882
- `Claim the pass with POST ${kb}/requests/${req.id}/start — it takes the organize lock and returns { baseRevision, generationId, wikiDir }. ` +
6883
- `Read the source set from GET ${kb}/status (the rows it marks state:"organizing" ARE this pass's snapshot), read each source's bytes from that project's knowledge/blobs/<blobSha256>, ` +
6884
- `and compile the project wiki INTO the returned wikiDir — never invent a path. ` +
6885
- `Publish with POST ${kb}/requests/${req.id}/finish { generationId, lintSummary }; on any failure release the lock with POST ${kb}/requests/${req.id}/fail { error }. ` +
6886
- `Do NOT DELETE this request and do NOT use /api/requests/${req.id} — finish/fail resolves it server-side. ` +
6887
- `If finish returns { rerun: true } the sources changed mid-pass: POST ${kb}/organize once for a FRESH request, then run start → compile → finish on that new id exactly once.`;
6888
- }
6889
- // The KB "reshape it" box (its UI lands in a later slice; the verb + route already exist).
6890
- if (req.type === 'knowledge-adjust') {
6891
- return `In floless project "${req.project}", reshape the Project Knowledge Base with your floless-app-knowledge skill: ${req.instruction || 'apply the requested change'}. ` +
6892
- `Edit the project's wiki notes accordingly, then re-organize so the published generation reflects the change.`;
6893
- }
6894
- // No branch matched. Fall back to what the USER typed rather than to nothing.
6895
- //
6896
- // Every type in the union has an arm today — 'tweak-contract' was the last one missing and #629
6897
- // gave it one. This is the floor for the NEXT type added to FlolessRequest before its arm lands,
6898
- // because of what that gap cost last time: a blank row in the Requests window AND a
6899
- // markedInstruction() of '', so the ⧉ silently put nothing on the clipboard while still toasting
6900
- // success. The request was never empty — it carried a real instruction — it was just unreadable
6901
- // and uncopyable, which reads as noise worth deleting.
6902
- //
6903
- // A composed arm is strictly better (it tells the terminal AI the protocol, not just the wish),
6904
- // so this never competes with one: every arm above returns first. A type that legitimately
6905
- // carries no instruction still lands on '' here, and the row says so in words.
6906
- return req.instruction ? String(req.instruction).trim() : '';
6907
- }
6908
-
6909
- // Which product skill applies each request type (named in the copied marker so the
6910
- // terminal AI picks up the right one).
6911
- const REQUEST_SKILL = {
6912
- 'use-template': 'floless-app-workflows',
6913
- tweak: 'floless-app-workflows',
6914
- 'ui-customize': 'floless-app-ui',
6915
- 'tweak-contract': 'floless-app-tweak-contract',
6916
- rebake: 'floless-app-rebake',
6917
- 'revision-read': 'floless-app-steel-takeoff',
6918
- // The guided-tour ask is picked up by onboarding; the instruction body names the
6919
- // per-app floless-app-<appId> skill for depth when one exists.
6920
- guide: 'floless-app-onboarding',
6921
- // Build-a-workflow-from-scratch: its own guide skill (interview → author → verify).
6922
- 'new-workflow': 'floless-app-new-workflow',
6923
- // Project Knowledge Base: one self-contained skill drives both the organize lifecycle and adjusts.
6924
- 'knowledge-organize': 'floless-app-knowledge',
6925
- 'knowledge-adjust': 'floless-app-knowledge',
6926
- };
6927
-
6928
- // The COPIED form of a request: instructionFor() prefixed with a self-identifying
6929
- // marker so a PASTED request is unmistakable to the terminal AI — it's a queued FloLess
6930
- // Dashboard request to APPLY (via the named skill + the authoritative /api/requests),
6931
- // not a literal instruction to run verbatim (#73). The modal preview keeps the plain
6932
- // instructionFor() text; only the clipboard carries the marker.
6933
- function markedInstruction(req) {
6934
- const body = instructionFor(req);
6935
- if (!body) return '';
6936
- // revision-read's skill is app-specific: steel takeoff by default, floless-app-vectorize for a
6937
- // vector project — keep the clipboard marker in step with the app-aware instruction body above.
6938
- let skill = REQUEST_SKILL[req.type] || 'floless-app-workflows';
6939
- if (req.type === 'revision-read' && (req.appTemplateId || req.appId) === 'vectorize') skill = 'floless-app-vectorize';
6940
- const base = (typeof location !== 'undefined' && location.origin) ? location.origin : 'http://127.0.0.1:4317';
6941
- // A revision-read is cleared by its own /revision-read POST — a separate DELETE would 404. A
6942
- // knowledge-organize is likewise lifecycle-owned: its finish/fail POST clears it, and a stray
6943
- // DELETE would strand the organize lock until the stale timeout. Every other type is
6944
- // applied-then-DELETEd by the terminal AI.
6945
- const clears = req.type === 'revision-read'
6946
- ? ((req.appTemplateId || req.appId) === 'steel-model'
6947
- ? `apply it in two phases: first write the Steel Filter checkpoint through the steel-prepass verb and stop for user Save; only after that checkpoint use the route in the line below (that POST clears this request, or stages it for the user's review — either way do NOT DELETE it separately).`
6948
- : `apply it via the route in the line below (that POST clears this request — do NOT DELETE it separately).`)
6949
- : req.type === 'knowledge-organize'
6950
- ? `drive it through the start → finish/fail lifecycle routes in the line below (finish or fail clears this request — do NOT DELETE it separately, that would strand the organize lock).`
6951
- : `apply that request, then DELETE ${base}/api/requests/${req.id}.`;
6952
- const marker =
6953
- `[floless-request type=${req.type} id=${req.id}] — queued from the FloLess Dashboard. ` +
6954
- `Apply it with your ${skill} skill: fetch the authoritative spec from GET ${base}/api/requests, ` +
6955
- `${clears} Don't run the line below verbatim.`;
6956
- return `${marker}\n${body}`;
6957
- }
6775
+ //
6776
+ // The prompt is composed SERVER-side now — see server/request-instruction.ts — and every request
6777
+ // view arrives already carrying { prompt, marker }. What used to be ~180 lines of instructionFor()
6778
+ // / REQUEST_SKILL / markedInstruction() here are two ACCESSORS: the browser composes no request
6779
+ // text at all any more. That is the point, not a tidy-up — it is what lets #571s headless run
6780
+ // endpoint take only a request id instead of a caller-supplied prompt, on a server whose CORS hook
6781
+ // deliberately admits callers that send no Origin.
6782
+ //
6783
+ // Two fields joined here rather than one pre-joined server-side because use-template embeds an
6784
+ // unbounded JSON.stringify(node.config) (this repo has a known ~223 KB baked-blob node) and
6785
+ // /api/requests is POLLED — this keeps one copy of that on the wire per poll instead of two.
6786
+ // BOTH fields checked, not just `marker`. The server's invariant is that `marker` is '' exactly
6787
+ // when the body is — but gating on `marker` alone while interpolating `prompt` means a response
6788
+ // carrying one and not the other (an un-enriched route, a partial payload) composes
6789
+ // "[floless-request …]\nundefined": non-empty, so copyToClipboard succeeds and the green
6790
+ // "Copied — paste it to your terminal AI" fires, while the row beside it renders "this request has
6791
+ // no instruction". That is #629's exact signature re-armed one layer up, so the browser does not
6792
+ // lean on a server invariant it cannot see.
6793
+ const instructionFor = (req) => (req && req.prompt) || '';
6794
+ const markedInstruction = (req) => (req && req.marker && req.prompt) ? `${req.marker}\n${req.prompt}` : '';
6958
6795
 
6959
6796
  async function copyToClipboard(text) {
6960
6797
  // Nothing in this app ever legitimately copies an empty string — every caller passes a command
6961
6798
  // or an instruction body. An empty one means the caller has a hole (a request type with no
6962
- // instructionFor() arm returns '' from markedInstruction), and writing it would still resolve,
6799
+ // arm in server/request-instruction.ts composes an empty body, so the server sends no `marker`
6800
+ // and markedInstruction returns ''), and writing it would still resolve,
6963
6801
  // so the user gets a green "Copied" over an empty clipboard. Report the failure instead.
6964
6802
  if (!text) return false;
6965
6803
  try { await navigator.clipboard.writeText(text); return true; } catch { return false; }
@@ -7179,9 +7017,10 @@
7179
7017
  //
7180
7018
  // `r.instruction` — what the USER actually typed — is searched alongside the composed
7181
7019
  // instruction, not instead of it. The two usually overlap, but the composed body is only as
7182
- // complete as instructionFor()'s arms, and a request you can see but cannot find by the words
7183
- // you wrote in it is the worst kind of search. Same forward-looking floor as the fallback at the
7184
- // end of instructionFor(): keep this field even though every type has an arm today.
7020
+ // complete as the server builder's arms (server/request-instruction.ts), and a request you can
7021
+ // see but cannot find by the words you wrote in it is the worst kind of search. Same
7022
+ // forward-looking floor as the fallback at the end of ITS instructionFor(): keep this field even
7023
+ // though every type has an arm today.
7185
7024
  //
7186
7025
  // Both the NAME and the raw ids are searchable: you may know a project as "Cedar Mill Warehouse"
7187
7026
  // or as the `take-5-6677ee` in its URL, and either should find it.
@@ -7266,8 +7105,9 @@
7266
7105
  }
7267
7106
 
7268
7107
  // The Requests window: every queued change in a list, each copyable + clearable,
7269
- // plus copy-all / clear-all. instructionFor() output (which embeds file-derived
7270
- // appId/nodeId/instruction) is rendered via textContent-equivalent escaping.
7108
+ // plus copy-all / clear-all. The server-composed prompt (which embeds file-derived
7109
+ // appId/nodeId/instruction) is rendered via textContent-equivalent escaping — which matters MORE
7110
+ // now that the string arrives over the wire rather than being built from local state.
7271
7111
  function renderRequests() {
7272
7112
  const $list = document.getElementById('requests-list');
7273
7113
  const $clear = document.getElementById('requests-clear');
@@ -4472,7 +4472,7 @@
4472
4472
  label: 'Working copy · DRAFT', group: 'Drafts',
4473
4473
  });
4474
4474
  for (const saved of data.checkpoints || []) out.push({ selector: { kind: 'checkpoint', checkpointId: saved.checkpointId, expectedHash: saved.hash }, label: `Checkpoint ${String(saved.checkpointId).slice(0, 8)} · DRAFT`, group: 'Drafts', sub: saved.baseVersion ? `Pending work from v${saved.baseVersion}` : 'No approved baseline' });
4475
- for (const row of data.approved || []) {
4475
+ for (const row of data.defaultUnavailable?.reason === 'refused' ? [] : (data.approved || [])) {
4476
4476
  if (!data.default || Number(row.version) !== Number(data.default.version)) out.push({ selector: { kind: 'approved', version: row.version }, label: `Older approved · v${row.version}`, group: 'Approved history' });
4477
4477
  }
4478
4478
  return out;
@@ -4491,7 +4491,8 @@
4491
4491
  function exportSourceHtml() {
4492
4492
  if (exportSourcesState.status === 'loading') return '<div class="export-source-status" role="status">Loading export sources…</div>';
4493
4493
  if (exportSourcesState.status !== 'ready') return '<div class="export-source-status unavailable" role="status">Export sources unavailable — retry by reopening Exports.</div>';
4494
- const options = exportSourceOptions(exportSourcesState.data);
4494
+ const data = exportSourcesState.data || {};
4495
+ const options = exportSourceOptions(data);
4495
4496
  const selected = currentExportSourceOption();
4496
4497
  const selectedKey = selected ? JSON.stringify(selected.selector) : '';
4497
4498
  const grouped = ['Recommended', 'Drafts', 'Approved history'].map((group) => {
@@ -4501,7 +4502,10 @@
4501
4502
  + rows.map((option) => { const key = JSON.stringify(option.selector); return `<button type="button" class="export-source-option${key === selectedKey ? ' selected' : ''}" role="option" aria-selected="${String(key === selectedKey)}" data-export-source="${escapeAttr(key)}"><span>${escapeHtml(option.label)}</span>${option.sub ? `<small>${escapeHtml(option.sub)}</small>` : ''}</button>`; }).join('') + '</div>';
4502
4503
  }).join('');
4503
4504
  let warning = '';
4504
- if (selected && selected.selector.kind === 'latest-approved') {
4505
+ if (data.defaultUnavailable?.reason === 'refused') {
4506
+ const unavailableVersion = data.defaultUnavailable.version ? ` v${data.defaultUnavailable.version}` : '';
4507
+ warning = `<div class="export-source-banner refused" role="alert"><b>Approved${unavailableVersion} is unavailable.</b> ${escapeHtml(data.defaultUnavailable.message)} Review the approval before exporting. <button type="button" data-review-changes>Review approval</button></div>`;
4508
+ } else if (selected && selected.selector.kind === 'latest-approved') {
4505
4509
  warning = approvalState.pendingCount ? `<div class="export-source-banner"><b>${approvalState.pendingCount} pending change${approvalState.pendingCount === 1 ? '' : 's'} aren’t included.</b> Exports use approved v${approvalState.headVersion}. <button type="button" data-review-changes>Review changes</button></div>` : '';
4506
4510
  } else if (selected && (selected.selector.kind === 'working' || selected.selector.kind === 'checkpoint')) {
4507
4511
  warning = '<div class="export-source-banner draft"><b>DRAFT · Unapproved changes will be included.</b> This source is frozen when export starts.</div>';
@@ -4532,7 +4536,9 @@
4532
4536
  // Same split as History's empty state (#490): with a model, Approve is genuinely the unlocking
4533
4537
  // action; with none, `POST …/approve` 404s, so pointing at it is a dead end and the real next
4534
4538
  // step is to go read a drawing. `stepLabel('drawings')` because that label is per-app.
4535
- html += hasModel
4539
+ html += exportSourcesState.data?.defaultUnavailable?.reason === 'refused'
4540
+ ? `<div class="ws-exports-gate refused" role="alert">Exports are paused because the approved snapshot failed its integrity check. <button type="button" data-review-changes>Review approval</button></div>`
4541
+ : hasModel
4536
4542
  ? `<div class="ws-exports-gate">Exports go out after sign-off — ` +
4537
4543
  `<button type="button" id="ws-exports-approve">Approve this version</button> to enable them.</div>`
4538
4544
  : `<div class="ws-exports-gate">Nothing to export yet — ` +
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@floless/app",
3
- "version": "0.126.1",
3
+ "version": "0.126.2",
4
4
  "type": "module",
5
5
  "description": "Thin localhost host for floless.app — serves web/ and shells the aware CLI. No engine, no LLM.",
6
6
  "bin": {