Search by

togos / tsoft1009

TOGoS

Structured document model: Org/Markdown/TEF parsing, Org/Markdown/HTML/TEF/JSON emission

Package info

github.com/TOGoS/TSoft1009

pkg:composer/togos/tsoft1009

Statistics

Installs: 8

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

0.4.2 2026-11-30 15:47 UTC

This package is auto-updated.

Last update: 2026-11-30 16:59:04 UTC


README

A PHP library representing structured documents in a common in-memory model. Parsers ingest .org, .md, and .tef; formatters write org, markdown, HTML, and TEF back out, plus lossless JSON tree transport. (The HTML parser is the remaining named gap; HTML output exists.)

Round-tripping preserves meaning rather than bytes; byte-level expectations differ per format (see Guarantees). Re-emitting a document we generated is always byte-stable.

Install

composer require togos/tsoft1009    # PHP >= 7.4

End to end:

require 'vendor/autoload.php';

$tree = TOGoS_TS1009_Parser_OrgParser::parse( file_get_contents( 'notes.org' ), 'notes.org' );
$html = (string)TOGoS_TS1009_Emitter_HTMLEmitter::format( $tree );

Naming note: the composer package is togos/tsoft1009 and classes carry the TOGoS_TS1009_ prefix, while the tag-URI vocabulary namespace keeps this project's original Scratchier46 ID (tag:nuke24.net,2026-11:s46c15005:). The two differ for historical reasons; both are stable.

Module layout

Each source module is a separate autoload "namespace root" so it can be extracted into its own project later with minimal surgery:

Module Source Tests Prefix
common src/common/php src/common-test TOGoS_TS1009_Common_
parser src/parser/php src/parser-test TOGoS_TS1009_Parser_
transform src/transform/php src/transform-test TOGoS_TS1009_Transform_
emitter src/emitter/php src/emitter-test TOGoS_TS1009_Emitter_

parser and emitter reference only common, never each other; composition happens in the caller. There is deliberately no facade module or format registry — each thing has exactly one obvious home.

Design conventions

  • Arrays for data, objects for components with behavior. A document node is a plain JSON-serializable PHP array (a "JSO") tagged by classRef.
  • classRef carries the node's type as a full tag URI in the tag:nuke24.net,2026-11:s46c15005: space; understood properties live as sibling keys (e.g. children).
  • Text is always an explicit node, never a bare string.
  • Source provenance: every node carries a sourceLocation array {source, startByte, startLine, startCol, endByte, endLine, endCol}, zero-based with nulls for unknown dimensions. Common_SourceLocation holds the behavior, including parse/render of the TOGETLTSV location grammar (L5C2 1-based, l4c1 0-based, b10...b23 byte spans, - for none).
  • Stages follow the push-sink pattern: invokable callables, null forwarded as end-of-input exactly once. Common_LineSplitter and Common_TreeSink are the working in-repo examples; one level below tree-building, the isomorphic Open / Open+Close / Close event stream (Common_Events) is available to sinks that cannot afford a whole document.
  • Reserved for the future HTML parser (nothing produces these yet): attributes found verbatim in input will live in an xmlAttrs map, and element/attribute keys will use namespace + " " + localName with - standing for "not in a namespace"; unknown markup will become a Generic node of the same shape as understood nodes, so there is no structural difference between what we parse and what we merely carry.
  • The node vocabulary lives in vocab/c15005.tef (TEF — eating our own dogfood). Entry identifiers there are kebab-case (=node-type); the canonical URIs use their PascalCase translation, and Attr: URIs follow the same rule. That file owns the mapping.

Public API

Everything is static — no objects to construct, no PHP namespaces (flat TOGoS_TS1009_Module_Class names, PSR-0 autoloaded per module). Every value's provenance is explicit:

// parse — canonical input is Nife_Blob; plain strings accepted as
// convenience. Returns a TAINTED tree (Tainted wrapper around the
// Document): parsed content is un-vetted until you say otherwise.
$tree = TOGoS_TS1009_Parser_OrgParser::parse( $blobOrString, $ref );
$tree = TOGoS_TS1009_Parser_MarkdownParser::parse( $blobOrString, $ref );
$tree = TOGoS_TS1009_Parser_TEFParser::parse( $blobOrString, $ref );   // TEF v0.3.0

// semantic pass — opt-in, idempotent; org trees (no-op on the others):
// attaches affiliated '#+' keywords to their elements, wraps file-keyword
// preambles in Metadata nodes. Preserves taint.
$tree = TOGoS_TS1009_Parser_OrgTransform::associate( $tree );

// untaint — the explicit "safened to my satisfaction" declaration;
// renderers refuse tainted trees until you call it (after whatever
// policy transforms you consider adequate, e.g. Transform_RefRewriting)
$tree = TOGoS_TS1009_Common_Taint::untaint( $tree );

// format — returns a Nife_Blob; cast when you want text
$htmlBlob = TOGoS_TS1009_Emitter_HTMLEmitter::format( $tree );
$html     = (string) $htmlBlob;

// JSON tree transport — unlike renderers it PRESERVES taint (stored
// trees stay tainted), and import taints untainted input
$encoded  = TOGoS_TS1009_Common_JSON::format( $tree );                 // Nife_Blob
$restored = TOGoS_TS1009_Common_JSON::parse( $encoded );              // tree; blob or string accepted

// diagnostics — collect Warning nodes from anywhere in the tree, then summarize
$warnings = TOGoS_TS1009_Common_Diagnostics::collect( $tree );        // array of nodes
$report   = TOGoS_TS1009_Common_Diagnostics::summarize( $warnings );  // string, "L5C2...L5C9: msg"

Other helpers: TOGoS_TS1009_Common_NodeTypes (classRefs, flavors, isInline()); TOGoS_TS1009_Common_SourceLocation (toString / fromString, the TOGETLTSV location grammar); TOGoS_TS1009_Common_ForcedEndingNewlineBlob (of( $blob ) / maybe( $blob, $force ) — adds a final LF if missing; a wrapper rather than a format() option so output policy stays at call sites); TOGoS_TS1009_Common_Taint (taint / untaint / isTainted — the parse/emit safety handshake).

Composition is the caller's one-liner, not a wrapper the library hides — the model tree is the hub and JSON is its lossless transport (org → json → md == org → md):

$orgText = file_get_contents( 'notes.org' );
$ref     = 'notes.org';
$md      = (string)TOGoS_TS1009_Emitter_MarkdownEmitter::format(
	TOGoS_TS1009_Common_Taint::untaint(
		TOGoS_TS1009_Parser_OrgParser::parse( $orgText, $ref ) ) );

$html = (string)TOGoS_TS1009_Emitter_HTMLEmitter::format(
	TOGoS_TS1009_Common_Taint::untaint(
		TOGoS_TS1009_Parser_OrgTransform::associate(
			TOGoS_TS1009_Parser_OrgParser::parse( $orgText, $ref ) ) ) );

// same-format format(untaint(parse($x))) is a canonicalizing no-op:
// idempotent thereafter

Cross-format translation. Where the target format has a native equivalent, emitters map to it (org headlines → # H, src/quote/example literals → fenced code, block argument → info string). Org-specific structures without one become prose in markdown ("NAME: t1", "Properties: k: v; …" blocks) and visible elements in HTML (p.org-directive, dl.org-metadata) — never comments or hidden markers; only unmap-able literals (center/verse) stay verbatim text. Alternative degradation flavors are sibling emitter classes, never format() flags.

TEF files split into entries structurally; entry bodies feed the org parser:

$path    = 'notes.tef';
$tefBlob = new Nife_FileBlob( $path );
$tefDoc  = TOGoS_TS1009_Parser_TEFParser::parse( $tefBlob, $path )['children'][0]; // untainted root
foreach( $tefDoc['children'] as $entry ) {
	// $entry: scope 'fileHeader'|'item' (items also carry type/id); children:
	// TEFHeader/TEFDirective/Comment in order, then a trailing TEFContent
	foreach( $entry['children'] as $child ) {
		if( ( $child['classRef'] ?? '' ) === TOGoS_TS1009_Common_NodeTypes::TEF_CONTENT ) {
			// bodies arrive tainted too; untaint (or transform, then untaint)
			// before emitting them
			$org = TOGoS_TS1009_Common_Taint::untaint( TOGoS_TS1009_Parser_OrgParser::parse(
				$child['text'], $path.'#'.( $entry['id'] ?? 'file' ) ) );
		}
	}
}

Guarantees

  • parse → format → parse is a fixpoint for every format tested here, and re-formatting generated output is byte-stable.
  • org / markdown are document markup — layout is meaning, so they aim at byte-fidelity: canonical sources re-emit identically, accepting only the documented canonicalizations (~code~ for verbatim spans, [[url]] for self-label links, soft-wrap folding of paragraph/item text, blank-line block separation, table cell padding, two-space item indentation; hard-break \, ordered markers, checkbox states, drawer delimiter spellings all survive).
  • TEF is a data language — like JSON, it round-trips values per its v0.3.0 spec (split header values, == escapes, content boundary rules) and does not promise to reproduce input formatting. Malformed shapes (colonless lines, compact key:value headers, orphan continuations) demote or normalize on first emit with a one-shot Warning; merely irregular spacing (space-indented continuations, stray blank separators) normalizes silently. Output is byte-stable from there.
  • Warning nodes render as nothing in org/markdown/TEF output (annotations must not move bytes) and as a visible <div class="c15005-warning"> in HTML.
  • Parsers hand out tainted trees (NodeType:Tainted wrapper; Perl taint-mode idiom). The four renderers refuse tainted input with a RuntimeException — wrappers are detected anywhere in the node graph, including off-children keys like affiliated runs (all whole-tree walks share one containment definition, TOGoS_TS1009_Common_NodeWalk) — so emitting un-vetted content is a loud error, not a silent default. TOGoS_TS1009_Common_Taint::untaint( $tree ) is how you declare "I have run whatever policy transforms I consider sufficient"; util/convert does this implicitly (it is a dev tool). Taint is a mandatory checkpoint, not a sandbox.
  • URL safety is a tree decision, never a rendering surprise: emitters serialize Attr:url verbatim except for percent-encoding characters browsers ignore inside urls (HTML strips-equivalent: tab/LF/CR; line-structure characters in org/markdown). The opt-in TOGoS_TS1009_Transform_RefRewriting edits refs — its shipped blockScriptSchemes() policy resolves schemes the way browsers do (interior tab/LF/CR invisible, leading whitespace trimmed) and drops executable-scheme urls (javascript:, vbscript:, …) into Attr:naughty, which HTML renders as data-naughty-href/ data-naughty-src. Schemes like data:, id:, elisp: stay live; custom policies (proxying, restoring) ride the same walk.

Errors

Parsers never throw on malformed input — the error channel is Warning nodes, and the policy is yours:

$warnings = TOGoS_TS1009_Common_Diagnostics::collect( $tree );
if( $warnings ) error_log( TOGoS_TS1009_Common_Diagnostics::summarize( $warnings ) );
// or refuse such input entirely:
if( $warnings ) throw new RuntimeException( 'refusing input with parse warnings' );

(Common_JSON::parse is the exception to "never throws": invalid JSON raises an EarthIT_JSON_JSONDecodeError.)

TOGoS_TS1009_Common_SourceLocation::toString( $loc ) renders L5C2...L5C9 / b10...b20 / -; fromString() parses it back.

Status

Org, markdown, and TEF round-trip through the common array-node model; fixpoints are tested in-suite against the two kitchen-sink fixtures (fixtures/org/, fixtures/tef/), backed by private-corpus audits (all 17 project-notes .tef files — 4176 entries, 2203 content bodies, all fixpoint through associate + org format; a 1.2 MB real-world org log re-emits content-equal under whitespace collapse).

Org parsing covers: headlines, sections, paragraphs, lists (bullets, 1./1) ordered, [ ]/[x]/[X]/[-] task checkboxes), inline markup (*strong*//em//_u_/~code~/links/images), hard line breaks, pipe tables with column-group separators preserved, #+ directives, #+begin_X…#+end_X literals, :PROPERTIES: drawers (spellings verbatim), horizontal rules, and comments.

Remaining gaps: the HTML parser; markdown tables beyond the org-syntax form; named (non-PROPERTIES) drawers; and setext headings, footnotes, indented code, and angle-bracket autolinks — each skipped knowingly, having zero hits in the private corpus.

Pre-1.0: minor releases may rename classes or vocabulary terms; vocab/c15005.tef remains the canonical term source.

Development

composer install    # once; needs PHP >= 7.4 and Composer
make                # lint + test

util/convert is a demo CLI over the same surface — outside the library on purpose, so the API keeps one obvious way per thing:

util/convert notes.org -o/html out.html -o/md - --deactivate-naughty-urls
util/convert --help

It untaints implicitly (it is a dev tool), but html output has NO default url policy: exactly one of --allow-naughty-urls (targets stay as the tree holds them) or --deactivate-naughty-urls (run blockScriptSchemes(): executable-scheme targets are removed and parked to data-naughty-*) is required; omitting both, or giving both, is a usage error. That forcing mirrors the library's own taint/untaint handshake — the demo must not silently train users on live-JS output.

AGENT-DEVLOG.md carries the running agent notes: decisions, traps, and review history.