Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

feat(skills): Add intent-only SOP fallback (sop_fallback) for skill-gen-4-enterprise-doc

amelafejzad87495504412
diff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/SKILL.md b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/SKILL.md
index 5049f73c3c..4e51a8ff8c 100644
--- a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/SKILL.md
+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/SKILL.md
@@ -10,11 +10,16 @@ Instructions here, **`reference/`**, and **`scripts/`** (package **`scripts/skil
## What you do (high level)
1. **Plain text**
+ - **Mandatory sequence when the user wanted a document but you still have no SOP plain text** (wrong path, **file not found**, fetch failed, empty body, permission error, etc.):
+ 1. **Recovery before fallback** — **Do not** call **`build_intent_fallback_sop`**, **`build_fallback_sop_structure`**, or generate the installable skill from intent-only fallback **in the same assistant turn** as that failure. A missing file is **only** a failed first ingest; it is **not** “no document” yet. Send **exactly one** recovery message first (single reply): offer a **corrected absolute path**, **URL**, or **paste**—same menu and tone as **[reference/sop-recovery-and-interview-fallback.md](./reference/sop-recovery-and-interview-fallback.md)** Part 1—and **wait** for the user’s next message (or treat recovery as already done if **one** recovery was sent earlier in the thread and the user **declined**, **ignored**, or **supplied** material afterward).
+ 2. **Fallback only after recovery** — Only when recovery is **complete** (user gave path/URL/paste you can use, or declined/ignored after the **one** ask) **and** there is **still** no parseable SOP body, proceed to **`build_intent_fallback_sop`** / **`build_fallback_sop_structure`** below. **Do not** skip step (1) because you “already know” the path failed.
- **Local file** → `python3 <ABS>/scripts/skill_generator_cli.py sop-text --sop-file <abs-path> [--out-text <path>]` or read the file in-tool; optional `--print-raw-chars` for length.
- **HTTP(S) / WeChat** → `url-fetch --url '…' [--out-json <path>]` then use page `text` as the SOP body for extraction.
- **Pasted only** — use the same string as input to **`parse_sop_raw_text`** (no skipping structured extraction).
-2. **Structured SOP (required)** → **`skill_gen.sop_parser.parse_sop_file`** or **`parse_sop_raw_text`** with **`invoke_llm_json`** (single path; **sop-structure-pipeline.md**).
+ - **No document after recovery** — you **must** build the canonical object in code. **Preferred (one call):** **`await skill_gen.sop_fallback.build_intent_fallback_sop(user_intent=…, skill_name_hint=…, invoke_llm_json=…)`** — **default:** pass **`invoke_llm_json`** whenever the runtime can invoke the model: deterministic skeleton **then** internal LLM refine (**`enrich_fallback_sop_with_llm`**). **Only if** the system **cannot** call a model for this step, pass **`invoke_llm_json=None`** (skeleton only) or use **`skill_gen.sop_fallback.build_fallback_sop_structure`** on sync-only paths (same shape; no enrich). Same **`SOPStructure`** fields as extraction (title, purpose, scope, roles, steps, `knowledge_items`, sections, decision points, exceptions, references, plus synthesized **`raw_text`**). Do **not** call **`parse_sop_raw_text`** on empty text; do **not** hand-write a “representative” or illustrative SOP in prose instead of running the fallback—downstream drafting depends on the real **`SOPStructure`** and **`extraction_meta`**. Treat **`extraction_meta["fallback_sop"]`** as “template only” in the generated skill body. Still **no** real SOP after LLM polish: keep **`fallback_sop`** semantics and do not treat output as audited policy.
+2. **Structured SOP (required)** → Either **`skill_gen.sop_parser.parse_sop_file`** / **`parse_sop_raw_text`** with **`invoke_llm_json`** when you have SOP plain text, **or** when you do not: **`await skill_gen.sop_fallback.build_intent_fallback_sop(..., invoke_llm_json=…)`** with **`invoke_llm_json`** whenever the runtime can invoke the model (default: skeleton + internal enrich); **`invoke_llm_json=None`** or **`build_fallback_sop_structure`** only when the system cannot (single path; **sop-structure-pipeline.md**).
3. **Draft package** → under **`get_agent_workspace_dir() / "skills-draft" / <skill_name>`** (when the host exposes that helper) or the equivalent **agent-workspace** path from the system prompt: **`SKILL.md`** (YAML frontmatter first) plus optional **`reference/`**, per **generator-worker-spec.md**. Create **`skills-draft`** next to the runtime **`skills/`** folder if it does not exist.
+ - **Intent-only snapshot (required when fallback)** — If **`extraction_meta["fallback_sop"]`** is true (intent-only / template path), you **must** add **`reference/intent-sop-snapshot.md`** in that draft folder. Start with a short warning block (this is **not** an authoritative enterprise SOP; synthesized from stated intent and optional LLM refine; provisional until a real document is attached). Then include the verbatim **`SOPStructure.raw_text`** from the structured object you used for drafting so reviewers can see exactly what the fallback produced.
4. **Install in the same workflow** → Call **`skills.import_local`** with **`path`** = **absolute** path to that draft directory (folder containing `SKILL.md`). Use **`force: true`** if **`get_agent_skills_dir() / <skill_name>`** already exists and should be replaced. Do **not** stop after step 3 and ask the user to import manually; promotion is **part of this skill’s default completion**.
After step 4, the new skill lives under **`get_agent_skills_dir() / <skill_name>`** (same directory tree the runtime loads user-installed skills from) and is available like any other installed skill.
@@ -37,6 +42,7 @@ The generated skill’s **`SKILL.md`** must start with **`---`** YAML frontmatte
| File | When |
|------|------|
| [reference/sop-structure-pipeline.md](./reference/sop-structure-pipeline.md) | **Always**: `SOPStructure` extraction. |
+| [reference/sop-recovery-and-interview-fallback.md](./reference/sop-recovery-and-interview-fallback.md) | **Always** before intent-only fallback: recovery menu wording and ordering (Part 1). |
| [reference/generator-worker-spec.md](./reference/generator-worker-spec.md) | **Always**: how to write a high-quality generated skill — **Writing a high-quality `SKILL.md`** (required structure) plus **Skill writing guide**. |
| [reference/operator-playbook.md](./reference/operator-playbook.md) | CLI, paths, **`skills.import_local`**, canonical flow, directory table, `SKILL.md` frontmatter rules. |
diff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/reference/generator-worker-spec.md b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/reference/generator-worker-spec.md
index 4a9e3a21bc..42dd24b086 100644
--- a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/reference/generator-worker-spec.md
+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/reference/generator-worker-spec.md
@@ -52,7 +52,7 @@ Use this as a hard gate before you treat a generated `SKILL.md` as done:
## What the worker is doing (conceptually)
-1. Ingest the source SOP from a local file, a URL, pasted raw text, or a structured SOP object.
+1. Ingest the source SOP from a local file, a URL, pasted raw text, or a structured SOP object. When **no** document text exists after brief recovery offers, **by default** use **`await skill_gen.sop_fallback.build_intent_fallback_sop(user_intent=…, skill_name_hint=…, invoke_llm_json=…)`** with **`invoke_llm_json`** whenever the runtime can invoke the model: full **`SOPStructure`** (and synthesized **`raw_text`**) plus one internal LLM refinement (**`enrich_fallback_sop_with_llm`**). **Only if** the system **cannot** invoke a model for that step, use **`invoke_llm_json=None`** with that same call, or **`skill_gen.sop_fallback.build_fallback_sop_structure`** (skeleton only). Label the draft as template-driven until the user supplies a canonical source—still not a substitute for attaching a real policy document.
2. Build or consume structured SOP data such as title, purpose, scope, steps, decision points, exceptions, roles, and references.
3. Draft an executable `SKILL.md` that turns the SOP into a usable agent workflow.
@@ -68,6 +68,17 @@ Then the authoring model should use both that **structured summary** and the **f
The structured object keeps the draft organized; the raw text keeps it faithful to the source.
+### Intent-only snapshot file (`reference/intent-sop-snapshot.md`)
+
+When **`extraction_meta["fallback_sop"]`** is true (intent-only template from **`build_intent_fallback_sop`** / **`build_fallback_sop_structure`**, not extracted from a policy file), the draft under **`skills-draft/<skill_name>/`** **must** include **`reference/intent-sop-snapshot.md`**.
+
+Contents:
+
+1. A **short warning** at the top (plain Markdown): this file is **not** an authoritative SOP; it records the **synthesized** procedure text used for drafting; treat as **provisional** until the user attaches a real document.
+2. The **verbatim** **`SOPStructure.raw_text`** from the same object you pass into skill authoring (no paraphrase).
+
+Do **not** drop this file to save tokens; it is the audit trail for what the fallback produced besides the generated **`SKILL.md`**.
+
### Same-session install (required for SOP → new skill)
When the target package is written under **`get_agent_workspace_dir() / "skills-draft" / <skill_name>`** (staging next to the runtime **`skills/`** tree), the driving agent **must** complete promotion in the **same workflow**: call **`skills.import_local`** with the **absolute** path to that directory so the skill appears under **`get_agent_skills_dir() / <skill_name>`** and is immediately loadable. See **[operator-playbook.md](./operator-playbook.md)** (**Canonical flow** and **Install the new skill**). This is not a separate optional step for the end user.
diff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/reference/operator-playbook.md b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/reference/operator-playbook.md
index e761b95223..f4dff4a747 100644
--- a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/reference/operator-playbook.md
+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/reference/operator-playbook.md
@@ -56,7 +56,7 @@ Use **`get_agent_root_dir()`**, **`get_agent_workspace_dir()`**, **`get_agent_sk
## After extraction: drafting
1. Obtain **`SOPStructure`** per **[sop-structure-pipeline.md](./sop-structure-pipeline.md)**.
-2. Produce **`SKILL.md`** per **[generator-worker-spec.md](./generator-worker-spec.md)** under **`get_agent_workspace_dir() / "skills-draft" / <skill_name>`** (create **`skills-draft`** if needed).
+2. Produce **`SKILL.md`** per **[generator-worker-spec.md](./generator-worker-spec.md)** under **`get_agent_workspace_dir() / "skills-draft" / <skill_name>`** (create **`skills-draft`** if needed). If **`extraction_meta["fallback_sop"]`**, also write **`reference/intent-sop-snapshot.md`** (see **generator-worker-spec** — *Intent-only snapshot file*).
3. Run **`skills.import_local`** as above.
---
@@ -69,7 +69,7 @@ This section is the same document as **# Skill Generator Operator Playbook** abo
1. **SOP plain text** — local file (`sop-text` / read in-tool), URL body (`url-fetch`), or pasted text in chat.
2. **Full `SOPStructure`** — **`parse_sop_file` / `parse_sop_raw_text` + `invoke_llm_json`** only ([sop-structure-pipeline.md](./sop-structure-pipeline.md)).
-3. **Draft package** — **`SKILL.md`** (and optional `reference/`, `evals.json`, …) under **`get_agent_workspace_dir() / "skills-draft" / <skill_name>`** ([generator-worker-spec.md](./generator-worker-spec.md)).
+3. **Draft package** — **`SKILL.md`** (and optional `reference/`, `evals.json`, …) under **`get_agent_workspace_dir() / "skills-draft" / <skill_name>`** ([generator-worker-spec.md](./generator-worker-spec.md)). When intent-only fallback was used, include **`reference/intent-sop-snapshot.md`**.
4. **Promote in the same workflow** — **`skills.import_local`** with **`path`** = **absolute** path to the draft directory (folder containing `SKILL.md`). Copies to **`get_agent_skills_dir() / <skill_name>`** (same root the runtime uses for user-installed skills) and refreshes indexes. Use **`force: true`** to replace an existing installed skill of the same name.
Optionally run **`scripts/skill_gen/validator.py`** on the draft directory before **`skills.import_local`**.
diff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/reference/sop-recovery-and-interview-fallback.md b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/reference/sop-recovery-and-interview-fallback.md
new file mode 100644
index 0000000000..dd292e4f56
--- /dev/null
+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/reference/sop-recovery-and-interview-fallback.md
@@ -0,0 +1,254 @@
+# SOP ingest recovery + structured interview fallback
+
+Use this file when **generating a skill from an SOP** but the system **cannot obtain SOP plain text** on the first try (bad path, missing file, fetch failed, empty body, permission, etc.).
+
+It defines three layers:
+
+1. **Recovery (ordered, user-facing)** — one clear menu so the user picks how to supply material next.
+2. **Structured fallback (interview)** — if there is still no document, **build a surrogate SOP** through guided questions so downstream steps see the same **`SOPStructure`-shaped** content as LLM extraction would produce (see **Alignment** below).
+3. **Insufficient input** — what to do when the user **does not answer**, **cannot** supply fields, or only knows part of the story (see **Part 3**).
+
+---
+
+## Part 1 — Recovery menu (run first, in order)
+
+After any ingest failure, **do not** silently switch modes. Send **one** short message that:
+
+1. States the failure in plain language (no stack traces to the user unless they ask).
+2. Presents **exactly** these options **in this order** (user picks one number or combines 1+2 over turns):
+
+| # | Option | What you do next |
+|---|--------|------------------|
+| **1** | **Corrected absolute path** | Retry local read / `sop-text` with the path the user gives. Confirm the file exists before promising extraction. |
+| **2** | **Paste the SOP** | User pastes full text (or large excerpt). Use **`parse_sop_raw_text`** on that string per [sop-structure-pipeline.md](./sop-structure-pipeline.md). |
+| **3** | **URL** | Run `url-fetch` (or equivalent), take page `text` as body, then **`parse_sop_raw_text`**. |
+| **4** | **Draft without a document** | Do **not** invent a full SOP by hand. **Default:** **`await skill_gen.sop_fallback.build_intent_fallback_sop(..., invoke_llm_json=...)`** with **`invoke_llm_json`** whenever the runtime can invoke the model; **`build_fallback_sop_structure`** or **`invoke_llm_json=None`** only when the system cannot ([sop-structure-pipeline.md](./sop-structure-pipeline.md)). Then continue skill drafting per [generator-worker-spec.md](./generator-worker-spec.md). **Or** — if the user wants something closer to a real SOP first — start **Part 2** (interview fallback). |
+
+**Suggested wording (adapt tone to channel):**
+
+> I couldn’t load that SOP. Choose how to continue:
+> **(1)** Send a **correct absolute path** to the file.
+> **(2)** **Paste** the SOP text here.
+> **(3)** Send a **URL** to the page or doc.
+> **(4)** Say **draft without a document** — I’ll use only what we’ve already discussed in chat **or** I can walk you through a short **Q&A** to capture a structured substitute (see below).
+
+If the user ignores the menu and pastes text or a URL, treat that as implicitly choosing **(2)** or **(3)** and proceed.
+
+---
+
+## Part 2 — Structured fallback: interview → surrogate SOP
+
+**Goal:** Produce text that is complete enough to run **`parse_sop_raw_text`** + **`invoke_llm_json`** so you stay on the **single extraction path** in [sop-structure-pipeline.md](./sop-structure-pipeline.md), **or** (if the host allows) assemble a JSON object compatible with **`SOPStructure`** and skip re-extraction — **default preference: markdown assembly + `parse_sop_raw_text`** so normalization stays consistent.
+
+**Principle:** The interview is **not** open-ended chat; it **fills fields** under **constraints** so the result maps cleanly to **`SOPStructure`** (`scripts/skill_gen/models.py`).
+
+### Constraints (v1 — tighten later)
+
+| Field | Constraint |
+|-------|------------|
+| `title` | Short name of the process or policy. Required before finishing. |
+| `purpose` | 1–3 sentences: why this exists. Required. |
+| `scope` | Who/what/when this applies; explicit “out of scope” if known. Required. |
+| `sop_type` | Exactly one of: `procedural` (mostly steps), `knowledge` (mostly rules/policies), `hybrid`. Required. |
+| `roles` | List of role names (strings). Empty list allowed only if truly N/A; if N/A, write one sentence in `scope`. |
+| `steps` | Ordered list. Each step has: `step_number`, `actor`, `action`, `system` (tool/system or “—”), `output` (artifact or “—”), `notes`. For `knowledge`-heavy SOPs, steps may be few; use `knowledge_items` instead. |
+| `knowledge_items` | Atomic rules (one rule per bullet/string). No narrative essays. |
+| `decision_points` | “If … then …” branches as short strings. |
+| `exceptions` | Escalations, waivers, edge cases. |
+| `references` | Links, policy IDs, ticket types, system names. |
+| `sections` | Optional outline mirrors; each item `{"heading": str, "summary": str}` is enough for v1. |
+
+**Quality gate before you call extraction:**
+At least **two** of the following must be non-empty: `steps`, `knowledge_items`, `sections` (with non-empty summaries). Otherwise keep asking until the surrogate is usable.
+
+### How to run the interview (interactive, recommended)
+
+Ask **one phase at a time**; summarize back what you captured before moving on.
+
+1. **Phase A — Framing**
+ - What is the **title**?
+ - **Purpose** (why)?
+ - **Scope** (who/what/when; out of scope)?
+ - **Type**: procedural / knowledge / hybrid — explain the three in one line if the user is unsure.
+
+2. **Phase B — Roles & systems**
+ - Who is involved (**roles**)?
+ - Which **systems/tools** (for step `system` fields)?
+
+3. **Phase C — Main body**
+ - If **procedural/hybrid**: walk through **steps** in order (“What happens first? Then?”). For each step capture actor, action, system, output, notes.
+ - If **knowledge**: collect **knowledge_items** as separate bullets; add **decision_points** where “if/then” matters.
+
+4. **Phase D — Edge layer**
+ - **Exceptions** and **decision_points** not yet captured.
+ - **References** (policy numbers, URLs, form names).
+
+5. **Phase E — Review**
+ - Show the filled **Markdown assembly** (template below). Ask: “Anything wrong or missing?” One correction round, then proceed to **`parse_sop_raw_text`** on the final string.
+
+### Markdown assembly template (paste answers into this, then `parse_sop_raw_text`)
+
+Use this skeleton so the LLM extractor sees familiar headings. Replace placeholders; remove empty optional blocks if truly unused.
+
+```markdown
+# SOP: {{title}}
+
+## Purpose
+{{purpose}}
+
+## Scope
+{{scope}}
+
+## Type
+{{sop_type}}
+
+## Roles
+{{bullet_list_roles}}
+
+## Workflow / Steps
+{{for each step:}}
+### Step {{step_number}} — {{actor}}
+- **Action:** {{action}}
+- **System / tool:** {{system}}
+- **Output / evidence:** {{output}}
+- **Notes:** {{notes}}
+
+## Knowledge / rules (non-step)
+{{bullet_list_knowledge_items}}
+
+## Decision points
+{{bullet_list_decision_points}}
+
+## Exceptions & escalations
+{{bullet_list_exceptions}}
+
+## References
+{{bullet_list_references}}
+```
+
+After assembly, set `source_label` in extraction meta if your caller supports it (e.g. `interview-fallback-v1`).
+
+### Optional JSON skeleton (for tooling or hand-off)
+
+If another tool consumes JSON before markdown assembly, shape must match **`SOPStructure`** fields:
+
+```json
+{
+ "title": "",
+ "purpose": "",
+ "scope": "",
+ "sop_type": "procedural | knowledge | hybrid",
+ "roles": [],
+ "steps": [
+ {
+ "step_number": 1,
+ "actor": "",
+ "action": "",
+ "system": "",
+ "output": "",
+ "notes": ""
+ }
+ ],
+ "knowledge_items": [],
+ "sections": [],
+ "decision_points": [],
+ "exceptions": [],
+ "references": [],
+ "raw_text": ""
+}
+```
+
+Populate `raw_text` with the same content as the **Markdown assembly** when serializing for storage.
+
+---
+
+## Part 3 — User gives no input, or cannot provide information
+
+Use this when: the user **never picks** (1)–(4), **stops replying**, says **“I don’t know”** / **“I can’t share that”** for many fields, or **does not have** access to the real SOP.
+
+### Principles
+
+- **Do not invent** confidential or precise operational detail to fill gaps. Prefer **explicit unknowns** over fake specificity.
+- **Align with** [generator-worker-spec.md](./generator-worker-spec.md): for non-SOP / thin context, the default is **draft with reasonable assumptions** and state them clearly — **unless** the gap is **blocking** or **unsafe** (see below).
+
+### A. No response after the recovery menu
+
+1. Send **one** short follow-up: restate that you still need one of (1)–(4), and that **(4)** includes “draft from chat only” if they have no file.
+2. If there is still **no substantive reply** (same session / product policy permitting):
+ - **If the thread already contains enough intent** (goal, audience, constraints): proceed with **intent-only** skill drafting per **generator-worker-spec** (“non-SOP skills”), and label limitations in the generated skill (what was **not** verified against a document).
+ - **If there is not enough to draft anything useful:** stop with a **clear, polite closure** — what is missing (e.g. “a path, pasted text, URL, or agreement to draft from chat”) and that they can resume anytime.
+
+Do **not** loop endless reminders in the same session unless the product explicitly wants that.
+
+### B. Interview started but the user cannot answer some questions
+
+- For **missing non-critical** fields (e.g. exact policy ID, secondary system name): insert **`[TBD: …]`** or a one-line **assumption** in the markdown assembly, and mirror that in the generated **`SKILL.md`** (“Assumptions / unknowns”) so reviewers can fix it later.
+- For **“I don’t know”** on a whole area: **shrink scope** in `scope` (“Applies only to what we confirmed: …”) and continue if the **quality gate** (Part 2) can still be met with steps or knowledge items from what *was* confirmed.
+- If the **quality gate cannot be met** even with TBDs: **do not** call extraction on empty fluff — either **narrow the ask** (one more focused question) or switch to **intent-only** skill with a **narrower** description and explicit “partial capture” wording.
+
+### C. User cannot provide *any* substantive SOP-like material
+
+(e.g. no access, policy forbids export, greenfield idea only.)
+
+- **Default:** **intent-only** skill from chat + stated constraints, per **generator-worker-spec** (“Interview and research (for non-SOP skills)”). No surrogate markdown pretending to be a full SOP unless the user **opts in** to a **minimal** interview (title + purpose + one workflow sentence).
+- **Do not** fabricate a long procedural SOP to pass **`parse_sop_raw_text`** when the user has not supplied or confirmed that content.
+
+### D. Blocking or high-risk gaps
+
+If missing information makes a **safe or compliant** skill impossible (e.g. regulated workflow, irreversible actions, no actor or approval path), **do not** ship a confident procedure. Options:
+
+- **Stop** and name the **minimum** fact needed to continue, or
+- Produce a **stub / checklist skill** that only lists **questions to resolve** and **no** automated procedure until the user fills in — still useful, and honest.
+
+---
+
+## After recovery or fallback
+
+Continue the **normal** skill-gen flow from [SKILL.md](../SKILL.md): structured extraction (unless you intentionally skip with a host-approved fast path), draft under `skills-draft/`, **`skills.import_local`**.
+
+---
+
+## Provenance: what was generated, and can the user tell?
+
+### What the pipeline produces
+
+- The **main deliverable** is an **installed skill** (`SKILL.md` + optional `reference/`, etc.), not a canonical “new SOP” file for the organization.
+- Internally, **`SOPStructure`** (JSON-shaped data) is produced by **`parse_sop_file` / `parse_sop_raw_text`** from **plain text** — that text may be a **real document**, **fetched HTML text**, **a paste**, or **markdown assembled from the interview** (surrogate).
+- A **separate user-visible SOP file** is **not** created by default. If you want one (e.g. `reference/captured-sop.md`), create it **explicitly** as part of the draft package and point to it from `SKILL.md`.
+
+### Can the user tell real vs recovery vs fallback?
+
+**In the skill file:** yes, when validation is used. Run **`skill_generator_cli.py validate-skill --skill-dir …`** (or **`skill_gen.validator.validate_skill`**) before import; it **requires** the section and a known **`source:<tag>`** (see `skill_gen.provenance.SKILL_PROVENANCE_SOURCES`). To build the block in code, use **`skill_gen.provenance.render_provenance_section()`**.
+
+**Normative (generator):** Every skill produced through this meta-skill **must** include **`## Source and provenance`** in the **generated** `SKILL.md` body (after frontmatter), with:
+
+1. **Exactly one** primary line **`source:<tag>`** chosen from the table below.
+2. **Immediately below**, at least **one plain-language sentence** (validated: ≥20 characters of prose after ignoring machine lines). A **non-technical reader** should understand **whether this skill mirrors a real document** or came from **paste, URL, guided Q&A, or chat only** — without having to decode `source:*`. Use **`render_provenance_section(..., detail="…")`** for the sentence(s).
+
+**Optional machine lines** (do not count as the user summary): `interview_version:…`, `prior_attempts:…`.
+
+| Tag | When to use (technical) | Example plain-language sentence for **`detail=`** (adapt to facts) |
+|-----|-------------------------|----------------------------------------------------------------------|
+| **`source:document_file`** | Plain text from a **local file** read successfully. | “This skill was generated from the SOP file `onboarding.md` on disk, then run through the normal extractor.” |
+| **`source:document_url`** | Plain text from a **fetched page**. | “This skill was generated from the policy text fetched from the URL you provided (not from an internal file share).” |
+| **`source:document_paste`** | Plain text **pasted** in chat. | “This skill was generated from SOP text you pasted into the chat (not from a file path or link).” |
+| **`source:interview_surrogate`** | **Part 2** interview + assembled markdown → extraction. | “No full SOP file was used. The workflow was captured through guided questions and then normalized by the same extractor used for documents.” |
+| **`source:intent_only_chat`** | **Part 3** / non-SOP path; **no** document through extraction. | “This skill was drafted from our conversation only; it does not claim to match a published SOP word-for-word.” |
+| **`source:packaged_reference`** | Pre-installed template skill. | “This is a bundled reference skill shipped with the workspace, not produced from your documents in this session.” |
+
+If **multiple** sources were tried (e.g. file missing, then paste worked), the **plain-language sentence** should say what **actually fed extraction** (e.g. “The first path failed; the skill reflects pasted text.”). The **`source:`** line still reflects the **primary** input to `parse_sop_raw_text` only. Add **`prior_attempts:`** if useful.
+
+**Optional:** repeat the gist in YAML **`description`** so routing metadata also hints at provenance.
+
+**Validator:** `skill_gen.provenance.verify_skill_md_provenance` rejects a section that has only `source:*` with no readable explanation.
+
+---
+
+## Versioning
+
+This document is **v1**. When you change field constraints or phases, bump a short note at the bottom (`v1 → v2`) so agents can cite which interview version produced a surrogate SOP.
+
+**v1.1** — Added **Part 3** (no response, partial answers, cannot provide material, blocking gaps).
+**v1.2** — Added **Provenance** (what is generated + required `## Source and provenance` on generated skills).
+**v1.3** — Provenance enforced by **`skill_gen.validator`** + **`validate-skill`** CLI; added **`source:packaged_reference`** and **`render_provenance_section()`**.
+**v1.4** — Required **plain-language summary** under provenance (end-user clarity); example sentences per `source:*` tag.
diff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/reference/sop-structure-pipeline.md b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/reference/sop-structure-pipeline.md
index 4cfe6b6784..7e06d92049 100644
--- a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/reference/sop-structure-pipeline.md
+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/reference/sop-structure-pipeline.md
@@ -13,4 +13,10 @@ Do not maintain a second, competing extraction spec elsewhere.
**Shell helpers:** `scripts/skill_generator_cli.py sop-text` outputs **plain text** extracted from a file (character count or full text). It does **not** emit `SOPStructure` JSON. For HTTP(S) or WeChat pages, use **`url-fetch`**, then run the same **`parse_sop_raw_text`** on the fetched body with **`invoke_llm_json`**.
+**No plain-text SOP (intent-only):** If there is no body to parse, follow **[SKILL.md](../SKILL.md)** step 1 **mandatory sequence**: complete **recovery** (one offer of path / URL / paste per **[sop-recovery-and-interview-fallback.md](./sop-recovery-and-interview-fallback.md)** Part 1) **before** calling **`build_intent_fallback_sop`** / **`build_fallback_sop_structure`**—a missing or unreadable file **does not** skip recovery. After recovery, if there is **still** no body, you **must** materialize the fallback in code—do **not** substitute a hand-authored “preview” SOP. **Preferred:** **`await skill_gen.sop_fallback.build_intent_fallback_sop(user_intent=…, skill_name_hint=…, invoke_llm_json=…)`** — **default:** pass **`invoke_llm_json`** whenever the runtime can invoke the model (deterministic skeleton, then **`enrich_fallback_sop_with_llm`** internally). Pass **`invoke_llm_json=None`** only when the system **cannot** call a model for this step, or use **`build_fallback_sop_structure`** on sync-only paths (no LLM). That path returns full **`SOPStructure`** and Markdown **`raw_text`** with the same structural elements as LLM extraction (purpose, scope, roles, procedure steps, rules slot, sections, branches, exceptions, references). It is **not** a substitute for a real policy document—generated skills must say assumptions are provisional until source material arrives.
+
+**Advanced:** **`enrich_fallback_sop_with_llm`** remains for custom pipelines; prefer **`build_intent_fallback_sop`** for the normal intent-only flow.
+
+**Draft artifact:** When the structured path used **`fallback_sop`**, the generated skill package **must** include **`reference/intent-sop-snapshot.md`** (warning + verbatim **`raw_text`**) per **[generator-worker-spec.md](./generator-worker-spec.md)**.
+
**After `SOPStructure` exists:** Write the target skill’s **`SKILL.md`** (user inputs, processing steps, deliverables, triggers) solely per **[generator-worker-spec.md](./generator-worker-spec.md)** under **`get_agent_workspace_dir() / "skills-draft" / <skill_name>`** (or the host’s equivalent), then in the **same workflow** call **`skills.import_local`** with the **absolute** draft directory path so the package is copied to **`get_agent_skills_dir() / <skill_name>`** and is immediately loadable ([operator-playbook.md](./operator-playbook.md) **Canonical flow**). Use **`force: true`** when overwriting an existing installed skill.
diff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/__init__.py b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/__init__.py
index c9324ddaef..cea354fad4 100644
--- a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/__init__.py
+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/__init__.py
@@ -1,6 +1,11 @@
"""SOP and URL ingest helpers for skill-gen-4-enterprise-doc."""
from .models import SOPStep, SOPStepDict, SOPStructure
+from .sop_fallback import (
+ build_fallback_sop_structure,
+ build_intent_fallback_sop,
+ enrich_fallback_sop_with_llm,
+)
from .sop_parser import DEFAULT_SINGLE_SHOT_BUDGET, parse_sop_file, parse_sop_raw_text
__all__ = [
@@ -8,6 +13,9 @@ __all__ = [
"SOPStep",
"SOPStepDict",
"SOPStructure",
+ "build_fallback_sop_structure",
+ "build_intent_fallback_sop",
+ "enrich_fallback_sop_with_llm",
"parse_sop_file",
"parse_sop_raw_text",
]
diff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/sop_fallback.py b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/sop_fallback.py
new file mode 100644
index 0000000000..c62637df20
--- /dev/null
+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/sop_fallback.py
@@ -0,0 +1,477 @@
+"""Intent-only fallback when no SOP plain text is available.
+
+Recovery paths (paste text, URL fetch, local file) stay primary when the user
+can supply a document. When there is still no source body, use
+:func:`build_intent_fallback_sop`: **by default** pass ``invoke_llm_json``
+whenever the runtime can invoke the model—it builds a deterministic
+:class:`SOPStructure` plus Markdown ``raw_text``, then always runs
+:func:`enrich_fallback_sop_with_llm` for that call. Pass ``invoke_llm_json=None``
+(or use :func:`build_fallback_sop_structure` alone) **only** when the system
+cannot run an LLM for this step (tests, offline, unwired host, policy).
+Downstream drafting sees the same fields as LLM extraction (title, purpose,
+scope, roles, steps, knowledge_items, sections, branches, exceptions,
+references).
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import re
+import textwrap
+from typing import Any, Callable
+
+from .models import SOPStep, SOPStructure
+
+logger = logging.getLogger(__name__)
+
+_MAX_RAW_TEXT_IN_ENRICH_PROMPT = 8000
+
+_ENRICH_FALLBACK_PROMPT = """\
+You refine a **draft SOP JSON** that was built **without** an authoritative source document (intent-only template).
+
+## Rules (strict)
+
+- Output **only** one JSON object with the same top-level keys as the input draft: \
+title, purpose, scope, sop_type, roles, steps, knowledge_items, sections, \
+decision_points, exceptions, references, raw_text.
+- Improve wording for clarity; align steps and knowledge_items with the stated intent where obvious.
+- **Do not** invent numeric SLAs, approval limits, legal deadlines, fines, system URLs, or \
+ company-specific policy not present in the draft JSON or the **Stated intent** block below.
+- If a field would require guessing policy detail, keep the draft’s cautious / TBD wording or \
+ leave lists shorter rather than fabricating.
+- steps[].step_number must be JSON strings (e.g. "1", "2a").
+- raw_text should be Markdown that reflects the refined structure (can shorten boilerplate).
+
+## Stated intent (verbatim, may be partial)
+
+{user_intent}
+
+## Draft JSON (refine this)
+
+{draft_json}
+
+Output JSON only, no markdown fences or commentary."""
+
+
+def _draft_dict_for_enrich_prompt(sop: SOPStructure) -> dict[str, Any]:
+ data = sop.to_dict()
+ rt = str(data.get("raw_text", ""))
+ if len(rt) > _MAX_RAW_TEXT_IN_ENRICH_PROMPT:
+ data["raw_text"] = rt[: _MAX_RAW_TEXT_IN_ENRICH_PROMPT - 1].rstrip() + "…"
+ data["_raw_text_truncated_for_enrich_prompt"] = True
+ else:
+ data.pop("_raw_text_truncated_for_enrich_prompt", None)
+ return data
+
+_MAX_INTENT_LINE_LEN = 220
+_MAX_INTENT_STRUCTURED_LINES = 12
+
+_NUMBERED_LINE = re.compile(r"^\s*(\d+)[.)]\s+(.+)$")
+_BULLET_LINE = re.compile(r"^\s*[-*•]\s+(.+)$")
+
+_POLICY_LEXICON_KEYWORDS = (
+ "sla",
+ "policy",
+ "compliance",
+ "regulation",
+ "audit",
+ "threshold",
+ "retention",
+ "gdpr",
+ "phi",
+ "pii",
+)
+
+
+def _infer_sop_type_from_intent(intent: str) -> tuple[str, str]:
+ """Return ``(sop_type, reason_tag)`` using cheap heuristics (no LLM)."""
+ if not intent.strip():
+ return "hybrid", "empty_intent_default_hybrid"
+ lines = intent.splitlines()
+ numbered = 0
+ for line in lines:
+ if _NUMBERED_LINE.match(line):
+ numbered += 1
+ bullets = 0
+ for line in lines:
+ if _BULLET_LINE.match(line):
+ bullets += 1
+ lower = intent.lower()
+ policy_lex = False
+ for kw in _POLICY_LEXICON_KEYWORDS:
+ if kw in lower:
+ policy_lex = True
+ break
+ if policy_lex and numbered < 2 and bullets < 2:
+ return "knowledge", "policy_lexicon_low_procedure_signal"
+ if numbered >= 2 or (numbered + bullets) >= 4:
+ if policy_lex:
+ return "hybrid", "ordered_steps_plus_policy_language"
+ return "procedural", "multiple_ordered_or_bullet_lines"
+ return "hybrid", "default_hybrid"
+
+
+def _structured_lines_from_intent(intent: str) -> list[str]:
+ """Pull numbered / bullet lines out of free-form intent into short snippets."""
+ seen: set[str] = set()
+ out: list[str] = []
+ for raw in intent.splitlines():
+ if len(out) >= _MAX_INTENT_STRUCTURED_LINES:
+ break
+ m_num = _NUMBERED_LINE.match(raw)
+ if m_num:
+ text = m_num.group(2).strip()
+ else:
+ m_bul = _BULLET_LINE.match(raw)
+ if not m_bul:
+ continue
+ text = m_bul.group(1).strip()
+ if len(text) < 3:
+ continue
+ if len(text) > _MAX_INTENT_LINE_LEN:
+ text = text[: _MAX_INTENT_LINE_LEN - 1].rstrip() + "…"
+ key = text.casefold()
+ if key in seen:
+ continue
+ seen.add(key)
+ out.append(f"From stated intent (unverified structure): {text}")
+ return out
+
+
+def _intent_title(user_intent: str, skill_name_hint: str) -> str:
+ hint = (skill_name_hint or "").strip()
+ if hint:
+ words = hint.replace("-", " ").replace("_", " ").strip()
+ return f"{words.title()} — procedure (draft from stated intent)"
+ intent = (user_intent or "").strip()
+ if intent:
+ one_line = " ".join(intent.split())
+ if len(one_line) > 90:
+ one_line = one_line[:87].rstrip() + "…"
+ return one_line
+ return "User-defined procedure (intent-only draft)"
+
+
+def build_fallback_sop_structure(
+ *,
+ user_intent: str = "",
+ skill_name_hint: str = "",
+) -> tuple[SOPStructure, dict[str, Any]]:
+ """Return a well-formed ``SOPStructure`` when no SOP document exists yet.
+
+ Use after optional recovery (file / URL / paste) is declined or unavailable.
+ The object is intentionally explicit that content is a **template** filled
+ from conversation, not extracted from an authoritative source.
+
+ For async hosts and LLM polish in **one** call, prefer
+ :func:`build_intent_fallback_sop` with ``invoke_llm_json`` whenever the
+ runtime can invoke the model (deterministic skeleton, then LLM refine).
+
+ Returns ``(sop, extraction_meta)`` with the same ``extraction_meta`` keys
+ callers already expect from :func:`parse_sop_raw_text`, plus
+ ``fallback_sop`` / ``fallback_reason`` for telemetry and prompts.
+ """
+ intent = (user_intent or "").strip()
+ title = _intent_title(intent, skill_name_hint)
+ sop_type, type_reason = _infer_sop_type_from_intent(intent)
+ intent_snippets = _structured_lines_from_intent(intent)
+
+ purpose = (
+ "Operationalize the user's stated goal as an executable agent skill. "
+ "Refine purpose, constraints, and success criteria using the conversation "
+ "until they match what a formal SOP would specify."
+ )
+ if intent:
+ purpose = (
+ f"{purpose} Stated intent (verbatim, may be partial): {intent}"
+ )
+
+ scope = (
+ "Applies to the workflow the user described in this session until a "
+ "canonical policy or SOP document is attached. Out of scope: "
+ "obligations not mentioned by the user unless required for safety "
+ "or compliance—then surface as open questions in outputs."
+ )
+
+ roles = [
+ "Process owner / requester (user)",
+ "Executing agent",
+ "Optional reviewers or approvers (name when known)",
+ ]
+
+ steps = [
+ SOPStep(
+ step_number="1",
+ actor="User or agent",
+ action=(
+ "Confirm required inputs, systems, and deliverable format from "
+ "the conversation or any supplied files."
+ ),
+ system="",
+ output="Input checklist or explicit assumption list",
+ notes="If blocking data is missing, prefer a short clarification over silent guesses.",
+ ),
+ SOPStep(
+ step_number="2",
+ actor="Agent",
+ action="Execute the core workflow aligned to sections and decision points below.",
+ system="Per skill tools and environment",
+ output="Intermediate artifacts (draft tables, messages, file edits) as needed",
+ notes="State provisional vs confirmed facts.",
+ ),
+ SOPStep(
+ step_number="3",
+ actor="Agent",
+ action="Validate outcomes against acceptance criteria implied by the intent and any later attachments.",
+ system="",
+ output="Pass/fail with gaps",
+ notes="Escalate ambiguities to the user.",
+ ),
+ SOPStep(
+ step_number="4",
+ actor="Agent",
+ action="Produce final deliverables using the naming and structure conventions in generator-worker-spec.",
+ system="",
+ output="Final user-facing artifacts",
+ notes="Include assumptions when the source SOP is still this template.",
+ ),
+ ]
+
+ knowledge_items = [
+ "This structure is a fallback skeleton, not an extracted enterprise SOP. "
+ "Replace generic language with organization-specific rules when a real document arrives.",
+ "Numeric SLAs, approval limits, legal text, and system IDs must not be invented; "
+ "capture them from the user or from linked documentation.",
+ "When the user pastes policy fragments or URLs later, merge them into knowledge_items "
+ "and steps in a follow-up revision of the generated skill.",
+ ]
+ knowledge_items.extend(intent_snippets)
+
+ sections = [
+ {
+ "id": "1",
+ "title": "Purpose and outcomes",
+ "content_summary": "Why the skill exists and what “done” means for this intent.",
+ },
+ {
+ "id": "2",
+ "title": "Scope and applicability",
+ "content_summary": "Boundaries until a formal SOP is attached.",
+ },
+ {
+ "id": "3",
+ "title": "Roles and responsibilities",
+ "content_summary": "Who supplies inputs, who executes, who approves.",
+ },
+ {
+ "id": "4",
+ "title": "Procedure",
+ "content_summary": "Ordered steps; expand with real systems and approvals from the user.",
+ },
+ {
+ "id": "5",
+ "title": "Decision points and exceptions",
+ "content_summary": "Branches, error paths, and when to stop for human input.",
+ },
+ {
+ "id": "6",
+ "title": "Deliverables and references",
+ "content_summary": "Artifacts to hand back plus pointers to external policies.",
+ },
+ ]
+
+ decision_points = [
+ "Are mandatory inputs present? If not, pause for user clarification vs proceed with labeled assumptions.",
+ "Does the task require human approval before external side effects (messages, tickets, payments)?",
+ ]
+
+ exceptions = [
+ (
+ "No authoritative SOP text in-session: "
+ "treat all operational detail as provisional until a file or URL is provided."
+ ),
+ (
+ "High-risk domains (finance, health, legal): require explicit user confirmation "
+ "before irreversible actions."
+ ),
+ ]
+
+ references = [
+ "Conversation with the user",
+ "Attachments, URLs, or tickets supplied later in the thread",
+ "Internal policy library (when the user names it)",
+ ]
+
+ raw_lines = [
+ f"# {title}",
+ "",
+ "## 1. Purpose",
+ textwrap.fill(purpose, width=92),
+ "",
+ "## 2. Scope",
+ textwrap.fill(scope, width=92),
+ "",
+ "## 3. Roles",
+ "\n".join(f"- {r}" for r in roles),
+ "",
+ "## 4. Procedure",
+ ]
+ for st in steps:
+ raw_lines.append(
+ f"{st.step_number}. **{st.actor}** — {st.action} "
+ f"(output: {st.output or 'n/a'})"
+ )
+ if st.notes:
+ raw_lines.append(f" - Note: {st.notes}")
+ raw_lines.extend(
+ [
+ "",
+ "## 5. Rules and standards (to be grounded in real policy)",
+ "\n".join(f"- {k}" for k in knowledge_items),
+ "",
+ "## 6. Decision points",
+ "\n".join(f"- {d}" for d in decision_points),
+ "",
+ "## 7. Exceptions",
+ "\n".join(f"- {e}" for e in exceptions),
+ "",
+ "## 8. References",
+ "\n".join(f"- {r}" for r in references),
+ ]
+ )
+ raw_text = "\n".join(raw_lines)
+
+ sop = SOPStructure(
+ title=title,
+ purpose=purpose,
+ scope=scope,
+ sop_type=sop_type,
+ roles=roles,
+ steps=steps,
+ knowledge_items=knowledge_items,
+ sections=sections,
+ decision_points=decision_points,
+ exceptions=exceptions,
+ references=references,
+ raw_text=raw_text,
+ )
+
+ meta: dict[str, Any] = {
+ "source_path": "",
+ "merge_warnings": ["intent_only_fallback_skeleton"],
+ "weak_reasons": ["intent_only_no_source_document"],
+ "use_raw_excerpt_draft_fallback": False,
+ "fallback_sop": True,
+ "fallback_reason": "no_document_intent_skeleton",
+ "fallback_inferred_sop_type": sop_type,
+ "fallback_sop_type_reason": type_reason,
+ "fallback_intent_structured_line_count": len(intent_snippets),
+ "output_counts": {
+ "steps": len(sop.steps),
+ "knowledge_items": len(sop.knowledge_items),
+ "sections": len(sop.sections),
+ "decision_points": len(sop.decision_points),
+ "exceptions": len(sop.exceptions),
+ },
+ }
+ return sop, meta
+
+
+async def enrich_fallback_sop_with_llm(
+ sop: SOPStructure,
+ *,
+ user_intent: str = "",
+ invoke_llm_json: Callable[..., Any],
+ trace_tag: str = "sop_fallback_enrich",
+) -> tuple[SOPStructure, dict[str, Any]]:
+ """Refine a fallback :class:`SOPStructure` with one LLM JSON call (internal step).
+
+ Prefer :func:`build_intent_fallback_sop` (pass ``invoke_llm_json`` by
+ default when the runtime can invoke the model) so deterministic build +
+ enrich stay one call.
+ This function remains
+ for tests or custom pipelines. On empty/invalid model output, returns the
+ input ``sop`` unchanged.
+
+ ``invoke_llm_json`` must match the same contract as ``sop_parser`` (async
+ callable returning a dict parsed from model JSON).
+ """
+ enrich_meta: dict[str, Any] = {
+ "fallback_llm_enrich": False,
+ "fallback_llm_enrich_trace": trace_tag,
+ }
+ draft = _draft_dict_for_enrich_prompt(sop)
+ draft.pop("_raw_text_truncated_for_enrich_prompt", None)
+ try:
+ draft_json = json.dumps(draft, ensure_ascii=False, indent=2)
+ except (TypeError, ValueError) as exc:
+ enrich_meta["merge_warnings"] = [f"fallback_llm_enrich_skipped_serialize_error:{exc}"]
+ return sop, enrich_meta
+
+ prompt = _ENRICH_FALLBACK_PROMPT.format(
+ user_intent=(user_intent or "").strip() or "(none)",
+ draft_json=draft_json,
+ )
+ try:
+ data = await invoke_llm_json(prompt, fallback={}, trace_tag=trace_tag)
+ except Exception as exc:
+ logger.warning("[SOPFallback] enrich LLM call failed: %s", exc)
+ enrich_meta["merge_warnings"] = [f"fallback_llm_enrich_failed:{type(exc).__name__}"]
+ return sop, enrich_meta
+
+ if not isinstance(data, dict) or not data:
+ enrich_meta["merge_warnings"] = ["fallback_llm_enrich_empty_response"]
+ return sop, enrich_meta
+
+ refined = SOPStructure.from_dict(data)
+ if not str(refined.raw_text or "").strip():
+ refined.raw_text = sop.raw_text
+ enrich_meta["fallback_llm_enrich"] = True
+ enrich_meta["merge_warnings"] = []
+ enrich_meta["output_counts"] = {
+ "steps": len(refined.steps),
+ "knowledge_items": len(refined.knowledge_items),
+ "sections": len(refined.sections),
+ "decision_points": len(refined.decision_points),
+ "exceptions": len(refined.exceptions),
+ }
+ return refined, enrich_meta
+
+
+async def build_intent_fallback_sop(
+ *,
+ user_intent: str = "",
+ skill_name_hint: str = "",
+ invoke_llm_json: Callable[..., Any] | None = None,
+) -> tuple[SOPStructure, dict[str, Any]]:
+ """Single entry point for intent-only SOP-shaped output (no source document).
+
+ **Default:** pass ``invoke_llm_json`` whenever the runtime can invoke the
+ model. This always runs the deterministic skeleton via
+ :func:`build_fallback_sop_structure`, then calls
+ :func:`enrich_fallback_sop_with_llm`. **Exception:** pass
+ ``invoke_llm_json=None`` only when the system cannot call the model for this
+ step—then the skeleton is returned unchanged.
+
+ ``fallback_sop`` semantics in ``extraction_meta`` are unchanged either way.
+ """
+ sop, meta = build_fallback_sop_structure(
+ user_intent=user_intent,
+ skill_name_hint=skill_name_hint,
+ )
+ if invoke_llm_json is None:
+ return sop, meta
+
+ sop2, enrich_meta = await enrich_fallback_sop_with_llm(
+ sop,
+ user_intent=user_intent,
+ invoke_llm_json=invoke_llm_json,
+ )
+ meta["fallback_llm_enrich"] = enrich_meta.get("fallback_llm_enrich", False)
+ meta["fallback_llm_enrich_trace"] = enrich_meta.get("fallback_llm_enrich_trace", "")
+ for w in enrich_meta.get("merge_warnings", []) or []:
+ meta.setdefault("merge_warnings", []).append(w)
+ if enrich_meta.get("fallback_llm_enrich"):
+ meta["output_counts"] = enrich_meta.get("output_counts", meta.get("output_counts", {}))
+ return sop2, meta
diff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_generator_cli.py b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_generator_cli.py
index 3a674aede7..299e16522a 100644
--- a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_generator_cli.py
+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_generator_cli.py
@@ -15,6 +15,10 @@ Examples:
Full ``SOPStructure`` JSON comes from ``skill_gen.sop_parser.parse_sop_file`` or
``parse_sop_raw_text`` plus ``invoke_llm_json`` (see ``reference/sop-structure-pipeline.md``).
+Intent-only fallback (no document): ``await skill_gen.sop_fallback.build_intent_fallback_sop(...)`` —
+pass ``invoke_llm_json`` by default whenever the runtime can invoke the model;
+omit it only when the system cannot (see ``../SKILL.md``).
+
End-to-end draft flow: ``../SKILL.md``.
"""