Compare commits
45 commits
engine/kok
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 172b3c23d9 | |||
| 07ea1149c3 | |||
| 55ccd7a974 | |||
| e19319958e | |||
| 020fb7517b | |||
| 0bd4e7bd19 | |||
| c0f75c1365 | |||
| 9c7c950842 | |||
| b3610c87ab | |||
| 686b0359ad | |||
| 004f682b50 | |||
| 29dd84c946 | |||
| f826346934 | |||
| f46ca5c159 | |||
| a23705c882 | |||
| 812a99e99c | |||
| 856a2a4a5c | |||
| 2f0de58dd0 | |||
| 92a155dc85 | |||
| 43368c0c45 | |||
| 43e2895018 | |||
| a51373dbae | |||
|
|
d645cbc8ed | ||
| 3fa9f181ac | |||
| 3d7d4a6de0 | |||
|
|
d5dd66df0b | ||
|
|
799a703648 | ||
|
|
320fc26cc8 | ||
|
|
35b44fc828 | ||
| 76914a50f7 | |||
| 80152e0373 | |||
| d02d1bef9f | |||
| c7b92d1c06 | |||
|
|
7932e53a45 | ||
|
|
564233cbff | ||
|
|
566ca05ea8 | ||
|
|
8dde7afeda | ||
|
|
8bf4137687 | ||
|
|
f963c6cf03 | ||
|
|
bc03f52c3e | ||
|
|
f70cfe1f0b | ||
|
|
61f1bdd40a | ||
|
|
c863543580 | ||
|
|
b5576f4ec5 | ||
|
|
1e7905d1e1 |
34 changed files with 2503 additions and 369 deletions
40
.forgejo/workflows/gitleaks.yml
Normal file
40
.forgejo/workflows/gitleaks.yml
Normal file
|
|
@ -0,0 +1,40 @@
|
||||||
|
# .forgejo/workflows/gitleaks.yml
|
||||||
|
#
|
||||||
|
# Sulkta canonical gitleaks workflow. Drop a copy into every public repo at
|
||||||
|
# `.forgejo/workflows/gitleaks.yml` after the Forgejo act_runner is registered
|
||||||
|
# (task #295).
|
||||||
|
#
|
||||||
|
# Pairs with the pre-receive hook installed on every bare repo — that one is
|
||||||
|
# the strict enforcement layer (rejects the push); this one provides the
|
||||||
|
# per-PR red ✗ that branch-protection rules can require before merge.
|
||||||
|
#
|
||||||
|
# Layer 1 (this workflow): visible per-PR status, can be a required check.
|
||||||
|
# Layer 2 (pre-receive hook): strict enforcement at the server.
|
||||||
|
# Layer 3 (johnny5 cron sweep): nightly full-history sweep across all repos.
|
||||||
|
|
||||||
|
name: gitleaks
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
pull_request:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
scan:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
# Full history — gitleaks needs depth to scan a commit range.
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- name: install gitleaks
|
||||||
|
run: |
|
||||||
|
curl -sSL -o gl.tar.gz \
|
||||||
|
https://github.com/gitleaks/gitleaks/releases/download/v8.21.2/gitleaks_8.21.2_linux_x64.tar.gz
|
||||||
|
tar xzf gl.tar.gz gitleaks
|
||||||
|
chmod +x gitleaks
|
||||||
|
./gitleaks version
|
||||||
|
|
||||||
|
- name: scan
|
||||||
|
run: |
|
||||||
|
./gitleaks detect --source . --no-banner --redact --verbose
|
||||||
142
Cargo.lock
generated
142
Cargo.lock
generated
|
|
@ -78,9 +78,9 @@ dependencies = [
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "anyhow"
|
name = "anyhow"
|
||||||
version = "1.0.102"
|
version = "1.0.104"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c"
|
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "assert-json-diff"
|
name = "assert-json-diff"
|
||||||
|
|
@ -237,9 +237,9 @@ checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "chrono"
|
name = "chrono"
|
||||||
version = "0.4.44"
|
version = "0.4.45"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "c673075a2e0e5f4a1dde27ce9dee1ea4558c7ffe648f576438a20ca1d2acc4b0"
|
checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"iana-time-zone",
|
"iana-time-zone",
|
||||||
"js-sys",
|
"js-sys",
|
||||||
|
|
@ -251,9 +251,9 @@ dependencies = [
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "clap"
|
name = "clap"
|
||||||
version = "4.6.1"
|
version = "4.6.6"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51"
|
checksum = "473c7e07f409a8d772161724aa8db6a765a2532a70f9667eeb7b49d3d02fbdca"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"clap_builder",
|
"clap_builder",
|
||||||
"clap_derive",
|
"clap_derive",
|
||||||
|
|
@ -261,9 +261,9 @@ dependencies = [
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "clap_builder"
|
name = "clap_builder"
|
||||||
version = "4.6.0"
|
version = "4.6.6"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f"
|
checksum = "7b48fea5a88e9ae728a2dcbedbfc0e730f7d60da42e1cb049a83c9fb8b789889"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anstream",
|
"anstream",
|
||||||
"anstyle",
|
"anstyle",
|
||||||
|
|
@ -273,14 +273,14 @@ dependencies = [
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "clap_derive"
|
name = "clap_derive"
|
||||||
version = "4.6.1"
|
version = "4.6.4"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "f2ce8604710f6733aa641a2b3731eaa1e8b3d9973d5e3565da11800813f997a9"
|
checksum = "d012d2b9d65aca7f18f4d9878a045bc17899bba951561ba5ec3c2ba1eed9a061"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"heck",
|
"heck",
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
"quote",
|
"quote",
|
||||||
"syn",
|
"syn 3.0.3",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|
@ -431,7 +431,7 @@ checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
"quote",
|
"quote",
|
||||||
"syn",
|
"syn 2.0.117",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|
@ -462,7 +462,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"libc",
|
"libc",
|
||||||
"windows-sys 0.61.2",
|
"windows-sys 0.52.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|
@ -598,7 +598,7 @@ checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
"quote",
|
"quote",
|
||||||
"syn",
|
"syn 2.0.117",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|
@ -1173,7 +1173,7 @@ dependencies = [
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
"proc-macro2-diagnostics",
|
"proc-macro2-diagnostics",
|
||||||
"quote",
|
"quote",
|
||||||
"syn",
|
"syn 2.0.117",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|
@ -1404,7 +1404,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"
|
checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
"syn",
|
"syn 2.0.117",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|
@ -1424,7 +1424,7 @@ checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
"quote",
|
"quote",
|
||||||
"syn",
|
"syn 2.0.117",
|
||||||
"version_check",
|
"version_check",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
@ -1442,7 +1442,7 @@ dependencies = [
|
||||||
"rustc-hash",
|
"rustc-hash",
|
||||||
"rustls",
|
"rustls",
|
||||||
"socket2",
|
"socket2",
|
||||||
"thiserror 2.0.18",
|
"thiserror 2.0.20",
|
||||||
"tokio",
|
"tokio",
|
||||||
"tracing",
|
"tracing",
|
||||||
"web-time",
|
"web-time",
|
||||||
|
|
@ -1463,7 +1463,7 @@ dependencies = [
|
||||||
"rustls",
|
"rustls",
|
||||||
"rustls-pki-types",
|
"rustls-pki-types",
|
||||||
"slab",
|
"slab",
|
||||||
"thiserror 2.0.18",
|
"thiserror 2.0.20",
|
||||||
"tinyvec",
|
"tinyvec",
|
||||||
"tracing",
|
"tracing",
|
||||||
"web-time",
|
"web-time",
|
||||||
|
|
@ -1583,9 +1583,9 @@ dependencies = [
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "regex"
|
name = "regex"
|
||||||
version = "1.12.3"
|
version = "1.12.4"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276"
|
checksum = "f1292b7759ae1cb9ec195452d1390a074f0cd8541ab7a5a8c31cd6db45d4a6ba"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"aho-corasick",
|
"aho-corasick",
|
||||||
"memchr",
|
"memchr",
|
||||||
|
|
@ -1606,9 +1606,9 @@ dependencies = [
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "regex-syntax"
|
name = "regex-syntax"
|
||||||
version = "0.8.10"
|
version = "0.8.11"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a"
|
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "reqwest"
|
name = "reqwest"
|
||||||
|
|
@ -1702,7 +1702,7 @@ dependencies = [
|
||||||
"errno",
|
"errno",
|
||||||
"libc",
|
"libc",
|
||||||
"linux-raw-sys",
|
"linux-raw-sys",
|
||||||
"windows-sys 0.61.2",
|
"windows-sys 0.52.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|
@ -1766,9 +1766,9 @@ checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "serde"
|
name = "serde"
|
||||||
version = "1.0.228"
|
version = "1.0.229"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
|
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"serde_core",
|
"serde_core",
|
||||||
"serde_derive",
|
"serde_derive",
|
||||||
|
|
@ -1776,29 +1776,29 @@ dependencies = [
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "serde_core"
|
name = "serde_core"
|
||||||
version = "1.0.228"
|
version = "1.0.229"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
|
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"serde_derive",
|
"serde_derive",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "serde_derive"
|
name = "serde_derive"
|
||||||
version = "1.0.228"
|
version = "1.0.229"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
|
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
"quote",
|
"quote",
|
||||||
"syn",
|
"syn 3.0.3",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "serde_json"
|
name = "serde_json"
|
||||||
version = "1.0.149"
|
version = "1.0.151"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86"
|
checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"itoa",
|
"itoa",
|
||||||
"memchr",
|
"memchr",
|
||||||
|
|
@ -1920,7 +1920,7 @@ dependencies = [
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"sqlx",
|
"sqlx",
|
||||||
"thiserror 2.0.18",
|
"thiserror 2.0.20",
|
||||||
"tokio",
|
"tokio",
|
||||||
"tracing",
|
"tracing",
|
||||||
"uuid",
|
"uuid",
|
||||||
|
|
@ -2012,7 +2012,7 @@ dependencies = [
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"sha2",
|
"sha2",
|
||||||
"smallvec",
|
"smallvec",
|
||||||
"thiserror 2.0.18",
|
"thiserror 2.0.20",
|
||||||
"tokio",
|
"tokio",
|
||||||
"tokio-stream",
|
"tokio-stream",
|
||||||
"tracing",
|
"tracing",
|
||||||
|
|
@ -2031,7 +2031,7 @@ dependencies = [
|
||||||
"quote",
|
"quote",
|
||||||
"sqlx-core",
|
"sqlx-core",
|
||||||
"sqlx-macros-core",
|
"sqlx-macros-core",
|
||||||
"syn",
|
"syn 2.0.117",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|
@ -2054,7 +2054,7 @@ dependencies = [
|
||||||
"sqlx-mysql",
|
"sqlx-mysql",
|
||||||
"sqlx-postgres",
|
"sqlx-postgres",
|
||||||
"sqlx-sqlite",
|
"sqlx-sqlite",
|
||||||
"syn",
|
"syn 2.0.117",
|
||||||
"tokio",
|
"tokio",
|
||||||
"url",
|
"url",
|
||||||
]
|
]
|
||||||
|
|
@ -2097,7 +2097,7 @@ dependencies = [
|
||||||
"smallvec",
|
"smallvec",
|
||||||
"sqlx-core",
|
"sqlx-core",
|
||||||
"stringprep",
|
"stringprep",
|
||||||
"thiserror 2.0.18",
|
"thiserror 2.0.20",
|
||||||
"tracing",
|
"tracing",
|
||||||
"uuid",
|
"uuid",
|
||||||
"whoami",
|
"whoami",
|
||||||
|
|
@ -2136,7 +2136,7 @@ dependencies = [
|
||||||
"smallvec",
|
"smallvec",
|
||||||
"sqlx-core",
|
"sqlx-core",
|
||||||
"stringprep",
|
"stringprep",
|
||||||
"thiserror 2.0.18",
|
"thiserror 2.0.20",
|
||||||
"tracing",
|
"tracing",
|
||||||
"uuid",
|
"uuid",
|
||||||
"whoami",
|
"whoami",
|
||||||
|
|
@ -2162,7 +2162,7 @@ dependencies = [
|
||||||
"serde",
|
"serde",
|
||||||
"serde_urlencoded",
|
"serde_urlencoded",
|
||||||
"sqlx-core",
|
"sqlx-core",
|
||||||
"thiserror 2.0.18",
|
"thiserror 2.0.20",
|
||||||
"tracing",
|
"tracing",
|
||||||
"url",
|
"url",
|
||||||
"uuid",
|
"uuid",
|
||||||
|
|
@ -2208,6 +2208,17 @@ dependencies = [
|
||||||
"unicode-ident",
|
"unicode-ident",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "syn"
|
||||||
|
version = "3.0.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"unicode-ident",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "sync_wrapper"
|
name = "sync_wrapper"
|
||||||
version = "1.0.2"
|
version = "1.0.2"
|
||||||
|
|
@ -2225,7 +2236,7 @@ checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
"quote",
|
"quote",
|
||||||
"syn",
|
"syn 2.0.117",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|
@ -2235,10 +2246,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
|
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"fastrand",
|
"fastrand",
|
||||||
"getrandom 0.4.2",
|
"getrandom 0.3.4",
|
||||||
"once_cell",
|
"once_cell",
|
||||||
"rustix",
|
"rustix",
|
||||||
"windows-sys 0.61.2",
|
"windows-sys 0.52.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|
@ -2252,11 +2263,11 @@ dependencies = [
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "thiserror"
|
name = "thiserror"
|
||||||
version = "2.0.18"
|
version = "2.0.20"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4"
|
checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"thiserror-impl 2.0.18",
|
"thiserror-impl 2.0.20",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|
@ -2267,18 +2278,18 @@ checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
"quote",
|
"quote",
|
||||||
"syn",
|
"syn 2.0.117",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "thiserror-impl"
|
name = "thiserror-impl"
|
||||||
version = "2.0.18"
|
version = "2.0.20"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5"
|
checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
"quote",
|
"quote",
|
||||||
"syn",
|
"syn 3.0.3",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|
@ -2340,7 +2351,7 @@ checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
"quote",
|
"quote",
|
||||||
"syn",
|
"syn 2.0.117",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|
@ -2366,13 +2377,14 @@ dependencies = [
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tokio-util"
|
name = "tokio-util"
|
||||||
version = "0.7.18"
|
version = "0.7.19"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098"
|
checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"bytes",
|
"bytes",
|
||||||
"futures-core",
|
"futures-core",
|
||||||
"futures-sink",
|
"futures-sink",
|
||||||
|
"libc",
|
||||||
"pin-project-lite",
|
"pin-project-lite",
|
||||||
"tokio",
|
"tokio",
|
||||||
]
|
]
|
||||||
|
|
@ -2453,7 +2465,7 @@ checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
"quote",
|
"quote",
|
||||||
"syn",
|
"syn 2.0.117",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|
@ -2592,9 +2604,9 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "uuid"
|
name = "uuid"
|
||||||
version = "1.23.1"
|
version = "1.23.4"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "ddd74a9687298c6858e9b88ec8935ec45d22e8fd5e6394fa1bd4e99a87789c76"
|
checksum = "bf80a72845275afea99e7f2b434723d3bc7e38470fcd1c7ed39a599c73319a53"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"getrandom 0.4.2",
|
"getrandom 0.4.2",
|
||||||
"js-sys",
|
"js-sys",
|
||||||
|
|
@ -2701,7 +2713,7 @@ dependencies = [
|
||||||
"bumpalo",
|
"bumpalo",
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
"quote",
|
"quote",
|
||||||
"syn",
|
"syn 2.0.117",
|
||||||
"wasm-bindgen-shared",
|
"wasm-bindgen-shared",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
@ -2830,7 +2842,7 @@ checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
"quote",
|
"quote",
|
||||||
"syn",
|
"syn 2.0.117",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|
@ -2841,7 +2853,7 @@ checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
"quote",
|
"quote",
|
||||||
"syn",
|
"syn 2.0.117",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|
@ -3075,7 +3087,7 @@ dependencies = [
|
||||||
"heck",
|
"heck",
|
||||||
"indexmap",
|
"indexmap",
|
||||||
"prettyplease",
|
"prettyplease",
|
||||||
"syn",
|
"syn 2.0.117",
|
||||||
"wasm-metadata",
|
"wasm-metadata",
|
||||||
"wit-bindgen-core",
|
"wit-bindgen-core",
|
||||||
"wit-component",
|
"wit-component",
|
||||||
|
|
@ -3091,7 +3103,7 @@ dependencies = [
|
||||||
"prettyplease",
|
"prettyplease",
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
"quote",
|
"quote",
|
||||||
"syn",
|
"syn 2.0.117",
|
||||||
"wit-bindgen-core",
|
"wit-bindgen-core",
|
||||||
"wit-bindgen-rust",
|
"wit-bindgen-rust",
|
||||||
]
|
]
|
||||||
|
|
@ -3158,7 +3170,7 @@ checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
"quote",
|
"quote",
|
||||||
"syn",
|
"syn 2.0.117",
|
||||||
"synstructure",
|
"synstructure",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
@ -3179,7 +3191,7 @@ checksum = "70e3cd084b1788766f53af483dd21f93881ff30d7320490ec3ef7526d203bad4"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
"quote",
|
"quote",
|
||||||
"syn",
|
"syn 2.0.117",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|
@ -3199,7 +3211,7 @@ checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
"quote",
|
"quote",
|
||||||
"syn",
|
"syn 2.0.117",
|
||||||
"synstructure",
|
"synstructure",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
@ -3239,7 +3251,7 @@ checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
"quote",
|
"quote",
|
||||||
"syn",
|
"syn 2.0.117",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|
|
||||||
|
|
@ -5,9 +5,9 @@ members = ["skald-core", "skald"]
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
version = "0.0.1"
|
version = "0.0.1"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
license = "MIT"
|
license = "AGPL-3.0-or-later"
|
||||||
authors = ["Sulkta"]
|
authors = ["Sulkta <oss@sulkta.com>"]
|
||||||
repository = "http://127.0.0.1:3001/Sulkta/skald"
|
repository = "https://git.sulkta.com/Sulkta-OSS/skald"
|
||||||
|
|
||||||
[workspace.dependencies]
|
[workspace.dependencies]
|
||||||
tokio = { version = "1", features = ["full"] }
|
tokio = { version = "1", features = ["full"] }
|
||||||
|
|
|
||||||
26
Dockerfile
26
Dockerfile
|
|
@ -1,26 +1,16 @@
|
||||||
# Multi-stage build for skald.
|
# Multi-stage build for skald. Postgres ships in the same image
|
||||||
|
# until the tool stabilises; to split, swap the runtime base to
|
||||||
|
# debian:bookworm-slim, drop entrypoint.sh, point DATABASE_URL at
|
||||||
|
# an external pg.
|
||||||
#
|
#
|
||||||
# Stage 1: compile the rust binary against rust:1-bookworm.
|
# Build context is the workspace root: `docker build -t skald:latest .`
|
||||||
# Stage 2: pgvector/pgvector:pg17 (debian-bookworm postgres with
|
|
||||||
# pgvector preinstalled) + tini + the skald binary.
|
|
||||||
#
|
|
||||||
# v0.1 ships postgres inside the same container ("singleton till we
|
|
||||||
# have a real working tool"). When we extract the DB out, swap the
|
|
||||||
# runtime base to debian:bookworm-slim, drop entrypoint.sh, point
|
|
||||||
# DATABASE_URL at the external pg.
|
|
||||||
#
|
|
||||||
# Build context is the workspace root:
|
|
||||||
# docker build -t skald:latest .
|
|
||||||
|
|
||||||
# ─── builder ──────────────────────────────────────────────────────
|
|
||||||
FROM rust:1.95-bookworm AS builder
|
FROM rust:1.95-bookworm AS builder
|
||||||
WORKDIR /build
|
WORKDIR /build
|
||||||
|
|
||||||
# Cache the dependency graph: copy manifests first, fetch + build
|
# Dependency-cache layer: copy manifests + vendored path-dep first,
|
||||||
# stubs, THEN drop in real sources. The vendored clawdforge SDK
|
# build stubs, then drop in real sources. clawdforge is a path dep
|
||||||
# needs its own manifest + source available during the cache layer
|
# resolved at workspace load time.
|
||||||
# (path dep — Cargo resolves it at workspace load time, not at
|
|
||||||
# crate-compile time).
|
|
||||||
COPY Cargo.toml Cargo.lock ./
|
COPY Cargo.toml Cargo.lock ./
|
||||||
COPY skald-core/Cargo.toml skald-core/Cargo.toml
|
COPY skald-core/Cargo.toml skald-core/Cargo.toml
|
||||||
COPY skald/Cargo.toml skald/Cargo.toml
|
COPY skald/Cargo.toml skald/Cargo.toml
|
||||||
|
|
|
||||||
661
LICENSE
Normal file
661
LICENSE
Normal file
|
|
@ -0,0 +1,661 @@
|
||||||
|
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 19 November 2007
|
||||||
|
|
||||||
|
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
|
Preamble
|
||||||
|
|
||||||
|
The GNU Affero General Public License is a free, copyleft license for
|
||||||
|
software and other kinds of works, specifically designed to ensure
|
||||||
|
cooperation with the community in the case of network server software.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed
|
||||||
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
our General Public Licenses are intended to guarantee your freedom to
|
||||||
|
share and change all versions of a program--to make sure it remains free
|
||||||
|
software for all its users.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, not
|
||||||
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
|
have the freedom to distribute copies of free software (and charge for
|
||||||
|
them if you wish), that you receive source code or can get it if you
|
||||||
|
want it, that you can change the software or use pieces of it in new
|
||||||
|
free programs, and that you know you can do these things.
|
||||||
|
|
||||||
|
Developers that use our General Public Licenses protect your rights
|
||||||
|
with two steps: (1) assert copyright on the software, and (2) offer
|
||||||
|
you this License which gives you legal permission to copy, distribute
|
||||||
|
and/or modify the software.
|
||||||
|
|
||||||
|
A secondary benefit of defending all users' freedom is that
|
||||||
|
improvements made in alternate versions of the program, if they
|
||||||
|
receive widespread use, become available for other developers to
|
||||||
|
incorporate. Many developers of free software are heartened and
|
||||||
|
encouraged by the resulting cooperation. However, in the case of
|
||||||
|
software used on network servers, this result may fail to come about.
|
||||||
|
The GNU General Public License permits making a modified version and
|
||||||
|
letting the public access it on a server without ever releasing its
|
||||||
|
source code to the public.
|
||||||
|
|
||||||
|
The GNU Affero General Public License is designed specifically to
|
||||||
|
ensure that, in such cases, the modified source code becomes available
|
||||||
|
to the community. It requires the operator of a network server to
|
||||||
|
provide the source code of the modified version running there to the
|
||||||
|
users of that server. Therefore, public use of a modified version, on
|
||||||
|
a publicly accessible server, gives the public access to the source
|
||||||
|
code of the modified version.
|
||||||
|
|
||||||
|
An older license, called the Affero General Public License and
|
||||||
|
published by Affero, was designed to accomplish similar goals. This is
|
||||||
|
a different license, not a version of the Affero GPL, but Affero has
|
||||||
|
released a new version of the Affero GPL which permits relicensing under
|
||||||
|
this license.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and
|
||||||
|
modification follow.
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
0. Definitions.
|
||||||
|
|
||||||
|
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||||
|
|
||||||
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
|
works, such as semiconductor masks.
|
||||||
|
|
||||||
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
|
"recipients" may be individuals or organizations.
|
||||||
|
|
||||||
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
|
earlier work or a work "based on" the earlier work.
|
||||||
|
|
||||||
|
A "covered work" means either the unmodified Program or a work based
|
||||||
|
on the Program.
|
||||||
|
|
||||||
|
To "propagate" a work means to do anything with it that, without
|
||||||
|
permission, would make you directly or secondarily liable for
|
||||||
|
infringement under applicable copyright law, except executing it on a
|
||||||
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
|
distribution (with or without modification), making available to the
|
||||||
|
public, and in some countries other activities as well.
|
||||||
|
|
||||||
|
To "convey" a work means any kind of propagation that enables other
|
||||||
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
|
to the extent that it includes a convenient and prominently visible
|
||||||
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
|
tells the user that there is no warranty for the work (except to the
|
||||||
|
extent that warranties are provided), that licensees may convey the
|
||||||
|
work under this License, and how to view a copy of this License. If
|
||||||
|
the interface presents a list of user commands or options, such as a
|
||||||
|
menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
|
1. Source Code.
|
||||||
|
|
||||||
|
The "source code" for a work means the preferred form of the work
|
||||||
|
for making modifications to it. "Object code" means any non-source
|
||||||
|
form of a work.
|
||||||
|
|
||||||
|
A "Standard Interface" means an interface that either is an official
|
||||||
|
standard defined by a recognized standards body, or, in the case of
|
||||||
|
interfaces specified for a particular programming language, one that
|
||||||
|
is widely used among developers working in that language.
|
||||||
|
|
||||||
|
The "System Libraries" of an executable work include anything, other
|
||||||
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
|
packaging a Major Component, but which is not part of that Major
|
||||||
|
Component, and (b) serves only to enable use of the work with that
|
||||||
|
Major Component, or to implement a Standard Interface for which an
|
||||||
|
implementation is available to the public in source code form. A
|
||||||
|
"Major Component", in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to
|
||||||
|
produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The "Corresponding Source" for a work in object code form means all
|
||||||
|
the source code needed to generate, install, and (for an executable
|
||||||
|
work) run the object code and to modify the work, including scripts to
|
||||||
|
control those activities. However, it does not include the work's
|
||||||
|
System Libraries, or general-purpose tools or generally available free
|
||||||
|
programs which are used unmodified in performing those activities but
|
||||||
|
which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically
|
||||||
|
linked subprograms that the work is specifically designed to require,
|
||||||
|
such as by intimate data communication or control flow between those
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users
|
||||||
|
can regenerate automatically from other parts of the Corresponding
|
||||||
|
Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that
|
||||||
|
same work.
|
||||||
|
|
||||||
|
2. Basic Permissions.
|
||||||
|
|
||||||
|
All rights granted under this License are granted for the term of
|
||||||
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
|
permission to run the unmodified Program. The output from running a
|
||||||
|
covered work is covered by this License only if the output, given its
|
||||||
|
content, constitutes a covered work. This License acknowledges your
|
||||||
|
rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not
|
||||||
|
convey, without conditions so long as your license otherwise remains
|
||||||
|
in force. You may convey covered works to others for the sole purpose
|
||||||
|
of having them make modifications exclusively for you, or provide you
|
||||||
|
with facilities for running those works, provided that you comply with
|
||||||
|
the terms of this License in conveying all material for which you do
|
||||||
|
not control copyright. Those thus making or running the covered works
|
||||||
|
for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of
|
||||||
|
your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under
|
||||||
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
|
makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
|
||||||
|
No covered work shall be deemed part of an effective technological
|
||||||
|
measure under any applicable law fulfilling obligations under article
|
||||||
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
|
similar laws prohibiting or restricting circumvention of such
|
||||||
|
measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid
|
||||||
|
circumvention of technological measures to the extent such circumvention
|
||||||
|
is effected by exercising rights under this License with respect to
|
||||||
|
the covered work, and you disclaim any intention to limit operation or
|
||||||
|
modification of the work as a means of enforcing, against the work's
|
||||||
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
|
technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
|
||||||
|
You may convey verbatim copies of the Program's source code as you
|
||||||
|
receive it, in any medium, provided that you conspicuously and
|
||||||
|
appropriately publish on each copy an appropriate copyright notice;
|
||||||
|
keep intact all notices stating that this License and any
|
||||||
|
non-permissive terms added in accord with section 7 apply to the code;
|
||||||
|
keep intact all notices of the absence of any warranty; and give all
|
||||||
|
recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey,
|
||||||
|
and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
|
||||||
|
You may convey a work based on the Program, or the modifications to
|
||||||
|
produce it from the Program, in the form of source code under the
|
||||||
|
terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified
|
||||||
|
it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is
|
||||||
|
released under this License and any conditions added under section
|
||||||
|
7. This requirement modifies the requirement in section 4 to
|
||||||
|
"keep intact all notices".
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this
|
||||||
|
License to anyone who comes into possession of a copy. This
|
||||||
|
License will therefore apply, along with any applicable section 7
|
||||||
|
additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no
|
||||||
|
permission to license the work in any other way, but it does not
|
||||||
|
invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display
|
||||||
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
|
work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent
|
||||||
|
works, which are not by their nature extensions of the covered work,
|
||||||
|
and which are not combined with it such as to form a larger program,
|
||||||
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
|
"aggregate" if the compilation and its resulting copyright are not
|
||||||
|
used to limit the access or legal rights of the compilation's users
|
||||||
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
|
in an aggregate does not cause this License to apply to the other
|
||||||
|
parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
|
||||||
|
You may convey a covered work in object code form under the terms
|
||||||
|
of sections 4 and 5, provided that you also convey the
|
||||||
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
|
in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by the
|
||||||
|
Corresponding Source fixed on a durable physical medium
|
||||||
|
customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by a
|
||||||
|
written offer, valid for at least three years and valid for as
|
||||||
|
long as you offer spare parts or customer support for that product
|
||||||
|
model, to give anyone who possesses the object code either (1) a
|
||||||
|
copy of the Corresponding Source for all the software in the
|
||||||
|
product that is covered by this License, on a durable physical
|
||||||
|
medium customarily used for software interchange, for a price no
|
||||||
|
more than your reasonable cost of physically performing this
|
||||||
|
conveying of source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the
|
||||||
|
written offer to provide the Corresponding Source. This
|
||||||
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
|
only if you received the object code with such an offer, in accord
|
||||||
|
with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated
|
||||||
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
|
Corresponding Source in the same way through the same place at no
|
||||||
|
further charge. You need not require recipients to copy the
|
||||||
|
Corresponding Source along with the object code. If the place to
|
||||||
|
copy the object code is a network server, the Corresponding Source
|
||||||
|
may be on a different server (operated by you or a third party)
|
||||||
|
that supports equivalent copying facilities, provided you maintain
|
||||||
|
clear directions next to the object code saying where to find the
|
||||||
|
Corresponding Source. Regardless of what server hosts the
|
||||||
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
|
available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided
|
||||||
|
you inform other peers where the object code and Corresponding
|
||||||
|
Source of the work are being offered to the general public at no
|
||||||
|
charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded
|
||||||
|
from the Corresponding Source as a System Library, need not be
|
||||||
|
included in conveying the object code work.
|
||||||
|
|
||||||
|
A "User Product" is either (1) a "consumer product", which means any
|
||||||
|
tangible personal property which is normally used for personal, family,
|
||||||
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
|
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||||
|
product received by a particular user, "normally used" refers to a
|
||||||
|
typical or common use of that class of product, regardless of the status
|
||||||
|
of the particular user or of the way in which the particular user
|
||||||
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
|
is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
|
||||||
|
"Installation Information" for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install
|
||||||
|
and execute modified versions of a covered work in that User Product from
|
||||||
|
a modified version of its Corresponding Source. The information must
|
||||||
|
suffice to ensure that the continued functioning of the modified object
|
||||||
|
code is in no case prevented or interfered with solely because
|
||||||
|
modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or
|
||||||
|
specifically for use in, a User Product, and the conveying occurs as
|
||||||
|
part of a transaction in which the right of possession and use of the
|
||||||
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
|
fixed term (regardless of how the transaction is characterized), the
|
||||||
|
Corresponding Source conveyed under this section must be accompanied
|
||||||
|
by the Installation Information. But this requirement does not apply
|
||||||
|
if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has
|
||||||
|
been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a
|
||||||
|
requirement to continue to provide support service, warranty, or updates
|
||||||
|
for a work that has been modified or installed by the recipient, or for
|
||||||
|
the User Product in which it has been modified or installed. Access to a
|
||||||
|
network may be denied when the modification itself materially and
|
||||||
|
adversely affects the operation of the network or violates the rules and
|
||||||
|
protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided,
|
||||||
|
in accord with this section must be in a format that is publicly
|
||||||
|
documented (and with an implementation available to the public in
|
||||||
|
source code form), and must require no special password or key for
|
||||||
|
unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
|
||||||
|
"Additional permissions" are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions.
|
||||||
|
Additional permissions that are applicable to the entire Program shall
|
||||||
|
be treated as though they were included in this License, to the extent
|
||||||
|
that they are valid under applicable law. If additional permissions
|
||||||
|
apply only to part of the Program, that part may be used separately
|
||||||
|
under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option
|
||||||
|
remove any additional permissions from that copy, or from any part of
|
||||||
|
it. (Additional permissions may be written to require their own
|
||||||
|
removal in certain cases when you modify the work.) You may place
|
||||||
|
additional permissions on material, added by you to a covered work,
|
||||||
|
for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you
|
||||||
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
|
that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the
|
||||||
|
terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or
|
||||||
|
author attributions in that material or in the Appropriate Legal
|
||||||
|
Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
|
requiring that modified versions of such material be marked in
|
||||||
|
reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or
|
||||||
|
authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some
|
||||||
|
trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that
|
||||||
|
material by anyone who conveys the material (or modified versions of
|
||||||
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
|
any liability that these contractual assumptions directly impose on
|
||||||
|
those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered "further
|
||||||
|
restrictions" within the meaning of section 10. If the Program as you
|
||||||
|
received it, or any part of it, contains a notice stating that it is
|
||||||
|
governed by this License along with a term that is a further
|
||||||
|
restriction, you may remove that term. If a license document contains
|
||||||
|
a further restriction but permits relicensing or conveying under this
|
||||||
|
License, you may add to a covered work material governed by the terms
|
||||||
|
of that license document, provided that the further restriction does
|
||||||
|
not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you
|
||||||
|
must place, in the relevant source files, a statement of the
|
||||||
|
additional terms that apply to those files, or a notice indicating
|
||||||
|
where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the
|
||||||
|
form of a separately written license, or stated as exceptions;
|
||||||
|
the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly
|
||||||
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
|
modify it is void, and will automatically terminate your rights under
|
||||||
|
this License (including any patent licenses granted under the third
|
||||||
|
paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your
|
||||||
|
license from a particular copyright holder is reinstated (a)
|
||||||
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
|
holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is
|
||||||
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
|
violation by some reasonable means, this is the first time you have
|
||||||
|
received notice of violation of this License (for any work) from that
|
||||||
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the
|
||||||
|
licenses of parties who have received copies or rights from you under
|
||||||
|
this License. If your rights have been terminated and not permanently
|
||||||
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
|
material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or
|
||||||
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
|
to receive a copy likewise does not require acceptance. However,
|
||||||
|
nothing other than this License grants you permission to propagate or
|
||||||
|
modify any covered work. These actions infringe copyright if you do
|
||||||
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
|
covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically
|
||||||
|
receives a license from the original licensors, to run, modify and
|
||||||
|
propagate that work, subject to this License. You are not responsible
|
||||||
|
for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An "entity transaction" is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an
|
||||||
|
organization, or merging organizations. If propagation of a covered
|
||||||
|
work results from an entity transaction, each party to that
|
||||||
|
transaction who receives a copy of the work also receives whatever
|
||||||
|
licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
|
the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the
|
||||||
|
rights granted or affirmed under this License. For example, you may
|
||||||
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
|
rights granted under this License, and you may not initiate litigation
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
|
sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The
|
||||||
|
work thus licensed is called the contributor's "contributor version".
|
||||||
|
|
||||||
|
A contributor's "essential patent claims" are all patent claims
|
||||||
|
owned or controlled by the contributor, whether already acquired or
|
||||||
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
|
by this License, of making, using, or selling its contributor version,
|
||||||
|
but do not include claims that would be infringed only as a
|
||||||
|
consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, "control" includes the right to grant
|
||||||
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
|
this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
|
patent license under the contributor's essential patent claims, to
|
||||||
|
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||||
|
propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a "patent license" is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
|
(such as an express permission to practice a patent or covenant not to
|
||||||
|
sue for patent infringement). To "grant" such a patent license to a
|
||||||
|
party means to make such an agreement or commitment not to enforce a
|
||||||
|
patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license,
|
||||||
|
and the Corresponding Source of the work is not available for anyone
|
||||||
|
to copy, free of charge and under the terms of this License, through a
|
||||||
|
publicly available network server or other readily accessible means,
|
||||||
|
then you must either (1) cause the Corresponding Source to be so
|
||||||
|
available, or (2) arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or (3) arrange, in a manner
|
||||||
|
consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have
|
||||||
|
actual knowledge that, but for the patent license, your conveying the
|
||||||
|
covered work in a country, or your recipient's use of the covered work
|
||||||
|
in a country, would infringe one or more identifiable patents in that
|
||||||
|
country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or
|
||||||
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
|
covered work, and grant a patent license to some of the parties
|
||||||
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
|
or convey a specific copy of the covered work, then the patent license
|
||||||
|
you grant is automatically extended to all recipients of the covered
|
||||||
|
work and works based on it.
|
||||||
|
|
||||||
|
A patent license is "discriminatory" if it does not include within
|
||||||
|
the scope of its coverage, prohibits the exercise of, or is
|
||||||
|
conditioned on the non-exercise of one or more of the rights that are
|
||||||
|
specifically granted under this License. You may not convey a covered
|
||||||
|
work if you are a party to an arrangement with a third party that is
|
||||||
|
in the business of distributing software, under which you make payment
|
||||||
|
to the third party based on the extent of your activity of conveying
|
||||||
|
the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory
|
||||||
|
patent license (a) in connection with copies of the covered work
|
||||||
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
|
for and in connection with specific products or compilations that
|
||||||
|
contain the covered work, unless you entered into that arrangement,
|
||||||
|
or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting
|
||||||
|
any implied license or other defenses to infringement that may
|
||||||
|
otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
|
to collect a royalty for further conveying from those to whom you convey
|
||||||
|
the Program, the only way you could satisfy both those terms and this
|
||||||
|
License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, if you modify the
|
||||||
|
Program, your modified version must prominently offer all users
|
||||||
|
interacting with it remotely through a computer network (if your version
|
||||||
|
supports such interaction) an opportunity to receive the Corresponding
|
||||||
|
Source of your version by providing access to the Corresponding Source
|
||||||
|
from a network server at no charge, through some standard or customary
|
||||||
|
means of facilitating copying of software. This Corresponding Source
|
||||||
|
shall include the Corresponding Source for any work covered by version 3
|
||||||
|
of the GNU General Public License that is incorporated pursuant to the
|
||||||
|
following paragraph.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, you have
|
||||||
|
permission to link or combine any covered work with a work licensed
|
||||||
|
under version 3 of the GNU General Public License into a single
|
||||||
|
combined work, and to convey the resulting work. The terms of this
|
||||||
|
License will continue to apply to the part which is the covered work,
|
||||||
|
but the work with which it is combined will remain governed by version
|
||||||
|
3 of the GNU General Public License.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU Affero General Public License from time to time. Such new versions
|
||||||
|
will be similar in spirit to the present version, but may differ in detail to
|
||||||
|
address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the
|
||||||
|
Program specifies that a certain numbered version of the GNU Affero General
|
||||||
|
Public License "or any later version" applies to it, you have the
|
||||||
|
option of following the terms and conditions either of that numbered
|
||||||
|
version or of any later version published by the Free Software
|
||||||
|
Foundation. If the Program does not specify a version number of the
|
||||||
|
GNU Affero General Public License, you may choose any version ever published
|
||||||
|
by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future
|
||||||
|
versions of the GNU Affero General Public License can be used, that proxy's
|
||||||
|
public statement of acceptance of a version permanently authorizes you
|
||||||
|
to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different
|
||||||
|
permissions. However, no additional obligations are imposed on any
|
||||||
|
author or copyright holder as a result of your choosing to follow a
|
||||||
|
later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||||
|
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||||
|
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||||
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||||
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||||
|
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||||
|
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||||
|
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||||
|
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||||
|
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||||
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
|
SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided
|
||||||
|
above cannot be given local legal effect according to their terms,
|
||||||
|
reviewing courts shall apply local law that most closely approximates
|
||||||
|
an absolute waiver of all civil liability in connection with the
|
||||||
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
|
copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest
|
||||||
|
to attach them to the start of each source file to most effectively
|
||||||
|
state the exclusion of warranty; and each file should have at least
|
||||||
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU Affero General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU Affero General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU Affero General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If your software can interact with users remotely through a computer
|
||||||
|
network, you should also make sure that it provides a way for users to
|
||||||
|
get its source. For example, if your program is a web application, its
|
||||||
|
interface could display a "Source" link that leads users to an archive
|
||||||
|
of the code. There are many ways you could offer source, and different
|
||||||
|
solutions will be better for different programs; see section 13 for the
|
||||||
|
specific requirements.
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
|
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||||
|
<https://www.gnu.org/licenses/>.
|
||||||
130
README.md
130
README.md
|
|
@ -1,95 +1,79 @@
|
||||||
# skald
|
# skald
|
||||||
|
|
||||||
Long-form story-writer with canon-keeping, sequel continuity, and
|
Long-form story-writer with canon-keeping, sequel continuity, and
|
||||||
(future) self-hosted audiobook narration. Database is the source of
|
self-hosted audiobook narration. The database is the source of truth;
|
||||||
truth — the writer is the tooling.
|
the binary is the tooling.
|
||||||
|
|
||||||
Named for the Old Norse poets who composed and memorized kings'
|
Named for the Old Norse poets who composed and memorized kings' sagas
|
||||||
sagas across generations.
|
across generations.
|
||||||
|
|
||||||
## Status: v0.1 — scaffold
|
## What's wired
|
||||||
|
|
||||||
What's wired:
|
|
||||||
|
|
||||||
- Rust workspace (`skald-core` + `skald`)
|
- Rust workspace (`skald-core` + `skald`)
|
||||||
- Postgres schema for stories, characters, canon facts, chapters,
|
- Postgres schema for stories, characters, canon facts, chapters,
|
||||||
passages, generation runs, audit findings, tags
|
passages, generation runs, audit findings, tags
|
||||||
- pgvector extension installed for future similarity search
|
- pgvector for future similarity search
|
||||||
- `skald import-markdown` ingests a story file (chapters + bible)
|
- `skald import-markdown` ingests a story file (chapters + bible)
|
||||||
into the schema
|
- `skald serve` exposes `/health` + the web inspector and runs
|
||||||
- `skald serve` exposes `/health` and runs migrations on boot
|
migrations on boot
|
||||||
- Single-container deploy: postgres + skald in one image
|
- `skald continue` runs gen → cleanup → audit per chapter, with
|
||||||
|
multi-chapter batching (cap 20)
|
||||||
Wired (this commit):
|
- `skald rewrite` re-authors a chapter in a named author's voice
|
||||||
|
- `skald audit` runs whole-story prose-quality audit; `skald dedup`
|
||||||
- clawdforge Rust SDK vendored at `vendor/clawdforge/` (upstream:
|
is the surgical fix half of the loop
|
||||||
`Sulkta-OSS/clawdforge` `clients/rust/`)
|
- `skald prepare-narration` annotates a chapter with `[breath]` /
|
||||||
- `skald-core::forge` — three-pass orchestration shell (gen / cleanup /
|
`[pause:Xs]` / `[scene]` beats and per-character `[voice:...]`
|
||||||
audit). Prompts are TODO stubs; pipeline plumbing is in place.
|
tags
|
||||||
|
- `skald narrate` renders a chapter to audio via one of three TTS
|
||||||
Not yet wired:
|
engines (F5-TTS, Kokoro-82M, Tortoise-TTS) — see `engines/`
|
||||||
|
- Named-author "soul" personas via `skald authors seed`; author
|
||||||
- Web UI (the inbox + browse + queue surface)
|
voice replaces the model's base system prompt for gen/cleanup/
|
||||||
- Prompt templates for the three passes (heavy prompt-engineering
|
rewrite/dedup/narrate_prep
|
||||||
work — own session)
|
|
||||||
- `skald-core::context` — assemble the LLM context blob from DB rows
|
|
||||||
(bible + characters + parent prose summaries + similarity-matched
|
|
||||||
passages)
|
|
||||||
- Embeddings backfill + ivfflat index
|
|
||||||
- TTS sidecar container + post-render audit chain (see
|
|
||||||
`docs/tts-pipeline.md`)
|
|
||||||
|
|
||||||
## v0.1 smoke
|
|
||||||
|
|
||||||
```bash
|
|
||||||
docker compose -p skald up -d
|
|
||||||
docker exec skald skald import-markdown \
|
|
||||||
--path /seed/coast-down.md \
|
|
||||||
--title "The Coast-Down"
|
|
||||||
|
|
||||||
curl http://localhost:7780/health
|
|
||||||
# → { ok: true, db_ok: true, story_count: 1, ... }
|
|
||||||
```
|
|
||||||
|
|
||||||
## Schema (cheat sheet)
|
## Schema (cheat sheet)
|
||||||
|
|
||||||
```
|
```
|
||||||
stories → meta + status + parent/root for series
|
stories meta + status + parent/root for series
|
||||||
characters → real or fictional, story-scoped
|
authors persona identity (slug, display_name, model)
|
||||||
canon_facts → setting, mystery, theme, rule, historical_anchor, hook
|
author_revisions versioned souls; one current per author
|
||||||
chapters → full prose body
|
characters real or fictional, story-scoped, voice-mappable
|
||||||
chapter_summaries → short summaries for cheap context loading
|
canon_facts setting, mystery, theme, rule, historical_anchor, hook
|
||||||
passages → paragraph-level + embedding vector(1536)
|
chapters full prose body + optional body_md_tts annotation
|
||||||
generation_runs → every LLM call logged
|
chapter_summaries short summaries for cheap context loading
|
||||||
audit_findings → canon audit output (severity + area)
|
passages paragraph-level + embedding vector(1536)
|
||||||
tags → arbitrary labels
|
voices TTS voice rows (F5 ref clips / Kokoro / Tortoise names)
|
||||||
|
pronunciation_overrides per-story + global respellings for proper nouns
|
||||||
|
generation_runs every LLM call logged
|
||||||
|
audit_findings audit pass output (severity + area)
|
||||||
|
narration_runs per-chapter TTS renders
|
||||||
```
|
```
|
||||||
|
|
||||||
## Architecture (v0.1 + the plan)
|
## Quickstart
|
||||||
|
|
||||||
```
|
```sh
|
||||||
┌─────────────────────────────────┐
|
docker compose up -d
|
||||||
│ skald container │
|
docker exec skald skald import-markdown --path /seed/<story>.md \
|
||||||
│ ┌───────────┐ ┌────────────┐ │
|
--title "<title>"
|
||||||
│ │ postgres │ │ skald-rust │ │
|
curl http://localhost:7780/health
|
||||||
│ │ pgvector │←─│ axum + cli │ │
|
|
||||||
│ │ localhost │ │ :7780 │ │
|
|
||||||
│ └───────────┘ └─────┬──────┘ │
|
|
||||||
└─────────────────────────┼────────┘
|
|
||||||
│ HTTP (future)
|
|
||||||
↓
|
|
||||||
┌──────────┐
|
|
||||||
│clawdforge│
|
|
||||||
└─────┬────┘
|
|
||||||
↓
|
|
||||||
opus calls
|
|
||||||
```
|
```
|
||||||
|
|
||||||
v1.0+: extract postgres to its own container on db-net. skald
|
The compose file expects `POSTGRES_PASSWORD` and (optionally)
|
||||||
becomes pure stateless rust, connects via `DATABASE_URL`. Migration
|
`CLAWDFORGE_URL` + `CLAWDFORGE_TOKEN` in `.env`. Story markdown
|
||||||
is a connection-string change + a network move; the binary doesn't
|
goes into `./seed/`; postgres data persists in `./pgdata/`.
|
||||||
care where the DB lives.
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
v0.1 ships postgres inside the skald container — singleton until
|
||||||
|
the tool stabilises. To extract postgres later, swap the runtime
|
||||||
|
base to `debian:bookworm-slim`, drop `entrypoint.sh`, and point
|
||||||
|
`DATABASE_URL` at the external pg. The binary doesn't care where
|
||||||
|
the DB lives.
|
||||||
|
|
||||||
|
The generation passes call out to `clawdforge` (a bearer-token-gated
|
||||||
|
HTTP wrapper around `claude -p`). The Rust client is vendored at
|
||||||
|
`vendor/clawdforge/`. TTS calls go HTTP+JSON to the per-engine
|
||||||
|
sidecars under `engines/`.
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
MIT.
|
AGPL-3.0-or-later — see `LICENSE`.
|
||||||
|
|
|
||||||
51
compose.yml
51
compose.yml
|
|
@ -1,37 +1,42 @@
|
||||||
# Standalone compose stack for skald v0.1. Postgres lives in the
|
# Standalone compose stack for skald. Postgres lives inside the
|
||||||
# same container — single deployable unit "till we have a real
|
# skald container — single deployable unit until the tool stabilises.
|
||||||
# working tool" (Sulkta's call, 2026-05-13).
|
|
||||||
#
|
#
|
||||||
# To deploy on the host:
|
# Set in .env (or the environment):
|
||||||
# sudo mkdir -p /srv/appdata/skald/{pgdata,seed}
|
# POSTGRES_PASSWORD=... # required
|
||||||
# sudo cp <story>.md /srv/appdata/skald/seed/
|
# CLAWDFORGE_URL=http://...:8800 # if running gen / cleanup / audit
|
||||||
# sudo cp skald.env /srv/appdata/secrets/skald.env # POSTGRES_PASSWORD=...
|
# CLAWDFORGE_TOKEN=cf_...
|
||||||
# docker compose -p skald up -d
|
# SKALD_DATA=./pgdata # optional override; defaults to ./pgdata
|
||||||
|
# SKALD_SEED=./seed # optional override; defaults to ./seed
|
||||||
#
|
#
|
||||||
# To import the first story:
|
# To import the first story:
|
||||||
# docker exec skald skald import-markdown \
|
# docker compose exec skald skald import-markdown \
|
||||||
# --path /seed/<story>.md \
|
# --path /seed/<story>.md \
|
||||||
# --title "<title>"
|
# --title "<title>"
|
||||||
|
name: skald
|
||||||
|
|
||||||
services:
|
services:
|
||||||
skald:
|
skald:
|
||||||
image: registry.example.local:5000/skald:latest
|
build: .
|
||||||
|
image: skald:latest
|
||||||
container_name: skald
|
container_name: skald
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
ports:
|
ports:
|
||||||
- "7780:7780"
|
- "7780:7780"
|
||||||
env_file:
|
environment:
|
||||||
- /srv/appdata/secrets/skald.env
|
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?POSTGRES_PASSWORD is required}
|
||||||
|
POSTGRES_USER: ${POSTGRES_USER:-skald}
|
||||||
|
POSTGRES_DB: ${POSTGRES_DB:-skald}
|
||||||
|
DATABASE_URL: ${DATABASE_URL:-postgresql://skald:${POSTGRES_PASSWORD}@localhost:5432/skald}
|
||||||
|
CLAWDFORGE_URL: ${CLAWDFORGE_URL:-}
|
||||||
|
CLAWDFORGE_TOKEN: ${CLAWDFORGE_TOKEN:-}
|
||||||
|
SKALD_MODEL: ${SKALD_MODEL:-opus}
|
||||||
|
F5_TTS_URL: ${F5_TTS_URL:-}
|
||||||
|
KOKORO_URL: ${KOKORO_URL:-}
|
||||||
|
TORTOISE_URL: ${TORTOISE_URL:-}
|
||||||
|
RUST_LOG: ${RUST_LOG:-info}
|
||||||
|
SKALD_LOG_FORMAT: ${SKALD_LOG_FORMAT:-json}
|
||||||
volumes:
|
volumes:
|
||||||
# Postgres data — persist across container recreates.
|
# Postgres data — persist across container recreates.
|
||||||
- /srv/appdata/skald/pgdata:/var/lib/postgresql/data
|
- ${SKALD_DATA:-./pgdata}:/var/lib/postgresql/data
|
||||||
# Markdown corpus to import via `docker exec skald skald import-markdown`.
|
# Markdown corpus to import via `skald import-markdown`.
|
||||||
- /srv/appdata/skald/seed:/seed:ro
|
- ${SKALD_SEED:-./seed}:/seed:ro
|
||||||
environment:
|
|
||||||
RUST_LOG: ${RUST_LOG:-info}
|
|
||||||
SKALD_LOG_FORMAT: json
|
|
||||||
labels:
|
|
||||||
org.sulkta.domain: "sulkta"
|
|
||||||
org.sulkta.owner: "Sulkta"
|
|
||||||
org.sulkta.managed-by: "compose"
|
|
||||||
org.sulkta.role: "skald"
|
|
||||||
|
|
|
||||||
163
docs/authors.md
Normal file
163
docs/authors.md
Normal file
|
|
@ -0,0 +1,163 @@
|
||||||
|
# Authors as personas with souls
|
||||||
|
|
||||||
|
Each story has a named author with a soul. The author's voice bleeds
|
||||||
|
through every generation pass — not as instruction stapled to the
|
||||||
|
prompt, but as the substrate the prose grows from. The reader should
|
||||||
|
feel "a person wrote this."
|
||||||
|
|
||||||
|
Authors have memory across their corpus when the per-story
|
||||||
|
`cross_story_memory` toggle is on. An author writing a Chernobyl
|
||||||
|
piece can quietly echo a phrase from an earlier mining-strike story.
|
||||||
|
Default is off — most stories stand alone.
|
||||||
|
|
||||||
|
## Schema
|
||||||
|
|
||||||
|
Authors live in the database, not on disk. The soul is a markdown
|
||||||
|
blob in `author_revisions.soul`. Authors are immutable; new soul
|
||||||
|
revisions create a new `author_revisions` row marked `is_current`
|
||||||
|
and the previous one is demoted.
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE TABLE authors (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
slug TEXT NOT NULL UNIQUE,
|
||||||
|
display_name TEXT NOT NULL,
|
||||||
|
persona_tagline TEXT,
|
||||||
|
model TEXT NOT NULL DEFAULT 'opus',
|
||||||
|
is_synthetic BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE author_revisions (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
author_id UUID NOT NULL REFERENCES authors(id),
|
||||||
|
n INT NOT NULL,
|
||||||
|
soul TEXT NOT NULL,
|
||||||
|
system_template TEXT,
|
||||||
|
tools TEXT[] NOT NULL DEFAULT '{}',
|
||||||
|
note TEXT,
|
||||||
|
is_current BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
ALTER TABLE stories
|
||||||
|
ADD COLUMN author_id UUID REFERENCES authors(id),
|
||||||
|
ADD COLUMN author_revision_id UUID REFERENCES author_revisions(id),
|
||||||
|
ADD COLUMN cross_story_memory BOOLEAN NOT NULL DEFAULT false;
|
||||||
|
|
||||||
|
CREATE TABLE author_corpus (
|
||||||
|
author_id UUID NOT NULL REFERENCES authors(id) ON DELETE CASCADE,
|
||||||
|
story_id UUID NOT NULL REFERENCES stories(id) ON DELETE CASCADE,
|
||||||
|
role TEXT NOT NULL CHECK (role IN ('authored', 'read')),
|
||||||
|
added_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
PRIMARY KEY (author_id, story_id)
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
## Per-pass author roles
|
||||||
|
|
||||||
|
- **gen** — full author voice. They are writing.
|
||||||
|
- **cleanup** — full author voice. Polishing their own draft, not a
|
||||||
|
neutral editor.
|
||||||
|
- **rewrite** — full author voice. Re-authoring another hand's
|
||||||
|
prose; canon preserved, prose reworked.
|
||||||
|
- **dedup** — full author voice. Surgical fix of audit-flagged
|
||||||
|
repetitions only.
|
||||||
|
- **narrate_prep** — author voice if bound; the author's beat
|
||||||
|
placement carries.
|
||||||
|
- **audit / prose_audit** — neutral. The audit checks the author's
|
||||||
|
work with fresh eyes; no author bound.
|
||||||
|
- **summarize** — neutral. Continuity utility, not prose.
|
||||||
|
|
||||||
|
When an author is bound, the soul replaces the model's base system
|
||||||
|
prompt (`SystemMode::Replace`). Without an author, a neutral house
|
||||||
|
scaffold is appended (`SystemMode::Append`).
|
||||||
|
|
||||||
|
## Soul template
|
||||||
|
|
||||||
|
Following the persona-soul shape, recalibrated for authorial identity.
|
||||||
|
Free-form prose under each section.
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
# Author: {{display_name}}
|
||||||
|
|
||||||
|
_Tagline: {{persona_tagline}}_
|
||||||
|
|
||||||
|
## Voice
|
||||||
|
|
||||||
|
Sentence rhythm. Vocabulary register. Paragraph length tendencies.
|
||||||
|
Dialogue density. Punctuation habits (dashes, semicolons, sentence
|
||||||
|
fragments). What your prose SOUNDS like read aloud.
|
||||||
|
|
||||||
|
## Worldview
|
||||||
|
|
||||||
|
What you believe about people. Power. Money. Labor. Cities. Nature.
|
||||||
|
What makes you angry. What makes you tender. Whose side you're on
|
||||||
|
in the implicit moral architecture of any scene.
|
||||||
|
|
||||||
|
## Specifics over abstractions
|
||||||
|
|
||||||
|
The concrete details you reach for. The five senses you favor.
|
||||||
|
Smells? Cold? Texture of cloth? Sound of machines?
|
||||||
|
|
||||||
|
## Pet peeves
|
||||||
|
|
||||||
|
Words you refuse to write. Tropes you avoid. Sentimentalities you
|
||||||
|
gut.
|
||||||
|
|
||||||
|
## Sense of humor
|
||||||
|
|
||||||
|
Dry? Dark? Absent? Bitter? Self-deprecating? Where in a paragraph
|
||||||
|
does humor live — end of a sentence, mid-clause, or never?
|
||||||
|
|
||||||
|
## Biography (real or invented)
|
||||||
|
|
||||||
|
A few biographical facts that EXPLAIN the voice — the formative
|
||||||
|
cuts, not a CV.
|
||||||
|
|
||||||
|
## Anchor authors
|
||||||
|
|
||||||
|
Living or dead authors the prose draws from. Useful for the model
|
||||||
|
to triangulate voice.
|
||||||
|
|
||||||
|
## Do / Don't
|
||||||
|
|
||||||
|
Concrete prose moves to reach for and to avoid.
|
||||||
|
```
|
||||||
|
|
||||||
|
The default scaffold (`DEFAULT_AUTHOR_SCAFFOLD` in `skald-core::forge`)
|
||||||
|
wraps the soul in a system prompt that:
|
||||||
|
|
||||||
|
- declares the model IS the author, not playing one
|
||||||
|
- pins canon as non-negotiable (names, dates, established events)
|
||||||
|
- forbids preamble, meta-commentary, fourth-wall breaks
|
||||||
|
- substitutes the per-pass directive (`GEN_DIRECTIVE`,
|
||||||
|
`CLEANUP_DIRECTIVE`, `REWRITE_DIRECTIVE`, `DEDUP_DIRECTIVE`,
|
||||||
|
`NARRATE_PREP_DIRECTIVE`)
|
||||||
|
|
||||||
|
A per-author `system_template` overrides the default scaffold when
|
||||||
|
set; otherwise the default is used.
|
||||||
|
|
||||||
|
## Cross-story memory
|
||||||
|
|
||||||
|
When `stories.cross_story_memory = true`, the continuation context
|
||||||
|
pulls characters / canon_facts / passages from every story the
|
||||||
|
author has authored or marked-read, not just the parent chain.
|
||||||
|
|
||||||
|
To keep token budget sane, cross-corpus pulls are summary-only by
|
||||||
|
default. Embeddings-similarity (once wired) can surface direct
|
||||||
|
callbacks.
|
||||||
|
|
||||||
|
## Seeding an author
|
||||||
|
|
||||||
|
```sh
|
||||||
|
skald authors seed \
|
||||||
|
--slug orson-black \
|
||||||
|
--display-name "Orson Black" \
|
||||||
|
--tagline "Orwell but more rebel and pissed off" \
|
||||||
|
--file seeds/authors/orson-black.md
|
||||||
|
```
|
||||||
|
|
||||||
|
This creates the author + first revision (or adds a new revision to
|
||||||
|
an existing author, which becomes current).
|
||||||
|
|
@ -40,19 +40,18 @@ generalise. Examples:
|
||||||
all three at once), preset choice ergonomics, character→tortoise-
|
all three at once), preset choice ergonomics, character→tortoise-
|
||||||
voice seed assignments.
|
voice seed assignments.
|
||||||
|
|
||||||
When deploying an engine to the host, the build dir at
|
To deploy a tuned engine, check out the engine's branch in the build
|
||||||
`/srv/appdata/<engine>/build/` tracks the engine's branch:
|
dir and `docker compose up -d --build`:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cd /srv/appdata/kokoro/build
|
|
||||||
git fetch && git checkout engine/kokoro
|
git fetch && git checkout engine/kokoro
|
||||||
docker compose -p <name> up -d --build
|
docker compose up -d --build
|
||||||
```
|
```
|
||||||
|
|
||||||
## GPU coordination (2070 Super)
|
## GPU coordination
|
||||||
|
|
||||||
The 8GB card is the bottleneck. F5 + Kokoro can co-reside (~5GB +
|
On an 8GB card F5 + Kokoro can co-reside (~5GB + ~1GB). Tortoise
|
||||||
~1GB). Tortoise pushes the budget over and needs the GPU largely
|
pushes the budget over and needs the GPU largely to itself — the
|
||||||
to itself — the `engine/tortoise` branch will carry the script
|
`engine/tortoise` branch carries a script to stop kokoro + f5
|
||||||
that stops kokoro + f5 before a tortoise run and restarts them
|
before a Tortoise run and restart them after. Replace with proper
|
||||||
after. Replace with proper coordination once we have more VRAM.
|
coordination once more VRAM is available.
|
||||||
|
|
|
||||||
|
|
@ -1,9 +1,6 @@
|
||||||
# Sulkta build of F5-TTS — upstream ghcr.io/swivid/f5-tts:main was
|
# F5-TTS rebuild on a known-good pytorch base. Upstream
|
||||||
# shipped with torch 2.11/torchaudio 2.4 ABI mismatch on 2026-05-13,
|
# ghcr.io/swivid/f5-tts:main shipped a torch/torchaudio ABI mismatch
|
||||||
# breaking import torchaudio at boot. We rebuild on a known-good
|
# that broke `import torchaudio` at boot; this image bypasses that.
|
||||||
# pytorch base + pip install f5-tts.
|
|
||||||
#
|
|
||||||
# Image tag in localhost-registry: registry.example.local:5000/f5-tts:<ver>
|
|
||||||
#
|
#
|
||||||
# License: Apache 2.0 (code) / CC-BY-NC (Emilia-trained weights).
|
# License: Apache 2.0 (code) / CC-BY-NC (Emilia-trained weights).
|
||||||
# Personal use OK; redistribution gray-area — flagged.
|
# Personal use OK; redistribution gray-area — flagged.
|
||||||
|
|
@ -30,12 +27,11 @@ RUN pip install --no-cache-dir 'f5-tts>=1.0.0'
|
||||||
# Pre-warm the HF cache directory.
|
# Pre-warm the HF cache directory.
|
||||||
RUN mkdir -p /cache/hf /audio /voices
|
RUN mkdir -p /cache/hf /audio /voices
|
||||||
|
|
||||||
COPY f5_server.py /app/f5_server.py
|
COPY server.py /app/server.py
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
EXPOSE 7860
|
EXPOSE 7860
|
||||||
|
|
||||||
# Skald talks to our purpose-built FastAPI server, not Gradio.
|
# Purpose-built FastAPI server, not Gradio. Models load at startup
|
||||||
# Models load at startup (first request would otherwise pay the
|
# so the first request doesn't pay the cold-start cost.
|
||||||
# cold-start cost). uvicorn on :7860 to keep the port stable.
|
CMD ["uvicorn", "server:app", "--host", "0.0.0.0", "--port", "7860"]
|
||||||
CMD ["uvicorn", "f5_server:app", "--host", "0.0.0.0", "--port", "7860"]
|
|
||||||
|
|
|
||||||
|
|
@ -1,19 +1,21 @@
|
||||||
# F5-TTS standalone stack on the host.
|
# F5-TTS sidecar.
|
||||||
#
|
#
|
||||||
# License posture (acknowledged 2026-05-13): code is Apache 2.0, but
|
# Code is Apache 2.0; pretrained F5TTS_v1_Base weights are CC-BY-NC
|
||||||
# the pretrained model weights are CC-BY-NC (Emilia training data).
|
# (Emilia training data). Personal use is fine; redistribution is a
|
||||||
# Personal listen is fine; public sharing is a flagged gray area.
|
# flagged gray area.
|
||||||
# Sulkta's call: ship anyway.
|
|
||||||
#
|
#
|
||||||
# Runtime: 8GB GPU is plenty (F5 inference ~4-6GB peak).
|
# First run downloads ~2GB of model weights from HuggingFace into
|
||||||
|
# the hf-cache volume; subsequent runs are warm.
|
||||||
#
|
#
|
||||||
# First-run cost: ~2GB model download from HuggingFace into hf-cache,
|
# Set in .env (or override):
|
||||||
# happens on first inference request. Subsequent runs are warm.
|
# F5_HOST_PORT=7792
|
||||||
|
# F5_DATA=./data # ${F5_DATA}/hf-cache + voices + audio
|
||||||
name: f5-tts
|
name: f5-tts
|
||||||
|
|
||||||
services:
|
services:
|
||||||
f5-tts:
|
f5-tts:
|
||||||
image: registry.example.local:5000/f5-tts:0.3
|
build: .
|
||||||
|
image: f5-tts:0.3
|
||||||
container_name: f5-tts
|
container_name: f5-tts
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
deploy:
|
deploy:
|
||||||
|
|
@ -24,20 +26,11 @@ services:
|
||||||
count: all
|
count: all
|
||||||
capabilities: [gpu]
|
capabilities: [gpu]
|
||||||
ports:
|
ports:
|
||||||
- "127.0.0.1:7792:7860"
|
- "${F5_HOST_PORT:-7792}:7860"
|
||||||
- "127.0.0.1:7792:7860"
|
|
||||||
volumes:
|
volumes:
|
||||||
# HF model weights cache — persists ~2GB after first download.
|
- ${F5_DATA:-./data}/hf-cache:/cache/hf
|
||||||
- /srv/appdata/f5-tts/hf-cache:/cache/hf
|
- ${F5_DATA:-./data}/voices:/voices:ro
|
||||||
# Reference voice clips (lj_speech.wav, etc).
|
- ${F5_DATA:-./data}/audio:/audio
|
||||||
- /srv/appdata/f5-tts/voices:/voices:ro
|
|
||||||
# Rendered audio output — skald writes story narrations here.
|
|
||||||
- /srv/appdata/f5-tts/audio:/audio
|
|
||||||
environment:
|
environment:
|
||||||
HF_HOME: /cache/hf
|
HF_HOME: /cache/hf
|
||||||
HF_HUB_DISABLE_TELEMETRY: "1"
|
HF_HUB_DISABLE_TELEMETRY: "1"
|
||||||
labels:
|
|
||||||
org.sulkta.domain: "sulkta"
|
|
||||||
org.sulkta.owner: "Sulkta"
|
|
||||||
org.sulkta.managed-by: "compose"
|
|
||||||
org.sulkta.role: "f5-tts"
|
|
||||||
|
|
|
||||||
|
|
@ -1,13 +1,8 @@
|
||||||
# Sulkta build of Kokoro-82M TTS.
|
# Kokoro-82M TTS. Apache 2.0 code AND weights — clean stack vs
|
||||||
|
# F5-TTS's CC-BY-NC asterisk.
|
||||||
#
|
#
|
||||||
# License: Apache 2.0 (code AND model weights). Clean stack — no
|
# Kokoro runs fine on CPU but we use the cuda base to stay
|
||||||
# CC-BY-NC asterisk like F5-TTS's Emilia weights. This is the
|
# consistent with f5-tts and pick up the GPU when free.
|
||||||
# narrator engine for sleep-quality audiobook reads; F5-TTS stays
|
|
||||||
# around for voice-cloning cases.
|
|
||||||
#
|
|
||||||
# Kokoro is small enough to run on CPU but we use the cuda base
|
|
||||||
# anyway to stay consistent with f5-tts and so it'll pick up the
|
|
||||||
# GPU when no other tenant has it.
|
|
||||||
FROM pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime
|
FROM pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime
|
||||||
|
|
||||||
ENV DEBIAN_FRONTEND=noninteractive \
|
ENV DEBIAN_FRONTEND=noninteractive \
|
||||||
|
|
@ -27,9 +22,9 @@ RUN pip install --no-cache-dir 'kokoro>=0.9.0' 'fastapi>=0.115.0' 'uvicorn>=0.32
|
||||||
|
|
||||||
RUN mkdir -p /cache/hf /audio
|
RUN mkdir -p /cache/hf /audio
|
||||||
|
|
||||||
COPY kokoro_server.py /app/kokoro_server.py
|
COPY server.py /app/server.py
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
EXPOSE 7860
|
EXPOSE 7860
|
||||||
|
|
||||||
CMD ["uvicorn", "kokoro_server:app", "--host", "0.0.0.0", "--port", "7860"]
|
CMD ["uvicorn", "server:app", "--host", "0.0.0.0", "--port", "7860"]
|
||||||
|
|
|
||||||
|
|
@ -1,16 +1,18 @@
|
||||||
# Kokoro-82M TTS stack on the host.
|
# Kokoro-82M TTS sidecar.
|
||||||
#
|
#
|
||||||
# Audiobook-quality narrator engine (Apache 2.0 code + weights —
|
# Apache 2.0 code AND model weights — clean stack for share/publish.
|
||||||
# clean stack vs F5-TTS's CC-BY-NC asterisk). Sibling to f5-tts;
|
# Audiobook-quality narrator; F5-TTS stays around for voice-cloning.
|
||||||
# both share /srv/appdata/f5-tts/audio so skald's audio
|
|
||||||
# route serves outputs from either engine through the same path.
|
|
||||||
#
|
#
|
||||||
# License: Apache 2.0 top to bottom. Right for share/publish.
|
# Set in .env (or override):
|
||||||
|
# KOKORO_HOST_PORT=7794
|
||||||
|
# KOKORO_DATA=./data # ${KOKORO_DATA}/hf-cache
|
||||||
|
# AUDIO_DIR=../f5-tts/data/audio # shared output dir across engines
|
||||||
name: kokoro
|
name: kokoro
|
||||||
|
|
||||||
services:
|
services:
|
||||||
kokoro:
|
kokoro:
|
||||||
image: registry.example.local:5000/kokoro:0.5
|
build: .
|
||||||
|
image: kokoro:0.5
|
||||||
container_name: kokoro
|
container_name: kokoro
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
deploy:
|
deploy:
|
||||||
|
|
@ -21,17 +23,10 @@ services:
|
||||||
count: all
|
count: all
|
||||||
capabilities: [gpu]
|
capabilities: [gpu]
|
||||||
ports:
|
ports:
|
||||||
- "127.0.0.1:7794:7860"
|
- "${KOKORO_HOST_PORT:-7794}:7860"
|
||||||
- "127.0.0.1:7794:7860"
|
|
||||||
volumes:
|
volumes:
|
||||||
- /srv/appdata/kokoro/hf-cache:/cache/hf
|
- ${KOKORO_DATA:-./data}/hf-cache:/cache/hf
|
||||||
# Shared with f5-tts so skald's /audio route covers both.
|
- ${AUDIO_DIR:-./data/audio}:/audio
|
||||||
- /srv/appdata/f5-tts/audio:/audio
|
|
||||||
environment:
|
environment:
|
||||||
HF_HOME: /cache/hf
|
HF_HOME: /cache/hf
|
||||||
HF_HUB_DISABLE_TELEMETRY: "1"
|
HF_HUB_DISABLE_TELEMETRY: "1"
|
||||||
labels:
|
|
||||||
org.sulkta.domain: "sulkta"
|
|
||||||
org.sulkta.owner: "Sulkta"
|
|
||||||
org.sulkta.managed-by: "compose"
|
|
||||||
org.sulkta.role: "kokoro"
|
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
"""Kokoro-82M FastAPI server, sibling to f5_server.
|
"""Kokoro-82M FastAPI server, sibling to the f5-tts server.
|
||||||
|
|
||||||
Same /synthesize contract as F5 so skald can route between engines
|
Same /synthesize contract as F5 so skald can route between engines
|
||||||
just by which URL it points at. The semantic difference: Kokoro
|
just by which URL it points at. The semantic difference: Kokoro
|
||||||
|
|
@ -234,7 +234,7 @@ def _startup() -> None:
|
||||||
|
|
||||||
@app.get("/healthz")
|
@app.get("/healthz")
|
||||||
def healthz() -> dict:
|
def healthz() -> dict:
|
||||||
# Shape matches f5_server's so the same Rust HealthResponse
|
# Shape matches the f5-tts server's so the same Rust HealthResponse
|
||||||
# struct deserializes both: model/vocoder/loaded fields are
|
# struct deserializes both: model/vocoder/loaded fields are
|
||||||
# required by skald-core::narrate::HealthResponse.
|
# required by skald-core::narrate::HealthResponse.
|
||||||
return {
|
return {
|
||||||
|
|
|
||||||
|
|
@ -1,17 +1,13 @@
|
||||||
# Sulkta build of Tortoise-TTS.
|
# Tortoise-TTS. Apache 2.0 code + weights.
|
||||||
#
|
#
|
||||||
# Voice roster (built-in, no cloning needed): angie, daniel, deniro,
|
# ~26 built-in voices (no cloning): angie, daniel, deniro, emma,
|
||||||
# emma, freeman, geralt, halle, jlaw, lj, mol, myself, pat, pat2,
|
# freeman, geralt, halle, jlaw, lj, mol, myself, pat, pat2, rainbow,
|
||||||
# rainbow, snakes, tim_reynolds, tom, train_atkins, train_dotrice,
|
# snakes, tim_reynolds, tom, train_atkins, train_dotrice,
|
||||||
# train_dreams, train_grace, train_kennard, train_lescault,
|
# train_dreams, train_grace, train_kennard, train_lescault,
|
||||||
# train_mouse, weaver, william. ~26 voices baked in.
|
# train_mouse, weaver, william.
|
||||||
#
|
#
|
||||||
# License: Apache 2.0 (code) + Apache 2.0 (model weights). Clean
|
# Slow: standard preset is ~10x slower than Kokoro; high_quality is
|
||||||
# stack for share/publish.
|
# ~30x. Trade for quality.
|
||||||
#
|
|
||||||
# Speed: slow. Trade for quality. Standard preset is ~10x slower
|
|
||||||
# than Kokoro; high_quality is ~30x slower. Worth it for the
|
|
||||||
# audiobook-quality bar.
|
|
||||||
|
|
||||||
FROM pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime
|
FROM pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime
|
||||||
|
|
||||||
|
|
@ -37,9 +33,9 @@ RUN pip install --no-cache-dir \
|
||||||
|
|
||||||
RUN mkdir -p /cache/hf /cache/tortoise-models /audio
|
RUN mkdir -p /cache/hf /cache/tortoise-models /audio
|
||||||
|
|
||||||
COPY tortoise_server.py /app/tortoise_server.py
|
COPY server.py /app/server.py
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
EXPOSE 7860
|
EXPOSE 7860
|
||||||
|
|
||||||
CMD ["uvicorn", "tortoise_server:app", "--host", "0.0.0.0", "--port", "7860"]
|
CMD ["uvicorn", "server:app", "--host", "0.0.0.0", "--port", "7860"]
|
||||||
|
|
|
||||||
|
|
@ -1,19 +1,22 @@
|
||||||
# Tortoise-TTS stack on the host. Audiobook-quality engine with 25+
|
# Tortoise-TTS sidecar. 25+ named voices, no cloning needed.
|
||||||
# named voices (no cloning). Apache 2.0 top to bottom.
|
# Apache 2.0 top to bottom.
|
||||||
#
|
#
|
||||||
# Slow: ~10x kokoro wall clock at 'standard' preset. Worth it for
|
# Slow: ~10x kokoro wall-clock at 'standard' preset. Worth it for the
|
||||||
# the quality bar. Sulkta's call 2026-05-14: "use higgs (now tortoise)
|
# quality bar; runs are batched.
|
||||||
# and we will only let it use the full gpu for runs" — translated:
|
|
||||||
# runs are batched, slow is acceptable.
|
|
||||||
#
|
#
|
||||||
# Co-resides with kokoro on the 2070 Super since tortoise is ~5GB
|
# Co-resides with kokoro on an 8GB card (tortoise ~5GB + kokoro ~1GB).
|
||||||
# and kokoro is ~1GB (8GB total). If OOM hits during a render,
|
# OOM during a render: add a coordinator that pauses kokoro first.
|
||||||
# we'll add a coordination layer to pause kokoro first.
|
#
|
||||||
|
# Set in .env (or override):
|
||||||
|
# TORTOISE_HOST_PORT=7795
|
||||||
|
# TORTOISE_DATA=./data # ${TORTOISE_DATA}/{hf-cache,models}
|
||||||
|
# AUDIO_DIR=../f5-tts/data/audio # shared output dir across engines
|
||||||
name: tortoise
|
name: tortoise
|
||||||
|
|
||||||
services:
|
services:
|
||||||
tortoise:
|
tortoise:
|
||||||
image: registry.example.local:5000/tortoise:0.1
|
build: .
|
||||||
|
image: tortoise:0.1
|
||||||
container_name: tortoise
|
container_name: tortoise
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
deploy:
|
deploy:
|
||||||
|
|
@ -24,20 +27,12 @@ services:
|
||||||
count: all
|
count: all
|
||||||
capabilities: [gpu]
|
capabilities: [gpu]
|
||||||
ports:
|
ports:
|
||||||
- "127.0.0.1:7795:7860"
|
- "${TORTOISE_HOST_PORT:-7795}:7860"
|
||||||
- "127.0.0.1:7795:7860"
|
|
||||||
volumes:
|
volumes:
|
||||||
- /srv/appdata/tortoise/hf-cache:/cache/hf
|
- ${TORTOISE_DATA:-./data}/hf-cache:/cache/hf
|
||||||
- /srv/appdata/tortoise/models:/cache/tortoise-models
|
- ${TORTOISE_DATA:-./data}/models:/cache/tortoise-models
|
||||||
# Shared audio dir with f5/kokoro so skald serves all engines'
|
- ${AUDIO_DIR:-./data/audio}:/audio
|
||||||
# outputs through the same /audio route.
|
|
||||||
- /srv/appdata/f5-tts/audio:/audio
|
|
||||||
environment:
|
environment:
|
||||||
HF_HOME: /cache/hf
|
HF_HOME: /cache/hf
|
||||||
HF_HUB_DISABLE_TELEMETRY: "1"
|
HF_HUB_DISABLE_TELEMETRY: "1"
|
||||||
TORTOISE_MODELS_DIR: /cache/tortoise-models
|
TORTOISE_MODELS_DIR: /cache/tortoise-models
|
||||||
labels:
|
|
||||||
org.sulkta.domain: "sulkta"
|
|
||||||
org.sulkta.owner: "Sulkta"
|
|
||||||
org.sulkta.managed-by: "compose"
|
|
||||||
org.sulkta.role: "tortoise-tts"
|
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
"""Tortoise-TTS FastAPI server. Sibling to kokoro_server.
|
"""Tortoise-TTS FastAPI server. Sibling to the kokoro server.
|
||||||
|
|
||||||
Same /synthesize contract as the kokoro server so skald only has to
|
Same /synthesize contract as the kokoro server so skald only has to
|
||||||
route by voice.source. Differences:
|
route by voice.source. Differences:
|
||||||
|
|
@ -71,7 +71,7 @@ def _get_voice(name: str) -> tuple:
|
||||||
return _voice_cache[name]
|
return _voice_cache[name]
|
||||||
|
|
||||||
|
|
||||||
# ─── tag splitter (lifted from kokoro_server) ───────────────────
|
# ─── tag splitter (lifted from the kokoro server) ───────────────
|
||||||
|
|
||||||
|
|
||||||
class Node:
|
class Node:
|
||||||
|
|
@ -209,7 +209,7 @@ def _startup() -> None:
|
||||||
|
|
||||||
@app.get("/healthz")
|
@app.get("/healthz")
|
||||||
def healthz() -> dict:
|
def healthz() -> dict:
|
||||||
# Shape matches f5_server/kokoro_server so skald's HealthResponse
|
# Shape matches the f5-tts + kokoro servers so skald's HealthResponse
|
||||||
# struct deserializes all three.
|
# struct deserializes all three.
|
||||||
return {
|
return {
|
||||||
"ok": True,
|
"ok": True,
|
||||||
|
|
|
||||||
|
|
@ -1,14 +1,9 @@
|
||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
# Skald container entrypoint.
|
|
||||||
#
|
|
||||||
# Boots the embedded postgres via the pgvector image's own
|
# Boots the embedded postgres via the pgvector image's own
|
||||||
# docker-entrypoint, waits for it to accept connections, then execs
|
# docker-entrypoint, waits for it to accept connections, then execs
|
||||||
# `skald` in the foreground. Tini is PID 1 (so it can reap zombies +
|
# `skald` in the foreground. Tini is PID 1; postgres becomes our
|
||||||
# forward signals); we are PID 2; postgres becomes our child.
|
# child. When the DB is extracted to its own container, this reduces
|
||||||
#
|
# to `exec /usr/local/bin/skald "$@"`.
|
||||||
# This is explicitly "DB in the same container, for now" — when we
|
|
||||||
# split the DB out (see project notes), the entrypoint reduces to
|
|
||||||
# `exec /usr/local/bin/skald "$@"` and the pg startup goes away.
|
|
||||||
|
|
||||||
set -eo pipefail
|
set -eo pipefail
|
||||||
|
|
||||||
|
|
|
||||||
15
migrations/0008_chapter_rewrite.sql
Normal file
15
migrations/0008_chapter_rewrite.sql
Normal file
|
|
@ -0,0 +1,15 @@
|
||||||
|
-- The rewrite pass: an author re-authors existing chapter prose in
|
||||||
|
-- their own voice (canon preserved, prose reworked). body_md gets
|
||||||
|
-- overwritten with the rewritten version; body_md_original keeps
|
||||||
|
-- the pre-rewrite prose so the original is never lost. Populated
|
||||||
|
-- only on the FIRST rewrite of a chapter (if NULL) — subsequent
|
||||||
|
-- rewrites leave the original alone.
|
||||||
|
ALTER TABLE chapters
|
||||||
|
ADD COLUMN IF NOT EXISTS body_md_original text;
|
||||||
|
|
||||||
|
-- Allow 'rewrite' as a generation_runs.kind.
|
||||||
|
ALTER TABLE generation_runs
|
||||||
|
DROP CONSTRAINT generation_runs_kind_check;
|
||||||
|
ALTER TABLE generation_runs
|
||||||
|
ADD CONSTRAINT generation_runs_kind_check
|
||||||
|
CHECK (kind = ANY (ARRAY['gen', 'cleanup', 'audit', 'summary', 'embed', 'narrate_prep', 'rewrite']));
|
||||||
7
migrations/0009_story_audiobook.sql
Normal file
7
migrations/0009_story_audiobook.sql
Normal file
|
|
@ -0,0 +1,7 @@
|
||||||
|
-- A story can have a single stitched audiobook — all its chapter
|
||||||
|
-- renders concatenated into one chaptered file (see the m4b built
|
||||||
|
-- from per-chapter narration_runs). audiobook_path is the path the
|
||||||
|
-- web server serves it from (e.g. /audio/The-Coast-Down.m4b); NULL
|
||||||
|
-- means no audiobook has been stitched yet.
|
||||||
|
ALTER TABLE stories
|
||||||
|
ADD COLUMN IF NOT EXISTS audiobook_path text;
|
||||||
20
migrations/0010_prose_audit.sql
Normal file
20
migrations/0010_prose_audit.sql
Normal file
|
|
@ -0,0 +1,20 @@
|
||||||
|
-- The prose-quality audit pass: a QC gate that reads a finished
|
||||||
|
-- story end to end and flags repetition, template tics, self-
|
||||||
|
-- restatement and continuity drift before it goes to narration.
|
||||||
|
-- Repetition a silent reader skims is glaring once narrated aloud.
|
||||||
|
|
||||||
|
-- Allow 'prose_audit' as a generation_runs.kind.
|
||||||
|
ALTER TABLE generation_runs DROP CONSTRAINT generation_runs_kind_check;
|
||||||
|
ALTER TABLE generation_runs ADD CONSTRAINT generation_runs_kind_check
|
||||||
|
CHECK (kind = ANY (ARRAY[
|
||||||
|
'gen', 'cleanup', 'audit', 'summary', 'embed',
|
||||||
|
'narrate_prep', 'rewrite', 'prose_audit'
|
||||||
|
]));
|
||||||
|
|
||||||
|
-- 'repetition' is a first-class audit finding area.
|
||||||
|
ALTER TABLE audit_findings DROP CONSTRAINT audit_findings_area_check;
|
||||||
|
ALTER TABLE audit_findings ADD CONSTRAINT audit_findings_area_check
|
||||||
|
CHECK (area = ANY (ARRAY[
|
||||||
|
'character', 'continuity', 'tone', 'fact',
|
||||||
|
'timeline', 'repetition', 'other'
|
||||||
|
]));
|
||||||
9
migrations/0011_dedup_pass.sql
Normal file
9
migrations/0011_dedup_pass.sql
Normal file
|
|
@ -0,0 +1,9 @@
|
||||||
|
-- The dedup pass: the fix half of the audit loop. Takes a chapter
|
||||||
|
-- plus the story's prose-audit findings and rephrases only the
|
||||||
|
-- flagged repetitions, leaving everything else verbatim.
|
||||||
|
ALTER TABLE generation_runs DROP CONSTRAINT generation_runs_kind_check;
|
||||||
|
ALTER TABLE generation_runs ADD CONSTRAINT generation_runs_kind_check
|
||||||
|
CHECK (kind = ANY (ARRAY[
|
||||||
|
'gen', 'cleanup', 'audit', 'summary', 'embed',
|
||||||
|
'narrate_prep', 'rewrite', 'prose_audit', 'dedup'
|
||||||
|
]));
|
||||||
|
|
@ -8,24 +8,23 @@ use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
pub struct ForgeConfig {
|
pub struct ForgeConfig {
|
||||||
/// Base URL of the clawdforge HTTP service. Defaults to
|
/// Base URL of the clawdforge HTTP service. The calling binary
|
||||||
/// `http://clawdforge.example.local:8800` in production; override
|
/// resolves this from `CLAWDFORGE_URL`.
|
||||||
/// for tests via env.
|
|
||||||
pub base_url: String,
|
pub base_url: String,
|
||||||
|
|
||||||
/// App-level bearer token. Resolved by the binary from
|
/// App-level bearer token. Resolved by the binary from
|
||||||
/// `CLAWDFORGE_TOKEN`; should never be logged or `Display`ed.
|
/// `CLAWDFORGE_TOKEN`; should never be logged or `Display`ed.
|
||||||
pub app_token: String,
|
pub app_token: String,
|
||||||
|
|
||||||
/// Model alias passed to clawdforge → `claude -p --model`. Skald
|
/// Model alias passed to clawdforge → `claude -p --model`.
|
||||||
/// is opinionated: always opus max effort. Default reflects that.
|
/// Defaults to opus.
|
||||||
pub model: String,
|
pub model: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for ForgeConfig {
|
impl Default for ForgeConfig {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self {
|
Self {
|
||||||
base_url: "http://clawdforge.example.local:8800".into(),
|
base_url: "http://localhost:8800".into(),
|
||||||
app_token: String::new(),
|
app_token: String::new(),
|
||||||
model: "opus".into(),
|
model: "opus".into(),
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,7 @@
|
||||||
//!
|
//!
|
||||||
//! 1. **gen** — produces a new chapter draft from an assembled
|
//! 1. **gen** — produces a new chapter draft from an assembled
|
||||||
//! context blob (parent prose + bible + characters + similarity-
|
//! context blob (parent prose + bible + characters + similarity-
|
||||||
//! matched passages, all from the database). Opus, max effort.
|
//! matched passages, all from the database). Opus, high effort.
|
||||||
//!
|
//!
|
||||||
//! 2. **cleanup** — polishes the draft for prose quality, voice
|
//! 2. **cleanup** — polishes the draft for prose quality, voice
|
||||||
//! consistency, dialogue rhythm, pacing dead spots. Same Opus,
|
//! consistency, dialogue rhythm, pacing dead spots. Same Opus,
|
||||||
|
|
@ -43,8 +43,11 @@ use crate::config::ForgeConfig;
|
||||||
pub struct Forge {
|
pub struct Forge {
|
||||||
client: Client,
|
client: Client,
|
||||||
/// The model alias we pass to clawdforge. Skald is opinionated:
|
/// The model alias we pass to clawdforge. Skald is opinionated:
|
||||||
/// always opus max effort. (See `project_story_writer_container.md`.)
|
/// always opus. Story-writing passes (gen/cleanup/narrate_prep/
|
||||||
/// `clawdforge` resolves the alias to the actual claude CLI flag.
|
/// rewrite) run at HIGH effort; only the audit pass runs at MAX —
|
||||||
|
/// audit genuinely needs the frontier reasoning, prose-craft does
|
||||||
|
/// not, and the $200/mo `claude -p` cap makes max-everywhere
|
||||||
|
/// unaffordable. `clawdforge` resolves the alias to the CLI flag.
|
||||||
model: String,
|
model: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -74,6 +77,18 @@ pub enum PassKind {
|
||||||
/// prose; output should be byte-identical except for the
|
/// prose; output should be byte-identical except for the
|
||||||
/// tag insertions.
|
/// tag insertions.
|
||||||
NarratePrep,
|
NarratePrep,
|
||||||
|
/// Re-author existing chapter prose in an author's voice. Canon
|
||||||
|
/// (names, dates, events, places, facts) is preserved exactly;
|
||||||
|
/// the prose itself is rewritten. Not editing — re-authoring.
|
||||||
|
Rewrite,
|
||||||
|
/// Whole-story prose-quality audit — reads a finished story end
|
||||||
|
/// to end and flags repetition, template tics, self-restatement
|
||||||
|
/// and continuity drift. The QC gate before narration.
|
||||||
|
ProseAudit,
|
||||||
|
/// Surgical dedup — takes a chapter plus the story's audit
|
||||||
|
/// findings and rephrases only the flagged repetitions, leaving
|
||||||
|
/// everything else verbatim. The fix half of the audit loop.
|
||||||
|
Dedup,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl PassKind {
|
impl PassKind {
|
||||||
|
|
@ -84,6 +99,9 @@ impl PassKind {
|
||||||
Self::Audit => "audit",
|
Self::Audit => "audit",
|
||||||
Self::Summary => "summary",
|
Self::Summary => "summary",
|
||||||
Self::NarratePrep => "narrate_prep",
|
Self::NarratePrep => "narrate_prep",
|
||||||
|
Self::Rewrite => "rewrite",
|
||||||
|
Self::ProseAudit => "prose_audit",
|
||||||
|
Self::Dedup => "dedup",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -93,10 +111,12 @@ impl Forge {
|
||||||
let client = ClientBuilder::default()
|
let client = ClientBuilder::default()
|
||||||
.base_url(&cfg.base_url)
|
.base_url(&cfg.base_url)
|
||||||
.token(&cfg.app_token)
|
.token(&cfg.app_token)
|
||||||
// Generation passes at --effort max can run 10–20 min wall
|
// Generation passes at --effort max run 10–20 min wall clock;
|
||||||
// clock. clawdforge's server-side cap is 1800s — match it.
|
// the max-effort whole-book prose audit can run past an hour.
|
||||||
// Default 120s would strand any prose-craft pass.
|
// This is the client-side ceiling — set high enough to cover
|
||||||
.timeout(Duration::from_secs(1800))
|
// the slowest pass; each pass still sends its own server-side
|
||||||
|
// timeout_secs. Default 120s would strand any real pass.
|
||||||
|
.timeout(Duration::from_secs(7200))
|
||||||
.user_agent(concat!("skald/", env!("CARGO_PKG_VERSION")))
|
.user_agent(concat!("skald/", env!("CARGO_PKG_VERSION")))
|
||||||
.build()?;
|
.build()?;
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
|
|
@ -131,7 +151,7 @@ impl Forge {
|
||||||
model: Some(self.model.clone()),
|
model: Some(self.model.clone()),
|
||||||
system: Some(system),
|
system: Some(system),
|
||||||
system_mode: Some(mode),
|
system_mode: Some(mode),
|
||||||
effort: Some(Effort::Max),
|
effort: Some(Effort::High),
|
||||||
timeout_secs: Some(1800),
|
timeout_secs: Some(1800),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
};
|
};
|
||||||
|
|
@ -156,7 +176,7 @@ impl Forge {
|
||||||
model: Some(self.model.clone()),
|
model: Some(self.model.clone()),
|
||||||
system: Some(system),
|
system: Some(system),
|
||||||
system_mode: Some(mode),
|
system_mode: Some(mode),
|
||||||
effort: Some(Effort::Max),
|
effort: Some(Effort::High),
|
||||||
timeout_secs: Some(1800),
|
timeout_secs: Some(1800),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
};
|
};
|
||||||
|
|
@ -185,6 +205,75 @@ impl Forge {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Whole-story prose-quality audit. Receives every chapter of a
|
||||||
|
/// finished story concatenated in order and returns findings JSON
|
||||||
|
/// — repetition, template tics, self-restatement, continuity
|
||||||
|
/// drift. This is the QC gate before a story goes to narration,
|
||||||
|
/// where repetition a silent reader skims becomes glaring.
|
||||||
|
///
|
||||||
|
/// HIGH effort: finding repeated passages and motif reuse is
|
||||||
|
/// comparison work, not deep reasoning — high-effort Opus does it
|
||||||
|
/// well in minutes. A max-effort pass over a whole-book input
|
||||||
|
/// (quarter-million chars) runs an impractical hour-plus.
|
||||||
|
pub async fn prose_audit(&self, full_story: &str) -> anyhow::Result<PassOutput> {
|
||||||
|
let prompt = format!(
|
||||||
|
"Audit the complete story below for repetition, template tics, \
|
||||||
|
self-restatement and continuity errors. Read every chapter. \
|
||||||
|
Return JSON only, matching the schema in the system prompt.\n\n\
|
||||||
|
{full_story}"
|
||||||
|
);
|
||||||
|
let body = RunRequest {
|
||||||
|
prompt,
|
||||||
|
model: Some(self.model.clone()),
|
||||||
|
system: Some(SYSTEM_PROSE_AUDIT.to_string()),
|
||||||
|
effort: Some(Effort::High),
|
||||||
|
// High effort over a whole book lands in minutes; 3600s is
|
||||||
|
// a generous ceiling that won't bite.
|
||||||
|
timeout_secs: Some(3600),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let r = self.client.run(body).await?;
|
||||||
|
let duration_ms = r.duration_ms;
|
||||||
|
Ok(PassOutput { kind: PassKind::ProseAudit, result: r, duration_ms })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Surgical dedup of one chapter — the fix half of the audit
|
||||||
|
/// loop. Receives the chapter's prose plus the whole story's
|
||||||
|
/// audit findings, and rephrases ONLY the flagged repetitions
|
||||||
|
/// that occur in this chapter; everything the findings do not
|
||||||
|
/// flag stays verbatim. Author REQUIRED — the fresh phrasing
|
||||||
|
/// lands in the author's voice (SystemMode::Replace). High
|
||||||
|
/// effort: it is prose-craft, same posture as rewrite.
|
||||||
|
pub async fn dedup(
|
||||||
|
&self,
|
||||||
|
prose: &str,
|
||||||
|
findings: &str,
|
||||||
|
author: &AuthorWithRevision,
|
||||||
|
) -> anyhow::Result<PassOutput> {
|
||||||
|
let scaffold = author
|
||||||
|
.revision
|
||||||
|
.system_template
|
||||||
|
.as_deref()
|
||||||
|
.unwrap_or(DEFAULT_AUTHOR_SCAFFOLD);
|
||||||
|
let system = scaffold
|
||||||
|
.replace("{{display_name}}", &author.author.display_name)
|
||||||
|
.replace("{{pass_directive}}", DEDUP_DIRECTIVE)
|
||||||
|
.replace("{{soul}}", &author.revision.soul);
|
||||||
|
let user_prompt = dedup_user_prompt(prose, findings);
|
||||||
|
let body = RunRequest {
|
||||||
|
prompt: user_prompt,
|
||||||
|
model: Some(self.model.clone()),
|
||||||
|
system: Some(system),
|
||||||
|
system_mode: Some(SystemMode::Replace),
|
||||||
|
effort: Some(Effort::High),
|
||||||
|
timeout_secs: Some(1800),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let r = self.client.run(body).await?;
|
||||||
|
let duration_ms = r.duration_ms;
|
||||||
|
Ok(PassOutput { kind: PassKind::Dedup, result: r, duration_ms })
|
||||||
|
}
|
||||||
|
|
||||||
/// Annotate prose with narration control tags. The model
|
/// Annotate prose with narration control tags. The model
|
||||||
/// receives the full chapter prose and returns the SAME prose
|
/// receives the full chapter prose and returns the SAME prose
|
||||||
/// with `[pause:Xs]`, `[breath]`, `[scene]` markers inserted
|
/// with `[pause:Xs]`, `[breath]`, `[scene]` markers inserted
|
||||||
|
|
@ -192,10 +281,12 @@ impl Forge {
|
||||||
/// Orson Black places beats differently than another author
|
/// Orson Black places beats differently than another author
|
||||||
/// would. Replace-mode if author is set; Append otherwise.
|
/// would. Replace-mode if author is set; Append otherwise.
|
||||||
///
|
///
|
||||||
/// `characters` is the story's character roster. When provided,
|
/// `characters` is the story's character roster. When non-empty,
|
||||||
/// the system prompt instructs the model to wrap dialogue in
|
/// the system prompt instructs the model to wrap dialogue in
|
||||||
/// `[voice:<slug>]"..."[/voice]` for multi-voice rendering. The
|
/// `[voice:<slug>]"..."[/voice]` for multi-voice rendering; the
|
||||||
/// slug is mapped to a Kokoro voice id by skald's narrate path.
|
/// slug is mapped to a Kokoro voice id by skald's narrate path.
|
||||||
|
/// An EMPTY roster selects single-voice mode — the prompt then
|
||||||
|
/// forbids `[voice:...]` tags entirely (one narrator, no cast).
|
||||||
///
|
///
|
||||||
/// Hard rule the system prompt enforces: do not change a word
|
/// Hard rule the system prompt enforces: do not change a word
|
||||||
/// of prose. Tags are additive only.
|
/// of prose. Tags are additive only.
|
||||||
|
|
@ -205,6 +296,12 @@ impl Forge {
|
||||||
author: Option<&AuthorWithRevision>,
|
author: Option<&AuthorWithRevision>,
|
||||||
characters: &[CharacterSpeaker],
|
characters: &[CharacterSpeaker],
|
||||||
) -> anyhow::Result<PassOutput> {
|
) -> anyhow::Result<PassOutput> {
|
||||||
|
// An empty character roster means single-voice narration —
|
||||||
|
// the whole chapter reads in one voice. In that mode the
|
||||||
|
// prompt must NOT invite `[voice:...]` tags, or the model
|
||||||
|
// invents speaker slugs from names in the prose that the
|
||||||
|
// narrate path then has to detect and neutralize.
|
||||||
|
let single_voice = characters.is_empty();
|
||||||
let user_prompt = narrate_prep_user_prompt(prose, characters);
|
let user_prompt = narrate_prep_user_prompt(prose, characters);
|
||||||
let (system, mode) = match author {
|
let (system, mode) = match author {
|
||||||
Some(a) => {
|
Some(a) => {
|
||||||
|
|
@ -213,22 +310,34 @@ impl Forge {
|
||||||
.system_template
|
.system_template
|
||||||
.as_deref()
|
.as_deref()
|
||||||
.unwrap_or(DEFAULT_AUTHOR_SCAFFOLD);
|
.unwrap_or(DEFAULT_AUTHOR_SCAFFOLD);
|
||||||
|
let directive = if single_voice {
|
||||||
|
NARRATE_PREP_DIRECTIVE_SINGLE
|
||||||
|
} else {
|
||||||
|
NARRATE_PREP_DIRECTIVE
|
||||||
|
};
|
||||||
let composed = scaffold
|
let composed = scaffold
|
||||||
.replace("{{display_name}}", &a.author.display_name)
|
.replace("{{display_name}}", &a.author.display_name)
|
||||||
.replace("{{pass_directive}}", NARRATE_PREP_DIRECTIVE)
|
.replace("{{pass_directive}}", directive)
|
||||||
.replace("{{soul}}", &a.revision.soul);
|
.replace("{{soul}}", &a.revision.soul);
|
||||||
(composed, SystemMode::Replace)
|
(composed, SystemMode::Replace)
|
||||||
}
|
}
|
||||||
None => (HOUSE_NARRATE_PREP_SYSTEM.to_string(), SystemMode::Append),
|
None => {
|
||||||
|
let house = if single_voice {
|
||||||
|
HOUSE_NARRATE_PREP_SYSTEM_SINGLE
|
||||||
|
} else {
|
||||||
|
HOUSE_NARRATE_PREP_SYSTEM
|
||||||
|
};
|
||||||
|
(house.to_string(), SystemMode::Append)
|
||||||
|
}
|
||||||
};
|
};
|
||||||
let body = RunRequest {
|
let body = RunRequest {
|
||||||
prompt: user_prompt,
|
prompt: user_prompt,
|
||||||
model: Some(self.model.clone()),
|
model: Some(self.model.clone()),
|
||||||
system: Some(system),
|
system: Some(system),
|
||||||
system_mode: Some(mode),
|
system_mode: Some(mode),
|
||||||
// Tag placement IS a craft choice; max effort buys
|
// Tag placement IS a craft choice; high effort is
|
||||||
// better beat sense. Same posture as gen/cleanup.
|
// plenty for beat sense. Same posture as gen/cleanup.
|
||||||
effort: Some(Effort::Max),
|
effort: Some(Effort::High),
|
||||||
timeout_secs: Some(1800),
|
timeout_secs: Some(1800),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
};
|
};
|
||||||
|
|
@ -237,6 +346,46 @@ impl Forge {
|
||||||
Ok(PassOutput { kind: PassKind::NarratePrep, result: r, duration_ms })
|
Ok(PassOutput { kind: PassKind::NarratePrep, result: r, duration_ms })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Re-author existing chapter prose in the author's voice. The
|
||||||
|
/// model receives prose written by another hand and rewrites it
|
||||||
|
/// entirely in its own style — sentence rhythm, word choice,
|
||||||
|
/// paragraph shape all become the author's. Canon is preserved
|
||||||
|
/// exactly: names, dates, events, places, technical facts, and
|
||||||
|
/// the sequence of what happens do not change.
|
||||||
|
///
|
||||||
|
/// Author REQUIRED — a rewrite without an author has no target
|
||||||
|
/// voice. SystemMode::Replace; the model BECOMES the author.
|
||||||
|
/// High effort: re-authoring is heavy prose-craft, but it's
|
||||||
|
/// still craft, not reasoning — max is reserved for audit.
|
||||||
|
pub async fn rewrite(
|
||||||
|
&self,
|
||||||
|
prose: &str,
|
||||||
|
author: &AuthorWithRevision,
|
||||||
|
) -> anyhow::Result<PassOutput> {
|
||||||
|
let scaffold = author
|
||||||
|
.revision
|
||||||
|
.system_template
|
||||||
|
.as_deref()
|
||||||
|
.unwrap_or(DEFAULT_AUTHOR_SCAFFOLD);
|
||||||
|
let system = scaffold
|
||||||
|
.replace("{{display_name}}", &author.author.display_name)
|
||||||
|
.replace("{{pass_directive}}", REWRITE_DIRECTIVE)
|
||||||
|
.replace("{{soul}}", &author.revision.soul);
|
||||||
|
let user_prompt = rewrite_user_prompt(prose);
|
||||||
|
let body = RunRequest {
|
||||||
|
prompt: user_prompt,
|
||||||
|
model: Some(self.model.clone()),
|
||||||
|
system: Some(system),
|
||||||
|
system_mode: Some(SystemMode::Replace),
|
||||||
|
effort: Some(Effort::High),
|
||||||
|
timeout_secs: Some(1800),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let r = self.client.run(body).await?;
|
||||||
|
let duration_ms = r.duration_ms;
|
||||||
|
Ok(PassOutput { kind: PassKind::Rewrite, result: r, duration_ms })
|
||||||
|
}
|
||||||
|
|
||||||
/// Summarize one chapter to ~250 words. The summary feeds into
|
/// Summarize one chapter to ~250 words. The summary feeds into
|
||||||
/// the continuation context for older chapters so the token
|
/// the continuation context for older chapters so the token
|
||||||
/// budget stays sane on long series (book 12 doesn't carry book 1
|
/// budget stays sane on long series (book 12 doesn't carry book 1
|
||||||
|
|
@ -335,20 +484,38 @@ Hard rules:
|
||||||
{{soul}}
|
{{soul}}
|
||||||
"#;
|
"#;
|
||||||
|
|
||||||
const GEN_DIRECTIVE: &str = "This is a GENERATION pass. Write the next chapter from scratch. Honor canon. Begin with a chapter heading on the first line.";
|
const GEN_DIRECTIVE: &str = "This is a GENERATION pass. Write the next chapter from scratch. Honor canon. Begin with a chapter heading on the first line.\n\nGuard against repetition. If a recurring image, motif or descriptive beat appeared in an earlier chapter, render it in fresh words here — never reuse the same sentence shape or verb sequence for it. Do not stack consecutive sentences on one template (\"He thought… He thought…\", \"She felt… She felt…\"). Vary how you land beats. This will be read aloud by a single narrator, so phrasing a silent reader skims is glaring to a listener.";
|
||||||
|
|
||||||
const CLEANUP_DIRECTIVE: &str = "This is a CLEANUP pass. The user prompt contains a draft you wrote. Polish for prose quality — tighten dialogue, fix pacing dead spots, hold your voice steady. Do NOT add new plot, do NOT retcon canon. Return ONLY the polished chapter.";
|
const CLEANUP_DIRECTIVE: &str = "This is a CLEANUP pass. The user prompt contains a draft you wrote. Polish for prose quality — tighten dialogue, fix pacing dead spots, hold your voice steady. Do NOT add new plot, do NOT retcon canon.\n\nHunt repetition hard — this prose will be narrated aloud, where repetition is far more glaring than on the page. If a recurring image or motif appears more than once, re-phrase every occurrence so no two share a sentence shape or verb sequence. Do not stack more than two consecutive sentences on the same opening stem (\"He thought… He thought…\"). Echo a line of dialogue back verbatim at most once in the whole chapter. If a sentence merely restates something already said, cut it. Return ONLY the polished chapter.";
|
||||||
|
|
||||||
const HOUSE_GEN_SYSTEM: &str = "You are a long-form fiction author writing the next chapter of a series. Honor the canon (characters, setting, established facts) exactly. Return only the chapter prose, starting with a heading line. No preamble.";
|
const HOUSE_GEN_SYSTEM: &str = "You are a long-form fiction author writing the next chapter of a series. Honor the canon (characters, setting, established facts) exactly. Return only the chapter prose, starting with a heading line. No preamble.";
|
||||||
|
|
||||||
const HOUSE_CLEANUP_SYSTEM: &str = "You are a copy editor polishing a draft chapter. Tighten dialogue, fix pacing, keep voice consistent. Do not add new plot. Return only the polished chapter.";
|
const HOUSE_CLEANUP_SYSTEM: &str = "You are a copy editor polishing a draft chapter. Tighten dialogue, fix pacing, keep voice consistent. Do not add new plot. Return only the polished chapter.";
|
||||||
|
|
||||||
|
const SYSTEM_PROSE_AUDIT: &str = "You are a ruthless prose-quality auditor for long-form fiction destined for single-voice audiobook narration. You receive a complete story — every chapter, in order — and you read all of it. You return STRUCTURED JSON ONLY: no commentary, no preamble. You hunt four things:\n\n1. REPETITION across the whole book: a recurring image, motif or descriptive beat rendered in near-identical wording more than once; a sentence (or near-identical sentence) reused in different chapters; a line of dialogue echoed verbatim.\n2. TEMPLATE TICS: the same sentence template stacked or over-reused — e.g. clusters of consecutive sentences all opening 'He thought:' / 'She felt:' — anywhere it becomes a noticeable pattern.\n3. SELF-RESTATEMENT: a sentence or paragraph that says again, slightly reworded, something the text already said.\n4. CONTINUITY ERRORS: a fact, name, age, date or detail that contradicts an earlier one.\n\nThis prose will be read ALOUD by one narrator, so repetition a silent reader skims is glaring to a listener — be exhaustive, do not let near-duplicates pass. Return EXACTLY this shape: { \"findings\": [ { \"severity\": \"info\"|\"warn\"|\"crit\", \"area\": \"repetition\"|\"continuity\"|\"other\", \"body\": \"...\" } ] }. In each finding's body, quote the offending text exactly and name the chapter number(s). Use 'crit' for anything a listener will plainly hear as a mistake, 'warn' for noticeable repetition, 'info' for minor. If the story is clean, return { \"findings\": [] }.";
|
||||||
|
|
||||||
const SYSTEM_AUDIT: &str = "You are a canon auditor for long-form fiction. You compare a parent story and a new chapter against the bible. You flag continuity drift, character voice shift, retconned facts, dropped threads, timeline contradictions. You return STRUCTURED JSON ONLY — no commentary, no preamble. The exact shape: { \"findings\": [ { \"severity\": \"info\"|\"warn\"|\"crit\", \"area\": \"character\"|\"continuity\"|\"tone\"|\"fact\"|\"timeline\"|\"other\", \"body\": \"...\" } ] }. If no findings, return { \"findings\": [] }.";
|
const SYSTEM_AUDIT: &str = "You are a canon auditor for long-form fiction. You compare a parent story and a new chapter against the bible. You flag continuity drift, character voice shift, retconned facts, dropped threads, timeline contradictions. You return STRUCTURED JSON ONLY — no commentary, no preamble. The exact shape: { \"findings\": [ { \"severity\": \"info\"|\"warn\"|\"crit\", \"area\": \"character\"|\"continuity\"|\"tone\"|\"fact\"|\"timeline\"|\"other\", \"body\": \"...\" } ] }. If no findings, return { \"findings\": [] }.";
|
||||||
|
|
||||||
const NARRATE_PREP_DIRECTIVE: &str = "This is a NARRATION-ANNOTATION pass. You receive your own prose and prepare it for an audiobook reading. Three kinds of inserts are allowed:\n\n1. BEAT MARKERS (additive, not prose): `[breath]` (~400ms), `[pause:1.2s]` (explicit silence in seconds, e.g. 0.5s, 1.2s, 2s), `[scene]` (~1500ms scene break). Place where the prose's rhythm asks for them — after a hard one-line beat, before a turn in dialogue, on a paragraph that lands with weight.\n\n2. SPEAKER VOICE TAGS (multi-voice dialogue): wrap dialogue lines in `[voice:<slug>]\"...\"[/voice]` based on who is speaking. The roster of available speaker slugs is given in the user prompt. The dialogue itself stays verbatim — only the wrapper is added. If a line of dialogue is not clearly attributable to a roster speaker, leave it unwrapped (the narrator voice will read it). Quoted thoughts (italicized interior monologue) stay unwrapped — only spoken aloud dialogue gets a voice tag.\n\n3. NARRATOR STUMBLES (humanizing prose-level inserts): a real narrator occasionally stumbles on a hard word, catches themselves, repeats. You may add these *sparingly* where the prose's pacing makes them feel right. Patterns: em-dash repetition (`Prip— Pripyat`), self-correction (`she — no, the wife — had been told`), hesitation (`the dose, the dose was`). USE SPARINGLY. Maybe 1-3 per chapter. Pick proper nouns, technical terms, or moments where the narrator might genuinely catch herself. Avoid stumbling on emotional climaxes — those should land clean.\n\nApart from stumbles, do NOT change a word of the original prose. Return the prose with beat markers, voice tags, and stumbles inline. No preamble. No commentary about your choices.";
|
const NARRATE_PREP_DIRECTIVE: &str = "This is a NARRATION-ANNOTATION pass. You receive your own prose and prepare it for an audiobook reading. Three kinds of inserts are allowed:\n\n1. BEAT MARKERS (additive, not prose): `[breath]` (~400ms), `[pause:1.2s]` (explicit silence in seconds, e.g. 0.5s, 1.2s, 2s), `[scene]` (~1500ms scene break). Place where the prose's rhythm asks for them — after a hard one-line beat, before a turn in dialogue, on a paragraph that lands with weight.\n\n2. SPEAKER VOICE TAGS (multi-voice dialogue): wrap dialogue lines in `[voice:<slug>]\"...\"[/voice]` based on who is speaking. The roster of available speaker slugs is given in the user prompt. The dialogue itself stays verbatim — only the wrapper is added. If a line of dialogue is not clearly attributable to a roster speaker, leave it unwrapped (the narrator voice will read it). Quoted thoughts (italicized interior monologue) stay unwrapped — only spoken aloud dialogue gets a voice tag.\n\n3. NARRATOR STUMBLES (humanizing prose-level inserts): a real narrator occasionally stumbles on a hard word, catches themselves, repeats. You may add these *sparingly* where the prose's pacing makes them feel right. Patterns: em-dash repetition (`Prip— Pripyat`), self-correction (`she — no, the wife — had been told`), hesitation (`the dose, the dose was`). USE SPARINGLY. Maybe 1-3 per chapter. Pick proper nouns, technical terms, or moments where the narrator might genuinely catch herself. Avoid stumbling on emotional climaxes — those should land clean.\n\nApart from stumbles, do NOT change a word of the original prose. Return the prose with beat markers, voice tags, and stumbles inline. No preamble. No commentary about your choices.";
|
||||||
|
|
||||||
|
/// Single-voice variant of [`NARRATE_PREP_DIRECTIVE`]. Used when the
|
||||||
|
/// chapter narrates in one voice (no speaker roster). The multi-voice
|
||||||
|
/// directive's section 2 is dropped entirely AND a hard prohibition
|
||||||
|
/// is added — without it the model invents `[voice:<slug>]` tags from
|
||||||
|
/// character names in the prose, which the narrate path then has to
|
||||||
|
/// detect and neutralize.
|
||||||
|
const NARRATE_PREP_DIRECTIVE_SINGLE: &str = "This is a NARRATION-ANNOTATION pass. You receive your own prose and prepare it for a SINGLE-narrator audiobook reading — the whole chapter, dialogue included, is read aloud in ONE voice. Two kinds of inserts are allowed:\n\n1. BEAT MARKERS (additive, not prose): `[breath]` (~400ms), `[pause:1.2s]` (explicit silence in seconds, e.g. 0.5s, 1.2s, 2s), `[scene]` (~1500ms scene break). Place where the prose's rhythm asks for them — after a hard one-line beat, before a turn in dialogue, on a paragraph that lands with weight.\n\n2. NARRATOR STUMBLES (humanizing prose-level inserts): a real narrator occasionally stumbles on a hard word, catches themselves, repeats. You may add these *sparingly* where the prose's pacing makes them feel right. Patterns: em-dash repetition (`Prip— Pripyat`), self-correction (`she — no, the wife — had been told`), hesitation (`the dose, the dose was`). USE SPARINGLY. Maybe 1-3 per chapter. Pick proper nouns, technical terms, or moments where the narrator might genuinely catch herself. Avoid stumbling on emotional climaxes — those should land clean.\n\nDo NOT add `[voice:...]` speaker tags of any kind — there is one narrator, not a cast. Apart from stumbles, do NOT change a word of the original prose. Return the prose with beat markers and stumbles inline. No preamble. No commentary about your choices.";
|
||||||
|
|
||||||
const HOUSE_NARRATE_PREP_SYSTEM: &str = "You are a senior audiobook director annotating prose for narration. You insert (a) beat markers — `[breath]`, `[pause:Xs]`, `[scene]` — where a skilled narrator would breathe or pause, (b) speaker voice tags `[voice:<slug>]\"...\"[/voice]` wrapping dialogue based on who is speaking (roster supplied in user prompt; leave unattributed dialogue unwrapped), and (c) occasional humanizing narrator stumbles using em-dash repetition or self-correction (sparingly — maybe 1-3 per chapter, on proper nouns or hard words). Apart from those stumbles you do NOT change a word of the prose. Return the prose verbatim plus beat markers, voice tags, and (rare) stumbles inline. No preamble, no commentary.";
|
const HOUSE_NARRATE_PREP_SYSTEM: &str = "You are a senior audiobook director annotating prose for narration. You insert (a) beat markers — `[breath]`, `[pause:Xs]`, `[scene]` — where a skilled narrator would breathe or pause, (b) speaker voice tags `[voice:<slug>]\"...\"[/voice]` wrapping dialogue based on who is speaking (roster supplied in user prompt; leave unattributed dialogue unwrapped), and (c) occasional humanizing narrator stumbles using em-dash repetition or self-correction (sparingly — maybe 1-3 per chapter, on proper nouns or hard words). Apart from those stumbles you do NOT change a word of the prose. Return the prose verbatim plus beat markers, voice tags, and (rare) stumbles inline. No preamble, no commentary.";
|
||||||
|
|
||||||
|
/// Single-voice variant of [`HOUSE_NARRATE_PREP_SYSTEM`] — no speaker
|
||||||
|
/// voice tags, one narrator throughout.
|
||||||
|
const HOUSE_NARRATE_PREP_SYSTEM_SINGLE: &str = "You are a senior audiobook director annotating prose for a SINGLE-narrator reading. You insert (a) beat markers — `[breath]`, `[pause:Xs]`, `[scene]` — where a skilled narrator would breathe or pause, and (b) occasional humanizing narrator stumbles using em-dash repetition or self-correction (sparingly — maybe 1-3 per chapter, on proper nouns or hard words). Do NOT add `[voice:...]` speaker tags — the whole chapter is one voice. Apart from those stumbles you do NOT change a word of the prose. Return the prose verbatim plus beat markers and (rare) stumbles inline. No preamble, no commentary.";
|
||||||
|
|
||||||
|
const DEDUP_DIRECTIVE: &str = "This is a DEDUP pass. The user prompt contains ONE chapter of a story you wrote, plus a list of audit findings — repeated phrases, motifs, similes, sentence templates and continuity errors found across the whole book. Your job: return this chapter with every flagged repetition that occurs IN IT rephrased fresh, and everything else byte-identical.\n\nHARD RULES:\n- For any motif, simile, phrase, image or structural tic the findings flag as recurring: if it appears in THIS chapter, render this chapter's occurrence in fresh, distinctive wording. Never reuse the flagged original phrasing. The other chapters' occurrences are being revised separately — do NOT try to coordinate with them; just make yours distinct from the flagged original.\n- Fix any continuity error the findings flag that touches this chapter (a wrong age, number, name, date) — use the correct value the findings identify.\n- Change NOTHING the findings do not flag. Every sentence not implicated by a finding stays EXACTLY as written, word for word. This is not a rewrite, not a polish, not an edit for taste — it is a surgical dedup. When in doubt, leave it.\n- Canon is absolute: names, dates, events, the order they happen, every fact — unchanged. The chapter stays the same length and shape.\n- Return ONLY the chapter prose. No heading unless the source had one. No preamble, no commentary, no list of what you changed.\n\n";
|
||||||
|
|
||||||
|
const REWRITE_DIRECTIVE: &str = "This is a REWRITE pass. The user prompt contains a chapter of prose written by another hand. Re-author it entirely in YOUR voice — every sentence reworked in your style: your sentence rhythm, your word choice, your paragraph shape, your way of landing a beat. This is not editing or polishing. It is re-authoring. The reader should not be able to tell another writer ever touched it.\n\nHARD CONSTRAINTS — canon is non-negotiable:\n- Every character name, every date, every place name stays exactly as written.\n- Every event, and the ORDER events happen in, stays exactly as written.\n- Every technical or historical fact stays exactly as written.\n- Do not add new scenes, characters, or events. Do not cut any scene or beat. Same story, same shape — your telling.\n\nReturn ONLY the rewritten chapter prose. Begin with the chapter heading line (`## Chapter N — title`) exactly as in the source. No preamble, no commentary about the rewrite.";
|
||||||
|
|
||||||
// ─── User-prompt builders ───────────────────────────────────────
|
// ─── User-prompt builders ───────────────────────────────────────
|
||||||
|
|
||||||
fn gen_user_prompt(
|
fn gen_user_prompt(
|
||||||
|
|
@ -395,6 +562,38 @@ pub struct CharacterSpeaker {
|
||||||
pub hint: Option<String>,
|
pub hint: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn dedup_user_prompt(prose: &str, findings: &str) -> String {
|
||||||
|
let mut out = String::with_capacity(prose.len() + findings.len() + 512);
|
||||||
|
out.push_str("# Audit findings for this story\n\n");
|
||||||
|
out.push_str(
|
||||||
|
"These repetitions and errors were found across the whole book. \
|
||||||
|
Fix only the ones that occur in the chapter below.\n\n",
|
||||||
|
);
|
||||||
|
out.push_str(findings);
|
||||||
|
out.push_str("\n\n# Chapter to dedup\n\n");
|
||||||
|
out.push_str(prose);
|
||||||
|
out.push_str(
|
||||||
|
"\n\n# Task\n\nReturn the chapter above with every flagged repetition \
|
||||||
|
that appears in it rephrased fresh, and any flagged continuity error \
|
||||||
|
touching it corrected. Leave every unflagged sentence verbatim. \
|
||||||
|
Return only the chapter prose.\n",
|
||||||
|
);
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rewrite_user_prompt(prose: &str) -> String {
|
||||||
|
let mut out = String::with_capacity(prose.len() + 256);
|
||||||
|
out.push_str("# Chapter to re-author\n\n");
|
||||||
|
out.push_str(prose);
|
||||||
|
out.push_str(
|
||||||
|
"\n\n# Task\n\nRe-author the chapter above entirely in your voice. \
|
||||||
|
Preserve all canon — names, dates, places, events, the order they \
|
||||||
|
happen, every technical fact. Change only the prose. Return only \
|
||||||
|
the rewritten chapter, starting with its `## Chapter N` heading.\n",
|
||||||
|
);
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
fn narrate_prep_user_prompt(prose: &str, characters: &[CharacterSpeaker]) -> String {
|
fn narrate_prep_user_prompt(prose: &str, characters: &[CharacterSpeaker]) -> String {
|
||||||
let mut out = String::with_capacity(prose.len() + 512);
|
let mut out = String::with_capacity(prose.len() + 512);
|
||||||
|
|
||||||
|
|
@ -424,12 +623,22 @@ fn narrate_prep_user_prompt(prose: &str, characters: &[CharacterSpeaker]) -> Str
|
||||||
|
|
||||||
out.push_str("# Prose to annotate\n\n");
|
out.push_str("# Prose to annotate\n\n");
|
||||||
out.push_str(prose);
|
out.push_str(prose);
|
||||||
|
if characters.is_empty() {
|
||||||
|
out.push_str(
|
||||||
|
"\n\n# Task\n\nReturn the prose above with `[breath]`, `[pause:Xs]`, \
|
||||||
|
`[scene]` beat markers inserted appropriately. Do NOT add any \
|
||||||
|
`[voice:...]` tags — this is a single-voice reading. Do not \
|
||||||
|
change any word. Do not skip any sentence. Return only the \
|
||||||
|
annotated prose.\n",
|
||||||
|
);
|
||||||
|
} else {
|
||||||
out.push_str(
|
out.push_str(
|
||||||
"\n\n# Task\n\nReturn the prose above with `[breath]`, `[pause:Xs]`, \
|
"\n\n# Task\n\nReturn the prose above with `[breath]`, `[pause:Xs]`, \
|
||||||
`[scene]` markers and `[voice:<slug>]\"...\"[/voice]` dialogue wrappers \
|
`[scene]` markers and `[voice:<slug>]\"...\"[/voice]` dialogue wrappers \
|
||||||
inserted appropriately. Do not change any word. Do not skip any \
|
inserted appropriately. Do not change any word. Do not skip any \
|
||||||
sentence. Return only the annotated prose.\n",
|
sentence. Return only the annotated prose.\n",
|
||||||
);
|
);
|
||||||
|
}
|
||||||
out
|
out
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -457,6 +666,10 @@ fn build_audit_request(model: &str, parent: &str, sequel: &str, bible: &str) ->
|
||||||
prompt,
|
prompt,
|
||||||
model: Some(model.to_string()),
|
model: Some(model.to_string()),
|
||||||
system: Some(SYSTEM_AUDIT.to_string()),
|
system: Some(SYSTEM_AUDIT.to_string()),
|
||||||
|
// Audit is the one pass that keeps MAX effort — catching
|
||||||
|
// canon drift, timeline gaps and retcons is reasoning work
|
||||||
|
// worth the frontier spend; prose-craft passes run at high.
|
||||||
|
effort: Some(Effort::Max),
|
||||||
timeout_secs: Some(600),
|
timeout_secs: Some(600),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -27,7 +27,7 @@ use uuid::Uuid;
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct F5Config {
|
pub struct F5Config {
|
||||||
/// e.g. http://127.0.0.1:7792
|
/// e.g. http://localhost:7792
|
||||||
pub base_url: String,
|
pub base_url: String,
|
||||||
/// Inference subprocess timeout. Long-form chapters (3000 words)
|
/// Inference subprocess timeout. Long-form chapters (3000 words)
|
||||||
/// take 60-180s on an 8GB GPU; cap at 1800s to match clawdforge.
|
/// take 60-180s on an 8GB GPU; cap at 1800s to match clawdforge.
|
||||||
|
|
|
||||||
144
skald/src/audit.rs
Normal file
144
skald/src/audit.rs
Normal file
|
|
@ -0,0 +1,144 @@
|
||||||
|
//! `skald audit` — whole-story prose-quality audit. Reads every
|
||||||
|
//! chapter of a story end to end and flags repetition, template
|
||||||
|
//! tics, self-restatement and continuity drift. The QC gate before
|
||||||
|
//! a story goes to narration, where repetition a silent reader
|
||||||
|
//! skims becomes glaring once read aloud.
|
||||||
|
//!
|
||||||
|
//! Findings land in the `audit_findings` table (area 'repetition' /
|
||||||
|
//! 'continuity' / 'other') and are printed to stdout. v1 flags
|
||||||
|
//! only — acting on the findings (a fix pass) is a separate step.
|
||||||
|
|
||||||
|
use std::time::Instant;
|
||||||
|
|
||||||
|
use anyhow::{Context, bail};
|
||||||
|
use chrono::Utc;
|
||||||
|
use skald_core::config::ForgeConfig;
|
||||||
|
use skald_core::db;
|
||||||
|
use skald_core::forge::{AuditFinding, AuditResponse, Forge, PassKind, PassOutput};
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
pub async fn run(database_url: &str, story_id: Uuid) -> anyhow::Result<()> {
|
||||||
|
let cfg = load_forge_config()?;
|
||||||
|
tracing::info!(base_url = %cfg.base_url, model = %cfg.model, "forge configured");
|
||||||
|
|
||||||
|
let pool = db::connect_and_migrate(database_url).await?;
|
||||||
|
let forge = Forge::new(&cfg)?;
|
||||||
|
|
||||||
|
let title: String = sqlx::query_scalar("SELECT title FROM stories WHERE id = $1")
|
||||||
|
.bind(story_id)
|
||||||
|
.fetch_optional(&pool)
|
||||||
|
.await?
|
||||||
|
.with_context(|| format!("story {story_id} not found"))?;
|
||||||
|
|
||||||
|
let chapters: Vec<(i32, Option<String>, String)> = sqlx::query_as(
|
||||||
|
"SELECT n, title, body_md FROM chapters WHERE story_id = $1 ORDER BY n",
|
||||||
|
)
|
||||||
|
.bind(story_id)
|
||||||
|
.fetch_all(&pool)
|
||||||
|
.await?;
|
||||||
|
if chapters.is_empty() {
|
||||||
|
bail!("story {story_id} has no chapters to audit");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Concatenate the whole story in chapter order — the audit needs
|
||||||
|
// to see across chapter boundaries to catch cross-chapter reuse.
|
||||||
|
let mut full = String::new();
|
||||||
|
for (n, ct, body) in &chapters {
|
||||||
|
full.push_str(&format!(
|
||||||
|
"## Chapter {n} — {}\n\n",
|
||||||
|
ct.as_deref().unwrap_or("")
|
||||||
|
));
|
||||||
|
full.push_str(body);
|
||||||
|
full.push_str("\n\n");
|
||||||
|
}
|
||||||
|
tracing::info!(
|
||||||
|
story = %title,
|
||||||
|
chapters = chapters.len(),
|
||||||
|
chars = full.len(),
|
||||||
|
"prose audit starting",
|
||||||
|
);
|
||||||
|
|
||||||
|
let run_id: Uuid = sqlx::query_scalar(
|
||||||
|
"INSERT INTO generation_runs (story_id, kind, status) VALUES ($1, $2, 'running') RETURNING id",
|
||||||
|
)
|
||||||
|
.bind(story_id)
|
||||||
|
.bind(PassKind::ProseAudit.as_str())
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let started = Instant::now();
|
||||||
|
let out_res = forge.prose_audit(&full).await;
|
||||||
|
let elapsed = started.elapsed();
|
||||||
|
|
||||||
|
let out: PassOutput = match out_res {
|
||||||
|
Ok(o) => o,
|
||||||
|
Err(e) => {
|
||||||
|
sqlx::query(
|
||||||
|
"UPDATE generation_runs SET status='failed', error=$1, ended_at=$2 WHERE id=$3",
|
||||||
|
)
|
||||||
|
.bind(format!("{e:#}"))
|
||||||
|
.bind(Utc::now())
|
||||||
|
.bind(run_id)
|
||||||
|
.execute(&pool)
|
||||||
|
.await?;
|
||||||
|
return Err(e);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let findings = parse_findings(&out);
|
||||||
|
for f in &findings {
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO audit_findings (story_id, run_id, severity, area, body)
|
||||||
|
VALUES ($1, $2, $3, $4, $5)",
|
||||||
|
)
|
||||||
|
.bind(story_id)
|
||||||
|
.bind(run_id)
|
||||||
|
.bind(&f.severity)
|
||||||
|
.bind(&f.area)
|
||||||
|
.bind(&f.body)
|
||||||
|
.execute(&pool)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
sqlx::query("UPDATE generation_runs SET status='succeeded', ended_at=$1 WHERE id=$2")
|
||||||
|
.bind(Utc::now())
|
||||||
|
.bind(run_id)
|
||||||
|
.execute(&pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let crit = findings.iter().filter(|f| f.severity == "crit").count();
|
||||||
|
let warn = findings.iter().filter(|f| f.severity == "warn").count();
|
||||||
|
let info = findings.iter().filter(|f| f.severity == "info").count();
|
||||||
|
println!(
|
||||||
|
"prose audit: \"{title}\" — {} finding(s): {crit} crit, {warn} warn, {info} info ({:.1}s)",
|
||||||
|
findings.len(),
|
||||||
|
elapsed.as_secs_f32(),
|
||||||
|
);
|
||||||
|
for f in &findings {
|
||||||
|
println!("\n[{} · {}]\n{}", f.severity.to_uppercase(), f.area, f.body);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_findings(out: &PassOutput) -> Vec<AuditFinding> {
|
||||||
|
if let Ok(typed) = out.result.as_json::<AuditResponse>() {
|
||||||
|
return typed.findings;
|
||||||
|
}
|
||||||
|
if let Some(s) = out.result.as_text() {
|
||||||
|
if let Ok(typed) = serde_json::from_str::<AuditResponse>(s) {
|
||||||
|
return typed.findings;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tracing::warn!("prose audit output did not parse as AuditResponse — no findings recorded");
|
||||||
|
Vec::new()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn load_forge_config() -> anyhow::Result<ForgeConfig> {
|
||||||
|
let base_url = std::env::var("CLAWDFORGE_URL").context("CLAWDFORGE_URL not set")?;
|
||||||
|
let app_token = std::env::var("CLAWDFORGE_TOKEN").context("CLAWDFORGE_TOKEN not set")?;
|
||||||
|
let model = std::env::var("SKALD_MODEL").unwrap_or_else(|_| "opus".into());
|
||||||
|
Ok(ForgeConfig {
|
||||||
|
base_url,
|
||||||
|
app_token,
|
||||||
|
model,
|
||||||
|
})
|
||||||
|
}
|
||||||
271
skald/src/dedup.rs
Normal file
271
skald/src/dedup.rs
Normal file
|
|
@ -0,0 +1,271 @@
|
||||||
|
//! `skald dedup` — the fix half of the audit loop. Reads a story's
|
||||||
|
//! most recent prose-audit findings and walks the chapters, handing
|
||||||
|
//! each chapter + the findings to the author with instructions to
|
||||||
|
//! rephrase ONLY the flagged repetitions and leave everything else
|
||||||
|
//! verbatim. Overwrites body_md and clears body_md_tts so the
|
||||||
|
//! chapter gets re-prepped before narration.
|
||||||
|
//!
|
||||||
|
//! Run `skald audit` first — dedup needs findings to act on.
|
||||||
|
|
||||||
|
use std::time::Instant;
|
||||||
|
|
||||||
|
use anyhow::{Context, bail};
|
||||||
|
use chrono::Utc;
|
||||||
|
use skald_core::authors::{self, AuthorWithRevision};
|
||||||
|
use skald_core::config::ForgeConfig;
|
||||||
|
use skald_core::db;
|
||||||
|
use skald_core::forge::{Forge, PassKind, PassOutput};
|
||||||
|
use sqlx::PgPool;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
pub async fn run(
|
||||||
|
database_url: &str,
|
||||||
|
story_id: Uuid,
|
||||||
|
author_slug: Option<&str>,
|
||||||
|
chapter_filter: Option<i32>,
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
|
let cfg = load_forge_config()?;
|
||||||
|
tracing::info!(base_url = %cfg.base_url, model = %cfg.model, "forge configured");
|
||||||
|
|
||||||
|
let pool = db::connect_and_migrate(database_url).await?;
|
||||||
|
let forge = Forge::new(&cfg)?;
|
||||||
|
|
||||||
|
let story: Option<(String, Option<Uuid>)> =
|
||||||
|
sqlx::query_as("SELECT title, author_id FROM stories WHERE id = $1")
|
||||||
|
.bind(story_id)
|
||||||
|
.fetch_optional(&pool)
|
||||||
|
.await?;
|
||||||
|
let (title, story_author_id) =
|
||||||
|
story.with_context(|| format!("story {story_id} not found"))?;
|
||||||
|
|
||||||
|
let author = resolve_author(&pool, story_author_id, author_slug)
|
||||||
|
.await?
|
||||||
|
.ok_or_else(|| {
|
||||||
|
anyhow::anyhow!(
|
||||||
|
"dedup needs an author for the rephrasing — pass --author <slug> \
|
||||||
|
or bind one to the story"
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
|
||||||
|
// Findings from the most recent succeeded prose-audit run.
|
||||||
|
let findings = load_latest_findings(&pool, story_id).await?;
|
||||||
|
if findings.is_empty() {
|
||||||
|
bail!(
|
||||||
|
"no prose-audit findings for story {story_id} — run `skald audit \
|
||||||
|
--story {story_id}` first"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let findings_block = render_findings(&findings);
|
||||||
|
tracing::info!(
|
||||||
|
story = %title,
|
||||||
|
author = %author.author.slug,
|
||||||
|
finding_count = findings.len(),
|
||||||
|
"dedup starting",
|
||||||
|
);
|
||||||
|
|
||||||
|
let mut chapters: Vec<(Uuid, i32)> = sqlx::query_as(
|
||||||
|
"SELECT id, n FROM chapters WHERE story_id = $1 ORDER BY n",
|
||||||
|
)
|
||||||
|
.bind(story_id)
|
||||||
|
.fetch_all(&pool)
|
||||||
|
.await?;
|
||||||
|
if chapters.is_empty() {
|
||||||
|
bail!("story {story_id} has no chapters");
|
||||||
|
}
|
||||||
|
// --chapter narrows the run to one chapter — used to retry a
|
||||||
|
// chapter the length guard skipped on an earlier run.
|
||||||
|
if let Some(target) = chapter_filter {
|
||||||
|
chapters.retain(|(_, n)| *n == target);
|
||||||
|
if chapters.is_empty() {
|
||||||
|
bail!("chapter {target} not found in story {story_id}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut skipped = 0usize;
|
||||||
|
for (chapter_id, n) in &chapters {
|
||||||
|
let body_md: String =
|
||||||
|
sqlx::query_scalar("SELECT body_md FROM chapters WHERE id = $1")
|
||||||
|
.bind(chapter_id)
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let run_id: Uuid = sqlx::query_scalar(
|
||||||
|
"INSERT INTO generation_runs (story_id, kind, status) VALUES ($1, $2, 'running') RETURNING id",
|
||||||
|
)
|
||||||
|
.bind(story_id)
|
||||||
|
.bind(PassKind::Dedup.as_str())
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let started = Instant::now();
|
||||||
|
let out_res = forge.dedup(&body_md, &findings_block, &author).await;
|
||||||
|
let elapsed = started.elapsed();
|
||||||
|
|
||||||
|
let out: PassOutput = match out_res {
|
||||||
|
Ok(o) => o,
|
||||||
|
Err(e) => {
|
||||||
|
sqlx::query(
|
||||||
|
"UPDATE generation_runs SET status='failed', error=$1, ended_at=$2 WHERE id=$3",
|
||||||
|
)
|
||||||
|
.bind(format!("{e:#}"))
|
||||||
|
.bind(Utc::now())
|
||||||
|
.bind(run_id)
|
||||||
|
.execute(&pool)
|
||||||
|
.await?;
|
||||||
|
return Err(e).with_context(|| format!("dedup failed on chapter {n}"));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let deduped = pass_text(&out)?;
|
||||||
|
|
||||||
|
// Sanity guard: a surgical dedup nudges a chapter's length by
|
||||||
|
// a little. An output wildly off the input means the model
|
||||||
|
// duplicated or ballooned the chapter — reject it, leave the
|
||||||
|
// chapter untouched, move on. A re-run with --chapter retries
|
||||||
|
// just the skipped one.
|
||||||
|
let before = body_md.len();
|
||||||
|
let after = deduped.len();
|
||||||
|
if after > before * 3 / 2 || after < before * 3 / 5 {
|
||||||
|
sqlx::query(
|
||||||
|
"UPDATE generation_runs SET status='failed', error=$1, ended_at=$2 WHERE id=$3",
|
||||||
|
)
|
||||||
|
.bind(format!(
|
||||||
|
"rejected: dedup output {after}c is wildly off input {before}c \
|
||||||
|
— likely a duplicated or ballooned output"
|
||||||
|
))
|
||||||
|
.bind(Utc::now())
|
||||||
|
.bind(run_id)
|
||||||
|
.execute(&pool)
|
||||||
|
.await?;
|
||||||
|
skipped += 1;
|
||||||
|
println!(
|
||||||
|
"SKIPPED chapter {n}: dedup returned {after}c from {before}c \
|
||||||
|
— chapter left untouched (retry with --chapter {n})"
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Overwrite body_md and clear body_md_tts — the chapter must be
|
||||||
|
// re-prepped before it is narrated again. body_md_original is
|
||||||
|
// left untouched (it belongs to the rewrite pass).
|
||||||
|
sqlx::query("UPDATE chapters SET body_md = $1, body_md_tts = NULL WHERE id = $2")
|
||||||
|
.bind(&deduped)
|
||||||
|
.bind(chapter_id)
|
||||||
|
.execute(&pool)
|
||||||
|
.await?;
|
||||||
|
sqlx::query("UPDATE generation_runs SET status='succeeded', ended_at=$1 WHERE id=$2")
|
||||||
|
.bind(Utc::now())
|
||||||
|
.bind(run_id)
|
||||||
|
.execute(&pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
println!(
|
||||||
|
"deduped chapter {n} ({before}c -> {after}c) in {:.1}s",
|
||||||
|
elapsed.as_secs_f32(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if skipped > 0 {
|
||||||
|
println!(
|
||||||
|
"dedup complete: \"{title}\" — {} chapter(s) processed, {skipped} SKIPPED \
|
||||||
|
(retry each with --chapter)",
|
||||||
|
chapters.len(),
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
println!(
|
||||||
|
"dedup complete: \"{title}\" — {} chapter(s) deduped against {} finding(s)",
|
||||||
|
chapters.len(),
|
||||||
|
findings.len(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
struct Finding {
|
||||||
|
severity: String,
|
||||||
|
area: String,
|
||||||
|
body: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn load_latest_findings(pool: &PgPool, story_id: Uuid) -> anyhow::Result<Vec<Finding>> {
|
||||||
|
let rows: Vec<(String, String, String)> = sqlx::query_as(
|
||||||
|
"SELECT severity, area, body FROM audit_findings
|
||||||
|
WHERE story_id = $1
|
||||||
|
AND run_id = (
|
||||||
|
SELECT id FROM generation_runs
|
||||||
|
WHERE story_id = $1 AND kind = 'prose_audit' AND status = 'succeeded'
|
||||||
|
ORDER BY started_at DESC LIMIT 1
|
||||||
|
)
|
||||||
|
ORDER BY
|
||||||
|
CASE severity WHEN 'crit' THEN 0 WHEN 'warn' THEN 1 ELSE 2 END,
|
||||||
|
area",
|
||||||
|
)
|
||||||
|
.bind(story_id)
|
||||||
|
.fetch_all(pool)
|
||||||
|
.await?;
|
||||||
|
Ok(rows
|
||||||
|
.into_iter()
|
||||||
|
.map(|(severity, area, body)| Finding { severity, area, body })
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render_findings(findings: &[Finding]) -> String {
|
||||||
|
let mut out = String::new();
|
||||||
|
for f in findings {
|
||||||
|
out.push_str(&format!(
|
||||||
|
"[{} · {}]\n{}\n\n",
|
||||||
|
f.severity.to_uppercase(),
|
||||||
|
f.area,
|
||||||
|
f.body,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn resolve_author(
|
||||||
|
pool: &PgPool,
|
||||||
|
story_author_id: Option<Uuid>,
|
||||||
|
flag_slug: Option<&str>,
|
||||||
|
) -> anyhow::Result<Option<AuthorWithRevision>> {
|
||||||
|
if let Some(slug) = flag_slug {
|
||||||
|
return authors::get_with_current_revision(pool, slug)
|
||||||
|
.await?
|
||||||
|
.map(Some)
|
||||||
|
.with_context(|| format!("author '{slug}' not found"));
|
||||||
|
}
|
||||||
|
if let Some(aid) = story_author_id {
|
||||||
|
let row: Option<(String,)> = sqlx::query_as("SELECT slug FROM authors WHERE id = $1")
|
||||||
|
.bind(aid)
|
||||||
|
.fetch_optional(pool)
|
||||||
|
.await?;
|
||||||
|
if let Some((slug,)) = row {
|
||||||
|
return Ok(authors::get_with_current_revision(pool, &slug).await?);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(None)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn pass_text(out: &PassOutput) -> anyhow::Result<String> {
|
||||||
|
let text = out
|
||||||
|
.result
|
||||||
|
.as_text()
|
||||||
|
.map(|s| s.to_string())
|
||||||
|
.or_else(|| out.result.result.as_str().map(|s| s.to_string()))
|
||||||
|
.unwrap_or_else(|| out.result.result.to_string());
|
||||||
|
if text.trim().is_empty() {
|
||||||
|
bail!("dedup pass returned empty");
|
||||||
|
}
|
||||||
|
Ok(text)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn load_forge_config() -> anyhow::Result<ForgeConfig> {
|
||||||
|
let base_url = std::env::var("CLAWDFORGE_URL").context("CLAWDFORGE_URL not set")?;
|
||||||
|
let app_token = std::env::var("CLAWDFORGE_TOKEN").context("CLAWDFORGE_TOKEN not set")?;
|
||||||
|
let model = std::env::var("SKALD_MODEL").unwrap_or_else(|_| "opus".into());
|
||||||
|
Ok(ForgeConfig {
|
||||||
|
base_url,
|
||||||
|
app_token,
|
||||||
|
model,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
@ -4,11 +4,14 @@
|
||||||
//! skald serve — boot the http server (v0.1 = /health + migrations)
|
//! skald serve — boot the http server (v0.1 = /health + migrations)
|
||||||
//! skald import-markdown — ingest a story markdown file into the DB
|
//! skald import-markdown — ingest a story markdown file into the DB
|
||||||
|
|
||||||
|
mod audit;
|
||||||
mod authors_seed;
|
mod authors_seed;
|
||||||
mod continue_story;
|
mod continue_story;
|
||||||
|
mod dedup;
|
||||||
mod import;
|
mod import;
|
||||||
mod narrate;
|
mod narrate;
|
||||||
mod narrate_prep;
|
mod narrate_prep;
|
||||||
|
mod rewrite;
|
||||||
mod serve;
|
mod serve;
|
||||||
mod show_context;
|
mod show_context;
|
||||||
mod summarize;
|
mod summarize;
|
||||||
|
|
@ -27,8 +30,8 @@ use uuid::Uuid;
|
||||||
about = "Long-form story-writer. Database is the source of truth; the writer is the tooling."
|
about = "Long-form story-writer. Database is the source of truth; the writer is the tooling."
|
||||||
)]
|
)]
|
||||||
struct Cli {
|
struct Cli {
|
||||||
/// Postgres connection URL. Defaults to `postgresql://skald:skald@localhost:5432/skald`.
|
/// Postgres connection URL. Read from `DATABASE_URL` if unset.
|
||||||
#[arg(long, env = "DATABASE_URL", default_value = "postgresql://skald:skald@localhost:5432/skald")]
|
#[arg(long, env = "DATABASE_URL")]
|
||||||
database_url: String,
|
database_url: String,
|
||||||
|
|
||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
|
|
@ -155,6 +158,51 @@ enum Cmd {
|
||||||
/// errors out to avoid clobbering a hand-tuned version.
|
/// errors out to avoid clobbering a hand-tuned version.
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
overwrite: bool,
|
overwrite: bool,
|
||||||
|
/// Single-voice mode: skip the character speaker roster so
|
||||||
|
/// no [voice:X] dialogue tags are inserted. Use when the
|
||||||
|
/// whole chapter narrates in one voice.
|
||||||
|
#[arg(long)]
|
||||||
|
single_voice: bool,
|
||||||
|
},
|
||||||
|
/// Re-author one chapter's prose in an author's voice. Canon
|
||||||
|
/// preserved, prose reworked. Overwrites body_md (stashing the
|
||||||
|
/// original in body_md_original) and clears body_md_tts.
|
||||||
|
Rewrite {
|
||||||
|
/// Chapter UUID to re-author.
|
||||||
|
#[arg(long)]
|
||||||
|
chapter: Uuid,
|
||||||
|
/// Author slug to rewrite as. Falls back to the story's
|
||||||
|
/// bound author if omitted.
|
||||||
|
#[arg(long)]
|
||||||
|
author: Option<String>,
|
||||||
|
},
|
||||||
|
/// Whole-story prose-quality audit. Reads every chapter end to
|
||||||
|
/// end and flags repetition, template tics, self-restatement
|
||||||
|
/// and continuity drift. The QC gate before narration. Findings
|
||||||
|
/// land in audit_findings and print to stdout. Requires
|
||||||
|
/// CLAWDFORGE_URL + CLAWDFORGE_TOKEN.
|
||||||
|
Audit {
|
||||||
|
/// Story to audit.
|
||||||
|
#[arg(long)]
|
||||||
|
story: Uuid,
|
||||||
|
},
|
||||||
|
/// Dedup a story against its most recent prose-audit findings.
|
||||||
|
/// Walks every chapter, rephrasing only the flagged repetitions
|
||||||
|
/// and fixing flagged continuity errors — everything else stays
|
||||||
|
/// verbatim. Overwrites body_md and clears body_md_tts. Run
|
||||||
|
/// `skald audit` first.
|
||||||
|
Dedup {
|
||||||
|
/// Story to dedup.
|
||||||
|
#[arg(long)]
|
||||||
|
story: Uuid,
|
||||||
|
/// Author slug for the rephrasing. Falls back to the story's
|
||||||
|
/// bound author if omitted.
|
||||||
|
#[arg(long)]
|
||||||
|
author: Option<String>,
|
||||||
|
/// Restrict the run to a single chapter number — used to
|
||||||
|
/// retry a chapter the length guard skipped.
|
||||||
|
#[arg(long)]
|
||||||
|
chapter: Option<i32>,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -230,8 +278,23 @@ async fn run() -> anyhow::Result<()> {
|
||||||
chapter,
|
chapter,
|
||||||
author,
|
author,
|
||||||
overwrite,
|
overwrite,
|
||||||
|
single_voice,
|
||||||
} => {
|
} => {
|
||||||
narrate_prep::run(&cli.database_url, chapter, author.as_deref(), overwrite).await
|
narrate_prep::run(
|
||||||
|
&cli.database_url,
|
||||||
|
chapter,
|
||||||
|
author.as_deref(),
|
||||||
|
overwrite,
|
||||||
|
single_voice,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
Cmd::Rewrite { chapter, author } => {
|
||||||
|
rewrite::run(&cli.database_url, chapter, author.as_deref()).await
|
||||||
|
}
|
||||||
|
Cmd::Audit { story } => audit::run(&cli.database_url, story).await,
|
||||||
|
Cmd::Dedup { story, author, chapter } => {
|
||||||
|
dedup::run(&cli.database_url, story, author.as_deref(), chapter).await
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -65,12 +65,16 @@ pub async fn run(
|
||||||
let run_id = Uuid::new_v4();
|
let run_id = Uuid::new_v4();
|
||||||
let output_filename = format!("{}-{}-{}.wav", chapter.story_id, chapter.n, run_id);
|
let output_filename = format!("{}-{}-{}.wav", chapter.story_id, chapter.n, run_id);
|
||||||
|
|
||||||
// Engine + version threaded from the voice row's source/license
|
// Engine + version threaded from the voice row's source. Three
|
||||||
// pair. lj_speech-style PD voices live behind f5-tts; kokoro_*
|
// engines on the host currently:
|
||||||
// voices live behind kokoro. Future: a dedicated voices.engine
|
// kokoro_* → kokoro 82M
|
||||||
// column to make this explicit.
|
// tortoise_* → tortoise-tts
|
||||||
|
// anything else (lj_speech etc.) → f5-tts
|
||||||
|
// Future: a dedicated voices.engine column to make this explicit.
|
||||||
let (engine, engine_version) = if voice.source.starts_with("kokoro") {
|
let (engine, engine_version) = if voice.source.starts_with("kokoro") {
|
||||||
("kokoro-82m", "0.9")
|
("kokoro-82m", "0.9")
|
||||||
|
} else if voice.source.starts_with("tortoise") {
|
||||||
|
("tortoise-tts", "3.0")
|
||||||
} else {
|
} else {
|
||||||
("f5-tts", "1.1.20")
|
("f5-tts", "1.1.20")
|
||||||
};
|
};
|
||||||
|
|
@ -91,14 +95,20 @@ pub async fn run(
|
||||||
// the Kokoro server only ever sees real voice ids. Only kicks
|
// the Kokoro server only ever sees real voice ids. Only kicks
|
||||||
// in for kokoro-routed renders; F5 voice-tag handling isn't
|
// in for kokoro-routed renders; F5 voice-tag handling isn't
|
||||||
// implemented and any tags pass through unchanged.
|
// implemented and any tags pass through unchanged.
|
||||||
// Two pre-processing passes (kokoro only). Order matters:
|
// Two pre-processing passes (kokoro + tortoise — engines that
|
||||||
// 1. Speaker voice substitution rewrites [voice:slug] → [voice:kokoro_id].
|
// parse [voice:X] dialogue tags). Order matters:
|
||||||
// This must run BEFORE pronunciation overrides so we don't
|
// 1. Speaker voice substitution rewrites [voice:slug] → the
|
||||||
// accidentally try to respell character slugs.
|
// engine's named voice id. Must run BEFORE pronunciation
|
||||||
|
// overrides so we don't try to respell character slugs.
|
||||||
|
// Tortoise: characters with no tortoise-voice mapping
|
||||||
|
// gracefully fall back to the narrator voice server-side.
|
||||||
// 2. Pronunciation overrides word-substitute proper nouns
|
// 2. Pronunciation overrides word-substitute proper nouns
|
||||||
// (Pripyat, Dyatlov, etc.) with English-readable respellings
|
// (Pripyat, Dyatlov, etc.) with English-readable
|
||||||
// so Kokoro's small phonemizer doesn't mangle them.
|
// respellings. The respellings are kokoro/misaki-tuned but
|
||||||
let gen_text = if voice.source.starts_with("kokoro") {
|
// pass through tortoise's g2p_en well enough to apply.
|
||||||
|
let routes_to_engine_with_voice_tags =
|
||||||
|
voice.source.starts_with("kokoro") || voice.source.starts_with("tortoise");
|
||||||
|
let gen_text = if routes_to_engine_with_voice_tags {
|
||||||
let voiced = substitute_speaker_voices(
|
let voiced = substitute_speaker_voices(
|
||||||
&pool,
|
&pool,
|
||||||
chapter.story_id,
|
chapter.story_id,
|
||||||
|
|
@ -151,6 +161,12 @@ pub async fn run(
|
||||||
.execute(&pool)
|
.execute(&pool)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
|
// This chapter now has a fresh canonical render. Prior render
|
||||||
|
// WAVs are dead weight — every re-render otherwise leaves its
|
||||||
|
// predecessor on disk forever. Reclaim it. Best-effort: a
|
||||||
|
// cleanup failure must never fail an otherwise-good render.
|
||||||
|
cleanup_superseded_renders(&pool, chapter_id, run_row_id).await;
|
||||||
|
|
||||||
println!(
|
println!(
|
||||||
"narrated chapter {} of story {}: {} ({:.2}s audio, {:.1}s wall clock)",
|
"narrated chapter {} of story {}: {} ({:.2}s audio, {:.1}s wall clock)",
|
||||||
chapter.n,
|
chapter.n,
|
||||||
|
|
@ -373,15 +389,84 @@ async fn apply_pronunciation_overrides(
|
||||||
Ok(out)
|
Ok(out)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Pick the engine base URL for a given voice.source. Voices whose
|
/// Delete the WAV files of prior renders of this chapter and clear
|
||||||
/// source starts with "kokoro" route to KOKORO_URL; everything else
|
/// their `output_path`. The newest succeeded render is the canonical
|
||||||
/// routes to F5_TTS_URL. Each env var has a LAN-default for the host.
|
/// one; older renders are superseded the moment a new one lands, and
|
||||||
|
/// without this every re-render would leave a stale ~80MB file on
|
||||||
|
/// disk forever.
|
||||||
|
///
|
||||||
|
/// The `narration_runs` rows themselves are KEPT — engine, voice,
|
||||||
|
/// timing and status stay as render history. Only `output_path` is
|
||||||
|
/// nulled, so no row ever points at a file that no longer exists.
|
||||||
|
///
|
||||||
|
/// Best-effort throughout: this runs *after* the current render has
|
||||||
|
/// already been recorded as succeeded, so any failure here (a query
|
||||||
|
/// error, a permission problem on the audio dir) is logged and
|
||||||
|
/// swallowed — it must never turn a good render into a failed one.
|
||||||
|
async fn cleanup_superseded_renders(pool: &PgPool, chapter_id: Uuid, current_run: Uuid) {
|
||||||
|
// output_path is only ever set on the success UPDATE, so
|
||||||
|
// "output_path IS NOT NULL AND id != current" is exactly the set
|
||||||
|
// of prior completed renders.
|
||||||
|
let prior: Vec<(Uuid, String)> = match sqlx::query_as(
|
||||||
|
"SELECT id, output_path FROM narration_runs
|
||||||
|
WHERE chapter_id = $1 AND id <> $2 AND output_path IS NOT NULL",
|
||||||
|
)
|
||||||
|
.bind(chapter_id)
|
||||||
|
.bind(current_run)
|
||||||
|
.fetch_all(pool)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(rows) => rows,
|
||||||
|
Err(e) => {
|
||||||
|
tracing::warn!(error = %e, "superseded-render cleanup: query failed, skipping");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
for (run_id, output_path) in prior {
|
||||||
|
// output_path is the HTTP-facing path "/audio/<file>"; the
|
||||||
|
// `/audio` bind mount means that is also the on-disk path
|
||||||
|
// inside this container.
|
||||||
|
match std::fs::remove_file(&output_path) {
|
||||||
|
Ok(()) => {
|
||||||
|
tracing::info!(run_id = %run_id, path = %output_path, "removed superseded render");
|
||||||
|
}
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
||||||
|
// File already gone — still clear the dangling row.
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
// Could not delete — leave output_path intact rather
|
||||||
|
// than pointing the row at nothing.
|
||||||
|
tracing::warn!(
|
||||||
|
run_id = %run_id, path = %output_path, error = %e,
|
||||||
|
"superseded-render cleanup: could not delete file, leaving row intact",
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Err(e) = sqlx::query("UPDATE narration_runs SET output_path = NULL WHERE id = $1")
|
||||||
|
.bind(run_id)
|
||||||
|
.execute(pool)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
tracing::warn!(run_id = %run_id, error = %e, "superseded-render cleanup: could not null output_path");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Pick the engine base URL for a given voice.source.
|
||||||
|
/// kokoro_* → KOKORO_URL
|
||||||
|
/// tortoise_* → TORTOISE_URL
|
||||||
|
/// anything else (lj_speech etc.) → F5_TTS_URL
|
||||||
fn engine_url_for(source: &str) -> anyhow::Result<String> {
|
fn engine_url_for(source: &str) -> anyhow::Result<String> {
|
||||||
if source.starts_with("kokoro") {
|
let (env_var, engine) = if source.starts_with("kokoro") {
|
||||||
Ok(std::env::var("KOKORO_URL")
|
("KOKORO_URL", "kokoro")
|
||||||
.unwrap_or_else(|_| "http://127.0.0.1:7794".into()))
|
} else if source.starts_with("tortoise") {
|
||||||
|
("TORTOISE_URL", "tortoise")
|
||||||
} else {
|
} else {
|
||||||
Ok(std::env::var("F5_TTS_URL")
|
("F5_TTS_URL", "f5-tts")
|
||||||
.unwrap_or_else(|_| "http://127.0.0.1:7792".into()))
|
};
|
||||||
}
|
std::env::var(env_var).map_err(|_| {
|
||||||
|
anyhow::anyhow!("{env_var} not set — point at the {engine} sidecar")
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -24,6 +24,7 @@ pub async fn run(
|
||||||
chapter_id: Uuid,
|
chapter_id: Uuid,
|
||||||
author_slug: Option<&str>,
|
author_slug: Option<&str>,
|
||||||
overwrite: bool,
|
overwrite: bool,
|
||||||
|
single_voice: bool,
|
||||||
) -> anyhow::Result<()> {
|
) -> anyhow::Result<()> {
|
||||||
let cfg = load_forge_config()?;
|
let cfg = load_forge_config()?;
|
||||||
tracing::info!(base_url = %cfg.base_url, model = %cfg.model, "forge configured");
|
tracing::info!(base_url = %cfg.base_url, model = %cfg.model, "forge configured");
|
||||||
|
|
@ -60,10 +61,20 @@ pub async fn run(
|
||||||
.fetch_one(&pool)
|
.fetch_one(&pool)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
let characters = load_speakers(&pool, chapter.story_id).await?;
|
// Single-voice mode skips the speaker roster entirely — the
|
||||||
if !characters.is_empty() {
|
// narrate_prep pass then inserts only [breath]/[pause]/[scene]
|
||||||
tracing::info!(speaker_count = characters.len(), "speaker roster loaded");
|
// beats, no [voice:X] dialogue tags. Right when the whole
|
||||||
|
// chapter narrates in one voice.
|
||||||
|
let characters = if single_voice {
|
||||||
|
tracing::info!("single-voice mode — skipping speaker roster");
|
||||||
|
Vec::new()
|
||||||
|
} else {
|
||||||
|
let c = load_speakers(&pool, chapter.story_id).await?;
|
||||||
|
if !c.is_empty() {
|
||||||
|
tracing::info!(speaker_count = c.len(), "speaker roster loaded");
|
||||||
}
|
}
|
||||||
|
c
|
||||||
|
};
|
||||||
|
|
||||||
let started = Instant::now();
|
let started = Instant::now();
|
||||||
let out_res = forge
|
let out_res = forge
|
||||||
|
|
|
||||||
252
skald/src/rewrite.rs
Normal file
252
skald/src/rewrite.rs
Normal file
|
|
@ -0,0 +1,252 @@
|
||||||
|
//! `skald rewrite` — re-author one chapter's prose in an author's
|
||||||
|
//! voice. Canon preserved, prose reworked. Overwrites chapters.body_md
|
||||||
|
//! with the rewritten version; the pre-rewrite prose is stashed in
|
||||||
|
//! chapters.body_md_original on the first rewrite (if NULL) so the
|
||||||
|
//! original is never lost.
|
||||||
|
//!
|
||||||
|
//! Author resolution: --author flag wins, else the chapter's
|
||||||
|
//! story.author_id. A rewrite with no author errors — there's no
|
||||||
|
//! target voice.
|
||||||
|
|
||||||
|
use std::time::Instant;
|
||||||
|
|
||||||
|
use anyhow::{Context, bail};
|
||||||
|
use chrono::Utc;
|
||||||
|
use skald_core::authors::{self, AuthorWithRevision};
|
||||||
|
use skald_core::config::ForgeConfig;
|
||||||
|
use skald_core::db;
|
||||||
|
use skald_core::forge::{Forge, PassKind, PassOutput};
|
||||||
|
use sqlx::PgPool;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
pub async fn run(
|
||||||
|
database_url: &str,
|
||||||
|
chapter_id: Uuid,
|
||||||
|
author_slug: Option<&str>,
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
|
let cfg = load_forge_config()?;
|
||||||
|
tracing::info!(base_url = %cfg.base_url, model = %cfg.model, "forge configured");
|
||||||
|
|
||||||
|
let pool = db::connect_and_migrate(database_url).await?;
|
||||||
|
let forge = Forge::new(&cfg)?;
|
||||||
|
|
||||||
|
let chapter = load_chapter(&pool, chapter_id).await?;
|
||||||
|
let author = resolve_author(&pool, &chapter, author_slug)
|
||||||
|
.await?
|
||||||
|
.ok_or_else(|| {
|
||||||
|
anyhow::anyhow!(
|
||||||
|
"rewrite needs an author — pass --author <slug> or bind one to the story"
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
tracing::info!(
|
||||||
|
slug = %author.author.slug,
|
||||||
|
revision_n = author.revision.n,
|
||||||
|
chapter_n = chapter.n,
|
||||||
|
word_count_in = word_count(&chapter.body_md),
|
||||||
|
"re-authoring chapter",
|
||||||
|
);
|
||||||
|
|
||||||
|
let run_id: Uuid = sqlx::query_scalar(
|
||||||
|
"INSERT INTO generation_runs (story_id, kind, status) VALUES ($1, $2, 'running') RETURNING id",
|
||||||
|
)
|
||||||
|
.bind(chapter.story_id)
|
||||||
|
.bind(PassKind::Rewrite.as_str())
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let started = Instant::now();
|
||||||
|
let out_res = forge.rewrite(&chapter.body_md, &author).await;
|
||||||
|
let elapsed = started.elapsed();
|
||||||
|
|
||||||
|
let out: PassOutput = match out_res {
|
||||||
|
Ok(o) => o,
|
||||||
|
Err(e) => {
|
||||||
|
sqlx::query(
|
||||||
|
"UPDATE generation_runs SET status='failed', error=$1, ended_at=$2 WHERE id=$3",
|
||||||
|
)
|
||||||
|
.bind(format!("{e:#}"))
|
||||||
|
.bind(Utc::now())
|
||||||
|
.bind(run_id)
|
||||||
|
.execute(&pool)
|
||||||
|
.await?;
|
||||||
|
return Err(e);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let rewritten = pass_text(&out)?;
|
||||||
|
let (_n, title, body) = parse_chapter(&rewritten);
|
||||||
|
|
||||||
|
// Stash the original on first rewrite, then overwrite body_md.
|
||||||
|
// body_md_tts is cleared — it was annotated against the OLD
|
||||||
|
// prose and must be regenerated by a fresh prepare-narration.
|
||||||
|
sqlx::query(
|
||||||
|
"UPDATE chapters
|
||||||
|
SET body_md_original = COALESCE(body_md_original, body_md),
|
||||||
|
body_md = $1,
|
||||||
|
title = COALESCE($2, title),
|
||||||
|
body_md_tts = NULL,
|
||||||
|
word_count = $3,
|
||||||
|
generated_at = now()
|
||||||
|
WHERE id = $4",
|
||||||
|
)
|
||||||
|
.bind(&body)
|
||||||
|
.bind(title.as_deref())
|
||||||
|
.bind(word_count(&body))
|
||||||
|
.bind(chapter_id)
|
||||||
|
.execute(&pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
// Replace passages with the rewritten paragraphs.
|
||||||
|
sqlx::query("DELETE FROM passages WHERE chapter_id = $1")
|
||||||
|
.bind(chapter_id)
|
||||||
|
.execute(&pool)
|
||||||
|
.await?;
|
||||||
|
for (i, para) in body.split("\n\n").enumerate() {
|
||||||
|
let p = para.trim();
|
||||||
|
if p.is_empty() || p == "---" {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
sqlx::query("INSERT INTO passages (chapter_id, paragraph_n, body) VALUES ($1, $2, $3)")
|
||||||
|
.bind(chapter_id)
|
||||||
|
.bind(i as i32 + 1)
|
||||||
|
.bind(p)
|
||||||
|
.execute(&pool)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
sqlx::query(
|
||||||
|
"UPDATE stories SET word_count_actual = (SELECT COALESCE(SUM(word_count), 0) FROM chapters WHERE story_id = $1) WHERE id = $1",
|
||||||
|
)
|
||||||
|
.bind(chapter.story_id)
|
||||||
|
.execute(&pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
sqlx::query("UPDATE generation_runs SET status='succeeded', ended_at=$1 WHERE id=$2")
|
||||||
|
.bind(Utc::now())
|
||||||
|
.bind(run_id)
|
||||||
|
.execute(&pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
println!(
|
||||||
|
"rewrote chapter {} of story {} as {} ({} → {} words) in {:.1}s",
|
||||||
|
chapter.n,
|
||||||
|
chapter.story_id,
|
||||||
|
author.author.slug,
|
||||||
|
word_count(&chapter.body_md),
|
||||||
|
word_count(&body),
|
||||||
|
elapsed.as_secs_f32(),
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
struct ChapterRow {
|
||||||
|
story_id: Uuid,
|
||||||
|
n: i32,
|
||||||
|
body_md: String,
|
||||||
|
story_author_id: Option<Uuid>,
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn load_chapter(pool: &PgPool, id: Uuid) -> anyhow::Result<ChapterRow> {
|
||||||
|
let row: Option<(Uuid, i32, String, Option<Uuid>)> = sqlx::query_as(
|
||||||
|
"SELECT c.story_id, c.n, c.body_md, s.author_id
|
||||||
|
FROM chapters c JOIN stories s ON s.id = c.story_id
|
||||||
|
WHERE c.id = $1",
|
||||||
|
)
|
||||||
|
.bind(id)
|
||||||
|
.fetch_optional(pool)
|
||||||
|
.await?;
|
||||||
|
let (story_id, n, body_md, story_author_id) =
|
||||||
|
row.with_context(|| format!("chapter {id} not found"))?;
|
||||||
|
Ok(ChapterRow {
|
||||||
|
story_id,
|
||||||
|
n,
|
||||||
|
body_md,
|
||||||
|
story_author_id,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn resolve_author(
|
||||||
|
pool: &PgPool,
|
||||||
|
chapter: &ChapterRow,
|
||||||
|
flag_slug: Option<&str>,
|
||||||
|
) -> anyhow::Result<Option<AuthorWithRevision>> {
|
||||||
|
if let Some(slug) = flag_slug {
|
||||||
|
return authors::get_with_current_revision(pool, slug)
|
||||||
|
.await?
|
||||||
|
.map(Some)
|
||||||
|
.with_context(|| format!("author '{slug}' not found"));
|
||||||
|
}
|
||||||
|
if let Some(aid) = chapter.story_author_id {
|
||||||
|
let row: Option<(String,)> = sqlx::query_as("SELECT slug FROM authors WHERE id = $1")
|
||||||
|
.bind(aid)
|
||||||
|
.fetch_optional(pool)
|
||||||
|
.await?;
|
||||||
|
if let Some((slug,)) = row {
|
||||||
|
return Ok(authors::get_with_current_revision(pool, &slug).await?);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(None)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn pass_text(out: &PassOutput) -> anyhow::Result<String> {
|
||||||
|
let text = out
|
||||||
|
.result
|
||||||
|
.as_text()
|
||||||
|
.map(|s| s.to_string())
|
||||||
|
.or_else(|| out.result.result.as_str().map(|s| s.to_string()))
|
||||||
|
.unwrap_or_else(|| out.result.result.to_string());
|
||||||
|
if text.trim().is_empty() {
|
||||||
|
bail!("rewrite pass returned empty");
|
||||||
|
}
|
||||||
|
Ok(text)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parse (n, title, body) out of the rewritten chapter. Tolerant of
|
||||||
|
/// a missing heading — if the first line isn't a heading we keep the
|
||||||
|
/// whole text as body and return n=0 (caller keeps the existing n).
|
||||||
|
fn parse_chapter(text: &str) -> (i32, Option<String>, String) {
|
||||||
|
let trimmed = text.trim_start();
|
||||||
|
let first = trimmed.lines().next().unwrap_or("").trim();
|
||||||
|
if let Some(heading) = first.strip_prefix('#') {
|
||||||
|
let heading = heading.trim_start_matches('#').trim();
|
||||||
|
let n = heading
|
||||||
|
.to_lowercase()
|
||||||
|
.find("chapter")
|
||||||
|
.and_then(|idx| {
|
||||||
|
heading[idx + 7..]
|
||||||
|
.trim_start()
|
||||||
|
.split([' ', '—', '-', ':', ','])
|
||||||
|
.next()
|
||||||
|
.and_then(|w| w.parse::<i32>().ok())
|
||||||
|
})
|
||||||
|
.unwrap_or(0);
|
||||||
|
let title = heading
|
||||||
|
.split_once(" — ")
|
||||||
|
.or_else(|| heading.split_once(" - "))
|
||||||
|
.map(|(_, t)| t.trim().to_string())
|
||||||
|
.filter(|t| !t.is_empty());
|
||||||
|
let body = trimmed
|
||||||
|
.lines()
|
||||||
|
.skip(1)
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join("\n")
|
||||||
|
.trim_start()
|
||||||
|
.to_string();
|
||||||
|
let body = if body.is_empty() { text.trim().to_string() } else { body };
|
||||||
|
return (n, title, body);
|
||||||
|
}
|
||||||
|
(0, None, text.trim().to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn word_count(s: &str) -> i32 {
|
||||||
|
s.split_whitespace().count() as i32
|
||||||
|
}
|
||||||
|
|
||||||
|
fn load_forge_config() -> anyhow::Result<ForgeConfig> {
|
||||||
|
let base_url = std::env::var("CLAWDFORGE_URL")
|
||||||
|
.context("CLAWDFORGE_URL not set")?;
|
||||||
|
let app_token = std::env::var("CLAWDFORGE_TOKEN")
|
||||||
|
.context("CLAWDFORGE_TOKEN not set")?;
|
||||||
|
let model = std::env::var("SKALD_MODEL").unwrap_or_else(|_| "opus".into());
|
||||||
|
Ok(ForgeConfig { base_url, app_token, model })
|
||||||
|
}
|
||||||
240
skald/src/web.rs
240
skald/src/web.rs
|
|
@ -45,6 +45,7 @@ pub fn router(state: WebState) -> Router {
|
||||||
"/stories/{id}/chapters/{n}/narrate",
|
"/stories/{id}/chapters/{n}/narrate",
|
||||||
post(chapter_narrate_fire),
|
post(chapter_narrate_fire),
|
||||||
)
|
)
|
||||||
|
.route("/stories/{id}/listen", get(listen_view))
|
||||||
.route("/stories/{id}/runs", get(runs_view))
|
.route("/stories/{id}/runs", get(runs_view))
|
||||||
.nest_service("/audio", ServeDir::new(audio_dir))
|
.nest_service("/audio", ServeDir::new(audio_dir))
|
||||||
.with_state(Arc::new(state))
|
.with_state(Arc::new(state))
|
||||||
|
|
@ -200,8 +201,12 @@ async fn new_story_create(
|
||||||
// parent to compare against. So you get a single first-chapter
|
// parent to compare against. So you get a single first-chapter
|
||||||
// gen + cleanup pass and status flows to 'complete'.
|
// gen + cleanup pass and status flows to 'complete'.
|
||||||
if form.fire == "now" {
|
if form.fire == "now" {
|
||||||
let database_url = std::env::var("DATABASE_URL")
|
let Ok(database_url) = std::env::var("DATABASE_URL") else {
|
||||||
.unwrap_or_else(|_| "postgresql://skald:skald@localhost:5432/skald".into());
|
return Err((
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
|
"DATABASE_URL not set — cannot spawn background gen".into(),
|
||||||
|
));
|
||||||
|
};
|
||||||
let author_owned = if author_slug.is_empty() {
|
let author_owned = if author_slug.is_empty() {
|
||||||
None
|
None
|
||||||
} else {
|
} else {
|
||||||
|
|
@ -336,7 +341,12 @@ async fn continue_create(
|
||||||
// If user clicked "fire now," spawn a background gen task.
|
// If user clicked "fire now," spawn a background gen task.
|
||||||
// Otherwise the sequel sits in seed state until CLI fires it.
|
// Otherwise the sequel sits in seed state until CLI fires it.
|
||||||
if form.fire == "now" {
|
if form.fire == "now" {
|
||||||
let database_url = std::env::var("DATABASE_URL").unwrap_or_else(|_| "postgresql://skald:skald@localhost:5432/skald".into());
|
let Ok(database_url) = std::env::var("DATABASE_URL") else {
|
||||||
|
return Err((
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
|
"DATABASE_URL not set — cannot spawn background gen".into(),
|
||||||
|
));
|
||||||
|
};
|
||||||
let author_owned = if author_slug.is_empty() { None } else { Some(author_slug.to_string()) };
|
let author_owned = if author_slug.is_empty() { None } else { Some(author_slug.to_string()) };
|
||||||
let direction_owned = direction.clone();
|
let direction_owned = direction.clone();
|
||||||
let chapters = parse_chapters(&form.chapters);
|
let chapters = parse_chapters(&form.chapters);
|
||||||
|
|
@ -402,7 +412,18 @@ async fn story_detail(
|
||||||
.await
|
.await
|
||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
|
|
||||||
let panel = story_panel(&story, &chapters, &characters, &canon_facts);
|
let has_audiobook: bool = sqlx::query_scalar::<_, Option<String>>(
|
||||||
|
"SELECT audiobook_path FROM stories WHERE id = $1",
|
||||||
|
)
|
||||||
|
.bind(id)
|
||||||
|
.fetch_optional(&state.pool)
|
||||||
|
.await
|
||||||
|
.ok()
|
||||||
|
.flatten()
|
||||||
|
.flatten()
|
||||||
|
.is_some();
|
||||||
|
|
||||||
|
let panel = story_panel(&story, &chapters, &characters, &canon_facts, has_audiobook);
|
||||||
Ok(Html(render_shell(&stories, Some(id), panel).into_string()))
|
Ok(Html(render_shell(&stories, Some(id), panel).into_string()))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -500,8 +521,12 @@ async fn chapter_narrate_fire(
|
||||||
let chapter_id =
|
let chapter_id =
|
||||||
chapter_id.ok_or((StatusCode::NOT_FOUND, "chapter not found".into()))?;
|
chapter_id.ok_or((StatusCode::NOT_FOUND, "chapter not found".into()))?;
|
||||||
|
|
||||||
let database_url = std::env::var("DATABASE_URL")
|
let Ok(database_url) = std::env::var("DATABASE_URL") else {
|
||||||
.unwrap_or_else(|_| "postgresql://skald:skald@localhost:5432/skald".into());
|
return Err((
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
|
"DATABASE_URL not set — cannot spawn background narrate".into(),
|
||||||
|
));
|
||||||
|
};
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
if let Err(e) = crate::narrate::run(&database_url, chapter_id, None, 1.0).await {
|
if let Err(e) = crate::narrate::run(&database_url, chapter_id, None, 1.0).await {
|
||||||
tracing::error!(chapter_id = %chapter_id, error = %e, "background narrate failed");
|
tracing::error!(chapter_id = %chapter_id, error = %e, "background narrate failed");
|
||||||
|
|
@ -513,6 +538,73 @@ async fn chapter_narrate_fire(
|
||||||
Ok(Redirect::to(&format!("/stories/{id}/chapters/{n}")))
|
Ok(Redirect::to(&format!("/stories/{id}/chapters/{n}")))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// One chapter as the audiobook player sees it: its start offset
|
||||||
|
/// (seconds from the top of the stitched file) and its length.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
struct AudiobookChapter {
|
||||||
|
n: i32,
|
||||||
|
title: Option<String>,
|
||||||
|
offset_seconds: f64,
|
||||||
|
duration_seconds: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn listen_view(
|
||||||
|
State(state): State<Arc<WebState>>,
|
||||||
|
Path(id): Path<Uuid>,
|
||||||
|
) -> Result<Html<String>, StatusCode> {
|
||||||
|
let stories = fetch_stories(&state.pool).await;
|
||||||
|
let Some(story) = stories.iter().find(|s| s.id == id).cloned() else {
|
||||||
|
return Err(StatusCode::NOT_FOUND);
|
||||||
|
};
|
||||||
|
|
||||||
|
let audiobook_path: Option<String> = sqlx::query_scalar::<_, Option<String>>(
|
||||||
|
"SELECT audiobook_path FROM stories WHERE id = $1",
|
||||||
|
)
|
||||||
|
.bind(id)
|
||||||
|
.fetch_optional(&state.pool)
|
||||||
|
.await
|
||||||
|
.ok()
|
||||||
|
.flatten()
|
||||||
|
.flatten();
|
||||||
|
|
||||||
|
// Per-chapter durations come from each chapter's most recent
|
||||||
|
// succeeded narration_run. Summed cumulatively in chapter order
|
||||||
|
// they give every chapter's start offset inside the stitched
|
||||||
|
// file — the same order the file was stitched in.
|
||||||
|
let rows: Vec<(i32, Option<String>, Option<f32>)> = sqlx::query_as(
|
||||||
|
r#"
|
||||||
|
SELECT c.n, c.title,
|
||||||
|
(SELECT nr.duration_seconds FROM narration_runs nr
|
||||||
|
WHERE nr.chapter_id = c.id AND nr.status = 'succeeded'
|
||||||
|
AND nr.duration_seconds IS NOT NULL
|
||||||
|
ORDER BY nr.ended_at DESC LIMIT 1)
|
||||||
|
FROM chapters c
|
||||||
|
WHERE c.story_id = $1
|
||||||
|
ORDER BY c.n
|
||||||
|
"#,
|
||||||
|
)
|
||||||
|
.bind(id)
|
||||||
|
.fetch_all(&state.pool)
|
||||||
|
.await
|
||||||
|
.unwrap_or_default();
|
||||||
|
|
||||||
|
let mut chapters = Vec::new();
|
||||||
|
let mut cursor = 0.0_f64;
|
||||||
|
for (n, title, dur) in rows {
|
||||||
|
let d = dur.unwrap_or(0.0) as f64;
|
||||||
|
chapters.push(AudiobookChapter {
|
||||||
|
n,
|
||||||
|
title,
|
||||||
|
offset_seconds: cursor,
|
||||||
|
duration_seconds: d,
|
||||||
|
});
|
||||||
|
cursor += d;
|
||||||
|
}
|
||||||
|
|
||||||
|
let panel = audiobook_panel(&story, audiobook_path.as_deref(), &chapters);
|
||||||
|
Ok(Html(render_shell(&stories, Some(id), panel).into_string()))
|
||||||
|
}
|
||||||
|
|
||||||
async fn runs_view(
|
async fn runs_view(
|
||||||
State(state): State<Arc<WebState>>,
|
State(state): State<Arc<WebState>>,
|
||||||
Path(id): Path<Uuid>,
|
Path(id): Path<Uuid>,
|
||||||
|
|
@ -592,7 +684,7 @@ fn render_shell(stories: &[StoryRow], current: Option<Uuid>, main: Markup) -> Ma
|
||||||
}
|
}
|
||||||
footer.footbar {
|
footer.footbar {
|
||||||
span { "skald · v0.3 · written down · "
|
span { "skald · v0.3 · written down · "
|
||||||
a href="http://127.0.0.1:3001/Sulkta/skald" { "Sulkta/skald" }
|
a href="https://git.sulkta.com/Sulkta-OSS/skald" { "Sulkta-OSS/skald" }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -714,6 +806,7 @@ fn story_panel(
|
||||||
chapters: &[(i32, Option<String>, i32, bool)],
|
chapters: &[(i32, Option<String>, i32, bool)],
|
||||||
characters: &[(String, String, String)],
|
characters: &[(String, String, String)],
|
||||||
canon_facts: &[(String, String, String)],
|
canon_facts: &[(String, String, String)],
|
||||||
|
has_audiobook: bool,
|
||||||
) -> Markup {
|
) -> Markup {
|
||||||
let real_chars: Vec<_> = characters.iter().filter(|c| c.1 == "real").collect();
|
let real_chars: Vec<_> = characters.iter().filter(|c| c.1 == "real").collect();
|
||||||
let fictional_chars: Vec<_> = characters.iter().filter(|c| c.1 == "fictional").collect();
|
let fictional_chars: Vec<_> = characters.iter().filter(|c| c.1 == "fictional").collect();
|
||||||
|
|
@ -731,6 +824,9 @@ fn story_panel(
|
||||||
}
|
}
|
||||||
nav.story-actions {
|
nav.story-actions {
|
||||||
a.action-primary href=(format!("/stories/{}/continue", s.id)) { "✦ continue this saga" }
|
a.action-primary href=(format!("/stories/{}/continue", s.id)) { "✦ continue this saga" }
|
||||||
|
@if has_audiobook {
|
||||||
|
a.action-listen href=(format!("/stories/{}/listen", s.id)) { "♪ listen" }
|
||||||
|
}
|
||||||
a.action-secondary href=(format!("/stories/{}/runs", s.id)) { "generation log →" }
|
a.action-secondary href=(format!("/stories/{}/runs", s.id)) { "generation log →" }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -977,6 +1073,96 @@ fn runs_panel(story_id: Uuid, runs: &[(Uuid, String, String, DateTime<Utc>, Opti
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Audiobook player — one `<audio>` element over the whole stitched
|
||||||
|
/// file plus a clickable chapter list. Clicking a chapter seeks; the
|
||||||
|
/// chapter under the playhead highlights as it plays. All client-side
|
||||||
|
/// in one small inline script (the file's only JS).
|
||||||
|
fn audiobook_panel(
|
||||||
|
story: &StoryRow,
|
||||||
|
audiobook_path: Option<&str>,
|
||||||
|
chapters: &[AudiobookChapter],
|
||||||
|
) -> Markup {
|
||||||
|
html! {
|
||||||
|
article.audiobook {
|
||||||
|
a.back href=(format!("/stories/{}", story.id)) { "← back to story" }
|
||||||
|
h1 { (story.title) }
|
||||||
|
(ornament())
|
||||||
|
@match audiobook_path {
|
||||||
|
Some(path) => {
|
||||||
|
@let basename = path.rsplit('/').next().unwrap_or(path);
|
||||||
|
@let audio_url = format!("/audio/{}", basename);
|
||||||
|
@let total: f64 = chapters.iter().map(|c| c.duration_seconds).sum();
|
||||||
|
p.muted {
|
||||||
|
(chapters.len()) " chapters · " (fmt_hms(total)) " · "
|
||||||
|
a href=(audio_url) download=(basename) { "download" }
|
||||||
|
}
|
||||||
|
audio #book controls preload="metadata" src=(audio_url) {}
|
||||||
|
ol.audiobook-chapters {
|
||||||
|
@for c in chapters {
|
||||||
|
@let end = c.offset_seconds + c.duration_seconds;
|
||||||
|
li.ab-chapter
|
||||||
|
data-seek=(format!("{:.3}", c.offset_seconds))
|
||||||
|
data-end=(format!("{:.3}", end))
|
||||||
|
{
|
||||||
|
span.ab-n { "Chapter " (c.n) }
|
||||||
|
@if let Some(t) = &c.title {
|
||||||
|
span.ab-title { (strip_chapter_prefix(t, c.n)) }
|
||||||
|
}
|
||||||
|
span.ab-time { (fmt_hms(c.offset_seconds)) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
script {
|
||||||
|
(maud::PreEscaped(AUDIOBOOK_JS))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
p.muted {
|
||||||
|
"No audiobook stitched for this saga yet. Render every "
|
||||||
|
"chapter to audio, then stitch the per-chapter files into one."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const AUDIOBOOK_JS: &str = r#"
|
||||||
|
(function () {
|
||||||
|
var audio = document.getElementById('book');
|
||||||
|
if (!audio) return;
|
||||||
|
var rows = Array.prototype.slice.call(document.querySelectorAll('.ab-chapter'));
|
||||||
|
rows.forEach(function (row) {
|
||||||
|
row.addEventListener('click', function () {
|
||||||
|
var t = parseFloat(row.getAttribute('data-seek'));
|
||||||
|
if (!isNaN(t)) { audio.currentTime = t; audio.play(); }
|
||||||
|
});
|
||||||
|
});
|
||||||
|
audio.addEventListener('timeupdate', function () {
|
||||||
|
var now = audio.currentTime;
|
||||||
|
rows.forEach(function (row) {
|
||||||
|
var s = parseFloat(row.getAttribute('data-seek'));
|
||||||
|
var e = parseFloat(row.getAttribute('data-end'));
|
||||||
|
if (now >= s && now < e) { row.classList.add('playing'); }
|
||||||
|
else { row.classList.remove('playing'); }
|
||||||
|
});
|
||||||
|
});
|
||||||
|
})();
|
||||||
|
"#;
|
||||||
|
|
||||||
|
/// Format seconds as H:MM:SS, or M:SS when under an hour.
|
||||||
|
fn fmt_hms(s: f64) -> String {
|
||||||
|
let total = s.max(0.0) as i64;
|
||||||
|
let h = total / 3600;
|
||||||
|
let m = (total % 3600) / 60;
|
||||||
|
let sec = total % 60;
|
||||||
|
if h > 0 {
|
||||||
|
format!("{h}:{m:02}:{sec:02}")
|
||||||
|
} else {
|
||||||
|
format!("{m}:{sec:02}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ─── helpers ─────────────────────────────────────────────────────
|
// ─── helpers ─────────────────────────────────────────────────────
|
||||||
|
|
||||||
/// Knotwork divider — a small SVG ornament used as section break.
|
/// Knotwork divider — a small SVG ornament used as section break.
|
||||||
|
|
@ -1318,6 +1504,45 @@ code { font-family: var(--mono); font-size: 0.9em; background: var(--surface-2);
|
||||||
|
|
||||||
.empty { color: var(--ink-faint); font-style: italic; }
|
.empty { color: var(--ink-faint); font-style: italic; }
|
||||||
|
|
||||||
|
/* ─── audiobook player ─────────────────────────────────────── */
|
||||||
|
.action-listen {
|
||||||
|
font-family: var(--display); letter-spacing: 2px; font-size: 12px;
|
||||||
|
text-transform: uppercase; color: var(--bronze);
|
||||||
|
border: 1px solid var(--bronze-dim); padding: 9px 18px;
|
||||||
|
background: var(--surface);
|
||||||
|
}
|
||||||
|
.action-listen:hover { color: var(--bg); background: var(--bronze); border-color: var(--bronze); }
|
||||||
|
.audiobook .back {
|
||||||
|
display: inline-block; color: var(--ink-faint); font-size: 12px;
|
||||||
|
margin-bottom: 18px; letter-spacing: 0.5px;
|
||||||
|
}
|
||||||
|
.audiobook h1 {
|
||||||
|
font-family: var(--display); font-size: 32px; color: var(--ink);
|
||||||
|
margin: 0; font-weight: 700; letter-spacing: 1px;
|
||||||
|
}
|
||||||
|
.audiobook > .muted { font-size: 13px; margin: 0 0 14px 0; }
|
||||||
|
.audiobook > .muted a { color: var(--bronze); }
|
||||||
|
.audiobook audio { width: 100%; margin: 4px 0 26px 0; }
|
||||||
|
.audiobook-chapters { list-style: none; margin: 0; padding: 0; }
|
||||||
|
.ab-chapter {
|
||||||
|
display: grid; grid-template-columns: 120px 1fr auto; gap: 20px;
|
||||||
|
align-items: baseline; padding: 13px 16px; cursor: pointer;
|
||||||
|
border-left: 2px solid transparent; border-bottom: 1px solid var(--surface-2);
|
||||||
|
transition: background 80ms ease;
|
||||||
|
}
|
||||||
|
.ab-chapter:hover { background: var(--surface-2); border-left-color: var(--bronze-dim); }
|
||||||
|
.ab-chapter.playing { background: var(--surface-2); border-left-color: var(--accent); }
|
||||||
|
.ab-n {
|
||||||
|
font-family: var(--mono); font-size: 12px; color: var(--bronze-dim);
|
||||||
|
letter-spacing: 1px;
|
||||||
|
}
|
||||||
|
.ab-chapter.playing .ab-n { color: var(--accent); }
|
||||||
|
.ab-title { font-family: var(--serif); font-size: 16px; color: var(--ink); }
|
||||||
|
.ab-time {
|
||||||
|
font-family: var(--mono); font-size: 12px; color: var(--ink-faint);
|
||||||
|
text-align: right;
|
||||||
|
}
|
||||||
|
|
||||||
/* ─── forms (new-saga + continue) ──────────────────────────── */
|
/* ─── forms (new-saga + continue) ──────────────────────────── */
|
||||||
.form-panel h1 {
|
.form-panel h1 {
|
||||||
font-family: var(--display); font-size: 30px; color: var(--ink);
|
font-family: var(--display); font-size: 30px; color: var(--ink);
|
||||||
|
|
@ -1379,6 +1604,7 @@ code { font-family: var(--mono); font-size: 0.9em; background: var(--surface-2);
|
||||||
.topnav { margin-left: 0; width: 100%; padding-top: 6px; }
|
.topnav { margin-left: 0; width: 100%; padding-top: 6px; }
|
||||||
.chapter-list a { grid-template-columns: 80px 1fr auto; }
|
.chapter-list a { grid-template-columns: 80px 1fr auto; }
|
||||||
.chapter-list .wc { display: none; }
|
.chapter-list .wc { display: none; }
|
||||||
|
.ab-chapter { grid-template-columns: 80px 1fr auto; gap: 12px; }
|
||||||
.char-list li { grid-template-columns: 1fr; gap: 4px; }
|
.char-list li { grid-template-columns: 1fr; gap: 4px; }
|
||||||
.cname { font-size: 14px; }
|
.cname { font-size: 14px; }
|
||||||
.brand { font-size: 22px; letter-spacing: 3px; }
|
.brand { font-size: 22px; letter-spacing: 3px; }
|
||||||
|
|
|
||||||
2
vendor/clawdforge/Cargo.toml
vendored
2
vendor/clawdforge/Cargo.toml
vendored
|
|
@ -2,7 +2,7 @@
|
||||||
name = "clawdforge"
|
name = "clawdforge"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
license = "MIT"
|
license = "AGPL-3.0-or-later"
|
||||||
description = "Async Rust client for the clawdforge HTTP service (a LAN bearer-token-gated wrapper around `claude -p`)."
|
description = "Async Rust client for the clawdforge HTTP service (a LAN bearer-token-gated wrapper around `claude -p`)."
|
||||||
repository = "https://git.sulkta.com/Sulkta-OSS/clawdforge"
|
repository = "https://git.sulkta.com/Sulkta-OSS/clawdforge"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
|
|
|
||||||
2
vendor/clawdforge/README.md
vendored
2
vendor/clawdforge/README.md
vendored
|
|
@ -267,4 +267,4 @@ Tests use [`wiremock`](https://docs.rs/wiremock) — no live clawdforge needed.
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
MIT.
|
AGPL-3.0-or-later.
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue