Commit graph

5 commits

Author SHA1 Message Date
Yucong Sun
86d13cdb83
reference loops: docs, runtime cycle efuns, orphan collector, copy() unwind fix (#1276)
A complete treatment of reference loops (cyclic data structures) in LPC:
the reference-counting VM has no cycle collector, so a value that reaches
itself leaks permanently -- and silently -- once the last outside
reference is dropped, and it cannot be saved, deep-copied, or fully
printed in the meantime. This change documents the problem, fixes a
driver memory-safety bug it exposes, and adds runtime tooling to detect,
locate, break, and (on debug builds) collect such loops.

Driver fixes:

- copy() on a cyclic structure always hits the MAX_SAVE_SVALUE_DEPTH
  error(), and that unwind path leaked every partially-built container --
  allocated with the _empty_ (uninitialized-svalue) allocators and holding
  a borrowed, un-ref-counted pointer to the ORIGINAL value, which the
  Debug memory checker then read after free (heap-use-after-free abort
  under ASan, reproducible with just catch(copy(a)) on a[0] = a).
  deep_copy_* now allocate zero-filled, hold the destination in a
  unique_ptr whose deleter is the tag-symmetric free_*, and only write the
  destination slot after the child copy fully succeeded (ffi.cc precedent,
  AGENTS.md section 4).
- save_object/save_variable and copy()'s 'nested too deep' errors -- the
  classic symptom of a loop -- now say so (the has_cycle() pointer is
  gated on PACKAGE_CONTRIB so core never recommends an efun the build
  lacks).

New efuns (contrib package, src/packages/contrib/cycles.cc):

- has_cycle(mixed): 1 if the value's reference graph contains a loop.
- find_cycles(mixed): one index-path string per loop-closing slot
  ("[3][\"peer\"].1" style).
- break_cycles(mixed): clears every loop in place and returns the number
  of edges broken. Exactly the DFS back-edges are touched (a digraph is
  acyclic iff its DFS has no back-edges): item/value slots are zeroed, a
  loop closed in mapping-KEY position has its node deleted (hashed keys
  cannot be overwritten), and a loop closing on the funptr->args edge
  itself -- possible because bind() SHARES the args array between the old
  and new funptr -- detaches the bound funptr's args list and replaces it
  with a zero-filled one of the same size. DAG sharing is never touched;
  one cut un-loops a whole ring; afterwards the value saves, copies,
  prints, and frees normally.

  All three share one ITERATIVE walk (explicit heap stack, white/grey/
  black coloring): no C-stack recursion, no depth cap -- arbitrarily deep
  acyclic values scan cleanly where save_variable() errors. Edges:
  array/class items, mapping keys AND values, fp->hdr.args; objects are
  deliberately leaves (loops through object variables are the
  destruct()-managed kind: destruct2() zeroes the variable block).
  break_cycles() records fixes during a mutation-free walk and applies
  them in a post-pass that holds a reference on every touched container,
  zeroes slots before deleting nodes (only node deletion can cascade
  frees), and releases the holds last -- order-independent and safe
  against shared/overlapping fixes.

Orphaned-loop collector (develop package, Debug/DEBUGMALLOC_EXTENSIONS):

- find_orphaned_cycles(int collect): finds -- and with any nonzero
  argument reclaims -- data blocks that are unreachable because only a
  reference loop keeps them alive: the case nothing LPC-level can reach
  anymore. Detection is trial deletion (CPython-gc-style), implemented in
  md_scan_orphaned_cycles (checkmemory.cc): count each array/class/
  mapping/funptr's references held by OTHER data blocks; a block whose
  real ref count exceeds that is externally held (object variables, VM
  stack, call_out, any C++-side holder) and seeds liveness, which
  propagates along data edges; the remainder is loop garbage. No root
  enumeration to get wrong -- every legitimate holder shows up as an
  external ref. Collection: hold a ref on every dead block, sever all
  their child slots (releasing strings/objects/buffers/live values
  normally), then release the holds -- each dead block deallocates with
  nothing left to cascade into.
- check_all_blocks() runs the same scan (skippable via new flag bit 2,
  value 4) and reports 'unreachable data block(s) kept alive only by
  reference loop(s)', so the testsuite's per-file check_memory() gate
  turns a dropped cycle into a hard, attributed failure. That immediately
  caught a real pre-existing leak: tests/std/json.lpc's
  test_encode_circular_references() dropped all four of its
  deliberately-cyclic fixtures on every suite run since it was written.

Tests (testsuite/single/tests/):

- operators/reference_loop.lpc pins the driver contract around loops and
  crashes the unfixed Debug/ASan driver (the copy() unwind UAF).
- efuns/has_cycle.lpc, find_cycles.lpc, break_cycles.lpc cover self/
  mutual/ring loops across arrays, mappings (value and key position),
  classes, funptr args (including the bind()-shared-args case, which was
  unbreakable in an earlier revision of this change), DAG-sharing
  preservation, save/copy working again after a break, idempotency, and a
  5000-deep acyclic walk.
- efuns/find_orphaned_cycles.lpc pins baseline-relative detection of 6
  orphans across three dropped loop shapes, idempotent detection, that
  reachable loops are never classified as garbage, and that collection
  reclaims everything while reachable data survives.
- Every cycle-building test has UNCONDITIONAL teardown (body in catch(),
  find_orphaned_cycles(1) regardless, error re-raised) so a mid-test
  regression stays one [ FAILED ] entry instead of cascading the
  harness's LEAK gate into a suite-wide abort (AGENTS.md section 7).

Docs (Docusaurus, sidebar regenerated; full two-locale build verified):

- new concepts page docs/concepts/general/reference_loops.md: why loops
  leak, what each recursive consumer does, the destruct() exception,
  prevention patterns, the runtime tools, and the debug-build collector;
- efun pages for all four new efuns; check_memory.md documents the new
  scan and flag bit.

Validated on Debug+ASan/UBSan (full LPC suite, randomized order, multiple
runs) and RelWithDebInfo (full suite), 313 GTest unit tests, plus an
8-angle adversarially-verified self-review.

Round-2 self-review (4 fresh angles, adversarially verified) additionally:
- break_cycles() post-pass releases its held container references via an
  RAII guard: allocate_array() there can error() (set_config() can shrink
  __MAX_ARRAY_SIZE__ at runtime below a shared args array's size), and the
  old trailing release loop would have leaked every held ref on that
  unwind (AGENTS.md section 4).
- documented the pre-existing map_delete()-class caveat: deleting a
  key-closed loop's node while an outer unlocked foreach-ref variable is
  aimed at it dangles that variable (not specific to this efun; noted in
  code and doc).
- extended orphan-collector coverage from 6 to 10 blocks: class rings
  (TAG_CLASS candidate/sever/free_class paths), mapping pairs closed in
  KEY position (the collector's in-place key-zeroing sever path), and a
  buffer payload riding an orphaned ring (sever must release it or the
  Debug ref gate trips); added a destructed-object-in-walked-value test
  (render_key + leaf handling).
- docs: refs.md and copy.md now link back to the cycle tooling; zh-CN
  sidebar translation keys rescaffolded; AGENTS.md section 7 documents the
  new hard gate and the catch + find_orphaned_cycles(1) teardown pattern.
- re-entrancy audit (foreach/MAP_LOCKED/locked_map_nodes/merge_arg_lists)
  and LPC-test-semantics audit returned no code defects.


Claude-Session: https://claude.ai/code/session_01VaksxbPjc3hjzghoQPUHRo

Co-authored-by: Claude <noreply@anthropic.com>
2026-07-16 00:06:37 -07:00
Yucong Sun
4a9b2ed2d0
docs: rewrite FFI reference around buffer features, add worked libc examples (#1275)
* docs: rewrite FFI reference around buffer features, add worked libc examples

Update docs/driver/ffi-plan.md now that buffers carry the full byte
toolkit (string/int-array promotion, byte lvalues, range assignment,
foreach, concatenation):

- New "The buffer type does the heavy lifting" section mapping each
  buffer language feature to its FFI use.
- The C-string idiom is now the two-line promotion form
  (buffer b = s; b += ({ 0 })) instead of chained string_encode()
  calls; string_encode stays documented for non-UTF-8 encodings, and
  the doc notes that promotion never reaches inside ffi_call's args
  array (the byte boundary stays explicit).
- New "Worked examples -- calling libc" section: scalars (sqrt/pow/abs),
  strings in (strlen, incl. range assignment into an allocation),
  strings out (getenv + ffi_peek(addr, -1) + string_decode with a NULL
  check), out-parameters (frexp), structs (time/localtime via
  ffi_struct_layout), callbacks (qsort with an LPC comparator), and
  foreach over peeked bytes.
- Sync the reference with the implementation: add ffi_address() (was
  missing from the efun listing), correct ffi_free() (zeroes bytes; GC
  reclaims), ffi_peek(-1) (NUL-terminated read capped at the max
  buffer size config), FFI_POINTER args accepting int addresses
  (0 = NULL), pointer returns always being int addresses, the
  FFI_INT/FFI_LONG aliases, ffi_load("") semantics, the valid_ffi
  operation names with a sample master implementation, and the real
  build default (PACKAGE_FFI ships ON; runtime denies without a
  valid_ffi apply; WASM forces it off).

Every snippet is pinned verbatim by a new testsuite file,
testsuite/single/tests/efuns/ffi_doc_examples.lpc (guarded by
__PACKAGE_FFI__ and the ffi_probe availability fixture like the other
ffi tests). Verified: RelWithDebInfo build, ffi glob (21 files) and the
full LPC suite (600 files) pass.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SooGWcJbSWszCZ67k4iVQT

* docs: add a local build quickstart to AGENTS.md

Record the verified Debian/Ubuntu setup so future agents don't
rediscover it one configure failure at a time: the full apt package
list (CI's packages: lines assume a GitHub runner image that
preinstalls cmake/ninja/libicu-dev), the configure/build commands, the
build/src/driver binary path, -DPACKAGE_DB=OFF as the escape hatch
when no MySQL client dev package is available, that libevent is
vendored and GTest optional, and how to run the LPC suite without a
pipe masking the driver's exit status.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SooGWcJbSWszCZ67k4iVQT

* docs: rename driver/ffi-plan.md to driver/ffi.md

The page stopped being a plan and is the package reference; name it
accordingly (site URL /driver/ffi/, sidebar label "FFI Package").
Update every reference: source comments (ffi.spec, ffi.cc, both
include/ffi.h copies), tools/ffi (README, generate.py's module
docstring and the two comment lines it emits into generated bindings,
with the committed ffi_genmath.lpc fixture updated to match), the
testsuite doc-examples pin, sidebar_meta.json + regenerated
sidebars.generated.json, and the zh-CN sidebar-label key.

Note: the old /driver/ffi-plan/ URL is not redirected (the site has no
client-redirects plugin configured).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SooGWcJbSWszCZ67k4iVQT

* ffi: gate ffi_peek through valid_ffi("peek")

ffi_peek(address, nbytes) copies bytes from an arbitrary native
address, which makes it a process-memory disclosure primitive on its
own (and a driver crash on an unmapped address) -- yet it was the one
dangerous efun in the package not gated by valid_ffi, so any object
could call it whenever PACKAGE_FFI was compiled in, even under a
deny-all master. The other ungated efuns operate only on LPC-owned
buffers and handles (ffi_address reveals a buffer's own address, inert
without a peek/call grant) and stay ungated.

f_ffi_peek now calls check_valid_ffi("peek", address) before touching
any memory, exactly like load/symbol/prepare/callback. The testsuite
master denies a -0xDEAD sentinel address so the denial path is
testable without dereferencing anything; ffi_peek.lpc pins the exact
error. Docs updated: valid_ffi(4), ffi_peek(3), and the op list +
sample master in docs/driver/ffi.md.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SooGWcJbSWszCZ67k4iVQT

* stdlib: add /std/ffi_util, FFI-boundary helpers for package_ffi callers

A pure-LPC library packaging the recurring idioms at the C boundary so
binding code stops re-deriving them:

- cstr(s) / cstr_enc(s, enc): NUL-terminated C strings (buffer
  promotion for UTF-8, string_encode for other byte encodings)
- c_string(addr) / c_string_enc(addr, enc): read a returned char*,
  with the NULL -> 0 convention folded in
- c_out(type_code): a zeroed out-parameter block for T*
- c_argv(strings): a NULL-terminated char*[] plus the kept-alive
  per-string buffers (the lifetime footgun a library should own)
- c_field / c_field_set: struct-field access over ffi_struct_layout()
  layouts

Deliberately consumed via `inherit "/std/ffi_util"` rather than the
simul_efun object: c_string() calls ffi_peek(), gated by
valid_ffi("peek", addr, caller), and inheriting keeps the consuming
object as the security principal the master sees. The docs page
(docs/stdlib/ffi_util, "FFI Utilities" in the sidebar) spells this out.

Tests: testsuite/single/tests/std/ffi_util.lpc exercises every helper
against libc (strlen with both encodings, getenv through c_string,
frexp through c_out, strtol's char **endptr through
c_out(FFI_POINTER), and structural checks on c_argv's pointer array).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SooGWcJbSWszCZ67k4iVQT

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-07-15 22:09:25 -07:00
Yucong Sun
814c4fa5b9
vm: string foreach/ref fixes, buffers as byte arrays (foreach, strict bytes, to_buffer), thorough ref tests; #1196 docs follow-up (#1250)
* docs/tests: fix constructs index regression from #1196; add ref page to sidebar; extend & ref tests

- Restore extension-less links and the text_blocks entry in
  docs/lpc/constructs/index.md (the PR was recreated from a pre-Docusaurus
  branch and reintroduced .html links, which fail the docs build under
  onBrokenLinks: 'throw', and dropped text_blocks)
- Add lpc/constructs/ref to the hand-authored sidebar in docs/sidebars.ts
- Drop the stale VitePress 'layout: doc' frontmatter from ref.md
- Extend testsuite/single/tests/operators/ref.lpc: & in parameter
  declarations, ref keyword in foreach, and bitwise &/&= non-regression

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Skf9CfHwAngWorDNDzPKWp

* vm: fix string foreach crash and off-by-one ref reads; support += / -= on string chars

Three related defects around the shared string-codepoint lvalue
(global_lvalue_codepoint), all reproduced on the unfixed binary:

- Nested foreach over strings SEGFAULTED: the iteration cursor lived in
  the shared global, so the inner loop's F_EXIT_FOREACH reset the
  iterator out from under the outer loop (null deref in
  post_index_to_offset). The EGC cursor now lives in each loop's own
  stack slot (the T_NUMBER slot under the loop variable); the ref case
  re-arms the shared codepoint lvalue every iteration, and exit only
  clears the global when it still points at this loop's string slot.

- foreach (int ref c in str) read the WRONG characters: the shared
  index was advanced before the body ran, so every read through the ref
  was off by one ('abc' summed to 197 instead of 294, and the final
  iteration read one past the end). The global index now stays on the
  current character for the whole body. Writes through the ref still go
  to the loop's by-value stack copy and never reach the iterated
  variable -- semantics pinned by tests/operators/foreach.lpc.

- s[i] += n / s[i] -= n threw "Bad Argument 1 to +=()": F_ADD_EQ and
  f_sub_eq handled buffer byte lvalues (T_LVALUE_BYTE) but not string
  codepoint lvalues (T_LVALUE_CODEPOINT), even though ++/--/= worked.
  Both now route through a new codepoint_lvalue_add() helper and produce
  the resulting character as the rvalue.

Regression tests: nested (plain / ref / multi-byte UTF-8) string foreach
and ref-read correctness in tests/operators/foreach.lpc; compound
assignment on string chars (incl. reverse index, rvalue result, and
non-number rhs error) in tests/operators/string_index.lpc. Verified on
the unfixed binary: the nested-foreach test segfaults, the others fail.
Full LPC suite passes 2x on clang ASan/UBSan Debug and 2x on
RelWithDebInfo.

Docs: correct the ref.md note on foreach-over-strings; document the
string-char lvalue rules in AGENTS.md (section 8 + audit checklist 9)
and the ref/& feature in README.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Skf9CfHwAngWorDNDzPKWp

* vm: foreach ref over strings shares the s[i] char-lvalue logic; thorough ref tests

Arming a string-char lvalue now goes through one shared helper,
aim_lvalue_codepoint(): it validates the target EGC (out-of-bounds and
multi-codepoint error cleanly, same messages as s[i]) and points the
shared codepoint state at it. Both s[i] lvalues (push_indexed_lvalue)
and foreach ref loop variables use it, and every write consumer already
funnels into assign_lvalue_codepoint() -- so ref loop chars follow
exactly the s[i] rules:

- single-codepoint characters (and EGCs up to 4 bytes, which index as
  their first codepoint) keep working: reads deliver the character,
  assignments through the loop variable succeed
- wider EGCs (flag emoji, ZWJ sequences) now raise the catchable
  "Indexed character is multi-codepoint" error when the ref loop
  reaches them, instead of silently reading as -1; the non-ref form
  still iterates and delivers -1 for such clusters

tests/operators/ref.lpc is now a thorough pass-by-reference suite:
ref/& parameter declarations and call arguments, by-value contrast,
ref forwarding through call chains, call-site refs to array elements /
mapping values / string chars (forward and reverse index, write-back),
foreach ref over arrays / mapping values / strings (read correctness,
multi-byte codepoints, by-value write semantics, assignment error
parity, the multi-codepoint error, non-ref contrast), compile-time
rejections via generated sources (ref outside an argument list, ref to
a range), and bitwise &/&= non-regression -- 39 checks.

Full LPC suite passes 2x on RelWithDebInfo and 2x on a clean clang
ASan/UBSan Debug build.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Skf9CfHwAngWorDNDzPKWp

* tests: cover ref across all LPC types

Extend tests/operators/ref.lpc to 58 checks: ref parameters of every
value type (int, float, string, array, mapping, object, function,
buffer, class, mixed) verifying reassignment propagates; the by-value
contrast for reference-typed containers (member writes propagate,
reassignment doesn't); call-site refs to buffer bytes (forward and
reverse index) and class members (both . and -> spellings); foreach
ref over mapping values of mixed types; the compile-time rejection of
a ref mapping KEY in foreach; and the clean runtime error for foreach
over a non-iterable type (buffer).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Skf9CfHwAngWorDNDzPKWp

* buffers behave like byte arrays: foreach, strict 0..255 bytes, string/array promotion, to_buffer()

Buffers are now first-class byte containers:

- foreach iterates a buffer like an array, delivering each byte as an
  unsigned int 0..255. A ref loop variable mutates the buffer in place;
  each ref carries its OWN T_LVALUE_BYTE (in ref->sv), so nested buffer
  ref loops and b[i] lvalues in the body can't alias each other.
  T_LVALUE_BYTE consumers now read the lvalue's own pointer/subtype
  instead of reaching for the shared global_lvalue_byte (which remains
  only as the scratch instance b[i] arms).

- every LPC byte write path (=, ++, --, +=, -=) range-checks the result:
  a value outside 0..255 raises "Buffer byte value out of range" and
  leaves the byte unchanged, instead of silently truncating/wrapping.
  += / -= on bytes also yield the resulting value as their rvalue.

- strings and arrays of ints 0..255 PROMOTE to buffers: a new
  to_buffer() efun (registered like to_int/to_float) is wrapped around
  the rhs by do_promotions() / rule_expr_assign for 'buffer b = str',
  'b += str', initializers, and 'b + str'; range assignment and the
  runtime + / += paths convert unpromoted (mixed) values through the
  same svalue_to_buffer_bytes() helper. A string contributes its raw
  UTF-8 bytes; an array must hold only ints 0..255 (validated before
  allocation) or the conversion errors with the target unchanged.

- fixed a pre-existing ref_t leak: a foreach ref loop variable reused by
  a re-entered inner loop leaked one ref per outer iteration (flagged by
  the debug memory checker as 'Found temporary block: make_ref').

tests/operators/buffer_bytes.lpc pins the byte-range semantics, + / +=
concatenation, all promotion forms, and the error paths (106 checks);
foreach.lpc and ref.lpc pin buffer iteration and ref-loop independence;
buffer_range_assign.lpc gains range-read pins. New docs for to_buffer
(sidebar regenerated) and a rewritten lpc/types/buffer page.

Full LPC suite passes 2x on RelWithDebInfo and 2x on a clean clang
ASan/UBSan Debug build (no ref-checker warnings); GTest suite 312/312.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Skf9CfHwAngWorDNDzPKWp

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-07-12 01:39:30 -04:00
gesslar
1ad5953549
docs: validate "See Also" references, drop dead ones, document valid_ffi (#1251)
* empty

* docs: validate "See Also" references, drop dead ones, document valid_ffi

Reviewed the "See Also" section of every doc and dropped man-page
cross-references whose target page does not exist (verified against the
driver source, not just the docs tree):

  - errorp, each, opcprof, dump_socket_status, extract, shadowp,
    destruct_env_of, move, inventory_visible, inventory_accessible

These name efuns/applies that no longer exist in FluffOS. keys/values now
point at the `for` construct in place of the defunct `each` efun.

valid_ffi was the one "referenced but undocumented" case: it is a real
master apply (APPLY_VALID_FFI) gating every ffi_load/symbol/prepare/
callback, so it gets a proper apply page rather than having its references
removed. Sidebar regenerated to include it.

The 13 modern markdown-link "See Also" sections were already clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-12 01:09:17 -04:00
Yucong Sun
89060c5a6b
docs: fully-expandable generated sidebar + Chinese docs via Docusaurus i18n (#1246)
* docs: fully-expandable generated sidebar, replacing index.md link pages

Rework docs navigation so the sidebar expands to every page of every
reference tree, instead of terminating at generated index.md link lists:

- New docs/gen_sidebar.py (replaces gen_index.py + update_index.sh):
  walks efun/, apply/, stdlib/, concepts/, driver/, cli/ and zh-CN/ and
  emits sidebars.generated.json — a full Docusaurus category tree per
  directory. Category landing pages are now `generated-index` card pages
  (title/description/slug), so all generated index.md files are deleted.
  --check mode verifies freshness; new .github/workflows/docs-sidebar.yml
  runs it in CI.
- New docs/sidebar_meta.json holds curated presentation: category labels,
  one-line descriptions (shown on the landing cards), explicit ordering
  (driver/cli/concepts read top-down from user-facing to internals) and
  per-page label overrides.
- sidebars.ts becomes a hand-authored skeleton (Getting Started, lpc/,
  Historical) that splices in the generated trees.

Content reorganization (from a docs-wide review):
- Move misplaced efun pages out of efun/general: terminal/protocol efuns
  (act_mxp, send_zmp, request_term_*) to interactive/, debugging efuns
  (check_memory, dump_*, clear_debug_level, destructed_objects) to
  internals/, shallow_inherit_list to system/.
- Delete stub duplicates superseded by complete pages elsewhere:
  general/parse_{add_synonym,dump,my_rules,remove}, contrib/{shuffle,
  element_of}.

Modernize key pages with MDX:
- index.mdx: landing page with a card grid linking each doc section.
- build.mdx: per-platform <Tabs> (Ubuntu/macOS/Windows/Alpine+Docker),
  admonitions, VitePress [[toc]] leftover removed, stale per-platform CI
  workflow links updated to the unified ci.yml.
- ffi-plan.md: GitHub-style [!CAUTION] alert converted to an admonition.

`npm run build` passes clean (onBrokenLinks: throw, no warnings).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0174GM2azvAHBmvyESwxm5om

* docs: serve the Chinese corpus through Docusaurus i18n

Move the zh-CN/ directory out of the default docs tree and into a proper
Docusaurus locale (i18n/zh-CN/docusaurus-plugin-content-docs/current/):

- The flat zh-CN/efun/ directory (333 pages) is re-homed to mirror the
  categorized English layout (name-matched 1:1; `hash` maps to strings/
  per its own frontmatter). apply/ pages map 1:1; the stray English-text
  zh-CN/apply/master/view_errors.md documents a MudOS-era apply that no
  longer exists in the driver and is dropped; stdlib/db/database_zh.md
  becomes the i18n translation of stdlib/db/database.md; the Chinese
  build guide becomes the translation of build.mdx.
- Untranslated pages automatically fall back to English content under
  /zh-CN/, so the whole site is navigable in either locale from the new
  navbar locale dropdown.
- Both locales share one sidebar. Generated sidebar items now carry
  stable `key` fields (the directory/doc path) so translation keys are
  unique (both efun/ and stdlib/ have an "Arrays" category, crypto and
  strings both document `hash`). Category labels, generated-index
  titles/descriptions, navbar and footer are translated in
  i18n/zh-CN/...; theme UI strings come from Docusaurus' bundled
  zh-Hans translations. Translated landing page at /zh-CN/.
- The "中文文档" sidebar section, the zh-CN tree in gen_sidebar.py /
  sidebar_meta.json, and its slice of sidebars.generated.json are gone.
- Relative .md-file links on pages that render in both locales break
  the localized build (the file->permalink map points at the localized
  copy), so concepts/, the two socket_*_option pages and the config.md
  generator now emit extension-less route links instead.
- zh interactive.md/objects.md get explicit slugs like their English
  counterparts (a doc named after its parent directory is otherwise a
  Docusaurus category-index doc, colliding with the generated-index
  route).

`npm run build` builds both locales clean (onBrokenLinks: throw).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0174GM2azvAHBmvyESwxm5om

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-07-11 17:20:25 -04:00