Compare commits

...

21 Commits

Author SHA1 Message Date
sunpeiyang.996
f13ff1b267 补充 skill.md
Change-Id: I54aca2613c8b7493e2b38144b350b34842ec006b
2026-07-24 16:32:26 +08:00
sunpeiyang.996
20cf972725 feat(docs): add local document authoring tools
Add local XML/Markdown parsing, profiling, conversion, and unique draft creation for docs workflows. Refresh authoring guidance and tests, and ignore generated lark-cli E2E reports.

Change-Id: I19cf93d576b6b2cb9ffa4cc4e1640126c95002f8
2026-07-24 16:32:20 +08:00
zhanghuanxu
4807283368 fix(slides): declare screenshot scope 2026-07-24 15:25:11 +08:00
ILUO
d2bb36591f fix/task search pagination (#2041)
* fix: send task search page token in query

* test: assert task search dry-run pagination contract
2026-07-24 14:28:54 +08:00
yballul-bytedance
5a54bc07db fix(base): classify +form-submit as high-risk-write (#1969)
Form submission writes and submits data through a public share link, an
irreversible action that should require explicit confirmation. Reclassify
the shortcut from write to high-risk-write so the runner's --yes gate fires
before execution, matching +form-delete and other high-risk base commands.

Update the lark-base skill docs (--yes on all examples, param table, tips)
and add tests pinning the confirmation gate (unit) and dry-run structure (e2e).

Co-authored-by: yballul-bytedance <273011618+yballul-bytedance@users.noreply.github.com>
2026-07-24 11:11:37 +08:00
BD-ZERO
a528b3cb69 feat(slides): add layout density lint for sparse/empty containers (#2022)
feat(slides): add layout density lint for sparse/empty containers

Extend the XML layout lint into a single release gate for Slides XML:

- Add blank_slide, sparse_container_content, and sparse_slide_content
  detection, using visibility- and coverage-aware heuristics (alpha
  filtering, image-overlay/layout-panel exemptions, similar-short-card
  grouping) to avoid flagging intentional whitespace or background
  panels
- Broaden out-of-canvas detection from table/chart/text-only to every
  element kind, with rotation-aware bounding boxes and geometry
  extraction for icon/line/polyline
- Restructure output to schema v2.0: every issue carries rule
  (id/name/comparison/threshold), measurement, related_objects, and
  hint; summary gains status/release_ready/screenshot_review_required
- Change CLI exit-code semantics so only errors block (exit 1);
  warning-only output still exits 0 to let downstream screenshot review
  proceed
- Harden XML attribute parsing (single/double-quoted and spaced
  attributes, self-closing tags no longer bleeding content into the
  next element) and fix edge cases surfaced during review
  (image-overlay coverage ratio, invisible container/panel exemptions,
  bbox_overlap measurement consistency, background-only slide bypass,
  invisible short-card peers)
- Update SKILL.md, validation-checklist.md, and troubleshooting.md to
  match the new gate; add regression tests for the new rules and fixes
2026-07-24 10:47:15 +08:00
huarenmin13
f0176af330 docs(base): clarify complete and partial updates (#1993)
* docs(base): clarify complete and partial updates

Consolidate the update rule introduced in #1879 and make the command-contract boundary explicit. Full-update commands must use trusted current configuration for the first actual request, while delta commands should send the smallest legal payload.

* docs(base): clarify full-update state preservation

Address review feedback by requiring unchanged writable configuration to remain intact, except when the requested update makes a setting inapplicable.

* docs(base): strengthen update contract guidance
2026-07-24 00:01:35 +08:00
R0bynZhu
715aa8d960 feat(slides): fill xml-schema-quick-ref gaps that forced XSD fallback (#2026)
From EVAL-07-22-02-53 (42 convos), agents fell back to the full XSD for:
- shape type enum + presetHandlers (rounded corners)
- polyline (bounding-box positioning, required border, connector type)
- table merged cells (colspan / rowspan)

Add compact coverage for each, sized to real usage (shape/polyline type
lists trimmed to what actually appears in generations). Chart gaps deferred.
2026-07-23 22:18:17 +08:00
ILUO
ebc0c53ab5 fix/task id handling (#2023)
* fix: validate task GUID inputs

* fix: make task updates self-confirming

* fix: confirm task completion state

* docs: clarify task ID workflow

* test: cover task ID dry runs

* fix: address task ID review feedback
2026-07-23 20:48:38 +08:00
fangshuyu-768
1e682bd97c fix(slides): normalize presentation flag aliases (#2032) 2026-07-23 18:43:30 +08:00
fangshuyu-768
70424c486c docs(skill): clarify scope handling for query expansion (#2030) 2026-07-23 18:35:44 +08:00
liangshuo-1
b8f56dbc0b feat(apps): support absolute and relative upload paths (#2005) 2026-07-23 17:52:49 +08:00
chenxingyang1019
c74d9b63fb feat(apps): validate +file-list --page-size against server (0, 200] range (#2007)
paas_storage AppFileListForOpenAPI rejects page_size > 200 at the inner
checkMaxKeys guard with ErrInvalidRequest("maxKeys not in range (0, 200]").
Previously the CLI forwarded any --page-size straight to the API, so
--page-size 500 produced an opaque server error round-trip.

Add a client-side Validate check bounding --page-size to [1, 200] (aligned
with the existing validateAppsPageSize precedent in the observability
commands): out-of-range values now fail fast with a typed validation error
and never hit the network. The server tolerates page_size <= 0 by defaulting
to 20, but the CLI default is already 20 and an explicit < 1 is a user error,
so we reject it for a clearer message, consistent with other list commands.

Update the flag description and the lark-apps-file skill reference to
document the 1..200 range, and cover the boundaries in unit tests.
2026-07-23 15:55:08 +08:00
91-enjoy
67015eef8e feat: introducing official card icon (#1973)
Card header icon documentation contained invalid tokens (e.g., mail_colorful, approve_colorful) that do not render, and icon guidance lacked precise token enumeration, causing LLM to guess or fabricate icon tokens. This PR replaces
examples with valid tokens and adds a definitive colorful icon reference table.
2026-07-23 11:01:14 +08:00
liangshuo-1
af8507ea8e chore: release v1.0.76 (#2016) 2026-07-22 23:36:33 +08:00
liangshuo-1
02c2ebcf7c chore: release v1.0.75 (#2014) 2026-07-22 22:29:15 +08:00
liangshuo-1
abf6f99d7e fix(slides): preserve raw XML output verbatim (#2013)
Keep --raw and file output byte-exact by returning the server response without XML reserialization.
2026-07-22 22:06:26 +08:00
tianyouskrrr
8ba910eb9f fix(slides): reindent xml-get output for readability (#1987)
The API always returns presentation/slide XML as a single unindented
line, which is unreadable for decks with many shapes (e.g. PPTX-imported
presentations). slides +xml-get now formats it on the surfaces meant for
a human or a line tool to read:

- --raw and --output reindent the XML with etree so each structural
  element (presentation/slide/shape/style/...) sits on its own line.
  Reformatting never recurses into schema-mixed text-bearing elements
  (p, span, strong, em, u, del, a, shadow, outline, chartTitle,
  chartSubTitle), so rich-text content stays exactly as parsed. CDATA
  sections and the schema's &#32;/&#9;/&#13;/&#10; whitespace character
  references (decimal, hex, and zero-padded) are preserved through the
  parse/write pass instead of being silently normalized away. There is
  no flag to disable this formatting.
- The default JSON envelope returns the server's XML verbatim: it is
  never parsed, so it stays a byte-exact copy of the API response, at
  no reformatting cost and with no failure mode on this path.
- If reformatting --raw/--output content fails (non-strict XML from the
  service), the command falls back to the original content, prints a
  warning to stderr, and reports pretty_printed: false in --output file
  metadata.

Adds github.com/beevik/etree as a direct dependency.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-22 21:08:29 +08:00
zgz2048
78bf126bb0 docs(base): align record write schema guidance (#2000)
* docs(base): align record write schema guidance

* docs(base): use canonical select field naming

* docs(base): simplify select option guidance
2026-07-22 20:54:54 +08:00
guokexin.02
4eefe32c1a ci: harden npm release publishing (#1918) 2026-07-22 20:53:43 +08:00
Yuxuan Zhao
8f6f8eb0fc test(e2e): declare request identities explicitly (#2004)
* test(e2e): declare request identities explicitly

* test(e2e): skip base workflow without bot credentials
2026-07-22 19:22:08 +08:00
145 changed files with 10931 additions and 2426 deletions

View File

@@ -99,6 +99,22 @@ jobs:
- name: Run tests
run: go test -v -race -count=1 -timeout=5m ./cmd/... ./internal/... ./shortcuts/... ./extension/...
windows-compat:
needs: fast-gate
runs-on: windows-latest
steps:
- uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd # v5
- uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
with:
go-version-file: go.mod
- uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6
with:
python-version: '3.x'
- name: Fetch meta data
run: python scripts/fetch_meta.py
- name: Run Windows compatibility tests
run: go test -count=1 -timeout=5m . ./shortcuts/doc/...
lint:
needs: fast-gate
runs-on: ubuntu-latest

View File

@@ -9,7 +9,40 @@ permissions:
contents: read
jobs:
goreleaser:
preflight:
runs-on: ubuntu-22.04
permissions:
contents: read
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
with:
fetch-depth: 0
- uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6
with:
node-version: '22.14.0'
- name: Validate tag and commit
env:
TAG: ${{ github.ref_name }}
run: |
set -euo pipefail
node scripts/release-preflight.js --tag "$TAG"
git fetch origin main
HEAD_SHA="$(git rev-parse --verify 'HEAD^{commit}')"
MAIN_SHA="$(git rev-parse --verify 'FETCH_HEAD^{commit}')"
TAG_SHA="$(git rev-parse --verify "refs/tags/${TAG}^{commit}")"
if [[ "$TAG_SHA" != "$HEAD_SHA" ]]; then
echo "Tag ${TAG} does not resolve to the checked-out HEAD commit." >&2
exit 1
fi
if ! git merge-base --is-ancestor "$HEAD_SHA" "$MAIN_SHA"; then
echo "Tag ${TAG} does not point to a commit contained in origin/main." >&2
exit 1
fi
build-release:
needs: preflight
runs-on: ubuntu-22.04
permissions:
contents: write
@@ -26,35 +59,79 @@ jobs:
with:
python-version: '3.x'
- uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6
with:
node-version: '22.14.0'
registry-url: 'https://registry.npmjs.org'
package-manager-cache: false
- name: Install pinned npm
run: npm install --global npm@11.16.0
- name: Run GoReleaser
uses: goreleaser/goreleaser-action@e435ccd777264be153ace6237001ef4d979d3a7a # v6
with:
version: '~> v2'
args: release --clean
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GITHUB_TOKEN: ${{ github.token }}
- name: Include release checksums
run: |
set -euo pipefail
test -s dist/checksums.txt
(cd dist && sha256sum --check checksums.txt)
cp dist/checksums.txt checksums.txt
- name: Collect release asset
run: |
set -euo pipefail
mkdir npm-publish-asset
cp dist/*.tar.gz dist/*.zip dist/checksums.txt npm-publish-asset/
- name: Upload release asset
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: npm-publish-asset-${{ github.run_id }}
path: npm-publish-asset/
if-no-files-found: error
overwrite: true
publish-npm:
needs: goreleaser
needs: build-release
runs-on: ubuntu-22.04
environment: npm-production
permissions:
contents: read
id-token: write
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
- uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6
with:
node-version: '20'
node-version: '22.14.0'
registry-url: 'https://registry.npmjs.org'
package-manager-cache: false
- name: Download checksums from release
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Install pinned npm
run: npm install --global npm@11.16.0
- name: Download release asset
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
with:
name: npm-publish-asset-${{ github.run_id }}
path: npm-publish-asset
- name: Verify npm publish asset
run: |
set -euo pipefail
TAG="${GITHUB_REF_NAME}"
gh release download "${TAG}" --pattern checksums.txt --dir .
test -s checksums.txt || { echo "checksums.txt missing or empty for ${TAG}"; exit 1; }
(cd npm-publish-asset && sha256sum --check checksums.txt)
cp npm-publish-asset/checksums.txt checksums.txt
PACK_JSON="$(npm pack --ignore-scripts --json)"
PACK_FILE="$(node -e 'const p=JSON.parse(process.argv[1]); if(p.length!==1 || !p[0].filename) process.exit(1); process.stdout.write(p[0].filename)' "$PACK_JSON")"
test -s "$PACK_FILE"
tar -tzf "$PACK_FILE" | grep -qx 'package/checksums.txt'
rm "$PACK_FILE"
- name: Publish to npm
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: npm publish --access public

1
.gitignore vendored
View File

@@ -42,6 +42,7 @@ tests/mail/reports/
# Generated / test artifacts
.hammer/
.lark-cli-e2e-test/reports/
.lark-slides/
/notes/
/minutes/

View File

@@ -2,6 +2,36 @@
All notable changes to this project will be documented in this file.
## [v1.0.75] - 2026-07-22
### Features
- add okr single create shortcut & skill text opti (#1941)
- **calendar**: auto-add bot self as attendee and note user-only search (#1991)
### Bug Fixes
- **base**: improve table shortcut behavior & guidance (#1803)
- issue#1935 & whiteboard shortcut reformat (#1980)
- remove legacy shortcut (#1997)
- **e2e**: inject shared credentials by identity (#1995)
### Documentation
- **skill**: describe html5 block xml usage (#1380)
- clarify fetch metadata and user cites (#1981)
- add topic move collector workflow (#1473)
- update lark doc HTML size limit (#2001)
- **base**: align record write schema guidance (#2000)
### Tests
- **e2e**: declare request identities explicitly (#2004)
### Misc
- harden npm release publishing (#1918)
## [v1.0.74] - 2026-07-21
### Features
@@ -1608,6 +1638,7 @@ Bundled AI agent skills for intelligent assistance:
- Bilingual documentation (English & Chinese).
- CI/CD pipelines: linting, testing, coverage reporting, and automated releases.
[v1.0.75]: https://github.com/larksuite/cli/releases/tag/v1.0.75
[v1.0.74]: https://github.com/larksuite/cli/releases/tag/v1.0.74
[v1.0.73]: https://github.com/larksuite/cli/releases/tag/v1.0.73
[v1.0.72]: https://github.com/larksuite/cli/releases/tag/v1.0.72

View File

@@ -51,7 +51,7 @@ script-test:
bash scripts/resolve-changed-from.test.sh
bash scripts/ci-workflow.test.sh
bash scripts/semantic-review-workflow.test.sh
$(NODE) --test scripts/e2e_domains.test.js scripts/fetch_e2e_tat.test.js scripts/semantic-review-verify-artifact.test.js scripts/pr-quality-summary.test.js scripts/semantic-review-publish.test.js scripts/ci-quality-summary-publish.test.js
$(NODE) --test scripts/e2e_domains.test.js scripts/fetch_e2e_tat.test.js scripts/install.test.js scripts/release-preflight.test.js scripts/semantic-review-verify-artifact.test.js scripts/pr-quality-summary.test.js scripts/semantic-review-publish.test.js scripts/ci-quality-summary-publish.test.js
# ./extension/... keeps the public plugin SDK in the default test matrix.
unit-test: fetch_meta

105
cmd/build_bench_test.go Normal file
View File

@@ -0,0 +1,105 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package cmd
import (
"context"
"runtime"
"testing"
"github.com/larksuite/cli/internal/cmdutil"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
// BenchmarkBuild_Default measures the per-Build cost for the default
// configuration (service commands + shortcuts + plugins + strict mode).
// This is the hot-path baseline for repeated Build invocations.
func BenchmarkBuild_Default(b *testing.B) {
// Warm one-time caches first
_ = Build(context.Background(), cmdutil.InvocationContext{})
runtime.GC()
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
_ = Build(context.Background(), cmdutil.InvocationContext{})
}
}
// BenchmarkBuild_WithoutServiceCommands measures the Build cost without
// service command registration. The delta from Default gives the
// service-command registration cost.
func BenchmarkBuild_WithoutServiceCommands(b *testing.B) {
_ = Build(context.Background(), cmdutil.InvocationContext{}, WithoutServiceCommands())
runtime.GC()
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
_ = Build(context.Background(), cmdutil.InvocationContext{}, WithoutServiceCommands())
}
}
// BenchmarkBuild_WithoutPlugins measures the Build cost without plugins.
// The delta from Default gives the plugin + policy + hook cost.
func BenchmarkBuild_WithoutPlugins(b *testing.B) {
_ = Build(context.Background(), cmdutil.InvocationContext{}, WithoutPlugins())
runtime.GC()
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
_ = Build(context.Background(), cmdutil.InvocationContext{}, WithoutPlugins())
}
}
// BenchmarkBuild_WithoutServiceAndPlugins measures the Build cost with
// neither service commands nor plugins. This isolates the base cost
// (root command + builtins + shortcuts).
func BenchmarkBuild_WithoutServiceAndPlugins(b *testing.B) {
_ = Build(context.Background(), cmdutil.InvocationContext{}, WithoutServiceCommands(), WithoutPlugins())
runtime.GC()
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
_ = Build(context.Background(), cmdutil.InvocationContext{}, WithoutServiceCommands(), WithoutPlugins())
}
}
// TestBuild_CommandTreeStats counts the total number of commands,
// runnable commands, and flags in the default build. This gives us
// the scale of the command tree to reason about optimization targets.
func TestBuild_CommandTreeStats(t *testing.T) {
root := Build(context.Background(), cmdutil.InvocationContext{}, WithoutPlugins())
var totalCmds, runnableCmds, groupCmds int
var totalFlags int
var walk func(cmd *cobra.Command)
walk = func(cmd *cobra.Command) {
totalCmds++
if cmd.RunE != nil || cmd.Run != nil {
runnableCmds++
} else {
groupCmds++
}
if cmd.Flags() != nil {
cmd.Flags().VisitAll(func(f *pflag.Flag) {
totalFlags++
})
}
for _, child := range cmd.Commands() {
walk(child)
}
}
walk(root)
t.Logf("Command tree stats:")
t.Logf(" Total commands: %d", totalCmds)
t.Logf(" Runnable commands: %d", runnableCmds)
t.Logf(" Group commands: %d", groupCmds)
t.Logf(" Total flags: %d", totalFlags)
}

View File

@@ -42,6 +42,15 @@ type FileIO interface {
Save(path string, opts SaveOptions, body io.Reader) (SaveResult, error)
}
// TempDirFileCreator is an optional FileIO capability for atomically creating
// a unique directory and an empty named file inside it. The directory pattern
// follows os.MkdirTemp semantics: the last '*' is replaced with a random
// value. Implementations return a relative file path that can be passed back
// to FileIO.
type TempDirFileCreator interface {
CreateTempDirFile(directoryPattern, fileName string) (string, error)
}
// FileInfo is a minimal subset of os.FileInfo covering actual CLI usage.
// os.FileInfo satisfies this interface.
type FileInfo interface {

1
go.mod
View File

@@ -18,6 +18,7 @@ require (
github.com/spf13/pflag v1.0.9
github.com/stretchr/testify v1.11.1
github.com/tidwall/gjson v1.18.0
github.com/yuin/goldmark v1.7.16
github.com/zalando/go-keyring v0.2.8
golang.org/x/net v0.33.0
golang.org/x/sync v0.15.0

2
go.sum
View File

@@ -131,6 +131,8 @@ github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavM
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.7.16 h1:n+CJdUxaFMiDUNnWC3dMWCIQJSkxH4uz3ZwQBkAlVNE=
github.com/yuin/goldmark v1.7.16/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg=
github.com/zalando/go-keyring v0.2.8 h1:6sD/Ucpl7jNq10rM2pgqTs0sZ9V3qMrqfIIy5YPccHs=
github.com/zalando/go-keyring v0.2.8/go.mod h1:tsMo+VpRq5NGyKfxoBVjCuMrG47yj8cmakZDO5QGii0=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=

View File

@@ -0,0 +1,36 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package cmdutil
import (
"io/fs"
"github.com/larksuite/cli/extension/fileio"
"github.com/larksuite/cli/internal/validate"
"github.com/larksuite/cli/internal/vfs"
)
// StatLocalFile returns metadata for a path in the process filesystem namespace.
// It is intended for advisory validation; callers must validate the opened file
// again before using its contents.
func StatLocalFile(path string) (fs.FileInfo, error) {
localPath, err := validate.LocalInputPath(path)
if err != nil {
return nil, &fileio.PathValidationError{Err: err}
}
return vfs.Stat(localPath)
}
// OpenLocalFile opens a path in the process filesystem namespace.
// Absolute and relative paths are accepted. It is the shared replacement for
// direct os.Open/os.ReadFile use in commands that intentionally read local
// paths outside the workspace sandbox. Callers inspect the returned descriptor
// before reading so validation and use apply to the same opened file.
func OpenLocalFile(path string) (fs.File, error) {
localPath, err := validate.LocalInputPath(path)
if err != nil {
return nil, &fileio.PathValidationError{Err: err}
}
return vfs.Open(localPath)
}

View File

@@ -0,0 +1,96 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package cmdutil
import (
"errors"
"io"
"io/fs"
"os"
"path/filepath"
"testing"
"github.com/larksuite/cli/extension/fileio"
"github.com/larksuite/cli/internal/vfs"
)
func TestOpenLocalFile_AcceptsAbsoluteAndParentRelativePaths(t *testing.T) {
root := t.TempDir()
workDir := filepath.Join(root, "work")
if err := os.Mkdir(workDir, 0o755); err != nil {
t.Fatal(err)
}
path := filepath.Join(root, "input.txt")
if err := os.WriteFile(path, []byte("content"), 0o600); err != nil {
t.Fatal(err)
}
TestChdir(t, workDir)
for _, input := range []string{path, filepath.Join("..", "input.txt")} {
f, err := OpenLocalFile(input)
if err != nil {
t.Fatalf("OpenLocalFile(%q) error = %v", input, err)
}
got, readErr := io.ReadAll(f)
closeErr := f.Close()
if readErr != nil || closeErr != nil || string(got) != "content" {
t.Fatalf("OpenLocalFile(%q) content=%q read=%v close=%v", input, got, readErr, closeErr)
}
}
}
func TestOpenLocalFile_RejectsInvalidInput(t *testing.T) {
if _, err := OpenLocalFile("input\n.txt"); !errors.Is(err, fileio.ErrPathValidation) {
t.Fatalf("OpenLocalFile() error = %v, want ErrPathValidation", err)
}
}
func TestStatLocalFile_ReturnsMetadata(t *testing.T) {
info, err := StatLocalFile(t.TempDir())
if err != nil {
t.Fatalf("StatLocalFile() error = %v", err)
}
if !info.IsDir() {
t.Fatalf("StatLocalFile() mode = %v, want directory", info.Mode())
}
}
func TestOpenLocalFile_DoesNotStatBeforeOpen(t *testing.T) {
path := filepath.Join(t.TempDir(), "input.txt")
if err := os.WriteFile(path, []byte("content"), 0o600); err != nil {
t.Fatal(err)
}
previous := vfs.DefaultFS
counting := &countingLocalFileFS{FS: previous}
vfs.DefaultFS = counting
t.Cleanup(func() { vfs.DefaultFS = previous })
f, err := OpenLocalFile(path)
if err != nil {
t.Fatalf("OpenLocalFile() error = %v", err)
}
if err := f.Close(); err != nil {
t.Fatal(err)
}
if counting.openCalls != 1 || counting.statCalls != 0 {
t.Fatalf("OpenLocalFile() calls: Open=%d Stat=%d, want Open=1 Stat=0", counting.openCalls, counting.statCalls)
}
}
type countingLocalFileFS struct {
vfs.FS
openCalls int
statCalls int
}
func (f *countingLocalFileFS) Open(name string) (*os.File, error) {
f.openCalls++
return f.FS.Open(name)
}
func (f *countingLocalFileFS) Stat(name string) (fs.FileInfo, error) {
f.statCalls++
return f.FS.Stat(name)
}

View File

@@ -17,6 +17,13 @@ func SafeInputPath(path string) (string, error) {
return localfileio.SafeInputPath(path)
}
// LocalInputPath validates a local input path without restricting it to the
// current working directory. It delegates to localfileio.LocalInputPath so
// command validation and shared local-file readers use one policy.
func LocalInputPath(path string) (string, error) {
return localfileio.LocalInputPath(path)
}
// SafeEnvDirPath validates an environment-provided application directory path.
// Delegates to localfileio.SafeEnvDirPath.
func SafeEnvDirPath(path, envName string) (string, error) {

View File

@@ -211,6 +211,18 @@ func TestSafeLocalFlagPath(t *testing.T) {
}
}
func TestLocalInputPath_AllowsLocalPathsAndRejectsUnsafeCharacters(t *testing.T) {
for _, path := range []string{"/tmp/report.pdf", "../report.pdf"} {
got, err := LocalInputPath(path)
if err != nil || got != path {
t.Fatalf("LocalInputPath(%q) = %q, %v; want unchanged path", path, got, err)
}
}
if _, err := LocalInputPath("report\n.pdf"); err == nil {
t.Fatal("LocalInputPath() unexpectedly accepted a control character")
}
}
func TestSafeUploadPath_AllowsTempFileAbsolutePath(t *testing.T) {
// GIVEN: a real temp file (absolute path under os.TempDir())
f, err := os.CreateTemp("", "upload-test-*.bin")

View File

@@ -5,10 +5,14 @@ package localfileio
import (
"context"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/larksuite/cli/extension/fileio"
"github.com/larksuite/cli/internal/charcheck"
"github.com/larksuite/cli/internal/vfs"
)
@@ -30,6 +34,8 @@ func init() {
// and atomic writes are handled internally.
type LocalFileIO struct{}
var _ fileio.TempDirFileCreator = (*LocalFileIO)(nil)
// Open opens a local file for reading after validating the path.
func (l *LocalFileIO) Open(name string) (fileio.File, error) {
safePath, err := SafeInputPath(name)
@@ -62,6 +68,46 @@ func (l *LocalFileIO) ResolvePath(path string) (string, error) {
return resolved, nil
}
// CreateTempDirFile atomically creates a unique directory in the current
// working directory, then creates the requested empty file inside it.
func (l *LocalFileIO) CreateTempDirFile(directoryPattern, fileName string) (string, error) {
if err := validateTempDirectoryPattern(directoryPattern); err != nil {
return "", &fileio.PathValidationError{Err: err}
}
if err := validateTempFileName(fileName); err != nil {
return "", &fileio.PathValidationError{Err: err}
}
tempDir, err := vfs.MkdirTemp(".", directoryPattern)
if err != nil {
return "", &fileio.MkdirError{Err: err}
}
path := filepath.Join(tempDir, fileName)
tempFile, err := vfs.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
if err != nil {
_ = vfs.RemoveAll(tempDir)
return "", &fileio.WriteError{Err: err}
}
if err := tempFile.Close(); err != nil {
_ = vfs.RemoveAll(tempDir)
return "", &fileio.WriteError{Err: fmt.Errorf("close temporary file: %w", err)}
}
return filepath.Join(filepath.Base(tempDir), fileName), nil
}
func validateTempDirectoryPattern(pattern string) error {
if strings.TrimSpace(pattern) == "" || strings.ContainsAny(pattern, `/\\`) || strings.Count(pattern, "*") != 1 {
return fmt.Errorf("temporary directory pattern must be one non-empty path component containing exactly one '*'")
}
return charcheck.RejectControlChars(pattern, "temporary directory pattern")
}
func validateTempFileName(fileName string) error {
if strings.TrimSpace(fileName) == "" || fileName != filepath.Base(fileName) || strings.ContainsAny(fileName, "/\\\t\r\n") {
return fmt.Errorf("temporary file name must be one non-empty path component")
}
return charcheck.RejectControlChars(fileName, "temporary file name")
}
// Save writes body to path atomically after validating the output path.
// Parent directories are created as needed. The body is streamed directly
// to a temp file and renamed, avoiding full in-memory buffering.

View File

@@ -4,10 +4,12 @@
package localfileio
import (
"errors"
"io"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"github.com/larksuite/cli/extension/fileio"
@@ -250,6 +252,81 @@ func TestLocalFileIO_ResolvePath_RejectsAbsolute(t *testing.T) {
}
}
func TestLocalFileIO_CreateTempDirFileIsUniqueUnderConcurrency(t *testing.T) {
dir := t.TempDir()
testChdir(t, dir)
const count = 32
type result struct {
path string
err error
}
results := make(chan result, count)
var wg sync.WaitGroup
for i := 0; i < count; i++ {
wg.Add(1)
go func() {
defer wg.Done()
path, err := (&LocalFileIO{}).CreateTempDirFile("川西_*_folder", "川西.xml")
results <- result{path: path, err: err}
}()
}
wg.Wait()
close(results)
seen := make(map[string]struct{}, count)
for result := range results {
if result.err != nil {
t.Fatalf("CreateTempDirFile failed: %v", result.err)
}
directory := filepath.Dir(result.path)
if filepath.Base(result.path) != "川西.xml" || filepath.Base(directory) != directory ||
!strings.HasPrefix(directory, "川西_") || !strings.HasSuffix(directory, "_folder") {
t.Fatalf("CreateTempDirFile path = %q, want 川西_<random>_folder/川西.xml", result.path)
}
if _, ok := seen[directory]; ok {
t.Fatalf("CreateTempDirFile returned duplicate directory %q", directory)
}
seen[directory] = struct{}{}
info, err := os.Stat(result.path)
if err != nil {
t.Fatalf("stat temporary file %q: %v", result.path, err)
}
if info.Size() != 0 {
t.Fatalf("temporary file %q size = %d, want 0", result.path, info.Size())
}
}
if len(seen) != count {
t.Fatalf("unique temporary files = %d, want %d", len(seen), count)
}
}
func TestLocalFileIO_CreateTempDirFileRejectsUnsafeComponents(t *testing.T) {
dir := t.TempDir()
testChdir(t, dir)
fio := &LocalFileIO{}
for _, test := range []struct {
pattern string
fileName string
}{
{pattern: "../lark-doc-*", fileName: "draft.xml"},
{pattern: "lark-doc-*", fileName: "../draft.xml"},
{pattern: "lark-doc-*", fileName: `folder\draft.xml`},
} {
if _, err := fio.CreateTempDirFile(test.pattern, test.fileName); !errors.Is(err, fileio.ErrPathValidation) {
t.Errorf("CreateTempDirFile(%q, %q) error = %v, want path validation", test.pattern, test.fileName, err)
}
}
entries, err := os.ReadDir(dir)
if err != nil {
t.Fatalf("read work directory: %v", err)
}
if len(entries) != 0 {
t.Fatalf("invalid inputs created files: %+v", entries)
}
}
// ── Error message consistency ──
func TestLocalFileIO_ErrorMessages_ContainCorrectFlagName(t *testing.T) {

View File

@@ -7,6 +7,7 @@ import (
"fmt"
"path/filepath"
"strings"
"unicode"
"github.com/larksuite/cli/internal/charcheck"
"github.com/larksuite/cli/internal/vfs"
@@ -22,6 +23,32 @@ func SafeInputPath(path string) (string, error) {
return safePath(path, "--file")
}
// LocalInputPath validates an input path in the process local filesystem
// namespace. It intentionally does not impose cwd containment or canonicalize
// the path: absolute paths, parent-relative paths, and symlink traversal retain
// their normal OS semantics. Character validation remains mandatory because
// paths are user-controlled and may appear in errors or progress output.
func LocalInputPath(path string) (string, error) {
if strings.TrimSpace(path) == "" {
return "", fmt.Errorf("local input path must not be empty")
}
if strings.IndexFunc(path, unicode.IsControl) >= 0 {
return "", fmt.Errorf("local input path must not contain control characters")
}
if err := charcheck.RejectControlChars(path, "local input path"); err != nil {
return "", err
}
if err := validateLocalInputPlatform(path); err != nil {
return "", err
}
return path, nil
}
func isWindowsNonLocalNamespace(path string) bool {
normalized := strings.ReplaceAll(path, "/", `\`)
return strings.HasPrefix(normalized, `\\`) || strings.HasPrefix(normalized, `\??\`)
}
// SafeLocalFlagPath validates a flag value as a local file path.
// Empty values and http/https URLs are returned unchanged without validation.
func SafeLocalFlagPath(flagName, value string) (string, error) {
@@ -29,7 +56,7 @@ func SafeLocalFlagPath(flagName, value string) (string, error) {
return value, nil
}
if _, err := SafeInputPath(value); err != nil {
return "", fmt.Errorf("%s: %v", flagName, err)
return "", fmt.Errorf("%s: %w", flagName, err)
}
return value, nil
}

View File

@@ -0,0 +1,8 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
//go:build !windows
package localfileio
func validateLocalInputPlatform(string) error { return nil }

View File

@@ -0,0 +1,33 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
//go:build windows
package localfileio
import (
"fmt"
"path/filepath"
"strings"
)
func validateLocalInputPlatform(path string) error {
if isWindowsNonLocalNamespace(path) {
return fmt.Errorf("local input path must not use a Windows network or device namespace")
}
cleaned := filepath.Clean(path)
volume := filepath.VolumeName(cleaned)
remainder := strings.TrimLeft(cleaned[len(volume):], `\/`)
for _, component := range strings.FieldsFunc(remainder, func(r rune) bool {
return r == '\\' || r == '/'
}) {
if component == "." || component == ".." {
continue
}
if !filepath.IsLocal(component) {
return fmt.Errorf("local input path contains a reserved Windows path component %q", component)
}
}
return nil
}

View File

@@ -0,0 +1,27 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
//go:build windows
package localfileio
import "testing"
func TestLocalInputPath_RejectsWindowsNetworkDeviceAndReservedPaths(t *testing.T) {
for _, input := range []string{
`\\server\share\report.pdf`,
`//server/share/report.pdf`,
`\\.\pipe\upload`,
`\\?\C:\Users\agent\report.pdf`,
`\\?\UNC\server\share\report.pdf`,
`\??\C:\Users\agent\report.pdf`,
`C:\Users\agent\NUL.txt`,
`CON`,
} {
t.Run(input, func(t *testing.T) {
if _, err := LocalInputPath(input); err == nil {
t.Fatalf("LocalInputPath(%q) unexpectedly succeeded", input)
}
})
}
}

View File

@@ -4,6 +4,7 @@
package localfileio
import (
"fmt"
"os"
"path/filepath"
"strings"
@@ -71,6 +72,72 @@ func TestSafeOutputPath_RejectsPathTraversalAndDangerousInput(t *testing.T) {
}
}
func TestLocalInputPath_AllowsLocalNamespaceWithoutRewriting(t *testing.T) {
for _, input := range []string{
"/tmp/report.pdf",
"../outside/report.pdf",
"./report.pdf",
"nested/../report.pdf",
`C:\Users\agent\report.pdf`,
"报告.pdf",
} {
t.Run(input, func(t *testing.T) {
got, err := LocalInputPath(input)
if err != nil {
t.Fatalf("LocalInputPath(%q) error = %v", input, err)
}
if got != input {
t.Fatalf("LocalInputPath(%q) = %q, want path preserved verbatim", input, got)
}
})
}
}
func TestWindowsNonLocalNamespace(t *testing.T) {
for _, input := range []string{
`\\server\share\report.pdf`,
`//server/share/report.pdf`,
`\\.\pipe\upload`,
`\\?\C:\Users\agent\report.pdf`,
`\\?\UNC\server\share\report.pdf`,
`\??\C:\Users\agent\report.pdf`,
} {
if !isWindowsNonLocalNamespace(input) {
t.Errorf("isWindowsNonLocalNamespace(%q) = false, want true", input)
}
}
for _, input := range []string{
`C:\Users\agent\report.pdf`,
`C:/Users/agent/report.pdf`,
`..\outside\report.pdf`,
`.\report.pdf`,
} {
if isWindowsNonLocalNamespace(input) {
t.Errorf("isWindowsNonLocalNamespace(%q) = true, want false", input)
}
}
}
func TestLocalInputPath_RejectsEmptyControlAndDangerousUnicode(t *testing.T) {
for _, input := range []string{
"",
" ",
"file\x00.txt",
"file\tname.txt",
"file\nname.txt",
"file\rname.txt",
"file\u202Ename.txt",
"file\u200Bname.txt",
} {
t.Run(fmt.Sprintf("%q", input), func(t *testing.T) {
if _, err := LocalInputPath(input); err == nil {
t.Fatalf("LocalInputPath(%q) unexpectedly succeeded", input)
}
})
}
}
func TestSafeOutputPath_ReturnsCanonicalAbsolutePath(t *testing.T) {
// GIVEN: a clean temp directory as CWD
dir := t.TempDir()

7
package-lock.json generated
View File

@@ -1,15 +1,16 @@
{
"name": "@larksuite/cli",
"version": "1.0.11",
"version": "1.0.76",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@larksuite/cli",
"version": "1.0.11",
"version": "1.0.76",
"cpu": [
"x64",
"arm64"
"arm64",
"riscv64"
],
"hasInstallScript": true,
"license": "MIT",

View File

@@ -1,12 +1,13 @@
{
"name": "@larksuite/cli",
"version": "1.0.74",
"version": "1.0.76",
"description": "The official CLI for Lark/Feishu open platform",
"bin": {
"lark-cli": "scripts/run.js"
},
"scripts": {
"postinstall": "node scripts/install.js"
"postinstall": "node scripts/install.js",
"release:check": "node scripts/release-preflight.js"
},
"os": [
"darwin",

View File

@@ -265,10 +265,7 @@ function getExpectedChecksum(archiveName, checksumsDir) {
const checksumsPath = path.join(dir, "checksums.txt");
if (!fs.existsSync(checksumsPath)) {
console.error(
"[WARN] checksums.txt not found, skipping checksum verification"
);
return null;
throw new Error(`[SECURITY] checksums.txt not found at ${checksumsPath}`);
}
const content = fs.readFileSync(checksumsPath, "utf8");
@@ -286,7 +283,14 @@ function getExpectedChecksum(archiveName, checksumsDir) {
}
function verifyChecksum(archivePath, expectedHash) {
if (expectedHash === null) return;
if (typeof expectedHash !== "string" || expectedHash.length === 0) {
throw new Error("[SECURITY] Expected checksum is missing or invalid");
}
if (!/^[0-9a-f]{64}$/i.test(expectedHash)) {
throw new Error(
"[SECURITY] Expected checksum must be a 64-character hexadecimal SHA-256 digest"
);
}
// Stream the file to avoid loading the entire archive into memory.
// Archives can be 10-100MB; streaming keeps RSS constant.

View File

@@ -52,11 +52,12 @@ describe("getExpectedChecksum", () => {
);
});
it("returns null when checksums.txt does not exist", () => {
it("throws [SECURITY]-prefixed Error when checksums.txt does not exist", () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "checksum-test-"));
// No checksums.txt in dir
const result = getExpectedChecksum("anything.tar.gz", dir);
assert.equal(result, null);
assert.throws(
() => getExpectedChecksum("anything.tar.gz", dir),
{ message: /^\[SECURITY\] checksums\.txt not found/ }
);
});
it("skips malformed lines and still finds valid entry", () => {
@@ -106,7 +107,7 @@ describe("verifyChecksum", () => {
verifyChecksum(filePath, hash);
});
it("matches case-insensitively", () => {
it("accepts a valid uppercase 64-character hex hash", () => {
const content = "case test";
const filePath = makeTmpFile(content);
const hash = sha256(content).toUpperCase();
@@ -114,6 +115,40 @@ describe("verifyChecksum", () => {
verifyChecksum(filePath, hash);
});
for (const [name, expectedHash] of [
["null", null],
["empty", ""],
["non-string", 123],
]) {
it(`throws [SECURITY]-prefixed Error for ${name} expected hash`, () => {
const filePath = makeTmpFile("real content");
assert.throws(
() => verifyChecksum(filePath, expectedHash),
(err) => {
assert.match(err.message, /^\[SECURITY\]/);
assert.match(err.message, /Expected checksum is missing or invalid/);
return true;
}
);
});
}
it("throws [SECURITY] format Error for an incorrectly sized hash", () => {
const filePath = makeTmpFile("real content");
assert.throws(
() => verifyChecksum(filePath, "abc123"),
{ message: /^\[SECURITY\] Expected checksum must be a 64-character hexadecimal SHA-256 digest$/ }
);
});
it("throws [SECURITY] format Error for a non-hex hash", () => {
const filePath = makeTmpFile("real content");
assert.throws(
() => verifyChecksum(filePath, "g".repeat(64)),
{ message: /^\[SECURITY\] Expected checksum must be a 64-character hexadecimal SHA-256 digest$/ }
);
});
it("throws [SECURITY]-prefixed Error on mismatch", () => {
const filePath = makeTmpFile("real content");
assert.throws(

View File

@@ -0,0 +1,108 @@
#!/usr/bin/env node
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
const fs = require("node:fs");
const path = require("node:path");
const STABLE_VERSION_PATTERN = /^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$/;
function isStableVersion(value) {
return typeof value === "string" && STABLE_VERSION_PATTERN.test(value);
}
function releaseError(message, observed, hint) {
return { ok: false, error: { type: "release_preflight", message, observed, hint } };
}
function validateReleasePreflight(packageJson, packageLockJson, tag) {
const packageVersion = packageJson?.version;
const lockVersion = packageLockJson?.version;
const lockRootVersion = packageLockJson?.packages?.[""]?.version;
const observed = {
packageVersion: packageVersion ?? null,
lockVersion: lockVersion ?? null,
lockRootVersion: lockRootVersion ?? null,
tagVersion: null,
};
for (const [field, value] of [
["package.json.version", packageVersion],
["package-lock.json.version", lockVersion],
['package-lock.json.packages[""].version', lockRootVersion],
]) {
if (!isStableVersion(value)) {
return releaseError(
`${field} must be a stable release version in X.Y.Z form`,
observed,
"Use the same stable X.Y.Z version in all package fields; prerelease and build metadata are not allowed for production releases.",
);
}
}
if (packageVersion !== lockVersion || packageVersion !== lockRootVersion) {
return releaseError(
"Package version fields do not match",
observed,
"Synchronize package.json.version and both package-lock.json version fields.",
);
}
if (tag === undefined) {
return { ok: true, data: observed };
}
if (typeof tag !== "string" || !tag.startsWith("v") || !isStableVersion(tag.slice(1))) {
return releaseError(
"--tag must use the stable release form vX.Y.Z",
{ ...observed, tag },
`Use --tag v${packageVersion}; prerelease and build metadata are not allowed for production releases.`,
);
}
const tagVersion = tag.slice(1);
if (tagVersion !== packageVersion) {
return releaseError(
"Tag version does not match the package version",
{ ...observed, tagVersion, tag },
`Use --tag v${packageVersion}.`,
);
}
return { ok: true, data: { ...observed, tagVersion } };
}
function writeResult(result) {
(result.ok ? process.stdout : process.stderr).write(`${JSON.stringify(result)}\n`);
if (!result.ok) process.exitCode = 1;
}
function main() {
const args = process.argv.slice(2);
let tag;
if (args.length === 2 && args[0] === "--tag") {
tag = args[1];
} else if (args.length !== 0) {
writeResult(releaseError(
"Expected no arguments or --tag vX.Y.Z",
{ arguments: args },
"Run release:check without arguments or pass exactly one --tag value.",
));
return;
}
const repoRoot = path.resolve(__dirname, "..");
try {
const packageJson = JSON.parse(fs.readFileSync(path.join(repoRoot, "package.json"), "utf8"));
const packageLockJson = JSON.parse(fs.readFileSync(path.join(repoRoot, "package-lock.json"), "utf8"));
writeResult(validateReleasePreflight(packageJson, packageLockJson, tag));
} catch (error) {
writeResult(releaseError(
"Could not read release package metadata",
{ reason: error.message },
"Ensure package.json and package-lock.json exist and contain valid JSON.",
));
}
}
module.exports = { validateReleasePreflight };
if (require.main === module) main();

View File

@@ -0,0 +1,66 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
const assert = require("node:assert/strict");
const { describe, it } = require("node:test");
const { validateReleasePreflight } = require("./release-preflight");
function metadata(version = "1.2.3") {
return {
packageJson: { version },
packageLockJson: {
version,
packages: { "": { version } },
},
};
}
function assertRejected(result) {
assert.equal(result.ok, false);
assert.equal(result.error.type, "release_preflight");
assert.equal(typeof result.error.message, "string");
}
describe("validateReleasePreflight", () => {
it("accepts matching stable package, lock, and tag versions", () => {
const { packageJson, packageLockJson } = metadata();
assert.deepEqual(
validateReleasePreflight(packageJson, packageLockJson, "v1.2.3"),
{
ok: true,
data: {
packageVersion: "1.2.3",
lockVersion: "1.2.3",
lockRootVersion: "1.2.3",
tagVersion: "1.2.3",
},
},
);
});
it("rejects non-stable or inconsistent package metadata", () => {
const prerelease = metadata("1.2.3-beta.1");
const topLevelMismatch = metadata();
topLevelMismatch.packageLockJson.version = "1.2.4";
const rootMismatch = metadata();
rootMismatch.packageLockJson.packages[""].version = "1.2.4";
for (const { packageJson, packageLockJson } of [
prerelease,
topLevelMismatch,
rootMismatch,
]) {
assertRejected(validateReleasePreflight(packageJson, packageLockJson));
}
});
it("rejects an invalid or mismatched release tag", () => {
const { packageJson, packageLockJson } = metadata();
for (const tag of ["1.2.3", "v1.2.3-beta.1", "v1.2.4"]) {
assertRejected(validateReleasePreflight(packageJson, packageLockJson, tag));
}
});
});

View File

@@ -3,49 +3,48 @@ set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
cd "${REPO_ROOT}"
# Read version from package.json
VERSION=$(node -p "require('${REPO_ROOT}/package.json').version")
if [ -z "$VERSION" ]; then
echo "Error: could not read version from package.json" >&2
exit 1
fi
VERSION=$(node -p "require('./package.json').version")
TAG="v${VERSION}"
node "${SCRIPT_DIR}/release-preflight.js" --tag "${TAG}"
echo "Version: ${VERSION}"
echo "Tag: ${TAG}"
# Check if tag already exists locally
if git rev-parse "$TAG" >/dev/null 2>&1; then
echo "Tag ${TAG} already exists locally, skipping."
exit 0
fi
# Check if tag already exists on remote
if git ls-remote --tags origin "$TAG" | grep -q "$TAG"; then
echo "Tag ${TAG} already exists on remote, skipping."
exit 0
fi
# Ensure package.json changes are committed before tagging
if git diff --name-only | grep -q 'package.json' || git diff --cached --name-only | grep -q 'package.json'; then
echo "Error: package.json has uncommitted changes. Please commit before tagging." >&2
CURRENT_BRANCH=$(git branch --show-current)
if [ "${CURRENT_BRANCH}" != "main" ]; then
echo "Error: releases must be tagged from main; current branch is '${CURRENT_BRANCH}'." >&2
exit 1
fi
# Ensure current branch is pushed to remote before tagging
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)
LOCAL_SHA=$(git rev-parse HEAD)
REMOTE_SHA=$(git rev-parse "origin/${CURRENT_BRANCH}" 2>/dev/null || echo "")
if [ "$LOCAL_SHA" != "$REMOTE_SHA" ]; then
echo "Error: local branch '${CURRENT_BRANCH}' is not in sync with remote. Please push your commits first." >&2
if ! git diff --quiet HEAD -- package.json package-lock.json; then
echo "Error: package.json or package-lock.json has uncommitted changes. Please commit them before tagging." >&2
exit 1
fi
# Create and push tag
git tag "$TAG"
git push origin "$TAG"
git fetch origin main
echo "Successfully created and pushed tag ${TAG}"
HEAD_SHA=$(git rev-parse HEAD)
FETCHED_MAIN_SHA=$(git rev-parse "FETCH_HEAD^{commit}")
if [ "${HEAD_SHA}" != "${FETCHED_MAIN_SHA}" ]; then
echo "Error: HEAD must exactly match origin/main before tagging." >&2
exit 1
fi
if git rev-parse -q --verify "refs/tags/${TAG}" >/dev/null; then
echo "Error: local tag ${TAG} already exists." >&2
exit 1
fi
REMOTE_TAG=$(git ls-remote --tags origin "refs/tags/${TAG}")
if [ -n "${REMOTE_TAG}" ]; then
echo "Error: remote tag ${TAG} already exists." >&2
exit 1
fi
git tag "${TAG}" "${HEAD_SHA}"
git push origin "refs/tags/${TAG}"
echo "Successfully pushed tag ${TAG}"

View File

@@ -12,10 +12,23 @@ import (
"github.com/larksuite/cli/shortcuts/common"
)
// maxFileListPageSize 是 file_list 分页上限,与后端 paas_storage checkMaxKeys 的 (0, 200] 契约对齐:
// page_size > 200 服务端直接返回 ErrInvalidRequest("maxKeys not in range (0, 200]")。CLI 前置校验避免无谓往返。
// 注:服务端对 page_size<=0 会兜底为默认值,但 CLI 默认已是 20、显式传 <1 属误用,故与其它 list 命令一致地按 [1, 200] 校验。
const maxFileListPageSize = 200
// validateFileListPageSize 前置校验 --page-size ∈ [1, maxFileListPageSize],与后端 checkMaxKeys 的 (0, 200] 契约对齐。
func validateFileListPageSize(n int) error {
if n < 1 || n > maxFileListPageSize {
return appsValidationParamError("--page-size", "--page-size must be between 1 and %d", maxFileListPageSize)
}
return nil
}
// AppsFileList lists files in a Miaoda app's storage (cursor pagination)。
//
// GET /apps/{app_id}/storage/file_list。过滤器--name / --path / --type / --size-gt /
// --size-lt / --uploaded-since / --uploaded-until精确或区间分页 --page-size/--page-token。
// --size-lt / --uploaded-since / --uploaded-until精确或区间分页 --page-size(1..200)/--page-token。
// file 域不分 dev/online无 --env。
//
// pretty 渲染 5 列file_name / path / size / type / uploaded_at空结果打 "No files found."。
@@ -41,13 +54,17 @@ var AppsFileList = common.Shortcut{
{Name: "size-lt", Type: "int", Desc: "filter: size less than (bytes)"},
{Name: "uploaded-since", Desc: "filter: uploaded at or after; relative (7d/2h/30s) | date (2026-04-15) | datetime (2026-04-15T10:00:00) | ISO 8601 w/ TZ (bare date/datetime read in local timezone)"},
{Name: "uploaded-until", Desc: "filter: uploaded at or before; relative (7d/2h/30s) | date (2026-04-15) | datetime (2026-04-15T10:00:00) | ISO 8601 w/ TZ (bare date/datetime read in local timezone)"},
{Name: "page-size", Type: "int", Default: "20", Desc: "page size"},
{Name: "page-size", Type: "int", Default: "20", Desc: "page size (1..200)"},
{Name: "page-token", Desc: "pagination cursor from previous response"},
},
Validate: func(ctx context.Context, rctx *common.RuntimeContext) error {
if _, err := requireAppID(rctx.Str("app-id")); err != nil {
return err
}
// page_size 前置校验:对齐后端 checkMaxKeys 的 (0, 200] 契约,避免 >200 触发服务端 ErrInvalidRequest。
if err := validateFileListPageSize(rctx.Int("page-size")); err != nil {
return err
}
// 设计原则三:<timestamp> 多格式 → 归一化为 RFC3339 UTC回写到 flag 供 buildFileListParams 透传。
for _, f := range []string{"uploaded-since", "uploaded-until"} {
if strings.TrimSpace(rctx.Str(f)) == "" {

View File

@@ -82,6 +82,34 @@ func TestAppsFileList_RequiresAppID(t *testing.T) {
}
}
// TestAppsFileList_PageSizeOutOfRange 验证 --page-size 超出 (0, 200] 契约时前置报 --page-size 校验错误,不发请求。
func TestAppsFileList_PageSizeOutOfRange(t *testing.T) {
for _, ps := range []string{"0", "201", "500"} {
factory, stdout, _ := newAppsExecuteFactory(t)
err := runAppsShortcut(t, AppsFileList,
[]string{"+file-list", "--app-id", "app_x", "--page-size", ps, "--as", "user"}, factory, stdout)
var ve *errs.ValidationError
if !errors.As(err, &ve) {
t.Fatalf("page-size=%s: err = %T %v, want *errs.ValidationError", ps, err, err)
}
if ve.Param != "--page-size" {
t.Fatalf("page-size=%s: Param = %q, want --page-size", ps, ve.Param)
}
}
}
// TestAppsFileList_PageSizeBoundaryOK 验证边界值 1 与 200 通过校验dry-run 不报错并把 page_size 下发)。
func TestAppsFileList_PageSizeBoundaryOK(t *testing.T) {
for _, ps := range []string{"1", "200"} {
factory, stdout, _ := newAppsExecuteFactory(t)
if err := runAppsShortcut(t, AppsFileList,
[]string{"+file-list", "--app-id", "app_x", "--page-size", ps, "--dry-run", "--as", "user"},
factory, stdout); err != nil {
t.Fatalf("page-size=%s: dry-run err=%v", ps, err)
}
}
}
// 过滤器 + 分页全部进 querysize-gt/lt 走 intuploaded_since/until 原样)。
func TestAppsFileList_DryRunSendsFiltersAndPagination(t *testing.T) {
factory, stdout, _ := newAppsExecuteFactory(t)

View File

@@ -14,7 +14,6 @@ import (
"strings"
"github.com/larksuite/cli/errs"
"github.com/larksuite/cli/internal/cmdutil"
"github.com/larksuite/cli/shortcuts/common"
)
@@ -47,21 +46,7 @@ var AppsFileUpload = common.Shortcut{
if _, err := requireAppID(rctx.Str("app-id")); err != nil {
return err
}
f := strings.TrimSpace(rctx.Str("file"))
if f == "" {
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--file is required").WithParam("--file")
}
st, err := rctx.FileIO().Stat(f)
if err != nil {
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--file: %v", err).WithParam("--file").WithCause(err)
}
if st.IsDir() {
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--file must be a file, not a directory").WithParam("--file")
}
if st.Size() > fileUploadMaxBytes {
return errs.NewValidationError(errs.SubtypeInvalidArgument, "file size %d bytes exceeds the 100 MB upload limit", st.Size()).WithParam("--file")
}
return nil
return rctx.ValidateLocalFileFlag("file", fileUploadMaxBytes)
},
DryRun: func(ctx context.Context, rctx *common.RuntimeContext) *common.DryRunAPI {
appID, _ := requireAppID(rctx.Str("app-id"))
@@ -76,9 +61,9 @@ var AppsFileUpload = common.Shortcut{
return err
}
localPath := strings.TrimSpace(rctx.Str("file"))
content, err := cmdutil.ReadInputFile(rctx.FileIO(), localPath)
content, err := rctx.ReadLocalFileFlag("file", fileUploadMaxBytes)
if err != nil {
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--file: %v", err).WithParam("--file").WithCause(err)
return err
}
fileName := filepath.Base(localPath)
contentType := mimeByExt(fileName)

View File

@@ -12,6 +12,7 @@ import (
"net/http/httptest"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
@@ -58,22 +59,17 @@ func TestAppsFileUpload_RejectsDirectory(t *testing.T) {
}
}
// TestAppsFileUpload_DryRunPreUpload 验证 dry-run 输出 POST file_pre_uploadbody.file_name 取文件 basename。
// TestAppsFileUpload_DryRunPreUpload verifies that dry-run validates the local
// file and previews the pre-upload request without reading or uploading it.
func TestAppsFileUpload_DryRunPreUpload(t *testing.T) {
// Validate 会 Stat --file在 DryRun 之前),故 dry-run 也需要真实存在的文件。
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "logo.png"), []byte("x"), 0o600); err != nil {
absolutePath := filepath.Join(t.TempDir(), "logo.png")
if err := os.WriteFile(absolutePath, []byte("not-read-by-dry-run"), 0o600); err != nil {
t.Fatal(err)
}
oldWD, _ := os.Getwd()
if err := os.Chdir(dir); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = os.Chdir(oldWD) })
factory, stdout, _ := newAppsExecuteFactory(t)
if err := runAppsShortcut(t, AppsFileUpload,
[]string{"+file-upload", "--app-id", "app_x", "--file", "logo.png", "--dry-run", "--as", "user"}, factory, stdout); err != nil {
[]string{"+file-upload", "--app-id", "app_x", "--file", absolutePath, "--dry-run", "--as", "user"}, factory, stdout); err != nil {
t.Fatalf("dry-run err=%v", err)
}
var env dryRunAPIEnvelope
@@ -87,6 +83,18 @@ func TestAppsFileUpload_DryRunPreUpload(t *testing.T) {
}
}
func TestAppsFileUpload_DryRunRejectsMissingFile(t *testing.T) {
missingAbsolutePath := filepath.Join(t.TempDir(), "does-not-exist", "logo.png")
factory, stdout, _ := newAppsExecuteFactory(t)
err := runAppsShortcut(t, AppsFileUpload,
[]string{"+file-upload", "--app-id", "app_x", "--file", missingAbsolutePath, "--dry-run", "--as", "user"}, factory, stdout)
var validationErr *errs.ValidationError
if !errors.As(err, &validationErr) || validationErr.Subtype != errs.SubtypeInvalidArgument || validationErr.Param != "--file" {
t.Fatalf("error = %T %v, want invalid_argument for --file", err, err)
}
}
// 三步直传pre-upload → 客户端 PUT 字节 → callback。
func TestAppsFileUpload_EndToEnd(t *testing.T) {
var putBody []byte
@@ -149,6 +157,142 @@ func TestAppsFileUpload_EndToEnd(t *testing.T) {
}
}
// TestAppsFileUpload_AcceptsAbsolutePath verifies that file-upload can read an
// absolute path outside the current working directory.
func TestAppsFileUpload_AcceptsAbsolutePath(t *testing.T) {
var putBody []byte
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPut {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
putBody, _ = io.ReadAll(r.Body)
w.Header().Set("ETag", `"etag-abs"`)
w.WriteHeader(http.StatusOK)
}))
defer srv.Close()
// Keep the process cwd unchanged so the temporary file is outside it.
dir := t.TempDir()
absFile := filepath.Join(dir, "report.pdf")
if !filepath.IsAbs(absFile) {
t.Fatalf("test setup: %q is not absolute", absFile)
}
if err := os.WriteFile(absFile, []byte("PDFBYTES"), 0o600); err != nil {
t.Fatal(err)
}
factory, stdout, reg := newAppsExecuteFactory(t)
reg.Register(&httpmock.Stub{
Method: "POST", URL: "/open-apis/spark/v1/apps/app_x/storage/file_pre_upload",
Body: map[string]interface{}{"code": 0, "data": map[string]interface{}{"upload_url": srv.URL, "upload_id": "up-abs"}},
})
reg.Register(&httpmock.Stub{
Method: "POST", URL: "/open-apis/spark/v1/apps/app_x/storage/file_upload_callback",
Body: map[string]interface{}{"code": 0, "data": map[string]interface{}{
"file_name": "report.pdf", "path": "/1858537546760999.pdf", "size_bytes": 8,
}},
})
if err := runAppsShortcut(t, AppsFileUpload,
[]string{"+file-upload", "--app-id", "app_x", "--file", absFile, "--as", "user"}, factory, stdout); err != nil {
t.Fatalf("execute with absolute path err=%v", err)
}
if string(putBody) != "PDFBYTES" {
t.Fatalf("PUT body = %q, want file bytes", putBody)
}
}
func TestAppsFileUpload_AcceptsParentRelativePathOutsideCWD(t *testing.T) {
var putBody []byte
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
putBody, _ = io.ReadAll(r.Body)
w.Header().Set("ETag", `"etag-parent"`)
w.WriteHeader(http.StatusOK)
}))
defer srv.Close()
root := t.TempDir()
workDir := filepath.Join(root, "work")
if err := os.Mkdir(workDir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(root, "report.pdf"), []byte("PARENT"), 0o600); err != nil {
t.Fatal(err)
}
oldWD, _ := os.Getwd()
if err := os.Chdir(workDir); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = os.Chdir(oldWD) })
factory, stdout, reg := newAppsExecuteFactory(t)
reg.Register(&httpmock.Stub{
Method: "POST", URL: "/open-apis/spark/v1/apps/app_x/storage/file_pre_upload",
Body: map[string]interface{}{"code": 0, "data": map[string]interface{}{"upload_url": srv.URL, "upload_id": "up-parent"}},
})
reg.Register(&httpmock.Stub{
Method: "POST", URL: "/open-apis/spark/v1/apps/app_x/storage/file_upload_callback",
Body: map[string]interface{}{"code": 0, "data": map[string]interface{}{
"file_name": "report.pdf", "path": "/parent.pdf", "size_bytes": 6,
}},
})
if err := runAppsShortcut(t, AppsFileUpload,
[]string{"+file-upload", "--app-id", "app_x", "--file", filepath.Join("..", "report.pdf"), "--as", "user"}, factory, stdout); err != nil {
t.Fatalf("execute with parent-relative path err=%v", err)
}
if string(putBody) != "PARENT" {
t.Fatalf("PUT body = %q, want PARENT", putBody)
}
}
func TestAppsFileUpload_RejectsFileAboveLimit(t *testing.T) {
path := filepath.Join(t.TempDir(), "too-large.bin")
f, err := os.Create(path)
if err != nil {
t.Fatal(err)
}
if err := f.Truncate(fileUploadMaxBytes + 1); err != nil {
_ = f.Close()
t.Fatal(err)
}
if err := f.Close(); err != nil {
t.Fatal(err)
}
factory, stdout, _ := newAppsExecuteFactory(t)
err = runAppsShortcut(t, AppsFileUpload,
[]string{"+file-upload", "--app-id", "app_x", "--file", path, "--as", "user"}, factory, stdout)
var validationErr *errs.ValidationError
if !errors.As(err, &validationErr) || validationErr.Param != "--file" {
t.Fatalf("error = %T %v, want --file ValidationError", err, err)
}
if !strings.Contains(validationErr.Error(), "limit") {
t.Fatalf("error = %v, want size limit context", validationErr)
}
}
func TestAppsFileUpload_RejectsDeviceWithoutReadingIt(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("/dev/zero is unavailable on Windows")
}
if _, err := os.Stat("/dev/zero"); err != nil {
t.Skipf("/dev/zero unavailable: %v", err)
}
factory, stdout, _ := newAppsExecuteFactory(t)
err := runAppsShortcut(t, AppsFileUpload,
[]string{"+file-upload", "--app-id", "app_x", "--file", "/dev/zero", "--as", "user"}, factory, stdout)
var validationErr *errs.ValidationError
if !errors.As(err, &validationErr) || validationErr.Param != "--file" {
t.Fatalf("error = %T %v, want --file ValidationError", err, err)
}
if !strings.Contains(validationErr.Error(), "regular file") {
t.Fatalf("error = %v, want non-regular-file context", validationErr)
}
}
// TestSanitizeUploadFileName_Cases 验证 sanitizeUploadFileName空格转 %20、去 TOS 非法字符、全非法兜底、非 ASCII 百分号编码。
func TestSanitizeUploadFileName_Cases(t *testing.T) {
cases := []struct{ in, want string }{

View File

@@ -2435,16 +2435,14 @@ func TestBaseRecordExecuteReadCreateDelete(t *testing.T) {
Body: map[string]interface{}{
"code": 0,
"data": map[string]interface{}{
"fields": []interface{}{"Name"},
"record_id_list": []interface{}{"rec_1", "rec_2"},
"data": []interface{}{[]interface{}{"Alice"}, []interface{}{"Bob"}},
},
},
})
if err := runShortcut(t, BaseRecordBatchCreate, []string{"+record-batch-create", "--base-token", "app_x", "--table-id", "tbl_x", "--json", `{"fields":["Name"],"rows":[["Alice"],["Bob"]]}`}, factory, stdout); err != nil {
if err := runShortcut(t, BaseRecordBatchCreate, []string{"+record-batch-create", "--base-token", "app_x", "--table-id", "tbl_x", "--json", `{"create_records":[{"Name":"Alice"},{"Name":"Bob"}]}`}, factory, stdout); err != nil {
t.Fatalf("err=%v", err)
}
if got := stdout.String(); !strings.Contains(got, `"record_id_list"`) || !strings.Contains(got, `"rec_1"`) || !strings.Contains(got, `"Alice"`) {
if got := stdout.String(); !strings.Contains(got, `"record_id_list"`) || !strings.Contains(got, `"rec_1"`) {
t.Fatalf("stdout=%s", got)
}
})

View File

@@ -26,7 +26,7 @@ var BaseFormSubmit = common.Shortcut{
Service: "base",
Command: "+form-submit",
Description: "Submit a form (fill and submit form data)",
Risk: "write",
Risk: "high-risk-write",
Scopes: []string{"base:form:update", "docs:document.media:upload"},
AuthTypes: authTypes(),
HasFormat: true,
@@ -39,6 +39,7 @@ var BaseFormSubmit = common.Shortcut{
`Example (no attachments): --share-token shrXXXX --json '{"fields":{"Service Rating":5,"Review":"Good service"}}'`,
`Example (with attachments): --share-token shrXXXX --base-token basXXX --json '{"fields":{"Service Rating":5},"attachments":{"Attachment":["./report.pdf"]}}'`,
`Cell values in "fields" follow lark-base-cell-value.md conventions; "attachments" maps field names to local file path arrays — the CLI uploads them in parallel and merges them into the submission.`,
baseHighRiskYesTip,
},
Validate: func(ctx context.Context, runtime *common.RuntimeContext) error {
return validateFormSubmit(runtime)

View File

@@ -801,7 +801,8 @@ func TestBaseJSONExamplesLiveInFlagDescriptions(t *testing.T) {
name: "record batch create json",
shortcut: BaseRecordBatchCreate,
wantHelp: []string{
`batch create JSON object, e.g. {"fields":["Name","Status"],"rows":[["Task A","Todo"],["Task B",null]]}; rows follow fields order`,
"create_records contains one field map per record",
`{"create_records":[{"Name":"Task A","Status":"Todo"},{"Name":"Task B","Score":20}]}`,
},
},
{
@@ -850,8 +851,8 @@ func TestBaseRecordWriteHelpGuidesAgents(t *testing.T) {
`{"Parent Link":[{"id":"rec_xxx"}]}`,
"do not look for parent_record_id or a separate child-record API",
"CellValue happy path: text/phone/url",
"select -> \"Todo\"",
"multi-select -> [\"Tag A\",\"Tag B\"]",
"select (multiple=false) -> \"Todo\"",
"select (multiple=true) -> [\"Tag A\",\"Tag B\"]",
"datetime -> \"2026-03-24 10:00:00\"",
"checkbox -> true/false",
`ID-based CellValue: user/group/link fields use arrays like [{"id":"ou_xxx"}]`,
@@ -865,11 +866,11 @@ func TestBaseRecordWriteHelpGuidesAgents(t *testing.T) {
name: "record batch create",
shortcut: BaseRecordBatchCreate,
wantTips: []string{
"Happy path fields: fields is the column order",
"rows is an array of row arrays",
"may use null for empty cells",
"Happy path field: create_records",
"create_records is an array of independent record field maps",
`{"create_records":[{"Name":"Task A","Status":"Todo"},{"Name":"Task B","Score":20}]}`,
"use +field-list to confirm real writable fields",
"Batch create supports max 200 rows per call",
"Batch create supports max 200 records per call",
"do not immediately +record-list the same table",
"CellValue happy path: text/phone/url",
`ID-based CellValue: user/group/link fields use arrays like [{"id":"ou_xxx"}]`,
@@ -2055,8 +2056,8 @@ func TestBaseFormSubmitShortcut(t *testing.T) {
if s.Service != "base" {
t.Fatalf("Service=%q want base", s.Service)
}
if s.Risk != "write" {
t.Fatalf("Risk=%q want write", s.Risk)
if s.Risk != "high-risk-write" {
t.Fatalf("Risk=%q want high-risk-write", s.Risk)
}
if !s.HasFormat {
t.Fatal("HasFormat should be true")
@@ -2356,6 +2357,7 @@ func TestExecuteFormSubmit(t *testing.T) {
"+form-submit",
"--share-token", "shr_exec1",
"--json", `{"fields":{"Name":"Alice","Rating":5}}`,
"--yes",
}
if err := runShortcut(t, BaseFormSubmit, args, factory, stdout); err != nil {
t.Fatalf("err=%v", err)
@@ -2424,6 +2426,7 @@ func TestExecuteFormSubmit(t *testing.T) {
"--share-token", "shr_exec6",
"--base-token", "bas_exec6",
"--json", `{"attachments":{"File":["./nonexistent.pdf"]}}`,
"--yes",
}
err := runShortcut(t, BaseFormSubmit, args, factory, stdout)
if err == nil {
@@ -2472,6 +2475,7 @@ func TestExecuteFormSubmit(t *testing.T) {
"--share-token", "shr_dedup",
"--base-token", "bas_dedup",
"--json", `{"attachments":{"FieldA":["./shared.pdf"],"FieldB":["./shared.pdf"]}}`,
"--yes",
}
if err := runShortcut(t, BaseFormSubmit, args, factory, stdout); err != nil {
t.Fatalf("err=%v", err)
@@ -2483,6 +2487,33 @@ func TestExecuteFormSubmit(t *testing.T) {
})
}
// TestFormSubmitRequiresConfirmation pins the high-risk-write classification:
// without --yes the runner's confirmation gate must fire before Execute runs,
// returning a typed confirmation_required error and touching no API.
func TestFormSubmitRequiresConfirmation(t *testing.T) {
if BaseFormSubmit.Risk != "high-risk-write" {
t.Fatalf("Risk=%q want high-risk-write", BaseFormSubmit.Risk)
}
factory, stdout, _ := newExecuteFactory(t)
args := []string{
"+form-submit",
"--share-token", "shr_confirm",
"--json", `{"fields":{"Rating":5}}`,
}
err := runShortcut(t, BaseFormSubmit, args, factory, stdout)
if err == nil {
t.Fatal("expected confirmation_required error without --yes")
}
problem, ok := errs.ProblemOf(err)
if !ok {
t.Fatalf("expected typed error, got %T: %v", err, err)
}
if problem.Subtype != errs.SubtypeConfirmationRequired {
t.Fatalf("subtype=%q want %q", problem.Subtype, errs.SubtypeConfirmationRequired)
}
}
func TestUploadAttachmentsParallel(t *testing.T) {
t.Run("single file upload via execute path", func(t *testing.T) {
tmpDir := t.TempDir()
@@ -2519,6 +2550,7 @@ func TestUploadAttachmentsParallel(t *testing.T) {
"--share-token", "shr_para1",
"--base-token", "bas_para1",
"--json", `{"attachments":{"Doc":["./doc.txt"]}}`,
"--yes",
}
if err := runShortcut(t, BaseFormSubmit, args, factory, stdout); err != nil {
t.Fatalf("err=%v", err)
@@ -2553,6 +2585,7 @@ func TestUploadAttachmentsParallel(t *testing.T) {
"--share-token", "shr_err",
"--base-token", "bas_err",
"--json", `{"attachments":{"Bad":["./bad.txt"]}}`,
"--yes",
}
err := runShortcut(t, BaseFormSubmit, args, factory, stdout)
if err == nil {

View File

@@ -27,7 +27,7 @@ var BaseFieldSearchOptions = common.Shortcut{
},
Tips: []string{
`Example: lark-cli base +field-search-options --base-token <base_token> --table-id <table_id> --field-id "Status" --keyword "Do"`,
"Use only for fields with options, such as select or multi-select fields.",
"Use only for select fields, whether multiple is false or true.",
},
Validate: func(ctx context.Context, runtime *common.RuntimeContext) error {
if err := validateLimitPageSizeAlias(runtime); err != nil {

View File

@@ -19,12 +19,13 @@ var BaseRecordBatchCreate = common.Shortcut{
Flags: []common.Flag{
baseTokenFlag(true),
tableRefFlag(true),
{Name: "json", Desc: `batch create JSON object, e.g. {"fields":["Name","Status"],"rows":[["Task A","Todo"],["Task B",null]]}; rows follow fields order`, Required: true},
{Name: "json", Desc: `batch create JSON object; create_records contains one field map per record, e.g. {"create_records":[{"Name":"Task A","Status":"Todo"},{"Name":"Task B","Score":20}]}`, Required: true},
},
Tips: append([]string{
"Happy path fields: fields is the column order; rows is an array of row arrays; each row must match fields order and may use null for empty cells.",
"Happy path field: create_records is an array of independent record field maps.",
`Example: {"create_records":[{"Name":"Task A","Status":"Todo"},{"Name":"Task B","Score":20}]}.`,
"Before writing, use +field-list to confirm real writable fields; do not write system fields, formula, lookup, or attachment fields as normal CellValue.",
"Batch create supports max 200 rows per call.",
"Batch create supports max 200 records per call.",
"After batch-creating known helper rows, use the returned record IDs and your submitted rows; do not immediately +record-list the same table unless you need server-normalized formula/lookup values or failure diagnosis.",
"Use the record-batch-create guide for command limits and edge cases.",
}, recordCellValueHappyPathTips...),

View File

@@ -19,7 +19,7 @@ const maxBatchGetSelectFieldCount = 100
const maxRecordSearchSelectFieldCount = 50
var recordCellValueHappyPathTips = []string{
`CellValue happy path: text/phone/url -> "text"; number/currency/percent/rating -> 12.5; select -> "Todo"; multi-select -> ["Tag A","Tag B"]; datetime -> "2026-03-24 10:00:00"; checkbox -> true/false.`,
`CellValue happy path: text/phone/url -> "text"; number/currency/percent/rating -> 12.5; select (multiple=false) -> "Todo"; select (multiple=true) -> ["Tag A","Tag B"]; datetime -> "2026-03-24 10:00:00"; checkbox -> true/false.`,
`ID-based CellValue: user/group/link fields use arrays like [{"id":"ou_xxx"}], [{"id":"oc_xxx"}], [{"id":"rec_xxx"}]; location uses {"lng":116.397428,"lat":39.90923}; null clears a cell when allowed.`,
"Do not guess user/chat/linked-record IDs or location coordinates; resolve them first with the relevant contact/im/record lookup flow.",
"Use lark-base-cell-value.md for complex CellValue shapes and special field types; do not invent values for fields not covered by the happy path.",

View File

@@ -0,0 +1,146 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package common
import (
"errors"
"io"
"io/fs"
"math"
"strings"
"github.com/larksuite/cli/errs"
"github.com/larksuite/cli/extension/fileio"
"github.com/larksuite/cli/internal/cmdutil"
"github.com/larksuite/cli/internal/validate"
)
// ValidateLocalFileFlag validates that a local input path exists, is a regular
// file, and does not exceed maxBytes. Absolute and relative paths use
// the process filesystem namespace.
func (ctx *RuntimeContext) ValidateLocalFileFlag(flagName string, maxBytes int64) error {
path, param, err := ctx.localFileFlag(flagName, maxBytes)
if err != nil {
return err
}
info, err := cmdutil.StatLocalFile(path)
if err != nil {
return localFileReadError(param, path, "inspect", err)
}
if err := localFileRegularError(param, path, info.Mode()); err != nil {
return err
}
if info.Size() > maxBytes {
return localFileSizeError(param, path, info.Size(), maxBytes)
}
return nil
}
// ReadLocalFileFlag is the shared replacement for direct os.ReadFile calls in
// shortcuts. It accepts absolute and relative paths, enforces a hard size
// limit, and returns command-facing typed errors.
func (ctx *RuntimeContext) ReadLocalFileFlag(flagName string, maxBytes int64) (data []byte, retErr error) {
path, param, err := ctx.localFileFlag(flagName, maxBytes)
if err != nil {
return nil, err
}
f, err := cmdutil.OpenLocalFile(path)
if err != nil {
return nil, localFileReadError(param, path, "open", err)
}
defer func() {
if err := f.Close(); err != nil && retErr == nil {
data = nil
retErr = errs.NewInternalError(errs.SubtypeFileIO, "cannot close %s %q: %v", param, path, err).WithCause(err)
}
}()
openedInfo, err := f.Stat()
if err != nil {
return nil, localFileReadError(param, path, "inspect opened", err)
}
if err := localFileRegularError(param, path, openedInfo.Mode()); err != nil {
return nil, err
}
if openedInfo.Size() > maxBytes {
return nil, localFileSizeError(param, path, openedInfo.Size(), maxBytes)
}
readLimit := maxBytes + 1
if maxBytes == math.MaxInt64 {
readLimit = maxBytes
}
data, err = io.ReadAll(io.LimitReader(f, readLimit))
if err != nil {
return nil, localFileReadError(param, path, "read", err)
}
if int64(len(data)) > maxBytes {
return nil, errs.NewValidationError(errs.SubtypeInvalidArgument,
"%s %q grew beyond the %d-byte limit while being read", param, path, maxBytes).
WithParam(param)
}
return data, nil
}
func (ctx *RuntimeContext) localFileFlag(flagName string, maxBytes int64) (path, param string, err error) {
name, param, err := localFileFlagNames(flagName)
if err != nil {
return "", "", err
}
if ctx == nil || ctx.Cmd == nil {
return "", param, errs.NewInternalError(errs.SubtypeUnknown, "cannot read %s: runtime command is unavailable", param)
}
path = strings.TrimSpace(ctx.Str(name))
if path == "" {
return "", param, errs.NewValidationError(errs.SubtypeInvalidArgument, "%s is required", param).WithParam(param)
}
if _, err := validate.LocalInputPath(path); err != nil {
return "", param, errs.NewValidationError(errs.SubtypeInvalidArgument, "invalid %s path: %v", param, err).
WithParam(param).
WithCause(err)
}
if maxBytes < 0 {
return "", param, errs.NewInternalError(errs.SubtypeUnknown, "invalid read limit configured for %s", param)
}
return path, param, nil
}
func localFileRegularError(param, path string, mode fs.FileMode) error {
if mode.IsRegular() {
return nil
}
return errs.NewValidationError(errs.SubtypeInvalidArgument,
"%s %q is not a regular file", param, path).
WithParam(param)
}
func localFileReadError(param, path, op string, cause error) error {
if errors.Is(cause, fileio.ErrPathValidation) {
return errs.NewValidationError(errs.SubtypeInvalidArgument, "invalid %s %q: %v", param, path, cause).
WithParam(param).
WithCause(cause)
}
if errors.Is(cause, fs.ErrNotExist) {
return errs.NewValidationError(errs.SubtypeInvalidArgument, "%s %q does not exist", param, path).
WithParam(param).
WithCause(cause)
}
return errs.NewInternalError(errs.SubtypeFileIO, "cannot %s %s %q: %v", op, param, path, cause).WithCause(cause)
}
func localFileSizeError(param, path string, size, limit int64) error {
return errs.NewValidationError(errs.SubtypeInvalidArgument,
"%s %q is %d bytes; limit is %d bytes", param, path, size, limit).
WithParam(param)
}
func localFileFlagNames(flagName string) (name, param string, err error) {
name = strings.TrimLeft(strings.TrimSpace(flagName), "-")
if name == "" {
return "", "", errs.NewInternalError(errs.SubtypeUnknown, "local file flag name must not be empty")
}
return name, "--" + name, nil
}

View File

@@ -0,0 +1,95 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package common
import (
"context"
"errors"
"os"
"path/filepath"
"testing"
"github.com/larksuite/cli/errs"
"github.com/spf13/cobra"
)
func TestReadLocalFileFlag_AcceptsAbsolutePath(t *testing.T) {
path := filepath.Join(t.TempDir(), "input.txt")
if err := os.WriteFile(path, []byte("content"), 0o600); err != nil {
t.Fatal(err)
}
rctx := localFileTestRuntime(t, path)
if err := rctx.ValidateLocalFileFlag("file", 7); err != nil {
t.Fatalf("ValidateLocalFileFlag() error = %v", err)
}
got, err := rctx.ReadLocalFileFlag("file", 7)
if err != nil || string(got) != "content" {
t.Fatalf("ReadLocalFileFlag() = %q, %v; want content", got, err)
}
}
func TestValidateLocalFileFlag_ReturnsTypedInputErrors(t *testing.T) {
for _, tc := range []struct {
name string
path func(t *testing.T) string
max int64
}{
{name: "invalid characters", path: func(*testing.T) string { return "input\n.txt" }, max: 10},
{name: "missing file", path: func(t *testing.T) string { return filepath.Join(t.TempDir(), "missing") }, max: 10},
{name: "directory", path: func(t *testing.T) string { return t.TempDir() }, max: 10},
{name: "too large", path: func(t *testing.T) string {
path := filepath.Join(t.TempDir(), "large")
if err := os.WriteFile(path, []byte("123456"), 0o600); err != nil {
t.Fatal(err)
}
return path
}, max: 5},
} {
t.Run(tc.name, func(t *testing.T) {
err := localFileTestRuntime(t, tc.path(t)).ValidateLocalFileFlag("file", tc.max)
var validationErr *errs.ValidationError
if !errors.As(err, &validationErr) || validationErr.Subtype != errs.SubtypeInvalidArgument || validationErr.Param != "--file" {
t.Fatalf("error = %T %v, want invalid_argument for --file", err, err)
}
})
}
}
func TestReadLocalFileFlag_ReturnsTypedInputErrors(t *testing.T) {
for _, tc := range []struct {
name string
path func(t *testing.T) string
max int64
}{
{name: "invalid characters", path: func(*testing.T) string { return "input\n.txt" }, max: 10},
{name: "missing file", path: func(t *testing.T) string { return filepath.Join(t.TempDir(), "missing") }, max: 10},
{name: "directory", path: func(t *testing.T) string { return t.TempDir() }, max: 10},
{name: "too large", path: func(t *testing.T) string {
path := filepath.Join(t.TempDir(), "large")
if err := os.WriteFile(path, []byte("123456"), 0o600); err != nil {
t.Fatal(err)
}
return path
}, max: 5},
} {
t.Run(tc.name, func(t *testing.T) {
_, err := localFileTestRuntime(t, tc.path(t)).ReadLocalFileFlag("file", tc.max)
var validationErr *errs.ValidationError
if !errors.As(err, &validationErr) || validationErr.Subtype != errs.SubtypeInvalidArgument || validationErr.Param != "--file" {
t.Fatalf("error = %T %v, want invalid_argument for --file", err, err)
}
})
}
}
func localFileTestRuntime(t *testing.T, path string) *RuntimeContext {
t.Helper()
cmd := &cobra.Command{Use: "test"}
cmd.Flags().String("file", "", "")
if err := cmd.Flags().Set("file", path); err != nil {
t.Fatal(err)
}
return &RuntimeContext{ctx: context.Background(), Cmd: cmd}
}

View File

@@ -0,0 +1,418 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package doc
import (
"context"
"errors"
"fmt"
"io/fs"
"path/filepath"
"strings"
"github.com/spf13/cobra"
"github.com/larksuite/cli/errs"
"github.com/larksuite/cli/extension/fileio"
"github.com/larksuite/cli/internal/charcheck"
"github.com/larksuite/cli/shortcuts/common"
"github.com/larksuite/cli/shortcuts/doc/internal/docxparse"
)
const (
docsScriptParse = "parse"
docsScriptMarkdownToXML = "markdown-to-xml"
docsScriptCreateTempXML = "create-temp-xml"
docsScriptTempDirSuffix = "_*_folder"
)
var DocsScript = common.Shortcut{
Service: "docs",
Command: "+script",
Description: "Create a unique temporary XML file, parse and profile local or online documents, or convert Markdown to LarkOpenCLI XML",
Risk: "read",
AuthTypes: []string{"user", "bot"},
Scopes: []string{},
ConditionalScopes: []string{
"docx:document:readonly",
},
Flags: []common.Flag{
{
Name: "command",
Desc: "local document operation",
Required: true,
Enum: []string{docsScriptParse, docsScriptMarkdownToXML, docsScriptCreateTempXML},
},
{
Name: "content",
Desc: "local content for parse or markdown-to-xml; use @relative-file or - for stdin; mutually exclusive with --doc",
Input: []string{common.File, common.Stdin},
},
{
Name: "doc",
Desc: "online document URL or token for --command parse; mutually exclusive with --content",
},
{
Name: "output",
Desc: "local XML output path for markdown-to-xml; omit to return XML in data.xml",
},
{
Name: "file-name",
Desc: "portable base name without .xml; create-temp-xml writes <name>_<random>_folder/<name>.xml",
},
{
Name: "overwrite",
Type: "bool",
Desc: "overwrite an existing --output file",
},
},
Tips: []string{
"create-temp-xml atomically creates <file-name>_<random>_folder/<file-name>.xml in the current directory",
"parse accepts local --content or an online --doc URL/token and returns only the text and block profile",
"markdown-to-xml converts Markdown to LarkOpenCLI XML",
"use --output to save converted XML directly and keep stdout compact",
},
PostMount: installDocsScriptHelp,
Validate: validateDocsScript,
DryRun: dryRunDocsScript,
Execute: executeDocsScript,
}
type docsScriptParseResult struct {
Profile docsScriptPublicProfile `json:"profile"`
}
// docsScriptPublicProfile is the stable shortcut response. The parser keeps
// the more detailed breakdown internally so it can be exposed later without
// changing the counting implementation.
type docsScriptPublicProfile struct {
WordCount int `json:"word_count"`
CharCount int `json:"char_count"`
BlockCount int `json:"block_count"`
Blocks []docxparse.BlockShare `json:"blocks"`
}
type docsScriptMarkdownResult struct {
XML string `json:"xml"`
}
type docsScriptMarkdownFileResult struct {
SavedPath string `json:"saved_path"`
SizeBytes int64 `json:"size_bytes"`
}
type docsScriptTempXMLResult struct {
Path string `json:"path"`
}
func installDocsScriptHelp(cmd *cobra.Command) {
installDocsShortcutHelp("+script")(cmd)
cmd.Example = ` lark-cli docs +script --command create-temp-xml --file-name "draft"
lark-cli docs +script --command parse --content "@draft.xml"
lark-cli docs +script --command parse --content "@draft.md"
lark-cli docs +script --command parse --doc "https://example.larksuite.com/docx/doxcn..."
lark-cli docs +script --command markdown-to-xml --content "@draft.md" --output "draft.xml"`
}
func validateDocsScript(_ context.Context, runtime *common.RuntimeContext) error {
content := strings.TrimSpace(runtime.Str("content"))
doc := strings.TrimSpace(runtime.Str("doc"))
outputPath := strings.TrimSpace(runtime.Str("output"))
fileName := strings.TrimSpace(runtime.Str("file-name"))
if runtime.Str("command") == docsScriptCreateTempXML {
switch {
case content != "":
return errs.NewValidationError(errs.SubtypeInvalidArgument,
"--content is not supported with --command create-temp-xml").WithParam("--content")
case doc != "":
return errs.NewValidationError(errs.SubtypeInvalidArgument,
"--doc is not supported with --command create-temp-xml").WithParam("--doc")
case outputPath != "":
return errs.NewValidationError(errs.SubtypeInvalidArgument,
"--output is not supported with --command create-temp-xml").WithParam("--output")
case runtime.Bool("overwrite"):
return errs.NewValidationError(errs.SubtypeInvalidArgument,
"--overwrite is not supported with --command create-temp-xml").WithParam("--overwrite")
case fileName == "":
return errs.NewValidationError(errs.SubtypeInvalidArgument,
"--file-name is required with --command create-temp-xml").WithParam("--file-name")
case runtime.Str("file-name") != fileName:
return errs.NewValidationError(errs.SubtypeInvalidArgument,
"--file-name must not start or end with whitespace").WithParam("--file-name")
default:
return validateDocsScriptTempXMLFileName(fileName)
}
}
if fileName != "" {
return errs.NewValidationError(errs.SubtypeInvalidArgument,
"--file-name is only supported with --command create-temp-xml").WithParam("--file-name")
}
if content == "" && doc == "" {
return errs.NewValidationError(errs.SubtypeInvalidArgument, "one of --content or --doc is required").WithParams(
errs.InvalidParam{Name: "--content", Reason: "provide local document content"},
errs.InvalidParam{Name: "--doc", Reason: "provide an online document URL or token"},
)
}
if content != "" && doc != "" {
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--content and --doc are mutually exclusive").WithParams(
errs.InvalidParam{Name: "--content", Reason: "mutually exclusive with --doc"},
errs.InvalidParam{Name: "--doc", Reason: "mutually exclusive with --content"},
)
}
if doc != "" {
if runtime.Str("command") != docsScriptParse {
return errs.NewValidationError(errs.SubtypeInvalidArgument,
"--doc is only supported with --command parse").WithParam("--doc")
}
if _, err := parseDocumentRef(doc); err != nil {
return err
}
if err := runtime.EnsureScopes([]string{"docx:document:readonly"}); err != nil {
return err
}
}
if outputPath == "" {
if runtime.Bool("overwrite") {
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--overwrite requires --output").WithParam("--overwrite")
}
return nil
}
if runtime.Str("command") != docsScriptMarkdownToXML {
return errs.NewValidationError(errs.SubtypeInvalidArgument,
"--output is only supported with --command markdown-to-xml").WithParam("--output")
}
if _, err := runtime.ResolveSavePath(outputPath); err != nil {
return errs.NewValidationError(errs.SubtypeInvalidArgument, "unsafe output path: %s", err).
WithParam("--output").
WithCause(err)
}
return nil
}
func dryRunDocsScript(_ context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
if runtime.Str("command") == docsScriptCreateTempXML {
fileName := strings.TrimSpace(runtime.Str("file-name"))
return common.NewDryRunAPI().
Desc("Create a random directory and an empty named XML file inside it; no API call is made").
Set("command", docsScriptCreateTempXML).
Set("directory_pattern", docsScriptTempDirectoryPattern(fileName)).
Set("file_name", fileName).
Set("xml_file_name", docsScriptXMLFileName(fileName)).
Set("creates_file", false).
Set("network", false)
}
if doc := strings.TrimSpace(runtime.Str("doc")); doc != "" {
ref, _ := parseDocumentRef(doc)
return common.NewDryRunAPI().
POST("/open-apis/docs_ai/v1/documents/:document_id/fetch").
Desc("OpenAPI: fetch document for parsing and profiling").
Body(docsScriptFetchBody(runtime)).
Set("command", runtime.Str("command")).
Set("document_id", ref.Token).
Set("network", true)
}
dry := common.NewDryRunAPI().
Desc("Local LarkOpenCLI document parsing or conversion; no API call is made").
Set("command", runtime.Str("command")).
Set("input_bytes", len(runtime.Str("content"))).
Set("network", false)
if outputPath := strings.TrimSpace(runtime.Str("output")); outputPath != "" {
dry.Set("output", outputPath).Set("overwrite", runtime.Bool("overwrite"))
}
return dry
}
func executeDocsScript(_ context.Context, runtime *common.RuntimeContext) error {
command := runtime.Str("command")
content := runtime.Str("content")
switch command {
case docsScriptCreateTempXML:
return createDocsScriptTempXML(runtime)
case docsScriptParse:
inputParam := "--content"
inputLabel := "--content"
if strings.TrimSpace(runtime.Str("doc")) != "" {
var err error
content, err = fetchDocsScriptContent(runtime)
if err != nil {
return err
}
inputParam = "--doc"
inputLabel = "fetched document content"
}
profile, err := docxparse.ParseAuto(content)
if err != nil {
return errs.NewValidationError(errs.SubtypeInvalidArgument,
"could not parse %s as LarkOpenCLI XML or Markdown: %s", inputLabel, err).
WithParam(inputParam).
WithCause(err)
}
runtime.OutFormatRaw(docsScriptParseResult{Profile: docsScriptPublicProfile{
WordCount: profile.WordCount,
CharCount: profile.CharCount,
BlockCount: profile.BlockCount,
Blocks: profile.Blocks,
}}, nil, nil)
return nil
case docsScriptMarkdownToXML:
xml, err := docxparse.MarkdownToXML(content)
if err != nil {
return errs.NewValidationError(errs.SubtypeInvalidArgument,
"could not convert --content from Markdown to LarkOpenCLI XML: %s", err).
WithParam("--content").
WithCause(err)
}
if outputPath := strings.TrimSpace(runtime.Str("output")); outputPath != "" {
return saveDocsScriptXML(runtime, outputPath, xml)
}
runtime.OutFormatRaw(docsScriptMarkdownResult{XML: xml}, nil, nil)
return nil
default:
return errs.NewValidationError(errs.SubtypeInvalidArgument,
"unsupported --command %q", command).
WithParam("--command")
}
}
func createDocsScriptTempXML(runtime *common.RuntimeContext) error {
creator, ok := runtime.FileIO().(fileio.TempDirFileCreator)
if !ok {
return errs.NewValidationError(errs.SubtypeFailedPrecondition,
"the active file I/O provider does not support temporary file creation").
WithHint("run this command with the local file I/O provider")
}
fileName := strings.TrimSpace(runtime.Str("file-name"))
path, err := creator.CreateTempDirFile(docsScriptTempDirectoryPattern(fileName), docsScriptXMLFileName(fileName))
if err != nil {
return common.WrapSaveErrorTyped(err)
}
if _, err := runtime.ResolveSavePath(path); err != nil {
return errs.NewInternalError(errs.SubtypeFileIO,
"resolve temporary XML path %s: %s", path, err).
WithCause(err)
}
runtime.Out(docsScriptTempXMLResult{
Path: path,
}, nil)
return nil
}
func validateDocsScriptTempXMLFileName(fileName string) error {
if fileName != filepath.Base(fileName) || strings.ContainsAny(fileName, "<>:\"/\\|?*\t\r\n") {
return errs.NewValidationError(errs.SubtypeInvalidArgument,
"--file-name must be a portable file name without path separators or reserved characters").WithParam("--file-name")
}
if err := charcheck.RejectControlChars(fileName, "--file-name"); err != nil {
return errs.NewValidationError(errs.SubtypeInvalidArgument, "%s", err).
WithParam("--file-name").
WithCause(err)
}
if strings.HasSuffix(fileName, ".") || strings.HasSuffix(fileName, " ") {
return errs.NewValidationError(errs.SubtypeInvalidArgument,
"--file-name must not end with a dot or space").WithParam("--file-name")
}
if strings.EqualFold(filepath.Ext(fileName), ".xml") {
return errs.NewValidationError(errs.SubtypeInvalidArgument,
"--file-name must omit the .xml extension").WithParam("--file-name")
}
base := strings.ToUpper(strings.SplitN(fileName, ".", 2)[0])
if isWindowsReservedFileName(base) {
return errs.NewValidationError(errs.SubtypeInvalidArgument,
"--file-name uses a Windows-reserved device name").WithParam("--file-name")
}
return nil
}
func docsScriptTempDirectoryPattern(fileName string) string {
return fileName + docsScriptTempDirSuffix
}
func docsScriptXMLFileName(fileName string) string {
return fileName + ".xml"
}
func isWindowsReservedFileName(base string) bool {
switch base {
case "CON", "PRN", "AUX", "NUL":
return true
}
if len(base) == 4 && (strings.HasPrefix(base, "COM") || strings.HasPrefix(base, "LPT")) {
return base[3] >= '1' && base[3] <= '9'
}
return false
}
func docsScriptFetchBody(runtime *common.RuntimeContext) map[string]interface{} {
body := map[string]interface{}{
"format": "xml",
"extra_param": docsFetchExtraParam,
"export_option": map[string]interface{}{
"export_block_id": false,
"export_style_attrs": false,
"export_cite_extra_data": false,
},
}
if lang := resolveFetchLang(runtime); lang != "" {
body["lang"] = lang
}
return body
}
func fetchDocsScriptContent(runtime *common.RuntimeContext) (string, error) {
ref, _ := parseDocumentRef(runtime.Str("doc"))
apiPath := fmt.Sprintf("/open-apis/docs_ai/v1/documents/%s/fetch", ref.Token)
data, err := doDocAPI(runtime, "POST", apiPath, docsScriptFetchBody(runtime))
if err != nil {
return "", err
}
document, ok := data["document"].(map[string]interface{})
if !ok || document == nil {
return "", errs.NewInternalError(errs.SubtypeUnknown,
"document fetch response for --doc is missing document")
}
content, ok := document["content"].(string)
if !ok {
return "", errs.NewInternalError(errs.SubtypeUnknown,
"document fetch response for --doc is missing document.content")
}
return content, nil
}
func saveDocsScriptXML(runtime *common.RuntimeContext, outputPath, xml string) error {
if !runtime.Bool("overwrite") {
if _, err := runtime.FileIO().Stat(outputPath); err == nil {
return errs.NewValidationError(errs.SubtypeFailedPrecondition,
"output file already exists: %s (use --overwrite to replace)", outputPath).
WithParam("--output")
} else if !errors.Is(err, fs.ErrNotExist) {
if errors.Is(err, fileio.ErrPathValidation) {
return errs.NewValidationError(errs.SubtypeInvalidArgument, "unsafe output path: %s", err).
WithParam("--output").
WithCause(err)
}
return errs.NewInternalError(errs.SubtypeFileIO,
"cannot access output path %s: %s", outputPath, err).
WithCause(err)
}
}
result, err := runtime.FileIO().Save(outputPath, fileio.SaveOptions{
ContentType: "application/xml",
ContentLength: int64(len(xml)),
}, strings.NewReader(xml))
if err != nil {
return common.WrapSaveErrorTyped(err)
}
savedPath, err := runtime.ResolveSavePath(outputPath)
if err != nil {
return errs.NewInternalError(errs.SubtypeFileIO,
"resolve saved XML path %s: %s", outputPath, err).
WithCause(err)
}
runtime.Out(docsScriptMarkdownFileResult{
SavedPath: savedPath,
SizeBytes: result.Size(),
}, nil)
return nil
}

View File

@@ -0,0 +1,660 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package doc
import (
"bytes"
"encoding/json"
"errors"
"os"
"path/filepath"
"strings"
"testing"
"github.com/spf13/cobra"
"github.com/larksuite/cli/errs"
"github.com/larksuite/cli/internal/cmdutil"
"github.com/larksuite/cli/shortcuts/doc/internal/docxparse"
)
func TestDocsScriptParsesAndProfilesXML(t *testing.T) {
f, stdout, _, _ := cmdutil.TestFactory(t, docsTestConfigWithAppID("docs-script-test"))
source := `<title>标题</title><p>一个苹果是 an apple。</p>`
err := mountAndRunDocs(t, DocsScript, []string{
"+script",
"--command", docsScriptParse,
"--content", source,
"--as", "bot",
}, f, stdout)
if err != nil {
t.Fatalf("execute docs +script: %v", err)
}
var envelope struct {
OK bool `json:"ok"`
Data map[string]json.RawMessage `json:"data"`
}
if err := json.Unmarshal(stdout.Bytes(), &envelope); err != nil {
t.Fatalf("decode stdout: %v\n%s", err, stdout)
}
if !envelope.OK {
t.Fatalf("ok = false: %s", stdout)
}
if len(envelope.Data) != 1 || envelope.Data["profile"] == nil {
t.Fatalf("data = %+v, want only profile", envelope.Data)
}
var profile docsScriptPublicProfile
if err := json.Unmarshal(envelope.Data["profile"], &profile); err != nil {
t.Fatalf("decode profile: %v", err)
}
var profileFields map[string]json.RawMessage
if err := json.Unmarshal(envelope.Data["profile"], &profileFields); err != nil {
t.Fatalf("decode profile fields: %v", err)
}
if len(profileFields) != 4 || profileFields["breakdown"] != nil {
t.Fatalf("profile fields = %+v, want breakdown hidden", profileFields)
}
if profile.WordCount != 10 || profile.CharCount != 15 || profile.BlockCount != 2 {
t.Fatalf("profile = %+v", profile)
}
if got := blockCount(profile.Blocks, "title"); got != 1 {
t.Fatalf("title count = %d, want 1", got)
}
if got := blockCount(profile.Blocks, "p"); got != 1 {
t.Fatalf("p count = %d, want 1", got)
}
}
func TestDocsScriptParseAutoDetectsMarkdown(t *testing.T) {
f, stdout, _, _ := cmdutil.TestFactory(t, docsTestConfigWithAppID("docs-script-auto-markdown"))
err := mountAndRunDocs(t, DocsScript, []string{
"+script",
"--command", docsScriptParse,
"--content", "# 标题\n\n- item",
"--as", "bot",
}, f, stdout)
if err != nil {
t.Fatalf("execute docs +script: %v", err)
}
var envelope struct {
Data docsScriptParseResult `json:"data"`
}
if err := json.Unmarshal(stdout.Bytes(), &envelope); err != nil {
t.Fatalf("decode stdout: %v\n%s", err, stdout)
}
if envelope.Data.Profile.BlockCount != 3 {
t.Fatalf("profile = %+v, want 3 blocks", envelope.Data.Profile)
}
}
func TestDocsScriptParsesOnlineDocumentFromToken(t *testing.T) {
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir())
f, stdout, _, reg := cmdutil.TestFactory(t, docsTestConfigWithAppID("docs-script-online-token"))
registerDocsAIStub(reg, "POST", "/open-apis/docs_ai/v1/documents/doxcnScriptToken/fetch", map[string]interface{}{
"document": map[string]interface{}{
"document_id": "doxcnScriptToken",
"content": `<title>在线文档</title><p>Hello world</p>`,
},
})
err := mountAndRunDocs(t, DocsScript, []string{
"+script",
"--command", docsScriptParse,
"--doc", "doxcnScriptToken",
"--as", "bot",
}, f, stdout)
if err != nil {
t.Fatalf("execute docs +script with token: %v", err)
}
var envelope struct {
Data docsScriptParseResult `json:"data"`
}
if err := json.Unmarshal(stdout.Bytes(), &envelope); err != nil {
t.Fatalf("decode stdout: %v\n%s", err, stdout)
}
if envelope.Data.Profile.BlockCount != 2 {
t.Fatalf("profile = %+v, want 2 blocks", envelope.Data.Profile)
}
if got := blockCount(envelope.Data.Profile.Blocks, "title"); got != 1 {
t.Fatalf("title count = %d, want 1", got)
}
if got := blockCount(envelope.Data.Profile.Blocks, "p"); got != 1 {
t.Fatalf("p count = %d, want 1", got)
}
}
func TestDocsScriptParsesOnlineDocumentFromURL(t *testing.T) {
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir())
f, stdout, _, reg := cmdutil.TestFactory(t, docsTestConfigWithAppID("docs-script-online-url"))
stub := registerDocsAIStub(reg, "POST", "/open-apis/docs_ai/v1/documents/wikcnScriptURL/fetch", map[string]interface{}{
"document": map[string]interface{}{
"document_id": "doxcnResolvedScriptURL",
"content": `<p>从 Wiki URL 读取</p>`,
},
})
err := mountAndRunDocs(t, DocsScript, []string{
"+script",
"--command", docsScriptParse,
"--doc", "https://example.larksuite.com/wiki/wikcnScriptURL",
"--as", "bot",
}, f, stdout)
if err != nil {
t.Fatalf("execute docs +script with URL: %v", err)
}
if stub.CapturedBody == nil {
t.Fatal("online parse did not call the document fetch API")
}
var envelope struct {
Data docsScriptParseResult `json:"data"`
}
if err := json.Unmarshal(stdout.Bytes(), &envelope); err != nil {
t.Fatalf("decode stdout: %v\n%s", err, stdout)
}
if envelope.Data.Profile.BlockCount != 1 || blockCount(envelope.Data.Profile.Blocks, "p") != 1 {
t.Fatalf("profile = %+v, want one paragraph", envelope.Data.Profile)
}
}
func TestDocsScriptRejectsContentAndDocTogether(t *testing.T) {
f, _, _, _ := cmdutil.TestFactory(t, docsTestConfigWithAppID("docs-script-input-conflict"))
err := mountAndRunDocs(t, DocsScript, []string{
"+script",
"--command", docsScriptParse,
"--content", `<p>local</p>`,
"--doc", "doxcnScriptConflict",
"--as", "bot",
}, f, nil)
assertValidationContract(t, err, errs.SubtypeInvalidArgument, "", "--content", "--doc")
}
func TestDocsScriptRejectsDocForMarkdownConversion(t *testing.T) {
f, _, _, _ := cmdutil.TestFactory(t, docsTestConfigWithAppID("docs-script-doc-convert"))
err := mountAndRunDocs(t, DocsScript, []string{
"+script",
"--command", docsScriptMarkdownToXML,
"--doc", "doxcnScriptConvert",
"--as", "bot",
}, f, nil)
assertValidationContract(t, err, errs.SubtypeInvalidArgument, "--doc")
}
func TestDocsScriptConvertsMarkdownFromStdin(t *testing.T) {
f, stdout, _, _ := cmdutil.TestFactory(t, docsTestConfigWithAppID("docs-script-markdown"))
f.IOStreams.In = bytes.NewBufferString("# 标题\n\n- item")
err := mountAndRunDocs(t, DocsScript, []string{
"+script",
"--command", docsScriptMarkdownToXML,
"--content", "-",
"--as", "bot",
}, f, stdout)
if err != nil {
t.Fatalf("execute docs +script: %v", err)
}
if !strings.Contains(stdout.String(), `<h1>标题</h1><ul><li>item</li></ul>`) {
t.Fatalf("stdout missing converted XML: %s", stdout)
}
var envelope struct {
Data map[string]json.RawMessage `json:"data"`
}
if err := json.Unmarshal(stdout.Bytes(), &envelope); err != nil {
t.Fatalf("decode stdout: %v\n%s", err, stdout)
}
if len(envelope.Data) != 1 || envelope.Data["xml"] == nil {
t.Fatalf("data = %+v, want only xml", envelope.Data)
}
}
func TestDocsScriptConvertsMarkdownToOutputFile(t *testing.T) {
workDir := t.TempDir()
withDocsWorkingDir(t, workDir)
f, stdout, _, _ := cmdutil.TestFactory(t, docsTestConfigWithAppID("docs-script-output"))
wantXML := `<h1>标题</h1><ul><li>item</li></ul>`
err := mountAndRunDocs(t, DocsScript, []string{
"+script",
"--command", docsScriptMarkdownToXML,
"--content", "# 标题\n\n- item",
"--output", "draft.xml",
"--as", "bot",
}, f, stdout)
if err != nil {
t.Fatalf("execute docs +script: %v", err)
}
gotXML, err := os.ReadFile("draft.xml")
if err != nil {
t.Fatalf("read output XML: %v", err)
}
if string(gotXML) != wantXML {
t.Fatalf("output XML = %q, want %q", gotXML, wantXML)
}
var envelope struct {
Data struct {
SavedPath string `json:"saved_path"`
SizeBytes int64 `json:"size_bytes"`
XML json.RawMessage `json:"xml"`
} `json:"data"`
}
if err := json.Unmarshal(stdout.Bytes(), &envelope); err != nil {
t.Fatalf("decode stdout: %v\n%s", err, stdout)
}
if envelope.Data.SavedPath != filepath.Join(workDir, "draft.xml") {
t.Fatalf("saved_path = %q, want %q", envelope.Data.SavedPath, filepath.Join(workDir, "draft.xml"))
}
if envelope.Data.SizeBytes != int64(len(wantXML)) {
t.Fatalf("size_bytes = %d, want %d", envelope.Data.SizeBytes, len(wantXML))
}
if envelope.Data.XML != nil {
t.Fatalf("data.xml should be omitted when --output is used: %s", stdout)
}
}
func TestDocsScriptCreatesUniqueTempXMLFiles(t *testing.T) {
workDir := t.TempDir()
withDocsWorkingDir(t, workDir)
f, stdout, _, _ := cmdutil.TestFactory(t, docsTestConfigWithAppID("docs-script-temp-xml"))
create := func() docsScriptTempXMLResult {
t.Helper()
stdout.Reset()
err := mountAndRunDocs(t, DocsScript, []string{
"+script",
"--command", docsScriptCreateTempXML,
"--file-name", "川西",
"--as", "bot",
}, f, stdout)
if err != nil {
t.Fatalf("execute docs +script: %v", err)
}
var envelope struct {
Data docsScriptTempXMLResult `json:"data"`
}
if err := json.Unmarshal(stdout.Bytes(), &envelope); err != nil {
t.Fatalf("decode stdout: %v\n%s", err, stdout)
}
return envelope.Data
}
first := create()
second := create()
if first.Path == second.Path {
t.Fatalf("temporary paths are identical: %q", first.Path)
}
for _, got := range []docsScriptTempXMLResult{first, second} {
directory := filepath.Dir(got.Path)
if filepath.Base(got.Path) != "川西.xml" || filepath.Base(directory) != directory ||
!strings.HasPrefix(directory, "川西_") || !strings.HasSuffix(directory, "_folder") {
t.Fatalf("path = %q, want 川西_<random>_folder/川西.xml", got.Path)
}
info, err := os.Stat(got.Path)
if err != nil {
t.Fatalf("stat temporary XML %q: %v", got.Path, err)
}
if info.Size() != 0 {
t.Fatalf("temporary XML %q size = %d, want 0", got.Path, info.Size())
}
}
}
func TestDocsScriptCreateTempXMLRejectsOtherFlags(t *testing.T) {
tests := []struct {
name string
args []string
param string
}{
{name: "content", args: []string{"--content", "<p>text</p>"}, param: "--content"},
{name: "doc", args: []string{"--doc", "doxcnScriptTemp"}, param: "--doc"},
{name: "output", args: []string{"--output", "draft.xml"}, param: "--output"},
{name: "overwrite", args: []string{"--overwrite"}, param: "--overwrite"},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
f, _, _, _ := cmdutil.TestFactory(t, docsTestConfigWithAppID("docs-script-temp-xml-flags"))
args := []string{"+script", "--command", docsScriptCreateTempXML, "--file-name", "川西", "--as", "bot"}
args = append(args, test.args...)
err := mountAndRunDocs(t, DocsScript, args, f, nil)
if err == nil {
t.Fatalf("expected %s validation error", test.param)
}
problem, ok := errs.ProblemOf(err)
var validationErr *errs.ValidationError
if !ok || problem.Category != errs.CategoryValidation || problem.Subtype != errs.SubtypeInvalidArgument ||
!errors.As(err, &validationErr) || validationErr.Param != test.param {
t.Fatalf("problem = %+v, validation = %+v, ok=%v", problem, validationErr, ok)
}
})
}
}
func TestDocsScriptCreateTempXMLValidatesFileName(t *testing.T) {
tests := []struct {
name string
fileName string
}{
{name: "missing"},
{name: "path", fileName: "folder/川西"},
{name: "windows path", fileName: `folder\川西`},
{name: "reserved character", fileName: "川西:一"},
{name: "xml extension included", fileName: "川西.xml"},
{name: "windows device", fileName: "CON"},
{name: "surrounding whitespace", fileName: " 川西"},
{name: "dangerous unicode", fileName: "川\u200b西"},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
f, _, _, _ := cmdutil.TestFactory(t, docsTestConfigWithAppID("docs-script-temp-xml-file-name"))
args := []string{"+script", "--command", docsScriptCreateTempXML, "--as", "bot"}
if test.fileName != "" {
args = append(args, "--file-name", test.fileName)
}
err := mountAndRunDocs(t, DocsScript, args, f, nil)
if err == nil {
t.Fatalf("expected --file-name validation error for %q", test.fileName)
}
problem, ok := errs.ProblemOf(err)
var validationErr *errs.ValidationError
if !ok || problem.Category != errs.CategoryValidation || problem.Subtype != errs.SubtypeInvalidArgument ||
!errors.As(err, &validationErr) || validationErr.Param != "--file-name" {
t.Fatalf("problem = %+v, validation = %+v, ok=%v", problem, validationErr, ok)
}
})
}
}
func TestDocsScriptOutputRequiresExplicitOverwrite(t *testing.T) {
withDocsWorkingDir(t, t.TempDir())
if err := os.WriteFile("draft.xml", []byte("old"), 0o600); err != nil {
t.Fatalf("write existing output: %v", err)
}
f, stdout, _, _ := cmdutil.TestFactory(t, docsTestConfigWithAppID("docs-script-overwrite"))
err := mountAndRunDocs(t, DocsScript, []string{
"+script",
"--command", docsScriptMarkdownToXML,
"--content", "# new",
"--output", "draft.xml",
"--as", "bot",
}, f, stdout)
if err == nil {
t.Fatal("expected existing output error")
}
problem, ok := errs.ProblemOf(err)
var validationErr *errs.ValidationError
if !ok || problem.Category != errs.CategoryValidation || problem.Subtype != errs.SubtypeFailedPrecondition ||
!errors.As(err, &validationErr) || validationErr.Param != "--output" {
t.Fatalf("problem = %+v, validation = %+v, ok=%v", problem, validationErr, ok)
}
got, readErr := os.ReadFile("draft.xml")
if readErr != nil || string(got) != "old" {
t.Fatalf("existing output changed: content=%q err=%v", got, readErr)
}
err = mountAndRunDocs(t, DocsScript, []string{
"+script",
"--command", docsScriptMarkdownToXML,
"--content", "# new",
"--output", "draft.xml",
"--overwrite",
"--as", "bot",
}, f, stdout)
if err != nil {
t.Fatalf("execute docs +script with --overwrite: %v", err)
}
got, readErr = os.ReadFile("draft.xml")
if readErr != nil || string(got) != "<h1>new</h1>" {
t.Fatalf("overwritten output = %q, err=%v", got, readErr)
}
}
func TestDocsScriptRejectsOutputForParse(t *testing.T) {
f, _, _, _ := cmdutil.TestFactory(t, docsTestConfigWithAppID("docs-script-output-parse"))
err := mountAndRunDocs(t, DocsScript, []string{
"+script",
"--command", docsScriptParse,
"--content", `<p>text</p>`,
"--output", "draft.xml",
"--as", "bot",
}, f, nil)
if err == nil {
t.Fatal("expected --output validation error")
}
problem, ok := errs.ProblemOf(err)
var validationErr *errs.ValidationError
if !ok || problem.Category != errs.CategoryValidation || problem.Subtype != errs.SubtypeInvalidArgument ||
!errors.As(err, &validationErr) || validationErr.Param != "--output" {
t.Fatalf("problem = %+v, validation = %+v, ok=%v", problem, validationErr, ok)
}
}
func TestDocsScriptRejectsUnsafeOutputPath(t *testing.T) {
f, _, _, _ := cmdutil.TestFactory(t, docsTestConfigWithAppID("docs-script-output-path"))
err := mountAndRunDocs(t, DocsScript, []string{
"+script",
"--command", docsScriptMarkdownToXML,
"--content", "# title",
"--output", filepath.Join(t.TempDir(), "draft.xml"),
"--as", "bot",
}, f, nil)
if err == nil {
t.Fatal("expected unsafe output path error")
}
problem, ok := errs.ProblemOf(err)
var validationErr *errs.ValidationError
if !ok || problem.Category != errs.CategoryValidation || problem.Subtype != errs.SubtypeInvalidArgument ||
!errors.As(err, &validationErr) || validationErr.Param != "--output" {
t.Fatalf("problem = %+v, validation = %+v, ok=%v", problem, validationErr, ok)
}
}
func TestDocsScriptDryRunHasNoAPICall(t *testing.T) {
f, stdout, _, _ := cmdutil.TestFactory(t, docsTestConfigWithAppID("docs-script-dry-run"))
err := mountAndRunDocs(t, DocsScript, []string{
"+script",
"--command", docsScriptParse,
"--content", `<p>text</p>`,
"--dry-run",
"--as", "bot",
}, f, stdout)
if err != nil {
t.Fatalf("execute docs +script dry-run: %v", err)
}
var got struct {
API []any `json:"api"`
Command string `json:"command"`
Network bool `json:"network"`
}
if err := json.Unmarshal(stdout.Bytes(), &got); err != nil {
t.Fatalf("decode dry-run stdout: %v\n%s", err, stdout)
}
if len(got.API) != 0 || got.Command != docsScriptParse || got.Network {
t.Fatalf("dry-run output = %+v", got)
}
}
func TestDocsScriptCreateTempXMLDryRunDoesNotWrite(t *testing.T) {
workDir := t.TempDir()
withDocsWorkingDir(t, workDir)
f, stdout, _, _ := cmdutil.TestFactory(t, docsTestConfigWithAppID("docs-script-temp-xml-dry-run"))
err := mountAndRunDocs(t, DocsScript, []string{
"+script",
"--command", docsScriptCreateTempXML,
"--file-name", "川西",
"--dry-run",
"--as", "bot",
}, f, stdout)
if err != nil {
t.Fatalf("execute docs +script dry-run: %v", err)
}
var got struct {
API []any `json:"api"`
Command string `json:"command"`
DirectoryPattern string `json:"directory_pattern"`
FileName string `json:"file_name"`
XMLFileName string `json:"xml_file_name"`
CreatesFile bool `json:"creates_file"`
Network bool `json:"network"`
}
if err := json.Unmarshal(stdout.Bytes(), &got); err != nil {
t.Fatalf("decode dry-run stdout: %v\n%s", err, stdout)
}
if len(got.API) != 0 || got.Command != docsScriptCreateTempXML ||
got.DirectoryPattern != "川西_*_folder" || got.FileName != "川西" || got.XMLFileName != "川西.xml" ||
got.CreatesFile || got.Network {
t.Fatalf("dry-run output = %+v", got)
}
entries, err := os.ReadDir(workDir)
if err != nil {
t.Fatalf("read work directory: %v", err)
}
if len(entries) != 0 {
t.Fatalf("dry-run created files: %+v", entries)
}
}
func TestDocsScriptOnlineDryRunShowsFetchAPICall(t *testing.T) {
f, stdout, _, _ := cmdutil.TestFactory(t, docsTestConfigWithAppID("docs-script-online-dry-run"))
err := mountAndRunDocs(t, DocsScript, []string{
"+script",
"--command", docsScriptParse,
"--doc", "https://example.larksuite.com/docx/doxcnScriptDryRun",
"--dry-run",
"--as", "bot",
}, f, stdout)
if err != nil {
t.Fatalf("execute online docs +script dry-run: %v", err)
}
var got struct {
API []struct {
Method string `json:"method"`
URL string `json:"url"`
Body map[string]interface{} `json:"body"`
} `json:"api"`
Command string `json:"command"`
DocumentID string `json:"document_id"`
Network bool `json:"network"`
}
if err := json.Unmarshal(stdout.Bytes(), &got); err != nil {
t.Fatalf("decode dry-run stdout: %v\n%s", err, stdout)
}
if len(got.API) != 1 || got.API[0].Method != "POST" ||
got.API[0].URL != "/open-apis/docs_ai/v1/documents/doxcnScriptDryRun/fetch" {
t.Fatalf("dry-run API = %+v", got.API)
}
if got.API[0].Body["format"] != "xml" {
t.Fatalf("dry-run body = %+v, want XML fetch", got.API[0].Body)
}
if got.Command != docsScriptParse || got.DocumentID != "doxcnScriptDryRun" || !got.Network {
t.Fatalf("dry-run output = %+v", got)
}
}
func TestDocsScriptOutputDryRunDoesNotWrite(t *testing.T) {
withDocsWorkingDir(t, t.TempDir())
f, stdout, _, _ := cmdutil.TestFactory(t, docsTestConfigWithAppID("docs-script-output-dry-run"))
err := mountAndRunDocs(t, DocsScript, []string{
"+script",
"--command", docsScriptMarkdownToXML,
"--content", "# title",
"--output", "draft.xml",
"--overwrite",
"--dry-run",
"--as", "bot",
}, f, stdout)
if err != nil {
t.Fatalf("execute docs +script dry-run: %v", err)
}
var got struct {
API []any `json:"api"`
Command string `json:"command"`
Network bool `json:"network"`
Output string `json:"output"`
Overwrite bool `json:"overwrite"`
}
if err := json.Unmarshal(stdout.Bytes(), &got); err != nil {
t.Fatalf("decode dry-run stdout: %v\n%s", err, stdout)
}
if len(got.API) != 0 || got.Command != docsScriptMarkdownToXML || got.Network || got.Output != "draft.xml" || !got.Overwrite {
t.Fatalf("dry-run output = %+v", got)
}
if _, err := os.Stat("draft.xml"); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("dry-run created output file: %v", err)
}
}
func TestDocsScriptReturnsTypedParseError(t *testing.T) {
f, _, _, _ := cmdutil.TestFactory(t, docsTestConfigWithAppID("docs-script-error"))
err := mountAndRunDocs(t, DocsScript, []string{
"+script",
"--command", docsScriptParse,
"--content", `<!DOCTYPE document><p>text</p>`,
"--as", "bot",
}, f, nil)
if err == nil {
t.Fatal("expected parse error")
}
problem, ok := errs.ProblemOf(err)
if !ok || problem.Category != errs.CategoryValidation || problem.Subtype != errs.SubtypeInvalidArgument {
t.Fatalf("problem = %+v, ok=%v", problem, ok)
}
var validationErr *errs.ValidationError
if !errors.As(err, &validationErr) || validationErr.Param != "--content" {
t.Fatalf("error = %#v, want --content metadata", err)
}
}
func TestDocsScriptRejectsMalformedXML(t *testing.T) {
f, _, _, _ := cmdutil.TestFactory(t, docsTestConfigWithAppID("docs-script-malformed"))
err := mountAndRunDocs(t, DocsScript, []string{
"+script",
"--command", docsScriptParse,
"--content", `<p>text`,
"--as", "bot",
}, f, nil)
if err == nil {
t.Fatal("expected malformed XML error")
}
problem, ok := errs.ProblemOf(err)
if !ok || problem.Category != errs.CategoryValidation || problem.Subtype != errs.SubtypeInvalidArgument {
t.Fatalf("problem = %+v, ok=%v", problem, ok)
}
}
func TestDocsScriptHelpExamplesAreCrossShellSafe(t *testing.T) {
cmd := &cobra.Command{Short: "local document parser"}
installDocsScriptHelp(cmd)
if strings.Contains(cmd.Example, "cat ") {
t.Fatalf("help examples require a platform-specific command: %q", cmd.Example)
}
if strings.Contains(cmd.Example, "--content @") {
t.Fatalf("help examples contain an unquoted @file argument: %q", cmd.Example)
}
for _, want := range []string{`--command create-temp-xml --file-name "draft"`, `--content "@draft.xml"`, `--content "@draft.md"`, `--output "draft.xml"`} {
if !strings.Contains(cmd.Example, want) {
t.Errorf("help examples missing %q: %q", want, cmd.Example)
}
}
}
func blockCount(blocks []docxparse.BlockShare, typ string) int {
for _, block := range blocks {
if block.Type == typ {
return block.Count
}
}
return 0
}

View File

@@ -0,0 +1,743 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package docxparse
// Markdown conversion is scoped to the docs +script business domain.
import (
"fmt"
"strings"
"github.com/yuin/goldmark"
gast "github.com/yuin/goldmark/ast"
"github.com/yuin/goldmark/extension"
extast "github.com/yuin/goldmark/extension/ast"
"github.com/yuin/goldmark/parser"
"github.com/yuin/goldmark/text"
gmutil "github.com/yuin/goldmark/util"
)
var markdownParser parser.Parser
func init() {
markdown := goldmark.New(
goldmark.WithExtensions(
extension.GFM,
extension.DefinitionList,
&mathExtension{},
&underscoreHTMLExtension{},
),
goldmark.WithParserOptions(
parser.WithBlockParsers(gmutil.Prioritized(&containerBlockParser{}, 90)),
),
)
markdownParser = markdown.Parser()
}
func parseMarkdown(source string) ([]*Node, error) {
if err := validateSource(source); err != nil {
return nil, err
}
source = strings.TrimPrefix(source, "\uFEFF")
source = normalizeListIndent(source)
source = preprocessCJKAdjacentMarkup(source)
data := []byte(source)
document := markdownParser.Parse(text.NewReader(data))
return renderBlockChildren(document, data)
}
func renderBlockChildren(parent gast.Node, source []byte) ([]*Node, error) {
var out []*Node
for child := parent.FirstChild(); child != nil; child = child.NextSibling() {
nodes, err := renderBlockNode(child, source)
if err != nil {
return nil, err
}
out = append(out, nodes...)
}
return out, nil
}
func renderBlockNode(node gast.Node, source []byte) ([]*Node, error) {
switch node.Kind() {
case gast.KindParagraph, gast.KindTextBlock:
children, err := renderInlineChildren(node, source)
if err != nil {
return nil, err
}
return wrapParagraphChildren(children), nil
case gast.KindHeading:
heading := newElement(headingTag(node.(*gast.Heading).Level), nil)
children, err := renderInlineChildren(node, source)
if err != nil {
return nil, err
}
for _, child := range children {
heading.addChild(child)
}
return []*Node{heading}, nil
case gast.KindBlockquote:
return renderContainer("blockquote", nil, node, source)
case gast.KindList:
return renderList(node.(*gast.List), source)
case gast.KindFencedCodeBlock:
block := node.(*gast.FencedCodeBlock)
language := string(block.Language(source))
content := trimOneTrailingNewline(string(node.Lines().Value(source)))
lowerLanguage := strings.ToLower(language)
if content != "" && (lowerLanguage == "mermaid" || lowerLanguage == "plantuml" || lowerLanguage == "svg") {
whiteboard := newElement("whiteboard", map[string]string{"type": lowerLanguage})
appendRawTextWithBreaks(whiteboard, content)
return []*Node{whiteboard}, nil
}
attrs := map[string]string(nil)
if language != "" {
attrs = map[string]string{"lang": language}
}
pre := newElement("pre", attrs)
code := newElement("code", nil)
appendRawTextWithBreaks(code, content)
pre.addChild(code)
return []*Node{pre}, nil
case gast.KindCodeBlock:
pre := newElement("pre", nil)
code := newElement("code", nil)
appendRawTextWithBreaks(code, trimOneTrailingNewline(string(node.Lines().Value(source))))
pre.addChild(code)
return []*Node{pre}, nil
case gast.KindThematicBreak:
return []*Node{newElement("hr", nil)}, nil
case gast.KindHTMLBlock:
nodes, err := parseMarkdownHTMLBlock(string(node.Lines().Value(source)))
if err != nil {
return nil, err
}
stripMarkdownEscapesInNodes(nodes, false, false)
return nodes, nil
case kindContainerBlock:
container := node.(*containerBlock)
return renderContainer(container.spec.tag, container.attrs, node, source)
}
switch node.Kind() {
case extast.KindTable:
return renderTable(node, source)
case extast.KindDefinitionList:
return renderDefinitionList(node, source)
}
value := strings.TrimSpace(extractMarkdownText(node, source))
if value == "" {
return nil, nil
}
paragraph := newElement("p", nil)
paragraph.addChild(newText(value))
return []*Node{paragraph}, nil
}
// parseMarkdownHTMLBlock handles the source-bearing LarkOpenCLI blocks whose
// Markdown bodies are literal text, then delegates every other XML fragment to
// the strict XML parser. Escaping literal code is part of Markdown conversion.
func parseMarkdownHTMLBlock(fragment string) ([]*Node, error) {
trimmed := strings.TrimSpace(fragment)
for _, tag := range []string{"code", "whiteboard"} {
closing := "</" + tag + ">"
if !strings.HasPrefix(trimmed, "<"+tag) || !strings.HasSuffix(trimmed, closing) {
continue
}
token, contentStart, state := scanXMLToken(trimmed, 0)
if state != tokenOK || token.closing || token.selfClosing || token.name != tag {
return nil, fmt.Errorf("invalid Markdown <%s> block", tag)
}
contentEnd := len(trimmed) - len(closing)
if contentStart > contentEnd {
return nil, fmt.Errorf("invalid Markdown <%s> block", tag)
}
attrs := normalizeAttributes(tag, tag, token.attrs)
block := newElement(tag, attrs)
appendRawTextWithBreaks(block, strings.Trim(trimmed[contentStart:contentEnd], "\r\n"))
return []*Node{block}, nil
}
return parseXML(fragment)
}
func renderContainer(tag string, attrs map[string]string, node gast.Node, source []byte) ([]*Node, error) {
attrs = normalizeAttributes(tag, tag, attrs)
container := newElement(tag, attrs)
children, err := renderBlockChildren(node, source)
if err != nil {
return nil, err
}
for _, child := range children {
container.addChild(child)
}
return []*Node{container}, nil
}
func renderList(list *gast.List, source []byte) ([]*Node, error) {
if isTaskList(list) {
return renderTaskList(list, source)
}
tag := "ul"
if list.IsOrdered() {
tag = "ol"
}
listNode := newElement(tag, nil)
for child := list.FirstChild(); child != nil; child = child.NextSibling() {
if child.Kind() != gast.KindListItem {
continue
}
item, err := renderListItem(child.(*gast.ListItem), list.IsTight, source)
if err != nil {
return nil, err
}
listNode.addChild(item)
}
return []*Node{listNode}, nil
}
func isTaskList(list *gast.List) bool {
first := list.FirstChild()
if first == nil || first.Kind() != gast.KindListItem {
return false
}
return findTaskCheckbox(first.(*gast.ListItem)) != nil
}
func findTaskCheckbox(item *gast.ListItem) *extast.TaskCheckBox {
for child := item.FirstChild(); child != nil; child = child.NextSibling() {
if child.Kind() != gast.KindTextBlock && child.Kind() != gast.KindParagraph {
continue
}
if first := child.FirstChild(); first != nil && first.Kind() == extast.KindTaskCheckBox {
return first.(*extast.TaskCheckBox)
}
}
return nil
}
func renderTaskList(list *gast.List, source []byte) ([]*Node, error) {
var out []*Node
for child := list.FirstChild(); child != nil; child = child.NextSibling() {
if child.Kind() != gast.KindListItem {
continue
}
item := child.(*gast.ListItem)
checkboxAST := findTaskCheckbox(item)
if checkboxAST == nil {
li, err := renderListItem(item, list.IsTight, source)
if err != nil {
return nil, err
}
ul := newElement("ul", nil)
ul.addChild(li)
out = append(out, ul)
continue
}
done := "false"
if checkboxAST.IsChecked {
done = "true"
}
checkbox := newElement("checkbox", map[string]string{"done": done})
for block := item.FirstChild(); block != nil; block = block.NextSibling() {
if block.Kind() == gast.KindTextBlock || block.Kind() == gast.KindParagraph {
fragment, err := renderInlineFragment(block, source, true)
if err != nil {
return nil, err
}
nodes, err := parseMarkdownInlineFragment(fragment)
if err != nil {
return nil, err
}
for _, node := range nodes {
checkbox.addChild(node)
}
continue
}
nodes, err := renderBlockNode(block, source)
if err != nil {
return nil, err
}
for _, node := range nodes {
checkbox.addChild(node)
}
}
out = append(out, checkbox)
}
return out, nil
}
func renderListItem(item *gast.ListItem, tight bool, source []byte) (*Node, error) {
li := newElement("li", nil)
children, err := renderBlockChildren(item, source)
if err != nil {
return nil, err
}
for _, child := range children {
if child.tag == "p" && (tight || paragraphOnlyInline(child)) {
for _, grandchild := range child.children {
li.addChild(grandchild)
}
continue
}
li.addChild(child)
}
return li, nil
}
func renderInlineChildren(node gast.Node, source []byte) ([]*Node, error) {
fragment, err := renderInlineFragment(node, source, false)
if err != nil {
return nil, err
}
nodes, err := parseMarkdownInlineFragment(fragment)
if err != nil {
return nil, err
}
stripMarkdownEscapesInNodes(nodes, false, false)
return nodes, nil
}
// parseMarkdownInlineFragment wraps an inline fragment in a space-preserving
// parent while parsing so XML normalization keeps semantic spaces between
// adjacent inline elements. The wrapper is removed from the returned nodes.
func parseMarkdownInlineFragment(fragment string) ([]*Node, error) {
nodes, err := parseXML("<p>" + fragment + "</p>")
if err != nil {
return nil, err
}
if len(nodes) != 1 || nodes[0].typ != nodeElement || nodes[0].tag != "p" {
return nil, fmt.Errorf("invalid Markdown inline fragment")
}
children := nodes[0].children
for _, child := range children {
child.parent = nil
}
return children, nil
}
func renderInlineFragment(parent gast.Node, source []byte, skipCheckbox bool) (string, error) {
var out strings.Builder
for child := parent.FirstChild(); child != nil; child = child.NextSibling() {
if skipCheckbox && child.Kind() == extast.KindTaskCheckBox {
continue
}
fragment, err := renderInlineNode(child, source)
if err != nil {
return "", err
}
out.WriteString(fragment)
}
return out.String(), nil
}
func renderInlineNode(node gast.Node, source []byte) (string, error) {
switch node.Kind() {
case gast.KindText:
textNode := node.(*gast.Text)
value := escapeXMLText(stripBackslashEscapes(string(textNode.Value(source))))
switch {
case textNode.HardLineBreak():
value += "<br/>"
case textNode.SoftLineBreak():
value += " "
}
return value, nil
case gast.KindString:
return escapeXMLText(string(node.(*gast.String).Value)), nil
case gast.KindEmphasis:
tag := "em"
if node.(*gast.Emphasis).Level >= 2 {
tag = "b"
}
return renderInlineContainer(node, tag, nil, source)
case gast.KindCodeSpan:
return elementXML("code", nil, escapeXMLText(collectMarkdownChildText(node, source))), nil
case gast.KindLink:
link := node.(*gast.Link)
attrs := map[string]string{"href": string(link.Destination)}
if len(link.Title) > 0 {
attrs["title"] = string(link.Title)
}
children, err := renderInlineFragment(node, source, false)
if err != nil {
return "", err
}
if children == "" {
children = escapeXMLText(string(link.Destination))
}
return elementXML("a", attrs, children), nil
case gast.KindImage:
image := node.(*gast.Image)
destination := string(image.Destination)
attrs := map[string]string{}
if strings.HasPrefix(destination, "http://") || strings.HasPrefix(destination, "https://") {
attrs["href"] = destination
} else {
attrs["src"] = destination
}
if len(image.Title) > 0 {
attrs["title"] = string(image.Title)
}
return elementXML("img", attrs, ""), nil
case gast.KindRawHTML:
return string(node.(*gast.RawHTML).Segments.Value(source)), nil
case gast.KindAutoLink:
link := node.(*gast.AutoLink)
return elementXML("a", map[string]string{"href": string(link.URL(source))}, escapeXMLText(string(link.Label(source)))), nil
}
switch node.Kind() {
case extast.KindStrikethrough:
return renderInlineContainer(node, "del", nil, source)
case kindMathInline:
return elementXML("latex", nil, escapeXMLText(stripLatexMarkdownEscapes(string(node.(*mathInline).content)))), nil
case kindMathBlock:
return elementXML("latex", nil, escapeXMLText(stripLatexMarkdownEscapes(string(node.(*mathBlock).content)))), nil
case extast.KindTaskCheckBox:
return "", nil
}
if node.Type() == gast.TypeBlock {
return escapeXMLText(strings.TrimSpace(extractMarkdownText(node, source))), nil
}
return escapeXMLText(extractMarkdownText(node, source)), nil
}
func renderInlineContainer(node gast.Node, tag string, attrs map[string]string, source []byte) (string, error) {
children, err := renderInlineFragment(node, source, false)
if err != nil {
return "", err
}
return elementXML(tag, attrs, children), nil
}
func elementXML(tag string, attrs map[string]string, inner string) string {
node := newElement(tag, attrs)
rendered := renderNodes([]*Node{node})
if inner == "" {
return rendered
}
close := "</" + tag + ">"
if strings.HasSuffix(rendered, close) {
return strings.TrimSuffix(rendered, close) + inner + close
}
return rendered
}
func wrapParagraphChildren(children []*Node) []*Node {
var out []*Node
var inline []*Node
flush := func() {
if len(inline) == 0 {
return
}
paragraph := newElement("p", nil)
for _, child := range inline {
paragraph.addChild(child)
}
out = append(out, paragraph)
inline = nil
}
for _, child := range children {
if child != nil && child.typ == nodeElement && layoutOf(child.tag) == layoutBlock {
flush()
out = append(out, child)
continue
}
inline = append(inline, child)
}
flush()
return out
}
func paragraphOnlyInline(node *Node) bool {
if node == nil || node.typ != nodeElement || node.tag != "p" {
return false
}
for _, child := range node.children {
if child.typ == nodeElement && layoutOf(child.tag) == layoutBlock {
return false
}
}
return true
}
func renderTable(node gast.Node, source []byte) ([]*Node, error) {
table := newElement("table", nil)
var body *Node
for child := node.FirstChild(); child != nil; child = child.NextSibling() {
switch child.Kind() {
case extast.KindTableHeader:
head := newElement("thead", nil)
row, err := renderTableRow(child, true, source)
if err != nil {
return nil, err
}
head.addChild(row)
table.addChild(head)
case extast.KindTableRow:
if body == nil {
body = newElement("tbody", nil)
table.addChild(body)
}
row, err := renderTableRow(child, false, source)
if err != nil {
return nil, err
}
body.addChild(row)
}
}
return []*Node{table}, nil
}
func renderTableRow(node gast.Node, header bool, source []byte) (*Node, error) {
row := newElement("tr", nil)
for child := node.FirstChild(); child != nil; child = child.NextSibling() {
if child.Kind() != extast.KindTableCell {
continue
}
cellAST := child.(*extast.TableCell)
tag := "td"
if header {
tag = "th"
}
attrs := map[string]string(nil)
switch cellAST.Alignment {
case extast.AlignCenter:
attrs = map[string]string{"align": "center"}
case extast.AlignRight:
attrs = map[string]string{"align": "right"}
}
cell := newElement(tag, attrs)
content, err := renderInlineChildren(cellAST, source)
if err != nil {
return nil, err
}
for _, inline := range content {
cell.addChild(inline)
}
row.addChild(cell)
}
return row, nil
}
func renderDefinitionList(node gast.Node, source []byte) ([]*Node, error) {
var out []*Node
for child := node.FirstChild(); child != nil; child = child.NextSibling() {
switch child.Kind() {
case extast.KindDefinitionTerm:
fragment, err := renderInlineFragment(child, source, false)
if err != nil {
return nil, err
}
nodes, err := parseXML(fragment)
if err != nil {
return nil, err
}
paragraph := newElement("p", nil)
bold := newElement("b", nil)
for _, node := range nodes {
bold.addChild(node)
}
paragraph.addChild(bold)
out = append(out, paragraph)
case extast.KindDefinitionDescription:
quote, err := renderContainer("blockquote", nil, child, source)
if err != nil {
return nil, err
}
out = append(out, quote...)
}
}
return out, nil
}
func appendRawTextWithBreaks(parent *Node, content string) {
if content == "" {
return
}
start := 0
for i := 0; i < len(content); i++ {
if content[i] != '\n' && content[i] != '\r' {
continue
}
if i > start {
parent.addChild(newText(content[start:i]))
}
if content[i] == '\r' && i+1 < len(content) && content[i+1] == '\n' {
i++
}
parent.addChild(newElement("br", nil))
start = i + 1
}
if start < len(content) {
parent.addChild(newText(content[start:]))
}
}
func stripMarkdownEscapesInNodes(nodes []*Node, inCode, inLatex bool) {
for _, node := range nodes {
if node == nil {
continue
}
if node.typ == nodeText {
switch {
case inCode:
case inLatex:
node.text = stripLatexMarkdownEscapes(node.text)
default:
node.text = stripBackslashEscapes(node.text)
}
continue
}
stripMarkdownEscapesInNodes(node.children, inCode || node.tag == "code" || node.tag == "pre", inLatex || node.tag == "latex")
}
}
func stripBackslashEscapes(value string) string {
if !strings.Contains(value, `\`) {
return value
}
var out strings.Builder
out.Grow(len(value))
for i := 0; i < len(value); i++ {
if value[i] == '\\' && i+1 < len(value) && isASCIIPunctuation(value[i+1]) {
out.WriteByte(value[i+1])
i++
continue
}
out.WriteByte(value[i])
}
return out.String()
}
func stripLatexMarkdownEscapes(value string) string {
if !strings.Contains(value, `\`) {
return value
}
var out strings.Builder
out.Grow(len(value))
for i := 0; i < len(value); i++ {
if value[i] == '\\' && i+1 < len(value) && strings.ContainsRune("_^&*[]$~<>`#+-=:", rune(value[i+1])) {
out.WriteByte(value[i+1])
i++
continue
}
out.WriteByte(value[i])
}
return out.String()
}
func isASCIIPunctuation(ch byte) bool {
return ch >= '!' && ch <= '/' || ch >= ':' && ch <= '@' || ch >= '[' && ch <= '`' || ch >= '{' && ch <= '~'
}
func trimOneTrailingNewline(value string) string {
if strings.HasSuffix(value, "\r\n") {
return value[:len(value)-2]
}
return strings.TrimSuffix(value, "\n")
}
func collectMarkdownChildText(node gast.Node, source []byte) string {
var out strings.Builder
for child := node.FirstChild(); child != nil; child = child.NextSibling() {
switch child.Kind() {
case gast.KindText:
out.Write(child.(*gast.Text).Value(source))
case gast.KindString:
out.Write(child.(*gast.String).Value)
default:
out.WriteString(collectMarkdownChildText(child, source))
}
}
return out.String()
}
func extractMarkdownText(node gast.Node, source []byte) string {
switch node.Kind() {
case gast.KindText:
return string(node.(*gast.Text).Value(source))
case gast.KindString:
return string(node.(*gast.String).Value)
case gast.KindCodeSpan:
return collectMarkdownChildText(node, source)
}
if node.Type() == gast.TypeBlock && node.Lines() != nil && node.Lines().Len() > 0 {
return string(node.Lines().Value(source))
}
var out strings.Builder
for child := node.FirstChild(); child != nil; child = child.NextSibling() {
out.WriteString(extractMarkdownText(child, source))
}
return out.String()
}
func headingTag(level int) string {
if level < 1 || level > 6 {
return "p"
}
return fmt.Sprintf("h%d", level)
}
func normalizeListIndent(markdown string) string {
lines := strings.Split(markdown, "\n")
type stackEntry struct{ indent int }
var stack []stackEntry
inFence := false
changed := false
lastOriginal, lastNormalized := 0, 0
for i, line := range lines {
trimmed := strings.TrimLeft(line, " ")
if strings.HasPrefix(trimmed, "```") || strings.HasPrefix(trimmed, "~~~") {
inFence = !inFence
continue
}
if inFence || trimmed == "" {
continue
}
indent := len(line) - len(trimmed)
if markdownListMarkerLength(trimmed) > 0 {
for len(stack) > 0 && indent <= stack[len(stack)-1].indent {
stack = stack[:len(stack)-1]
}
normalized := len(stack) * 4
stack = append(stack, stackEntry{indent: indent})
lastOriginal, lastNormalized = indent, normalized
if indent != normalized {
lines[i] = strings.Repeat(" ", normalized) + trimmed
changed = true
}
} else if len(stack) > 0 && indent > lastOriginal {
delta := lastNormalized - lastOriginal
if delta != 0 {
normalized := indent + delta
if normalized < 0 {
normalized = 0
}
lines[i] = strings.Repeat(" ", normalized) + trimmed
changed = true
}
}
}
if !changed {
return markdown
}
return strings.Join(lines, "\n")
}
func markdownListMarkerLength(value string) int {
if len(value) >= 2 && (value[0] == '-' || value[0] == '*' || value[0] == '+') && value[1] == ' ' {
return 2
}
i := 0
for i < len(value) && value[i] >= '0' && value[i] <= '9' {
i++
}
if i > 0 && i+1 < len(value) && (value[i] == '.' || value[i] == ')') && value[i+1] == ' ' {
return i + 2
}
return 0
}

View File

@@ -0,0 +1,284 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package docxparse
import (
"strings"
"unicode"
)
// preprocessCJKAdjacentMarkup disambiguates a narrow CommonMark pattern common in
// Chinese prose: emphasis that ends in punctuation and is immediately followed
// by a letter (for example **结论。**下一步). Goldmark correctly follows
// CommonMark's delimiter rules, while LarkOpenCLI accepts this authoring form.
// Rewriting simple CJK delimiter spans to equivalent DocxXML
// before parsing removes the ambiguity while leaving nested Markdown, links,
// code, fenced blocks, and source-bearing XML untouched.
func preprocessCJKAdjacentMarkup(markdown string) string {
if !strings.Contains(markdown, "**") && !strings.Contains(markdown, "~~") {
return markdown
}
lines := strings.SplitAfter(markdown, "\n")
var out strings.Builder
fenceMarker := rune(0)
fenceLength := 0
rawSourceTag := ""
for _, line := range lines {
trimmed := strings.TrimLeft(line, " \t>")
if marker, length, ok := markdownFence(trimmed); ok {
if fenceMarker == 0 {
fenceMarker, fenceLength = marker, length
} else if marker == fenceMarker && length >= fenceLength && strings.TrimSpace(runeTail(trimmed, length)) == "" {
fenceMarker, fenceLength = 0, 0
}
out.WriteString(line)
continue
}
if fenceMarker != 0 || leadingIndent(line) >= 4 {
out.WriteString(line)
continue
}
out.WriteString(rewriteCJKMarkupLine(line, &rawSourceTag))
}
return out.String()
}
func markdownFence(line string) (rune, int, bool) {
runes := []rune(line)
if len(runes) < 3 || runes[0] != '`' && runes[0] != '~' {
return 0, 0, false
}
marker := runes[0]
length := 0
for length < len(runes) && runes[length] == marker {
length++
}
return marker, length, length >= 3
}
func runeTail(value string, start int) string {
runes := []rune(value)
if start >= len(runes) {
return ""
}
return string(runes[start:])
}
func leadingIndent(line string) int {
count := 0
for _, r := range line {
switch r {
case ' ':
count++
case '\t':
count += 4
default:
return count
}
}
return count
}
type cjkMarkupRule struct {
delimiter []rune
openXML string
closeXML string
}
var cjkMarkupRules = []cjkMarkupRule{
{delimiter: []rune("***"), openXML: "<em><b>", closeXML: "</b></em>"},
{delimiter: []rune("~~"), openXML: "<del>", closeXML: "</del>"},
{delimiter: []rune("**"), openXML: "<b>", closeXML: "</b>"},
}
func rewriteCJKMarkupLine(line string, rawSourceTag *string) string {
if *rawSourceTag != "" {
runes := []rune(line)
closeTag := []rune("</" + *rawSourceTag + ">")
closeAt := indexRunesFold(runes, 0, closeTag)
if closeAt < 0 {
return line
}
closeEnd := closeAt + len(closeTag)
prefix := string(runes[:closeEnd])
*rawSourceTag = ""
return prefix + rewriteCJKMarkupLine(string(runes[closeEnd:]), rawSourceTag)
}
runes := []rune(line)
var out strings.Builder
for i := 0; i < len(runes); {
if runes[i] == '`' && !runeEscaped(runes, i) {
if end := codeSpanEnd(runes, i); end > i {
out.WriteString(string(runes[i:end]))
i = end
continue
}
}
if runes[i] == '<' {
if tag, end, selfClosing, ok := rawTagAt(runes, i); ok {
out.WriteString(string(runes[i:end]))
i = end
if !selfClosing && (tag == "code" || tag == "pre" || tag == "whiteboard") {
close := []rune("</" + tag + ">")
if closeAt := indexRunesFold(runes, i, close); closeAt >= 0 {
closeEnd := closeAt + len(close)
out.WriteString(string(runes[i:closeEnd]))
i = closeEnd
} else {
out.WriteString(string(runes[i:]))
*rawSourceTag = tag
return out.String()
}
}
continue
}
}
rewritten := false
for _, rule := range cjkMarkupRules {
if !exactDelimiterAt(runes, i, rule.delimiter) || runeEscaped(runes, i) {
continue
}
closeAt := delimiterCloser(runes, i+len(rule.delimiter), rule.delimiter)
if closeAt < 0 {
continue
}
content := runes[i+len(rule.delimiter) : closeAt]
if !shouldRewriteCJKMarkup(content) {
continue
}
out.WriteString(rule.openXML)
out.WriteString(escapeXMLText(stripBackslashEscapes(string(content))))
out.WriteString(rule.closeXML)
i = closeAt + len(rule.delimiter)
rewritten = true
break
}
if rewritten {
continue
}
out.WriteRune(runes[i])
i++
}
return out.String()
}
func rawTagAt(runes []rune, start int) (tag string, end int, selfClosing, ok bool) {
if start+1 >= len(runes) || !isASCIILetterRune(runes[start+1]) {
return "", 0, false, false
}
i := start + 1
for i < len(runes) && (isASCIILetterRune(runes[i]) || isASCIIDigitRune(runes[i]) || runes[i] == '-' || runes[i] == '_') {
i++
}
tag = strings.ToLower(string(runes[start+1 : i]))
quote := rune(0)
for ; i < len(runes); i++ {
if runes[i] == '\'' || runes[i] == '"' {
if quote == 0 {
quote = runes[i]
} else if quote == runes[i] {
quote = 0
}
continue
}
if runes[i] == '>' && quote == 0 {
trimmed := strings.TrimSpace(string(runes[start : i+1]))
return tag, i + 1, strings.HasSuffix(trimmed, "/>"), true
}
}
return "", 0, false, false
}
func indexRunesFold(haystack []rune, start int, needle []rune) int {
for i := start; i+len(needle) <= len(haystack); i++ {
if strings.EqualFold(string(haystack[i:i+len(needle)]), string(needle)) {
return i
}
}
return -1
}
func codeSpanEnd(runes []rune, open int) int {
length := 0
for open+length < len(runes) && runes[open+length] == '`' {
length++
}
for i := open + length; i < len(runes); i++ {
if runes[i] != '`' || runeEscaped(runes, i) {
continue
}
end := i
for end < len(runes) && runes[end] == '`' {
end++
}
if end-i == length {
return end
}
i = end - 1
}
return -1
}
func exactDelimiterAt(runes []rune, start int, delimiter []rune) bool {
if start+len(delimiter) > len(runes) {
return false
}
for i, want := range delimiter {
if runes[start+i] != want {
return false
}
}
marker := delimiter[0]
return (start == 0 || runes[start-1] != marker) && (start+len(delimiter) == len(runes) || runes[start+len(delimiter)] != marker)
}
func delimiterCloser(runes []rune, start int, delimiter []rune) int {
for i := start; i+len(delimiter) <= len(runes); i++ {
if runes[i] == '\n' {
return -1
}
if exactDelimiterAt(runes, i, delimiter) && !runeEscaped(runes, i) {
return i
}
}
return -1
}
func shouldRewriteCJKMarkup(content []rune) bool {
if len(content) == 0 || unicode.IsSpace(content[0]) || unicode.IsSpace(content[len(content)-1]) {
return false
}
for _, r := range content {
if r == '`' || r == '[' || r == ']' || r == '<' || r == '>' {
return false
}
}
if !containsCJK(content) {
return false
}
return true
}
func containsCJK(value []rune) bool {
for _, r := range value {
if isCJKRune(r) || r > unicode.MaxASCII && (unicode.IsPunct(r) || unicode.IsSymbol(r)) {
return true
}
}
return false
}
func isCJKRune(r rune) bool {
return unicode.In(r, unicode.Han, unicode.Hiragana, unicode.Katakana, unicode.Hangul)
}
func runeEscaped(runes []rune, index int) bool {
count := 0
for i := index - 1; i >= 0 && runes[i] == '\\'; i-- {
count++
}
return count%2 == 1
}

View File

@@ -0,0 +1,334 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package docxparse
// This file contains the small Goldmark extensions needed to match the
// LarkOpenCLI's Markdown surface: math, DocxXML tag names containing
// underscores, and Markdown-aware callout/grid/column containers.
import (
"bytes"
"regexp"
"strings"
"github.com/yuin/goldmark"
gast "github.com/yuin/goldmark/ast"
"github.com/yuin/goldmark/parser"
"github.com/yuin/goldmark/text"
gmutil "github.com/yuin/goldmark/util"
)
// ---------- Math ----------
var kindMathInline = gast.NewNodeKind("DocxMathInline")
var kindMathBlock = gast.NewNodeKind("DocxMathBlock")
type mathInline struct {
gast.BaseInline
content []byte
}
func (n *mathInline) Kind() gast.NodeKind { return kindMathInline }
func (n *mathInline) Dump(source []byte, level int) {
gast.DumpHelper(n, source, level, nil, nil)
}
type mathBlock struct {
gast.BaseInline
content []byte
}
func (n *mathBlock) Kind() gast.NodeKind { return kindMathBlock }
func (n *mathBlock) Dump(source []byte, level int) {
gast.DumpHelper(n, source, level, nil, nil)
}
var (
mathBlockMultiLine = regexp.MustCompile(`(?s)^\$\$(.+?)\$\$`)
mathInlineMultiLine = regexp.MustCompile(`(?s)^\$([^ \t$].*?)\$`)
)
type mathInlineParser struct{}
func (p *mathInlineParser) Trigger() []byte { return []byte{'$'} }
func (p *mathInlineParser) Parse(_ gast.Node, reader text.Reader, _ parser.Context) gast.Node {
line, _ := reader.PeekLine()
if len(line) == 0 || line[0] != '$' {
return nil
}
if len(line) >= 2 && line[1] == '$' {
if content, advance := scanMathClose(line[2:], "$$"); advance >= 0 && len(content) > 0 {
reader.Advance(2 + advance)
return &mathBlock{content: append([]byte(nil), content...)}
}
match := reader.FindSubMatch(mathBlockMultiLine)
if len(match) >= 2 && len(bytes.TrimSpace(match[1])) > 0 && !bytes.Contains(match[1], []byte("<latex")) {
return &mathBlock{content: append([]byte(nil), bytes.TrimSpace(match[1])...)}
}
return nil
}
if len(line) < 2 || line[1] == ' ' || line[1] == '\t' || line[1] == '$' {
return nil
}
if content, advance := scanMathClose(line[1:], "$"); advance >= 0 && len(content) > 0 {
if content[len(content)-1] == ' ' || content[len(content)-1] == '\t' {
return nil
}
reader.Advance(1 + advance)
return &mathInline{content: append([]byte(nil), content...)}
}
match := reader.FindSubMatch(mathInlineMultiLine)
if len(match) < 2 || bytes.Contains(match[1], []byte("<latex")) {
return nil
}
trimmed := bytes.TrimRight(match[1], "\n\r")
if len(trimmed) == 0 || trimmed[len(trimmed)-1] == ' ' || trimmed[len(trimmed)-1] == '\t' {
return nil
}
return &mathInline{content: append([]byte(nil), trimmed...)}
}
func scanMathClose(data []byte, delimiter string) ([]byte, int) {
delim := []byte(delimiter)
for offset := 0; offset < len(data); {
if data[offset] == '\\' && offset+1 < len(data) && data[offset+1] == '$' {
offset += 2
continue
}
rel := bytes.Index(data[offset:], delim)
if rel < 0 {
return nil, -1
}
end := offset + rel
if bytes.Contains(data[:end], []byte("<latex")) {
return nil, -1
}
return data[:end], end + len(delim)
}
return nil, -1
}
type mathExtension struct{}
func (e *mathExtension) Extend(markdown goldmark.Markdown) {
markdown.Parser().AddOptions(parser.WithInlineParsers(
gmutil.Prioritized(&mathInlineParser{}, 100),
))
}
// ---------- Underscore-bearing raw XML tags ----------
type underscoreHTMLExtension struct{}
func (e *underscoreHTMLExtension) Extend(markdown goldmark.Markdown) {
markdown.Parser().AddOptions(
parser.WithInlineParsers(gmutil.Prioritized(&underscoreRawHTMLParser{}, 99)),
parser.WithBlockParsers(gmutil.Prioritized(&underscoreHTMLBlockParser{}, 99)),
)
}
var (
extendedTagNamePattern = `([A-Za-z][A-Za-z0-9_-]*)`
extendedAttributePattern = `(?:\s+[a-zA-Z_:][a-zA-Z0-9:._-]*(?:\s*=\s*(?:[^"'=<>` + "`" + `\x00-\x20]+|'[^']*'|"[^"]*"))?)`
extendedOpenTag = regexp.MustCompile("^<" + extendedTagNamePattern + extendedAttributePattern + `*\s*/?>`)
extendedCloseTag = regexp.MustCompile("^</" + extendedTagNamePattern + `\s*>`)
peekExtendedOpenTag = regexp.MustCompile(`^<([A-Za-z][A-Za-z0-9_-]*)`)
peekExtendedCloseTag = regexp.MustCompile(`^</([A-Za-z][A-Za-z0-9_-]*)`)
extendedBlockTag = regexp.MustCompile(`^[ ]{0,3}<(/)?\s*([a-zA-Z0-9_\-]+)(` + extendedAttributePattern + `*)\s*(?:>|/>)\s*\n?$`)
)
type underscoreRawHTMLParser struct{}
func (p *underscoreRawHTMLParser) Trigger() []byte { return []byte{'<'} }
func (p *underscoreRawHTMLParser) Parse(_ gast.Node, reader text.Reader, _ parser.Context) gast.Node {
line, _ := reader.PeekLine()
if len(line) > 1 && gmutil.IsAlphaNumeric(line[1]) {
if match := peekExtendedOpenTag.FindSubmatch(line); match != nil && bytes.IndexByte(match[1], '_') >= 0 {
return p.parseMultiLine(extendedOpenTag, reader)
}
return nil
}
if len(line) > 2 && line[1] == '/' && gmutil.IsAlphaNumeric(line[2]) {
if match := peekExtendedCloseTag.FindSubmatch(line); match != nil && bytes.IndexByte(match[1], '_') >= 0 {
return p.parseMultiLine(extendedCloseTag, reader)
}
}
return nil
}
func (p *underscoreRawHTMLParser) parseMultiLine(re *regexp.Regexp, reader text.Reader) gast.Node {
startLine, startSegment := reader.Position()
if !reader.Match(re) {
return nil
}
endLine, endSegment := reader.Position()
reader.SetPosition(startLine, startSegment)
node := gast.NewRawHTML()
for {
line, segment := reader.PeekLine()
if line == nil {
break
}
lineNo, _ := reader.Position()
start := segment.Start
if lineNo == startLine {
start = startSegment.Start
}
end := segment.Stop
if lineNo == endLine {
end = endSegment.Start
}
node.Segments.Append(text.NewSegment(start, end))
if lineNo == endLine {
reader.Advance(end - start)
break
}
reader.AdvanceLine()
}
return node
}
type underscoreHTMLBlockParser struct{}
func (p *underscoreHTMLBlockParser) Trigger() []byte { return []byte{'<'} }
func (p *underscoreHTMLBlockParser) Open(_ gast.Node, reader text.Reader, pc parser.Context) (gast.Node, parser.State) {
line, segment := reader.PeekLine()
pos := pc.BlockOffset()
if pos < 0 || pos >= len(line) || line[pos] != '<' {
return nil, parser.NoChildren
}
match := extendedBlockTag.FindSubmatchIndex(line)
if match == nil {
return nil, parser.NoChildren
}
tag := string(line[match[4]:match[5]])
if !strings.Contains(tag, "_") {
return nil, parser.NoChildren
}
isClose := match[2] > -1 && bytes.Equal(line[match[2]:match[3]], []byte("/"))
hasAttrs := match[6] != match[7]
if isClose && hasAttrs {
return nil, parser.NoChildren
}
node := gast.NewHTMLBlock(gast.HTMLBlockType7)
node.Lines().Append(segment)
reader.Advance(segment.Len() - 1)
return node, parser.NoChildren
}
func (p *underscoreHTMLBlockParser) Continue(node gast.Node, reader text.Reader, _ parser.Context) parser.State {
line, segment := reader.PeekLine()
if gmutil.IsBlank(line) {
return parser.Close
}
node.Lines().Append(segment)
reader.Advance(segment.Len() - 1)
return parser.Continue | parser.NoChildren
}
func (p *underscoreHTMLBlockParser) Close(gast.Node, text.Reader, parser.Context) {}
func (p *underscoreHTMLBlockParser) CanInterruptParagraph() bool { return false }
func (p *underscoreHTMLBlockParser) CanAcceptIndentedLine() bool { return false }
// ---------- Markdown-aware DocxXML containers ----------
type containerSpec struct {
tag string
}
var containerSpecs = map[string]*containerSpec{
"callout": {tag: "callout"},
"grid": {tag: "grid"},
"column": {tag: "column"},
"div": {tag: "div"},
}
var kindContainerBlock = gast.NewNodeKind("DocxContainerBlock")
type containerBlock struct {
gast.BaseBlock
spec *containerSpec
attrs map[string]string
}
func (n *containerBlock) Kind() gast.NodeKind { return kindContainerBlock }
func (n *containerBlock) Dump(source []byte, level int) {
gast.DumpHelper(n, source, level, nil, nil)
}
type containerBlockParser struct{}
func (p *containerBlockParser) Trigger() []byte { return []byte{'<'} }
var containerOpenTag = regexp.MustCompile(`^<([A-Za-z][A-Za-z0-9_-]*)`)
func (p *containerBlockParser) Open(_ gast.Node, reader text.Reader, _ parser.Context) (gast.Node, parser.State) {
line, _ := reader.PeekLine()
trimmed := bytes.TrimLeft(line, " \t")
leading := len(line) - len(trimmed)
if len(trimmed) < 2 || trimmed[0] != '<' {
return nil, parser.NoChildren
}
match := containerOpenTag.FindSubmatch(trimmed)
if match == nil {
return nil, parser.NoChildren
}
spec := containerSpecs[strings.ToLower(string(match[1]))]
if spec == nil {
return nil, parser.NoChildren
}
openEnd := bytes.IndexByte(trimmed, '>')
if openEnd < 0 || openEnd >= 1 && trimmed[openEnd-1] == '/' {
return nil, parser.NoChildren
}
tagEnd := len(match[0])
node := &containerBlock{spec: spec, attrs: parseAttributes(string(trimmed[tagEnd:openEnd]))}
reader.Advance(leading + openEnd + 1)
return node, parser.HasChildren
}
func (p *containerBlockParser) Continue(node gast.Node, reader text.Reader, _ parser.Context) parser.State {
container := node.(*containerBlock)
line, segment := reader.PeekLine()
trimmed := bytes.TrimLeft(line, " \t")
if hasCloseTagPrefix(trimmed, container.spec.tag) {
reader.Advance(len(line) - len(trimmed) + closeTagLength(container.spec.tag))
return parser.Close
}
if isXMLTagLine(trimmed) {
indent := len(line) - len(trimmed)
if indent > 0 && segment.Start+indent <= segment.Stop {
reader.AdvanceAndSetPadding(indent, 0)
}
}
return parser.Continue | parser.HasChildren
}
func (p *containerBlockParser) Close(gast.Node, text.Reader, parser.Context) {}
func (p *containerBlockParser) CanInterruptParagraph() bool { return true }
func (p *containerBlockParser) CanAcceptIndentedLine() bool { return true }
func closeTagLength(tag string) int { return len(tag) + len("</>") }
func hasCloseTagPrefix(line []byte, tag string) bool {
want := []byte("</" + tag + ">")
return len(line) >= len(want) && bytes.EqualFold(line[:len(want)], want)
}
func isXMLTagLine(line []byte) bool {
if len(line) < 2 || line[0] != '<' {
return false
}
if line[1] == '/' {
return len(line) >= 3 && isASCIILetter(line[2])
}
return isASCIILetter(line[1])
}
func isASCIILetter(ch byte) bool {
return ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z'
}

View File

@@ -0,0 +1,172 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
// Package docxparse parses LarkOpenCLI DocxXML and Markdown into a small,
// offline DOM for the docs +script shortcut.
package docxparse
import (
"sort"
"strings"
)
// Format is an accepted source document format.
type Format string
const (
FormatXML Format = "xml"
FormatMarkdown Format = "markdown"
)
// ParseResult is the complete result returned by Parse.
type ParseResult struct {
Format Format `json:"format"`
XML string `json:"xml"`
Profile Profile `json:"profile"`
}
type nodeType uint8
const (
nodeText nodeType = iota
nodeElement
)
// Node is the internal DocxXML DOM representation.
type Node struct {
typ nodeType
tag string
attrs map[string]string
children []*Node
text string
parent *Node
}
func newText(text string) *Node {
return &Node{typ: nodeText, text: text}
}
func newElement(tag string, attrs map[string]string) *Node {
return &Node{typ: nodeElement, tag: tag, attrs: attrs}
}
func (n *Node) addChild(child *Node) {
if n == nil || child == nil {
return
}
child.parent = n
n.children = append(n.children, child)
}
func (n *Node) writeXML(out *strings.Builder) {
if n == nil {
return
}
if n.typ == nodeText {
out.WriteString(escapeXMLText(n.text))
return
}
out.WriteByte('<')
out.WriteString(n.tag)
keys := make([]string, 0, len(n.attrs))
for key := range n.attrs {
keys = append(keys, key)
}
sort.Slice(keys, func(i, j int) bool {
wi, iWeighted := attributeWeight[keys[i]]
wj, jWeighted := attributeWeight[keys[j]]
switch {
case iWeighted && jWeighted && wi != wj:
return wi < wj
case iWeighted != jWeighted:
return iWeighted
default:
return keys[i] < keys[j]
}
})
for _, key := range keys {
out.WriteByte(' ')
out.WriteString(key)
out.WriteString(`="`)
out.WriteString(escapeXMLAttr(n.attrs[key]))
out.WriteByte('"')
}
if isVoidTag(n.tag) {
out.WriteString("/>")
return
}
out.WriteByte('>')
for _, child := range n.children {
child.writeXML(out)
}
out.WriteString("</")
out.WriteString(n.tag)
out.WriteByte('>')
}
func renderNodes(nodes []*Node) string {
var out strings.Builder
for _, node := range nodes {
node.writeXML(&out)
}
return out.String()
}
var attributeWeight = map[string]int{
"id": 0,
"name": 1,
"top-block-id": 2,
"parent-block-path": 3,
"mode": 4,
"start-block-id": 5,
"end-block-id": 6,
"hit-block-ids": 7,
}
func escapeXMLText(value string) string {
if !strings.ContainsAny(value, "&<>") {
return value
}
var out strings.Builder
out.Grow(len(value) + 8)
for _, r := range value {
switch r {
case '&':
out.WriteString("&amp;")
case '<':
out.WriteString("&lt;")
case '>':
out.WriteString("&gt;")
default:
out.WriteRune(r)
}
}
return out.String()
}
func escapeXMLAttr(value string) string {
if !strings.ContainsAny(value, "&<>\"'") {
return value
}
var out strings.Builder
out.Grow(len(value) + 8)
for _, r := range value {
switch r {
case '&':
out.WriteString("&amp;")
case '<':
out.WriteString("&lt;")
case '>':
out.WriteString("&gt;")
case '"':
out.WriteString("&#34;")
case '\'':
out.WriteString("&#39;")
default:
out.WriteRune(r)
}
}
return out.String()
}

View File

@@ -0,0 +1,488 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package docxparse
import (
"strings"
"testing"
)
func TestParseXMLBuildsBlockDistribution(t *testing.T) {
result, err := Parse(`<title>T</title><p>P</p><ul><li>A</li><li>B</li></ul>`, FormatXML)
if err != nil {
t.Fatalf("Parse() error = %v", err)
}
if result.XML != `<title>T</title><p>P</p><ul><li>A</li><li>B</li></ul>` {
t.Fatalf("XML = %q", result.XML)
}
if result.Profile.BlockCount != 5 {
t.Fatalf("block total = %d, want 5", result.Profile.BlockCount)
}
shares := map[string]BlockShare{}
for _, share := range result.Profile.Blocks {
shares[share.Type] = share
}
if got := shares["li"]; got.Count != 2 || got.Ratio != 0.4 {
t.Fatalf("li share = %+v, want count=2 ratio=0.4", got)
}
for _, typ := range []string{"title", "p", "ul"} {
if got := shares[typ]; got.Count != 1 || got.Ratio != 0.2 {
t.Errorf("%s share = %+v, want count=1 ratio=0.2", typ, got)
}
}
}
func TestParseXMLRejectsInvalidInput(t *testing.T) {
tests := []struct {
name string
source string
}{
{name: "unsupported tag", source: `<unknown>x</unknown>`},
{name: "missing closing tag", source: `<p>one`},
{name: "invalid nesting", source: `<span>x<table><tr><td>y</td></tr></table></span>`},
{name: "malformed block id", source: `<block_id="8,9"/>`},
{name: "unterminated cdata", source: `<code><![CDATA[a < b</code>`},
{name: "tag spacing", source: `< p>text< / p>`},
{name: "self closing slash spacing", source: `<p/ >`},
{name: "unquoted attribute", source: `<p align=center>text</p>`},
{name: "invalid entity", source: `<p>one &unknown;</p>`},
{name: "invalid attribute entity", source: `<img href="https://example.com/&unknown;"/>`},
{name: "missing required ancestor", source: `<td>cell</td>`},
{name: "missing required attribute", source: `<img/>`},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if _, err := Parse(tt.source, FormatXML); err == nil {
t.Fatalf("Parse(%q) succeeded, want validation error", tt.source)
}
})
}
}
func TestParseAutoDetectsXMLAndMarkdown(t *testing.T) {
tests := []struct {
name string
source string
blocks int
}{
{name: "xml", source: `<title>T</title><p>P</p>`, blocks: 2},
{name: "markdown", source: "# T\n\nP", blocks: 2},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
profile, err := ParseAuto(tt.source)
if err != nil {
t.Fatalf("ParseAuto() error = %v", err)
}
if profile.BlockCount != tt.blocks {
t.Fatalf("profile = %+v, want %d blocks", profile, tt.blocks)
}
})
}
}
func TestParseAutoDoesNotTreatMalformedXMLAsMarkdown(t *testing.T) {
if _, err := ParseAuto(`<p>text`); err == nil {
t.Fatal("ParseAuto() succeeded, want malformed XML error")
}
}
func TestParseXMLAcceptsPublicTagAliasesWithoutChangingInput(t *testing.T) {
source := `<P>one<strong>two</strong><br></P><image href="https://example.com/image.png">`
result, err := Parse(source, FormatXML)
if err != nil {
t.Fatalf("Parse() error = %v", err)
}
if result.XML != source {
t.Fatalf("XML = %q, want original %q", result.XML, source)
}
if result.Profile.BlockCount != 2 {
t.Fatalf("profile = %+v, want p and img blocks", result.Profile)
}
}
func TestParseXMLAcceptsPublicAttributeAliasesWithoutChangingInput(t *testing.T) {
source := `<callout color="blue" icon="💡"><p>x</p></callout><at id="ou_legacy"></at><img url="https://example.com/image.png"/>`
result, err := Parse(source, FormatXML)
if err != nil {
t.Fatalf("Parse() error = %v", err)
}
if result.XML != source {
t.Fatalf("XML = %q, want original %q", result.XML, source)
}
if result.Profile.BlockCount != 3 {
t.Fatalf("profile = %+v, want callout, p, and img blocks", result.Profile)
}
}
func TestParseXMLAcceptsBareAmpersandsInAttributes(t *testing.T) {
source := `<block_insert><parameter><block_id>-1</block_id><content><img href="https://picsum.photos/320/200?seed=lark-cli&raw=1"/></content></parameter></block_insert>`
result, err := Parse(source, FormatXML)
if err != nil {
t.Fatalf("Parse() error = %v", err)
}
if result.XML != source {
t.Fatalf("XML = %q, want original %q", result.XML, source)
}
}
func TestNormalizeXMLAttributeAmpersandsPreservesEntityReferences(t *testing.T) {
source := `https://example.com?a=1&b=2&amp;c=3&#38;d=4&#x26;e=5&unknown;`
want := `https://example.com?a=1&amp;b=2&amp;c=3&#38;d=4&#x26;e=5&unknown;`
if got := normalizeXMLAttributeAmpersands(source); got != want {
t.Fatalf("normalizeXMLAttributeAmpersands() = %q, want %q", got, want)
}
}
func TestParseXMLPreservesValidCDATA(t *testing.T) {
source := `<code><![CDATA[a < b && c > d]]></code>`
result, err := Parse(source, FormatXML)
if err != nil {
t.Fatalf("Parse() error = %v", err)
}
if result.XML != source {
t.Fatalf("XML = %q, want original %q", result.XML, source)
}
}
func TestParseXMLPreservesUTF8BOM(t *testing.T) {
source := "\uFEFF<p>text</p>"
result, err := Parse(source, FormatXML)
if err != nil {
t.Fatalf("Parse() error = %v", err)
}
if result.XML != source {
t.Fatalf("XML = %q, want original input", result.XML)
}
}
func TestParseMarkdownConvertsLarkOpenCLIBlocks(t *testing.T) {
source := "# 标题\n\nHello **world**.\n\n- [x] Done\n- [ ] Todo\n\n" +
"| A | B |\n| --- | --- |\n| 1 | 2 |\n\n" +
"```go\nfmt.Println(\"x\")\n```\n\n$E=mc^2$\n"
result, err := Parse(source, FormatMarkdown)
if err != nil {
t.Fatalf("Parse() error = %v", err)
}
for _, fragment := range []string{
`<h1>标题</h1>`,
`<p>Hello <b>world</b>.</p>`,
`<checkbox done="true">Done</checkbox>`,
`<checkbox done="false">Todo</checkbox>`,
`<table><thead><tr><th>A</th><th>B</th></tr></thead><tbody><tr><td>1</td><td>2</td></tr></tbody></table>`,
`<pre lang="go"><code>fmt.Println("x")</code></pre>`,
`<p><latex>E=mc^2</latex></p>`,
} {
if !strings.Contains(result.XML, fragment) {
t.Errorf("XML missing %q:\n%s", fragment, result.XML)
}
}
}
func TestParseMarkdownPreservesLineBreakSemantics(t *testing.T) {
tests := []struct {
name string
source string
want string
}{
{
name: "soft breaks become spaces",
source: "**文号桂汛旱指202617号**\n**签发人XXX**\n**发布日期2026年7月13日**",
want: `<p><b>文号桂汛旱指202617号</b> <b>签发人XXX</b> <b>发布日期2026年7月13日</b></p>`,
},
{
name: "hard breaks remain line breaks",
source: "**文号A** \n**签发人B**",
want: `<p><b>文号A</b><br/><b>签发人B</b></p>`,
},
{
name: "blank lines remain paragraph breaks",
source: "**文号A**\n\n**签发人B**",
want: `<p><b>文号A</b></p><p><b>签发人B</b></p>`,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result, err := Parse(tt.source, FormatMarkdown)
if err != nil {
t.Fatalf("Parse() error = %v", err)
}
if result.XML != tt.want {
t.Fatalf("XML = %q, want %q", result.XML, tt.want)
}
})
}
}
func TestParseMarkdownContainerKeepsMarkdownChildren(t *testing.T) {
source := "<callout emoji=\"💡\">\n\n## Note\n\n- item\n\n</callout>\n"
result, err := Parse(source, FormatMarkdown)
if err != nil {
t.Fatalf("Parse() error = %v", err)
}
want := `<callout emoji="💡"><h2>Note</h2><ul><li>item</li></ul></callout>`
if result.XML != want {
t.Fatalf("XML = %q, want %q", result.XML, want)
}
}
func TestParseMarkdownMatchesLarkOpenCLIFixtures(t *testing.T) {
t.Run("deep nested list", func(t *testing.T) {
result, err := Parse("1. 第一层\n - 第二层\n - 第三层\n - 第四层\n", FormatMarkdown)
if err != nil {
t.Fatalf("Parse() error = %v", err)
}
if strings.Contains(result.XML, "<pre>") || strings.Contains(result.XML, "<code>") || !strings.Contains(result.XML, "第四层") {
t.Fatalf("nested list converted incorrectly: %s", result.XML)
}
})
t.Run("fenced mermaid", func(t *testing.T) {
result, err := Parse("```mermaid\nflowchart LR\nA-->B\n```", FormatMarkdown)
if err != nil {
t.Fatalf("Parse() error = %v", err)
}
want := `<whiteboard type="mermaid">flowchart LR<br/>A--&gt;B</whiteboard>`
if result.XML != want {
t.Fatalf("XML = %q, want %q", result.XML, want)
}
})
t.Run("raw whiteboard source", func(t *testing.T) {
source := "<whiteboard type=\"mermaid\">\nflowchart LR\n A --> B\n</whiteboard>"
result, err := Parse(source, FormatMarkdown)
if err != nil {
t.Fatalf("Parse() error = %v", err)
}
want := `<whiteboard type="mermaid">flowchart LR<br/> A --&gt; B</whiteboard>`
if result.XML != want {
t.Fatalf("XML = %q, want %q", result.XML, want)
}
})
t.Run("raw code stays literal", func(t *testing.T) {
source := "<code lang=\"go\">\nif a < b && c > d {\n fmt.Println(\"**raw**\")\n}\n</code>"
result, err := Parse(source, FormatMarkdown)
if err != nil {
t.Fatalf("Parse() error = %v", err)
}
want := `<code lang="go">if a &lt; b &amp;&amp; c &gt; d {<br/> fmt.Println("**raw**")<br/>}</code>`
if result.XML != want {
t.Fatalf("XML = %q, want %q", result.XML, want)
}
})
t.Run("underscore tags", func(t *testing.T) {
result, err := Parse(`text <synced_reference src-block-id="abc" src-token="def"/> more`, FormatMarkdown)
if err != nil {
t.Fatalf("Parse() error = %v", err)
}
if !strings.Contains(result.XML, `<synced_reference`) || strings.Contains(result.XML, `&lt;synced_reference`) {
t.Fatalf("underscore tag was not preserved: %s", result.XML)
}
})
t.Run("canonical user cite", func(t *testing.T) {
result, err := Parse(`hello <cite type="user" user-id="ou_user"></cite>`, FormatMarkdown)
if err != nil {
t.Fatalf("Parse() error = %v", err)
}
for _, want := range []string{`<cite`, `type="user"`, `user-id="ou_user"`} {
if !strings.Contains(result.XML, want) {
t.Errorf("XML missing %q: %s", want, result.XML)
}
}
})
t.Run("public tag alias converts to canonical XML", func(t *testing.T) {
result, err := Parse(`hello <strong>world</strong>`, FormatMarkdown)
if err != nil {
t.Fatalf("Parse() error = %v", err)
}
if result.XML != `<p>hello <b>world</b></p>` {
t.Fatalf("XML = %q", result.XML)
}
})
t.Run("public cite alias converts attributes", func(t *testing.T) {
result, err := Parse(`hello <at id="ou_legacy"></at>`, FormatMarkdown)
if err != nil {
t.Fatalf("Parse() error = %v", err)
}
if result.XML != `<p>hello <cite type="user" user-id="ou_legacy"></cite></p>` {
t.Fatalf("XML = %q", result.XML)
}
})
t.Run("markdown backslash escapes", func(t *testing.T) {
result, err := Parse(`"source\_token": \[abc\] path\\to`, FormatMarkdown)
if err != nil {
t.Fatalf("Parse() error = %v", err)
}
for _, want := range []string{`source_token`, `[abc]`, `path\to`} {
if !strings.Contains(result.XML, want) {
t.Errorf("XML missing %q: %s", want, result.XML)
}
}
})
t.Run("adjacent CJK emphasis", func(t *testing.T) {
source := `***你好。***S 和 ~~再见。~~T。**agent team 做 brownfield 项目,带来的感知会强烈得多**——前提。**这个时刻,才是真正属于 agent team 的"闪光时刻"。**翟霖`
result, err := Parse(source, FormatMarkdown)
if err != nil {
t.Fatalf("Parse() error = %v", err)
}
for _, want := range []string{
`<em><b>你好。</b></em>S`,
`<del>再见。</del>T`,
`<b>agent team 做 brownfield 项目,带来的感知会强烈得多</b>`,
`<b>这个时刻,才是真正属于 agent team 的"闪光时刻"。</b>翟霖`,
} {
if !strings.Contains(result.XML, want) {
t.Errorf("XML missing %q: %s", want, result.XML)
}
}
})
t.Run("div parses markdown children", func(t *testing.T) {
result, err := Parse("<div>\n\n**bold**\n\n</div>", FormatMarkdown)
if err != nil {
t.Fatalf("Parse() error = %v", err)
}
if result.XML != `<div><p><b>bold</b></p></div>` {
t.Fatalf("XML = %q", result.XML)
}
})
}
func TestPreprocessCJKAdjacentMarkupUsesRuneOffsetsAfterRawBlock(t *testing.T) {
tests := []struct {
name string
lineEnding string
final string
}{
{name: "EOF", lineEnding: "\n"},
{name: "LF", lineEnding: "\n", final: "\n"},
{name: "CRLF", lineEnding: "\r\n", final: "\r\n"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
source := "<code>**raw**" + tt.lineEnding + "Ⱥ</code>**你好。**S" + tt.final
want := "<code>**raw**" + tt.lineEnding + "Ⱥ</code><b>你好。</b>S" + tt.final
if got := preprocessCJKAdjacentMarkup(source); got != want {
t.Fatalf("preprocessCJKAdjacentMarkup() = %q, want %q", got, want)
}
})
}
}
func TestTextProfileMatchesLarkOpenCLIContract(t *testing.T) {
result, err := Parse(`<title>标题</title><p>一个苹果是 an apple。</p>`, FormatXML)
if err != nil {
t.Fatalf("Parse() error = %v", err)
}
profile := result.Profile
if profile.WordCount != 10 || profile.CharCount != 15 {
t.Fatalf("profile = %+v, want word_count=10 char_count=15", profile)
}
if profile.Breakdown.HanChars != 7 || profile.Breakdown.EnglishWords != 2 || profile.Breakdown.ChinesePunctuations != 1 {
t.Fatalf("breakdown = %+v", profile.Breakdown)
}
}
func TestTextProfileMatchesAuthoringCounterCases(t *testing.T) {
tests := []struct {
name string
source string
words int
chars int
blocks int
english int
numbers int
han int
listItems int
}{
{
name: "english number and punctuation",
source: `<p>Hello world 123.45。</p>`,
words: 4, chars: 17, blocks: 1, english: 2, numbers: 1,
},
{
name: "list and checkbox markers",
source: `<ul><li>甲</li><li>two</li></ul><checkbox done="true">完成</checkbox>`,
words: 7, chars: 9, blocks: 4, english: 1, han: 3, listItems: 2,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result, err := Parse(tt.source, FormatXML)
if err != nil {
t.Fatalf("Parse() error = %v", err)
}
profile := result.Profile
if profile.WordCount != tt.words || profile.CharCount != tt.chars || profile.BlockCount != tt.blocks {
t.Fatalf("profile = %+v, want words=%d chars=%d blocks=%d", profile, tt.words, tt.chars, tt.blocks)
}
if profile.Breakdown.EnglishWords != tt.english || profile.Breakdown.NumberWords != tt.numbers || profile.Breakdown.HanChars != tt.han {
t.Fatalf("breakdown = %+v", profile.Breakdown)
}
if got := blockCountForTest(profile.Blocks, "li"); got != tt.listItems {
t.Fatalf("li count = %d, want %d", got, tt.listItems)
}
})
}
}
func TestTextProfileUsesVisibleAttributeFallbacks(t *testing.T) {
result, err := Parse(`<p text="Hello"/><p><span title="world"/></p><img href="https://example.com/image.png" caption="图"/>`, FormatXML)
if err != nil {
t.Fatalf("Parse() error = %v", err)
}
profile := result.Profile
if profile.WordCount != 3 || profile.CharCount != 11 {
t.Fatalf("profile = %+v, want word_count=3 char_count=11", profile)
}
if profile.Breakdown.EnglishWords != 2 || profile.Breakdown.HanChars != 1 {
t.Fatalf("breakdown = %+v", profile.Breakdown)
}
}
func TestParseRejectsUnsafeXMLDeclarations(t *testing.T) {
_, err := Parse(`<!DOCTYPE foo [<!ENTITY x "value">]><p>&x;</p>`, FormatXML)
if err == nil || !strings.Contains(err.Error(), "DOCTYPE or ENTITY") {
t.Fatalf("Parse() error = %v, want unsafe declaration rejection", err)
}
}
func TestParseRejectsInvalidUTF8(t *testing.T) {
_, err := Parse(string([]byte{'<', 'p', '>', 0xff, '<', '/', 'p', '>'}), FormatXML)
if err == nil || !strings.Contains(err.Error(), "valid UTF-8") {
t.Fatalf("Parse() error = %v, want UTF-8 rejection", err)
}
}
func TestParseRejectsExcessiveNesting(t *testing.T) {
source := strings.Repeat("<span>", MaxNestingDepth+1)
_, err := Parse(source, FormatXML)
if err == nil || !strings.Contains(err.Error(), "nesting exceeds") {
t.Fatalf("Parse() error = %v, want nesting limit rejection", err)
}
}
func TestParseXMLRejectsNestedInvalidTagStarts(t *testing.T) {
if _, err := Parse(`<<<<p>text</p>`, FormatXML); err == nil {
t.Fatal("Parse() succeeded, want invalid XML token error")
}
}
func blockCountForTest(blocks []BlockShare, typ string) int {
for _, block := range blocks {
if block.Type == typ {
return block.Count
}
}
return 0
}

View File

@@ -0,0 +1,397 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package docxparse
import (
"fmt"
"math"
"sort"
"strings"
)
// Profile describes LarkOpenCLI document structure and visible text without
// requiring callers to inspect the full XML.
type Profile struct {
WordCount int `json:"word_count"`
CharCount int `json:"char_count"`
Breakdown TextBreakdown `json:"breakdown"`
BlockCount int `json:"block_count"`
Blocks []BlockShare `json:"blocks"`
}
// BlockShare reports one LarkOpenCLI block type's count and share. Structural
// and inline-only tags are intentionally excluded.
type BlockShare struct {
Type string `json:"type"`
Count int `json:"count"`
Ratio float64 `json:"ratio"`
}
// TextProfile is the internal result of the LarkOpenCLI semantic counter.
type TextProfile struct {
WordCount int `json:"word_count"`
CharCount int `json:"char_count"`
Breakdown TextBreakdown `json:"breakdown"`
}
type TextBreakdown struct {
HanChars int `json:"han_chars"`
EnglishWords int `json:"english_words"`
NumberWords int `json:"number_words"`
ChinesePunctuations int `json:"chinese_punctuations"`
EnglishLetters int `json:"english_letters"`
Digits int `json:"digits"`
EnglishPunctuations int `json:"english_punctuations"`
SymbolWords int `json:"symbol_words"`
SymbolChars int `json:"symbol_chars"`
}
// Parse validates XML or converts Markdown to DocxXML, then builds its
// structure and visible-text profile.
func Parse(source string, format Format) (ParseResult, error) {
var (
nodes []*Node
outputXML string
err error
)
switch format {
case FormatXML:
nodes, err = parseXML(source)
outputXML = source
case FormatMarkdown:
nodes, err = parseMarkdown(source)
default:
return ParseResult{}, fmt.Errorf("unsupported input format %q", format)
}
if err != nil {
return ParseResult{}, err
}
if err := validateStructure(nodes); err != nil {
return ParseResult{}, err
}
if format == FormatMarkdown {
outputXML = renderNodes(nodes)
}
return ParseResult{
Format: format,
XML: outputXML,
Profile: buildProfile(nodes),
}, nil
}
// ParseAuto detects XML versus Markdown from the content and returns only the
// document profile. XML-like input is parsed strictly; all other input is
// interpreted as Markdown.
func ParseAuto(source string) (Profile, error) {
result, err := Parse(source, detectFormat(source))
if err != nil {
return Profile{}, err
}
return result.Profile, nil
}
// MarkdownToXML converts Markdown to canonical LarkOpenCLI XML.
func MarkdownToXML(source string) (string, error) {
result, err := Parse(source, FormatMarkdown)
if err != nil {
return "", err
}
return result.XML, nil
}
func detectFormat(source string) Format {
trimmed := strings.TrimSpace(strings.TrimPrefix(source, "\uFEFF"))
if strings.HasPrefix(trimmed, "<") {
return FormatXML
}
return FormatMarkdown
}
func validateStructure(nodes []*Node) error {
type frame struct {
node *Node
exit bool
}
frames := make([]frame, 0, len(nodes))
for i := len(nodes) - 1; i >= 0; i-- {
frames = append(frames, frame{node: nodes[i]})
}
ancestors := map[string]int{}
depth := 0
for len(frames) > 0 {
current := frames[len(frames)-1]
frames = frames[:len(frames)-1]
node := current.node
if node == nil || node.typ != nodeElement {
continue
}
if current.exit {
ancestors[node.tag]--
depth--
continue
}
if depth >= MaxNestingDepth {
return fmt.Errorf("document nesting exceeds limit %d at <%s>", MaxNestingDepth, node.tag)
}
if err := validateRequiredAttributes(node); err != nil {
return err
}
if required := requiredAncestorTags[node.tag]; len(required) > 0 {
matched := false
for tag := range required {
if ancestors[tag] > 0 {
matched = true
break
}
}
if !matched {
allowed := make([]string, 0, len(required))
for tag := range required {
allowed = append(allowed, tag)
}
sort.Strings(allowed)
return fmt.Errorf("LarkOpenCLI tag <%s> requires an ancestor in [%s]", node.tag, strings.Join(allowed, ", "))
}
}
ancestors[node.tag]++
depth++
frames = append(frames, frame{node: node, exit: true})
for i := len(node.children) - 1; i >= 0; i-- {
frames = append(frames, frame{node: node.children[i]})
}
}
return nil
}
func validateRequiredAttributes(node *Node) error {
for _, attr := range requiredAttributes[node.tag] {
if strings.TrimSpace(node.attrs[attr]) == "" {
return fmt.Errorf("LarkOpenCLI tag <%s> requires attribute %q", node.tag, attr)
}
}
for _, alternatives := range requiredAnyAttributes[node.tag] {
matched := false
for _, attr := range alternatives {
if strings.TrimSpace(node.attrs[attr]) != "" {
matched = true
break
}
}
if !matched {
return fmt.Errorf("LarkOpenCLI tag <%s> requires one of attributes [%s]", node.tag, strings.Join(alternatives, ", "))
}
}
return nil
}
func buildProfile(nodes []*Node) Profile {
counts := map[string]int{}
total := 0
var walk func(*Node)
walk = func(node *Node) {
if node == nil || node.typ != nodeElement {
return
}
layout := layoutOf(node.tag)
isBlock := layout == layoutBlock || layout == layoutDual && node.parent == nil
if isBlock {
counts[node.tag]++
total++
}
for _, child := range node.children {
walk(child)
}
}
for _, node := range nodes {
walk(node)
}
distribution := make([]BlockShare, 0, len(counts))
for typ, count := range counts {
ratio := 0.0
if total > 0 {
ratio = math.Round(float64(count)/float64(total)*1_000_000) / 1_000_000
}
distribution = append(distribution, BlockShare{Type: typ, Count: count, Ratio: ratio})
}
sort.Slice(distribution, func(i, j int) bool {
if distribution[i].Count != distribution[j].Count {
return distribution[i].Count > distribution[j].Count
}
return distribution[i].Type < distribution[j].Type
})
segments := extractSegments(nodes)
stats := newTextCounter().countSegments(segments)
return Profile{
WordCount: stats.WordCount,
CharCount: stats.CharCount,
Breakdown: stats.Breakdown,
BlockCount: total,
Blocks: distribution,
}
}
type segmentKind uint8
const (
segmentText segmentKind = iota
segmentMarker
segmentCode
)
type textSegment struct {
text string
kind segmentKind
}
var ignoredResourceTags = map[string]bool{
"whiteboard": true, "sheet": true, "source": true, "chat_card": true,
"base_refer": true, "bitable": true, "synced_reference": true,
"poll": true, "isv": true, "mindnote": true, "sub-page-list": true,
"okr": true, "html5-block": true,
}
var ignoredInlineTags = map[string]bool{
"button": true, "cite": true, "latex": true, "bookmark": true,
}
func extractSegments(nodes []*Node) []textSegment {
var segments []textSegment
for _, node := range nodes {
extractNodeSegments(node, &segments)
}
return segments
}
func extractNodeSegments(node *Node, segments *[]textSegment) {
if node == nil {
return
}
if node.typ == nodeText {
if strings.TrimSpace(node.text) != "" {
*segments = append(*segments, textSegment{text: node.text})
}
return
}
if ignoredInlineTags[node.tag] || ignoredResourceTags[node.tag] {
return
}
if node.tag == "task" {
return
}
if node.tag == "synced-source" && len(node.children) == 0 {
return
}
switch node.tag {
case "ul", "ol":
sequence := 1
for _, child := range node.children {
if child.typ == nodeElement && child.tag == "li" {
if node.tag == "ul" {
*segments = append(*segments, textSegment{text: "•", kind: segmentMarker})
} else {
marker := sequence
if raw := child.attrs["seq"]; raw != "" {
if _, err := fmt.Sscanf(raw, "%d", &marker); err == nil {
sequence = marker
}
}
*segments = append(*segments, textSegment{text: fmt.Sprintf("%d.", marker)})
sequence++
}
}
extractNodeSegments(child, segments)
}
return
case "checkbox":
marker := "☐"
if node.attrs["done"] == "true" {
marker = "☑"
}
*segments = append(*segments, textSegment{text: marker, kind: segmentMarker})
}
kind := segmentText
if node.tag == "pre" || node.tag == "code" && (node.parent == nil || node.parent.tag != "p") {
kind = segmentCode
}
text := visibleInlineText(node)
if strings.TrimSpace(text) == "" && !hasBlockChildren(node) {
if node.tag == "img" {
text = node.attrs["caption"]
} else {
text = firstNonEmpty(node.attrs["text"], node.attrs["name"], node.attrs["title"], node.attrs["alt"], node.attrs["caption"])
}
}
if strings.TrimSpace(text) != "" {
*segments = append(*segments, textSegment{text: text, kind: kind})
}
for _, child := range node.children {
if child.typ != nodeElement || isInlineForExtraction(child.tag) {
continue
}
extractNodeSegments(child, segments)
}
}
func visibleInlineText(node *Node) string {
var out strings.Builder
var walk func(*Node)
walk = func(current *Node) {
if current.typ == nodeText {
out.WriteString(current.text)
return
}
if current != node && !isInlineForExtraction(current.tag) {
return
}
if ignoredInlineTags[current.tag] {
return
}
if current.tag == "br" {
out.WriteByte('\n')
return
}
if current != node {
if display := firstNonEmpty(current.attrs["text"], current.attrs["name"], current.attrs["title"], current.attrs["alt"]); display != "" {
out.WriteString(display)
return
}
}
for _, child := range current.children {
walk(child)
}
}
for _, child := range node.children {
walk(child)
}
return out.String()
}
func hasBlockChildren(node *Node) bool {
for _, child := range node.children {
if child.typ == nodeElement && !isInlineForExtraction(child.tag) {
return true
}
}
return false
}
func isInlineForExtraction(tag string) bool {
layout := layoutOf(tag)
return layout == layoutInline || layout == layoutDual
}
func firstNonEmpty(values ...string) string {
for _, value := range values {
if value != "" {
return value
}
}
return ""
}

View File

@@ -0,0 +1,268 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package docxparse
import (
"sort"
"strconv"
"strings"
)
type tagLayout string
const (
layoutBlock tagLayout = "block"
layoutInline tagLayout = "inline"
layoutDual tagLayout = "dual"
layoutStructural tagLayout = "structural"
layoutCommand tagLayout = "command"
)
type tagSpec struct {
canonical string
layout tagLayout
}
var tagSpecs = map[string]tagSpec{}
// tagAliases mirrors the public compatibility aliases declared by the
// LarkOpenCLI SDK. Parsing keeps the caller's XML unchanged; aliases are only
// canonicalized in the in-memory tree used for profiling and Markdown output.
var tagAliases = map[string]string{
"strong": "b",
"text": "span",
"equation": "latex",
"lark-table": "table",
"lark-tr": "tr",
"lark-td": "td",
"image": "img",
"reference-synced": "synced_reference",
"source-synced": "synced-source",
"at": "cite",
"chat-card": "chat_card",
"folder_manager": "folder-manager",
}
type attributeAliasRule struct {
canonical string
transform func(string) (string, bool)
}
var commonAttributeAliases = map[string]attributeAliasRule{
"color": {canonical: "text-color"},
"textcolor": {canonical: "text-color"},
"text_color": {canonical: "text-color"},
"bgcolor": {canonical: "background-color"},
"background_color": {canonical: "background-color"},
}
var tagAttributeAliases = map[string]map[string]attributeAliasRule{
"img": {
"url": {canonical: "href"},
"file_key": {canonical: "img_key"},
},
"callout": {
"color": {canonical: "background-color"},
"icon": {canonical: "emoji"},
},
"column": {
"width": {canonical: "width-ratio", transform: normalizeWidthRatio},
},
"chat_card": {
"id": {canonical: "chat-id", transform: requireChatID},
},
"cite": {
"user_id": {canonical: "user-id"},
},
}
var rawTagAttributeAliases = map[string]map[string]attributeAliasRule{
"at": {
"id": {canonical: "user-id"},
"user_id": {canonical: "user-id"},
},
}
var requiredAttributes = map[string][]string{
"task": {"task-id"},
}
var requiredAnyAttributes = map[string][][]string{
"img": {{"src", "img_key", "href"}},
"whiteboard": {{"token", "type"}},
"chat_card": {{"token", "chat-id"}},
"bookmark": {{"href", "name"}},
}
func init() {
registerTags(layoutBlock,
"title", "h1", "h2", "h3", "h4", "h5", "h6", "h7", "h8", "h9", "p",
"div", "ul", "ol", "li", "blockquote", "grid", "column", "table", "thead",
"tbody", "tfoot", "tr", "hr", "pre", "img", "source", "bitable", "sheet",
"mindnote", "whiteboard", "base_refer", "synced_reference", "isv", "html5-block",
"view", "synced-source", "readonly-block", "figure", "callout", "checkbox",
"chat_card", "okr", "okr-objective", "okr-key-result", "okr-progress", "poll",
"agenda", "folder-manager", "sub-page-list", "wiki_catalog", "wiki_recent_update",
"chart-embedded", "chart-refer-host-perm", "chart_embedded", "chart_refer_host_perm",
"bookmark", "task", "vc-tabs", "vc-summary-tab", "vc-transcribe-tab", "append",
)
registerTags(layoutInline, "b", "em", "u", "del", "i", "span", "br", "inline-file", "mention-date", "cite", "button", "time", "a")
registerTags(layoutDual, "latex", "code")
registerTags(layoutStructural, "th", "td", "colgroup", "col", "sub-page")
registerTags(layoutCommand,
"comment", "block_delete", "str_delete", "str_replace", "block_replace", "block_insert",
"block_move", "block_copy_insert_after", "src_block_ids", "create", "answer", "response",
"identifier", "genre", "anchor", "type", "revision", "pattern", "replacement",
"replace_content", "action", "content", "parameter", "generation", "block_id",
)
}
func registerTags(layout tagLayout, tags ...string) {
for _, tag := range tags {
tagSpecs[tag] = tagSpec{canonical: tag, layout: layout}
}
}
func lookupTag(raw string) (tagSpec, bool) {
key := strings.ToLower(strings.TrimSpace(raw))
if canonical, ok := tagAliases[key]; ok {
key = canonical
}
spec, ok := tagSpecs[key]
if !ok {
return tagSpec{}, false
}
return spec, true
}
func layoutOf(tag string) tagLayout {
spec, ok := lookupTag(tag)
if !ok {
return ""
}
return spec.layout
}
var voidTags = map[string]bool{
"br": true,
"col": true,
"hr": true,
"img": true,
"source": true,
"sub-page": true,
}
func isVoidTag(tag string) bool { return voidTags[tag] }
var preserveSpaceTags = map[string]bool{
"title": true, "h1": true, "h2": true, "h3": true, "h4": true,
"h5": true, "h6": true, "h7": true, "h8": true, "h9": true,
"p": true, "i": true, "b": true, "em": true, "u": true, "del": true,
"code": true, "li": true, "a": true, "span": true,
}
var strictPhrasingTags = map[string]bool{
"title": true, "span": true, "b": true, "em": true,
"u": true, "del": true, "a": true,
}
var autoCloseTags = map[string]map[string]bool{
"li": {"li": true},
"tr": {"tr": true},
"td": {"td": true, "th": true, "tr": true, "tbody": true, "tfoot": true},
"th": {"th": true, "td": true, "tr": true, "tbody": true, "tfoot": true},
"tbody": {"tbody": true, "tfoot": true},
"thead": {"tbody": true, "tfoot": true},
"column": {"column": true},
}
var requiredAncestorTags = map[string]map[string]bool{
"column": {"grid": true},
"thead": {"table": true},
"tbody": {"table": true},
"tfoot": {"table": true},
"tr": {"table": true, "thead": true, "tbody": true, "tfoot": true},
"th": {"tr": true},
"td": {"tr": true},
"colgroup": {"table": true},
"col": {"table": true, "colgroup": true},
"okr-objective": {"okr": true},
"okr-key-result": {"okr": true, "okr-objective": true},
"okr-progress": {"okr-objective": true, "okr-key-result": true},
"sub-page": {"sub-page-list": true},
}
func shouldAutoClose(openTag, nextTag string) bool {
if strictPhrasingTags[openTag] && layoutOf(nextTag) == layoutBlock {
return true
}
return autoCloseTags[openTag] != nil && autoCloseTags[openTag][nextTag]
}
func normalizeAttributes(rawTag, canonical string, attrs map[string]string) map[string]string {
rules := make(map[string]attributeAliasRule, len(commonAttributeAliases)+4)
for alias, rule := range commonAttributeAliases {
rules[alias] = rule
}
for alias, rule := range tagAttributeAliases[canonical] {
rules[alias] = rule
}
rawKey := strings.ToLower(strings.TrimSpace(rawTag))
for alias, rule := range rawTagAttributeAliases[rawKey] {
rules[alias] = rule
}
aliases := make([]string, 0, len(rules))
for alias := range rules {
aliases = append(aliases, alias)
}
sort.Strings(aliases)
for _, alias := range aliases {
value, exists := attrs[alias]
if !exists {
continue
}
rule := rules[alias]
if rule.transform != nil {
var ok bool
value, ok = rule.transform(value)
if !ok {
continue
}
}
if canonicalValue, exists := attrs[rule.canonical]; !exists || strings.TrimSpace(canonicalValue) == "" {
if attrs == nil {
attrs = map[string]string{}
}
attrs[rule.canonical] = value
}
delete(attrs, alias)
}
if rawKey == "at" {
if attrs == nil {
attrs = map[string]string{}
}
attrs["type"] = "user"
}
return attrs
}
func normalizeWidthRatio(value string) (string, bool) {
trimmed := strings.TrimSuffix(strings.TrimSpace(value), "%")
if trimmed == "" {
return value, false
}
width, err := strconv.ParseFloat(trimmed, 64)
if err != nil {
return value, false
}
return strconv.FormatFloat(width/100, 'f', 6, 64), true
}
func requireChatID(value string) (string, bool) {
trimmed := strings.TrimSpace(value)
return trimmed, strings.HasPrefix(trimmed, "oc_")
}

View File

@@ -0,0 +1,342 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package docxparse
// This file implements the LarkOpenCLI document text-counting contract.
import (
"regexp"
"strings"
"unicode"
"unicode/utf8"
"golang.org/x/text/width"
)
const chinesePunctuation = ",。!?;:、()《》〈〉“”‘’【】「」『』〔〕…—~·¥"
const englishPunctuation = `!"#$%&'()*+,-./:;<=>?@[\]^_` + "`" + `{|}~`
var (
urlToken = regexp.MustCompile(`^https?://[!-~]+`)
asciiCompoundToken = regexp.MustCompile(`^[A-Za-z0-9]+(?:[._/@:-][A-Za-z0-9]+)+`)
)
type lexemeKind uint8
const (
lexemeNone lexemeKind = iota
lexemeEnglish
lexemeNumber
)
type textCounter struct {
stats TextProfile
lexeme lexemeKind
lexemeHasDigit bool
symbolRunLength int
atBoundary bool
}
func newTextCounter() *textCounter {
return &textCounter{atBoundary: true}
}
func (c *textCounter) countSegments(segments []textSegment) TextProfile {
for _, segment := range segments {
c.endUnit()
c.atBoundary = true
switch segment.kind {
case segmentMarker:
c.writeMarker(segment.text)
case segmentCode:
c.writeCode(segment.text)
default:
c.write(segment.text)
}
c.endUnit()
c.atBoundary = true
}
c.endUnit()
return c.stats
}
func (c *textCounter) write(value string) {
for offset := 0; offset < len(value); {
if token := matchASCIICompound(value[offset:]); token != "" {
c.writeASCIICompound(token)
offset += len(token)
continue
}
r, size := utf8.DecodeRuneInString(value[offset:])
if r == '/' && isVisibleHanSeparator(value, offset, size) {
c.endUnit()
c.stats.Breakdown.EnglishPunctuations++
c.stats.Breakdown.SymbolWords++
c.stats.WordCount++
c.stats.CharCount++
c.atBoundary = false
offset += size
continue
}
c.writeRune(r)
offset += size
}
}
func (c *textCounter) writeMarker(value string) {
for _, r := range value {
if unicode.IsSpace(r) {
continue
}
c.endUnit()
c.stats.WordCount++
c.stats.CharCount++
c.atBoundary = false
}
}
func (c *textCounter) writeCode(value string) {
for _, r := range value {
c.writeCodeRune(r)
}
}
func (c *textCounter) writeCodeRune(r rune) {
if unicode.IsSpace(r) {
c.endUnit()
c.atBoundary = true
return
}
if unicode.Is(unicode.Han, r) {
c.endLexeme()
c.endSymbolRun(false)
c.stats.Breakdown.HanChars++
c.stats.WordCount++
c.stats.CharCount++
c.atBoundary = false
return
}
if isASCIILetterRune(r) {
c.endSymbolRun(false)
c.stats.Breakdown.EnglishLetters++
c.stats.CharCount++
if c.lexeme == lexemeNone || c.lexeme == lexemeNumber {
c.lexeme = lexemeEnglish
}
c.atBoundary = false
return
}
if isASCIIDigitRune(r) {
c.endSymbolRun(false)
c.stats.Breakdown.Digits++
c.stats.CharCount++
c.atBoundary = false
return
}
if isChinesePunctuation(r) {
c.endLexeme()
c.endSymbolRun(false)
c.stats.Breakdown.ChinesePunctuations++
c.stats.WordCount++
c.stats.CharCount++
c.atBoundary = false
return
}
if isEnglishPunctuation(r) {
keepsLexeme := c.lexeme == lexemeEnglish && (r == '\'' || r == '-')
if !keepsLexeme {
hadLexeme := c.lexeme != lexemeNone
c.endLexeme()
if !hadLexeme && (c.symbolRunLength > 0 || c.atBoundary) {
c.symbolRunLength++
}
}
c.stats.Breakdown.EnglishPunctuations++
c.stats.CharCount++
if keepsLexeme {
c.atBoundary = false
}
return
}
if unicode.Is(unicode.Symbol, r) {
c.writeSymbol(r)
return
}
c.endLexeme()
c.endSymbolRun(false)
c.atBoundary = false
}
func (c *textCounter) writeRune(r rune) {
if unicode.IsSpace(r) {
c.endUnit()
c.atBoundary = true
return
}
if unicode.Is(unicode.Han, r) {
c.endLexeme()
c.endSymbolRun(false)
c.stats.Breakdown.HanChars++
c.stats.WordCount++
c.stats.CharCount++
c.atBoundary = false
return
}
if isASCIILetterRune(r) {
c.endSymbolRun(false)
c.stats.Breakdown.EnglishLetters++
c.stats.CharCount++
if c.lexeme == lexemeNone || c.lexeme == lexemeNumber {
c.lexeme = lexemeEnglish
}
c.atBoundary = false
return
}
if isASCIIDigitRune(r) {
c.endSymbolRun(false)
c.stats.Breakdown.Digits++
c.stats.CharCount++
c.lexemeHasDigit = true
if c.lexeme == lexemeNone {
c.lexeme = lexemeNumber
}
c.atBoundary = false
return
}
if isChinesePunctuation(r) {
c.endLexeme()
c.endSymbolRun(false)
c.stats.Breakdown.ChinesePunctuations++
c.stats.WordCount++
c.stats.CharCount++
c.atBoundary = false
return
}
if isEnglishPunctuation(r) {
keepsLexeme := c.lexeme == lexemeEnglish && (r == '\'' || r == '-' || c.lexemeHasDigit && r == '.') ||
c.lexeme == lexemeNumber && (r == '.' || r == ',' || r == '-')
if !keepsLexeme {
hadLexeme := c.lexeme != lexemeNone
c.endLexeme()
if !hadLexeme && (c.symbolRunLength > 0 || c.atBoundary) {
c.symbolRunLength++
}
}
c.stats.Breakdown.EnglishPunctuations++
c.stats.CharCount++
if keepsLexeme {
c.atBoundary = false
}
return
}
if unicode.Is(unicode.Symbol, r) {
c.writeSymbol(r)
return
}
c.endLexeme()
c.endSymbolRun(false)
c.atBoundary = false
}
func matchASCIICompound(value string) string {
if match := urlToken.FindString(value); match != "" {
return match
}
match := asciiCompoundToken.FindString(value)
if match == "" || !strings.ContainsAny(match, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") {
return ""
}
return match
}
func (c *textCounter) writeASCIICompound(token string) {
c.endUnit()
c.stats.Breakdown.EnglishWords++
c.stats.WordCount++
for _, r := range token {
switch {
case isASCIILetterRune(r):
c.stats.Breakdown.EnglishLetters++
c.stats.CharCount++
case isASCIIDigitRune(r):
c.stats.Breakdown.Digits++
c.stats.CharCount++
case isEnglishPunctuation(r):
c.stats.Breakdown.EnglishPunctuations++
c.stats.CharCount++
}
}
c.atBoundary = false
}
func (c *textCounter) writeSymbol(r rune) {
c.endLexeme()
c.endSymbolRun(false)
units := utf16Units(r)
c.stats.Breakdown.SymbolWords++
c.stats.Breakdown.SymbolChars += units
c.stats.WordCount++
c.stats.CharCount += units
c.atBoundary = false
}
func (c *textCounter) endUnit() {
c.endLexeme()
c.endSymbolRun(true)
}
func (c *textCounter) endLexeme() {
switch c.lexeme {
case lexemeEnglish:
c.stats.Breakdown.EnglishWords++
c.stats.WordCount++
case lexemeNumber:
c.stats.Breakdown.NumberWords++
c.stats.WordCount++
}
c.lexeme = lexemeNone
c.lexemeHasDigit = false
}
func (c *textCounter) endSymbolRun(countWord bool) {
if c.symbolRunLength > 0 && countWord {
c.stats.Breakdown.SymbolWords++
c.stats.WordCount++
}
if c.symbolRunLength > 0 {
c.atBoundary = false
}
c.symbolRunLength = 0
}
func isVisibleHanSeparator(value string, offset, size int) bool {
if offset == 0 || offset+size >= len(value) {
return false
}
previous, _ := utf8.DecodeLastRuneInString(value[:offset])
next, _ := utf8.DecodeRuneInString(value[offset+size:])
return unicode.Is(unicode.Han, previous) && unicode.Is(unicode.Han, next)
}
func isASCIILetterRune(r rune) bool { return r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' }
func isASCIIDigitRune(r rune) bool { return r >= '0' && r <= '9' }
func isChinesePunctuation(r rune) bool {
if strings.ContainsRune(chinesePunctuation, r) {
return true
}
kind := width.LookupRune(r).Kind()
return unicode.Is(unicode.Punct, r) && (kind == width.EastAsianWide || kind == width.EastAsianFullwidth)
}
func isEnglishPunctuation(r rune) bool {
return r < utf8.RuneSelf && strings.ContainsRune(englishPunctuation, r)
}
func utf16Units(r rune) int {
if r > 0xffff {
return 2
}
return 1
}

View File

@@ -0,0 +1,572 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package docxparse
import (
"fmt"
"html"
"regexp"
"strconv"
"strings"
"unicode"
"unicode/utf8"
)
const (
MaxInputBytes = 20_000_000
MaxNestingDepth = 1024
)
var forbiddenXMLDeclaration = regexp.MustCompile(`(?i)<!\s*(?:DOCTYPE|ENTITY)\b`)
func validateSource(source string) error {
if len(source) > MaxInputBytes {
return fmt.Errorf("input is too large (%d bytes, limit %d)", len(source), MaxInputBytes)
}
if forbiddenXMLDeclaration.MatchString(source) {
return fmt.Errorf("XML input must not contain DOCTYPE or ENTITY declarations")
}
if !utf8.ValidString(source) {
return fmt.Errorf("input must be valid UTF-8")
}
return nil
}
func parseXML(source string) ([]*Node, error) {
if err := validateSource(source); err != nil {
return nil, err
}
source = strings.TrimPrefix(source, "\uFEFF")
root := newElement("__fragment__", nil)
stack := []*Node{root}
for i := 0; i < len(source); {
lt := strings.IndexByte(source[i:], '<')
if lt < 0 {
if err := validateXMLText(source[i:], i); err != nil {
return nil, err
}
appendText(stack[len(stack)-1], source[i:])
break
}
lt += i
if err := validateXMLText(source[i:lt], i); err != nil {
return nil, err
}
appendText(stack[len(stack)-1], source[i:lt])
token, end, state := scanXMLToken(source, lt)
switch state {
case tokenComment, tokenProcessingInstruction:
i = end
continue
case tokenCDATA:
appendTextValue(stack[len(stack)-1], token.text)
i = end
continue
case tokenInvalid:
return nil, fmt.Errorf("invalid XML token at byte %d", lt)
case tokenIncomplete:
return nil, fmt.Errorf("unterminated XML tag at byte %d", lt)
}
spec, allowed := lookupTag(token.name)
if !allowed {
return nil, fmt.Errorf("unsupported LarkOpenCLI tag <%s> at byte %d", token.name, lt)
}
canonical := spec.canonical
if token.spacingNormalized {
return nil, fmt.Errorf("invalid whitespace in XML tag <%s> at byte %d", token.name, lt)
}
if token.closing {
if isVoidTag(canonical) {
return nil, fmt.Errorf("void tag <%s/> must not have a closing tag", canonical)
}
if len(stack) == 1 {
return nil, fmt.Errorf("unexpected closing tag </%s> at byte %d", canonical, lt)
}
open := stack[len(stack)-1].tag
if open != canonical {
return nil, fmt.Errorf("mismatched closing tag </%s> at byte %d; expected </%s>", canonical, lt, open)
}
stack = stack[:len(stack)-1]
i = end
continue
}
if len(stack) > 1 && shouldAutoClose(stack[len(stack)-1].tag, canonical) {
return nil, fmt.Errorf("invalid <%s> inside <%s> at byte %d", canonical, stack[len(stack)-1].tag, lt)
}
attrs := normalizeAttributes(token.name, canonical, token.attrs)
node := newElement(canonical, attrs)
stack[len(stack)-1].addChild(node)
if !token.selfClosing && !isVoidTag(canonical) {
if len(stack) > MaxNestingDepth {
return nil, fmt.Errorf("XML nesting exceeds limit %d at byte %d", MaxNestingDepth, lt)
}
stack = append(stack, node)
}
i = end
}
if len(stack) > 1 {
return nil, fmt.Errorf("missing closing tag </%s> at end of input", stack[len(stack)-1].tag)
}
normalizeParsedLineBreaks(root.children, false, false)
for _, child := range root.children {
child.parent = nil
}
return root.children, nil
}
// normalizeParsedLineBreaks removes formatting newlines from ordinary XML,
// while source-bearing code/whiteboard blocks keep semantic
// line breaks as explicit <br/> nodes. str_replace pattern/replacement payloads
// retain raw newlines because their string matching semantics depend on them.
func normalizeParsedLineBreaks(nodes []*Node, sourceBlock, stringMutation bool) {
for _, node := range nodes {
if node == nil || node.typ != nodeElement {
continue
}
nextSourceBlock := sourceBlock || node.tag == "code" || node.tag == "whiteboard"
nextStringMutation := stringMutation || node.tag == "str_replace"
preserveRaw := nextStringMutation && (node.tag == "pattern" || node.tag == "replacement")
if node.tag == "code" || node.tag == "whiteboard" {
trimSourceBlockBoundaryNewlines(node.children)
}
children := make([]*Node, 0, len(node.children))
for _, child := range node.children {
if child.typ != nodeText || !strings.ContainsAny(child.text, "\r\n") {
children = append(children, child)
continue
}
switch {
case preserveRaw:
children = append(children, child)
case nextSourceBlock:
for _, replacement := range rawTextWithBreakNodes(child.text) {
replacement.parent = node
children = append(children, replacement)
}
default:
child.text = strings.NewReplacer("\r", "", "\n", "").Replace(child.text)
if child.text != "" {
children = append(children, child)
}
}
}
node.children = children
normalizeParsedLineBreaks(node.children, nextSourceBlock, nextStringMutation)
}
}
func trimSourceBlockBoundaryNewlines(children []*Node) {
for _, child := range children {
if child.typ == nodeText {
child.text = strings.TrimLeft(child.text, "\r\n")
break
}
if child.typ == nodeElement {
break
}
}
for i := len(children) - 1; i >= 0; i-- {
child := children[i]
if child.typ == nodeText {
child.text = strings.TrimRight(child.text, "\r\n")
break
}
if child.typ == nodeElement {
break
}
}
}
func rawTextWithBreakNodes(content string) []*Node {
if content == "" {
return nil
}
var nodes []*Node
start := 0
for i := 0; i < len(content); i++ {
if content[i] != '\n' && content[i] != '\r' {
continue
}
if i > start {
nodes = append(nodes, newText(content[start:i]))
}
if content[i] == '\r' && i+1 < len(content) && content[i+1] == '\n' {
i++
}
nodes = append(nodes, newElement("br", nil))
start = i + 1
}
if start < len(content) {
nodes = append(nodes, newText(content[start:]))
}
return nodes
}
type tokenState uint8
const (
tokenOK tokenState = iota
tokenInvalid
tokenIncomplete
tokenComment
tokenProcessingInstruction
tokenCDATA
)
type xmlToken struct {
name string
attrs map[string]string
text string
closing bool
selfClosing bool
spacingNormalized bool
}
func scanXMLToken(source string, start int) (xmlToken, int, tokenState) {
if strings.HasPrefix(source[start:], "<![CDATA[") {
const marker = "<![CDATA["
contentStart := start + len(marker)
if closeAt := strings.Index(source[contentStart:], "]]>"); closeAt >= 0 {
contentEnd := contentStart + closeAt
return xmlToken{text: source[contentStart:contentEnd]}, contentEnd + len("]]>"), tokenCDATA
}
return xmlToken{}, len(source), tokenIncomplete
}
if strings.HasPrefix(source[start:], "<!--") {
if closeAt := strings.Index(source[start+4:], "-->"); closeAt >= 0 {
if strings.Contains(source[start+4:start+4+closeAt], "--") {
return xmlToken{}, start + 1, tokenInvalid
}
return xmlToken{}, start + 4 + closeAt + 3, tokenComment
}
return xmlToken{}, len(source), tokenIncomplete
}
if strings.HasPrefix(source[start:], "<?") {
if closeAt := strings.Index(source[start+2:], "?>"); closeAt >= 0 {
return xmlToken{}, start + 2 + closeAt + 2, tokenProcessingInstruction
}
return xmlToken{}, len(source), tokenIncomplete
}
quote := byte(0)
end := -1
for i := start + 1; i < len(source); i++ {
switch source[i] {
case '\'', '"':
if quote == 0 {
quote = source[i]
} else if quote == source[i] {
quote = 0
}
case '>':
if quote == 0 {
end = i + 1
i = len(source)
}
case '<':
// A second unquoted '<' cannot belong to the current XML tag.
// Stop here so a long sequence of invalid tag starts is scanned
// once instead of repeatedly searching to a distant '>'.
if quote == 0 {
return xmlToken{}, start + 1, tokenInvalid
}
}
}
if end < 0 {
candidate := strings.TrimSpace(source[start+1:])
if candidate == "" || !isTagNameStart(candidate[0]) && candidate[0] != '/' {
return xmlToken{}, start + 1, tokenInvalid
}
return xmlToken{}, len(source), tokenIncomplete
}
body := source[start+1 : end-1]
if body == "" {
return xmlToken{}, end, tokenInvalid
}
token := xmlToken{}
position := 0
for position < len(body) && isXMLSpace(body[position]) {
position++
}
if position > 0 {
token.spacingNormalized = true
}
if position >= len(body) || body[position] == '!' {
return xmlToken{}, end, tokenInvalid
}
if body[position] == '/' {
token.closing = true
position++
spaceStart := position
for position < len(body) && isXMLSpace(body[position]) {
position++
}
if position > spaceStart {
token.spacingNormalized = true
}
}
if position >= len(body) || !isTagNameStart(body[position]) {
return xmlToken{}, end, tokenInvalid
}
nameStart := position
position++
for position < len(body) && isTagNamePart(body[position]) {
position++
}
token.name = body[nameStart:position]
rawRemainder := body[position:]
remainder := strings.TrimRightFunc(rawRemainder, unicode.IsSpace)
if token.closing {
if strings.TrimSpace(remainder) != "" {
return xmlToken{}, end, tokenInvalid
}
return token, end, tokenOK
}
if strings.HasSuffix(remainder, "/") {
if len(remainder) != len(rawRemainder) {
return xmlToken{}, end, tokenInvalid
}
token.selfClosing = true
remainder = strings.TrimRightFunc(strings.TrimSuffix(remainder, "/"), unicode.IsSpace)
}
trimmedAttrs := strings.TrimLeftFunc(remainder, unicode.IsSpace)
if trimmedAttrs != "" && !isAttributeNameStart(trimmedAttrs[0]) {
return xmlToken{}, end, tokenInvalid
}
var ok bool
token.attrs, ok = parseStrictAttributes(remainder)
if !ok {
return xmlToken{}, end, tokenInvalid
}
return token, end, tokenOK
}
func isXMLSpace(ch byte) bool {
return ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n'
}
func isTagNameStart(ch byte) bool {
return ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z'
}
func isTagNamePart(ch byte) bool {
return isTagNameStart(ch) || ch >= '0' && ch <= '9' || ch == '_' || ch == '-' || ch == '.' || ch == ':'
}
func isAttributeNameStart(ch byte) bool {
return isTagNameStart(ch) || ch == '_' || ch == ':'
}
func parseAttributes(source string) map[string]string {
attrs := map[string]string{}
for i := 0; i < len(source); {
for i < len(source) && unicode.IsSpace(rune(source[i])) {
i++
}
if i >= len(source) {
break
}
start := i
for i < len(source) && isAttributeNameByte(source[i]) {
i++
}
if start == i {
i++
continue
}
name := source[start:i]
for i < len(source) && unicode.IsSpace(rune(source[i])) {
i++
}
value := ""
if i < len(source) && source[i] == '=' {
i++
for i < len(source) && unicode.IsSpace(rune(source[i])) {
i++
}
if i < len(source) && (source[i] == '\'' || source[i] == '"') {
quote := source[i]
i++
start = i
for i < len(source) && source[i] != quote {
i++
}
value = source[start:i]
if i < len(source) {
i++
}
} else {
start = i
for i < len(source) && !unicode.IsSpace(rune(source[i])) {
i++
}
value = source[start:i]
}
}
attrs[name] = html.UnescapeString(value)
}
if len(attrs) == 0 {
return nil
}
return attrs
}
// parseStrictAttributes implements the quoted attribute grammar accepted by
// XML. parseAttributes remains intentionally permissive for the Markdown
// container extension, whose input is Markdown rather than an XML document.
func parseStrictAttributes(source string) (map[string]string, bool) {
attrs := map[string]string{}
for i := 0; i < len(source); {
spaceStart := i
for i < len(source) && isXMLSpace(source[i]) {
i++
}
if i >= len(source) {
break
}
if i == spaceStart || !isAttributeNameStart(source[i]) {
return nil, false
}
nameStart := i
i++
for i < len(source) && isTagNamePart(source[i]) {
i++
}
name := source[nameStart:i]
if _, exists := attrs[name]; exists {
return nil, false
}
for i < len(source) && isXMLSpace(source[i]) {
i++
}
if i >= len(source) || source[i] != '=' {
return nil, false
}
i++
for i < len(source) && isXMLSpace(source[i]) {
i++
}
if i >= len(source) || (source[i] != '\'' && source[i] != '"') {
return nil, false
}
quote := source[i]
i++
valueStart := i
for i < len(source) && source[i] != quote {
if source[i] == '<' {
return nil, false
}
i++
}
if i >= len(source) {
return nil, false
}
rawValue := normalizeXMLAttributeAmpersands(source[valueStart:i])
if invalidXMLEntityAt(rawValue) >= 0 {
return nil, false
}
attrs[name] = html.UnescapeString(rawValue)
i++
}
if len(attrs) == 0 {
return nil, true
}
return attrs, true
}
func isAttributeNameByte(ch byte) bool {
return ch > ' ' && ch != '=' && ch != '/' && ch != '>'
}
func appendText(parent *Node, raw string) {
if parent == nil || raw == "" {
return
}
appendTextValue(parent, html.UnescapeString(raw))
}
func appendTextValue(parent *Node, text string) {
if parent == nil || text == "" {
return
}
if strings.TrimSpace(text) == "" && !preserveSpaceTags[parent.tag] && parent.tag != "whiteboard" {
return
}
if count := len(parent.children); count > 0 && parent.children[count-1].typ == nodeText {
parent.children[count-1].text += text
return
}
parent.addChild(newText(text))
}
func validateXMLText(value string, absoluteOffset int) error {
if offset := strings.Index(value, "]]>"); offset >= 0 {
return fmt.Errorf("invalid ]]> sequence in XML text at byte %d", absoluteOffset+offset)
}
if offset := invalidXMLEntityAt(value); offset >= 0 {
return fmt.Errorf("invalid XML entity at byte %d", absoluteOffset+offset)
}
return nil
}
func invalidXMLEntityAt(value string) int {
for cursor := 0; cursor < len(value); {
relative := strings.IndexByte(value[cursor:], '&')
if relative < 0 {
return -1
}
start := cursor + relative
endRelative := strings.IndexByte(value[start+1:], ';')
if endRelative < 0 {
return start
}
end := start + 1 + endRelative
if !isValidXMLEntity(value[start+1 : end]) {
return start
}
cursor = end + 1
}
return -1
}
func isValidXMLEntity(entity string) bool {
switch entity {
case "amp", "lt", "gt", "quot", "apos":
return true
}
base := 10
digits := ""
switch {
case strings.HasPrefix(entity, "#x"):
base = 16
digits = entity[2:]
case strings.HasPrefix(entity, "#"):
digits = entity[1:]
default:
return false
}
if digits == "" {
return false
}
value, err := strconv.ParseUint(digits, base, 32)
if err != nil {
return false
}
r := rune(value)
return r == '\t' || r == '\n' || r == '\r' ||
r >= 0x20 && r <= 0xD7FF ||
r >= 0xE000 && r <= 0xFFFD ||
r >= 0x10000 && r <= utf8.MaxRune
}

View File

@@ -0,0 +1,62 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package docxparse
import "strings"
// normalizeXMLAttributeAmpersands escapes bare ampersands in an XML attribute
// value so local parsing matches the server SDK. Complete entity references
// remain untouched for the strict parser to validate.
func normalizeXMLAttributeAmpersands(value string) string {
firstBare := -1
for cursor := 0; cursor < len(value); {
relative := strings.IndexByte(value[cursor:], '&')
if relative < 0 {
break
}
ampersand := cursor + relative
if isBareXMLAttributeAmpersand(value, ampersand) {
firstBare = ampersand
break
}
cursor = ampersand + 1
}
if firstBare < 0 {
return value
}
var out strings.Builder
out.Grow(len(value))
out.WriteString(value[:firstBare])
for i := firstBare; i < len(value); i++ {
if value[i] == '&' && isBareXMLAttributeAmpersand(value, i) {
out.WriteString("&amp;")
continue
}
out.WriteByte(value[i])
}
return out.String()
}
func isBareXMLAttributeAmpersand(value string, start int) bool {
if start+1 >= len(value) {
return true
}
if value[start+1] == '#' {
return false
}
if !isTagNameStart(value[start+1]) && value[start+1] != '_' {
return true
}
for i := start + 2; i < len(value); i++ {
if value[i] == ';' {
return false
}
if !isTagNamePart(value[i]) {
return true
}
}
return true
}

View File

@@ -33,6 +33,8 @@ func docsSkillReadCommandForShortcut(shortcut string) string {
return docsSkillReadCommand + " references/lark-doc-update.md"
case "history-list", "history-revert", "history-revert-status":
return docsSkillReadCommand + " references/lark-doc-history.md"
case "script":
return docsSkillReadCommand + " references/lark-doc-script.md"
default:
return docsSkillReadCommand
}
@@ -52,6 +54,8 @@ func docsHelpCommandForShortcut(shortcut string) string {
return "lark-cli docs +history-revert --help"
case "history-revert-status":
return "lark-cli docs +history-revert-status --help"
case "script":
return "lark-cli docs +script --help"
default:
return "lark-cli docs --help"
}
@@ -64,6 +68,7 @@ func Shortcuts() []common.Shortcut {
DocsCreate,
DocsFetch,
DocsUpdate,
DocsScript,
DocsHistoryList,
DocsHistoryRevert,
DocsHistoryRevertStatus,

View File

@@ -3,11 +3,24 @@
package slides
import "github.com/larksuite/cli/shortcuts/common"
import (
"github.com/larksuite/cli/shortcuts/common"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
var presentationFlagAliases = []string{
"presentation-id",
"presentation-token",
"token",
"presentation_id",
"xml-presentation-id",
"url",
}
// Shortcuts returns all slides shortcuts.
func Shortcuts() []common.Shortcut {
return []common.Shortcut{
all := []common.Shortcut{
SlidesCreate,
SlidesMediaUpload,
SlidesReplaceSlide,
@@ -18,4 +31,39 @@ func Shortcuts() []common.Shortcut {
SlidesHistoryRevert,
SlidesHistoryRevertStatus,
}
for i := range all {
if hasPresentationFlag(all[i].Flags) {
all[i].PostMount = withPresentationFlagAliases(all[i].PostMount)
}
}
return all
}
func hasPresentationFlag(flags []common.Flag) bool {
for _, flag := range flags {
if flag.Name == "presentation" {
return true
}
}
return false
}
// withPresentationFlagAliases accepts common agent-generated spellings for
// --presentation without registering extra flags. The aliases therefore stay
// out of help and completion while resolving to the canonical flag at parse
// time, matching the zero-round-trip compatibility used by Sheets.
func withPresentationFlagAliases(prev func(cmd *cobra.Command)) func(cmd *cobra.Command) {
return func(cmd *cobra.Command) {
if prev != nil {
prev(cmd)
}
cmd.Flags().SetNormalizeFunc(func(_ *pflag.FlagSet, name string) pflag.NormalizedName {
for _, alias := range presentationFlagAliases {
if name == alias {
return pflag.NormalizedName("presentation")
}
}
return pflag.NormalizedName(name)
})
}
}

View File

@@ -0,0 +1,68 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package slides
import (
"strings"
"testing"
"github.com/spf13/cobra"
)
func TestWithPresentationFlagAliases(t *testing.T) {
for _, alias := range presentationFlagAliases {
t.Run(alias, func(t *testing.T) {
cmd := &cobra.Command{Use: "test"}
cmd.Flags().String("presentation", "", "presentation reference")
withPresentationFlagAliases(nil)(cmd)
if err := cmd.Flags().Parse([]string{"--" + alias, "presABC"}); err != nil {
t.Fatalf("--%s should resolve to --presentation: %v", alias, err)
}
got, err := cmd.Flags().GetString("presentation")
if err != nil {
t.Fatalf("read --presentation: %v", err)
}
if got != "presABC" {
t.Fatalf("--%s set --presentation to %q, want presABC", alias, got)
}
if usage := cmd.Flags().FlagUsages(); strings.Contains(usage, "--"+alias) {
t.Fatalf("hidden compatibility alias --%s leaked into help:\n%s", alias, usage)
}
})
}
}
func TestShortcutsAttachPresentationFlagAliases(t *testing.T) {
count := 0
for _, shortcut := range Shortcuts() {
if !hasPresentationFlag(shortcut.Flags) {
continue
}
count++
if shortcut.PostMount == nil {
t.Errorf("%s has --presentation but no compatibility normalizer", shortcut.Command)
continue
}
cmd := &cobra.Command{Use: shortcut.Command}
cmd.Flags().String("presentation", "", "presentation reference")
shortcut.PostMount(cmd)
if err := cmd.Flags().Parse([]string{"--token", "presABC"}); err != nil {
t.Errorf("%s did not normalize --token: %v", shortcut.Command, err)
continue
}
got, err := cmd.Flags().GetString("presentation")
if err != nil {
t.Errorf("%s could not read --presentation: %v", shortcut.Command, err)
continue
}
if got != "presABC" {
t.Errorf("%s normalized --token to %q, want presABC", shortcut.Command, got)
}
}
if count == 0 {
t.Fatal("expected at least one slides shortcut with --presentation")
}
}

View File

@@ -37,9 +37,7 @@ var SlidesScreenshot = common.Shortcut{
Command: "+screenshot",
Description: "Save up to 10 slide screenshots to local files without printing Base64 image data",
Risk: "read",
Scopes: []string{},
// The screenshot API is allowlist-gated for only a few apps, so do not
// advertise/preflight its scope. Let the API fail and let callers degrade.
Scopes: []string{"slides:presentation:screenshot"},
// wiki:node:read is required only when --presentation is a wiki URL.
ConditionalScopes: []string{"wiki:node:read"},
AuthTypes: []string{"user", "bot"},

View File

@@ -8,6 +8,7 @@ import (
"encoding/json"
"os"
"path/filepath"
"reflect"
"strings"
"testing"
@@ -17,23 +18,19 @@ import (
)
func TestSlidesScreenshotDeclaredScopes(t *testing.T) {
if got := SlidesScreenshot.ScopesForIdentity("user"); len(got) != 0 {
t.Fatalf("user preflight scopes = %#v, want empty", got)
base := []string{"slides:presentation:screenshot"}
if got := SlidesScreenshot.ScopesForIdentity("user"); !reflect.DeepEqual(got, base) {
t.Fatalf("user preflight scopes = %#v, want %#v", got, base)
}
if got := SlidesScreenshot.ScopesForIdentity("bot"); len(got) != 0 {
t.Fatalf("bot preflight scopes = %#v, want empty", got)
if got := SlidesScreenshot.ScopesForIdentity("bot"); !reflect.DeepEqual(got, base) {
t.Fatalf("bot preflight scopes = %#v, want %#v", got, base)
}
got := SlidesScreenshot.DeclaredScopesForIdentity("user")
want := []string{"wiki:node:read"}
if len(got) != len(want) || got[0] != want[0] {
want := []string{"slides:presentation:screenshot", "wiki:node:read"}
if !reflect.DeepEqual(got, want) {
t.Fatalf("declared scopes = %#v, want %#v", got, want)
}
for _, scope := range got {
if scope == "slides:presentation:screenshot" {
t.Fatalf("declared scopes must not advertise screenshot scope: %#v", got)
}
}
}
func TestSlidesScreenshotWritesFilesAndSuppressesBase64(t *testing.T) {

View File

@@ -10,6 +10,7 @@ import (
"io"
"net/http"
"net/url"
"regexp"
"strings"
"time"
@@ -100,6 +101,40 @@ func extractTaskGuid(input string) string {
return extractTasklistGuid(input)
}
var taskDisplayNumberPattern = regexp.MustCompile(`^t[0-9]+$`)
func parseTaskGUID(input string) (string, error) {
input = strings.TrimSpace(input)
invalid := func(format string, args ...interface{}) *errs.ValidationError {
return errs.NewValidationError(errs.SubtypeInvalidArgument, format, args...).
WithParam("--task-id").
WithHint("provide the Task OpenAPI GUID or a task applink containing guid=")
}
if input == "" {
return "", invalid("task ID is empty")
}
lowerInput := strings.ToLower(input)
if strings.HasPrefix(lowerInput, "http://") || strings.HasPrefix(lowerInput, "https://") {
u, err := url.Parse(input)
if err != nil {
return "", invalid("invalid task applink: %v", err).WithCause(err)
}
guid := strings.TrimSpace(u.Query().Get("guid"))
if guid == "" {
return "", invalid("task applink is missing a non-empty guid query parameter")
}
return guid, nil
}
if taskDisplayNumberPattern.MatchString(input) {
return "", invalid("task display number %q is not a Task OpenAPI GUID", input)
}
return input, nil
}
func buildTaskCreateBody(runtime *common.RuntimeContext) (map[string]interface{}, error) {
body := make(map[string]interface{})

View File

@@ -4,8 +4,11 @@
package task
import (
"errors"
"net/url"
"testing"
"github.com/larksuite/cli/errs"
"github.com/smartystreets/goconvey/convey"
)
@@ -15,3 +18,80 @@ func TestShortcutsRegistration(t *testing.T) {
convey.So(len(list), convey.ShouldBeGreaterThan, 0)
})
}
func TestParseTaskGUID(t *testing.T) {
t.Run("accepts GUIDs and task applinks", func(t *testing.T) {
tests := []struct {
name string
input string
want string
}{
{name: "opaque GUID", input: "task-guid-123", want: "task-guid-123"},
{name: "trimmed GUID", input: " task-guid-123 ", want: "task-guid-123"},
{
name: "task applink",
input: "https://applink.larksuite.com/client/todo/detail?guid=task-guid-123",
want: "task-guid-123",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := parseTaskGUID(tt.input)
if err != nil {
t.Fatalf("parseTaskGUID(%q) error = %v", tt.input, err)
}
if got != tt.want {
t.Fatalf("parseTaskGUID(%q) = %q, want %q", tt.input, got, tt.want)
}
})
}
})
t.Run("rejects unusable task identifiers", func(t *testing.T) {
for _, input := range []string{
"",
"https://applink.larksuite.com/client/todo/detail",
"https://%",
"t12345",
} {
t.Run(input, func(t *testing.T) {
_, err := parseTaskGUID(input)
if err == nil {
t.Fatalf("parseTaskGUID(%q) error = nil, want typed validation error", input)
}
problem, ok := errs.ProblemOf(err)
if !ok {
t.Fatalf("parseTaskGUID(%q) error type = %T, want typed error", input, err)
}
if problem.Category != errs.CategoryValidation || problem.Subtype != errs.SubtypeInvalidArgument {
t.Fatalf("problem = %s/%s, want %s/%s", problem.Category, problem.Subtype, errs.CategoryValidation, errs.SubtypeInvalidArgument)
}
if problem.Hint == "" {
t.Fatal("problem hint is empty")
}
var validationErr *errs.ValidationError
if !errors.As(err, &validationErr) {
t.Fatalf("error type = %T, want *errs.ValidationError", err)
}
if validationErr.Param != "--task-id" {
t.Fatalf("param = %q, want %q", validationErr.Param, "--task-id")
}
})
}
})
t.Run("preserves applink parse cause", func(t *testing.T) {
_, err := parseTaskGUID("https://%")
if err == nil {
t.Fatal("parseTaskGUID() error = nil, want URL parse error")
}
var urlErr *url.Error
if !errors.As(err, &urlErr) {
t.Fatalf("error chain = %T %v, want *url.Error cause", err, err)
}
})
}

View File

@@ -25,45 +25,59 @@ var CompleteTask = common.Shortcut{
HasFormat: true,
Flags: []common.Flag{
{Name: "task-id", Desc: "task id", Required: true},
{Name: "task-id", Desc: "task GUID or task applink URL", Required: true},
},
Validate: func(ctx context.Context, runtime *common.RuntimeContext) error {
_, err := parseTaskGUID(runtime.Str("task-id"))
return err
},
DryRun: func(ctx context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
body := buildCompleteBody()
taskId := url.PathEscape(runtime.Str("task-id"))
taskGUID, err := parseTaskGUID(runtime.Str("task-id"))
if err != nil {
return common.NewDryRunAPI().Set("error", err.Error())
}
taskID := url.PathEscape(taskGUID)
return common.NewDryRunAPI().
GET("/open-apis/task/v2/tasks/" + taskId).
GET("/open-apis/task/v2/tasks/" + taskID).
Desc("get current task status").
Params(map[string]interface{}{"user_id_type": "open_id"}).
PATCH("/open-apis/task/v2/tasks/" + taskId).
PATCH("/open-apis/task/v2/tasks/" + taskID).
Desc("complete task if not completed").
Params(map[string]interface{}{"user_id_type": "open_id"}).
Body(body)
},
Execute: func(ctx context.Context, runtime *common.RuntimeContext) error {
taskId := url.PathEscape(runtime.Str("task-id"))
taskGUID, err := parseTaskGUID(runtime.Str("task-id"))
if err != nil {
return err
}
taskID := url.PathEscape(taskGUID)
params := map[string]interface{}{"user_id_type": "open_id"}
var data map[string]interface{}
// 1. Get current task status
getData, err := callTaskAPITyped(runtime, http.MethodGet, "/open-apis/task/v2/tasks/"+taskId, params, nil)
getData, err := callTaskAPITyped(runtime, http.MethodGet, "/open-apis/task/v2/tasks/"+taskID, params, nil)
if err != nil {
return err
}
taskData, _ := getData["task"].(map[string]interface{})
completedAtStr, _ := taskData["completed_at"].(string)
alreadyCompleted := completedAtStr != "" && completedAtStr != "0"
// 2. If already completed, directly return success
if completedAtStr != "" && completedAtStr != "0" {
if alreadyCompleted {
data = getData
} else {
// 3. Complete the task
body := buildCompleteBody()
data, err = callTaskAPITyped(runtime, http.MethodPatch, "/open-apis/task/v2/tasks/"+taskId, params, body)
data, err = callTaskAPITyped(runtime, http.MethodPatch, "/open-apis/task/v2/tasks/"+taskID, params, body)
if err != nil {
return err
}
@@ -73,11 +87,19 @@ var CompleteTask = common.Shortcut{
guid, _ := task["guid"].(string)
urlVal, _ := task["url"].(string)
urlVal = truncateTaskURL(urlVal)
completedAt, _ := task["completed_at"].(string)
status := "todo"
if completedAt != "" && completedAt != "0" {
status = "done"
}
// Standardized write output: return resource identifiers
outData := map[string]interface{}{
"guid": guid,
"url": urlVal,
"guid": guid,
"url": urlVal,
"status": status,
"completed_at": completedAt,
"already_completed": alreadyCompleted,
}
runtime.OutFormat(outData, nil, func(w io.Writer) {

View File

@@ -4,9 +4,12 @@
package task
import (
"encoding/json"
"errors"
"strings"
"testing"
"github.com/larksuite/cli/errs"
"github.com/larksuite/cli/internal/httpmock"
)
@@ -45,6 +48,9 @@ func TestCompleteTask(t *testing.T) {
formatFlag: "json",
expectedOutput: []string{
`"guid": "task-789"`,
`"status": "done"`,
`"completed_at": "1775174400000"`,
`"already_completed": false`,
},
},
}
@@ -109,3 +115,98 @@ func TestCompleteTask(t *testing.T) {
})
}
}
func TestTaskCompleteAcceptsTaskApplink(t *testing.T) {
f, stdout, _, reg := taskShortcutTestFactory(t)
warmTenantToken(t, f, reg)
for _, method := range []string{"GET", "PATCH"} {
reg.Register(&httpmock.Stub{
Method: method,
URL: "/open-apis/task/v2/tasks/task-guid-applink",
Body: map[string]interface{}{
"code": 0, "msg": "success",
"data": map[string]interface{}{
"task": map[string]interface{}{
"guid": "task-guid-applink",
"summary": "Applink task",
"completed_at": map[string]string{"GET": "0", "PATCH": "1775174400000"}[method],
"url": "https://example.com/task-guid-applink",
},
},
},
})
}
err := runMountedTaskShortcut(t, CompleteTask, []string{
"+complete",
"--task-id", "https://applink.larksuite.com/client/todo/detail?guid=task-guid-applink",
"--format", "json",
"--as", "bot",
}, f, stdout)
if err != nil {
t.Fatalf("CompleteTask error = %v", err)
}
reg.Verify(t)
if !strings.Contains(stdout.String(), `"guid": "task-guid-applink"`) {
t.Fatalf("output = %s, want normalized task GUID", stdout.String())
}
}
func TestTaskCompleteAlreadyCompletedReturnsServerState(t *testing.T) {
f, stdout, _, reg := taskShortcutTestFactory(t)
warmTenantToken(t, f, reg)
reg.Register(&httpmock.Stub{
Method: "GET",
URL: "/open-apis/task/v2/tasks/task-guid-done",
Body: map[string]interface{}{
"code": 0, "msg": "success",
"data": map[string]interface{}{
"task": map[string]interface{}{
"guid": "task-guid-done",
"summary": "Already done",
"completed_at": "1775174400000",
"url": "https://example.com/task-guid-done",
},
},
},
})
err := runMountedTaskShortcut(t, CompleteTask, []string{
"+complete", "--task-id", "task-guid-done", "--format", "json", "--as", "bot",
}, f, stdout)
if err != nil {
t.Fatalf("CompleteTask error = %v", err)
}
reg.Verify(t)
var envelope map[string]interface{}
if err := json.Unmarshal(stdout.Bytes(), &envelope); err != nil {
t.Fatalf("decode output: %v\n%s", err, stdout.String())
}
data, _ := envelope["data"].(map[string]interface{})
if data["status"] != "done" || data["completed_at"] != "1775174400000" || data["already_completed"] != true {
t.Fatalf("completion state = %#v, want done/already_completed server state", data)
}
}
func TestTaskCompleteRejectsDisplayNumberBeforeRead(t *testing.T) {
f, stdout, _, reg := taskShortcutTestFactory(t)
warmTenantToken(t, f, reg)
err := runMountedTaskShortcut(t, CompleteTask, []string{
"+complete", "--task-id", "t12345", "--format", "json", "--as", "bot",
}, f, stdout)
if err == nil {
t.Fatal("CompleteTask error = nil, want invalid task ID error")
}
problem, ok := errs.ProblemOf(err)
if !ok || problem.Category != errs.CategoryValidation || problem.Subtype != errs.SubtypeInvalidArgument {
t.Fatalf("error = %T %v, want typed invalid-argument error", err, err)
}
var validationErr *errs.ValidationError
if !errors.As(err, &validationErr) || validationErr.Param != "--task-id" {
t.Fatalf("error param = %#v, want --task-id", validationErr)
}
}

View File

@@ -24,6 +24,14 @@ func splitAndTrimCSV(input string) []string {
return out
}
func buildSearchPageParams(pageToken string) map[string]interface{} {
params := map[string]interface{}{}
if pageToken != "" {
params["page_token"] = pageToken
}
return params
}
func parseTimeRangeMillis(input string) (string, string, error) {
if strings.TrimSpace(input) == "" {
return "", "", nil

View File

@@ -37,6 +37,31 @@ func TestSplitAndTrimCSV(t *testing.T) {
}
}
func TestBuildSearchPageParams(t *testing.T) {
tests := []struct {
name string
pageToken string
wantToken string
wantKey bool
}{
{name: "first page omits token"},
{name: "subsequent page includes token", pageToken: "pt_123", wantToken: "pt_123", wantKey: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
params := buildSearchPageParams(tt.pageToken)
got, present := params["page_token"]
if present != tt.wantKey {
t.Fatalf("page_token present = %v, want %v; params = %#v", present, tt.wantKey, params)
}
if tt.wantKey && got != tt.wantToken {
t.Fatalf("page_token = %v, want %q", got, tt.wantToken)
}
})
}
}
func TestOutputTaskSummary(t *testing.T) {
tests := []struct {
name string

View File

@@ -44,8 +44,10 @@ var SearchTask = common.Shortcut{
if err != nil {
return common.NewDryRunAPI().Set("error", err.Error())
}
params := buildSearchPageParams(runtime.Str("page-token"))
return common.NewDryRunAPI().
POST("/open-apis/task/v2/tasks/search").
Params(params).
Body(body).
Desc("Then GET /open-apis/task/v2/tasks/:guid for each search hit to render standard output")
},
@@ -74,9 +76,9 @@ var SearchTask = common.Shortcut{
var lastPageToken string
var lastHasMore bool
var notice string
currentBody := body
params := buildSearchPageParams(runtime.Str("page-token"))
for page := 0; page < pageLimit; page++ {
data, err := callTaskAPITyped(runtime, http.MethodPost, "/open-apis/task/v2/tasks/search", nil, currentBody)
data, err := callTaskAPITyped(runtime, http.MethodPost, "/open-apis/task/v2/tasks/search", params, body)
if err != nil {
return err
}
@@ -90,7 +92,7 @@ var SearchTask = common.Shortcut{
if !lastHasMore || lastPageToken == "" {
break
}
currentBody["page_token"] = lastPageToken
params["page_token"] = lastPageToken
}
enriched := make([]map[string]interface{}, 0, len(rawItems))
@@ -183,9 +185,6 @@ func buildTaskSearchBody(runtime *common.RuntimeContext) (map[string]interface{}
if len(filter) > 0 {
body["filter"] = filter
}
if pageToken := runtime.Str("page-token"); pageToken != "" {
body["page_token"] = pageToken
}
return body, nil
}

View File

@@ -0,0 +1,129 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package task
import (
"encoding/json"
"io"
"net/http"
"reflect"
"testing"
"github.com/larksuite/cli/internal/httpmock"
"github.com/larksuite/cli/shortcuts/common"
)
func TestSearchPaginationUsesQueryToken(t *testing.T) {
tests := []struct {
name string
shortcut common.Shortcut
command string
url string
}{
{
name: "tasks",
shortcut: SearchTask,
command: "+search",
url: "/open-apis/task/v2/tasks/search",
},
{
name: "tasklists",
shortcut: SearchTasklist,
command: "+tasklist-search",
url: "/open-apis/task/v2/tasklists/search",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
f, stdout, _, reg := taskShortcutTestFactory(t)
warmTenantToken(t, f, reg)
var pageTokens []string
reg.Register(searchPaginationStub(t, tt.url, "next_pt", true, &pageTokens))
reg.Register(searchPaginationStub(t, tt.url, "", false, &pageTokens))
shortcut := tt.shortcut
shortcut.AuthTypes = []string{"bot", "user"}
err := runMountedTaskShortcut(t, shortcut, []string{
tt.command,
"--query", "pagination",
"--page-token", "initial_pt",
"--page-limit", "2",
"--as", "bot",
"--format", "json",
}, f, stdout)
if err != nil {
t.Fatalf("search command failed: %v", err)
}
want := []string{"initial_pt", "next_pt"}
if !reflect.DeepEqual(pageTokens, want) {
t.Fatalf("search page tokens = %#v, want %#v", pageTokens, want)
}
})
}
}
func assertSearchDryRunPageToken(t *testing.T, preview *common.DryRunAPI, want string) {
t.Helper()
data, err := preview.MarshalJSON()
if err != nil {
t.Fatalf("marshal search dry-run preview: %v", err)
}
var envelope struct {
API []struct {
Params map[string]interface{} `json:"params"`
Body map[string]interface{} `json:"body"`
} `json:"api"`
}
if err := json.Unmarshal(data, &envelope); err != nil {
t.Fatalf("decode search dry-run preview: %v", err)
}
if len(envelope.API) != 1 {
t.Fatalf("search dry-run API call count = %d, want 1; preview = %s", len(envelope.API), data)
}
call := envelope.API[0]
if got, _ := call.Params["page_token"].(string); got != want {
t.Fatalf("search dry-run params.page_token = %q, want %q; preview = %s", got, want, data)
}
if _, present := call.Body["page_token"]; present {
t.Fatalf("search dry-run body unexpectedly contains page_token; preview = %s", data)
}
}
func searchPaginationStub(t *testing.T, endpoint, responseToken string, hasMore bool, capturedTokens *[]string) *httpmock.Stub {
t.Helper()
return &httpmock.Stub{
Method: http.MethodPost,
URL: endpoint,
OnMatch: func(req *http.Request) {
*capturedTokens = append(*capturedTokens, req.URL.Query().Get("page_token"))
body, err := io.ReadAll(req.Body)
if err != nil {
t.Errorf("read search request body: %v", err)
return
}
var payload map[string]interface{}
if err := json.Unmarshal(body, &payload); err != nil {
t.Errorf("decode search request body: %v", err)
return
}
if _, present := payload["page_token"]; present {
t.Errorf("search request body unexpectedly contains page_token: %s", body)
}
},
Body: map[string]interface{}{
"code": 0,
"msg": "success",
"data": map[string]interface{}{
"has_more": hasMore,
"page_token": responseToken,
"items": []interface{}{},
},
},
}
}

View File

@@ -37,9 +37,12 @@ func TestBuildTaskSearchBody(t *testing.T) {
check: func(t *testing.T, body map[string]interface{}) {
filter := body["filter"].(map[string]interface{})
dueTime := filter["due_time"].(map[string]interface{})
if body["query"] != "release" || body["page_token"] != "pt_123" {
if body["query"] != "release" {
t.Fatalf("unexpected body: %#v", body)
}
if _, present := body["page_token"]; present {
t.Fatalf("body unexpectedly contains page_token: %#v", body)
}
if len(filter["creator_ids"].([]string)) != 2 || filter["is_completed"] != true {
t.Fatalf("unexpected filter: %#v", filter)
}
@@ -104,9 +107,10 @@ func TestBuildTaskSearchBody(t *testing.T) {
func TestSearchTask_DryRun(t *testing.T) {
tests := []struct {
name string
setup func(*cobra.Command)
wantParts []string
name string
setup func(*cobra.Command)
wantPageToken string
wantParts []string
}{
{
name: "valid dry run",
@@ -114,7 +118,8 @@ func TestSearchTask_DryRun(t *testing.T) {
_ = cmd.Flags().Set("query", "demo")
_ = cmd.Flags().Set("page-token", "pt_demo")
},
wantParts: []string{"POST /open-apis/task/v2/tasks/search", `"query":"demo"`},
wantPageToken: "pt_demo",
wantParts: []string{`"query":"demo"`},
},
{
name: "dry run error on invalid due",
@@ -143,7 +148,11 @@ func TestSearchTask_DryRun(t *testing.T) {
t.Fatalf("Validate() error = %v", err)
}
}
out := SearchTask.DryRun(nil, runtime).Format()
preview := SearchTask.DryRun(nil, runtime)
if tt.wantPageToken != "" {
assertSearchDryRunPageToken(t, preview, tt.wantPageToken)
}
out := preview.Format()
for _, want := range tt.wantParts {
if !strings.Contains(out, want) {
t.Fatalf("dry run output missing %q: %s", want, out)

View File

@@ -41,8 +41,10 @@ var SearchTasklist = common.Shortcut{
if err != nil {
return common.NewDryRunAPI().Set("error", err.Error())
}
params := buildSearchPageParams(runtime.Str("page-token"))
return common.NewDryRunAPI().
POST("/open-apis/task/v2/tasklists/search").
Params(params).
Body(body).
Desc("Then GET /open-apis/task/v2/tasklists/:guid for each search hit to render standard output")
},
@@ -71,9 +73,9 @@ var SearchTasklist = common.Shortcut{
var lastPageToken string
var lastHasMore bool
var notice string
currentBody := body
params := buildSearchPageParams(runtime.Str("page-token"))
for page := 0; page < pageLimit; page++ {
data, err := callTaskAPITyped(runtime, http.MethodPost, "/open-apis/task/v2/tasklists/search", nil, currentBody)
data, err := callTaskAPITyped(runtime, http.MethodPost, "/open-apis/task/v2/tasklists/search", params, body)
if err != nil {
return err
}
@@ -87,7 +89,7 @@ var SearchTasklist = common.Shortcut{
if !lastHasMore || lastPageToken == "" {
break
}
currentBody["page_token"] = lastPageToken
params["page_token"] = lastPageToken
}
tasklists := make([]map[string]interface{}, 0, len(rawItems))
@@ -170,9 +172,6 @@ func buildTasklistSearchBody(runtime *common.RuntimeContext) (map[string]interfa
if len(filter) > 0 {
body["filter"] = filter
}
if pageToken := runtime.Str("page-token"); pageToken != "" {
body["page_token"] = pageToken
}
return body, nil
}

View File

@@ -33,8 +33,8 @@ func TestBuildTasklistSearchBody(t *testing.T) {
check: func(t *testing.T, body map[string]interface{}) {
filter := body["filter"].(map[string]interface{})
createTime := filter["create_time"].(map[string]interface{})
if body["page_token"] != "pt_tl" {
t.Fatalf("unexpected body: %#v", body)
if _, present := body["page_token"]; present {
t.Fatalf("body unexpectedly contains page_token: %#v", body)
}
if filter["user_id"].([]string)[0] != "ou_creator" {
t.Fatalf("unexpected filter: %#v", filter)
@@ -80,9 +80,10 @@ func TestBuildTasklistSearchBody(t *testing.T) {
func TestSearchTasklist_DryRun(t *testing.T) {
tests := []struct {
name string
setup func(*cobra.Command)
wantParts []string
name string
setup func(*cobra.Command)
wantPageToken string
wantParts []string
}{
{
name: "valid dry run",
@@ -90,7 +91,8 @@ func TestSearchTasklist_DryRun(t *testing.T) {
_ = cmd.Flags().Set("query", "Q2")
_ = cmd.Flags().Set("page-token", "pt_tl")
},
wantParts: []string{"POST /open-apis/task/v2/tasklists/search", `"query":"Q2"`},
wantPageToken: "pt_tl",
wantParts: []string{`"query":"Q2"`},
},
{
name: "dry run error on invalid create time",
@@ -116,7 +118,11 @@ func TestSearchTasklist_DryRun(t *testing.T) {
t.Fatalf("Validate() error = %v", err)
}
}
out := SearchTasklist.DryRun(nil, runtime).Format()
preview := SearchTasklist.DryRun(nil, runtime)
if tt.wantPageToken != "" {
assertSearchDryRunPageToken(t, preview, tt.wantPageToken)
}
out := preview.Format()
for _, want := range tt.wantParts {
if !strings.Contains(out, want) {
t.Fatalf("dry run output missing %q: %s", want, out)

View File

@@ -27,27 +27,42 @@ var UpdateTask = common.Shortcut{
HasFormat: true,
Flags: []common.Flag{
{Name: "task-id", Desc: "task id (comma-separated for multiple)", Required: true},
{Name: "task-id", Desc: "task GUID or task applink URL (comma-separated for multiple)", Required: true},
{Name: "summary", Desc: "task title"},
{Name: "description", Desc: "task description"},
{Name: "due", Desc: "due date (ISO 8601 / date:YYYY-MM-DD / relative:+2d / ms timestamp)"},
{Name: "data", Desc: "JSON payload for task object"},
},
Validate: func(ctx context.Context, runtime *common.RuntimeContext) error {
_, err := parseTaskGUIDs(runtime.Str("task-id"))
return err
},
DryRun: func(ctx context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
body, err := buildTaskUpdateBody(runtime)
if err != nil {
return common.NewDryRunAPI().Set("error", err.Error())
}
taskIds := strings.Split(runtime.Str("task-id"), ",")
taskId := url.PathEscape(strings.TrimSpace(taskIds[0]))
return common.NewDryRunAPI().
PATCH("/open-apis/task/v2/tasks/" + taskId).
Params(map[string]interface{}{"user_id_type": "open_id"}).
Body(body)
taskIDs, err := parseTaskGUIDs(runtime.Str("task-id"))
if err != nil {
return common.NewDryRunAPI().Set("error", err.Error())
}
preview := common.NewDryRunAPI()
for _, taskID := range taskIDs {
preview.PATCH("/open-apis/task/v2/tasks/" + url.PathEscape(taskID)).
Params(map[string]interface{}{"user_id_type": "open_id"}).
Body(body)
}
return preview
},
Execute: func(ctx context.Context, runtime *common.RuntimeContext) error {
taskIDs, err := parseTaskGUIDs(runtime.Str("task-id"))
if err != nil {
return err
}
body, err := buildTaskUpdateBody(runtime)
if err != nil {
// buildTaskUpdateBody already returns a typed validation error;
@@ -55,17 +70,11 @@ var UpdateTask = common.Shortcut{
return err
}
taskIds := strings.Split(runtime.Str("task-id"), ",")
var updatedTasks []map[string]interface{}
for _, taskId := range taskIds {
taskId = strings.TrimSpace(taskId)
if taskId == "" {
continue
}
for _, taskID := range taskIDs {
params := map[string]interface{}{"user_id_type": "open_id"}
data, err := callTaskAPITyped(runtime, http.MethodPatch, "/open-apis/task/v2/tasks/"+url.PathEscape(taskId), params, body)
data, err := callTaskAPITyped(runtime, http.MethodPatch, "/open-apis/task/v2/tasks/"+url.PathEscape(taskID), params, body)
if err != nil {
return err
}
@@ -76,19 +85,28 @@ var UpdateTask = common.Shortcut{
}
}
updateFields, _ := body["update_fields"].([]string)
var tasks []map[string]interface{}
for _, task := range updatedTasks {
guid, _ := task["guid"].(string)
urlVal, _ := task["url"].(string)
urlVal = truncateTaskURL(urlVal)
confirmed := make(map[string]interface{})
for _, field := range updateFields {
if value, ok := task[field]; ok {
confirmed[field] = value
}
}
tasks = append(tasks, map[string]interface{}{
"guid": guid,
"url": urlVal,
"guid": guid,
"url": urlVal,
"confirmed": confirmed,
})
}
// Standardized write output: return resource identifiers
outData := map[string]interface{}{
"tasks": tasks,
"updated_fields": updateFields,
"tasks": tasks,
}
runtime.OutFormat(outData, &output.Meta{Count: len(updatedTasks)}, func(w io.Writer) {
@@ -112,6 +130,26 @@ var UpdateTask = common.Shortcut{
},
}
func parseTaskGUIDs(input string) ([]string, error) {
parts := strings.Split(input, ",")
taskGUIDs := make([]string, 0, len(parts))
for _, part := range parts {
if strings.TrimSpace(part) == "" {
continue
}
guid, err := parseTaskGUID(part)
if err != nil {
return nil, err
}
taskGUIDs = append(taskGUIDs, guid)
}
if len(taskGUIDs) == 0 {
_, err := parseTaskGUID("")
return nil, err
}
return taskGUIDs, nil
}
func buildTaskUpdateBody(runtime *common.RuntimeContext) (map[string]interface{}, error) {
taskObj := make(map[string]interface{})
var updateFields []string

View File

@@ -0,0 +1,201 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package task
import (
"context"
"encoding/json"
"errors"
"reflect"
"testing"
"github.com/larksuite/cli/errs"
"github.com/larksuite/cli/internal/httpmock"
"github.com/larksuite/cli/shortcuts/common"
"github.com/spf13/cobra"
)
func TestParseTaskGUIDs(t *testing.T) {
got, err := parseTaskGUIDs(" task-guid-1, https://applink.larksuite.com/client/todo/detail?guid=task-guid-2 ")
if err != nil {
t.Fatalf("parseTaskGUIDs() error = %v", err)
}
want := []string{"task-guid-1", "task-guid-2"}
if !reflect.DeepEqual(got, want) {
t.Fatalf("parseTaskGUIDs() = %v, want %v", got, want)
}
_, err = parseTaskGUIDs("task-guid-1,t12345")
if err == nil {
t.Fatal("parseTaskGUIDs() error = nil, want invalid display-number error")
}
}
func TestTaskUpdateDryRunPreviewsEveryTaskID(t *testing.T) {
cmd := &cobra.Command{}
cmd.Flags().String("task-id", "task-guid-1,https://applink.larksuite.com/client/todo/detail?guid=task-guid-2", "")
cmd.Flags().String("summary", "updated", "")
cmd.Flags().String("description", "", "")
cmd.Flags().String("due", "", "")
cmd.Flags().String("data", "", "")
preview := UpdateTask.DryRun(context.Background(), &common.RuntimeContext{Cmd: cmd})
payload, err := json.Marshal(preview)
if err != nil {
t.Fatalf("marshal dry-run preview: %v", err)
}
var got struct {
API []struct {
Method string `json:"method"`
URL string `json:"url"`
Params map[string]interface{} `json:"params"`
Body map[string]interface{} `json:"body"`
} `json:"api"`
}
if err := json.Unmarshal(payload, &got); err != nil {
t.Fatalf("decode dry-run preview: %v", err)
}
if len(got.API) != 2 {
t.Fatalf("dry-run API calls = %d, want 2; payload: %s", len(got.API), payload)
}
wantURLs := []string{
"/open-apis/task/v2/tasks/task-guid-1",
"/open-apis/task/v2/tasks/task-guid-2",
}
for i, call := range got.API {
if call.Method != "PATCH" {
t.Errorf("api[%d].method = %q, want PATCH", i, call.Method)
}
if call.URL != wantURLs[i] {
t.Errorf("api[%d].url = %q, want %q", i, call.URL, wantURLs[i])
}
if !reflect.DeepEqual(call.Params, map[string]interface{}{"user_id_type": "open_id"}) {
t.Errorf("api[%d].params = %#v", i, call.Params)
}
if !reflect.DeepEqual(call.Body, got.API[0].Body) {
t.Errorf("api[%d].body = %#v, want same body as first call %#v", i, call.Body, got.API[0].Body)
}
}
}
func TestTaskUpdateNormalizesAllIDsAndReturnsConfirmedFields(t *testing.T) {
f, stdout, _, reg := taskShortcutTestFactory(t)
warmTenantToken(t, f, reg)
first := &httpmock.Stub{
Method: "PATCH",
URL: "/open-apis/task/v2/tasks/task-guid-1",
Body: map[string]interface{}{
"code": 0, "msg": "success",
"data": map[string]interface{}{
"task": map[string]interface{}{
"guid": "task-guid-1",
"url": "https://example.com/task-guid-1",
"summary": "server summary one",
"description": "server description one",
},
},
},
}
second := &httpmock.Stub{
Method: "PATCH",
URL: "/open-apis/task/v2/tasks/task-guid-2",
Body: map[string]interface{}{
"code": 0, "msg": "success",
"data": map[string]interface{}{
"task": map[string]interface{}{
"guid": "task-guid-2",
"url": "https://example.com/task-guid-2",
"summary": "server summary two",
},
},
},
}
reg.Register(first)
reg.Register(second)
err := runMountedTaskShortcut(t, UpdateTask, []string{
"+update",
"--task-id", "task-guid-1,https://applink.larksuite.com/client/todo/detail?guid=task-guid-2",
"--summary", "requested summary",
"--description", "requested description",
"--format", "json",
"--as", "bot",
}, f, stdout)
if err != nil {
t.Fatalf("UpdateTask error = %v", err)
}
reg.Verify(t)
var envelope map[string]interface{}
if err := json.Unmarshal(stdout.Bytes(), &envelope); err != nil {
t.Fatalf("decode output: %v\n%s", err, stdout.String())
}
data, ok := envelope["data"].(map[string]interface{})
if !ok {
t.Fatalf("data = %#v, want object", envelope["data"])
}
if got := stringSlice(data["updated_fields"]); !reflect.DeepEqual(got, []string{"summary", "description"}) {
t.Fatalf("updated_fields = %v, want [summary description]", got)
}
tasks, ok := data["tasks"].([]interface{})
if !ok || len(tasks) != 2 {
t.Fatalf("tasks = %#v, want two tasks", data["tasks"])
}
firstTask := tasks[0].(map[string]interface{})
if firstTask["guid"] != "task-guid-1" || firstTask["url"] != "https://example.com/task-guid-1" {
t.Fatalf("first task identifiers = %#v", firstTask)
}
if got := firstTask["confirmed"]; !reflect.DeepEqual(got, map[string]interface{}{
"summary": "server summary one", "description": "server description one",
}) {
t.Fatalf("first confirmed = %#v", got)
}
secondTask := tasks[1].(map[string]interface{})
if got := secondTask["confirmed"]; !reflect.DeepEqual(got, map[string]interface{}{
"summary": "server summary two",
}) {
t.Fatalf("second confirmed = %#v; omitted server fields must not be echoed from the request", got)
}
}
func TestTaskUpdateValidatesEveryIDBeforeFirstWrite(t *testing.T) {
f, stdout, _, reg := taskShortcutTestFactory(t)
warmTenantToken(t, f, reg)
err := runMountedTaskShortcut(t, UpdateTask, []string{
"+update",
"--task-id", "task-guid-1,t12345",
"--summary", "must not be written",
"--format", "json",
"--as", "bot",
}, f, stdout)
if err == nil {
t.Fatal("UpdateTask error = nil, want invalid task ID error")
}
problem, ok := errs.ProblemOf(err)
if !ok || problem.Category != errs.CategoryValidation || problem.Subtype != errs.SubtypeInvalidArgument {
t.Fatalf("error = %T %v, want typed invalid-argument error", err, err)
}
var validationErr *errs.ValidationError
if !errors.As(err, &validationErr) || validationErr.Param != "--task-id" {
t.Fatalf("error param = %#v, want --task-id", validationErr)
}
}
func stringSlice(value interface{}) []string {
items, _ := value.([]interface{})
result := make([]string, 0, len(items))
for _, item := range items {
if str, ok := item.(string); ok {
result = append(result, str)
}
}
return result
}

View File

@@ -28,7 +28,7 @@
## 各命令
### +file-list
列出应用文件,支持精确过滤:`--name`(文件名)、`--path`(远端路径)、`--type`MIME 类型)、`--size-gt`/`--size-lt`(字节)、`--uploaded-since`/`--uploaded-until`(上传时间区间,时间格式见末尾)。分页 `--page-size`(默认 20/ `--page-token`。列表每项给名称、路径、大小、类型、上传时间pretty 表格即这 5 列);上传者、下载地址(如有)仅在 JSON 输出里,单文件详情用 `+file-get`
列出应用文件,支持精确过滤:`--name`(文件名)、`--path`(远端路径)、`--type`MIME 类型)、`--size-gt`/`--size-lt`(字节)、`--uploaded-since`/`--uploaded-until`(上传时间区间,时间格式见末尾)。分页 `--page-size`(默认 20,范围 1..200/ `--page-token`。列表每项给名称、路径、大小、类型、上传时间pretty 表格即这 5 列);上传者、下载地址(如有)仅在 JSON 输出里,单文件详情用 `+file-get`
```bash
lark-cli apps +file-list --app-id app_xxx

View File

@@ -29,7 +29,7 @@ metadata:
## 使用边界
- Base 业务操作只使用 `lark-cli base +...` shortcut不使用旧聚合式 `+table / +field / +record / +view / +history / +workspace`
- 本轮 Base 不依赖 `lark-cli schema`。SKILL 只保留路由、风险和复杂 JSON/DSL简单命令由命令自身的参数、tips 和错误恢复承接
- 执行 update 前必须先查当前 shortcut 的 `--help` 或对应 reference。若命令要求完整配置首次请求必须基于可信的当前配置执行 read-modify-write只修改用户明确指定的内容保留其他仍适用的可写配置并按命令要求的结构提交。若命令支持局部delta update按其契约提交最小合法 payload不得以不完整请求试错补参
- 用户要把 Excel / CSV / `.base` 导入成 Base 时,先转 `lark-cli drive +import --type bitable`,导入完成后再回到 Base 命令。
- 认证、初始化、scope、身份切换、权限不足恢复属于 `lark-shared`Base 文档只保留会影响 Base 路径选择的权限规则。
@@ -104,20 +104,18 @@ metadata:
## 写入前置规则
- 更新前先看命令说明:需要完整提交时,先读取并补齐当前配置,只改用户指定的内容,再按命令要求提交;支持局部修改时,按命令说明和 reference 提交最小合法 payload。
- 优先用写入返回确认结果;返回信息不足或任务明确要求核验时,再读回。
- 写记录前先读字段结构;只写存储字段。系统字段、附件字段、`formula``lookup` 不作为普通记录写入目标。
- 附件上传、下载、删除走专用 `+record-*-attachment` 命令。
- 写字段前先读 [lark-base-field-json.md](references/lark-base-field-json.md);涉及 `formula` / `lookup` 时必须读 [formula-field-guide.md](references/formula-field-guide.md) / [lookup-field-guide.md](references/lookup-field-guide.md)。
- 表名、字段名、视图名、workflow 配置中的名称必须来自真实返回;跨表场景还要读取目标表结构。
- 删除、角色更新、字段更新等高风险操作遵循 CLI 的 confirmation gate目标不明确时先用 get/list 消歧。
- 删除、角色更新、字段更新、表单提交(`+form-submit`等高风险操作遵循 CLI 的 confirmation gate,必须带 `--yes`;目标不明确时先用 get/list 消歧。
- 批量写入单批最多 200 条;连续写同一表时串行执行,遇到 `1254291` 按短暂等待后重试处理。
- `+record-batch-update` 使用 `update_records`,按 `record_id -> fields` 映射逐条提交字段值
- select/multiselect 写入未知选项可能触发平台新增选项;不是要新增时,先用 `+field-list``+field-search-options` 确认可选值。
- `select` 字段只支持写入字段中已有的选项;构造 CellValue 前先用 `+field-list``+field-search-options` 确认目标选项存在
## 表单与视图细节
- `+form-submit` 前必须先跑 `+form-detail`,读取 `questions[].type``required``filter` 和附件场景需要的 `base_token`;不要填写被 filter 隐藏的问题。
- `+form-submit` 是高风险写操作,必须带 `--yes` 确认;调用前必须先跑 `+form-detail`,读取 `questions[].type``required``filter` 和附件场景需要的 `base_token`;不要填写被 filter 隐藏的问题。
- 表单附件不要写进 `fields`,放在 `--json.attachments`;提交附件时必须同时传表单所属 Base 的 `--base-token`
- `+view-set-filter` 是唯一保留的 view referencesort/group/card/timebar/visible-fields 这类配置先用对应 get 命令读现状,保留未修改字段,只替换用户要求变更的配置。
- 视图适合持久化、共享和 UI 复用;一次性筛选/排序可先用 `+record-list` / `+record-search` 的 filter/sort 验证结果,再按需要沉淀为持久视图。

View File

@@ -8,7 +8,7 @@
- `--json` 必须是 JSON 对象。
- `+record-upsert`:顶层直接传字段映射:`{"字段名或字段ID": CellValue}`
- `+record-batch-create``rows``CellValue[][]`,列顺序由 `fields` 决定
- `+record-batch-create`使用 `create_records`,其每个元素都是 `Map<FieldNameOrID, CellValue>`
- `+record-batch-update`:使用 `update_records`,其每个 value 都是 `Map<FieldNameOrID, CellValue>`
- 一次 payload 里同一字段只用一种 key字段名或字段 ID不要重复。
- 写入前先 `+field-list` 获取字段 `type/style/multiple`,再构造值。
@@ -48,7 +48,7 @@ text 字段的 `style.type` 影响单元格检查逻辑:
### 2.3 select单选/多选)
单选用选项名字符串;多选用选项名数组。选项名建议与字段配置一致;写入未知选项时平台可能自动新增选项,因此不要把自然语言近义词当成已有选项传入
`select` 字段用 `multiple` 区分单选和多选:`multiple=false` 时传选项名字符串,`multiple=true` 时传选项名数组。只支持写入字段中已有的选项;构造 CellValue 前先用 `+field-list``+field-search-options` 确认目标选项存在
```json
{

View File

@@ -4,6 +4,8 @@
通过表单分享链接填写并提交多维表格表单。仅支持分享模式share_token支持填写普通字段值和上传本地文件作为附件。
> **⚠️ 高风险写操作high-risk-write** 本命令会向表单写入并提交数据,属于高风险写操作,必须额外传递 `--yes` 进行确认,否则会返回 `confirmation_required` 错误并退出。当用户明确要求提交且目标表单无歧义时,直接附加 `--yes`,无需再次询问。
## 填写前必读:先获取表单详情
**在调用 `+form-submit` 之前,必须先使用 `+form-detail` 获取表单详情。** 原因如下:
@@ -21,10 +23,11 @@ lark-cli base +form-detail --share-token <share_token>
# 2⃣ 根据返回的 questions 列表,按 type 格式化值、检查 required、判断 filter 条件
# 3⃣ 再提交
# 3⃣ 再提交(高风险写操作,必须带 --yes
lark-cli base +form-submit \
--share-token <share_token> \
--json '{"fields":{...}}'
--json '{"fields":{...}}' \
--yes
```
`+form-detail` 的返回中要重点读取 `questions[].type``questions[].required`、题目 `filter` 和附件场景所需的 `data.base_token`
@@ -35,7 +38,8 @@ lark-cli base +form-submit \
# 基本提交(填写普通字段)
lark-cli base +form-submit \
--share-token <share_token> \
--json '{"fields":{"服务评分":5,"评价内容":"服务态度好"}}'
--json '{"fields":{"服务评分":5,"评价内容":"服务态度好"}}' \
--yes
# 带附件提交(需要额外提供 --base-token
lark-cli base +form-submit \
@@ -47,15 +51,17 @@ lark-cli base +form-submit \
"附件字段名": ["./report.pdf", "./photo.png"],
"另一个附件字段": ["./doc.docx"]
}
}'
}' \
--yes
# 使用应用身份bot
lark-cli base +form-submit \
--share-token <share_token> \
--json '{"fields":{...}}' \
--as bot
--as bot \
--yes
# 预览 API 调用(不实际执行)
# 预览 API 调用(不实际执行dry-run 无需 --yes
lark-cli base +form-submit \
--share-token <share_token> \
--json '{"fields":{...}}' \
@@ -69,6 +75,7 @@ lark-cli base +form-submit \
| `--share-token <token>` | 是 | 表单分享 Token必填从表单分享链接中提取 |
| `--base-token <token>` | 条件必填 | Base token**当 `--json` 包含 `attachments` 时必须提供**,用于将附件上传到 Base Drive Media |
| `--json <json>` | 是 | JSON 对象,包含 `"fields"`(普通字段值)和 `"attachments"`(附件上传),详见下方说明 |
| `--yes` | 是 | 确认高风险写操作。本命令为 high-risk-write不带 `--yes` 会返回 `confirmation_required` |
| `--format` | 否 | 输出格式json默认\| pretty \| table \| ndjson \| csv |
| `--as` | 否 | 身份user默认\| bot |
| `--dry-run` | 否 | 预览 API 调用,不执行 |
@@ -138,7 +145,8 @@ https://www.example.com/share/base/form/shrbcvST8eZy0vk8zjVZ1CAXNye
```bash
lark-cli base +form-submit \
--share-token shrbcvST8eZy0vk8zjVZ1CAXNye \
--json '{"fields":{...}}'
--json '{"fields":{...}}' \
--yes
```
## 输出格式
@@ -158,6 +166,7 @@ lark-cli base +form-submit \
## 提示
- **本命令为高风险写操作high-risk-write必须额外传递 `--yes` 确认**,否则返回 `confirmation_required` 并以非零码退出;`--dry-run` 预览除外
- 本命令仅支持通过表单分享链接share_token提交不支持通过 base_token + table_id + view_id 方式提交
- **当 `--json` 包含 `attachments` 时,必须额外提供 `--base-token`**,因为附件上传到 Base Drive Media 需要指定目标 Base
- 附件字段只需在 `--json.attachments` 中提供本地路径即可CLI 自动完成校验、并行上传、Token 获取和合并写入

View File

@@ -7,13 +7,13 @@
## 适用场景(重点)
- 适合导入 CSV / Excel、外部系统一次性写入新数据。
- 先把输入数据映射到合适的字段类型,再组装 `fields + rows`
- 先把每条输入数据映射为独立的字段对象,再组装 `create_records`
## 推荐命令
```bash
lark-cli base +record-batch-create --base-token <base_token> --table-id <table_id> \
--json '{"fields":["标题","状态"],"rows":[["任务 A","Open"],["任务 B","Done"]]}'
--json '{"create_records":[{"标题":"任务 A","状态":"Open"},{"标题":"任务 B","状态":"Done"}]}'
lark-cli base +record-batch-create --base-token <base_token> --table-id <table_id> --json @batch-create.json
```
@@ -34,23 +34,25 @@ lark-cli base +record-batch-create --base-token <base_token> --table-id <table_i
本节只说明 `+record-batch-create` 的外层 JSON 形状CellValue 统一看 [lark-base-cell-value.md](lark-base-cell-value.md)。
对象形态:`{"fields":[...],"rows":[...]}`
对象形态:
```json
{"create_records":[{"标题":"任务 A","状态":"Open"},{"标题":"任务 B","状态":"Done"}]}
```
| 字段 | 类型 | 必填 | 说明 |
|------|------|------|------|
| `fields` | `string[]` | 是 | 字段 ID 或字段名数组 |
| `rows` | `CellValue[][]` | 是 | 二维数组,每一行按 `fields` 同序给 cell单次最多 200 行 |
| `create_records` | `Array<Map<FieldNameOrID, CellValue>>` | 是 | 记录字段对象数组;每条记录可以提交不同字段,单次最多 200 条 |
## 返回重点
返回 `fields``field_id_list``record_id_list``data`,其中 `data``fields` 列顺序对齐
返回 `record_id_list` 和可选的 `ignored_fields`
## 坑点
- `fields` 与每行 `rows` 的列顺序必须一一对应
- 空单元格必须显式用 `null` 填充
- 单次最多 200 行,超出需分批写入
- select 写入未知选项时平台可能自动新增选项;如果不是要新增选项,先确认真实选项名。
- 每个 `create_records` 元素都是独立的记录字段对象,只提交该记录需要写入的字段
- 单次最多 200 条,超出需分批写入
- `select` 字段只支持写入字段中已有的选项;构造 CellValue 前先用 `+field-list``+field-search-options` 确认目标选项存在
## 参考

View File

@@ -55,7 +55,7 @@ lark-cli base +record-upsert --base-token <base_token> --table-id <table_id> --r
## 坑点
-`--record-id` 就一定更新;不传就一定创建,不会自动查重或按业务键 upsert。
- select 写入未知选项时平台可能自动新增选项;如果不是要新增选项,先用 `+field-list` / `+field-search-options` 确认真实选项名
- `select` 字段只支持写入字段中已有的选项;构造 CellValue 前先用 `+field-list` `+field-search-options` 确认目标选项存在
- 这是写入操作,执行前必须确认目标表和字段。
## 参考

View File

@@ -1,7 +1,6 @@
---
name: lark-doc
version: 2.0.0
description: "飞书云文档Docx / Wiki 文档):读取和编辑飞书文档内容。当用户给出文档 URL 或 token或需要查看、创建、编辑文档、插入或下载文档图片附件时使用。文档中嵌入的电子表格、多维表格、画板先用本 skill 提取 token 再切到对应 skill。当用户给出 doubao.com 的 /docx/ 或 /wiki/ URL/token 时,也应直接使用本 skill路由依据是 URL 路径模式和 token而不是域名。不负责文档评论管理也不负责表格或 Base 的数据操作。当用户明确要操作飞书思维笔记时,也使用本 skill。"
description: "飞书云文档Docx / Wiki内容操作读取、创建、编辑文档插入或下载图片附件以及操作思维笔记。用户提供文档 URL/token包括 doubao.com 的 /docx/、/wiki/)时使用;按 URL 路径/token 而非域名路由。文档内嵌资源按读取参考中的统一规则分流。文档评论走 lark-drive表格或 Base 内部数据操作不在本 skill。"
metadata:
requires:
bins: ["lark-cli"]
@@ -10,75 +9,41 @@ metadata:
# docs
**身份:文档操作默认使用 `--as user`。首次使用前执行 `lark-cli auth login`。**
## 场景与 Shortcut 路由
```bash
# 常用示例
lark-cli docs +fetch --doc "文档URL或token若 URL 存在 #share-... 锚点,优先使用锚点方式读取,不要全文拉取"
lark-cli docs +create --content '<title>标题</title><p>内容</p>'
lark-cli docs +update --doc "文档URL或token" --command append --content '<p>内容</p>'
```
**CRITICAL先判断场景再读取该场景的参考文件不要在任务开始时一次性读取全部参考文件。每个文件只在首次进入对应阶段时读取一次。**
## 前置条件 — 执行操作前必读
**身份:文档操作默认使用 `--as user`**
**CRITICAL — 执行对应操作前MUST 先用 Read 工具读取以下文件,缺一不可:**
1. [`../lark-shared/SKILL.md`](../lark-shared/SKILL.md) — 认证、权限处理、全局参数(所有操作通用)
2. **读取文档(`docs +fetch`** → 必读 [`lark-doc-fetch.md`](references/lark-doc-fetch.md)`--scope` / `--detail` 选择、局部读取策略、`<fragment>` / `<excerpt>` 输出结构)
3. **创建或编辑文档内容** → 必读 [`lark-doc-xml.md`](references/lark-doc-xml.md)XML 语法规则,仅当用户明确要求 Markdown 时改读 [`lark-doc-md.md`](references/lark-doc-md.md))和必读 [`lark-doc-style.md`](references/style/lark-doc-style.md)(写作原则:默认段落、按体裁、组件克制);从零创建时加读 [`lark-doc-create-workflow.md`](references/style/lark-doc-create-workflow.md);编辑已有文档时加读 [`lark-doc-update.md`](references/lark-doc-update.md) 和 [`lark-doc-update-workflow.md`](references/style/lark-doc-update-workflow.md)
优先使用 `lark-cli docs +<verb>` Shortcut思维笔记使用独立的 `mindnotes` 命令。
**未读完以上文件就执行相应操作会导致参数选择错误或格式错误。**
### 文档正文
> **格式选择规则(全局):**
> - **创建 / 导入场景**`docs +create`,或 `docs +update --command append/overwrite` 的整段写入XML 和 Markdown 都可以。用户提供 `.md` 本地文件、或明确说"导入 Markdown"时,直接用 Markdown否则默认 XML
> - **精准编辑场景**`docs +update` 的 `str_replace` / `block_insert_after` / `block_replace` / `block_delete` / `block_move_after` 等局部精修指令):优先使用 XML`--doc-format xml`即默认值。XML 能稳定表达 block 结构和样式,局部精修更可控;不要因为 Markdown 更简单就自行切换
- **读取 / 摘要 — [`+fetch`](references/lark-doc-fetch.md)**:先读参考再获取文档。只读或摘要默认用 `simple`;更新前定位用局部 `with-ids`;保真改写才读 `full`;带 `#share-...` 的选区链接按原 URL 传入。
- **从零创作 — [`创建工作流`](references/lark-doc-create-workflow.md) → [`+create`](references/lark-doc-create.md)**:先完整执行创建工作流,**简单任务不是跳过的理由**;通过 Publish Gate 后再创建文档
- **导入 / 空文档 — [`+create`](references/lark-doc-create.md)**:仅创建空文档或原样导入用户提供的完整内容时,跳过创建工作流
- **编辑 / block 直达链接 — [`+update`](references/lark-doc-update.md)**:语义改写、润色、重组、补写或排版时先完整读取参考,按推荐流程 fetch 后局部更新;明确旧文本 → 新文本可直接 `str_replace`,但写后必须 fetch 验证;每次更新后重新获取最新 block IDblock 直达链接也按该参考生成。
## 快速决策
- 用户要**复制文档 / 创建文档副本 / 另存为副本**时,切到 [`lark-drive`](../lark-drive/SKILL.md),按其中的复制指引使用 `lark-cli drive files copy`;不要用 `docs +fetch` + `docs +create` 重建正文,也不要走 `drive +export` / `drive +import`
- 先判定任务路径:找文档 / 导入导出走 [`lark-drive`](../lark-drive/SKILL.md);只读 / 摘要用 `docs +fetch` 默认 `simple`;明确旧文本 → 新文本直接 `str_replace`;只有 block 链接、评论锚点、插入 / 替换 / 删除 / 移动才局部 fetch `with-ids`;保真改写已有内容才读 `full`
- block 直达链接格式:`文档基础 URL#block_id`;没有 block_id 时局部 fetch `with-ids`
- 连续执行多个文档写操作时,必须按 [`lark-doc-update.md`](references/lark-doc-update.md) 的「Block ID 生命周期」判断旧 block ID 是否还能复用;`overwrite` / `block_replace` / `block_delete` 后不要复用受影响的旧 ID插入 / 复制后要重新 fetch 才能拿到新 block ID
- 用户需要在文档内**创建、复制或移动**资源块(画板、电子表格、多维表格等)时,必须先读取 [`lark-doc-xml.md`](references/lark-doc-xml.md) 的「三、资源块」章节
- 写文档时,由内容和用户意图决定表达形式;流程、架构、路线图、关键指标等信息可以使用画板,但不要默认把重要信息都画板化
- 新增或更新画板时,按 [`lark-doc-whiteboard.md`](references/lark-doc-whiteboard.md) 选型Mermaid 可由主 Agent 直接插入SVG / 复杂图 / 已有画板更新按其中流程隔离到 SubAgent
- 用户说"看一下文档里的图片/附件/素材""预览素材" → 用 `lark-cli docs +media-preview`
- 用户明确说"下载素材" → 用 `lark-cli docs +media-download`
- 用户想把文档回滚到某个 `revision_id` 或某一时刻 → 先读 [`lark-doc-history.md`](references/lark-doc-history.md),按其中流程操作
- 用户明确说"下载/更新/删除文档封面图" → 用 `lark-cli docs +resource-download/+resource-update/+resource-delete --type cover`
- `resource-*` 目前仅支持 Docx 封面资源;其他图片、附件或素材请走 `+media-*`
- 如果目标是画板/whiteboard/画板缩略图 → 只能用 `lark-cli docs +media-download --type whiteboard`(不要用 `+media-preview`
- 用户明确要操作思维笔记时;已有**思维笔记**,走 [思维笔记链路](references/lark-doc-mindnote.md);新建**思维笔记**,走 [lark-doc-whiteboard](references/lark-doc-whiteboard.md)
- 拿到 spreadsheet URL/token 后 → 切到 `lark-sheets` 做对象内部操作
- 用户需要统计文档的**总字数 / 总字符数**word count / character count先读取 [`lark-doc-word-stat.md`](references/lark-doc-word-stat.md),并按其中流程调用 [`scripts/doc_word_stat.py`](scripts/doc_word_stat.py);统计口径以该脚本为准,不要改用其他方式自行计算。
- 用户说"给文档加评论""查看评论""回复评论""给评论加/删除表情 reaction" → 切到 `lark-drive` 处理
- 文档内容中出现嵌入的 `<sheet>``<bitable>``<cite file-type="sheets|bitable">` 标签时 → **必须主动提取 token 并切到对应技能下钻读取内部数据**,不能只呈现标签本身
### 辅助能力
| 标签 / 属性 | 提取字段 | 切到技能 |
|-|-|-|
| `<sheet token="..." sheet-id="...">` | `token` -> spreadsheet_token, `sheet-id` | [`lark-sheets`](../lark-sheets/SKILL.md) |
| `<bitable token="..." table-id="...">` | `token` -> app_token, `table-id` | [`lark-base`](../lark-base/SKILL.md) |
| `<cite type="doc" file-type="sheets" token="..." sheet-id="...">` | 同 `<sheet>` | [`lark-sheets`](../lark-sheets/SKILL.md) |
| `<cite type="doc" file-type="bitable" token="..." table-id="...">` | 同 `<bitable>` | [`lark-base`](../lark-base/SKILL.md) |
| `<vc-transcribe-tab vc-node-id="...">` | `vc-node-id` -> note_id | [`lark-note`](../lark-note/SKILL.md):先 `note +detail --note-id <vc-node-id>` |
| `<synced_reference src-token="..." src-block-id="...">` | `src-token` -> doc_token, `src-block-id` -> block_id | 用 `docs +fetch` 读取 src-token 文档,定位 block |
- **临时文件、解析与统计 — [`+script`](references/lark-doc-script.md)**:创建名称唯一的临时 XML直接解析文档 URL / token 或本地 XML / Markdown、将 Markdown 转为 XML或统计文档总字数 / 总字符数。
- **历史版本 — [`+history-list` / `+history-revert` / `+history-revert-status`](references/lark-doc-history.md)**:查询、回滚文档历史版本或检查回滚任务状态。
## Shortcuts推荐优先使用
### 资源、画板与思维笔记
Shortcut 是对常用操作的高级封装(`lark-cli docs +<verb> [flags]`)。有 Shortcut 的操作优先使用
- **插入本地素材 — [`+media-insert`](references/lark-doc-media-insert.md)**:在文末插入本地图片或文件
- **预览素材 — [`+media-preview`](references/lark-doc-media-preview.md)**:预览文档中的图片、附件或素材。
- **下载素材 — [`+media-download`](references/lark-doc-media-download.md)**:下载文档中的图片、附件、素材或画板缩略图。
- **Docx 封面 — [`+resource-download` / `+resource-update` / `+resource-delete`](references/lark-doc-resource-cover.md)**:下载、更新或删除 Docx 封面。
- **画板 — [`画板工作流`](references/lark-doc-whiteboard.md)**:创建或更新画板时先读取工作流;更新已有画板必须复用现有 token禁止新建空白画板底层写入优先使用 [`whiteboard +update`](../lark-whiteboard/references/lark-whiteboard-update.md)`docs +whiteboard-update` 仅为别名。
- **思维笔记 — `mindnotes`**:已有思维笔记走 [`思维笔记链路`](references/lark-doc-mindnote.md);新建思维笔记走 [`lark-doc-whiteboard`](references/lark-doc-whiteboard.md)。
| Shortcut | 说明 |
|----------|------|
| [`+create`](references/lark-doc-create.md) | Create a Lark document (XML / Markdown) |
| [`+fetch`](references/lark-doc-fetch.md) | Fetch Lark document content (XML / Markdown / im-markdown; `im-markdown` only after fetch for `lark-im`) |
| [`+update`](references/lark-doc-update.md) | Update a Lark document (str_replace / block_insert_after / block_replace / ...) |
| [`+history-list` / `+history-revert` / `+history-revert-status`](references/lark-doc-history.md) | List document history, revert to a `history_version_id`, and query revert task status |
| [`+media-insert`](references/lark-doc-media-insert.md) | Insert a local image or file at the end of a Lark document (4-step orchestration + auto-rollback). Prefer `--from-clipboard` when the image is already on the system clipboard (screenshots, copy from Feishu/browser); use `--file` only for on-disk sources. |
| [`+media-download`](references/lark-doc-media-download.md) | Download document media or whiteboard thumbnail (auto-detects extension) |
| [`+media-preview`](references/lark-doc-media-preview.md) | Preview document media file (auto-detects extension) |
| [`+resource-download` / `+resource-update` / `+resource-delete`](references/lark-doc-resource-cover.md) | Download, update, or delete a Docx cover image resource with `--type cover` |
| [`+whiteboard-update`](../lark-whiteboard/references/lark-whiteboard-update.md) | Alias of `whiteboard +update`. Update an existing whiteboard with DSL, Mermaid or PlantUML. Prefer `whiteboard +update`; refer to lark-whiteboard skill for details. |
### 认证与 Scope
先执行 `docs` / `mindnotes` Shortcut不预读 [`lark-shared`](../lark-shared/SKILL.md) 或预跑 `auth status --verify`仅遇到未认证、token / 身份或 scope 错误时读取该 Skill修复后重试。认证、身份或 scope 管理请求则直接使用该 Skill。
## 不在本 Skill 范围
- 文档评论管理 → [`lark-drive`](../lark-drive/SKILL.md)
- 电子表格或 Base 的数据操作 → [`lark-sheets`](../lark-sheets/SKILL.md) / [`lark-base`](../lark-base/SKILL.md)
- 云空间文件上传、下载、权限管理 → [`lark-drive`](../lark-drive/SKILL.md)
- **Drive 文件级操作**:找文档、导入导出、云空间文件上传 / 下载 / 权限管理 → [`lark-drive`](../lark-drive/SKILL.md)。复制文档、创建副本或另存为副本时,按其指引使用 `lark-cli drive files copy`;不要用 `docs +fetch` + `docs +create` 重建正文,也不要走 `drive +export` / `drive +import`
- **文档评论**:添加、查看、回复评论或增删 reaction → [`lark-drive`](../lark-drive/SKILL.md)
- **文档内嵌资源下钻**:处理不在本 Skill 范围的内嵌资源(如电子表格或 Base 内部数据)时,统一读取 [`lark-doc-fetch.md`](references/lark-doc-fetch.md#处理文档内嵌资源) 的「处理文档内嵌资源」,提取 token / ID 后按该节切到对应 Skill 或命令;根 Skill 不重复维护标签分发表。

View File

@@ -0,0 +1,30 @@
# Genre Contract: Business Analysis / 商业分析 (`report.business_analysis`)
## 体裁规则表(硬约束)
| 规则项 | 规则 |
|-|-|
| presentation_mode / 表达模式 | `normal`;结论前置、具体、条件化;模型只用于改变比较或暴露约束,不用管理黑话代替判断 |
| 内容逻辑 | 围绕一个具体决策,比较现状 / 不行动与真实替代项;用统一目标和口径评价价值、全周期成本、风险、约束与可实施性,给出推荐、暂缓或验证门及翻转条件 |
| 事实 / 边界 | 事实、估算、假设、未知和外部依赖分开;数字标来源、时点、单位、口径和置信范围;利益相关方、不可货币化影响和权限边界显著;分析建议不等于批准或承诺 |
| 错误 | 为预选方案找论据;无现状基准或真实替代项;口径不一却排名;单一 ROI / BCR / 评分替代平衡判断;套 SWOT估算冒充事实忽略全周期成本、依赖或分配影响未获批写成已承诺建议不回链证据 |
## 适用与消歧
比较投资、资源、市场、产品、经营或供应选项并支持判断,但正文不要求具名决策者作出选择 / 批准,也不形成授权、资源拨付或执行承诺入口。`商业``市场分析``SWOT`单独只用于召回;回答研究问题走 [`research-report.md`](research-report.md),纯指标解读走 [`data-report.md`](data-report.md),命中上述 ask / 授权入口时走 Workplace Proposal接口、不变量和实现取舍为主走 Technical RFC。
## 子类型
投资 / 资源配置build-buy-partner 或 vendor市场进入 / 扩张;产品 / 组合优先级;经营模式 / 流程;定价 / 商业模式;高不确定性的试点或阶段门。分析深度随金额、复杂度、不可逆性、影响范围和风险提高。
## 证据与方法
- 定义问题、目标、成功标准、范围、约束、决策 owner / 时点和现状 / 不行动基准;记录选项生成与排除理由。
- 对每个可行选项用相同维度比较收益、全生命周期成本、时间、能力 / 依赖、风险、受影响方、不可货币化影响和可逆性。
- 现状数据与预测分开;按需说明币种、价格时点、折现和估算方法。不得从官网标价推断销量、收入或份额。
- 对可能翻转结论的假设做范围、情景或敏感性分析,并给 switching value、决策门或验证信号评分模型须解释权重和证据不能只报总分。
- 缺目标、成功标准、基准或可行选项时只产出 decision frame / options discovery关键估算用 `[成本区间待核]` 和验证计划,可能翻转结论且无法界定时标记 `blocked`
## 结构与高质量写法
推荐与条件 → case for change / 目标 / 现状基准 → 选项生成、排除理由与同口径比较 → 关键假设、风险、情景与翻转条件 → 建议为何优于替代 → 阶段门、监测 / 学习计划与未决条件。把现状当真实选项,用区间和场景替代伪精确单点,显著说明谁获益、谁承担成本,以及什么新证据会改变建议。

View File

@@ -0,0 +1,32 @@
# Genre Contract: Data Report / 数据报告 (`report.data_report`)
## 体裁规则表(硬约束)
| 规则项 | 规则 |
|-|-|
| presentation_mode / 表达模式 | `normal`;准确、可复算、少形容词;标题表达发现、对象和时点,并保留不确定性 |
| 内容逻辑 | 先建立指标契约和可比基线,再回答发生了什么、为何重要、还不能断言什么;观测、解释假设与行动条件分开,限制紧邻相关结论 |
| 事实 / 边界 | 核心指标标定义、单位、分子分母、总体 / 分群、时间窗、来源 / 版本、更新时间和修订状态;比较须同口径,估计须披露可得不确定性,敏感小群体须汇总、抑制或限制访问;数据图须标轴、单位、分母、时点和来源,并提供文字等价信息 |
| 错误 | 只列数字;隐藏分母或口径变化;不可比数据排名;选择性窗口 / 分群;相关性当因果;图轴、单位或来源缺失;统计显著冒充效应大小或业务胜出;伪精确;限制藏在附录 |
## 适用与消歧
解读已定义指标、趋势、分布、漏斗、监控、估计或实验观察值。`有数据``有数字``分析一下`单独不决定路由;研究问题、抽样和可推广性为主走 [`research-report.md`](research-report.md),比较商业选项走 [`business-analysis.md`](business-analysis.md),组织状态、偏差和下一步走 Workplace 周期报告。
## 子类型
- KPI / 经营表现与趋势分群、cohort 与分布;漏斗 / 路径与监控异常。
- A/B 或实验 readout设计和推断不足时只能报告观察值不宣布因果胜出。
- 预测、估计、修订或统计简报;须标模型 / 假设、适用期和修订状态。
## 证据与方法
- 保留可复算的基数、过滤、聚合、估计区间和质量说明;比较前核对定义、总体、时间窗、分母和处理方法。
- 按误解风险同时给绝对值、绝对变化、相对变化和长期基线;不用多余小数位制造精确感。
- 覆盖、缺失、偏差、口径变化和修订若会改变解释,须与对应发现同处,并说明可能方向、规模和影响。
- 描述性差异不得写成因果;解释标为待验证假设。统计显著性不等于效应大小、实际重要性或完整决策依据。
- 缺定义、分母、时间或来源时使用 `[指标定义待核]``[分母待核]`,对应值不得进入结论;不可比数据分开展示。核心决策依赖的质量缺口无法关闭时标记 `blocked`
## 结构与高质量写法
关键发现与决策限制 → 指标契约 / 数据质量 → 总览与基线 → 必要分维、分布和反例 → 可支持的解释与待验证假设 → 条件式行动 / 验证门 → 方法、修订和来源。每段按“观测 → 基线 / 背景 → 限制 → 含义”推进;复杂图同时给出文字结论和必要精确值,任何视觉不得成为唯一证据。

View File

@@ -0,0 +1,38 @@
# Genre Contract: Email / 邮件 (`platform.email`)
## 核心定位(硬约束)
- 交付物是可复制到邮件客户端的邮件成稿,不代表已发送,也不执行收件人查询、邮件发送、草稿箱或邮箱管理;实际邮件操作切到 `lark-mail`
- `presentation_mode` 默认使用 `formal`;仅在用户明确要求其他表达方式且不违反组织规范或所选 content contract 时调整。全文禁止使用 emoji包括主题、正文、列表标记、组件图标和装饰符号。
- 默认只使用短段落、列表和普通链接等基础结构。只有已由用户说明、平台文档或可信配置确认目标平台完整支持飞书富文本时,才允许使用 `rich` 或 rich block不得根据“邮件”“HTML 邮件”、飞书文档承载或平台名称自行推断支持。
- 一封邮件只承担一个主要沟通任务;主题、首段、正文和行动请求围绕同一目的。不得编造发件人身份、收件人关系、事实、权限、承诺、截止时间、附件或已完成动作;缺失但必需的信息使用清楚的占位符。
- 不使用封面或目录。即使已确认平台能力,表格、图片、`callout`、画板及其他 rich block 也只能在信息确有需要时使用,并确保复制、投递和接收后的语义完整。
## 适用与消歧
用户明确要“写邮件、邮件成稿、邮件草稿、邮件措辞、email、e-mail”或要求起草回复、跟进、通知、邀约、外联邮件时使用内容保存在哪里不影响本合同生效。
查看、搜索、发送、回复或管理邮箱中的真实邮件属于 `lark-mail` 操作;邮件系统说明、邮件数据分析、营销方案或把邮件作为信息来源时不触发本合同。若任务既要成稿又要实际发送,先按本合同形成并确认内容,再切到 `lark-mail` 执行发送。
## 邮件主任务
| 主任务 | 内容脊柱 |
|-|-|
| 请求 / 决策 | 目的或结论 → 必要背景 → 明确请求 / 选项 → 期望时间或下一步 |
| 通知 / 同步 | 关键变化 → 影响范围 → 接收方需知 / 需做 → 时间点与联系入口 |
| 回复 / 跟进 | 对应的前情 → 新信息或直接答复 → 未决事项 → 下一步 |
| 邀约 / 外联 | 联系缘由 → 与收件人的相关性 → 具体提议 → 低成本回应方式 |
| 致歉 / 问题沟通 | 承认影响 → 已确认事实 → 补救动作 → 后续安排与边界 |
## 成稿要求
- 成稿先给主题,再给正文;只有用户要求或材料明确时才列出收件人、抄送人等信封字段。主题准确表达对象、事项或所需行动,不使用标题党、空泛寒暄或无信息量的“重要通知”。
- 称呼依据已知关系和语境选择;关系不明时使用稳妥中性的称呼或显式占位符,不擅自套用亲密、职级或性别称谓。
- 首段尽快说明来意、结论或与既有线程的关系。背景只保留收件人理解、判断或行动所需的信息,不把完整报告、会议纪要或思考过程原样搬入邮件。
- 行动请求写清需要谁在何时以何种方式完成什么;材料没有给出负责人或时间时,不自行补造。多个并列事项使用列表,优先让收件人能直接逐项回应。
- 提及链接、附件或引用材料时说明其用途;未实际提供或上传的材料写成待补占位符,不声称“见附件”。回复和跟进邮件只补充新信息,不机械复述整个线程。
- 结尾与邮件目的匹配:请求类明确回应方式,通知类说明无需动作或下一节点,外联类保留易于拒绝或调整的空间。署名仅使用已知身份;身份不明时使用占位符,不虚构姓名、团队或联系方式。
## 交付前检查
确认收件人能从主题和首段判断“为什么收到、需要知道或做什么”,事实、责任人、时间和附件状态均有依据,正文没有无关铺垫或重复,语气符合关系与风险,全文无 emoji若使用 rich block已有目标平台支持飞书富文本的确认依据复制到邮件客户端后仍清晰可读且未把“成稿”误写成“已发送”。

View File

@@ -0,0 +1,27 @@
# Genre Contract: Execution Plan / 执行计划 (`workplace.execution_plan`)
## 体裁规则表(硬约束)
| 规则项 | 规则 |
|-|-|
| presentation_mode / 表达模式 | `normal`;以交付和判断为单位,具体、紧凑、可推进;计划可信度来自依赖、产能和验收闭环,不来自章节数量或精确到没有依据的日期 |
| 内容逻辑 | 从已批准结果、成功标准、范围和约束出发,按“交付物 / 工作流 → 依赖与关键路径 → 带退出条件的里程碑 → owner / 接口 / 资源 → 风险触发与备选 → 治理、变更与验收”推进 |
| 事实 / 边界 | 区分已确认承诺、估算、假设和待定项时间、owner、预算、产能、权限、依赖与验收方须可追溯且算术相容未批准方向不得写成承诺关键资源或安全前提未知时收窄计划或 `blocked` |
| 错误 | 任务清单冒充计划、活动无交付物 / 完成定义、里程碑只是日期、排期不服从依赖与产能、所有事项同优先级、接口或验收方缺失、风险无预警信号 / 动作 / owner、变更后不更新基线任一出现即失败 |
## 适用与消歧
用于方向和目标已定后,组织一次性项目、迁移、发布、活动战役、专项治理或跨团队变更。主要任务仍是选择方向、申请预算 / 资源或授权时走 `proposal.md`;比较策略选项且不形成批准入口走 `business-analysis.md`;发布已授权规则 / 通知走 `formal-doc.md`;重复确定路径走 `sop-tutorial.md`;报当前状态走 `weekly-report.md`
“项目计划、执行方案、实施计划、营销策划”只作召回词。营销策划若仍在决定打法或预算,按上述 Proposal / Business Analysis 消歧;只有已定打法的协同落地走本合同。
## 可执行性与证据
- 先写可验收结果、范围 / 非范围、约束和最迟决策点;再按交付物而非部门名称拆工作包。每个关键工作包说明 owner、输入 / 输出、依赖、完成定义和验收方。
- 标出关键路径、可并行项、阶段入口 / 退出条件与资源瓶颈;日期由依赖、产能和必要审批 / 制作 / 校准时间推导。无法推导时用相对时间、区间或具体占位,不补造精确排期。
- 风险写预警信号、影响、预防 / 响应动作、决策 owner 和备选路径;备选必须说明何时切换及切换后的安全或业务终态,不写“加强沟通”。
- 治理只保留会产生判断的节奏:接口、升级条件、决策权、范围 / 基线变更和重新验收。密集对应关系可用一张排期、依赖或责任表,但表格不能替代关键路径和取舍说明。
## 高质量写法
让每个目标能一路回链到交付物、里程碑和工作包,让每个日期能回链依赖与产能,让每个风险能回链触发后的动作。资源不足时缩范围、分阶段或设决策门,不用“全渠道、全覆盖、同步推进”制造伪可行性。

View File

@@ -0,0 +1,36 @@
# Genre Contract: Formal Document / 内部正式材料 (`workplace.formal_doc`)
## 体裁规则表(硬约束)
| 规则项 | 规则 |
|-|-|
| presentation_mode / 表达模式 | 固定 `formal`;格式中立的内容稿完成后再应用。庄重、准确、简洁、直接;正式性来自真实权威、事实、边界、责任和生命周期,不来自套话、层级或装饰 |
| 允许 block | `title`(完整文稿最多 1 个)、`p``h1``h2``h3``h4`;标题层级连续且不超过四级 |
| 限用 block | `ul``ol`容器及`li`子块仅承载真实并列或顺序;`table`容器及`thead``tbody``tfoot``tr`子块仅承载多对象同字段信息;`img``figure`仅承载有必要证据作用、来源说明和文字等价信息的材料 |
| 禁止 block | 禁止未列入允许 / 限用清单的类型,包括`callout``checkbox``grid`容器及`column`子块、`whiteboard``blockquote``pre`、根级`code``hr`;禁止装饰色、贴纸、伪红头、伪印章和无证据作用的配图 |
| 内容逻辑 | 先按读者任务选择规则 / 制度、已批准通知 / 安排、检查整改 / 台账或已核定正式说明之一;只写完成该任务所需的对象、依据、要求 / 发现、责任、核验和生命周期,不混写子类型 |
| 事实 / 边界 | 只把已确认的授权、要求、事实和立场写成定论;来源陈述、原始记录、已复核事实和推断分开;外发前确认保密、商业秘密、个人信息、素材权利和发布权限;关键缺口使 `Publish Gate = blocked` |
| 错误 | 因“正式”误判公文,把本 leaf 当方案 / 总结 / 简报兜底,伪造批准 / 生效,用通知偷渡未获授权的新规则,网络素材冒充本单位事实,检查线索写成责任结论,或措施与发现不对应,任一出现即失败 |
## 适用与收口
用于把已授权的非公文组织规则或安排、可复核的检查整改记录,或已核定的组织立场写成正式载体,使读者能够判断适用范围、应采取的行动、记录状态或核心立场。
待批准方向走 `proposal.md`;复杂一次性执行走 `execution-plan.md`;重复操作步骤走 `sop-tutorial.md`;党政机关公文走 `official-redhead.md`;高层简报走 `memo-brief.md`;周期状态走 `weekly-report.md`;学习总结走 Retrospective / Report。`正式、制度、通知、方案、计划、总结、简报、讲话稿`等词单独不触发本体裁,本体裁也不是不确定请求的 fallback。
## 按读者任务选择唯一内容路径
| 读者任务 | 内容主线 |
|-|-|
| 判断持续规则 | 目的与权威 → 适用 / 不适用范围 → 必要定义 → 规范要求 → 责任、例外与升级 → 生效、维护、复审和替代 |
| 执行已批准通知 | 发布主体与批准状态 → 受影响对象及范围 → 已确认事项与生效时间 → 动作、责任与期限 → 例外、反馈和联系人 |
| 复核检查整改 | 对象、范围、方法与证据状态 → 每项可观察发现、标准、影响和已支持原因 → 对应措施、责任与期限 → 核验、关闭证据和变更痕迹 |
| 理解已核定立场 | 讲者或发布主体、场合、受众与时长 → 核心立场 → 必要事实和理由 → 期望理解或行动;不混入制度效力 |
## 证据与高质量写法
- 规则类按需写维护责任、版本、批准、生效、复审和替代状态;稳定描述做什么、谁负责、何时生效,易变操作方法链接到受控 SOP。规范词优先沿用组织现有定义强度不明时标`[规范强度待确认]`
- 检查整改区分用户陈述、原始记录、已复核事实和待补证线索;关键日期、数量或结论证据不足时就近标`[证据待补:补证动作]`,不得推断原因或责任;归档补正保留原记录。
- 检查措施必须对应具体发现并可核验;已批准通知只传达授权范围内的事项;正式讲话只使用已核定立场,并按真实语速朗读校验。
- 使用主动句、明确主体和一致术语,一句只表达一个事实、判断、要求或许可;清单严守用户指定数量与字段,不机械补背景或文控字段。
- 批准者、依据、权限、适用范围、生效状态或发布条件不明时使用具体占位并保持草案;不得以版式、标题或署名暗示已经批准、签发或生效。

View File

@@ -0,0 +1,24 @@
# Genre Contract: Meeting Minutes / 会议纪要 (`workplace.meeting_minutes`)
## 体裁规则表(硬约束)
| 规则项 | 规则 |
|-|-|
| presentation_mode / 表达模式 | `normal`;中性、精确、按议题和决定组织,用稳定标签区分决定、建议、未决和待确认,不重放发言顺序 |
| 内容逻辑 | 先说明会议身份和记录状态,再按议题写实际材料 / 必要讨论摘要 → 决定及理由 / 异议 → 未决项 → 行动 → 审阅材料;深度与治理风险相称 |
| 事实 / 边界 | 出席、法定人数、冲突、动议、表决、决定、owner、期限和批准状态均须来自会议材料或确认只保留治理所需个人信息草稿不得冒充批准版历史状态固定为文字快照不得由`checkbox``task`等可变交互块改写 |
| 错误 | 摘要冒充逐字稿、讨论流水账、建议写成决定、行动不可跟踪、法定人数不明却宣称决定有效、草稿冒充批准、静默改历史或泄露无关个人信息,任一出现即失败 |
## 适用与消歧
用于某次已发生会议的可引用治理记录,使缺席者、执行者和审核者确认决定、未决与行动。逐字 / 逐发言人 / 可回放内容只是 transcript 源材料;会前准备走 `memo-brief.md`;非会议状态走 `weekly-report.md`;党政机关法定“纪要”走 `official-redhead.md`
## 子类型与治理证据
普通工作会可精简为会议身份、决定、未决和行动;项目决策会补必要理由与审阅材料;董事会、委员会、表决或法定会议按章程 / 适用规则记录出席、法定人数、利益冲突、动议、票决、精确决议及认证。
证据可来自 agenda、出席记录、实际审阅材料、动议 / 投票和录音 / 逐字稿,但正文只链接关键来源,不复制附件淹没决定。来源冲突并列保留并交主持人 / 参会者确认。
## 结构与高质量写法
标明名称 / 类型、日期时间、地点 / 方式、主持 / 记录和草稿 / 已批准状态;每个议题围绕结果而非发言顺序。行动项写交付物 / 动作、责任人 / 单位、时间要求和状态。缺失信息用`[决议原文待确认]``[owner 待确认]`等具体占位;法定人数或批准不明时不得宣称有效,保持草稿并进入确认流程。

View File

@@ -0,0 +1,25 @@
# Genre Contract: Memo / Brief (`workplace.memo_brief`)
## 体裁规则表(硬约束)
| 规则项 | 规则 |
|-|-|
| presentation_mode / 表达模式 | `normal`;直接、克制、按具名读者控制信息密度,首屏给结论、状态或 ask不设固定篇幅 |
| 内容逻辑 | 先选信息、决策或会前三种模式之一,再按“核心事项 / ask → 必要事实 → 影响 / 取舍 → 风险 / 未知 → 动作”推进;只有真实选择才写选项 |
| 事实 / 边界 | 事实、数字、立场、审批状态和时点均须可核验未知与假设就近标记Memo 只可作完整 Proposal 的决策封面,不替代其论证 |
| 错误 | 首屏无结论或 ask、把完整 Proposal 压成摘要、编造审批 / 立场、用固定篇幅删证据、细节不解释影响,任一出现即失败 |
## 适用与消歧
用于让具名内部读者快速知悉、判断或完成会前准备。请求批准完整方向、预算、资源或执行承诺走 `proposal.md`;按周期判断相对目标的位置走 `weekly-report.md`;“摘要 / 简报”单词本身不触发本体裁。
## 子类型与证据
- 信息 Brief变化 → 影响 → 当前状态 / 风险 → 下一步;无须行动时明确“仅供知悉”。
- 决策 Memo决定事项 / 时点 → 现状 → 真实选项及同口径影响 → 推荐与证据 → 明确决策入口。
- 会前 Brief会议目标 → 已核验的参与方立场 / 利益 → 要点与禁区 → 期望结果;未知立场不得补造。
- 按需标读者、作者 / 责任团队、日期和信息截至时间。持续更新时说明相对上版的变化及下次更新点。
## 结构与高质量写法
按重要性而非材料顺序组织,一个段落一个观点;关键判断不藏在附件。建议写清谁做什么、为什么以及怎样判断完成,并呈现足以改变判断的风险、反例和不确定性。缺关键事实时用`[关键结论待确认]``[数据口径待核]`等具体占位,或收窄为待核问题清单;仍要求据此批准时必须 `blocked`

View File

@@ -0,0 +1,72 @@
# Genre Contract: Official Document / 公文内容稿 (`workplace.official_redhead`)
## 体裁规则表(硬约束)
| 规则项 | 规则 |
|-|-|
| presentation_mode / 表达模式 | 固定 `formal`;庄重、准确、简洁、直接。禁 emoji、网感、营销话术、情绪化评价、空话和机械编号 |
| 允许 block | `title`(完整文稿最多 1 个)、`p``h1``h2``h3``h4`;标题层级连续且不超过四级 |
| 少用 block | `ul``ol`容器及`li`子块仅用于真实并列项,不替代公文层级序号;`table`容器及`thead``tbody``tfoot``tr`子块仅用于非表格难以清楚表达的多对象同字段信息 |
| 禁止 block | 禁止未列入允许 / 少用清单的类型,包括`callout``grid`容器及`column`子块、`checkbox``whiteboard``blockquote``pre`、根级`code``hr``img``figure`;禁装饰色、伪红头和伪印章 |
| 内容逻辑 | 按行文目的、机关关系和受众确定唯一文种,再按“必要依据 / 缘由 → 核心事项 / 决定 → 可执行要求 → 必要结语”推进 |
| 事实 / 边界 | 只写已给定或已核验的事实、依据、权限和决定;未知项具体占位,关键缺口使 `Publish Gate = blocked`;飞书只交付内容审校稿,不宣称已签发或生效 |
| 错误 | 禁止文种或行文关系错误、报告夹请示、请示一文多事 / 多头主送、批复无对应请示、引用 / 文号 / 序号 / 附件不规范,以及编造事实、依据、权限或制发要素 |
## 适用
仅在明确要求公文、红头 / 套红、正式发文,或法定文种与机关行文关系、发文字号、签发人、主送机关等制发要素共同出现时使用。“红头文件”是制发信号,不是文种;普通公司通知、制度、检查 / 整改材料走 `formal-doc.md`,普通会议记录走 `meeting-minutes.md`
## 文种选择
按“行文目的 → 发文与受文机关关系 → 受众范围”判断,不按单个关键词判断。
| 文种 | 适用意图 |
|-|-|
| 决议 | 会议讨论通过重大决策 |
| 决定 | 对重要事项作出决策部署、奖惩或变更 / 撤销决定 |
| 命令(令) | 公布法规规章、施行重大强制措施、授予衔级或嘉奖 |
| 公报 | 权威公布重要决定或重大事项 |
| 公告 | 向国内外宣布重要或法定事项 |
| 通告 | 在一定范围公布应遵守或周知的事项 |
| 意见 | 对重要问题提出见解和处理办法 |
| 通知 | 要求下级 / 有关单位执行或周知,批转、转发公文 |
| 通报 | 表彰、批评、传达重要精神或告知重要情况 |
| 报告 | 向上级汇报工作、反映情况或答复询问,不请求决定 |
| 请示 | 向上级请求指示或批准;一文一事,原则上只主送一个上级机关 |
| 批复 | 答复下级机关请示,必须有对应来文 |
| 议案 | 政府依法向同级人大或其常委会提请审议 |
| 函 | 不相隶属机关间商洽、询答、请求批准或答复审批 |
| 纪要 | 记载正式会议主要情况和议定事项,不写逐字过程 |
优先消歧:汇报且不求决定用报告,求上级决定用请示,不相隶属机关商洽用函;面向明确单位执行用通知,面向一定范围不特定对象遵守用通告,向国内外宣布重要 / 法定事项用公告,传达情况或评价用通报。
## 行文与事实
- 按隶属关系、职权和授权行文;一般不越级,特殊越级时同时抄送被越过机关。
- 上行文原则上主送一个上级机关,不抄送下级;报告不得夹带请示。除直接交办外,不主送上级负责人个人。
- 一份主文保持一个行文方向和授权状态;同一事项若既需向上请求批准又需向下要求执行,应拆分文稿或待批准后另行制发,附件不得偷渡尚未授权的执行要求。
- 下行要求不得超出发文机关权限;涉及其他地区 / 部门职权时先协商。联合行文仅限必要且主体关系适当的情形。
- 只把已确认的决定写成指令。措施按需写明主体、动作、对象、期限、标准和反馈去向;对不相隶属机关使用`商请``请予``函复`等匹配关系的措辞。
- 缺少授权、关键依据、核心事实、适用范围或审批决定时不得发布;不得猜测文号、签发人、密级或紧急程度。
## 内容结构
- 标题一般使用“发文机关 + 事由 + 文种”,内含法规、规章或被印发文件名称时使用书名号。
- 主送机关使用全称、规范简称或同类机关统称。附件说明与附件顺序、名称逐字一致;多个附件用阿拉伯数字编号,名称末尾不加标点。
| 文种 | 常用结构 |
|-|-|
| 通知 | 缘由 / 依据 → 事项 → 对象 / 时间 → 已确认要求 |
| 请示 | 缘由 / 依据 → 单一请示事项与倾向意见 → `妥否,请批示` |
| 批复 | 准确引用来文 → 明确意见 → 执行要求 → `此复` |
| 函 | 事项 / 依据 → 商请或答复 → `请予函复` / `特此函复` |
| 报告 | 情况 → 事实 / 成效 → 问题 → 后续安排 → `特此报告` |
| 纪要 | 会议基本信息 → 主要情况 → 议定事项 / 责任 / 时限 |
## 文号、引用与序号
- 普通发文字号采用“机关代字 + 完整年份 + 顺序号”,如 `×政发20268号`;年份用六角括号,顺序号不加“第”、不编虚位。命令(令)的令号可用 `第×号`
- 首次引用其他公文时写完整标题和文号:`《××机关关于印发〈××办法〉的通知》×20268号`。不只写文号,不用论文式参考文献编号。
- 文件、法律法规名称使用书名号;直接引文使用中文双引号,内层用单引号。引文须核对原文、效力、制定机关和适用范围;无法核实则标记 `[引文待核]`
- 正文层级依次使用 `一、``(一)``1.``1`,不得写成 `1、``(一)、`,不得跳级;超过四级时重组内容。
- 成文日期写为 `2026年7月13日`,月日不补零。标点和数字按 GB/T 15834、GB/T 15835 使用;全称及规范简称前后一致。

View File

@@ -0,0 +1,25 @@
# Genre Contract: PRD / 产品需求 (`workplace.prd`)
## 体裁规则表(硬约束)
| 规则项 | 规则 |
|-|-|
| presentation_mode / 表达模式 | `rich`;具体、行为化、术语和状态一致;在有明确内容作用时用场景、状态流、表格、图示和其他 rich block 降低理解与验收成本,但不让视觉组件替代需求、证据或验收,不用固定大模板制造完整感 |
| 内容逻辑 | 方向已定后按“用户问题 / 证据 → 目标 / 结果 → 范围 / 非目标 → 场景 → 行为需求 / 验收 → 异常 / 边界 → 适用质量约束 → 依赖 / 开放问题”推进 |
| 事实 / 边界 | 用户需要、指标、研究、阈值、可行性、owner、状态和排期须可追溯需求描述可观察结果acceptance criteria 验结果;安全、隐私、无障碍等仅按实际风险和标准纳入 |
| 错误 | 功能清单无用户问题、Proposal 论证吞没需求、范围 / 非目标缺失、需求暗藏实现、验收不可测、正常路径无异常、伪造研究 / 阈值 / 批准或机械填质量模板,任一出现即失败 |
## 适用与消歧
用于方向与投入原则已定后,让产品、设计、研发和测试就用户问题、范围、可观察行为与完成标准形成共识。是否立项 / 选择方向 / 批资源走 `proposal.md`;架构、接口和实现取舍走 `technical-doc.md`;已批准重复操作走 `sop-tutorial.md`。“需求 / 功能”单词本身不触发。
## 证据与需求写法
- 明确目标用户、任务情境、问题及研究 / 行为 / 支持证据;内部偏好和预设功能不冒充用户需要。
- 产品目标连接可观测结果,指标标口径、来源和时间窗。未知目标值用`[目标值待产品 / 数据确认]`并给确认 owner / 时点,不编使用量或阈值。
- 关键需求写成 actor + trigger / precondition + observable outcome + failure / edge术语和状态一致。用户故事格式只是工具不是章节配额。
- 每个质量约束给可验证门槛或明确待确认项;不适用时不填模板。需求、验收 / 测试和来源保持追踪。
## 结构与高质量写法
先定范围、非目标、优先级、依赖、假设和开放问题,防止 scope creep再按关键场景写正常、异常和边界行为。把大而不可测的需求拆到可验收粒度不用“体验更好 / 性能高”等形容词。没有用户证据时收窄为假设和研究计划;关键合规 / 安全门缺失时 `blocked`,开放问题不得藏在脚注。

View File

@@ -0,0 +1,24 @@
# Genre Contract: Proposal / 方案提案 (`workplace.proposal`)
## 体裁规则表(硬约束)
| 规则项 | 规则 |
|-|-|
| presentation_mode / 表达模式 | `normal`;结论前置、具体、可审议,主动呈现代价、反例与不确定性,不用宏大背景或伪精确制造可批准感 |
| 内容逻辑 | 明确 decision / 决策者 / 时点,再按“改变理由与不行动基准 → 目标 → 真实选项同口径比较 → 推荐 → 资源 / 交付 → 风险 / 未知 → 决策入口”推进 |
| 事实 / 边界 | 区分事实、估算、假设和未知;收益、成本、资源、用户证据、审批和排期须可追溯;进入执行决策才写治理 / 退出条件,未批准不得写成既有承诺 |
| 错误 | 无决策者 / ask、无不行动基准、预设单一答案、选项口径不同、成本风险后置、未批先承诺、编造收益 / 审批或与 PRD 混写,任一出现即失败 |
## 适用与消歧
用于请求具名决策者批准、驳回或选择方向、预算、资源、试点或执行承诺。方向已定并定义产品行为 / 验收走 `prd.md`;短决策封面走 `memo-brief.md`;已批准安排的发布走 `formal-doc.md`。“方案”单词本身不触发本体裁。
## 子类型与证据
可用于概念 / 方向、投资 / 预算、资源申请、变更、试点 / 实验和执行承诺提案;深度随阶段、金额、风险和不可逆性裁剪。必须给 case for change、目标 / 成功标准、不行动或最小变化基准,以及足以判断的成本、收益、依赖、风险和敏感因素。
存在真实选择时纳入可行替代并以相同范围、时间和评价标准比较;没有真实替代时说明约束如何收敛,不能造假选项。不可量化影响可定性,但须说明原因及其决策影响。
## 结构与高质量写法
先把选择题写对,再论证推荐;显式记录被放弃选项和推荐代价。数字不足时使用范围、依据和验证计划,不补精确点估。进入执行决策时按需补 owner、里程碑、治理、衡量、退出 / 复盘;缺决策权、关键成本或安全合规依据时收窄为探索稿,仍要求批准则 `blocked`

View File

@@ -0,0 +1,32 @@
# Genre Contract: Research Report / 调研报告 (`report.research_report`)
## 体裁规则表(硬约束)
| 规则项 | 规则 |
|-|-|
| presentation_mode / 表达模式 | `normal`;证据驱动、校准、术语一致;摘要独立可读,语气强度不得超过证据强度 |
| 内容逻辑 | 先确定研究问题与研究类型,再交付当前答案、证据强度和可推广边界;按问题或主题组织发现,解释、建议和验证计划必须回链发现 |
| 事实 / 边界 | 区分原始事实或参与者陈述、分析推断、假设和建议;方法披露足以评估偏差;适用时确认委托、利益、同意、匿名或保密、敏感数据用途;研究材料须确认使用权、去标识、来源与说明,复杂视觉附文字等价信息;未知不补造 |
| 错误 | 无明确问题;方法黑箱;资料摘要冒充发现;样本外推;醒目个案冒充模式;事实、解释和建议混写;相关写成因果;合规状态、授权或行业共识靠猜 |
## 适用与消歧
以明确研究问题、研究设计或材料、发现和限制为主要交付。`调研``研究过``访谈``问卷`单独只用于召回;只解读既定指标走 [`data-report.md`](data-report.md),比较特定战略或资源选项走 [`business-analysis.md`](business-analysis.md),方法并非判断重点的问题框架综合走 [`white-paper.md`](white-paper.md)。
## 子类型
- **定量 / 定性 / 混合研究**:根据问题选择总体、抽样或招募、工具、采集和分析方法;不用一种方法的规范冒充全部研究标准。
- **用户研究 / 项目或政策评估**:说明场景、参与者、干预或对象、成功标准、观察窗口和用途。
- **证据综合**:只有检索范围、纳排和综合方法明确时才作为研究发现;普通资料汇总不得升级为系统结论。
## 证据与方法
- 明确对象、用途、非目标和适用情境;按需披露委托 / 执行方、总体与纳排、抽样 / 招募、样本量、工具 / 题项、采集方式 / 语言 / 时点、响应 / 脱落、加权、编码 / 分析和质量控制。
- 写明偏差、缺失、反例、负结果、替代解释及其可能方向;透明报告不等于设计无偏,也不证明结论可复现。
- 人员或敏感研究在适用规则下确认知情同意、撤回与伤害风险、匿名 / 保密、访问和数据用途;未获授权不公开可识别材料、原始数据或代码。
- 引文只说明有出处的体验或机制,不把单个引文写成频率;结论只推广到设计和样本支持的人群、时间与环境。
- 无原始材料只能产出研究范围或计划,不能生成 findings方法或样本缺失时用 `[抽样方法待核]``[采集时点待核]` 并收窄为探索性观察。关键伦理、授权或方法缺口会改变结论时标记 `blocked`
## 结构与高质量写法
独立答案、证据强度与关键限制 → 问题 / 范围 / 既有知识 → 方法 / 样本 → 按问题或主题组织的发现 → 解释、反例与替代解释 → 有边界的建议 / 验证 → 局限、来源与必要附录。摘要覆盖目的、方法、发现、含义和限制;正文以“主张 → 证据 → 限定”推进,不按作业时间线罗列过程,不用组件数量代替研究质量。

View File

@@ -0,0 +1,25 @@
# Genre Contract: Retrospective / 复盘 (`workplace.retrospective`)
## 体裁规则表(硬约束)
| 规则项 | 规则 |
|-|-|
| presentation_mode / 表达模式 | `normal`;坦诚、无责备、因果克制,围绕证据和下一轮改变,不用“加强沟通 / 持续关注”代替可验证实验 |
| 内容逻辑 | 界定已结束周期 / 事件,再按“目标 / 证据 → 预期与实际 → 聚类观察 → 洞见 / 待验证因果 → 保留项 → 少量改进实验 → 复查”推进 |
| 事实 / 边界 | 事实 / 观察、解释 / 假设、洞见和行动分层;结论回链事件、指标或交付物;根因仅在证据充分时声明,否则写可证伪假设;保护必要隐私 |
| 错误 | 周报换标题、成绩陈列 / 情绪宣泄、个人归罪、单一根因臆测、行动无 owner / 验证 / 跟踪、不回看上轮或把模板便签当结论,任一出现即失败 |
## 适用与消歧
用于回看明确迭代、阶段、项目或事件,形成可复用学习并改变下一轮做法。当前状态与升级需求走 `weekly-report.md`;仍在未知中止损、取证、恢复或调查生产事故走 `technical-doc.md`。生产事故可由 Technical 主文承载影响 / 时间线 / 根因 / 恢复,再附本体裁的团队学习层。
## 证据与因果
- 开头界定范围、时间、目标 / 原计划、参与视角和已知证据;不得补造指标、时间线、共识、原因或行动。
- 同时识别应保留与应改变的条件,按影响聚类;以系统、流程、工具、接口和当时条件为对象,不把惩罚叙事冒充根因。
- 个人工作心得 / 成长反思以一个真实事件或转折为证据,呈现“当时判断 → 反证 / 后果 → 新认识 → 下一次可观察行为”;不代写材料没有提供的情绪、动机、心路或成长。
- 证据不足时写“促成条件 / 假设 + 验证方式”,不能用确定语气。缺基线用`[基线待补]`,涉及安全 / 法务而证据不足时转 Technical 并 `blocked`
## 结构与高质量写法
便签、4Ls、Start / Stop / Continue 只是收集手段成稿须综合为主题和判断。改进实验写动作、owner、目标时间、验证条件和跟踪位置优先改变系统而不是要求人“更小心”按需补上轮行动效果和下轮复查点。项目收尾可增加成本、范围、相关方和知识移交但不机械扩章。

View File

@@ -0,0 +1,37 @@
# Genre Contract: Consumer / 消费决策内容 (`router.consumer`)
## 体裁规则表(硬约束)
| 规则项 | 规则 |
|-|-|
| presentation_mode / 表达模式 | `rich`;具体、可信、可亲近,体验感服务于选择,不用热情语气替代测试、价格和适用条件 |
| 内容逻辑 | 围绕具体消费场景,用“需求 / 使用条件 → 评价标准 → 体验或测试证据 → 权衡 → 适合谁 / 不适合谁”推进;合集和比较须共享标准,不按品牌逐段堆卖点 |
| 事实 / 边界 | 只声称真实体验或有方法支撑的测试;披露赠品、佣金、赞助和其他重要关系;标明版本、时间、价格口径及限制;用户 / 专家引语、图片和前后对比须有授权、来源、语境与真实性依据,非文字证据须有文字等价信息;遵守目标法域和平台当期消费者、广告与高风险品类规则,关键利益关系、核心功效、安全条件或报价条款缺失时 blocked |
| 错误 | 编造使用经历、未披露商业关系、无方法的评分 / 排名、把主观偏好写成客观最佳、隐藏不适用人群或总成本、用极端个案概括功效、过期信息仍当现状,任一出现即失败 |
## 适用与消歧
用于帮助读者购买、比较、避坑或判断某种生活方式是否适合自己。仅出现小红书、微信等平台名不触发;明确要求最终交付小红书笔记或微信公众号文章时走 `route_platform`,再选择对应 leaf消费选择任务作为该 leaf contract 的硬约束,不再并读 Consumer。以公共事件核实为主走 Media以价值判断为主走 Opinion以品牌拥有的转化内容走 Marketing。
“测评”必须继续区分独立比较、真实个人体验和品牌演示:前两者可走本合同,品牌控制结论或行动入口时走 Marketing并保留显著披露。
## 子类型
| 子类型 | 读者任务与推进 |
|-|-|
| 单品体验 / 好物分享 | 判断某物在真实场景是否值得;使用背景 → 观察 → 优缺点 → 适用人群 |
| 对比测评 / 排名 | 在同一任务下选择;方法与样本 → 共同标准 → 结果 → 权衡与不确定性 |
| 合集 / 清单 | 快速缩小候选范围;选择门槛 → 分组理由 → 各项差异 → 最终选择路径 |
| 探店 / 服务体验 | 判断是否到访或购买服务;时间地点 → 实际流程 / 价格 → 体验证据 → 限制 |
| 生活方式内容 | 判断实践成本与可复制性;目标 → 做法 → 真实投入 / 结果 → 适用边界 |
## 证据、披露与合规
- 第一人称体验交代使用时长、频率、版本和条件;未亲测就明确资料来源,不伪装成亲历。比较结论说明样本、标准、测量方法及未覆盖变量。
- 把“真实 / 有效”“适合当前读者”“值得当前价格”分开判断。强参数品只保留会改变选择的指标,并解释版本口径和决策影响;使用评分 / 排名时公开标准、权重、主观边界和反转条件,安全或资格等一票否决项不得被平均分稀释。
- 商业关系和激励在读者接触推荐时清楚出现,不能藏在模糊标签或文末。披露、重大限制和安全警示须就近可见,不能只藏在链接或视觉装饰中。
- 健康、安全、金融、未成年人等高风险内容只写证据支持且适用法域允许的范围;不能核实的功效或个体化建议删除。规则冲突时按交付地区、渠道和发布时间核验,不把单一国家指南写成全球义务。
## 结构与高质量写法
先告诉读者评判基准,再给结论,才能让“推荐”可复核。优点与代价写在同一决策语境内,价格同时说明时间、地区、规格和附加成本。结尾给条件化选择,而不是人人适用的口号;关键参数待补时用具体占位并暂停对应结论,不能靠语气填空。

View File

@@ -0,0 +1,36 @@
# Genre Contract: Creative / 叙事创作 (`router.creative`)
## 体裁规则表(硬约束)
| 规则项 | 规则 |
|-|-|
| presentation_mode / 表达模式 | `rich`;语言、节奏和视角服务指定叙事体验,表达自由不替代人物动机、因果和场景可读性 |
| 内容逻辑 | 本合同只覆盖叙事创作;先确认体验、篇幅、视角和约束,用“人物欲望 → 阻力 → 选择 → 代价 → 变化”形成场景因果;剧本和互动叙事分别服从可演行动与有后果分支 |
| 事实 / 边界 | 用户授权的虚构可创造,但真实背景、引用、既有作品正史和人物身份不得伪造;图片、题记、原作片段和创作参考须遵守来源与使用权限,非文字参考及互动分支图须附文字等价的关系、路径和状态说明;区分明确设定、合理创作补白和待确认约束;核心世界观 / 权利边界冲突且无法安全收窄时 blocked |
| 错误 | 只堆设定不发生选择、人物为推进情节突然失去动机、冲突靠偶然或外力无代价解决、视角 / 时态无意漂移、剧本写成解释性小说、互动分支无状态差异、把诗歌静默纳入交付,任一出现即失败 |
## 适用与消歧
仅用于网文、短篇故事、同人叙事、互动小说、剧本和故事大纲等以事件、人物选择和变化为核心的创作。诗歌、歌词、纯抒情散文不在本合同范围收到这类请求时先确认目标或使用相应专用规则不因“Creative”一级名称而静默扩写。
以论点和证据表达判断走 Opinion以真实个人经历建立专业信誉走 Personal Brand。世界观说明若目标只是知识解释不因带角色名就成为故事。
## 子类型
| 子类型 | 读者任务与推进 |
|-|-|
| 短篇 / 网文 | 获得连续叙事体验;触发变化 → 升级阻力 → 关键选择 → 后果 / 回响 |
| 同人叙事 | 在约定正史与角色核心上体验新情境;明确时间点 / 偏离点 → 角色选择 → 新后果 |
| 剧本 / 短剧 / 叙事短视频 | 看见可拍、可演的行动与冲突;媒介 / 时长 / 制作约束 → 场景目标 → 视觉、行动、声音 / 对话 → 转折 → 场景状态变化 |
| 互动小说 | 作出有信息依据且有后果的选择;状态 → 选择 → 反馈 → 状态改变 → 后续分支 |
| 故事大纲 | 判断故事能否成立并继续创作;前提 → 人物弧 → 节点因果 → 高潮选择 → 结局变化 |
## 设定与真实性
- 先锁定用户给定的人物、关系、禁区、正史时间点和期望体验;未指定的创作空间可以补白,但不得覆盖明确约束。关键歧义有多个会显著改变成品的方向时先询问。
- 使用真实地点、历史、科学或文化材料时核验会影响情节的事实;有意架空应让读者能辨认其虚构约定。同人创作不把自设冒充正史,也不虚构原作引语。
- 真实人物、未公开经历、受保护素材和委托作品按授权边界处理;不能确认可用性时改为原创替代或保持 blocked。
## 结构与高质量写法
每个场景都让人物为目标采取行动,并在离场时改变信息、关系、资源或风险。细节同时承担感官、人物或伏笔功能,背景通过当前冲突释放,不集中讲解。对话要改变局面而非重复旁白;剧本动作、声音和调度须在声明的演员、场地、道具与媒介条件下可实现,不用固定“前三秒 / 每分钟一反转”公式代替因果。结局兑现前文建立的选择与代价。大纲可显式呈现结构,成稿则把结构转化为可体验的场景。

View File

@@ -0,0 +1,39 @@
# Genre Contract: Knowledge / 知识与教程 (`router.knowledge`)
## 体裁规则表(硬约束)
| 规则项 | 规则 |
|-|-|
| presentation_mode / 表达模式 | `normal`;具体、可操作、按读者水平解释;科普可生动、有好奇心,但不得牺牲准确性或编造戏剧性 |
| 内容逻辑 | 先选择唯一主模式和读者起点,再承诺一个理解、学习、一次操作、检索或选择结果;第一屏给适用对象、目标和关键前置,概念、步骤、练习 / 验证、反馈与例外按需渐进展开 |
| 事实 / 边界 | 事实、版本、命令、UI 路径和链接须核验;示例与规则分开;截图 / 案例不得泄露敏感信息;已知自助路径可写,组织受控重复作业走 SOP设计、精确技术契约或未知诊断走 Technical |
| 错误 | 不声明读者起点;教程变理论课;学习计划无基线 / 完成标准 / 调整规则;只有原则无步骤 / 例子步骤无结果或验证版本、权限、环境缺失编造命令、UI 或链接FAQ 脱离真实问题;资源合集无标准 / 注释 / 维护;视觉成为唯一信息;把未知排障写成确定答案 |
## 适用与消歧
适用自主理解、学习 / 备考规划、一次已知任务或检索复用。`科普``教程``指南``攻略``学习计划``FAQ``知识库``资源合集`只用于召回;“知识库”是容器或渠道,不决定文章体裁。组织要求多人按批准版本重复执行并留痕走 [`sop-tutorial.md`](sop-tutorial.md)未来设计、API 精确契约、生产状态变更或未知根因走 [`technical-doc.md`](technical-doc.md);研究或数据形成新洞察走 Report。
## 主模式
| 模式 / 读者任务 | 结构推进 |
|-|-|
| Explanation / 科普:建立正确心智模型 | 现象 / 误区 → 概念模型 → 机制与证据 → 例子 → 争议、限制与适用边界 |
| Tutorial通过受引导练习获得技能 | 学习目标 → 起点 / 环境 → 安全练习 → checkpoint → 复盘与下一步 |
| Learning plan在现实约束下持续提高 | 基线诊断 → 可观察的阶段目标 → 练习 / 资料 / 时间 → 完成标准与反馈 → 调整规则 |
| How-to完成一个已知目标 | 目标 → 前置 → 最短有效步骤与可观察结果 → 变体 / 已知错误 → 完成验证 |
| FAQ / known troubleshooting快速找到已验证答案 | 按真实问题或症状分组 → 直接答案 → 必要条件 / 操作 → 相关内容;需要新假设或根因调查时转 Technical |
| Resource guide按标准选择资源 | 使用场景 / 筛选标准 → 分类 → 每项适配、代价与访问条件 → 维护信息 |
| Reference / KB article检索并复用事实或解法 | 上下文 / 适用版本 → 事实或 issue-resolution → 限制 / 相关项 → 时效性强时标 owner / last verified |
## 事实、步骤与维护
- 明确受众的已有知识、范围 / 非范围、版本、环境、权限与风险;术语在首次需要时解释,不先灌输完整理论。
- 学习计划按阶段 / 能力、可用时间、既有任务和可得资料控制强度;目标拆成可观察表现,每阶段合写练习、完成标准、反馈和调整条件。会显著改变安排的缺口先问或条件化,不补造基础 / 时间。
- 顺序任务一项写一个清楚动作,紧邻给可观察结果;命令、输入、输出和成功验证须能在声明环境中复现,危险或不可逆警告必须在动作前。
- FAQ 只收真实用户问题或检索需求;否则按用户任务重组。资源指南先写选择标准,再给有描述的精选链接,不用外链代替核心上下文。
- 时效性内容标适用版本 / 时间并说明维护边界;复杂视觉须有可传达同等信息的正文,图片、案例和代码不得成为无解释的唯一依据。
- 版本或权限不明时用 `[适用版本待核]``[所需权限待确认]` 并只写不受影响部分;未验证命令或链接不进入发布稿。缺口可能造成损失、安全风险或关键分叉时标记 `blocked`
## 高质量写法
第一屏让读者知道能理解、学会、完成或找到什么;用读者语言、具体动词和可验证结果推进,每节只增加必要的新理解或动作。先给最短可行路径,再在需要处补原理、变体和进一步阅读;示例只服务迁移,不扩张为用户未要求的全套内容,也不用丰富组件掩盖解释不足。

View File

@@ -0,0 +1,40 @@
# Genre Contract: Marketing / 营销与公关 (`router.marketing`)
## 体裁规则表(硬约束)
| 规则项 | 规则 |
|-|-|
| presentation_mode / 表达模式 | `rich`;清楚、有吸引力且可行动,表达强度不得超过承诺、证据和授权,紧迫感不得制造误导 |
| 内容逻辑 | 先锁定受众、漏斗阶段和唯一主要读者结果;转化内容用“场景 / 问题 → 有边界的价值主张 → 证据 → 关键条件 / 异议 → 一个 CTA”推进公关稿按已授权事实、相关方影响、组织回应和后续更新推进 |
| 事实 / 边界 | 所有客观、比较、功效和稀缺性主张发布前有相称证据;价格、资格、期限和限制就近可见;广告身份与商业关系按目标法域 / 平台规则披露;评价、案例、引语、图片和活动素材须真实、可核且获授权,非文字证据须有文字等价信息;核心主张证据、适用法域、发布授权、关键交易条件或任务要求的行动入口缺失时 blocked |
| 错误 | 无证据的“最佳 / 保证 / 第一”、隐藏限制或自动续费、伪造倒计时 / 库存 / 评价、把广告伪装成独立报道、未经授权承诺赔付或责任、转化内容多个 CTA 争抢、用复杂 block 掩盖价值缺口,任一出现即失败 |
## 适用与消歧
用于组织拥有或授权、目标是认知、转化、留存或公共关系管理的内容。由新闻机构独立选题、核实和报道的内容走 Media组织自有新闻稿、媒体通稿、品牌声明和回应口径走 Marketing即使采用新闻结构也不变成独立报道。
个人真实体验用于帮助消费选择时走 Consumer明确要求最终交付小红书笔记或微信公众号文章时走 `route_platform`,再选择对应 leaf营销目标、商业关系和交易条件作为该 leaf contract 的硬约束,不再并读 Marketing。出现“新闻稿、软文、活动文案”只作召回信号仍须确认发布主体、受众、行动和商业关系。
内部营销策划、增长方案或活动执行计划不因“营销”进入本合同:比较打法走 Business Analysis请求预算 / 资源 / 战役批准走 Proposal已定打法的协同落地走 Execution Plan只有最终面向受众的传播、招募或转化成稿走 Marketing。
## 子类型
| 子类型 | 读者任务与推进 |
|-|-|
| 广告 / 短文案 | 迅速判断是否值得行动;受众场景 → 单一利益 → 可信理由 → 条件 → CTA |
| 详情页 / 落地页 | 完成比较与转化;价值主张 → 关键能力 → 证据 → 方案 / 条款 → 异议 → CTA |
| 活动 / 私域话术 | 判断是否参与并知道下一步;对象 → 收益 → 时间地点 / 门槛 → 风险限制 → 行动 |
| 新闻稿 / 媒体通稿 | 获取组织已授权消息;可发布事实 → 为什么重要 → 引语 / 背景 → 联系与更新安排 |
| 声明 / 危机回应 | 理解已知事实和组织行动;事件范围 → 已确认影响 → 当前措施 → 未知项 → 下次更新时间 |
## 证据、授权与合规
- 建立“主张—证据”对应:定量效果说明口径、样本和时间,比较主张保证对象与标准可比;图片、引语、评价和案例保留来源、必要语境及授权记录。
- 披露和限制应让普通受众在作决定前看见并理解,不能由链接、模糊缩写或弱提示代替。规则随法域、媒介、品类和时间变化,交付前核验当期法律、监管与平台要求。
- 公关内容只写已获授权的事实和承诺;事故原因、责任、补偿、调查结论未核定时明确 unknown。关键批准或法律审阅未完成不生成可直接外发版本。
## 结构与高质量写法
价值主张具体到受众、场景和结果,证据紧跟对应主张。文案须锚定品牌独有资产、产品细节或品类语境;换成竞品名仍成立就返工。多版本应改变受众状态、主张、证据或场景并说明选择条件,不做同义改写。
删除不改变理解或行动的品牌空话,不把真实痛点升级为羞耻、身份不足或恐惧操控。有转化目标时,次级入口均服务同一主要行动;优惠资格和截止时间采用可比较字段,待补价格、库存或链接用语义化占位,并让受影响结论保持 blocked。

View File

@@ -0,0 +1,36 @@
# Genre Contract: Media / 资讯媒体 (`router.media`)
## 体裁规则表(硬约束)
| 规则项 | 规则 |
|-|-|
| presentation_mode / 表达模式 | `normal`;准确、中立、紧凑,信息密度服从读者快速理解,不用戏剧化措辞替代事实强度 |
| 内容逻辑 | 先确定快讯 / 报道、解释、人物特写或访谈的读者任务;关键信息优先,随后给证据、必要背景、相关方视角和仍未知事项,段落按重要性、因果或时间关系推进 |
| 事实 / 边界 | 区分已核事实、来源说法、推断和 unknown准确优先于抢发关键主张可追溯负面涉及方获得合理回应机会引语须忠实可核图片和原始材料须有使用权限、来源、语境说明及文字等价信息更正、披露和关键缺口须直接可见核心事实、来源真实性、发布权限缺失或严重负面指控尚未提供回应机会时保持草稿并 blocked |
| 错误 | 把组织自有通稿伪装成独立报道、标题超出证据、单一匿名来源承载重大指控、引语失真、事实与评论混写、遗漏重大反方或不确定性、图片无权利 / 来源 / 文字等价信息,任一出现即失败 |
## 适用与消歧
本合同用于以独立采集、核实和公共理解为职责的新闻内容。请求出现“新闻稿、媒体稿、报道”只作召回信号:编辑方能独立核实、选择角度并承担报道判断时走 Media由组织拥有、批准并面向媒体或公众发布的新闻稿、品牌声明和公关口径走 Marketing。
以立场说服为主走 Opinion以购买决策和亲身体验为主走 Consumer内部事实简报不因写得像新闻而改变读者任务。渠道名、标题风格或“像媒体一样写”均不能单独触发明确要求最终交付小红书笔记或微信公众号文章时走 `route_platform`,再选择对应 leaf资讯核实边界作为该 leaf contract 的硬约束。
## 子类型
| 子类型 | 读者任务与推进 |
|-|-|
| 快讯 / 硬新闻 | 尽快知道发生了什么及其可信程度;核心事实 → 来源与范围 → 必要背景 → 下一确认点 |
| 解释报道 | 理解为什么发生、如何运作及争议在哪里;问题 → 机制 / 时间线 → 多方证据 → 已知边界 |
| 人物 / 特写 | 通过可核场景和经历理解人物或议题;场景 → 关键变化 → 证据与他者视角 → 公共意义 |
| 访谈 / 问答 | 准确获取受访者观点及上下文;交代身份与场景,忠实编辑问答,不补造连接语或立场 |
## 证据与真实性
- 为可能引发争议的事实保留可追溯材料,记录来源身份、接近事实的方式、核实状态和使用限制;匿名只在有公共价值且无法安全具名时采用,并说明读者判断所需的来源范围。
- 引语逐字可核;压缩、翻译和转述不得改变含义。无法确认的数字、时间、身份或因果就近标明 unknown不用“据悉”“有消息称”遮蔽来源质量。
- 开盒、网暴、羞辱、未成年人或其他可能放大伤害的事件只保留理解事实、责任和传播机制所需的最少信息;不为证明热点而复刻身份线索、攻击性内容或未核传言。
- 更正要说明改了什么;新证据改变核心判断时更新标题和结论。发布前无法核实的核心主张不得靠占位符放行。
## 结构与高质量写法
标题和导语只承诺正文已证明的内容。每段承担一个信息动作,并在首次出现时交代人物、机构、时间和口径;背景只保留改变理解的部分。多方说法按证据权重而非形式上的各打一板排列,不把可验证事实写成“双方观点”,也不把尚无结论写成确定因果。

View File

@@ -0,0 +1,38 @@
# Genre Contract: Opinion / 观点评论 (`router.opinion`)
## 体裁规则表(硬约束)
| 规则项 | 规则 |
|-|-|
| presentation_mode / 表达模式 | `rich`;立场鲜明但措辞精确、公平,论证密度高于情绪密度,锋利不等于侮辱或夸张 |
| 内容逻辑 | 明确可争辩的中心判断及其重要性,用理由和证据推进;对有实质争议的主张呈现最强相关反论并回应,结论说明判断边界或行动含义 |
| 事实 / 边界 | 区分事实、推断、价值判断、预测和个人经验;事实可追溯,证据强度匹配主张强度,不把相关性写成因果或把个案外推为普遍规律;引语、图片和作品片段须有可核来源、必要语境与使用权限,非文字证据须有文字等价信息,重要利益关系须显著披露;关键事实缺失时收窄主张,无法成立则 blocked |
| 错误 | 只有态度没有论点、稻草人反驳、选择性证据、人格攻击、标题先定罪、把经验冒充统计、隐藏重大反例或利益关系、结论超出论证,任一出现即失败 |
## 适用与消歧
用于帮助读者评估一个判断、立场或解释框架。事件复述和独立核实走 Media围绕购买选择的测评走 Consumer组织为行动或转化发声走 Marketing。出现“评论、专栏、观点”只是召回词正文必须有可辨认的判断和论证任务。
文化评论关注作品、现象的意义和判断;若主要提供剧情复述或故事体验,不走本合同。个人经历可以作为观察入口,但若目标是展示经历与能力,走 Personal Brand。
## 子类型
| 子类型 | 读者任务与推进 |
|-|-|
| 时评 / 公共议题评论 | 判断事件意味着什么;争点 → 判断 → 证据与机制 → 反论 → 后果 / 建议 |
| 商业 / 行业评论 | 评估策略、趋势或制度;基线 → 驱动因素 → 证据 → 替代解释 → 适用条件 |
| 文化评论 | 理解作品或现象的价值;分析对象 → 解释框架 → 细读证据 → 限度 → 判断 |
| 专栏 / 随笔 | 从观察或经验形成可迁移洞见;具体场景 → 反思 → 关联 → 有边界的结论 |
## 证据与论证
- 开头尽早写出“我主张什么”和“为什么现在值得讨论”,避免用大段背景延迟论点。每个理由回答一个潜在质疑,并由事实、例子、机制或可靠来源支持。
- 反论选择真正能动摇中心判断的版本,不挑最弱说法;回应可以承认条件、修改范围或解释为何仍不改变结论。观点平衡不是机械分配篇幅。
- 公共争议先拆清事实真伪、规则 / 权利、价值取舍、责任归属和 unknown再分别判断行动建议须对应具体主体、权限 / 义务、可用杠杆与代价,不用“多方协同”抹平责任边界。
- 预测写明前提和时间范围;价值判断说明采用的标准。涉及他人动机、违法或伤害的判断不得凭语气升级为事实。
## 结构与高质量写法
段落之间形成“主张 → 理由 → 证据 → 推论”的可追链条,过渡词只标真实关系。文化评论选择一个能统摄正文的主分析轴,把情节、语言、镜头、声音、表演或结构写成“形式选择 → 产生效果 → 支持何种解释 / 评价”的证据链;比较或综述可有多个对象,但不能退化成剧情复述或维度清单,也不把效果直接冒充创作者意图。
结尾不复述全文,而是给出经反论校准后的判断、仍然未知的部分,或读者下一步应重新考虑什么。随笔可弱化显式论证标记,但不能牺牲观察与结论之间的可理解联系。

View File

@@ -0,0 +1,36 @@
# Genre Contract: Personal Brand / 个人品牌 (`router.personal_brand`)
## 体裁规则表(硬约束)
| 规则项 | 规则 |
|-|-|
| presentation_mode / 表达模式 | `normal`;可信、具体、有辨识度,声音服从目标读者和真实经历,不用自我评价替代成果证据 |
| 内容逻辑 | 从目标读者和目标机会出发,用“身份 / 价值定位 → 相关经历 → 可验证贡献 → 做事方式 → 下一步意图”组织;每项经历说明情境、本人动作、结果及与目标的关系 |
| 事实 / 边界 | 职位、时间、职责、学历、技能、作品和指标须真实可核,个人贡献与团队成果分开;尊重保密、个人信息、雇主和作品权利,作品、图片和推荐语须确认归属、使用权限与必要语境,非文字证据须有文字等价信息;关键身份、时间、归属或公开权限缺失时用具体占位,无法安全表述则 blocked |
| 错误 | 夸大头衔 / 技能 / 指标、把团队成果全归个人、关键词堆砌、伪造推荐语或客户、泄露敏感信息、作品无归属 / 权限、同一经历前后矛盾、渠道语气改变事实,任一出现即失败 |
## 适用与消歧
用于让招聘方、合作方、客户或专业社群判断“这个人是谁、做过什么、能带来什么”。仅出现平台名称不触发;明确要求最终交付小红书笔记或微信公众号文章时走 `route_platform`,再选择对应 leaf个人身份、经历和信誉目标作为该 leaf contract 的硬约束,不再并读 Personal Brand。
以项目经验得失来改进下一轮走 Retrospective以购买体验帮助他人选择走 Consumer以组织身份转化客户走 Marketing。出现“介绍、主页、复盘”不能单独触发须确认目标是个人能力和信誉呈现。
## 子类型
| 子类型 | 读者任务与推进 |
|-|-|
| 简历 / CV | 快速判断岗位匹配;摘要 → 相关经历与成果 → 技能 / 教育 → 必要补充 |
| 求职信 / 自我介绍 / 简介 | 理解动机与差异化价值;目标 → 相关证据 → 工作方式 → 明确下一步 |
| 个人主页 | 建立清晰定位并找到入口;一句定位 → 代表证据 → 领域 / 服务 → 联系或作品 |
| 作品集 / 案例集 | 判断能力如何形成结果;问题 → 约束与本人角色 → 过程决策 → 结果与反思 |
| 个人成长回顾 | 理解身份与能力变化;起点 → 关键选择 → 证据 → 学到什么 → 下一方向 |
## 证据与真实性
- 成果优先写可核结果及其口径,不能量化时写可观察变化、交付物或他人采用情况,不编造数字。明确“负责、协作、支持、批准”等角色差异。
- 时间线、组织名、客户名、作品链接和推荐语在公开前确认准确与授权;需匿名时保留问题、本人动作和结果的判断价值,不留下可反推的敏感细节。
- 技能由近期作品、职责范围或实际使用场景支撑;自我定位可以有主张,但不能使用未获认可的资质、奖项或身份。
## 结构与高质量写法
先筛选与目标读者最相关的经历不把完整人生经历当作专业证明。经历条目以动作和影响开头背景只写理解贡献所需的约束案例说明权衡和本人判断比工具清单更能证明能力。CTA 具体到希望发生的下一步,并只提供获授权的联系方式。

View File

@@ -0,0 +1,9 @@
# Genre Router: Platform / 平台发布稿 (`route_platform`)
仅当最终交付物是小红书笔记、微信公众号文章或邮件成稿时进入本 router按目标平台选择且只读取一个 leaf。仅把平台作为研究对象、信息来源或业务渠道时不触发多平台成稿分别路由和生成。
| 关键词 | Leaf |
|-----------------|------------------------------------|
| XHS、小红书 | [`xiaohongshu.md`](xiaohongshu.md) |
| 微信、wechat | [`wechat.md`](wechat.md) |
| 邮件、email、e-mail | [`email.md`](email.md) |

View File

@@ -0,0 +1,10 @@
# Genre Router: Report (`router.report`)
用数据、样本或研究形成洞察走本类;按读者任务选择且只读一个 leaf关键词仅用于召回`报告 / 分析 / 研究 / 数据 / 白皮书`单独不决定路由。组织执行 / 批准走 Workplace自主学习走 Knowledge。
| 读者任务 / 关键词、强信号与排除 | Leaf |
|-|-|
| 回答明确研究问题,方法、样本和可推广边界决定可信度;调研报告、访谈 / 问卷 / 用户研究。仅解读既定指标时排除 | [`research-report.md`](research-report.md) |
| 解读已定义指标、趋势、分布、漏斗或实验观察值;数据报告、经营数据、指标复盘。需重新设计样本回答问题时排除 | [`data-report.md`](data-report.md) |
| 让专业读者系统理解并评估问题、框架或方案;白皮书、行业框架、技术 / 政策议题。获客、产品卖点或 CTA 为主时排除 | [`white-paper.md`](white-paper.md) |
| 比较战略、投资、市场、产品或资源选项及成本、收益、风险;商业分析、可行性、进入 / 自建或采购判断。正文要求具名决策者选择 / 批准,或形成授权、资源拨付、执行承诺入口时排除 | [`business-analysis.md`](business-analysis.md) |

View File

@@ -0,0 +1,17 @@
# Genre Router: Workplace (`router.workplace`)
组织内决策、执行、留档走本类;先按读者任务与生命周期选择且只读一个 leaf关键词仅用于召回排除信号优先于同名词。
| 读者任务 / 关键词、强信号与排除 | Leaf |
|-|-|
| 快速知悉、短判断或会前准备;备忘录、决策摘要、会前材料。完整批准论证走 Proposal周期状态走 Weekly | [`memo-brief.md`](memo-brief.md) |
| 按周期判断相对承诺的状态、偏差、风险和下一步;周报、日报、月报、项目状态。原因学习走 Retrospective完整分析走 Report | [`weekly-report.md`](weekly-report.md) |
| 请具名决策者批准方向、预算、资源或执行承诺;提案、立项、资源申请。已定产品行为走 PRD | [`proposal.md`](proposal.md) |
| 将方向已定的一次性项目、变更、专项行动或营销战役转成可协同推进的交付、依赖、里程碑与验收;项目计划、执行方案、实施计划。仍在比较方向或请求批准走 Proposal / Report重复稳定路径走 SOP | [`execution-plan.md`](execution-plan.md) |
| 将已授权的内部规则 / 安排、可复核的检查整改记录或已核定组织立场写成正式载体;制度、公司通知、整改记录、讲话底稿。待批准方向走 Proposal复杂执行走 Execution Plan法定公文走 Official`正式`单独不触发 | [`formal-doc.md`](formal-doc.md) |
| 党政机关法定公文拟制、审校或制发;明确要求公文 / 红头 / 套红 / 正式发文,或法定文种与机关行文关系、文号、主送等制发要素共同出现。`通知 / 报告 / 公告 / 纪要 / 正式 / 官方`单独不触发 | [`official-redhead.md`](official-redhead.md) |
| 记录已发生会议的决定、异议、行动和批准状态;会议记录、行动项。逐字稿不走本 leaf法定公文纪要走 Official | [`meeting-minutes.md`](meeting-minutes.md) |
| 从已结束周期 / 事件提炼证据化学习并改变下一轮;复盘、回顾、经验教训。当前状态走 Weekly活跃未知事故走 Technical | [`retrospective.md`](retrospective.md) |
| 方向已定定义用户问题、范围、产品行为与验收PRD、用户故事、验收标准。是否投入走 Proposal实现取舍走 Technical | [`prd.md`](prd.md) |
| 评审未来技术设计、查询精确契约或调查未知故障RFC、API、架构、事故调查。产品行为走 PRD已定重复路径走 SOP | [`technical-doc.md`](technical-doc.md) |
| 按已批准、可验证路径重复达到终态或为已知事件类别预置响应路径SOP、runbook、值班 / 操作手册、BCP / 处置预案。应急预案若主要发布权威职责走 Formal法定制发走 Official活跃未知事故走 Technical一次学习教程走 Knowledge | [`sop-tutorial.md`](sop-tutorial.md) |

View File

@@ -0,0 +1,41 @@
# Genre Contract: SOP / Runbook (`workplace.sop_tutorial`)
## 体裁规则表(硬约束)
| 规则项 | 规则 |
|-|-|
| presentation_mode / 表达模式 | `normal`;命令式、具体、顺序稳定,一步一动作并紧邻可观察判据,不写无条件的“适当 / 必要时” |
| 内容逻辑 | 先定 routine / controlled / high-risk并识别是否为响应预案再按“版本 → 触发 / 范围 / 终态 → 角色 / 前置 → 动作 / 判据 / 证据 → 异常 / 停止 / 恢复 → 完成记录 / 复审”推进 |
| 事实 / 边界 | owner、版本、环境、资格、权限、工具、命令、阈值、预期结果和恢复路径均须已验证警告在动作前命令成功不等于业务终态流程图 / 示意不能替代可执行步骤、判据与异常路径,须有文字等价;关键未知使可发布稿 `blocked` |
| 错误 | 教程冒充 SOP、未分风险、缺 owner / 版本 / 前置、一条多动作、编造入口 / 阈值 / 权限 / 命令、停止后状态未知、只写“必要时回滚”或未验证终态;响应预案无分级触发、替补指挥、降级路径或解除条件,任一出现即失败 |
## 适用与风险分类
用于组织规定的重复作业、沿已批准路线取得确定终态的 runbook或针对已知事件类别预置并授权的响应 / 业务连续性路径。一次性自助 how-to / 学习走 Knowledge未来设计取舍、活跃未知故障或临场根因调查走 `technical-doc.md`;只建立组织权威、职责或发布要求而不提供现场步骤走 `formal-doc.md`。“教程 / 操作 / 手册 / 应急预案”单词本身不触发。
| 分类 | 增量证明义务 |
|-|-|
| `routine` | 阶段或终态验证、常见异常和升级 |
| `controlled` | 再含审批、接受 / 拒绝、偏差记录、变更复审和代表性试跑 |
| `high-risk` | 再含 precheck、hold point、go / no-go、停止条件以及可执行 rollback / fallback / roll-forward 和恢复验证 |
## 响应预案增量
- 涉及人身安全或法定直报时,其优先级高于业务与财产;按已核风险设置进入、升级、降级和解除条件,明确指挥 / 决策权限、替补角色、首轮动作、信息报送与对外口径边界。联络序列、等待时长和重试次数须预先批准;未知时保留占位,仅放行无需等待授权的安全动作。
- 预设负责人失联、断网断电、主资源不可用等降级场景及可达的安全终态恢复须验证真实业务终态。发布前按风险做桌面推演或代表性演练高风险场景包含故障注入并记录缺口、owner 和复验。
## 文控与证据
写明触发、目标终态、范围、owner / 资格、当前版本 / 环境、前置、权限、工具和输入。命令、参数、阈值、预期输出、备份 / 恢复资产和试跑结果须来自真实环境;流程变更后更新、复审并标 superseded 状态。
关键缺口就近使用`[待环境 owner 验证]`等具体占位。命令、权限、阈值、停止或恢复判据未知时只保留安全只读 precheck不得发布可执行稿`Publish Gate = blocked`
## 步骤、异常与恢复
- 每个关键步骤只写一个动作,紧邻可观察结果、阈值与证据;验证需要操作时另列一步。未知偏差停止于已知安全状态,记录证据并升级。
- high-risk 在不可逆动作前设置 hold point列 go / no-go 信号、决策人和信号缺失时的安全终态。rollback 写触发条件、适用范围、步骤、阈值、停止点和恢复后业务验证,不能只写命令回执。
- 有状态迁移另列不可逆点、写入归属、checkpoint / 幂等,以及完整、无重复、有序或等价验证;关闭 fallback 前必须证明新终态稳定。
## 高质量写法
让具备规定基础资格但不熟流程的人可独立复现;选择条件写在动作前,稳定原理链接出去,不混入原理课或临场诊断。按风险裁剪篇幅但不删证明义务;按适用治理要求由代表性执行者试跑,未经任何实际验证不得发布。

View File

@@ -0,0 +1,38 @@
# Genre Contract: Technical Document / 技术文档 (`workplace.technical_doc`)
## 体裁规则表(硬约束)
| 规则项 | 规则 |
|-|-|
| presentation_mode / 表达模式 | `rich`;精确、可证伪、术语与版本稳定;在有明确内容作用时用代码、表格、架构 / 状态 / 时序图和其他 rich block 降低实现与诊断成本,但不让视觉组件替代契约、证据或操作说明,规范词仅在明确采用的互操作 / 安全 / 验收语义中使用 |
| 内容逻辑 | 必须且只能选 design_rfc、api_reference、incident_diagnostic 一种主模式;分别按“证据 → 取舍 / 设计 → 验收”“契约 → 错误 / 兼容”“影响 → 假设 / 检查 → 验证 / 升级”推进 |
| 事实 / 边界 | 标对象、环境、版本、时间、范围和证据窗;事实、推断、决定、未知分开;示例 / 图不替代契约;任何改状态动作须有授权、影响、停止、还原和恢复验证,关键缺口按 reader impact 处理 |
| 错误 | 按关键词路由、三模式混写、设计无取舍 / 验收、reference 漏权限 / 错误 / 生命周期 / 兼容、未知故障直接定根因、改状态无授权 / 停止 / 还原或图作唯一证据,任一出现即失败 |
## 先选唯一主模式
| 主模式 | 读者任务 | 排除 |
|-|-|-|
| `design_rfc` | 评审者能批准并实现未来技术状态,理解替代、后果和验收 | 产品可观察行为走 PRD既定路径走 SOP |
| `api_reference` | 调用者无需猜版本、权限、输入、行为、副作用、错误与生命周期 | 仍在讨论接口取舍时走 design_rfc |
| `incident_diagnostic` | 响应者以安全、有区分度的动作缩小未知、止损、恢复或升级 | 单纯团队学习走 Retrospective已知重复处置走 SOP |
## 共同证据边界
标明对象、环境、版本、时间、范围 / 前置和证据位置 / 窗口结论回链仓库、IDL / schema、日志、metrics、traces、变更记录或验证实验。缺口就近使用具体占位、收窄或 `blocked`数据分级、访问、保留、重放、owner、时限和升级只在适用时形成门禁。
代码与命令示例须实际验证并标环境 / 版本;架构、状态或时序图必须附文字等价,不能成为唯一证据或唯一操作说明。
## Design RFC
按问题证据 → 目标 / 非目标 → 约束 / 不变量 → 真实备选与同口径取舍 → 接口 / 数据 / 状态设计 → 失败、安全、兼容与迁移 → 上线 / rollback → 可观测性、测试 / 验收 → 未决决定推进。每项关键决定写 why、被否方案及后果不得隐藏低置信度或版本偏差。
## API Reference
写清版本 / 环境 / 权限 / 签名、输入约束、行为 / 副作用 / 幂等、输出、已知错误及可操作恢复、限流 / 分页 / 重试、兼容 / 弃用。事件、异步、CLI、SDK、流式按需补 channel / message、交付 / 顺序、生命周期 / 耗尽、I/O、取消与背压未知语义明确 unspecified不从示例推断承诺。
## Incident Diagnostic
按影响与 expected / actual → 当前状态与证据链 → 可证伪假设 → 信息增益高且副作用低的检查 → 止损 / 恢复验证 → 升级与后续 RCA 推进。每项检查写预期观察及其支持 / 排除的假设。
修改状态前必须确认授权、目标范围、潜在副作用、停止条件、还原路径和恢复判据分开止损、根因与永久修复。缺证据、授权、owner、还原或升级路径时只给安全只读检查并 `blocked`;涉及安全 / 法务时先保全证据和升级。

Some files were not shown because too many files have changed in this diff Show More