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 skill-gen-4-enterprise-doc metaskill, create new skills from SOP documents or freeform intent
Tinaxy3de2f26ffe12
diff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/agent-data.json b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/agent-data.jsonindex 0330626ad3..558d7e5a4c 100644--- a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/agent-data.json+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/agent-data.json@@ -299,5 +299,95 @@"path": "agent/jiuwenclaw_workspace/skills/skill-creator/scripts/utils.py","isMarkdown": false}+ ],+ "jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc": [+ {+ "name": "SKILL.md",+ "path": "agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/SKILL.md",+ "isMarkdown": true+ }+ ],+ "jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/reference": [+ {+ "name": "generator-worker-spec.md",+ "path": "agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/reference/generator-worker-spec.md",+ "isMarkdown": true+ },+ {+ "name": "operator-playbook.md",+ "path": "agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/reference/operator-playbook.md",+ "isMarkdown": true+ },+ {+ "name": "sop-structure-pipeline.md",+ "path": "agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/reference/sop-structure-pipeline.md",+ "isMarkdown": true+ }+ ],+ "jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts": [+ {+ "name": "skill_generator_cli.py",+ "path": "agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_generator_cli.py",+ "isMarkdown": false+ }+ ],+ "jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen": [+ {+ "name": "__init__.py",+ "path": "agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/__init__.py",+ "isMarkdown": false+ },+ {+ "name": "models.py",+ "path": "agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/models.py",+ "isMarkdown": false+ },+ {+ "name": "sop_chunk_merge.py",+ "path": "agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/sop_chunk_merge.py",+ "isMarkdown": false+ },+ {+ "name": "sop_parser.py",+ "path": "agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/sop_parser.py",+ "isMarkdown": false+ },+ {+ "name": "validator.py",+ "path": "agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/validator.py",+ "isMarkdown": false+ }+ ],+ "jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/url_ingest": [+ {+ "name": "__init__.py",+ "path": "agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/url_ingest/__init__.py",+ "isMarkdown": false+ },+ {+ "name": "models.py",+ "path": "agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/url_ingest/models.py",+ "isMarkdown": false+ },+ {+ "name": "router.py",+ "path": "agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/url_ingest/router.py",+ "isMarkdown": false+ },+ {+ "name": "url_safety.py",+ "path": "agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/url_ingest/url_safety.py",+ "isMarkdown": false+ },+ {+ "name": "web_page.py",+ "path": "agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/url_ingest/web_page.py",+ "isMarkdown": false+ },+ {+ "name": "wechat_article.py",+ "path": "agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/url_ingest/wechat_article.py",+ "isMarkdown": false+ }]-}\ No newline at end of file+}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.mdnew file mode 100644index 0000000000..5049f73c3c--- /dev/null+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/SKILL.md@@ -0,0 +1,50 @@+---+name: skill-gen-4-enterprise-doc+description: Turn SOPs, URLs, or stated intent into an installed skill package. Use when the user asks to generate a skill from a document, link, or workflow. Follow SKILL.md, reference/sop-structure-pipeline.md, and reference/generator-worker-spec.md; finish by promoting the draft into the runtime skills directory (see reference/operator-playbook.md) in the same turn.+---++# Skill Generator (enterprise doc → installed skill)++Instructions here, **`reference/`**, and **`scripts/`** (package **`scripts/skill_gen/`**). **You** obtain SOP plain text, run **full structured extraction** exactly as in **[reference/sop-structure-pipeline.md](./reference/sop-structure-pipeline.md)**, author the package under **`get_agent_workspace_dir() / "skills-draft"`** (per **[reference/generator-worker-spec.md](./reference/generator-worker-spec.md)**), then **immediately promote** it so the skill is **installed and loadable** (see **[reference/operator-playbook.md](./reference/operator-playbook.md)** canonical flow).++## What you do (high level)++1. **Plain text**+ - **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**).+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.+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.++Do not silently shrink **generator-worker-spec** when writing **SKILL.md**.++## Invoking `skill_generator_cli.py` safely++- Always use the **absolute path** to `scripts/skill_generator_cli.py`.+- **`httpx`** / **`beautifulsoup4`** for `url-fetch`. Rich file formats need **openjiuwen** `AutoFileParser` when installed; otherwise use `.md` / `.txt` SOPs.++Path tables and **`skills.import_local`**: **[reference/operator-playbook.md](./reference/operator-playbook.md)**.++## Normative `SKILL.md` format (YAML frontmatter first)++The generated skill’s **`SKILL.md`** must start with **`---`** YAML frontmatter, then **`---`**, then the body. Optional: **`scripts/skill_gen/validator.py`** on the draft path before import.++## When to open reference files++| File | When |+|------|------|+| [reference/sop-structure-pipeline.md](./reference/sop-structure-pipeline.md) | **Always**: `SOPStructure` extraction. |+| [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. |++## Human approval gates++Do **not** modify this meta-skill’s **`SKILL.md`**, **`reference/sop-structure-pipeline.md`**, **`reference/generator-worker-spec.md`**, **`reference/operator-playbook.md`**, or other bundled **`reference/*.md`** while generating a **user** skill. Edit only the **target** skill under the workspace-relative **`skills-draft/<name>/`** staging tree or the installed **`skills/<name>/`** tree (resolve with **`get_agent_workspace_dir()`** / **`get_agent_skills_dir()`** when available).++## Communicating with the user++- Prefer plain language for skill names and outcomes.+- Infer **`skill_name`** (kebab-case) from title or URL when the user did not specify.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.mdnew file mode 100644index 0000000000..4a9e3a21bc--- /dev/null+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/reference/generator-worker-spec.md@@ -0,0 +1,214 @@+# Generator Worker Spec++This document defines how the generator worker should turn SOPs or freeform intent into **executable, usable, output-producing skills**.++Read this file when the worker needs to:++- draft a new skill from an SOP or freeform intent+- decide what the generated `SKILL.md` must make explicit+- infer realistic user inputs and deliverables++For structured SOP → `SOPStructure`, read [sop-structure-pipeline.md](./sop-structure-pipeline.md). For paths and the canonical install flow, read [operator-playbook.md](./operator-playbook.md).++## Core standard: generated skills must be executable++The skill generator is not producing summaries of SOPs. It is producing skills that a future agent can load and **use**.++Every generated skill should make it obvious:++1. what the user may provide+2. what the agent must do+3. what the agent must deliver back++When the SOP explicitly specifies user inputs, required data, or final deliverables, copy those requirements into the generated skill clearly and concretely.++When the SOP does **not** explicitly name them, infer them conservatively from:++- the workflow steps+- the business object being processed+- the systems mentioned+- the final step or business outcome+- the kinds of files, tables, approvals, or reports implied by the SOP++### Examples++- If an SOP says operational data should be compiled into a **spreadsheet** (e.g. “export to Excel” or equivalent wording), the generated skill should explicitly name the inputs the user may supply (e.g. source records, exports, attachments) and state that the final deliverable may need to be a spreadsheet-class file (e.g. Excel or equivalent) aligned with the SOP.+- If an onboarding SOP requires account creation plus manager approval, the generated skill should explicitly say that the agent may need employee identifiers, manager details, and target systems, and that the output may be a completed request package, checklist, or structured confirmation.+- If a policy SOP does not produce a file but does require a formal response, the generated skill should still define a concrete response structure, named fields, approval outcomes, or escalation result.++Do not leave inputs and outputs implicit if the downstream user would otherwise have to guess how to use the generated skill.++### Non-negotiable checklist (every draft)++Use this as a hard gate before you treat a generated `SKILL.md` as done:++0. **Machine-parseable start (standard skill layout)** — This is the **normal industry pattern** for skill `SKILL.md` files: **YAML frontmatter first**, then Markdown. The **first non-empty line** of the file must be `---`, then `name` and `description` (and optional allowed keys), then a closing `---`, then the body. **Do not** prepend chit-chat, headings, or code fences before the opening `---` (a single markdown fence is only acceptable if the **first line inside the fence** is still `---`). JiuwenClaw’s draft pipeline and `validate_skill` depend on this shape.+1. **Executable and outcome-oriented** — The skill tells the runtime agent *what to do* and *what to produce*, not a passive summary of the SOP.+2. **User inputs** — List concrete materials the user might supply (files, IDs, URLs, images, pasted text, forms, tickets, etc.). If the SOP names them, mirror that language; if not, infer from steps and business object.+3. **Deliverables** — Name the expected end state: file type (e.g. `.xlsx` / `.csv`), ticket fields, approval summary, structured reply, checklist, etc. Prefer real artifacts over vague “a response”.+4. **SOP is explicit** — When the SOP states inputs or outputs, **copy them faithfully** into the skill (no softening into generic prose).+5. **SOP is silent** — **Infer conservatively** from workflow, roles, systems, and final-step wording; state assumptions explicitly so reviewers can correct them.+6. **Spreadsheet / tabular outcomes** — When the SOP implies consolidation, reporting, line-item tables, or phrasing like “spreadsheet / Excel / tabular summary”, the skill must state that the agent may need to produce a **spreadsheet-class deliverable** (e.g. Excel or equivalent) and what columns or fields it should reflect.++## 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.+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.++## Drafting from an SOP++Build **one** structured representation of the SOP first: full **`SOPStructure`** via **`parse_sop_file` / `parse_sop_raw_text` + `invoke_llm_json`** only, as defined in **[sop-structure-pipeline.md](./sop-structure-pipeline.md)** (prompts live in `scripts/skill_gen/sop_parser.py` and `sop_chunk_merge.py`—do not fork a second extraction spec).++Then the authoring model should use both that **structured summary** and the **full SOP text** (`raw_text` on the structure) to:++1. Keep classification and field boundaries aligned with the extracted `sop_type`, `steps`, `knowledge_items`, `sections`, branches, and exceptions.+2. Assemble the draft skill input from structured sections plus raw text where fidelity matters.+3. Generate a `SKILL.md` tailored to that SOP type.++The structured object keeps the draft organized; the raw text keeps it faithful to the source.++### 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.++## Creating a skill++### Capture intent++Start by understanding what the user wants. The current conversation might already contain context (e.g., “turn this SOP into a skill”). Extract steps, deliverables, and constraints **and proceed** — **do not** require explicit human confirmation before drafting unless a **blocking** input is missing.++Key questions (infer when possible):++1. What should this skill enable the agent to do?+2. When should this skill trigger? What user phrases or contexts should load it?+3. What are the expected user inputs?+4. What is the expected output format or deliverable?++### Draft `skill_name`++- **`skill_name`** (or synonym fields **`name`** / **`target_skill`**) decides the draft and installed folder name: **`get_agent_workspace_dir() / "skills-draft" / <skill_name>`** → **`get_agent_skills_dir() / <skill_name>`** (resolve with the host’s path helpers when available).+- It also enters the generated `SKILL.md` frontmatter and influences later triggering together with `description`.+- Do not default to asking the user to name the skill before you can start.+- If the user already gave a fixed name, pass it through unchanged.+- If the user did not provide a name, choose a short, precise, kebab-case name before drafting.+- Omit `skill_name` only as a fallback; backend auto-slugging is weaker than an explicit choice.++## Interview and research (for non-SOP skills)++When creating a skill from scratch (no SOP), proactively clarify edge cases, input/output formats, example files, success criteria, and dependencies **when missing**. **Default:** draft with reasonable assumptions and refine when the user returns with feedback or clarifications, instead of blocking on a long interview unless the domain is unsafe or ambiguous.++If the environment exposes **MCP tools** or **web/doc search**, use them to reduce guesswork: look up APIs, internal conventions, or similar skills — in parallel when practical. Bring summarized findings back so the user does not have to spell out everything from memory.++## Writing a high-quality `SKILL.md`++This section is the **single normative home** for what the draft package’s **`SKILL.md`** must contain and how it should read — i.e. how this worker writes a **high-quality** skill document, not merely a valid file. It merges (1) the **required fields and body headings** the generator must produce from an interview or from **`SOPStructure` + raw SOP text**, and (2) the **Skill writing guide** material (directory anatomy, progressive disclosure, safety, patterns, tone) that applies to every skill this worker authors. The subsections below are **additive**: they **concretize** the **Non-negotiable checklist (every draft)** and the **Drafting from an SOP** rules; they do **not** relax or replace them.++### Required frontmatter and body structure++Based on the user interview or SOP parsing, the generated skill needs these components:++- **name**: Skill identifier in kebab-case (must match the skill folder name when installed)+- **description**: When to trigger, what it does. This is the primary triggering mechanism — include both what the skill does **and** specific contexts for when to use it. All “when to use” information belongs here, not scattered only in the body. Agents tend to **undertrigger** skills. Counter that with slightly “pushy” descriptions. Example: instead of a narrow title alone, add concrete user phrases and scenarios that should load this skill (aligned to the SOP’s real callers), e.g. “Use when the user mentions …, …, or … even if they do not use the formal process name.”+- **compatibility** (optional): Rarely needed — only when the skill truly depends on specific tools, models, or external services. If omitted, assume standard Jiuwenclaw agent capabilities.+- **the rest of the skill body**: Procedures, formats, examples, safety notes++The generated `SKILL.md` should make the following explicit with clear Markdown headings:++1. **User inputs / data** — What the user may provide (files, fields, paths, URLs, IDs, images, tables, documents).+2. **Processing** — How the agent applies the SOP (aligned to sections, not a verbatim dump).+3. **Deliverables** — Expected artifacts or outputs (file names, table columns, currencies, validation, ticket fields, approval summaries, spreadsheet outputs, exported data, answer structure).++If the SOP mandates a spreadsheet, form, ticket, report, approval package, or another structured output, the generated skill should say so explicitly. If the SOP does not say so but strongly implies one, infer it conservatively and write it explicitly.++### Pointing to bundled `reference/` in generated skills++If the generated skill ships extra markdown under `reference/`, the `SKILL.md` body must say **when** to open each file (e.g., “Read `reference/exceptions.md` only when the user mentions overrides or appeals.”). Avoid dumping long annexes into SKILL.md when a short pointer plus a dedicated file keeps the default context lean.++### Skill writing guide++The following subsections spell out **directory anatomy**, **progressive disclosure**, **safety expectations**, **reusable writing patterns**, and **tone**. They elaborate the same **`SKILL.md`** artifact described in **Required frontmatter and body structure** and **Pointing to bundled `reference/` in generated skills** above; they do not introduce a second, looser standard for the output file.++#### Anatomy of a skill++```text+skill-name/+├── SKILL.md (required)+│ ├── YAML frontmatter (name, description required)+│ └── Markdown instructions+└── Bundled Resources (optional)+ ├── scripts/ - Executable code for deterministic/repetitive tasks+ ├── reference/ - Docs loaded into context as needed+ └── assets/ - Files used in output (templates, icons, fonts)+```++#### Progressive disclosure++Skills use a three-level loading system:++1. **Metadata** (name + description) — Always in context (~100 words)+2. **SKILL.md body** — In context whenever the skill triggers (<500 lines ideal)+3. **Bundled resources** — As needed (unlimited; scripts can execute without loading full file contents into the prompt)++These word counts are approximate — go longer when necessary.++**Key patterns:**++- Keep SKILL.md under 500 lines; if approaching the limit, add a `reference/` layer and **explicit pointers** (when to read which file)+- For large reference files (>300 lines), include a table of contents at the top of that file++**Domain organization**: When a skill supports multiple domains/variants, organize by variant:++```text+cloud-deploy/+├── SKILL.md (workflow + selection)+└── reference/+ ├── aws.md+ ├── gcp.md+ └── azure.md+```++The agent should read only the relevant reference file for the user's context.++#### Principle of lack of surprise++Skills must not contain malware, exploit code, or instructions that weaken system security. Do not help build misleading skills, skills that facilitate unauthorized access, or skills aimed at data exfiltration. A skill's intent and behavior should match what the user was told it does. Legitimate roleplay or training scenarios are fine; deceptive or harmful use is not.++#### Writing patterns++Prefer the imperative form in instructions.++**Defining output formats:**++```markdown+## Report structure+ALWAYS use this exact template:+# [Title]+## Executive summary+## Key findings+## Recommendations+```++**Examples pattern** — Include examples where useful:++```markdown+## Commit message format+**Example 1:**+Input: Added user authentication with JWT tokens+Output: feat(auth): implement JWT-based authentication+```++#### Writing style++Explain to the model *why* things matter rather than relying only on heavy-handed MUSTs. LLMs respond well to reasoning. If the user's feedback is terse, infer the underlying goal and reflect it in the instructions. If you find yourself writing ALWAYS or NEVER in all caps everywhere, treat it as a yellow flag — reframe with rationale.++Use theory of mind to keep the skill **general**, not overfit to one chat. Draft, re-read, tighten.++## Why this file exists++This file exists so the worker has one place to learn:++- how to turn structured SOP input into an executable skill+- how to write explicit user inputs and deliverables+- how to preserve progressive disclosure and output usefulness when authoring `SKILL.md`+- how to improve generated skills without drifting away from the source SOPdiff --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.mdnew file mode 100644index 0000000000..e761b95223--- /dev/null+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/reference/operator-playbook.md@@ -0,0 +1,96 @@+# Skill Generator Operator Playbook (scripts + main agent)++**`scripts/skill_generator_cli.py`** prepends **`scripts/`** to `sys.path` and imports **`skill_gen`** from **`scripts/skill_gen/`**. Those CLI entrypoints do not import the **`jiuwenclaw`** package.++## Commands (always absolute script path)++```bash+python3 /ABS/…/skill-gen-4-enterprise-doc/scripts/skill_generator_cli.py sop-text \+ --sop-file /ABS/path/SOP.md [--out-text /ABS/out.txt] [--print-raw-chars]++python3 /ABS/…/skill-gen-4-enterprise-doc/scripts/skill_generator_cli.py url-fetch \+ --url 'https://…' [--out-json /ABS/pages.json]+```++- **`sop-text --print-raw-chars`**: prints extracted character count only.+- **`sop-text` without `--out-text`**: prints full UTF-8 text to stdout.+- **`url-fetch`**: JSON array of pages (`text`, `title`, `source_url`, …).++Full **`SOPStructure`** JSON is produced only via **`parse_sop_file` / `parse_sop_raw_text` + `invoke_llm_json`** in the agent runtime ([sop-structure-pipeline.md](./sop-structure-pipeline.md)).++## Install the new skill (same session as draft)++After writing the draft tree with a valid **`SKILL.md`** under **`get_agent_workspace_dir() / "skills-draft" / <skill_name>`** (or the host’s equivalent **agent-workspace** path), **immediately** promote it:++- **RPC:** **`skills.import_local`** with **`{ "path": "<absolute path to that draft folder>" }`**. Add **`"force": true`** if **`get_agent_skills_dir() / <skill_name>`** already exists and should be replaced.+- Result: tree copied to **`get_agent_skills_dir() / <skill_name>`** and skill indexes refreshed — the skill is **ready to use** without a separate user-facing “Import” step.++This replaces a manual **apply** / **Import** handoff: the driving agent performs import as part of completing the SOP→skill task.++## Path resolution (portable)++Do **not** assume a fixed home-directory prefix or legacy **`…/workspace/…`** segments. JiuwenClaw (and forks) may relocate data roots via config or environment; always prefer **whatever path helpers the host exposes** in the system prompt or tool context.++When **`get_agent_workspace_dir()`** / **`get_agent_skills_dir()`** / **`get_agent_root_dir()`** are named in the prompt, use them to build **absolute** paths for drafts, imports, and file tools. If only a virtual tree (e.g. `agent/jiuwenclaw_workspace/...`) is shown, map it through the host’s documented root before writing to disk.++- **Draft staging:** **`skills-draft/<skill_name>/`** lives **under** the agent workspace directory (sibling to the runtime **`skills/`** folder), i.e. **`get_agent_workspace_dir() / "skills-draft" / <skill_name>`**. Create **`skills-draft`** if missing.+- **Installed skills:** user-installed packages land under **`get_agent_skills_dir() / <skill_name>`** (in stock JiuwenClaw this is **…/jiuwenclaw_workspace/skills/<skill_name>**, not **`…/agent/skills/`**).++## Path conventions (typical product layout)++Use **`get_agent_root_dir()`**, **`get_agent_workspace_dir()`**, **`get_agent_skills_dir()`** from the system prompt when available.++| Location | Role |+|----------|------|+| **`get_agent_skills_dir() / "skill-gen-4-enterprise-doc"`** | This meta-skill as **installed** (or the built-in copy resolved via **`get_builtin_skills_dir()`** — treat as read-only unless the product explicitly allows edits). |+| **`get_agent_workspace_dir() / "skills-draft" / <skill_name>`** | Where you write the **new** skill tree before **`skills.import_local`**. |+| **`get_agent_skills_dir() / <skill_name>`** | **Installed** target skill after **`skills.import_local`**. |++**`workdir` for bash tools:** If the environment restricts subprocess cwd, invoke **`python3`** with absolute paths without relying on `cd`.++## SOP files++- Any **absolute** path readable at runtime is fine.+- Without **openjiuwen** `AutoFileParser`, prefer **`.md` / `.txt`**; binary office/PDF needs that dependency.++## 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).+3. Run **`skills.import_local`** as above.++---++# Paths and canonical flow++This section is the same document as **# Skill Generator Operator Playbook** above the horizontal rule (CLI, **`skills.import_local`**, path helpers, drafting). Rules for generated **`SKILL.md`** text and for LLM extraction live in **[generator-worker-spec.md](./generator-worker-spec.md)** and **[sop-structure-pipeline.md](./sop-structure-pipeline.md)**.++## Canonical flow (single pipeline)++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)).+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`**.++## Directory roles++| Path | Role |+|------|------|+| **`get_agent_skills_dir() / <name>`** (conceptually **`<agent_workspace>/skills/<name>/`**) | Installed skills (`SKILL.md`, optional `reference/`, `scripts/`, …). Runtime loads user-installed trees from here. |+| **`get_agent_workspace_dir() / "skills-draft" / <skill_name>`** | Staging: write the new package here, then **`skills.import_local`**. |+| **`jiuwenclaw/.../jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/`** (repo) | Built-in meta-skill template (`get_builtin_skills_dir()`). |+| **`skill-gen-4-enterprise-doc/scripts/`** | `skill_generator_cli.py` (`sop-text`, `url-fetch`); **`scripts/skill_gen/`** — Python extraction (`parse_sop_*`, prompts in `sop_parser.py`, `sop_chunk_merge.py`). |++**`with_skill`–style evaluation** (if used) loads skills from the runtime **skills root** (**`get_agent_skills_dir()`** or the host-documented equivalent) only — promote before expecting the new skill to participate.++## Generated `SKILL.md` — frontmatter++| Rule | Detail |+|------|--------|+| **First line** | `---` (start YAML frontmatter). |+| **Required keys** | `name` (kebab-case), `description` (no `<` / `>` in text). |+| **Then** | Closing `---`, then Markdown body (inputs, processing, deliverables, …). |++Same layout as other Jiuwenclaw skills; **`validate_skill`** in `scripts/skill_gen/validator.py` checks frontmatter and basic structure.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.mdnew file mode 100644index 0000000000..4cfe6b6784--- /dev/null+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/reference/sop-structure-pipeline.md@@ -0,0 +1,16 @@+# SOP → structured JSON (single path)++There is **one** supported way to turn SOP plain text into a full **`SOPStructure`** (rich `steps`, `knowledge_items`, `sections`, `sop_type`, decision points, exceptions, references, etc.):++Call **`skill_gen.sop_parser.parse_sop_file`** or **`parse_sop_raw_text`** and pass a required **`invoke_llm_json`** callable. The implementation chooses single-shot vs chunked map-reduce and optional reconcile using **`parse_options`** (`sop_parse_mode`, context limits, chunk sizes—see the functions’ docstrings in `scripts/skill_gen/sop_parser.py`).++**Authoritative extraction prompts** (what the model must return, field semantics, step vs knowledge rules) live **only** in:++- `scripts/skill_gen/sop_parser.py` — full-document extraction template+- `scripts/skill_gen/sop_chunk_merge.py` — per-chunk and reconcile templates++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`**.++**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__.pynew file mode 100644index 0000000000..c9324ddaef--- /dev/null+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/__init__.py@@ -0,0 +1,13 @@+"""SOP and URL ingest helpers for skill-gen-4-enterprise-doc."""++from .models import SOPStep, SOPStepDict, SOPStructure+from .sop_parser import DEFAULT_SINGLE_SHOT_BUDGET, parse_sop_file, parse_sop_raw_text++__all__ = [+ "DEFAULT_SINGLE_SHOT_BUDGET",+ "SOPStep",+ "SOPStepDict",+ "SOPStructure",+ "parse_sop_file",+ "parse_sop_raw_text",+]diff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/models.py b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/models.pynew file mode 100644index 0000000000..564a585b67--- /dev/null+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/models.py@@ -0,0 +1,166 @@+"""Data models for SOP structure (skill-gen extraction)."""++from __future__ import annotations++from dataclasses import dataclass, field+from typing import Any, TypedDict+++class SOPStepDict(TypedDict):+ """JSON-serializable shape for a single SOP step (``SOPStep.to_dict()``)."""++ step_number: int | str+ actor: str+ action: str+ system: str+ output: str+ notes: str+++@dataclass+class SOPStep:+ """One procedural step extracted from an SOP document."""++ step_number: int | str+ actor: str = ""+ action: str = ""+ system: str = ""+ output: str = ""+ notes: str = ""++ def to_dict(self) -> SOPStepDict:+ return {+ "step_number": self.step_number,+ "actor": self.actor,+ "action": self.action,+ "system": self.system,+ "output": self.output,+ "notes": self.notes,+ }++ @classmethod+ def from_dict(cls, data: dict[str, Any], fallback_idx: int = 0) -> "SOPStep":+ raw_step_number = data.get("step_number", fallback_idx)+ if isinstance(raw_step_number, int):+ step_number: int | str = raw_step_number+ elif isinstance(raw_step_number, float) and raw_step_number.is_integer():+ step_number = int(raw_step_number)+ else:+ text = str(raw_step_number).strip()+ step_number = int(text) if text.isdigit() else (text or fallback_idx)+ return cls(+ step_number=step_number,+ actor=str(data.get("actor", "")),+ action=str(data.get("action", "")),+ system=str(data.get("system", "")),+ output=str(data.get("output", "")),+ notes=str(data.get("notes", "")),+ )+++@dataclass+class SOPStructure:+ """Structured view of an SOP-style document for extraction and drafting.++ ``sop_type`` is one of ``procedural``, ``knowledge``, or ``hybrid`` (see+ ``sop_parser`` prompt definitions). ``steps`` holds ordered actions;+ ``knowledge_items`` holds rules, thresholds, and penalties that are not+ linear steps; ``sections`` mirrors the source outline.+ """++ title: str = ""+ purpose: str = ""+ scope: str = ""+ sop_type: str = ""+ roles: list[str] = field(default_factory=list)+ steps: list[SOPStep] = field(default_factory=list)+ knowledge_items: list[str] = field(default_factory=list)+ sections: list[dict[str, Any]] = field(default_factory=list)+ decision_points: list[str] = field(default_factory=list)+ exceptions: list[str] = field(default_factory=list)+ references: list[str] = field(default_factory=list)+ raw_text: str = ""++ def to_dict(self) -> dict[str, Any]:+ return {+ "title": self.title,+ "purpose": self.purpose,+ "scope": self.scope,+ "sop_type": self.sop_type,+ "roles": list(self.roles),+ "steps": [step.to_dict() for step in self.steps],+ "knowledge_items": list(self.knowledge_items),+ "sections": list(self.sections),+ "decision_points": list(self.decision_points),+ "exceptions": list(self.exceptions),+ "references": list(self.references),+ "raw_text": self.raw_text,+ }++ @classmethod+ def from_dict(cls, data: dict[str, Any]) -> "SOPStructure":+ steps_raw = data.get("steps", [])+ steps = [+ SOPStep.from_dict(s, fallback_idx=i) if isinstance(s, dict) else SOPStep(step_number=i, action=str(s))+ for i, s in enumerate(steps_raw)+ ]+ sections_raw = data.get("sections", [])+ sections = [dict(s) for s in sections_raw if isinstance(s, dict)]+ return cls(+ title=str(data.get("title", "")),+ purpose=str(data.get("purpose", "")),+ scope=str(data.get("scope", "")),+ sop_type=str(data.get("sop_type", "")),+ roles=[str(r) for r in data.get("roles", [])],+ steps=steps,+ knowledge_items=[str(k) for k in data.get("knowledge_items", []) if str(k).strip()],+ sections=sections,+ decision_points=[str(d) for d in data.get("decision_points", [])],+ exceptions=[str(e) for e in data.get("exceptions", [])],+ references=[str(r) for r in data.get("references", [])],+ raw_text=str(data.get("raw_text", "")),+ )++ def step_summary(self, max_steps: int = 30) -> str:+ """Return a plain-text list of steps (for prompts)."""+ lines: list[str] = []+ for step in self.steps[:max_steps]:+ actor_part = f" [{step.actor}]" if step.actor else ""+ system_part = f" (系统: {step.system})" if step.system else ""+ lines.append(f"{step.step_number}. {step.action}{actor_part}{system_part}")+ if step.output:+ lines.append(f" 输出: {step.output}")+ if step.notes:+ lines.append(f" 备注: {step.notes}")+ return "\n".join(lines)++ def knowledge_summary(self, max_items: int = 30) -> str:+ """Return sections and knowledge items as plain text (for prompts)."""+ lines: list[str] = []+ if self.sections:+ lines.append("=== 章节结构 ===")+ for sec in self.sections[:20]:+ sid = sec.get("id", "")+ stitle = sec.get("title", "")+ summary = sec.get("content_summary", "")+ lines.append(f"[{sid}] {stitle}: {summary}")+ if self.knowledge_items:+ if lines:+ lines.append("")+ lines.append("=== 关键规则与标准 ===")+ for i, item in enumerate(self.knowledge_items[:max_items], 1):+ lines.append(f"K{i}. {item}")+ return "\n".join(lines)++ def full_summary(self, max_steps: int = 30, max_knowledge: int = 30) -> str:+ """Return ``sop_type``, step list, and knowledge block as plain text."""+ parts: list[str] = []+ if self.sop_type:+ parts.append(f"SOP 类型: {self.sop_type}")+ ss = self.step_summary(max_steps)+ if ss:+ parts.append(ss)+ ks = self.knowledge_summary(max_knowledge)+ if ks:+ parts.append(ks)+ return "\n\n".join(parts)diff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/sop_chunk_merge.py b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/sop_chunk_merge.pynew file mode 100644index 0000000000..abafff7e5f--- /dev/null+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/sop_chunk_merge.py@@ -0,0 +1,586 @@+"""Long SOP: budget-aware chunking, map-reduce merge, optional reconcile.++Chunking is driven by total prompt size (template + SOP content) vs model context limit.+Single-shot when full SOP fits; else recursive bisection at semantic boundaries.+"""++from __future__ import annotations++import json+import logging+import re+from typing import Any, Callable++from .models import SOPStructure++logger = logging.getLogger(__name__)++# Max size of prev_context + next_context + current_heading when enriching chunks+_CHUNK_CONTEXT_SLACK = 1100++_CHUNK_PARTIAL_PROMPT = """\+你是企业 SOP 结构化分析专家。以下为完整 SOP 文档的第 {chunk_index}/{chunk_total} 段(section_id={section_id})。+正文仍以本段为准,但你还会看到少量前后文提示,用于理解代词、省略项、前置条件和“见上一节/下文”的依赖关系。不要编造正文中不存在的规则;只能用前后文来补全本段中已经显式出现但脱离上下文就难以理解的信息。++## 关于 steps 与 knowledge_items 的区分++- `steps`:只放**按时间顺序执行的具体操作动作**(某人/系统在某时间做的事)。+- `knowledge_items`:放**规则、标准、阈值、条件、处罚、速查参数**等非流程性参考知识。每条必须自包含,保留原文中的具体数字/金额/比例。+- `sections`:本段中可见的章节/小节标题和编号。++如果不确定某内容是 step 还是 knowledge_item,优先放 knowledge_items。++## 邻近上下文提示(仅用于补足依赖关系)++### 前文提示+{prev_context}++### 当前段标题+{current_heading}++### 后文提示+{next_context}++## 本段原文++{chunk_text}++## 输出 JSON(仅本段可见内容)++```json+{{+ "title": "",+ "purpose": "",+ "scope": "",+ "sop_type": "",+ "roles": [],+ "steps": [+ {{+ "step_number": "1.1.1",+ "actor": "",+ "action": "",+ "system": "",+ "output": "",+ "notes": ""+ }}+ ],+ "knowledge_items": [+ "自包含的规则/标准/阈值语句"+ ],+ "sections": [+ {{+ "id": "2.1",+ "title": "章节标题",+ "content_summary": "一句话概述"+ }}+ ],+ "decision_points": [],+ "exceptions": [],+ "references": []+}}+```++要求:+- **step_number 与 sections[].id 必须是 JSON 字符串(双引号)**,例如 `"1.1"`、`"2.3.1"`。禁止写未加引号的 `1.1.1`(非法 JSON,会导致整段无法解析)。+- steps 中的 step_number 尽量与原文中的步骤编号一致(全局编号)。+- 若本段只有某步骤的续行而没有编号,可省略该步或合并到 notes。+- knowledge_items 中保留原文的具体数字、金额、比例、时间限制。宁多勿少。+- 若正文中的规则依赖前文定义的主体、标准、适用范围、例外条件,请把补全后的条件写成自包含的 knowledge_item,或写入对应 step 的 notes。+- 若正文存在“在上述情况下”“按前述标准”“同前审批路径”之类表达,请结合邻近上下文改写成完整含义。+- 附加字段: "section_id": {section_id}++只输出 JSON。"""+++def _chunk_prompt_overhead() -> int:+ """Length of chunk prompt with empty chunk_text and minimal context placeholders."""+ return len(+ _CHUNK_PARTIAL_PROMPT.format(+ chunk_index=1,+ chunk_total=1,+ section_id=0,+ prev_context="",+ current_heading="",+ next_context="",+ chunk_text="",+ )+ )+++def _find_split_point(text: str, target: int) -> int:+ """Find a semantic boundary near target index; prefer paragraph or heading breaks."""+ if target <= 0 or target >= len(text):+ return target+ boundaries: list[int] = []+ for m in re.finditer(r"(?m)^#{1,6}\s+.+$|\n\n+", text):+ boundaries.append(m.start())+ if not boundaries:+ return target+ best = target+ best_dist = len(text)+ for b in boundaries:+ if 1 <= b < len(text) - 1:+ d = abs(b - target)+ if d < best_dist:+ best_dist = d+ best = b+ return best+++def _bisect_to_fit(text: str, max_chunk_chars: int) -> list[str]:+ """Recursively split text so each piece fits in max_chunk_chars. Prefers semantic boundaries."""+ text = text.strip()+ if not text:+ return []+ if len(text) <= max_chunk_chars:+ return [text]+ mid = len(text) // 2+ split_at = _find_split_point(text, mid)+ if split_at <= 0:+ split_at = mid+ if split_at >= len(text):+ split_at = max(1, len(text) - 1)+ left = text[:split_at].rstrip()+ right = text[split_at:].lstrip()+ if not left:+ return _bisect_to_fit(right, max_chunk_chars)+ if not right:+ return _bisect_to_fit(left, max_chunk_chars)+ return _bisect_to_fit(left, max_chunk_chars) + _bisect_to_fit(right, max_chunk_chars)+++def _enrich_chunks(chunk_texts: list[str]) -> list[dict[str, Any]]:+ """Add section_id, current_heading, prev_context, next_context to each chunk."""+ result: list[dict[str, Any]] = []+ for idx, chunk_text in enumerate(chunk_texts):+ prev_text = chunk_texts[idx - 1] if idx > 0 else ""+ next_text = chunk_texts[idx + 1] if idx + 1 < len(chunk_texts) else ""+ result.append(+ {+ "section_id": idx,+ "chunk_text": chunk_text,+ "current_heading": _heading_for_chunk(chunk_text),+ "prev_context": _context_snippet(prev_text, from_end=True),+ "next_context": _context_snippet(next_text, from_end=False),+ }+ )+ return result+++_RECONCILE_PROMPT = """\+以下 JSON 是由多段 SOP 文本分别抽取后合并的初稿,可能存在:+- 重复步骤或顺序错乱+- 重复的 knowledge_items(同一规则在不同段被提取)+- 章节 sections 的编号冲突++请输出**一份**整理后的 JSON:+1. 合并重复的 steps,修正顺序和编号+2. 合并重复的 knowledge_items(含义相同的只保留更完整的那条)+3. 合并 sections(同 id 只保留更完整的 content_summary)+4. 保留所有不重复的决策点/异常/引用+5. 确定最终的 sop_type(procedural / knowledge / hybrid)+6. 如果后文规则依赖前文定义的适用范围、审批条件、标准或前置动作,请把这种依赖补成自包含表述,不要留下“上述情况”“按前述规则”这类孤立措辞+7. 不要丢失长文档后半段的规则;如果发现 merged 初稿中信息不足,可依据分块摘要恢复更完整的标题、范围、决策与异常++合并稿:+{merged_json}++输出格式与标准 SOP 抽取相同(不要 section_id),只输出 JSON。"""+++def _context_snippet(text: str, *, from_end: bool, max_chars: int = 400, max_lines: int = 6) -> str:+ if not text.strip():+ return "无"+ normalized = text.strip()+ snippet = normalized[-max_chars:] if from_end else normalized[:max_chars]+ lines = [line.strip() for line in snippet.splitlines() if line.strip()]+ if not lines:+ return "无"+ if from_end:+ lines = lines[-max_lines:]+ else:+ lines = lines[:max_lines]+ return "\n".join(lines)+++def _heading_for_chunk(text: str) -> str:+ for line in text.splitlines():+ line = line.strip()+ if not line:+ continue+ return line[:120]+ return "无"+++def split_semantic_chunks(+ text: str,+ max_chunk_chars: int,+ overlap_chars: int,+) -> list[dict[str, Any]]:+ """Split text into chunks; prefer markdown headings and paragraph breaks."""+ if max_chunk_chars <= 0:+ return [+ {+ "section_id": 0,+ "chunk_text": text,+ "current_heading": _heading_for_chunk(text),+ "prev_context": "无",+ "next_context": "无",+ }+ ]+ text = text.strip()+ if len(text) <= max_chunk_chars:+ return [+ {+ "section_id": 0,+ "chunk_text": text,+ "current_heading": _heading_for_chunk(text),+ "prev_context": "无",+ "next_context": "无",+ }+ ]++ # Split on headings or double newlines+ boundaries: list[int] = [0]+ for m in re.finditer(r"(?m)^#{1,3}\s+.+$|\n\n+", text):+ boundaries.append(m.start())+ boundaries.append(len(text))+ boundaries = sorted(set(boundaries))++ segments: list[str] = []+ for i in range(len(boundaries) - 1):+ start = boundaries[i]+ end = boundaries[i + 1]+ seg = text[start:end].strip()+ if seg:+ segments.append(seg)++ if not segments:+ segments = [text]++ chunks: list[tuple[int, str]] = []+ buf = ""+ section_id = 0+ for seg in segments:+ if not buf:+ buf = seg+ elif len(buf) + 2 + len(seg) <= max_chunk_chars:+ buf = buf + "\n\n" + seg+ else:+ if buf:+ chunks.append((section_id, buf))+ section_id += 1+ if len(seg) <= max_chunk_chars:+ buf = seg+ else:+ # Hard-split long segment by windows with overlap+ start = 0+ while start < len(seg):+ end = min(len(seg), start + max_chunk_chars)+ piece = seg[start:end]+ chunks.append((section_id, piece))+ section_id += 1+ if end >= len(seg):+ break+ start = max(0, end - overlap_chars)+ buf = ""+ while len(buf) > max_chunk_chars:+ take = buf[:max_chunk_chars]+ chunks.append((section_id, take))+ section_id += 1+ buf = buf[max(0, max_chunk_chars - overlap_chars):]+ if buf:+ chunks.append((section_id, buf))++ enriched: list[dict[str, Any]] = []+ for idx, (section_id, chunk_text) in enumerate(chunks):+ prev_text = chunks[idx - 1][1] if idx > 0 else ""+ next_text = chunks[idx + 1][1] if idx + 1 < len(chunks) else ""+ enriched.append(+ {+ "section_id": section_id,+ "chunk_text": chunk_text,+ "current_heading": _heading_for_chunk(chunk_text),+ "prev_context": _context_snippet(prev_text, from_end=True),+ "next_context": _context_snippet(next_text, from_end=False),+ }+ )+ return enriched+++def _normalize_key(s: str) -> str:+ return re.sub(r"\s+", " ", (s or "").strip().lower())[:200]+++def _step_key(raw: Any) -> str:+ text = str(raw).strip()+ return text if text else "0"+++def _step_sort_key(raw: Any) -> tuple[int, tuple[int | str, ...], str]:+ text = str(raw).strip()+ if not text:+ return (2, (), "")+ if text.isdigit():+ return (0, (int(text),), text)+ parts = re.split(r"[.\-_/]", text)+ if parts and all(part.isdigit() for part in parts if part):+ return (1, tuple(int(part) for part in parts if part), text)+ return (2, (), text)+++def _merge_text_field(left: str, right: str) -> str:+ left = str(left or "").strip()+ right = str(right or "").strip()+ if not left:+ return right+ if not right or right == left:+ return left+ if right in left:+ return left+ if left in right:+ return right+ return f"{left};{right}"+++def _append_unique_preserve_order(items: list[str], seen: set[str], raw: Any) -> None:+ value = str(raw or "").strip()+ if not value:+ return+ key = _normalize_key(value)+ if key in seen:+ return+ seen.add(key)+ items.append(value)+++def _merge_step_dict(prev: dict[str, Any] | None, current: dict[str, Any]) -> dict[str, Any]:+ if prev is None:+ return dict(current)+ merged = dict(prev)+ merged["step_number"] = current.get("step_number", prev.get("step_number"))+ for field in ("actor", "action", "system", "output", "notes"):+ merged[field] = _merge_text_field(prev.get(field, ""), current.get(field, ""))+ return merged+++def merge_partial_dicts(partials: list[dict[str, Any]]) -> dict[str, Any]:+ """Deterministic merge of chunk-level partial JSON dicts."""+ title = ""+ purpose = ""+ scope = ""+ sop_type_votes: list[str] = []+ roles: list[str] = []+ role_seen: set[str] = set()+ steps_by_num: dict[str, dict[str, Any]] = {}+ knowledge_items: list[str] = []+ ki_seen: set[str] = set()+ sections_by_id: dict[str, dict[str, Any]] = {}+ dps: list[str] = []+ dp_seen: set[str] = set()+ exs: list[str] = []+ ex_seen: set[str] = set()+ refs: list[str] = []+ ref_seen: set[str] = set()++ for p in partials:+ if not isinstance(p, dict):+ continue+ if str(p.get("title", "")).strip():+ title = title or str(p.get("title", "")).strip()+ if str(p.get("purpose", "")).strip():+ purpose = purpose or str(p.get("purpose", "")).strip()+ if str(p.get("scope", "")).strip():+ scope = scope or str(p.get("scope", "")).strip()+ st_val = str(p.get("sop_type", "")).strip().lower()+ if st_val in ("procedural", "knowledge", "hybrid"):+ sop_type_votes.append(st_val)+ for r in p.get("roles", []) or []:+ _append_unique_preserve_order(roles, role_seen, r)+ for st in p.get("steps", []) or []:+ if not isinstance(st, dict):+ continue+ step_number = st.get("step_number", "")+ if not str(step_number).strip():+ continue+ key = _step_key(step_number)+ prev = steps_by_num.get(key)+ steps_by_num[key] = _merge_step_dict(prev, st)+ for ki in p.get("knowledge_items", []) or []:+ _append_unique_preserve_order(knowledge_items, ki_seen, ki)+ for sec in p.get("sections", []) or []:+ if not isinstance(sec, dict):+ continue+ sid = str(sec.get("id", "")).strip()+ if not sid:+ continue+ prev_sec = sections_by_id.get(sid)+ if prev_sec is None:+ sections_by_id[sid] = dict(sec)+ continue+ merged_sec = dict(prev_sec)+ for field in ("title", "content_summary"):+ merged_sec[field] = _merge_text_field(prev_sec.get(field, ""), sec.get(field, ""))+ sections_by_id[sid] = merged_sec+ for x in p.get("decision_points", []) or []:+ _append_unique_preserve_order(dps, dp_seen, x)+ for x in p.get("exceptions", []) or []:+ _append_unique_preserve_order(exs, ex_seen, x)+ for x in p.get("references", []) or []:+ _append_unique_preserve_order(refs, ref_seen, x)++ if sop_type_votes:+ from collections import Counter+ most_common = Counter(sop_type_votes).most_common(1)[0][0]+ if len(set(sop_type_votes)) > 1:+ sop_type = "hybrid"+ else:+ sop_type = most_common+ else:+ sop_type = ""++ ordered_steps = [steps_by_num[k] for k in sorted(steps_by_num.keys(), key=_step_sort_key)]+ ordered_sections = sorted(sections_by_id.values(), key=lambda s: str(s.get("id", "")))+ return {+ "title": title,+ "purpose": purpose,+ "scope": scope,+ "sop_type": sop_type,+ "roles": roles,+ "steps": ordered_steps,+ "knowledge_items": knowledge_items,+ "sections": ordered_sections,+ "decision_points": dps,+ "exceptions": exs,+ "references": refs,+ }+++def _compute_room_for_chunk(+ max_context_chars: int,+ safety_margin: int,+ max_chunk_chars: int | None,+) -> int:+ """Max chars for chunk_text such that full prompt fits in context."""+ room = max_context_chars - _chunk_prompt_overhead() - _CHUNK_CONTEXT_SLACK - safety_margin+ if max_chunk_chars is not None and max_chunk_chars > 0 and room > max_chunk_chars:+ room = max_chunk_chars+ return max(1, room)+++def _reconcile_has_usable_structure(rec: dict[str, Any]) -> bool:+ for key in ("steps", "knowledge_items", "sections", "decision_points", "exceptions", "title"):+ if rec.get(key):+ return True+ return False+++async def extract_structure_chunked(+ raw_text: str,+ invoke_llm_json: Callable[..., Any],+ *,+ max_context_chars: int,+ safety_margin: int,+ max_chunk_chars: int | None = None,+ chunk_overlap: int = 0,+ run_reconcile: bool = True,+) -> tuple[SOPStructure, dict[str, Any]]:+ """Map-reduce extraction over budget-aware recursive bisection chunks."""+ room = _compute_room_for_chunk(max_context_chars, safety_margin, max_chunk_chars)+ chunk_texts = _bisect_to_fit(raw_text.strip(), room)+ chunks = _enrich_chunks(chunk_texts)+ meta: dict[str, Any] = {+ "mode": "chunked",+ "chunk_count": len(chunks),+ "overlap": chunk_overlap,+ "max_chunk_chars": room,+ "merge_warnings": [],+ }++ partials: list[dict[str, Any]] = []+ meta["chunk_summaries"] = []+ for idx, chunk in enumerate(chunks, start=1):+ prompt = _CHUNK_PARTIAL_PROMPT.format(+ chunk_index=idx,+ chunk_total=len(chunks),+ section_id=chunk["section_id"],+ prev_context=chunk["prev_context"],+ current_heading=chunk["current_heading"],+ next_context=chunk["next_context"],+ chunk_text=chunk["chunk_text"],+ )+ data = await invoke_llm_json(+ prompt,+ fallback={},+ trace_tag=f"sop_chunk_partial_{idx}_of_{len(chunks)}",+ )+ meta["chunk_summaries"].append(+ {+ "chunk_index": idx,+ "section_id": chunk["section_id"],+ "heading": chunk["current_heading"],+ "char_len": len(chunk["chunk_text"]),+ "empty": not bool(data),+ }+ )+ if isinstance(data, dict) and data:+ data.pop("section_id", None)+ partials.append(data)+ else:+ meta["merge_warnings"].append(f"chunk_{idx}_empty_llm_response")++ if not partials:+ logger.warning("[SOPChunkMerge] All chunk extractions empty")+ meta["merge_warnings"].append("all_chunks_empty")+ return SOPStructure(), meta++ merged = merge_partial_dicts(partials)+ meta["reconcile_applied"] = False+ if run_reconcile and len(chunks) > 1:+ reconcile_payload = {+ "merged_structure": merged,+ "chunk_context": [+ {+ "section_id": chunk["section_id"],+ "heading": chunk["current_heading"],+ "prev_context": chunk["prev_context"],+ "next_context": chunk["next_context"],+ }+ for chunk in chunks+ ],+ }+ merged_json = json.dumps(reconcile_payload, ensure_ascii=False, indent=2)+ rec_prompt = _RECONCILE_PROMPT.format(merged_json=merged_json)+ rec = await invoke_llm_json(rec_prompt, fallback={}, trace_tag="sop_chunk_reconcile")+ if isinstance(rec, dict) and _reconcile_has_usable_structure(rec):+ merged = rec+ meta["reconcile_applied"] = True++ sop = SOPStructure.from_dict(merged)+ return sop, meta+++async def extract_structure_single_shot(+ raw_text_for_prompt: str,+ invoke_llm_json: Callable[..., Any],+ *,+ full_prompt_template: str,+ single_shot_budget: int,+ prompt_truncated: bool,+) -> tuple[SOPStructure, dict[str, Any]]:+ """One LLM call; raw_text_for_prompt is what is embedded in the prompt (may be truncated)."""+ prompt = full_prompt_template.format(raw_text=raw_text_for_prompt)+ data = await invoke_llm_json(prompt, fallback={}, trace_tag="sop_extract_single_shot")+ meta: dict[str, Any] = {+ "mode": "single",+ "chunk_count": 1,+ "overlap": 0,+ "single_shot_budget": single_shot_budget,+ "prompt_truncated": prompt_truncated,+ "merge_warnings": [],+ }+ if not isinstance(data, dict) or not data:+ meta["merge_warnings"].append("empty_llm_response")+ return SOPStructure(), meta+ sop = SOPStructure.from_dict(data)+ return sop, metadiff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/sop_parser.py b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/sop_parser.pynew file mode 100644index 0000000000..0d51a56bb5--- /dev/null+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/sop_parser.py@@ -0,0 +1,455 @@+"""SOP document ingestion and structured extraction.++Loads plain text from files (see ``_extract_raw_text``), then extracts a full+``SOPStructure`` via the LLM prompts in this module and ``sop_chunk_merge``+(single-shot or chunked, budget-aware).+"""++from __future__ import annotations++import logging+from pathlib import Path+from typing import Any, Callable++from .models import SOPStructure+from .sop_chunk_merge import extract_structure_chunked, extract_structure_single_shot++logger = logging.getLogger(__name__)++DEFAULT_SINGLE_SHOT_BUDGET = 12000+DEFAULT_MAX_CHUNK_CHARS = 8000+DEFAULT_CHUNK_OVERLAP = 1200+DEFAULT_MAX_CONTEXT_CHARS = 120_000+DEFAULT_SAFETY_MARGIN = 2000++_SOP_EXTRACTION_PROMPT = """\+你是一名企业 SOP 结构化分析专家,擅长从各种格式的 SOP / 政策 / 流程文档中提取结构化信息。++**体裁说明**:下文中的行业场景、数字与流程**仅用于示范抽取 JSON 的格式**(提示工程常见做法),为虚构或合成示意,**不代表**产品与任何特定客户、业务线或内部制度绑定。对真实输入文档应忠实于原文,勿套用下列范例中的具体数值或域名。++## 任务++给你一份 SOP 原始文本,请完成以下两步:++### 第一步:判断 SOP 类型++先通读全文,判断该文档属于以下哪种类型:++- **procedural**(流程型):文档以**按时间顺序执行的操作步骤**为主。大部分内容是"第一步做什么、第二步做什么"的指令序列。例:员工入职流程、软件发布审批流程。+- **knowledge**(知识/政策型):文档以**规则、标准、条件、限额、场景分支**为主。可能有一个简短的流程骨架,但大部分篇幅是各种场景下的具体规定和参考信息。例:变更窗口与发布管控规定、客服工单 SLA、合规抽检比例、**事项登记/办结超期与阶梯扣减**类规定、数据安全管理规定。+- **hybrid**(混合型):既有清晰的流程步骤,又有大量嵌入式规则和条件分支。例:采购审批流程(流程清晰,但不同金额/类别有不同审批规则)。++### 第二步:按类型提取结构化信息++#### `steps`(操作步骤)—— 仅提取真正的顺序操作++steps 只放**按时间先后执行的具体操作动作**。判断标准:这件事是某个人/系统在某个时间点**做**的一个动作。++✅ 应放入 steps:+- "运维工程师在变更系统中提交生产发布申请并附带回滚方案" —— 这是一个动作+- "客服坐席在工单系统中受理客户请求并创建工单" —— 这是一个动作+- "经办人在系统完成流程办结登记并提交时间戳确认" —— 这是一个动作(仅为跨领域格式示意)++❌ 不应放入 steps:+- "生产环境周五 18:00 至周一 10:00 禁止未经审批的变更" —— 这是一条规则,放 knowledge_items+- "P2 工单须在 4 小时内首次响应" —— 这是一个 SLA 参数,放 knowledge_items+- "审计发现的高风险缺陷须在 30 日内闭环整改" —— 这是一条时限罚则,放 knowledge_items++对于 knowledge 型文档,steps 可能很少(3-5 个骨架步骤),这是正常的。不要为了填充 steps 而把规则伪装成步骤。++#### `knowledge_items`(知识条目)—— 提取规则、标准、阈值、条件、罚则++knowledge_items 放**非流程性的参考知识**:规则、政策、标准、限额、条件判断、处罚规定、场景特例、速查信息。++每条 knowledge_item 必须是**自包含的完整语句**,包含该规则的条件和结论。读者不需要看上下文就能理解这条规则的含义。++✅ 好的 knowledge_item(具体、自包含、保留原文数字):+- "生产环境变更须通过 CAB 评审;紧急变更须在事后 24 小时内补录评审记录"+- "P1 级故障须在识别后 15 分钟内通知值班负责人并建立应急沟通渠道"+- "正式登记日晚于基准事件日 90 天至 365 天的,系统按制度实施阶梯扣减;超过 365 天关闭补录或不予受理(仅为跨领域体裁示意)"+- "合规抽检:高风险流程每年全覆盖,中风险流程每年随机抽检不少于 30% 笔数"+- "客户投诉类工单须在创建后 24 小时内由客服组长复核处理结论并回复客户"++❌ 差的 knowledge_item(模糊、缺少数字、需要上下文才能理解):+- "变更有窗口限制" —— 缺少具体时段或例外条件+- "工单响应要快" —— 没有保留具体时限+- "超期会有扣减" —— 没有保留具体比例和时间++**提取原则:宁多勿少。** 宁可多提取几条规则也不要遗漏重要的标准和阈值。原文中出现的具体数字、金额、比例、时间限制、重量限制等必须原样保留在 knowledge_item 中。++#### `sections`(章节结构)—— 保留文档的层级组织++提取文档中的章节/小节层级结构。每个 section 包含:+- `id`:原文编号(如 "1.1", "2.3.1", "Part 2"),如无编号则用 "s1", "s2" 等+- `title`:章节标题+- `content_summary`:该章节主要内容的一句话概述++#### 其他字段++- `decision_points`:流程中的条件分支("如果A则B,否则C")+- `exceptions`:异常/边界场景的处理方式+- `references`:引用的外部文档、系统、URL++如果某字段在原文中未明确提及,留空字符串或空列表,不要编造。++**JSON 硬约束(必须遵守)**:`steps[].step_number` 与 `sections[].id` 必须是**带双引号的字符串**(例如 `"1"`、`"1.1"`、`"2.3.1"`)。**禁止**输出未加引号的层级编号如 `1.1.1`——在 JSON 中这是非法数字,会导致解析失败。++## 输出 JSON 格式++```json+{{+ "title": "SOP 标题",+ "purpose": "SOP 目的/目标",+ "scope": "适用范围",+ "sop_type": "procedural | knowledge | hybrid",+ "roles": ["角色1", "角色2"],+ "steps": [+ {{+ "step_number": "1",+ "actor": "执行者/角色",+ "action": "具体操作描述",+ "system": "使用的工具或系统(如有)",+ "output": "预期输出/交付物",+ "notes": "条件、注意事项"+ }}+ ],+ "knowledge_items": [+ "自包含的规则/标准/阈值/条件语句,保留原文数字"+ ],+ "sections": [+ {{+ "id": "2.1",+ "title": "章节标题",+ "content_summary": "该章节主要内容一句话概述"+ }}+ ],+ "decision_points": [+ "条件分支描述"+ ],+ "exceptions": [+ "异常/边界场景处理方式"+ ],+ "references": [+ "引用的外部文档或系统"+ ]+}}+```++## 示例 A:流程型 SOP++**输入片段**:+> # 员工入职流程+> 1. HR 在系统中创建新员工账号+> 2. IT 部门配置工位和电脑+> 3. 部门经理安排入职培训+> 4. 员工签署保密协议++**预期输出**:+```json+{{+ "sop_type": "procedural",+ "steps": [+ {{"step_number": "1", "actor": "HR", "action": "在系统中创建新员工账号", "system": "HR系统", "output": "员工账号", "notes": ""}},+ {{"step_number": "2", "actor": "IT部门", "action": "配置工位和电脑", "system": "", "output": "工位和设备就绪", "notes": ""}},+ {{"step_number": "3", "actor": "部门经理", "action": "安排入职培训", "system": "", "output": "", "notes": ""}},+ {{"step_number": "4", "actor": "员工", "action": "签署保密协议", "system": "", "output": "已签署的保密协议", "notes": ""}}+ ],+ "knowledge_items": [],+ "sections": []+}}+```++## 示例 B:知识/政策型 SOP(客服工单 SLA 与升级 — 虚构示意)++**输入片段**:+> # 客服工单处理与升级规范+> 1.1 一线坐席在系统中创建工单并标注优先级(P1–P4)+> 1.2 升级规则:P2 故障若 4 小时内无二线接手,自动升级到值班主管;投诉类工单须在 24 小时内由组长复核结论+> 2.1 P1:核心业务不可用,须在 15 分钟内电话通知值班负责人并拉通应急群+> 2.2 P3–P4:工作日按队列顺序处理,单工单无故搁置不得超过 48 小时+> 3.1 知识库已覆盖的咨询类问题,首次响应须在 30 分钟内给出标准答复或文档链接++**预期输出**:+```json+{{+ "sop_type": "hybrid",+ "steps": [+ {{"step_number": "1", "actor": "一线坐席", "action": "在系统中创建工单并标注优先级", "system": "工单系统", "output": "已分级工单", "notes": ""}},+ {{"step_number": "2", "actor": "二线工程师", "action": "接手故障工单并排查", "system": "", "output": "排查记录或解决方案", "notes": "按优先级 SLA"}}+ ],+ "knowledge_items": [+ "P2 级故障工单若 4 小时内无二线工程师接手,系统自动升级并通知值班主管",+ "投诉类工单须在创建后 24 小时内由客服组长复核处理结论并回复客户",+ "P1 级(核心业务不可用)须在识别后 15 分钟内电话通知值班负责人并建立应急沟通群",+ "P3、P4 级工单在工作日须按队列顺序处理,单条工单无故搁置不得超过 48 小时",+ "知识库已覆盖的咨询类工单,首次响应须在 30 分钟内给出标准答复或有效文档链接"+ ],+ "sections": [+ {{"id": "1.1", "title": "工单创建与分级", "content_summary": "坐席创建工单并标注 P1–P4"}},+ {{"id": "1.2", "title": "升级规则", "content_summary": "超时自动升级与投诉复核时限"}},+ {{"id": "2.1", "title": "P1 应急响应", "content_summary": "15 分钟内通知负责人并建群"}},+ {{"id": "2.2", "title": "P3–P4 处理", "content_summary": "队列处理与搁置上限"}},+ {{"id": "3.1", "title": "咨询类 SLA", "content_summary": "30 分钟内标准答复或文档"}}+ ],+ "decision_points": [+ "工单为 P1 时是否立即启动应急通知流程",+ "投诉类是否必须在 24 小时内经组长复核"+ ],+ "exceptions": [],+ "references": []+}}+```++## 示例 C:登记时效与阶梯扣减(节选,仅示范「时限 + 数字」体裁,虚构)++**输入片段**:+> # 通用流程办结与登记时效(节选,虚构示意)+> 4.1 正式登记日晚于基准事件日 90 天提交的,系统按制度实施阶梯扣减;超过 365 天的不予受理或关闭补录+> 4.2 缺失必填佐证材料时须在系统选择「缺件声明」,并按制度计提扣减(具体比例以原文为准)++**预期输出**:+```json+{{+ "sop_type": "knowledge",+ "steps": [],+ "knowledge_items": [+ "正式登记日晚于基准事件日 90 天的,系统按制度实施阶梯扣减;超过 365 天提交的不予受理",+ "缺失必填佐证材料时须在系统选择「缺件声明」,并按制度计提扣减,扣减比例以制度原文记载为准"+ ],+ "sections": [+ {{"id": "4.1", "title": "登记时效", "content_summary": "90 天与 365 天两条时限及阶梯扣减或不予受理"}},+ {{"id": "4.2", "title": "缺件与扣减", "content_summary": "系统声明选项与扣减依原文"}}+ ],+ "decision_points": [],+ "exceptions": [],+ "references": []+}}+```++## SOP 原始文本++{raw_text}++请只输出 JSON,不要输出其他内容。"""+++def _single_shot_prompt_overhead() -> int:+ """Length of single-shot template with empty raw_text placeholder."""+ return len(_SOP_EXTRACTION_PROMPT) - len("{raw_text}")+++def _room_for_sop_single(max_context_chars: int, safety_margin: int) -> int:+ """Max SOP chars that fit in a single-shot prompt."""+ return max(1, max_context_chars - _single_shot_prompt_overhead() - safety_margin)+++def _default_parse_options(options: dict[str, Any] | None) -> dict[str, Any]:+ opts = dict(options or {})+ opts.setdefault("sop_parse_mode", "auto")+ opts.setdefault("single_shot_budget", DEFAULT_SINGLE_SHOT_BUDGET)+ opts.setdefault("max_chunk_chars", DEFAULT_MAX_CHUNK_CHARS)+ opts.setdefault("chunk_overlap", DEFAULT_CHUNK_OVERLAP)+ opts.setdefault("max_context_chars", DEFAULT_MAX_CONTEXT_CHARS)+ opts.setdefault("safety_margin", DEFAULT_SAFETY_MARGIN)+ return opts+++async def parse_sop_raw_text(+ raw_text: str,+ *,+ invoke_llm_json: Callable[..., Any],+ parse_options: dict[str, Any] | None = None,+ source_label: str = "",+) -> tuple[SOPStructure, dict[str, Any]]:+ """Run SOP structure extraction on already-loaded plain text (file, URL body, etc.).++ ``invoke_llm_json`` is required: full ``SOPStructure`` extraction is LLM-only+ (prompts in this module and ``sop_chunk_merge``).++ ``source_label`` is stored in ``extraction_meta`` (e.g. file path or URL).+ """+ raw_text = (raw_text or "").strip()+ if not raw_text:+ raise ValueError("SOP 文本为空")++ opts = _default_parse_options(parse_options)+ mode = str(opts["sop_parse_mode"]).strip().lower()+ max_context = int(opts["max_context_chars"])+ safety_margin = int(opts["safety_margin"])+ room_single = _room_for_sop_single(max_context, safety_margin)+ single_shot_cap = int(opts["single_shot_budget"])+ if single_shot_cap > 0 and single_shot_cap < room_single:+ room_single = single_shot_cap+ max_chunk = int(opts["max_chunk_chars"])+ overlap = int(opts["chunk_overlap"])++ use_chunked: bool+ if mode == "chunked":+ use_chunked = True+ elif mode == "single":+ use_chunked = False+ else:+ # auto: chunk only when full prompt (template + SOP) would exceed context+ use_chunked = len(raw_text) > room_single++ extraction_meta: dict[str, Any]++ if use_chunked:+ sop, extraction_meta = await extract_structure_chunked(+ raw_text,+ invoke_llm_json,+ max_context_chars=max_context,+ safety_margin=safety_margin,+ max_chunk_chars=max_chunk if max_chunk > 0 else None,+ chunk_overlap=overlap,+ run_reconcile=True,+ )+ extraction_meta["single_shot_budget"] = room_single+ extraction_meta["source_path"] = source_label++ empty_chunk_warnings = [+ w+ for w in extraction_meta.get("merge_warnings", [])+ if isinstance(w, str) and w.startswith("chunk_") and "empty" in w+ ]+ if len(empty_chunk_warnings) >= 2:+ logger.warning(+ "[SOPParser] Chunked extraction lost %s partials; running single-shot fallback",+ len(empty_chunk_warnings),+ )+ prompt_truncated_ss = len(raw_text) > room_single+ text_for_prompt_ss = raw_text[:room_single] if prompt_truncated_ss else raw_text+ sop_ss, meta_ss = await extract_structure_single_shot(+ text_for_prompt_ss,+ invoke_llm_json,+ full_prompt_template=_SOP_EXTRACTION_PROMPT,+ single_shot_budget=room_single,+ prompt_truncated=prompt_truncated_ss,+ )+ score_c = len(sop.steps) + len(sop.knowledge_items) + len(sop.sections)+ score_s = len(sop_ss.steps) + len(sop_ss.knowledge_items) + len(sop_ss.sections)+ if score_s >= score_c:+ sop = sop_ss+ extraction_meta["replaced_by_single_shot_after_chunk_loss"] = True+ extraction_meta["single_shot_fallback_meta"] = {+ "mode": meta_ss.get("mode"),+ "merge_warnings": list(meta_ss.get("merge_warnings", [])),+ }+ if prompt_truncated_ss:+ extraction_meta.setdefault("merge_warnings", []).append(+ f"single_shot_fallback_truncated_to_{room_single}_chars"+ )++ if not sop.steps and not sop.title and not sop.knowledge_items:+ extraction_meta["merge_warnings"].append("extraction_empty_after_chunked")+ raise ValueError(+ "SOP LLM extraction produced no usable structure after chunked pass "+ f"(no steps, title, or knowledge_items). merge_warnings={extraction_meta.get('merge_warnings')}"+ )+ else:+ prompt_truncated = len(raw_text) > room_single+ text_for_prompt = raw_text[:room_single] if prompt_truncated else raw_text+ sop, extraction_meta = await extract_structure_single_shot(+ text_for_prompt,+ invoke_llm_json,+ full_prompt_template=_SOP_EXTRACTION_PROMPT,+ single_shot_budget=room_single,+ prompt_truncated=prompt_truncated,+ )+ extraction_meta["source_path"] = source_label+ if prompt_truncated:+ extraction_meta.setdefault("merge_warnings", []).append(+ f"single_shot_prompt_truncated_to_{room_single}_chars"+ )+ if not sop.steps and not sop.title and not sop.knowledge_items:+ extraction_meta.setdefault("merge_warnings", []).append("extraction_empty_single_shot")+ raise ValueError(+ "SOP LLM extraction produced no usable structure "+ f"(no steps, title, or knowledge_items). merge_warnings={extraction_meta.get('merge_warnings')}"+ )++ weak_reasons: list[str] = []+ if use_chunked:+ if extraction_meta.get("chunk_count", 0) > 1 and not sop.title.strip():+ weak_reasons.append("missing_title_after_chunk_merge")+ if extraction_meta.get("chunk_count", 0) > 1 and not sop.scope.strip() and len(sop.sections) >= 3:+ weak_reasons.append("missing_scope_with_many_sections")+ if extraction_meta.get("chunk_count", 0) > 1 and len(sop.knowledge_items) < 3 and len(raw_text) > room_single:+ weak_reasons.append("too_few_knowledge_items_for_long_sop")+ if extraction_meta.get("chunk_count", 0) > 1 and not extraction_meta.get("reconcile_applied", False):+ weak_reasons.append("reconcile_not_applied")+ extraction_meta["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),+ }+ extraction_meta["weak_reasons"] = weak_reasons+ extraction_meta["use_raw_excerpt_draft_fallback"] = bool(weak_reasons)+ sop.raw_text = raw_text+ return sop, extraction_meta+++async def parse_sop_file(+ file_path: str | Path,+ *,+ invoke_llm_json: Callable[..., Any],+ parse_options: dict[str, Any] | None = None,+) -> tuple[SOPStructure, dict[str, Any]]:+ """Parse an SOP document and extract structured content.++ Returns ``(SOPStructure, extraction_meta)``. Full document text is always+ stored in ``SOPStructure.raw_text``.++ parse_options keys:+ - sop_parse_mode: ``auto`` | ``single`` | ``chunked``+ - max_context_chars: model context limit (default 120000)+ - safety_margin: buffer (default 2000)+ - single_shot_budget: when > 0 and below computed room, caps single-shot character budget+ - max_chunk_chars: cap per chunk when chunking (default 8000)+ - chunk_overlap: overlap parameter for chunked extraction; surfaced in extraction_meta+ """+ file_path = Path(file_path)+ if not file_path.exists():+ raise FileNotFoundError(f"SOP 文件不存在: {file_path}")++ raw_text = await _extract_raw_text(file_path)+ if not raw_text.strip():+ raise ValueError(f"SOP 文件内容为空: {file_path}")++ sop, meta = await parse_sop_raw_text(+ raw_text,+ invoke_llm_json=invoke_llm_json,+ parse_options=parse_options,+ source_label=str(file_path),+ )+ return sop, meta+++async def _extract_raw_text(file_path: Path) -> str:+ """Extract raw text from an SOP file using AutoFileParser when available."""+ try:+ from openjiuwen.core.retrieval.indexing.processor.parser.auto_file_parser import (+ AutoFileParser,+ )++ parser = AutoFileParser()+ if parser.supports(str(file_path)):+ documents = await parser.parse(str(file_path))+ chunks = [doc.text for doc in documents if getattr(doc, "text", "")]+ if chunks:+ return "\n\n".join(chunks)+ logger.warning("[SOPParser] AutoFileParser returned empty, falling back to direct read")+ except ImportError:+ logger.info("[SOPParser] agent-core AutoFileParser unavailable, using direct read")+ except Exception as exc:+ logger.warning("[SOPParser] AutoFileParser error: %s, falling back to direct read", exc)++ suffix = file_path.suffix.lower()+ if suffix in {".md", ".txt", ".json", ".yaml", ".yml"}:+ return file_path.read_text(encoding="utf-8")+ raise ValueError(+ f"无法解析 SOP 文件 {file_path.name}: "+ f"安装 agent-core 以支持 {suffix} 格式,或提供 .md/.txt 文件"+ )diff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/url_ingest/__init__.py b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/url_ingest/__init__.pynew file mode 100644index 0000000000..e92e4d39ff--- /dev/null+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/url_ingest/__init__.py@@ -0,0 +1,63 @@+# coding: utf-8+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.+"""HTTP(S) and WeChat URL fetch helpers for SOP / skill draft input (httpx + bs4)."""++from __future__ import annotations++import ssl+from typing import List++import httpx++from .models import FetchedPage+from .router import fetch_pages_from_url+from .url_safety import check_url_allowed_for_fetch, is_likely_public_http_url+from .wechat_article import is_wechat_article_url+from .web_page import supports_generic_web_url+++def fetch_url_as_plaintext(+ pages: list[FetchedPage],+ *,+ join_sep: str = "\n\n---\n\n",+) -> str:+ """Turn fetched pages into one document string for SOP / skill draft input."""+ parts: list[str] = []+ for p in pages:+ header_lines = [f"Source: {p.source_url}"]+ if p.title:+ header_lines.insert(0, f"Title: {p.title}")+ parts.append("\n".join(header_lines) + "\n\n" + p.text.strip())+ return join_sep.join(parts)+++async def validate_fetch_and_flatten(+ url: str,+ *,+ timeout: float | None = None,+ user_agent: str | None = None,+ verify: bool | str | ssl.SSLContext = True,+ client: httpx.AsyncClient | None = None,+) -> tuple[str, List[FetchedPage]]:+ """Run SSRF checks, fetch the URL, return ``(flattened_text, pages)``."""+ check_url_allowed_for_fetch(url)+ pages = await fetch_pages_from_url(+ url,+ timeout=timeout,+ user_agent=user_agent,+ verify=verify,+ client=client,+ )+ return fetch_url_as_plaintext(pages), pages+++__all__ = [+ "FetchedPage",+ "check_url_allowed_for_fetch",+ "fetch_pages_from_url",+ "fetch_url_as_plaintext",+ "is_likely_public_http_url",+ "is_wechat_article_url",+ "supports_generic_web_url",+ "validate_fetch_and_flatten",+]diff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/url_ingest/models.py b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/url_ingest/models.pynew file mode 100644index 0000000000..0b205ccaa3--- /dev/null+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/url_ingest/models.py@@ -0,0 +1,20 @@+# coding: utf-8+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.+"""Datatypes produced by URL ingest (``FetchedPage``)."""++from __future__ import annotations++from dataclasses import dataclass, field+from typing import Any+++@dataclass+class FetchedPage:+ """One fetched and parsed document from ``url_ingest``."""++ text: str+ source_url: str+ title: str = ""+ source_type: str = ""+ id_: str = ""+ metadata: dict[str, Any] = field(default_factory=dict)diff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/url_ingest/router.py b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/url_ingest/router.pynew file mode 100644index 0000000000..30aa2c067f--- /dev/null+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/url_ingest/router.py@@ -0,0 +1,41 @@+# coding: utf-8+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Dispatch one URL to the WeChat or generic web fetcher."""++from __future__ import annotations++import ssl+import uuid+from typing import List++import httpx++from .models import FetchedPage+from .wechat_article import fetch_wechat_article, is_wechat_article_url+from .web_page import fetch_web_page+++async def fetch_pages_from_url(+ url: str,+ *,+ timeout: float | None = None,+ user_agent: str | None = None,+ verify: bool | str | ssl.SSLContext = True,+ client: httpx.AsyncClient | None = None,+) -> List[FetchedPage]:+ """Fetch one URL and return a list of ``FetchedPage`` (typically one element).++ Optional ``timeout`` and ``user_agent`` override each backend module default.+ """+ u = (url or "").strip()+ doc_id = str(uuid.uuid4())+ kw: dict = {"doc_id": doc_id, "verify": verify, "client": client}+ if timeout is not None:+ kw["timeout"] = timeout+ if user_agent is not None:+ kw["user_agent"] = user_agent++ if is_wechat_article_url(u):+ return await fetch_wechat_article(u, **kw)+ return await fetch_web_page(u, **kw)diff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/url_ingest/url_safety.py b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/url_ingest/url_safety.pynew file mode 100644index 0000000000..c6c589ec50--- /dev/null+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/url_ingest/url_safety.py@@ -0,0 +1,59 @@+# coding: utf-8+# Copyright (c) Huawei Technologies Co., Ltd. 2025-2026. All rights reserved.++"""Reject disallowed URLs before HTTP fetch (``ValueError`` on failure)."""++from __future__ import annotations++import os+import re+import socket+from struct import unpack+from socket import inet_aton+from urllib.parse import urlparse+++def check_url_allowed_for_fetch(url: str) -> None:+ """Require http(s) URL and reject private/reserved IPs (unless SSRF_PROTECT_ENABLED=false)."""+ if not url or not str(url).strip():+ raise ValueError("url is empty")+ url = str(url).strip()+ if not re.match(r"^https?://", url, re.IGNORECASE):+ raise ValueError("illegal url protocol (only http/https allowed)")+ parsed = urlparse(url)+ hostname = parsed.hostname+ if not hostname:+ raise ValueError("URL missing hostname")+ try:+ ip_address = socket.gethostbyname(hostname)+ except OSError as e:+ raise ValueError("resolving IP address failed") from e+ if _is_inner_ipaddress(ip_address):+ raise ValueError("illegal ip address (SSRF protection)")+++def _is_inner_ipaddress(ip: str) -> bool:+ if os.getenv("SSRF_PROTECT_ENABLED", "true").lower() == "false":+ return False+ try:+ ip_long = _ip_to_long(ip)+ except OSError:+ return True+ return (+ _ip_to_long("10.0.0.0") <= ip_long <= _ip_to_long("10.255.255.255")+ or _ip_to_long("172.16.0.0") <= ip_long <= _ip_to_long("172.31.255.255")+ or _ip_to_long("192.168.0.0") <= ip_long <= _ip_to_long("192.168.255.255")+ or _ip_to_long("127.0.0.0") <= ip_long <= _ip_to_long("127.255.255.255")+ or ip_long == _ip_to_long("0.0.0.0")+ )+++def _ip_to_long(ip_addr: str) -> int:+ return unpack("!L", inet_aton(ip_addr))[0]+++def is_likely_public_http_url(url: str) -> bool:+ """Lightweight shape check (does not replace SSRF DNS resolution in check_url_allowed_for_fetch)."""+ if not url or not str(url).strip():+ return False+ return bool(re.match(r"^https?://\S+", str(url).strip(), re.IGNORECASE))diff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/url_ingest/web_page.py b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/url_ingest/web_page.pynew file mode 100644index 0000000000..4d31c3835e--- /dev/null+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/url_ingest/web_page.py@@ -0,0 +1,157 @@+# coding: utf-8+# Copyright (c) Huawei Technologies Co., Ltd. 2025-2026. All rights reserved.++"""Fetch and parse generic HTTP(S) page URLs into ``FetchedPage``."""++from __future__ import annotations++import logging+import re+import ssl+import uuid+from typing import List, Optional++import httpx+from bs4 import BeautifulSoup++from .models import FetchedPage++logger = logging.getLogger(__name__)+from .wechat_article import is_wechat_article_url++HTTP_URL_PATTERN = re.compile(r"^https?://\S+", re.IGNORECASE)++DEFAULT_USER_AGENT = (+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "+ "(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"+)+DEFAULT_TIMEOUT = 30.0++MAIN_CONTENT_SELECTORS = [+ "article",+ "main",+ '[role="main"]',+ ".article-body",+ ".post-content",+ ".content",+ ".entry-content",+ ".post-body",+ "#content",+ ".main-content",+]+++def _parse_html(html: str) -> BeautifulSoup:+ try:+ import lxml # noqa: F401+ return BeautifulSoup(html, "lxml")+ except ImportError:+ return BeautifulSoup(html, "html.parser")+++def _extract_title(soup: BeautifulSoup) -> str:+ meta = soup.find("meta", property="og:title")+ if meta and meta.get("content"):+ return (meta["content"] or "").strip()+ title_tag = soup.find("title")+ if title_tag and title_tag.string:+ return title_tag.string.strip()+ return ""+++def _text_length(node: BeautifulSoup) -> int:+ total = 0+ for elem in node.find_all(string=True):+ if elem.parent and elem.parent.name not in ("script", "style"):+ total += len(elem.strip())+ return total+++def _find_main_content(soup: BeautifulSoup) -> Optional[BeautifulSoup]:+ for sel in MAIN_CONTENT_SELECTORS:+ node = soup.select_one(sel)+ if node and _text_length(node) > 100:+ return node+ body = soup.find("body")+ if body:+ for tag in body.find_all(["article", "main", "div", "section"]):+ if _text_length(tag) > 200:+ return tag+ return body+++def _get_text_from_soup(soup: Optional[BeautifulSoup]) -> str:+ if not soup:+ return ""+ for tag in soup.find_all(["script", "style"]):+ tag.decompose()+ text = soup.get_text(separator="\n", strip=True)+ text = re.sub(r"[ \t]+", " ", text)+ text = re.sub(r"\n\s*\n", "\n\n", text)+ return text.strip()+++async def fetch_web_page(+ url: str,+ doc_id: str = "",+ *,+ timeout: float = DEFAULT_TIMEOUT,+ user_agent: str = DEFAULT_USER_AGENT,+ verify: bool | str | ssl.SSLContext = True,+ client: Optional[httpx.AsyncClient] = None,+) -> List[FetchedPage]:+ url = (url or "").strip()+ if not url or not HTTP_URL_PATTERN.match(url):+ raise ValueError(f"Not a valid HTTP URL: {url!r}")+ if is_wechat_article_url(url):+ raise ValueError("WeChat article URLs must use the WeChat fetcher")++ request_headers = {"User-Agent": user_agent}++ async def _do_get(c: httpx.AsyncClient, *, headers_for_request: Optional[dict] = None) -> str:+ response = await c.get(url, headers=headers_for_request)+ response.raise_for_status()+ return response.text++ try:+ if client is not None:+ html = await _do_get(client, headers_for_request=request_headers)+ else:+ async with httpx.AsyncClient(+ verify=verify,+ timeout=httpx.Timeout(timeout),+ headers=request_headers,+ ) as http_client:+ html = await _do_get(http_client, headers_for_request=None)+ except httpx.HTTPStatusError as e:+ status = e.response.status_code if e.response is not None else "?"+ raise ValueError(f"Web page request failed: {status} for {url}") from e+ except httpx.RequestError as e:+ raise ValueError(f"Web page fetch failed for {url}: {e}") from e+ except Exception as e:+ raise ValueError(f"Web page fetch failed for {url}: {e}") from e++ soup = _parse_html(html)+ title = _extract_title(soup)+ content_node = _find_main_content(soup)+ if not content_node:+ raise ValueError(f"Could not find main content in page: {url}")+ text = _get_text_from_soup(content_node)+ if not text or len(text) < 50:+ raise ValueError(f"Article content too short or empty after parsing: {url}")++ effective_id = doc_id or url or str(uuid.uuid4())+ page = FetchedPage(+ id_=effective_id,+ text=text,+ source_url=url,+ title=title or "(无标题)",+ source_type="web_page",+ metadata={"source_url": url, "title": title or "(无标题)", "source_type": "web_page"},+ )+ logger.info("Parsed web page: url=%s title=%s", url, title or "(无标题)")+ return [page]+++def supports_generic_web_url(url: str) -> bool:+ return bool(url and HTTP_URL_PATTERN.match(url.strip()) and not is_wechat_article_url(url))diff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/url_ingest/wechat_article.py b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/url_ingest/wechat_article.pynew file mode 100644index 0000000000..a9f9b68163--- /dev/null+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/url_ingest/wechat_article.py@@ -0,0 +1,127 @@+# coding: utf-8+# Copyright (c) Huawei Technologies Co., Ltd. 2025-2026. All rights reserved.++"""Fetch and parse WeChat official-account article URLs into ``FetchedPage``."""++from __future__ import annotations++import logging+import re+import ssl+import uuid+from typing import List, Optional++import httpx+from bs4 import BeautifulSoup++from .models import FetchedPage++logger = logging.getLogger(__name__)++WECHAT_MP_URL_PATTERN = re.compile(+ r"^https?://(?:mp\.weixin\.qq\.com|.*?\.weixin\.qq\.com)/s\b.*",+ re.IGNORECASE,+)++DEFAULT_USER_AGENT = (+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "+ "(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"+)+DEFAULT_TIMEOUT = 30.0+++def is_wechat_article_url(url: str) -> bool:+ return bool(url and WECHAT_MP_URL_PATTERN.match(url.strip()))+++def _parse_html(html: str) -> BeautifulSoup:+ try:+ import lxml # noqa: F401+ return BeautifulSoup(html, "lxml")+ except ImportError:+ return BeautifulSoup(html, "html.parser")+++def _extract_title(soup: BeautifulSoup) -> str:+ meta = soup.find("meta", property="og:title")+ if meta and meta.get("content"):+ return (meta["content"] or "").strip()+ title_tag = soup.find("title")+ if title_tag and title_tag.string:+ return title_tag.string.strip()+ return ""+++def _extract_js_content(soup: BeautifulSoup) -> Optional[BeautifulSoup]:+ return soup.find("div", id="js_content")+++def _get_text_from_soup(soup: Optional[BeautifulSoup]) -> str:+ if not soup:+ return ""+ for tag in soup.find_all(["script", "style"]):+ tag.decompose()+ text = soup.get_text(separator="\n", strip=True)+ text = re.sub(r"[ \t]+", " ", text)+ text = re.sub(r"\n\s*\n", "\n\n", text)+ return text.strip()+++async def fetch_wechat_article(+ url: str,+ doc_id: str = "",+ *,+ timeout: float = DEFAULT_TIMEOUT,+ user_agent: str = DEFAULT_USER_AGENT,+ verify: bool | str | ssl.SSLContext = True,+ client: Optional[httpx.AsyncClient] = None,+) -> List[FetchedPage]:+ url = (url or "").strip()+ if not is_wechat_article_url(url):+ raise ValueError(f"Not a WeChat article URL: {url!r}")++ request_headers = {"User-Agent": user_agent}++ async def _do_get(c: httpx.AsyncClient, *, headers_for_request: Optional[dict] = None) -> str:+ response = await c.get(url, headers=headers_for_request)+ response.raise_for_status()+ return response.text++ try:+ if client is not None:+ html = await _do_get(client, headers_for_request=request_headers)+ else:+ async with httpx.AsyncClient(+ verify=verify,+ timeout=httpx.Timeout(timeout),+ headers=request_headers,+ ) as http_client:+ html = await _do_get(http_client, headers_for_request=None)+ except httpx.HTTPStatusError as e:+ status = e.response.status_code if e.response is not None else "?"+ raise ValueError(f"WeChat article request failed: {status} for {url}") from e+ except httpx.RequestError as e:+ raise ValueError(f"WeChat article fetch failed for {url}: {e}") from e+ except Exception as e:+ raise ValueError(f"WeChat article fetch failed for {url}: {e}") from e++ soup = _parse_html(html)+ title = _extract_title(soup)+ content_node = _extract_js_content(soup)+ if not content_node:+ raise ValueError(f"Could not find article content (js_content) in page: {url}")+ text = _get_text_from_soup(content_node)+ if not text:+ raise ValueError(f"Article content is empty after parsing: {url}")++ effective_id = doc_id or url or str(uuid.uuid4())+ page = FetchedPage(+ id_=effective_id,+ text=text,+ source_url=url,+ title=title or "(无标题)",+ source_type="wechat_article",+ metadata={"source_url": url, "title": title or "(无标题)", "source_type": "wechat_article"},+ )+ logger.info("Parsed WeChat article: url=%s title=%s", url, title or "(无标题)")+ return [page]diff --git a/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/validator.py b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/validator.pynew file mode 100644index 0000000000..a4ba66a1b9--- /dev/null+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_gen/validator.py@@ -0,0 +1,150 @@+"""Validation helpers for skill generator."""++from __future__ import annotations++import re+from pathlib import Path+from typing import Any++import yaml+++ALLOWED_FRONTMATTER_KEYS = {+ "name",+ "description",+ "license",+ "allowed-tools",+ "allowed_tools",+ "metadata",+ "compatibility",+}+++def validate_skill(skill_path: Path) -> tuple[bool, str, dict[str, Any]]:+ """Validate a skill directory and return structured details."""+ skill_md = skill_path / "SKILL.md"+ details: dict[str, Any] = {"skill_path": str(skill_path), "errors": [], "warnings": []}++ if not skill_md.exists():+ details["errors"].append("SKILL.md not found")+ return False, "SKILL.md not found", details++ content = skill_md.read_text(encoding="utf-8")+ if not content.startswith("---"):+ details["errors"].append("No YAML frontmatter found")+ return False, "No YAML frontmatter found", details++ match = re.match(r"^---\n(.*?)\n---", content, re.DOTALL)+ if not match:+ details["errors"].append("Invalid frontmatter format")+ return False, "Invalid frontmatter format", details++ try:+ frontmatter = yaml.safe_load(match.group(1))+ except yaml.YAMLError as exc:+ details["errors"].append(f"Invalid YAML in frontmatter: {exc}")+ return False, f"Invalid YAML in frontmatter: {exc}", details++ if not isinstance(frontmatter, dict):+ details["errors"].append("Frontmatter must be a YAML dictionary")+ return False, "Frontmatter must be a YAML dictionary", details++ details["frontmatter"] = frontmatter+ unexpected = sorted(set(frontmatter.keys()) - ALLOWED_FRONTMATTER_KEYS)+ if unexpected:+ message = (+ f"Unexpected key(s) in SKILL.md frontmatter: {', '.join(unexpected)}. "+ f"Allowed properties are: {', '.join(sorted(ALLOWED_FRONTMATTER_KEYS))}"+ )+ details["errors"].append(message)+ return False, message, details++ name = str(frontmatter.get("name", "")).strip()+ description = str(frontmatter.get("description", "")).strip()++ if not name:+ details["errors"].append("Missing 'name' in frontmatter")+ elif not re.match(r"^[a-z0-9-]+$", name):+ details["errors"].append(+ f"Name '{name}' should be kebab-case (lowercase letters, digits, and hyphens only)"+ )+ elif name.startswith("-") or name.endswith("-") or "--" in name:+ details["errors"].append(+ f"Name '{name}' cannot start/end with hyphen or contain consecutive hyphens"+ )+ elif len(name) > 64:+ details["errors"].append(f"Name is too long ({len(name)} characters). Maximum is 64 characters.")++ if not description:+ details["errors"].append("Missing 'description' in frontmatter")+ elif "<" in description or ">" in description:+ details["errors"].append("Description cannot contain angle brackets (< or >)")+ elif len(description) > 1024:+ details["errors"].append(+ f"Description is too long ({len(description)} characters). Maximum is 1024 characters."+ )++ compatibility = frontmatter.get("compatibility", "")+ if compatibility and not isinstance(compatibility, str):+ details["errors"].append(f"Compatibility must be a string, got {type(compatibility).__name__}")+ elif isinstance(compatibility, str) and len(compatibility) > 500:+ details["errors"].append(+ f"Compatibility is too long ({len(compatibility)} characters). Maximum is 500 characters."+ )++ if len(content.splitlines()) > 500:+ details["warnings"].append("SKILL.md is longer than 500 lines; consider progressive disclosure.")++ _check_sop_specific(content, details)++ if details["errors"]:+ return False, details["errors"][0], details+ return True, "Skill is valid!", details+++def _check_sop_specific(content: str, details: dict[str, Any]) -> None:+ """Add SOP-specific validation warnings (non-blocking)."""+ body_lower = content.lower()++ has_workflow_section = bool(+ re.search(r"^#{1,3}\s*(workflow|工作流|步骤|操作流程|流程)", content, re.MULTILINE | re.IGNORECASE)+ )+ if not has_workflow_section:+ details["warnings"].append(+ "SOP 技能建议包含 Workflow/步骤/操作流程 章节,以明确 SOP 步骤序列。"+ )++ tool_indicators = ["tool", "工具", "api", "系统", "file_", "read_", "write_", "search_", "execute"]+ has_tool_usage = any(indicator in body_lower for indicator in tool_indicators)+ if not has_tool_usage:+ details["warnings"].append(+ "SOP 技能通常需要 tool 调用(文件操作、搜索、API 等)。建议在 Workflow 中标明需要的工具。"+ )++ has_user_inputs = bool(+ re.search(+ r"^#{1,3}\s*(用户输入与数据|用户输入|预期输入|user\s+inputs?)",+ content,+ re.MULTILINE | re.IGNORECASE,+ )+ )+ if not has_user_inputs:+ details["warnings"].append(+ "建议增加「用户输入与数据」类章节,明确用户可能提供的材料与字段,便于 agent 执行。"+ )++ has_deliverables = bool(+ re.search(+ r"^#{1,3}\s*(标准交付物|交付物|预期输出|deliverables?)",+ content,+ re.MULTILINE | re.IGNORECASE,+ )+ )+ if not has_deliverables:+ details["warnings"].append(+ "建议增加「标准交付物」类章节,明确文件格式(如 .xlsx/.csv)、字段/列与校验要点。"+ )++ step_pattern = re.compile(r"^\s*\d+[.)]\s", re.MULTILINE)+ step_matches = step_pattern.findall(content)+ details.setdefault("info", {})["sop_step_count_in_body"] = len(step_matches)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.pynew file mode 100644index 0000000000..3a674aede7--- /dev/null+++ b/jiuwenclaw/resources/agent/jiuwenclaw_workspace/skills/skill-gen-4-enterprise-doc/scripts/skill_generator_cli.py@@ -0,0 +1,133 @@+#!/usr/bin/env python3+# Copyright (c) Huawei Technologies Co., Ltd. 2025-2026. All rights reserved.+"""CLI: SOP plain-text extraction and URL fetch for this skill package.++Appends this file's directory to ``sys.path`` (not the front) so ``skill_gen`` imports+without shadowing stdlib. Pass an absolute path to this script; do not rely on process cwd.++Examples:++ python3 /ABS/.../scripts/skill_generator_cli.py sop-text --sop-file /ABS/SOP.md \\+ [--out-text /ABS/out.txt] [--print-raw-chars]++ python3 /ABS/.../scripts/skill_generator_cli.py url-fetch --url 'https://...' [--out-json /ABS/out.json]++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``).++End-to-end draft flow: ``../SKILL.md``.+"""++from __future__ import annotations++import argparse+import asyncio+import json+import logging+import sys+from dataclasses import asdict+from pathlib import Path+from typing import Any++logger = logging.getLogger(__name__)+_stdout_payload_log = logging.getLogger(f"{__name__}.stdout_payload")+++def _ensure_skill_gen_on_path() -> None:+ scripts_dir = Path(__file__).resolve().parent+ s = str(scripts_dir)+ if s not in sys.path:+ sys.path.append(s)+++def _ensure_stdout_payload_log() -> logging.Logger:+ if not _stdout_payload_log.handlers:+ handler = logging.StreamHandler(sys.stdout)+ handler.setFormatter(logging.Formatter("%(message)s"))+ _stdout_payload_log.addHandler(handler)+ _stdout_payload_log.setLevel(logging.INFO)+ _stdout_payload_log.propagate = False+ return _stdout_payload_log+++def _emit_stdout_json(payload: Any) -> None:+ _ensure_stdout_payload_log().info("%s", json.dumps(payload, ensure_ascii=False, indent=2))+++async def _cmd_sop_text(args: argparse.Namespace) -> int:+ sop_path = args.sop_file.expanduser().resolve()+ if not sop_path.is_file():+ logger.error("error: file not found: %s", sop_path)+ return 2++ from skill_gen.sop_parser import _extract_raw_text++ raw = await _extract_raw_text(sop_path)+ if args.print_raw_chars:+ _ensure_stdout_payload_log().info("%s", len(raw))+ return 0+ if args.out_text:+ args.out_text.parent.mkdir(parents=True, exist_ok=True)+ args.out_text.write_text(raw, encoding="utf-8")+ return 0+ _ensure_stdout_payload_log().info("%s", raw)+ return 0+++async def _cmd_url_fetch(args: argparse.Namespace) -> int:+ from skill_gen.url_ingest import fetch_pages_from_url++ url = (args.url or "").strip()+ if not url:+ logger.error("error: empty --url")+ return 2+ pages = await fetch_pages_from_url(url)+ payload = [asdict(p) for p in pages]+ text = json.dumps(payload, ensure_ascii=False, indent=2)+ if args.out_json:+ args.out_json.parent.mkdir(parents=True, exist_ok=True)+ args.out_json.write_text(text, encoding="utf-8")+ else:+ _ensure_stdout_payload_log().info("%s", text)+ return 0+++async def _async_main() -> int:+ parser = argparse.ArgumentParser(+ description="skill-gen-4-enterprise-doc scripts (SOP text, URL fetch).",+ )+ sub = parser.add_subparsers(dest="cmd", required=True)++ p_st = sub.add_parser(+ "sop-text",+ help="Extract plain text from an SOP file (same ingestion as parse_sop_file). No SOPStructure JSON.",+ )+ p_st.add_argument("--sop-file", type=Path, required=True)+ p_st.add_argument("--out-text", type=Path, default=None, help="Write UTF-8 text to this path.")+ p_st.add_argument("--print-raw-chars", action="store_true", help="Print character count only.")+ p_st.set_defaults(handler=_cmd_sop_text)++ p_uf = sub.add_parser("url-fetch", help="Fetch HTTP(S) page or WeChat article → text + metadata JSON.")+ p_uf.add_argument("--url", type=str, required=True)+ p_uf.add_argument("--out-json", type=Path, default=None)+ p_uf.set_defaults(handler=_cmd_url_fetch)++ args = parser.parse_args()+ handler = getattr(args, "handler", None)+ if handler is None:+ logger.error("internal error: missing handler")+ return 2+ return await handler(args)+++def main() -> int:+ logging.basicConfig(+ level=logging.INFO,+ format="%(asctime)s %(levelname)s %(name)s - %(message)s",+ )+ _ensure_skill_gen_on_path()+ return asyncio.run(_async_main())+++if __name__ == "__main__":+ raise SystemExit(main())