From 0c6f5b6515effe7431c4d9c9ed3c4a3e7d398253 Mon Sep 17 00:00:00 2001 From: Thomas Walker Lynch Date: Thu, 5 Mar 2026 12:00:39 +0000 Subject: [PATCH 1/1] Harmony 2.0 first commit --- .gitignore | 14 + 0pus_Harmony | 0 LICENSE | 7 + .../document/00_Project_Structure.html | 88 ++++ .../document/01_Workflow_Build_Contract.html | 72 +++ administrator/document/Harmony.md | 42 ++ .../deprecated/00_Project_Structure.org | 162 +++++++ .../01_Workflow_and_Build_Contract.org | 146 ++++++ .../document/deprecated/02_RT_Code_Format.org | 230 ++++++++++ .../03_Naming_and_Directory_Conventions.org | 33 ++ .../deprecated/04_Language_Addenda.org | 170 +++++++ administrator/document/style/RT_TOC.js | 102 +++++ administrator/document/style/RT_code.js | 129 ++++++ administrator/document/style/RT_math.js | 35 ++ administrator/document/style/RT_term.js | 107 +++++ administrator/document/style/RT_title.js | 60 +++ administrator/document/style/Rubio.js | 15 + .../document/style/article_tech_ref.js | 170 +++++++ .../document/style/body_visibility_hidden.js | 12 + .../document/style/body_visibility_visible.js | 13 + administrator/document/style/custom_tag.txt | 8 + .../document/style/page_fixed_glow.js | 88 ++++ .../document/style/paginate_by_element.js | 72 +++ .../document/style/style_orchestrator.js | 92 ++++ .../document/style/theme_dark_gold.js | 94 ++++ administrator/document/style/theme_light.js | 70 +++ .../document/style/theme_light_gold.js | 103 +++++ administrator/document/style/utility.js | 109 +++++ administrator/document/style/version.txt | 1 + administrator/tool/Harmony_sync | 1 + administrator/tool/after_pull | 124 ++++++ administrator/tool/archive | 284 ++++++++++++ administrator/tool/release | 291 ++++++++++++ administrator/tool/setup | 3 + developer/authored/.gitkeep | 0 developer/authored/hello.cli.c | 2 + developer/document/.gitkeep | 0 developer/document/00_RT_Code_Format.html | 97 ++++ developer/document/02_RT_Code_Format.html | 99 +++++ .../03_Naming_and_Directory_Conventions.html | 49 +++ developer/document/04_Language_Addenda.html | 96 ++++ developer/document/ontology.org | 45 ++ developer/experiment/.gitkeep | 0 developer/made/.gitkeep | 0 developer/scratchpad/.gitignore | 2 + developer/tool/.gitkeep | 0 developer/tool/do_all | 24 + developer/tool/make | 26 ++ developer/tool/makefile | 54 +++ developer/tool/release | 289 ++++++++++++ developer/tool/setup | 3 + document/.gitkeep | 0 document/style/rt_dark_doc.css | 44 ++ scratchpad/.gitignore | 2 + setup | 68 +++ shared/authored/scratchpad | 225 ++++++++++ shared/authored/setup | 130 ++++++ shared/authored/version | 4 + shared/document/.gitkeep | 0 shared/document/install_Python.org | 75 ++++ shared/document/install_generic.org | 81 ++++ shared/made/walk | 1 + shared/third_party/.gitignore | 8 + shared/third_party/upstream/.gitignore | 2 + tester/.gitkeep | 0 tester/RT_Format/RT_Format | 415 ++++++++++++++++++ tester/RT_Format/RT_Format.el | 4 + tester/RT_Format/test_0_data.c | 15 + tester/RT_Format/test_1_data.py | 16 + tester/authored/test_routine.sh | 28 ++ tester/tool/setup | 3 + user/scratchpad/.gitignore | 2 + user/tool/env | 7 + 73 files changed, 4863 insertions(+) create mode 100644 .gitignore create mode 100644 0pus_Harmony create mode 100644 LICENSE create mode 100644 administrator/document/00_Project_Structure.html create mode 100644 administrator/document/01_Workflow_Build_Contract.html create mode 100644 administrator/document/Harmony.md create mode 100644 administrator/document/deprecated/00_Project_Structure.org create mode 100644 administrator/document/deprecated/01_Workflow_and_Build_Contract.org create mode 100644 administrator/document/deprecated/02_RT_Code_Format.org create mode 100644 administrator/document/deprecated/03_Naming_and_Directory_Conventions.org create mode 100644 administrator/document/deprecated/04_Language_Addenda.org create mode 100644 administrator/document/style/RT_TOC.js create mode 100644 administrator/document/style/RT_code.js create mode 100644 administrator/document/style/RT_math.js create mode 100644 administrator/document/style/RT_term.js create mode 100644 administrator/document/style/RT_title.js create mode 100644 administrator/document/style/Rubio.js create mode 100644 administrator/document/style/article_tech_ref.js create mode 100644 administrator/document/style/body_visibility_hidden.js create mode 100644 administrator/document/style/body_visibility_visible.js create mode 100644 administrator/document/style/custom_tag.txt create mode 100644 administrator/document/style/page_fixed_glow.js create mode 100644 administrator/document/style/paginate_by_element.js create mode 100644 administrator/document/style/style_orchestrator.js create mode 100644 administrator/document/style/theme_dark_gold.js create mode 100644 administrator/document/style/theme_light.js create mode 100644 administrator/document/style/theme_light_gold.js create mode 100644 administrator/document/style/utility.js create mode 100644 administrator/document/style/version.txt create mode 120000 administrator/tool/Harmony_sync create mode 100755 administrator/tool/after_pull create mode 100755 administrator/tool/archive create mode 100755 administrator/tool/release create mode 100644 administrator/tool/setup create mode 100644 developer/authored/.gitkeep create mode 100644 developer/authored/hello.cli.c create mode 100644 developer/document/.gitkeep create mode 100644 developer/document/00_RT_Code_Format.html create mode 100644 developer/document/02_RT_Code_Format.html create mode 100644 developer/document/03_Naming_and_Directory_Conventions.html create mode 100644 developer/document/04_Language_Addenda.html create mode 100644 developer/document/ontology.org create mode 100644 developer/experiment/.gitkeep create mode 100644 developer/made/.gitkeep create mode 100644 developer/scratchpad/.gitignore create mode 100644 developer/tool/.gitkeep create mode 100755 developer/tool/do_all create mode 100755 developer/tool/make create mode 100644 developer/tool/makefile create mode 100755 developer/tool/release create mode 100644 developer/tool/setup create mode 100644 document/.gitkeep create mode 100644 document/style/rt_dark_doc.css create mode 100644 scratchpad/.gitignore create mode 100644 setup create mode 100755 shared/authored/scratchpad create mode 100644 shared/authored/setup create mode 100755 shared/authored/version create mode 100644 shared/document/.gitkeep create mode 100644 shared/document/install_Python.org create mode 100644 shared/document/install_generic.org create mode 120000 shared/made/walk create mode 100644 shared/third_party/.gitignore create mode 100644 shared/third_party/upstream/.gitignore create mode 100644 tester/.gitkeep create mode 100755 tester/RT_Format/RT_Format create mode 100644 tester/RT_Format/RT_Format.el create mode 100644 tester/RT_Format/test_0_data.c create mode 100644 tester/RT_Format/test_1_data.py create mode 100644 tester/authored/test_routine.sh create mode 100644 tester/tool/setup create mode 100644 user/scratchpad/.gitignore create mode 100644 user/tool/env diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..fcd4eb4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,14 @@ +# Python +__pycache__/ +*.py[cod] +*.pyo +*.pyd +.ipynb_checkpoints/ +.pytest_cache/ + +# editor backup files (optional) +*~ +*.bak + +# so that .gitignore is not required in user/release +/user/release diff --git a/0pus_Harmony b/0pus_Harmony new file mode 100644 index 0000000..e69de29 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..51c52bc --- /dev/null +++ b/LICENSE @@ -0,0 +1,7 @@ +Copyright © 2019, 2024, 2025, 2026 Reasoning Technology. All Rights Reserved. + +This software, including all source code, compiled code, text, images, graphics, and associated media (collectively, "the Software and Content"), is the proprietary property of Reasoning Technology. + +A limited license, revocable at any time, is granted to access and view the Software and Content strictly for normal web browsing purposes. + +Beyond this limited viewing permission, no other rights are granted. A person is strictly prohibited from copying, extracting, modifying, republishing, distributing, sublicensing, selling, or otherwise exploiting this Software and Content, in whole or in part, for any purpose, without express written consent from Reasoning Technology. No license to any underlying technology, patents, trademarks, or other intellectual property is granted or implied by this access. diff --git a/administrator/document/00_Project_Structure.html b/administrator/document/00_Project_Structure.html new file mode 100644 index 0000000..6a5ea2d --- /dev/null +++ b/administrator/document/00_Project_Structure.html @@ -0,0 +1,88 @@ + + + + + Project Structure and Ontology + + + + + + + + + + + +

Purpose

+

+ Harmony provides a language-agnostic project directory structure and maintenance tools for long-lived, multi-person team software development. The structure exists to enforce: +

+
    +
  1. Clarity about where things live. +
      +
    • Role-based work areas.
    • +
    • Separation of skeleton, team member authored, machine-made, and third-party installed software.
    • +
    +
  2. +
  3. A safe, predictable build and release workflow.
  4. +
+ +

Key Concepts

+

Created vs. Made

+

+ Harmony divides the world into two categories: +

+ +

+ This separation protects authored material from accidental overwrite and makes build artifacts fully disposable. +

+ +

Semantic Paths

+

+ Directory names in Harmony are not decorative. Each directory name is a property shared among files. A full path forms a semantic sentence describing those files. +

+ +

Top-Level Repository Layout

+

+ A team member will source the project setup file to take on a role. As of this writing, the supported roles are: administrator, developer, tester, and user. +

+ + + +

The User Tree

+

+ The user/release/ tree is where developers put work product that is ready to be consumed. The entire user/release directory is git-ignored and treated as a transient deployment target. +

+

+ Artifacts arrive in the release/ tree only when the developer invokes the release script, which performs a flat-copy from the developer's scratchpad/stage directory. +

+ +

The Developer Tree

+

+ This directory is entered by first going to the top-level directory of the project, then sourcing . setup developer. +

+ + + +
+ + diff --git a/administrator/document/01_Workflow_Build_Contract.html b/administrator/document/01_Workflow_Build_Contract.html new file mode 100644 index 0000000..bde91a0 --- /dev/null +++ b/administrator/document/01_Workflow_Build_Contract.html @@ -0,0 +1,72 @@ + + + + + Workflow and Build Contract + + + + + + + + + + + +

Roles and Process

+ +

Administrator Role

+

Responsibilities:

+
    +
  1. Setup the project directory and keep it in sync with the Harmony skeleton.
  2. +
  3. Maintain the role environments, apart from the <role>/tool/setup files which are owned by the respective role.
  4. +
  5. Install and maintain shared tools.
  6. +
+ +

Developer Role

+

Responsibilities:

+
    +
  1. Write and modify authored/ source.
  2. +
  3. Run builds and stage artifacts in scratchpad/stage.
  4. +
  5. Spot test in experiment/.
  6. +
  7. Execute the release write script to copy artifacts to user/release for consumption/testing.
  8. +
+ +

Tester Role

+

Responsibilities:

+
    +
  1. Validate candidates under user/release/.
  2. +
  3. Run regression suites.
  4. +
  5. Approve for quality and completeness, and create release branches.
  6. +
+ +

Entering the Project

+

+ To enter a project, cd to the top-level directory and source the setup file for your desired role: +

+ +. setup administrator +. setup developer +. setup tester +. setup user + +

+ It is common to have multiple terminal sessions or IDEs open, each running under a different role environment. +

+ +

Release Promotion

+

+ Building and promotion are separate activities. The developer compiles and stages files in developer/scratchpad/stage. The developer then runs release write to transfer those files to user/release. +

+

+ The user/release directory is strictly an untracked deployment target. No tools may rebuild during promotion, and no builds are run directly inside the release directory. +

+ + +
+ + diff --git a/administrator/document/Harmony.md b/administrator/document/Harmony.md new file mode 100644 index 0000000..45fb023 --- /dev/null +++ b/administrator/document/Harmony.md @@ -0,0 +1,42 @@ +# Harmony — RT project skeleton + +Tiny, opinionated starter project skeleton that we use across RT projects independent of language being coded. + +Pick a role, source the env, build your thing, then release. + +## Roles (source these, don’t execute) +- `env_developer` — dev workflow +- `env_tester` — test + repro +- `env_toolsmith` — shared tools + env wiring + +Developers work under `developer/`, testers under `tester/`, toolsmiths wire `shared/` and env scripts. + +## Layout (why it exists) +- `document/` — project docs (+ RT conventions in org) +- `developer/` — dev code, experiments, dev-specific docs/tools +- `tester/` — tests, fixtures, repro steps +- `shared/` — shared tools/env for all roles +- `shared/third_party/` — third-party tools +- `shared/third_party/python/` — your venv lives here (not committed) +- `release/` — publishable artifacts +- `tmp/` — scratch (gitignored) + +Empty directories are tracked with `.githolder` (kept out of release archives). + +## Quick start +```bash +# choose a role (must be sourced) +. setup developer # or env_tester / env_toolsmith + +# create the Python venv under shared/third_party/python/ (literally 'python' instead of 'venv' +./scripts/python_venv_bootstrap.sh + +# re-enter later +. setup developer + +# where used + +In public projects, this structure has been used with Python, Java, C, C++, and Lisp projects. + +Note the related https://github.com/Thomas-Walker-Lynch/RT-project-share project. It has the generic makefile used on C/C++ projects and other shared tools. Note the project https://github.com/Thomas-Walker-Lynch/RT_gcc for a more fully featured cpp. Note the projects https://github.com/Thomas-Walker-Lynch/Mosaic, and https://github.com/Thomas-Walker-Lynch/Mosaic for Java examples of this project skeleton being used for a Java testing and dependency grapph build tool, respectively. + diff --git a/administrator/document/deprecated/00_Project_Structure.org b/administrator/document/deprecated/00_Project_Structure.org new file mode 100644 index 0000000..dc3acaf --- /dev/null +++ b/administrator/document/deprecated/00_Project_Structure.org @@ -0,0 +1,162 @@ +#+TITLE: 00 - Project Structure and Ontology +#+AUTHOR: Harmony Project Team +#+DATE: 2025-11-21 +#+OPTIONS: toc:2 num:nil + +#+HTML_HEAD_EXTRA: +#+HTML_HEAD_EXTRA: + +#+BEGIN_EXPORT html +
+#+END_EXPORT + +* Purpose + +Harmony provides a language agnostic project directory structure and maintenance tools for long-lived, multi-person team software development. The structure exists to enforce: + +1. Clarity about where things live. +1.1. Role based work areas +1.2. Separation of skeleton, team member authored, machine-made, and third party installed software. +3. A safe, predictable build and release workflow. + +A newcomer should be able to clone Harmony and understand the entire +working model in minutes. + +To make a new project a toolsmith first clones Harmony, renames it to the project name, resets the history, and disconnects it from the Harmony project. The skeleton of the new project can be kept in sync with the Harmony skeleton by going to a Harmony skeleton clone and running the =Harmony/tool/sync= tool. + +Harmony is IDE agnostic. I typically use Emacs as an IDE and encourage its use. Because of this the documents standard format is emacs `.org` format. Files in this format can be exported to other formats, such as HTML. I have also used IntelliJ IDEA and Eclipse with Harmony, though the project skeleton has drifted some since then. I would like to update Harmony to work out of the box with these and other IDEs in the future. + +* 1. Key Concepts + +** Created vs. Made +Harmony divides the world into two categories: + +- *Created / Authored* + Human-written: source files, docs, design notes. + +- *Made* + Tool-produced: binaries, generated sources, intermediates. + +This separation protects authored material from accidental overwrite and +makes build artifacts fully disposable. + +** Semantic Paths +Directory names in Harmony are not decorative. +Each directory name is a *property* shared among files. Thus, a full path forms a semantic +sentence describing said files. + +Example: + +- =developer/authored/= + “Developer authored code” + +- =developer/scratchpad/made/= + “Developer → scratch workspace → tool-made binaries” + +Once you learn the ontology, you can infer the meaning of any path. + +* Top-Level Repository Layout + +The layout below is stable across all Harmony skeleton based projects: + +| Directory | Meaning | +|----------|---------| +| =developer/= | Primary workspace for developers | +| =tester/= | Regression and validation workspace for testers | +| =tool/= | Project-local tools | +| =shared/= | Shared ecosystem tools | +| =document/= | Documentation (local to project) | +| =release/= | Central Working Point for promoted artifacts | +| =scratchpad/= | Global scratch (misc experiments) | +| =env_* = | Role activators | + +The `env_*` files prepare PATH, set environment variables, and cd into +the correct workspace. A team member will source one of the =env_*= files to take on a role in the project. As of this writing the supported roles are: toolsmith, developer, and tester. + +* The =release/= tree. + +The =release/= tree is where developers put work product that is to be shared with testers. Once the contents of the =release/= directory are blessed by the tester, the project will be given a release branch, and then the =release/= tree contains the files that are shared with users. Users should not be pulling files from anywhere else in the project tree. + +The =release/= tree is owned by the developer. No other role should write into this tree. + +Ideally, artifacts arrive in the =release/= tree *only* then the developer invokes the =promote= tool. And take note, The developer's =promote= script, as initially provided with the Harmony skeleton, has a command for erasing the contents of the release directory. + +** =release/made_tracked/= + Architecture-agnostic artifacts. Tracked by Git, comes when the project is cloned. Users update the release directory when on a release branch, by pulling the project. + +** =release/made_untracked/= + Architecture-specific artifacts. Directory tracked, contents are git ignored. The contents of this directory are created by running a build after the project is cloned/pulled. This was a compromise to avoid the problem of maintaining architecture and platform specific binaries. + +** =release/documnt/= + Documents for users of the code in the release directory. + +* The =developer/= tree + +This property is set, i.e. this director is entered, by first going to the top level directory of the project, then sourcing the =env_developer= environment file. The developer can hook additional items into the environment by putting them into the =developer/tool/env= file. + +** =authored/= + Human-written source. Tools should never delete files in this directory. =authored/= files are tracked. + +** =made/= + + Generated by tools, and the artifacts are tracked. These artifacts + are stable across machine architectures. A common item to find in + the =developer/made/= directory is a link to a Python program in + the =authored/= directory. When following RT conventions the entry + point of command line driven Python files is `CLI.py`, so the link + in =developer/made/= gives the program a name. + +** =experiment/= + Try-it-here code. Short-lived. Developers do spot testing here. If tests are to longer lived, they should be moved to the tester role. + +** =scratchpad/= + Contents of this directory are git ignored. It is intended to hold all intermediate build outputs, and anything else the developer might consider scratchpad work. + +** =scratchpad/made/= + By RT convention, architecture specific build artifacts are not tracked, but rather are built each time the project is cloned. Such build artifacts are placed in =developer/scratchpad/made= and if they are to be shared with the tester, the release script will release them to =release/made_untracted=. + +** =tool/= + Developer specific tools. Additional tools will be found under =shared=. If the project is not self contained, then yet additional tools might come from the system environment. + +* Documents + +** =release/document/= + Documentation for users of released code. E.g.s a =man= page, user manual for an application, or a reference manually for a released library. + +** =document/= + Project wide documentation for project team members. + +** =developer/document/= + Documentation for developers. + +** =tester/document/= + Documentation for testers. + +** =shared/document/= + Documentation on installing the shared tools. Note if a tool has a document directory that remains with the tool. + This will typically have a list of tools that need to be installed for the project, and notes to help make installs go more smoothly. + +* Tools + +** =tool/= + +We call the team members who administer the project and install tools the 'toolsmith'. The top level =tool/= directory holds the toolsmith's tools. + +** =shared/= + +Shared tools are available to all team members. Those that have been written specifically for the Harmony skeleton or for this project go into the =shared/authored= directory. Note the tool =scratchpad=, try =scratchpat help=. + +Tools installed from third parties go into the git ignored directory =shared/third_party=. + +** =developer/tool= + +Developer role specific tools. The =release= script and the RT project shared =make= scripts are found here. + +** =tester/tool= + +Tester role specific tools. + + +#+BEGIN_EXPORT html +
+#+END_EXPORT diff --git a/administrator/document/deprecated/01_Workflow_and_Build_Contract.org b/administrator/document/deprecated/01_Workflow_and_Build_Contract.org new file mode 100644 index 0000000..e34bcf6 --- /dev/null +++ b/administrator/document/deprecated/01_Workflow_and_Build_Contract.org @@ -0,0 +1,146 @@ +#+TITLE: 01 - Workflow and Build Contract +#+AUTHOR: RT +#+DATE: 2025-11-21 +#+OPTIONS: toc:2 num:nil + +#+HTML_HEAD_EXTRA: +#+HTML_HEAD_EXTRA: + +#+BEGIN_EXPORT html +
+#+END_EXPORT + +* Purpose +The workflow contract defines the steps from authorship through release of work product. + +There are three circular loops. + +In the development loop, developers author code and run experiments, eventually then promoting work product to the =release/= directory. + +In the developer tester loop, testers test the promoted release candidates and file issues against them, developers address these, and then promote new release candidates. Or in a tighter version of this loop, a developer with a local copy of this project plays both roles so as to speed the cycle. + +In the third loop, the tester finds the release candidates to meet the goals for the release version, and to be of sufficient quality that they create a new release branch. Released code then has bug reports filed against it. Developers address these and the prior two loops are run until a new release candidate is stable, and a new release branch is made. + +Release branches have two integer numbers. The first number is the version of the software, as per the architectural specification. (That specification is placed into the project document directory.) The second number counts the number of times the tester has created a release branch for said version of the software. + +The workflow is designed for forward motion of through release numbers, so as to avoid having to maintain older releases separately. It is better to give a customer a new release if a bug must be fixed, even the customer will not pay for the new release, that it is to pay the cost of dealing with multi-release level bug fixes. However, as each release has its own branch, it is possible to perform multi-release level bug fixes if that is what is required or desired. + +* Roles and Process + +** Developer Role +Responsibilities: + +1. Write and modify authored source. Ensure code meets RT style (see =02_RT_Code_Format.org=). +2. Run builds. +3. Spot testing in =experiment/= +4. Promotes release candidates for more thorough testing using the customized =prommote= script. +5. Rinse, lather, repeat. + +** Tester Role +Responsibilities: + +1. Validate candidates under =release/=. +2. Run regression suites. +3. Approve for quality and completeness, and create release branches. + +** Toolsmith Role +Responsibilities: + +1. Setup the project directory, and keep the project in sync with the Harmony skeleton. +2. Maintain the role environments, apart from the =/tool/env= files which are owned by the respective ==. +3. Install and maintained shared tools, =tool/= and =shared/=, and other tools upon request. +4. Address issues with project workflow. Propose updates to the Harmony skeleton. + + +* Entering the project + +What I do to enter a project is to first run an emacs shell. I cd to the project I want to work on, and then source the =env_toolsmith=, =env_developer=, or =env_tester= file, depending on which role I want to work in. Although sourcing these files affects the environment of the shell I am running, it does not effect the environment of emacs. Hence after sourcing the environment, I launch an IDE. This newly launched IDE will have a correct environment. For myself, these days, that new IDE will be emacs again. + +It is common that I will have two or three IDE's (emacs invocations) running side by side, each as different roles. Then I can write code, spot test it, promote it, then change to the other IDE and run regression tests. And if it is a phase of the project where tools are in flux, I will use the third IDE for modifying tools. Hence, as one person I will taken on three roles simultaneously, each in a different IDE. + +On a large project, chances are that all team members will be doing something similar to this on their local clones of the project. However, there will be team members concentrating on code development, and others on testing and release. Early on a toolsmith will setup the project, and then continue to maintain it. + +* Developer + +** Authoring and Building + +Developers write the build fodder files in the =authored/= directory. File name extensions are used to signal to the build tools how the build fodder is to be used. When the conventional single extension giving the main file type is not enough, two extensions are used. + +For example, with the default makefile for C, compiler fodder is found in the =authored/= directory, each file has one these file name extensions: + +- CLIs end in =.cli.c= +- Libary code source end in =.lib.c= +- Kernel module sources are =.mod.c= + +Fodder with the =.cli.c= extension is made into a stand alone executable. + +Fodder with =.lib.c= extension is compiled as an object file and added to the =lib.a= archive. The =.cli.c= files are linkedin against said archive. + +Build tools never write into the =developer/authored= directory. Build products that are not to be tracked go on the =scratchpad/=. Those that are tracked go into the =developer/made= directory. + +It is expected that developers customize and add to the build scripts that come with the Harmony skeleton in order to fit their specific build needs. Note the Ariadne project for complex builds. + +** Developer Testing + +Spot tests are run in the =experiment/= directory. If the tests grow complex or are to be kept for the long term, move them to the tester environment. + +Once the developer finds the edits to be stable he or she can promote them. The promoted code is referred to as release candidates. Promoted release candidates can then be read by the tester role. + +As I mentioned, it is not uncommon for a team member to have two IDEs open, with one being in the developer environment, and one being in the tester environment, and then to bounce back and fourth between them. + +Once the release candidate code is stable, the developer can pull the remote repo, address merge conflicts, then push the local repo back. Merge conflicts on tracked release candidates are common as it is a bottleneck point in the code development. + +** Promotion for release + +As mentioned, files are promoted from the developer environment to the top level =release/= directory by the developer. The developer effects promotion for release by running the customized =developer/tool/promote= script, and then pushing the repository. Only a tester can actually perform a release. + +Building and promotion are separate activities. + +- No tool may rebuild during promotion. +- Promotion is a copy-only operation. +- No builds are run in the =release/= directory. + +If architecture specific files are to be part of the release, the developer will develop a =build_untracked= script and promote it into the =release/tool= directory. Then when a user clones a released project, as a second step the user will invoke the =release/tool/build_untracked= script. That script will fill in the =release/made_untracked= directory with code built specifically for the user's platform. + +- =release/documnt/= (documents for those who intend to use the work product) +- =release/authored= (interpreter fodder - _none are run directly_) +- =release/made_tracked/= (pushed to remote, pulled from remote, links into authored scripts) +- =release/made_untracked/= (local-only) +- =release/tool/= (=build_untracked= and other tools for maintaining released code) + +We chose the 'build after clone' approach over the 'thousand architecture specific binary release directories' approach, because maintaining many architecture release files became a maintenance problem. Note this new approach requires that third party tools be installed so that the =release/tool/build_untracked= script can run. This is the trade off cost for nothing having the thousand architecture directories. + +A user of the Harmony skeleton is free to customize the promotion tool and go back to multiple architecture specific binary release directories if that is what they want. + +Clearly if work product is intended to be distributed to lay users, there must be a deployment step after the release step, but we do not address this in these documents, as it this is not part of Harmony. + + +* Tester + +The developer has promoted release candidates to the =release/= directory. He or she claims those represent a complete high quality product at the given release level. The testers are going to prove the developers to be wrong about that claim. If testers can't disprove this claim, the testers will make a release branch at the next minor release number for the given major release version. + +- The tester reads the spec, and writes a complete set of feature tests. + +- The tester uses the Mosaic test tool, and writes a set of tests, first for the individual functions that make up the program, then for functions in groups. + +- The tester accumulates tests for each bug that ever comes back on a release. + +- The tester collects tests from the developer when they are offered. + +- The tester writes other tests as he or she sees fit. + +- When the tests pass, one presumes, the tester will create a release branch. + +* Separation of roles. + +A tester never patches code in the =developer/= directory, instead the tester files issues. A tester could propose a code fix on another branch, and then point the developers at it in the issue report. + +A developer never writes into =tester/=, instead a developer adds to the =experiment/= and offers to share tests. A developer can propose tests on another branch, and then point testers at it. + +It is up the project manager how strict role assignments will be. + +As mentioned before, one person can play multiple roles. For example, it makes perfect sense for a developer with a local copy of the repo, to have an IDE open as a tester, so that he or she can run tests on release candidates before pushing them. However, in when doing this, the test code might be read only. The developer is merely running it and has no plans to push changes to it. + +#+BEGIN_EXPORT html +
+#+END_EXPORT diff --git a/administrator/document/deprecated/02_RT_Code_Format.org b/administrator/document/deprecated/02_RT_Code_Format.org new file mode 100644 index 0000000..e5ced40 --- /dev/null +++ b/administrator/document/deprecated/02_RT_Code_Format.org @@ -0,0 +1,230 @@ +#+TITLE: 02 - RT Prescriptive Code Format Guide (Version 3) +#+AUTHOR: Thomas Walker Lynch +#+DATE: 2025-12-05 +#+OPTIONS: toc:2 num:nil + +#+HTML_HEAD_EXTRA: +#+HTML_HEAD_EXTRA: + +#+BEGIN_EXPORT html +
+#+END_EXPORT + +* Purpose + +The goal is consistency, readability, and predictability across all +languages and tools. + +This document covers: + +1. Naming conventions +2. Object vs. Instance Nomenclature +3. Vertical comma lists +4. Enclosure spacing +5. Line breaks and indentation +6. Cross-language guidance + +* Object vs. Instance Nomenclature + +In the RT world, we reserve the word 'object' for its general English meaning, as its technical meaning in programming often causes confusion. When discussing data that is manipulated solely through a defined interface, use the term **instance**. + +- **Object:** Anything that can be described or reasoned about. A 'math object' is anything defined using mathematics, and a 'Python object' is anything that can be described with Python syntax. +- **Instance:** Data that is only accessed or manipulated through a defined interface. This term is used to clearly denote data encapsulation and separation of concerns. + + +* Identifer Naming Conventions + +** Identifier Naming + +- Types, modules: *PascalCase* +- Functions, variables: *snake_case* +- Globals: UPPER_SNAKE_CASE + +** Proper Noun and Acronyms + +Even in PascalCase and snake_case, they remain capitalized, as per the English language convention. + +E.g.s + +- IEEE_publication_count +- person_Sara_novelties_list + + +** Suffix Semantics +Optionally suffixes are added to variable names to suggest type or interface. + +- =*_dp :: directory path, not specified if relative or absolute +- =*_dpr :: relative directory path +- =*_dpa :: absolute directory path + +- =*_fp :: file path, not specified if relative or absolute +- =*_fpr :: relative file path +- =*_fpa :: absolute file path + +If the file system node type is not specifically specified + +- =*_fs_nod_p :: file system node path, not specified if relative or absolute +- =*_fs_nod_pr :: relative file system node path +- =*_fs_nod_pa :: absolute file system node path + +- =*_list= :: generic ordered items +- =*_seq= :: ordered items accessed by index + +- =*_map= :: a keyed container +- =*_dict :: a keyed container + +- =*_count= :: number of elements +- =*_flag= :: boolean + +- = *_Type :: names specific type, where the type name is given in PascalCase, as is the norm for types. E.g.s =name_Array= or =name_Map= for the cases that name is an instance of a defined Array or Map type. + +Add a container type suffix instead of making variables names plural. For example, + +- =name_seq= :: a sequence of zero or more names, used in place of =names=. + + +* Comma separated list + +RT code format treats the comma in a list as belonging to the item that caused the comma to be needed. + +** Horizontal Comma List + +For lists on a single line, the comma is preceded by a space and abuts the item it follows. + +#+BEGIN_SRC c + int x ,y ,z; +#+END_SRC + +Note the space before the comma, and the comma abuts the item that caused the comma to be needed. This applies to language statements and data values alike. + +** Vertical Comma List + +For lists spanning multiple lines, the comma is placed *before* the item on the new line, aligned with the item's indentation. + +#+BEGIN_SRC c +result = some_function( + first_argument + ,second_argument + ,third_argument +); +#+END_SRC + +Example in Python: + +#+BEGIN_SRC python +items = [ + first_item + ,second_item + ,third_item +] +#+END_SRC + +- Two-space indent. +- Comma at column after indentation. +- All items aligned except the first, as it does not have a comma before it. +- This convention works identically across C, Python, Bash arrays, JSON-like data, etc. + +* Enclosure Spacing + +This rule applies on a line by line basis. + +** General Rules + +**No Space Between Adjacent Enclosures:** Generally, there is no space between adjacent enclosure punctuation (e.g., `f(g(x))`). + +** Single-Level Enclosures + +For enclosures that do not contain other enclosures (e.g., a simple `if(condition)`), there is **no space padding** inside the enclosure punctuation. + +Conforming: + +#+BEGIN_SRC c +if(condition){ + do_something(); +} +#+END_SRC + +Bad, non-conforming: + +#+BEGIN_SRC c +if(condition) { + do_something(); +} +#+END_SRC + +Bad, non-conforming: + +#+BEGIN_SRC c +if ( condition ) { + do_something ( ); +} +#+END_SRC + +** Multi-Level Enclosures + +For enclosures that contain other enclosures (e.g., `if( f(g(x)) )`), one space of padding is applied only to the **level one (outermost)** enclosure punctuation. All other levels follow the single-level rule (no padding). + +#+BEGIN_SRC c +if( f(g(x)) ){ + do_something(); +} +#+END_SRC + +In this example, the =if= has a three-level enclosure structure. The outermost parentheses of the =if= condition get one space of padding, while the inner parentheses for =f(...)= and =g(...)= get no padding. + +** Unmatched Enclosure Punctuation + +Format the enclosure punctuation that is present, as though it were matched. Treat an orphaned opening enclosure punctuation as though it were closed at the end of the line. Treat an extraneous closing, as though there were an opening at the beginning of the line. + +** Short Stuff Rule + +If a statement, such as an =if= block or a loop, can fit on a single line and is shorter than a reasonable line length (e.g., 40-60 characters), it should be kept on a single line without braces. + +#+BEGIN_SRC c +if(x == 0) return; +#+END_SRC + +* Indentation + +- Two spaces per indentation level. +- Never use tabs. +- Nest lines under the syntactic element that opened them. + +* Exercises + +To ensure a full understanding of the RT code format, please complete the following exercises. + +** Exercise 1: Comma and Function Call Formatting + +Reformat the following C code snippet to strictly adhere to the RT code format rules. Pay close attention to the horizontal and vertical comma lists, and the enclosure spacing for the function call. + +#+BEGIN_SRC c +void my_function(int a, int b, int c) { + int result = calculate_value(a, b, c); + printf("Result: %d, a: %d, b: %d, c: %d\n", result, a, b, c); +} + +result = my_function( + rediculously_long_first_argument, + rediculously_long_second_argument, + rediculously_long_third_argument +); +#+END_SRC + +** Exercise 2: Multi-Level Enclosure and Short Stuff Rule + +Reformat the following C code snippet. The `if` statement should use the multi-level enclosure rule, and the `for` loop body should use the short stuff rule. + +#+BEGIN_SRC c +if (check_permissions(user_id, file_path) && is_valid(file_path)) { + for (int i = 0; i < 10; i++) { + if (i % 2 == 0) { + printf("Even: %d\n", i); + } + } +} +#+END_SRC + +#+BEGIN_EXPORT html +
+#+END_EXPORT diff --git a/administrator/document/deprecated/03_Naming_and_Directory_Conventions.org b/administrator/document/deprecated/03_Naming_and_Directory_Conventions.org new file mode 100644 index 0000000..d719d5b --- /dev/null +++ b/administrator/document/deprecated/03_Naming_and_Directory_Conventions.org @@ -0,0 +1,33 @@ +#+TITLE: 03 - Naming and Directory Conventions +#+AUTHOR: RT +#+DATE: 2025-11-21 +#+OPTIONS: toc:2 num:nil +#+HTML_HEAD_EXTRA: +#+HTML_HEAD_EXTRA: + +#+BEGIN_EXPORT html +
+#+END_EXPORT + +A directory name is taken a property for a set of files. Consequently, directory names are rarely plural. E.g. suppose we have a number of test files in a directory. The directory would be named =test=. As each file in the directory has the property of being a test. + +It would be nice if we could attach multiple properties to a file as part of the file system framework, but conventional file systems do not support this. Consequently, when needed, people add a second property to a file use dot extensions to the file's name. Hence, we get something like =sqrt.c= in a directory called =source=. So the first property is that the file is source code, and the second property is that it is C code. + +We could extent the dot suffix model of adding a property to file by using multiple dot suffixes. Our C makefile structure makes use of this. + +So what is a reasonable primary property for a set of files? Perhaps: + +- Who uses each file with this property. Home directories are named like this. +- The role of the people using the file. This is a more generic version of the prior rule. The =developer= and =tester= directories were named in this manner. +- What program are the files for. Thus we might name a directory a bunch of files for the cc compiler `cc`. +- The generic category of program said files are for. Thus we end up with directories called =src= or =executable=. + +As for the names =src= and =executable= those come from times when almost all programs were compiled. We prefer instead the names =authored= and =made=. =authored= files are those written by humans (or these days, perhaps AI), while =made= files are products of tools. For a Python program, we put packages in =authored= with a module called =CLI.py= for the command line interface. Then we link from =made= into =authored= so as to give the program a name. + +The RT C coding environment does not use separate source and header files. Instead a variable is set that gates off the implementation if the source code is to be used as a header. Hence, all of our C source fits fine within and =authored= directory. + + + +#+BEGIN_EXPORT html +
+#+END_EXPORT diff --git a/administrator/document/deprecated/04_Language_Addenda.org b/administrator/document/deprecated/04_Language_Addenda.org new file mode 100644 index 0000000..b9b4c77 --- /dev/null +++ b/administrator/document/deprecated/04_Language_Addenda.org @@ -0,0 +1,170 @@ +#+TITLE: 04 - Language Addenda (C, Python, Bash) +#+AUTHOR: RT +#+DATE: 2025-11-21 +#+OPTIONS: toc:2 num:nil +#+HTML_HEAD_EXTRA: +#+HTML_HEAD_EXTRA: + +#+BEGIN_EXPORT html +
+#+END_EXPORT + + +* Purpose +The RT code format is language-agnostic, but actual languages differ in +syntax and constraints. + +This document explains how the RT rules are applied in: + +1. C +2. Python +3. Bash + +For each language we answer: + +1. What carries over directly from =02_RT_Code_Format.org=. +2. What must be adapted. +3. What extra discipline is required. + +* 1. C Addendum + +** 1.1 Control Structure and File Layout + +The detailed RT C file structure is described in the dedicated = +RT_C_control_structure= document. The core ideas: + +1. Each module has an *Interface* section and an *Implementation* + section in the same file. +2. The sections are toggled using preprocessor macros (e.g. =FACE=). +3. Interface declarations are processed even when included multiple + times; the implementation is compiled only when used as an + implementation. + +This approach: + +1. Keeps the interface and implementation in sync. +2. Avoids maintaining parallel =.h= and =.c= files for each module. +3. Integrates smoothly with standardized makefiles. + +** 1.2 Indentation and Comma Lists + +C code follows the RT two-space indentation and vertical comma lists: + +#+BEGIN_SRC c +result = some_function( + first_argument + ,second_argument_with_longer_name + ,third_argument +); +#+END_SRC + +Rules: + +1. Two spaces per block indentation. +2. The comma starts the line in vertical lists. +3. Align continuation lines under the first symbol after the equals + sign or opening parenthesis when feasible. + +** 1.3 Error Handling and Ownership + +Guidelines: + +1. Functions should document ownership of pointers and lifetimes. +2. Prefer explicit =*_count= parameters over sentinel values when + passing arrays. +3. Return codes should be consistent (=0= success, non-zero failure) or + use clearly documented enums. + +* 2. Python Addendum + +** 2.1 Indentation and Layout + +Python enforces indentation syntactically, so the RT two-space rule +becomes: + +1. Use *two-space indentation* for all Python code, even though four is + common in the wider ecosystem. +2. Vertical comma lists still place the comma at the start of the line, + after the indentation. + +Example: + +#+BEGIN_SRC python +items = [ + first_item + ,second_item + ,third_item +] +#+END_SRC + +** 2.2 Modules and CLI Separation + +Python scripts distinguish between: + +1. *Work functions* (importable API). +2. *CLI entry points* (argument parsing, printing, exit codes). + +Pattern: + +1. Put reusable logic into functions and classes. +2. Put argument parsing and =if __name__ == "__main__":= in the CLI + section. +3. Keep side effects out of import time. + +** 2.3 Error Handling + +1. Raise exceptions for exceptional conditions. +2. Catch exceptions at the CLI boundary and convert them into user + messages and exit codes. +3. Avoid catching broad =Exception= unless it is immediately converted + into a controlled failure. + +* 3. Bash Addendum + +** 3.1 Shebang and Safety + +Bash scripts should start with: + +#+BEGIN_SRC sh +#!/usr/bin/env bash +set -euo pipefail +#+END_SRC + +Explanation: + +1. =-e= :: Exit on error. +2. =-u= :: Treat unset variables as errors. +3. =-o pipefail= :: Propagate errors across pipelines. + +** 3.2 Functions vs. Top-Level Code + +RT-style Bash separates: + +1. A small top-level CLI harness (argument parsing, usage, dispatch). +2. A set of functions that implement the work. + +Pattern: + +1. Parse arguments into variables. +2. Call a main function with explicit parameters. +3. Avoid relying on global mutable state where possible. + +** 3.3 Logging and Diagnostics + +1. Use =printf= or =echo= for user-facing messages. +2. Send debug or trace output to stderr (=>&2=). +3. Make it obvious when the script is changing system state (e.g. + mounting, creating users, modifying firewall rules). + +* 4. Using the Addenda + +When in doubt: + +1. Start with =02_RT_Code_Format.org= for the core rules. +2. Apply the relevant language section here. +3. If a language requires deviation from the generic rules, document + that deviation in this file instead of ad-hoc decisions. + +#+BEGIN_EXPORT html +
+#+END_EXPORT diff --git a/administrator/document/style/RT_TOC.js b/administrator/document/style/RT_TOC.js new file mode 100644 index 0000000..86ee51a --- /dev/null +++ b/administrator/document/style/RT_TOC.js @@ -0,0 +1,102 @@ +/* + Processes tags. + Populates each with headings found below it. + + Attributes: + level="N" : Explicitly sets the target heading level (1-6). + e.g., level="1" collects H1s. level="2" collects H2s. + Stops collecting if it hits a heading of (level - 1) or higher. + + Default (No attribute): + Context-Aware. Looks backwards for the nearest heading H(N). + Targets H(N+1). Stops at the next H(N). +*/ +window.StyleRT = window.StyleRT || {}; + +window.StyleRT.RT_TOC = function() { + const debug = window.StyleRT.debug || { log: function(){} }; + const toc_tags = document.querySelectorAll('rt-toc'); + + toc_tags.forEach((container, toc_index) => { + container.style.display = 'block'; + + // 1. Determine Target Level + const attr_level = parseInt(container.getAttribute('level')); + let target_level; + + if (!isNaN(attr_level)) { + // EXPLICIT MODE + target_level = attr_level; + if (debug.log) debug.log('RT_TOC', `TOC #${toc_index} explicit target: H${target_level}`); + } else { + // IMPLICIT / CONTEXT MODE + let context_level = 0; // Default 0 (Root) + let prev = container.previousElementSibling; + while (prev) { + const match = prev.tagName.match(/^H([1-6])$/); + if (match) { + context_level = parseInt(match[1]); + break; + } + prev = prev.previousElementSibling; + } + target_level = context_level + 1; + if (debug.log) debug.log('RT_TOC', `TOC #${toc_index} context implied target: H${target_level}`); + } + + // Stop condition: Stop if we hit a heading that is a "parent" or "sibling" of the context. + // Mathematically: Stop if found_level < target_level. + const stop_threshold = target_level; + + // 2. Setup Container + container.innerHTML = ''; + const title = document.createElement('h1'); + // Title logic: If targeting H1, it's a Main TOC. Otherwise it's a Section TOC. + title.textContent = target_level === 1 ? 'Table of Contents' : 'Section Contents'; + title.style.textAlign = 'center'; + container.appendChild(title); + + const list = document.createElement('ul'); + list.style.listStyle = 'none'; + list.style.paddingLeft = '0'; + container.appendChild(list); + + // 3. Scan Forward + let next_el = container.nextElementSibling; + while (next_el) { + const match = next_el.tagName.match(/^H([1-6])$/); + if (match) { + const found_level = parseInt(match[1]); + + // STOP Logic: + // If we are looking for H2s, we stop if we hit an H1 (level 1). + // If we are looking for H1s, we stop if we hit... nothing (level 0). + if (found_level < target_level) { + break; + } + + // COLLECT Logic: + if (found_level === target_level) { + if (!next_el.id) next_el.id = `toc-ref-${toc_index}-${found_level}-${list.children.length}`; + + const li = document.createElement('li'); + li.style.marginBottom = '0.5rem'; + + const a = document.createElement('a'); + a.href = `#${next_el.id}`; + a.textContent = next_el.textContent; + a.style.textDecoration = 'none'; + a.style.color = 'inherit'; + a.style.display = 'block'; + + a.onmouseover = () => a.style.color = 'var(--rt-brand-primary)'; + a.onmouseout = () => a.style.color = 'inherit'; + + li.appendChild(a); + list.appendChild(li); + } + } + next_el = next_el.nextElementSibling; + } + }); +}; diff --git a/administrator/document/style/RT_code.js b/administrator/document/style/RT_code.js new file mode 100644 index 0000000..bc3418c --- /dev/null +++ b/administrator/document/style/RT_code.js @@ -0,0 +1,129 @@ +/* + Processes tags. + Uses the central config or CSS variables from the theme. + + Removes common indent from lines of code. +*/ +function RT_code() { + const RT = window.StyleRT; + const U = RT.utility; + const debug = RT.debug; + + debug.log('RT_code', 'Starting render cycle.'); + + const metrics = U.measure_ink_ratio('monospace'); + + document.querySelectorAll('rt-code').forEach((el) => { + el.style.fontFamily = 'monospace'; + + const computed = window.getComputedStyle(el); + const accent = computed.getPropertyValue('--rt-accent').trim() || 'gold'; + + const is_block = U.is_block_content(el); + const parentColor = computed.color; + const is_text_light = U.is_color_light(parentColor); + + const alpha = is_block ? 0.08 : 0.15; + const overlay = is_text_light ? `rgba(255,255,255,${alpha})` : `rgba(0,0,0,${alpha})`; + const text_color = is_text_light ? '#ffffff' : '#000000'; + + el.style.backgroundColor = overlay; + + if (is_block) { + el.style.display = 'block'; + + // --- Tag-Relative Auto-Dedent Logic --- + + // 1. Get Tag Indentation (The Anchor) + let tagIndent = ''; + const prevNode = el.previousSibling; + if (prevNode && prevNode.nodeType === 3) { + const prevText = prevNode.nodeValue; + const lastNewLineIndex = prevText.lastIndexOf('\n'); + if (lastNewLineIndex !== -1) { + tagIndent = prevText.substring(lastNewLineIndex + 1); + } else if (/^\s*$/.test(prevText)) { + tagIndent = prevText; + } + } + + // 2. Calculate Common Leading Whitespace from Content + const rawLines = el.textContent.split('\n'); + + // Filter out empty lines for calculation purposes so they don't break the logic + const contentLines = rawLines.filter(line => line.trim().length > 0); + + let commonIndent = null; + + if (contentLines.length > 0) { + // Assume the first line sets the standard + const firstMatch = contentLines[0].match(/^\s*/); + commonIndent = firstMatch ? firstMatch[0] : ''; + + // Reduce the commonIndent if subsequent lines have LESS indentation + for (let i = 1; i < contentLines.length; i++) { + const line = contentLines[i]; + // Determine how much of commonIndent this line shares + let j = 0; + while (j < commonIndent.length && j < line.length && commonIndent[j] === line[j]) { + j++; + } + commonIndent = commonIndent.substring(0, j); + if (commonIndent.length === 0) break; // Optimization + } + } else { + commonIndent = ''; + } + + // 3. Process Content + // Rule: Only strip if the Common Indent contains the Tag Indent (Safety Check) + // This handles the Emacs case: Tag is " ", Common is " ". " " starts with " ". + // We strip " ", leaving the code flush left. + let finalString = ''; + + if (commonIndent.length > 0 && commonIndent.startsWith(tagIndent)) { + const cleanedLines = rawLines.map(line => { + // Strip the common indent from valid lines + return line.startsWith(commonIndent) ? line.replace(commonIndent, '') : line; + }); + + // Remove artifact lines (first/last empty lines) + if (cleanedLines.length > 0 && cleanedLines[0].length === 0) { + cleanedLines.shift(); + } + if (cleanedLines.length > 0 && cleanedLines[cleanedLines.length - 1].trim().length === 0) { + cleanedLines.pop(); + } + finalString = cleanedLines.join('\n'); + } else { + // Fallback: Code is to the left of the tag or weirdly formatted. + // Just trim the wrapper newlines. + finalString = el.textContent.trim(); + } + + el.textContent = finalString; + // --- End Indentation Logic --- + + el.style.whiteSpace = 'pre'; + el.style.fontSize = (parseFloat(computed.fontSize) * metrics.ratio * 0.95) + 'px'; + el.style.padding = '1.2rem'; + el.style.margin = '1.5rem 0'; + el.style.borderLeft = `4px solid ${accent}`; + el.style.color = 'inherit'; + } else { + el.style.display = 'inline'; + const exactPx = parseFloat(computed.fontSize) * metrics.ratio * 1.0; + el.style.fontSize = exactPx + 'px'; + el.style.padding = '0.1rem 0.35rem'; + el.style.borderRadius = '3px'; + const offsetPx = metrics.baseline_diff * (exactPx / 100); + el.style.verticalAlign = offsetPx + 'px'; + el.style.color = text_color; + } + }); + + debug.log('RT_code', 'Render cycle complete.'); +} + +window.StyleRT = window.StyleRT || {}; +window.StyleRT.RT_code = RT_code; diff --git a/administrator/document/style/RT_math.js b/administrator/document/style/RT_math.js new file mode 100644 index 0000000..2d07cfa --- /dev/null +++ b/administrator/document/style/RT_math.js @@ -0,0 +1,35 @@ +/* + Processes tags. + JavaScript: RT_math() + HTML Tag: (parsed as rt-math) +*/ +function RT_math(){ + // querySelector treats 'rt-math' as case-insensitive for the tag + document.querySelectorAll('rt-math').forEach(el => { + if (el.textContent.startsWith('$')) return; + + const is_block = el.parentElement.tagName === 'DIV' || + el.textContent.includes('\n') || + el.parentElement.childNodes.length === 1; + + const delimiter = is_block ? '$$' : '$'; + el.style.display = is_block ? 'block' : 'inline'; + el.textContent = `${delimiter}${el.textContent.trim()}${delimiter}`; + }); + + // MathJax must find its config at window.MathJax + window.MathJax = { + tex: { + inlineMath: [['$', '$']], + displayMath: [['$$', '$$']] + } + }; + + const script = document.createElement('script'); + script.src = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js'; + script.async = true; + document.head.appendChild(script); +} + +window.StyleRT = window.StyleRT || {}; +window.StyleRT.RT_math = RT_math; diff --git a/administrator/document/style/RT_term.js b/administrator/document/style/RT_term.js new file mode 100644 index 0000000..1dec8fb --- /dev/null +++ b/administrator/document/style/RT_term.js @@ -0,0 +1,107 @@ +/* + Processes and tags. + - Styles only the first occurrence of a unique term/neologism. + - The "-em" variants (e.g., ) are always styled. + - Automatically generates IDs for first occurrences for future indexing. +*/ + +window.StyleRT = window.StyleRT || {}; + +window.StyleRT.RT_term = function() { + const RT = window.StyleRT; + + const debug = RT.debug || { + log: function() {} + ,warn: function() {} + ,error: function() {} + }; + + const DEBUG_TOKEN_S = 'term'; + + try { + // Track seen terms so only the first occurrence is decorated + const seen_terms_dpa = new Set(); + + const apply_style = (el, is_neologism_b) => { + el.style.fontStyle = 'italic'; + el.style.fontWeight = is_neologism_b ? '600' : '500'; + el.style.color = is_neologism_b + ? 'var(--rt-brand-secondary)' + : 'var(--rt-brand-primary)'; + el.style.paddingRight = '0.1em'; // Compensation for italic slant + el.style.display = 'inline'; + }; + + const clear_style = (el) => { + el.style.fontStyle = 'normal'; + el.style.color = 'inherit'; + el.style.fontWeight = 'inherit'; + el.style.paddingRight = ''; + el.style.display = ''; + }; + + const selector_s = [ + 'rt-term' + ,'rt-term-em' + ,'rt-neologism' + ,'rt-neologism-em' + ].join(','); + + const tags_dpa = document.querySelectorAll(selector_s); + + debug.log(DEBUG_TOKEN_S, `Scanning ${tags_dpa.length} term tags`); + + tags_dpa.forEach(el => { + const tag_name_s = el.tagName.toLowerCase(); + const is_neologism_b = tag_name_s.includes('neologism'); + const is_explicit_em_b = tag_name_s.endsWith('-em'); + + const term_text_raw_s = (el.textContent || '').trim(); + if (!term_text_raw_s.length) { + debug.warn(DEBUG_TOKEN_S, `Empty term tag encountered: <${tag_name_s}>`); + return; + } + + // Normalize text for uniqueness tracking + const term_norm_s = term_text_raw_s.toLowerCase(); + + // Slug for ID generation (simple + stable) + const slug_s = term_norm_s.replace(/\s+/g, '-'); + + const is_first_occurrence_b = !seen_terms_dpa.has(term_norm_s); + + if (is_explicit_em_b || is_first_occurrence_b) { + apply_style(el, is_neologism_b); + + if (!is_explicit_em_b && is_first_occurrence_b) { + seen_terms_dpa.add(term_norm_s); + + if (!el.id) { + el.id = `def-${is_neologism_b ? 'neo-' : ''}${slug_s}`; + debug.log( + DEBUG_TOKEN_S + ,`First occurrence: "${term_norm_s}" -> id="${el.id}"` + ); + } else { + debug.log( + DEBUG_TOKEN_S + ,`First occurrence: "${term_norm_s}" (existing id="${el.id}")` + ); + } + } else if (is_explicit_em_b) { + debug.log( + DEBUG_TOKEN_S + ,`Emphasized occurrence: "${term_norm_s}" (<${tag_name_s}>)` + ); + } + } else { + // Subsequent mentions render as normal prose + clear_style(el); + } + }); + + debug.log(DEBUG_TOKEN_S, `Unique terms defined: ${seen_terms_dpa.size}`); + } catch (e) { + debug.error('error', `RT_term failed: ${e && e.message ? e.message : String(e)}`); + } +}; diff --git a/administrator/document/style/RT_title.js b/administrator/document/style/RT_title.js new file mode 100644 index 0000000..93757f8 --- /dev/null +++ b/administrator/document/style/RT_title.js @@ -0,0 +1,60 @@ +/* + Processes tags. + Generates a standard document header block. + + Usage: + +*/ +window.StyleRT = window.StyleRT || {}; + +window.StyleRT.RT_title = function() { + const debug = window.StyleRT.debug || { log: function(){} }; + + document.querySelectorAll('rt-title').forEach(el => { + const title = el.getAttribute('title') || 'Untitled Document'; + const author = el.getAttribute('author'); + const date = el.getAttribute('date'); + + if (debug.log) debug.log('RT_title', `Generating title block: ${title}`); + + // Container + const container = document.createElement('div'); + container.style.textAlign = 'center'; + container.style.marginBottom = '3rem'; + container.style.marginTop = '2rem'; + container.style.borderBottom = '1px solid var(--rt-border-default)'; + container.style.paddingBottom = '1.5rem'; + + // Main Title (H1) + const h1 = document.createElement('h1'); + h1.textContent = title; + h1.style.margin = '0 0 0.8rem 0'; + h1.style.border = 'none'; // Override standard H1 border + h1.style.padding = '0'; + h1.style.color = 'var(--rt-brand-primary)'; + h1.style.fontSize = '2.5em'; + h1.style.lineHeight = '1.1'; + h1.style.letterSpacing = '-0.03em'; + + container.appendChild(h1); + + // Metadata Row (Author | Date) + if (author || date) { + const meta = document.createElement('div'); + meta.style.color = 'var(--rt-content-muted)'; + meta.style.fontStyle = 'italic'; + meta.style.fontSize = '1.1em'; + meta.style.fontFamily = '"Georgia", "Times New Roman", serif'; // Classy serif + + const parts = []; + if (author) parts.push(`${author}`); + if (date) parts.push(date); + + meta.innerHTML = parts.join('  —  '); + container.appendChild(meta); + } + + // Replace the raw tag with the generated block + el.replaceWith(container); + }); +}; diff --git a/administrator/document/style/Rubio.js b/administrator/document/style/Rubio.js new file mode 100644 index 0000000..cd21a5a --- /dev/null +++ b/administrator/document/style/Rubio.js @@ -0,0 +1,15 @@ +/* Style: The "State Department" Override + Description: Restores decorum. +*/ +(function(){ + const RT = window.StyleRT || {}; + + // Force the font regardless of other settings + RT.rubio = function() { + const articles = document.querySelectorAll("rt-article"); + articles.forEach(el => { + el.style.fontFamily = '"Times New Roman", "Times", serif'; + el.style.letterSpacing = "0px"; // No modern spacing allowed + }); + }; +})(); diff --git a/administrator/document/style/article_tech_ref.js b/administrator/document/style/article_tech_ref.js new file mode 100644 index 0000000..8ad9dbb --- /dev/null +++ b/administrator/document/style/article_tech_ref.js @@ -0,0 +1,170 @@ +/* + Article Layout: Technical Reference + Standard: Theme 1.0 + Description: High-readability layout for technical documentation on screens. + Features: Sans-serif, justified text, distinct headers, boxed code. +*/ +(function(){ + const RT = window.StyleRT = window.StyleRT || {}; + + RT.article = function() { + const debug = RT.debug || { log: function(){} }; + debug.log('layout', 'RT.article starting...'); + + RT.config = RT.config || {}; + + // Default Configuration + RT.config.article = { + font_family: '"Noto Sans", "Segoe UI", "Helvetica Neue", sans-serif' + ,line_height: "1.8" + ,font_size: "16px" + ,font_weight: "400" // Default (String) + ,max_width: "820px" + ,margin: "0 auto" + }; + + // SAFE THEME DETECTION + // If the theme is loaded and explicitly Light, bump the weight. + try { + if (RT.config.theme && RT.config.theme.meta_is_dark === false) { + RT.config.article.font_weight = "600"; + debug.log('layout', 'Light theme detected: adjusting font weight to 600.'); + } + } catch(e) { + console.warn("StyleRT: Auto-weight adjustment failed, using default.", e); + } + + const conf = RT.config.article; + const article_seq = document.querySelectorAll("RT-article"); + + if(article_seq.length === 0) { + debug.log('layout', 'No elements found. Exiting.'); + return; + } + + // 1. Apply Container Styles + article_seq.forEach( (article) =>{ + const style = article.style; + style.display = "block"; + style.fontFamily = conf.font_family; + style.fontSize = conf.font_size; + style.lineHeight = conf.line_height; + style.fontWeight = conf.font_weight; + style.maxWidth = conf.max_width; + style.margin = conf.margin; + style.padding = "0 20px"; + style.color = "var(--rt-content-main)"; + }); + + // 2. Inject Child Typography + const style_id = 'rt-article-typography'; + if (!document.getElementById(style_id)) { + debug.log('layout', 'Injecting CSS typography rules.'); + const style_el = document.createElement('style'); + style_el.id = style_id; + + style_el.textContent = ` + /* --- HEADERS --- */ + rt-article h1 { + color: var(--rt-brand-primary); + font-size: 2.0em; + font-weight: 500; + text-align: center; + margin-top: 1.2em; + margin-bottom: 0.6em; + border-bottom: 2px solid var(--rt-border-default); + padding-bottom: 0.3em; + line-height: 1.2; + letter-spacing: -0.02em; + } + + rt-article h2 { + color: var(--rt-brand-secondary); + font-size: 1.5em; + font-weight: 400; + text-align: center; + margin-top: 1.0em; + margin-bottom: 0.5em; + } + + rt-article h2 + h3 { + margin-top: -0.3em; + padding-top: 0; + } + + rt-article h3 { + color: var(--rt-brand-tertiary); + font-size: 1.4em; + font-weight: 400; + margin-top: 1.0em; + margin-bottom: 0.5em; + } + + /* --- DEEP LEVELS (H4-H6) --- */ + rt-article h4, rt-article h5, rt-article h6 { + color: var(--rt-brand-tertiary); + font-weight: bold; + margin-top: 1.2em; + font-style: italic; + } + rt-article h4 { margin-left: 2em; } + rt-article h5 { margin-left: 4em; } + rt-article h6 { margin-left: 6em; } + + /* --- BODY TEXT --- */ + rt-article p { + margin-bottom: 1.4em; + text-align: justify; + hyphens: auto; + color: var(--rt-content-main); + } + + /* --- RICH ELEMENTS --- */ + rt-article blockquote { + border-left: 4px solid var(--rt-brand-secondary); + margin: 1.5em 0; + padding: 0.5em 1em; + font-style: italic; + color: var(--rt-content-muted); + background: var(--rt-surface-1); + border-radius: 0 4px 4px 0; + } + + rt-article ul, rt-article ol { + margin-bottom: 1.4em; + padding-left: 2em; + } + rt-article li { + margin-bottom: 0.4em; + } + rt-article li::marker { + color: var(--rt-brand-secondary); + font-weight: bold; + } + + /* Links */ + rt-article a { + color: var(--rt-brand-link); + text-decoration: none; + border-bottom: 1px dotted var(--rt-border-default); + transition: all 0.2s; + } + rt-article a:hover { + color: var(--rt-brand-primary); + border-bottom: 1px solid var(--rt-brand-primary); + background: var(--rt-surface-1); + } + + /* --- TECHNICAL --- */ + rt-article pre { + background: var(--rt-surface-code); + padding: 1em; + border-radius: 4px; + overflow-x: auto; + border: 1px solid var(--rt-border-default); + } + `; + document.head.appendChild(style_el); + } + }; +})(); diff --git a/administrator/document/style/body_visibility_hidden.js b/administrator/document/style/body_visibility_hidden.js new file mode 100644 index 0000000..d6a178a --- /dev/null +++ b/administrator/document/style/body_visibility_hidden.js @@ -0,0 +1,12 @@ +/* + Targets the root element to ensure total blackout during load. +*/ +function body_visibility_hidden(){ + const gate = document.createElement('style'); + gate.id = 'rt-visibility-gate'; + gate.textContent = 'html{visibility:hidden !important; background:black !important;}'; + document.head.appendChild(gate); +} + +window.StyleRT = window.StyleRT || {}; +window.StyleRT.body_visibility_hidden = body_visibility_hidden; diff --git a/administrator/document/style/body_visibility_visible.js b/administrator/document/style/body_visibility_visible.js new file mode 100644 index 0000000..ff1c4b6 --- /dev/null +++ b/administrator/document/style/body_visibility_visible.js @@ -0,0 +1,13 @@ +/* + Restores visibility by removing the visibility gate. +*/ +function body_visibility_visible(){ + const gate = document.getElementById('rt-visibility-gate'); + if (gate){ + gate.remove(); + } + document.body.style.visibility = 'visible'; +} + +window.StyleRT = window.StyleRT || {}; +window.StyleRT.body_visibility_visible = body_visibility_visible; diff --git a/administrator/document/style/custom_tag.txt b/administrator/document/style/custom_tag.txt new file mode 100644 index 0000000..146d3ad --- /dev/null +++ b/administrator/document/style/custom_tag.txt @@ -0,0 +1,8 @@ + : The root container. + : The page wrapper. + + + + + : For Conventional terms (standard definitions) +: Terms introduced in this article diff --git a/administrator/document/style/page_fixed_glow.js b/administrator/document/style/page_fixed_glow.js new file mode 100644 index 0000000..91bd648 --- /dev/null +++ b/administrator/document/style/page_fixed_glow.js @@ -0,0 +1,88 @@ +/* + Page Layout: Fixed Glow + Standard: Theme 1.0 + Description: A fixed-height container with a glowing border effect that matches the active theme. +*/ +(function(){ + const RT = window.StyleRT = window.StyleRT || {}; + + // Function name stays generic so the orchestrator can call RT.page() regardless of file choice + RT.page = function() { + RT.config = RT.config || {}; + + // Default Configuration + // We use CSS Variables here so the Theme controls the actual colors. + const defaults = { + width: "100%" + ,height: "1056px" + ,padding: "3rem" + ,margin: "4rem auto" + + // Dynamic Theme Bindings + ,bg_color: "var(--rt-surface-0)" // Black (Dark) or Cream (Light) + ,border_color: "var(--rt-brand-primary)" // The Main Accent Color + ,text_color: "var(--rt-brand-primary)" // Page Number Color + + // The Glow: Uses the primary brand color for the shadow + ,shadow: "drop-shadow(0px 0px 15px var(--rt-brand-primary))" + }; + + // Merge defaults + RT.config.page = Object.assign({}, defaults, RT.config.page || {}); + + const conf = RT.config.page; + const style_id = 'rt-page-fixed-glow'; + + if (!document.getElementById(style_id)) { + const style_el = document.createElement('style'); + style_el.id = style_id; + + style_el.textContent = ` + /* Reset page counter on the article container */ + rt-article { + counter-reset: rt-page-counter; + } + + rt-page { + display: block; + position: relative; + box-sizing: border-box; + overflow: hidden; + + /* Dimensions */ + width: ${conf.width}; + height: ${conf.height}; + margin: ${conf.margin}; + padding: ${conf.padding}; + + /* Theming */ + background-color: ${conf.bg_color}; + border: 1px solid ${conf.border_color}; + + /* The "Glow" Effect */ + filter: ${conf.shadow}; + + /* Counter Increment */ + counter-increment: rt-page-counter; + } + + /* Page Numbering */ + rt-page::after { + content: "Page " counter(rt-page-counter); + position: absolute; + bottom: 1.5rem; + right: 3rem; + + font-family: "Noto Sans", sans-serif; + font-size: 0.9rem; + font-weight: bold; + + color: ${conf.text_color}; + opacity: 0.8; + pointer-events: none; /* Prevent interference with clicks */ + } + `; + document.head.appendChild(style_el); + } + }; +})(); diff --git a/administrator/document/style/paginate_by_element.js b/administrator/document/style/paginate_by_element.js new file mode 100644 index 0000000..e085148 --- /dev/null +++ b/administrator/document/style/paginate_by_element.js @@ -0,0 +1,72 @@ +/* + Layout Paginator: paginate_by_element +*/ +window.StyleRT = window.StyleRT || {}; + +window.StyleRT.paginate_by_element = function() { + const RT = window.StyleRT; + + // Fix: Read safely without overwriting the config namespace + const page_conf = (RT.config && RT.config.page) ? RT.config.page : {}; + const page_height_limit = page_conf.height_limit || 1000; + + const article_seq = document.querySelectorAll("RT-article"); + + // HURDLE: Error if no articles found to paginate + if(article_seq.length === 0) { + RT.debug.error('pagination', 'No elements found. Pagination aborted.'); + return; + } + + article_seq.forEach( (article) => { + const raw_elements = Array.from(article.children).filter(el => + !['SCRIPT', 'STYLE', 'RT-PAGE'].includes(el.tagName) + ); + + if(raw_elements.length === 0) return; + + const pages = []; + let current_batch = []; + let current_h = 0; + + const get_el_height = (el) => { + const rect = el.getBoundingClientRect(); + const style = window.getComputedStyle(el); + const margin = parseFloat(style.marginTop) + parseFloat(style.marginBottom); + return (rect.height || 0) + (margin || 0); + }; + + for (let i = 0; i < raw_elements.length; i++) { + const el = raw_elements[i]; + const h = get_el_height(el); + const is_heading = /^H[1-6]/.test(el.tagName); + + let total_required_h = h; + if (is_heading && i + 1 < raw_elements.length) { + total_required_h += get_el_height(raw_elements[i + 1]); + } + + if (current_h + total_required_h > page_height_limit && current_batch.length > 0) { + pages.push(current_batch); + current_batch = []; + current_h = 0; + } + + current_batch.push(el); + current_h += h; + } + + if (current_batch.length > 0) pages.push(current_batch); + + article.innerHTML = ''; + + pages.forEach( (list, index) => { + const page_el = document.createElement('rt-page'); + page_el.id = `page-${index+1}`; + list.forEach(item => page_el.appendChild(item)); + article.appendChild(page_el); + }); + + if (RT.debug) RT.debug.log('pagination', `Article paginated into ${pages.length} pages.`); + }); +}; diff --git a/administrator/document/style/style_orchestrator.js b/administrator/document/style/style_orchestrator.js new file mode 100644 index 0000000..755c1c8 --- /dev/null +++ b/administrator/document/style/style_orchestrator.js @@ -0,0 +1,92 @@ +/* + Master Loader & Orchestrator for StyleRT. +*/ + +window.StyleRT = window.StyleRT || {}; + +window.StyleRT.style_orchestrator = function() { + const RT = window.StyleRT; + + const modules = [ + // Theme & Semantics + 'style/RT_title.js', + 'style/theme_dark_gold.js', + 'style/RT_term.js', + 'style/RT_math.js', + 'style/RT_code.js', + 'style/article_tech_ref.js', + 'style/RT_TOC.js', + + // Layout & Pagination + 'style/paginate_by_element.js', + 'style/page_fixed_glow.js', + + // Visibility + 'style/body_visibility_visible.js' + ]; + + // 1. Bootloader + const utility = document.createElement('script'); + utility.src = 'style/utility.js'; + + utility.onload = () => { load_next(0); }; + utility.onerror = () => { console.error("StyleRT: Critical failure - utility.js missing."); }; + document.head.appendChild(utility); + + // 2. The Chain Loader + const load_next = (index) => { + if (index >= modules.length) { + run_style(); + return; + } + const src = modules[index]; + if (RT.debug) RT.debug.log('style', `Loading: ${src}`); + + const script = document.createElement('script'); + script.src = src; + script.onload = () => load_next(index + 1); + script.onerror = () => { + console.error(`StyleRT: Failed load on ${src}`); + load_next(index + 1); + }; + document.head.appendChild(script); + }; + + // 3. Phase 1: Semantics + const run_style = () => { + RT.debug.log('style', 'Starting Phase 1: Setup & Semantics'); + + // Naming Convention: RT. + if(RT.theme) RT.theme(); + if(RT.article) RT.article(); + + // NEW: Trigger the Title Generator + if(RT.RT_title) RT.RT_title(); + + if(RT.RT_term) RT.RT_term(); + if(RT.RT_math) RT.RT_math(); + if(RT.RT_code) RT.RT_code(); + + if (window.MathJax && MathJax.Hub && MathJax.Hub.Queue) { + RT.debug.log('style', 'MathJax detected. Queueing layout tasks...'); + MathJax.Hub.Queue(["Typeset", MathJax.Hub], continue_style); + } else { + continue_style(); + } + }; + + // 4. Phase 2: Layout + const continue_style = () => { + RT.debug.log('style', 'Starting Phase 2: Layout & Reveal'); + + // Debug: Dump the config to see what values we are using + if(RT.debug) RT.debug.log('config', JSON.stringify(RT.config || {}, null, 2)); + + if(RT.RT_TOC) RT.RT_TOC(); + if(RT.paginate_by_element) RT.paginate_by_element(); + if(RT.page) RT.page(); // Defined in page_css_pn.js + if(RT.body_visibility_visible) RT.body_visibility_visible(); + + RT.debug.log('style', 'Style execution complete.'); + }; +}; diff --git a/administrator/document/style/theme_dark_gold.js b/administrator/document/style/theme_dark_gold.js new file mode 100644 index 0000000..f576147 --- /dev/null +++ b/administrator/document/style/theme_dark_gold.js @@ -0,0 +1,94 @@ +/* + Theme: Inverse Wheat (Dark) + Standard: Theme 1.0 + Description: High contrast Amber on Deep Charcoal. +*/ +( function(){ + const RT = window.StyleRT = window.StyleRT || {}; + + RT.theme = function(){ + RT.config = RT.config || {}; + + // THEME 1.0 DATA CONTRACT + RT.config.theme = { + meta_is_dark: true + ,meta_name: "Inverse Wheat" + + // --- SURFACES (Depth & Container Hierarchy) --- + ,surface_0: "hsl(0, 0%, 5%)" // App Background (Deepest) + ,surface_1: "hsl(0, 0%, 10%)" // Sidebar / Nav / Panels + ,surface_2: "hsl(0, 0%, 14%)" // Cards / Floating Elements + ,surface_3: "hsl(0, 0%, 18%)" // Modals / Dropdowns / Popovers + ,surface_input: "hsl(0, 0%, 12%)" // Form Inputs + ,surface_code: "hsl(0, 0%, 11%)" // Code Block Background + ,surface_select: "hsl(45, 100%, 15%)" // Text Selection Highlight + + // --- CONTENT (Text & Icons) --- + ,content_main: "hsl(50, 60%, 85%)" // Primary Reading Text + ,content_muted: "hsl(36, 15%, 60%)" // Metadata, subtitles + ,content_subtle: "hsl(36, 10%, 40%)" // Placeholders, disabled states + ,content_inverse: "hsl(0, 0%, 5%)" // Text on high-contrast buttons + + // --- BRAND & ACTION (The "Wheat" Identity) --- + ,brand_primary: "hsl(45, 100%, 50%)" // Main Action / H1 / Focus Ring + ,brand_secondary: "hsl(38, 90%, 65%)" // Secondary Buttons / H2 + ,brand_tertiary: "hsl(30, 60%, 70%)" // Accents / H3 + ,brand_link: "hsl(48, 100%, 50%)" // Hyperlinks (High Visibility) + + // --- BORDERS & DIVIDERS --- + ,border_faint: "hsl(36, 20%, 15%)" // Subtle separation + ,border_default: "hsl(36, 20%, 25%)" // Standard Card Borders + ,border_strong: "hsl(36, 20%, 40%)" // Active states / Inputs + + // --- STATE & FEEDBACK (Earth Tones) --- + ,state_success: "hsl(100, 50%, 45%)" // Olive Green + ,state_warning: "hsl(35, 90%, 55%)" // Burnt Orange + ,state_error: "hsl(0, 60%, 55%)" // Brick Red + ,state_info: "hsl(200, 40%, 55%)" // Slate Blue + + // --- SYNTAX HIGHLIGHTING (For Code) --- + ,syntax_keyword: "hsl(35, 100%, 65%)" // Orange + ,syntax_string: "hsl(75, 50%, 60%)" // Sage Green + ,syntax_func: "hsl(45, 90%, 70%)" // Light Gold + ,syntax_comment: "hsl(36, 15%, 45%)" // Brown/Gray + }; + + // --- APPLY THEME --- + const palette = RT.config.theme; + const body = document.body; + const html = document.documentElement; + + // 1. Paint Base + html.style.backgroundColor = palette.surface_0; + body.style.backgroundColor = palette.surface_0; + body.style.color = palette.content_main; + + // 2. Export Variables (Standardization) + const s = body.style; + for (const [key, value] of Object.entries(palette)) { + s.setProperty(`--rt-${key.replace(/_/g, '-')}`, value); + } + + // 3. Global Overrides + const style_id = 'rt-global-overrides'; + if (!document.getElementById(style_id)) { + const style = document.createElement('style'); + style.id = style_id; + style.textContent = ` + ::selection { background: var(--rt-surface-select); color: var(--rt-brand-primary); } + ::-moz-selection { background: var(--rt-surface-select); color: var(--rt-brand-primary); } + + ::-webkit-scrollbar { width: 12px; } + ::-webkit-scrollbar-track { background: var(--rt-surface-0); } + ::-webkit-scrollbar-thumb { + background: var(--rt-border-default); + border: 2px solid var(--rt-surface-0); + border-radius: 8px; + } + ::-webkit-scrollbar-thumb:hover { background: var(--rt-brand-secondary); } + `; + document.head.appendChild(style); + } + }; + +} )(); diff --git a/administrator/document/style/theme_light.js b/administrator/document/style/theme_light.js new file mode 100644 index 0000000..4b5eea4 --- /dev/null +++ b/administrator/document/style/theme_light.js @@ -0,0 +1,70 @@ +/* + Theme: Classic Wheat (Light) + Standard: Theme 1.0 + Description: Warm paper tones with Burnt Orange accents. +*/ +( function(){ + const RT = window.StyleRT = window.StyleRT || {}; + + RT.theme_light = function(){ + RT.config = RT.config || {}; + + // THEME 1.0 DATA CONTRACT + RT.config.theme = { + meta_is_dark: false + ,meta_name: "Classic Wheat" + + // --- SURFACES --- + ,surface_0: "hsl(40, 30%, 94%)" // App Background (Cream/Linen) + ,surface_1: "hsl(40, 25%, 90%)" // Sidebar (Slightly darker beige) + ,surface_2: "hsl(40, 20%, 98%)" // Cards (Lighter, almost white) + ,surface_3: "hsl(0, 0%, 100%)" // Modals (Pure White) + ,surface_input: "hsl(40, 20%, 98%)" // Form Inputs + ,surface_code: "hsl(40, 15%, 90%)" // Code Block Background + ,surface_select: "hsl(45, 100%, 85%)" // Text Selection Highlight + + // --- CONTENT --- + ,content_main: "hsl(30, 20%, 20%)" // Deep Umber (Not Black) + ,content_muted: "hsl(30, 15%, 45%)" // Medium Brown + ,content_subtle: "hsl(30, 10%, 65%)" // Light Brown/Gray + ,content_inverse: "hsl(40, 30%, 94%)" // Text on dark buttons + + // --- BRAND & ACTION --- + ,brand_primary: "hsl(30, 90%, 35%)" // Burnt Orange (Action) + ,brand_secondary: "hsl(35, 70%, 45%)" // Rust / Gold + ,brand_tertiary: "hsl(25, 60%, 55%)" // Copper + ,brand_link: "hsl(30, 100%, 35%)" // Link Color + + // --- BORDERS --- + ,border_faint: "hsl(35, 20%, 85%)" + ,border_default: "hsl(35, 20%, 75%)" + ,border_strong: "hsl(35, 20%, 55%)" + + // --- STATE & FEEDBACK --- + ,state_success: "hsl(100, 40%, 40%)" // Forest Green + ,state_warning: "hsl(30, 90%, 50%)" // Persimmon + ,state_error: "hsl(0, 60%, 45%)" // Crimson + ,state_info: "hsl(200, 50%, 45%)" // Navy Blue + + // --- SYNTAX --- + ,syntax_keyword: "hsl(20, 90%, 45%)" // Rust + ,syntax_string: "hsl(100, 35%, 35%)" // Ivy Green + ,syntax_func: "hsl(300, 30%, 40%)" // Muted Purple + ,syntax_comment: "hsl(35, 10%, 60%)" // Light Brown + }; + + // --- APPLY THEME --- + const palette = RT.config.theme; + const body = document.body; + const html = document.documentElement; + + html.style.backgroundColor = palette.surface_0; + body.style.backgroundColor = palette.surface_0; + body.style.color = palette.content_main; + + const s = body.style; + for (const [key, value] of Object.entries(palette)) { + s.setProperty(`--rt-${key.replace(/_/g, '-')}`, value); + } + }; +} )(); diff --git a/administrator/document/style/theme_light_gold.js b/administrator/document/style/theme_light_gold.js new file mode 100644 index 0000000..206f3da --- /dev/null +++ b/administrator/document/style/theme_light_gold.js @@ -0,0 +1,103 @@ +/* + Theme: Golden Wheat (Light) - "Spanish Gold Edition" + File: style/theme-light-gold.js + Standard: Theme 1.0 + Description: Light Parchment background with Oxblood Red ink. +*/ +( function(){ + const RT = window.StyleRT = window.StyleRT || {}; + + RT.theme = function(){ + RT.config = RT.config || {}; + + RT.config.theme = { + meta_is_dark: false + ,meta_name: "Golden Wheat (Yellow)" + + // --- SURFACES (Light Parchment) --- + // Shifted lightness up to 94% for a "whiter" feel that still holds the yellow tint. + ,surface_0: "hsl(48, 50%, 94%)" // Main Page: Fine Parchment + ,surface_1: "hsl(48, 40%, 90%)" // Panels: Slightly darker + ,surface_2: "hsl(48, 30%, 97%)" // Cards: Very light + ,surface_3: "hsl(0, 0%, 100%)" // Popups + ,surface_input: "hsl(48, 20%, 96%)" + ,surface_code: "hsl(48, 25%, 88%)" // Distinct Code BG + ,surface_select: "hsl(10, 70%, 85%)" // Red Highlight + + // --- CONTENT (Deep Ink) --- + ,content_main: "hsl(10, 25%, 7%)" // Deep Warm Black (Ink) + ,content_muted: "hsl(10, 15%, 35%)" // Dark Grey-Red + ,content_subtle: "hsl(10, 10%, 55%)" + ,content_inverse: "hsl(48, 50%, 90%)" + + // --- BRAND & ACTION (The Red Spectrum) --- + ,brand_primary: "hsl(12, 85%, 30%)" // H1 (Deep Oxblood) + ,brand_secondary: "hsl(10, 80%, 35%)" // H2 (Garnet) + ,brand_tertiary: "hsl(8, 70%, 40%)" // H3 (Brick) + ,brand_link: "hsl(12, 90%, 35%)" // Link + + // --- BORDERS --- + ,border_faint: "hsl(45, 30%, 80%)" + ,border_default: "hsl(45, 30%, 70%)" // Pencil Grey + ,border_strong: "hsl(12, 50%, 40%)" + + // --- STATE --- + ,state_success: "hsl(120, 40%, 30%)" + ,state_warning: "hsl(25, 90%, 45%)" + ,state_error: "hsl(0, 75%, 35%)" + ,state_info: "hsl(210, 60%, 40%)" + + // --- SYNTAX --- + ,syntax_keyword: "hsl(0, 75%, 35%)" + ,syntax_string: "hsl(100, 35%, 25%)" + ,syntax_func: "hsl(15, 85%, 35%)" + ,syntax_comment: "hsl(45, 20%, 50%)" + }; + + // --- APPLY THEME --- + const palette = RT.config.theme; + const body = document.body; + const html = document.documentElement; + + html.style.backgroundColor = palette.surface_0; + body.style.backgroundColor = palette.surface_0; + body.style.color = palette.content_main; + + const s = body.style; + for (const [key, value] of Object.entries(palette)) { + s.setProperty(`--rt-${key.replace(/_/g, '-')}`, value); + } + + // Global overrides + const style_id = 'rt-global-overrides'; + if (!document.getElementById(style_id)) { + const style = document.createElement('style'); + style.id = style_id; + style.textContent = ` + ::selection { background: var(--rt-surface-select); color: var(--rt-brand-primary); } + ::-moz-selection { background: var(--rt-surface-select); color: var(--rt-brand-primary); } + + ::-webkit-scrollbar { width: 12px; } + ::-webkit-scrollbar-track { background: var(--rt-surface-0); } + ::-webkit-scrollbar-thumb { + background: var(--rt-border-default); + border: 2px solid var(--rt-surface-0); + border-radius: 8px; + } + ::-webkit-scrollbar-thumb:hover { background: var(--rt-brand-secondary); } + + rt-article p, rt-article li { + text-shadow: 0px 0px 0.5px rgba(0,0,0, 0.2); + } + + .MathJax, .MathJax_Display, .mjx-chtml { + color: var(--rt-content-main) !important; + fill: var(--rt-content-main) !important; + stroke: var(--rt-content-main) !important; + } + `; + document.head.appendChild(style); + } + }; + +} )(); diff --git a/administrator/document/style/utility.js b/administrator/document/style/utility.js new file mode 100644 index 0000000..258eb28 --- /dev/null +++ b/administrator/document/style/utility.js @@ -0,0 +1,109 @@ +/* + General utilities for the StyleRT library. +*/ + +window.StyleRT = window.StyleRT || {}; + +// --- DEBUG SYSTEM --- +window.StyleRT.debug = { + + // all debug messages enabled +/* + active_tokens: new Set([ + 'style', 'layout', 'pagination' + ,'selector', 'config', 'error' + ,'term' + ]), +*/ + active_tokens: new Set([ + 'term' + ]), + + log: function(token, message) { + if (this.active_tokens.has(token)) { + console.log(`[StyleRT:${token}]`, message); + } + }, + + warn: function(token, message) { + if (this.active_tokens.has(token)) { + console.warn(`[StyleRT:${token}]`, message); + } + }, + + // New: Always log errors regardless of token, but tag them + error: function(token, message) { + console.error(`[StyleRT:${token}] CRITICAL:`, message); + }, + + enable: function(token) { this.active_tokens.add(token); console.log(`Enabled: ${token}`); }, + disable: function(token) { this.active_tokens.delete(token); console.log(`Disabled: ${token}`); } +}; + +// --- UTILITIES --- +window.StyleRT.utility = { + // --- FONT PHYSICS --- + measure_ink_ratio: function(target_font, ref_font = null) { + const debug = window.StyleRT.debug; + debug.log('layout', `Measuring ink ratio for ${target_font}`); + + const canvas = document.createElement('canvas'); + const ctx = canvas.getContext('2d'); + + if (!ref_font) { + const bodyStyle = window.getComputedStyle(document.body); + ref_font = bodyStyle.fontFamily; + } + + const get_metrics = (font) => { + ctx.font = '100px ' + font; + const metrics = ctx.measureText('M'); + return { + ascent: metrics.actualBoundingBoxAscent, + descent: metrics.actualBoundingBoxDescent + }; + }; + + const ref_m = get_metrics(ref_font); + const target_m = get_metrics(target_font); + + const ratio = ref_m.ascent / target_m.ascent; + // debug.log('layout', `Ink Ratio calculated: ${ratio.toFixed(3)}`); + + return { + ratio: ratio, + baseline_diff: ref_m.descent - target_m.descent + }; + }, + + // --- COLOR PHYSICS --- + is_color_light: function(color_string) { + const debug = window.StyleRT.debug; + + // 1. HSL Check + if (color_string.startsWith('hsl')) { + const numbers = color_string.match(/\d+/g); + if (numbers && numbers.length >= 3) { + const lightness = parseInt(numbers[2]); + return lightness > 50; + } + } + + // 2. RGB Check + const rgb = color_string.match(/\d+/g); + if (!rgb) { + // debug.warn('color_layout', `Failed to parse color: "${color_string}". Defaulting to Light.`); + return true; + } + + const r = parseInt(rgb[0]); + const g = parseInt(rgb[1]); + const b = parseInt(rgb[2]); + const luma = (r * 299 + g * 587 + b * 114) / 1000; + return luma > 128; + }, + + is_block_content: function(element) { + return element.textContent.trim().includes('\n'); + } +}; diff --git a/administrator/document/style/version.txt b/administrator/document/style/version.txt new file mode 100644 index 0000000..a85e614 --- /dev/null +++ b/administrator/document/style/version.txt @@ -0,0 +1 @@ +v0.3 diff --git a/administrator/tool/Harmony_sync b/administrator/tool/Harmony_sync new file mode 120000 index 0000000..22ddb4e --- /dev/null +++ b/administrator/tool/Harmony_sync @@ -0,0 +1 @@ +../shared/authored/Harmony_sync/CLI.py \ No newline at end of file diff --git a/administrator/tool/after_pull b/administrator/tool/after_pull new file mode 100755 index 0000000..946d9ad --- /dev/null +++ b/administrator/tool/after_pull @@ -0,0 +1,124 @@ +#!/usr/bin/env -S python3 -B +# -*- mode: python; coding: utf-8; python-indent-offset: 2; indent-tabs-mode: nil -*- + +""" +set_project_permissions — normalize a freshly cloned project to Harmony policies. + +usage: + set_project_permissions [default] + set_project_permissions help | --help | -h + +notes: + • Must be run from the toolsmith environment (ENV=tool/env, ROLE=toolsmith). + • Starts at $REPO_HOME. + • Baseline is umask-077 congruence: + - directories → 0700 + - files → 0600, but preserve owner-exec (→ 0700 for executables) + applied to the entire repo, including release/, EXCEPT: + - release/kmod/*.ko → 0440 + • Skips .git/ and symlinks. +""" + +import os, sys, stat + +# Must match shared/authored/env policy: +DEFAULT_UMASK = 0o077 # reminder only; effective modes below implement 077 congruence. + +DIR_MODE_077 = 0o700 + +def die(msg, code=1): + print(f"set_project_permissions: {msg}", file=sys.stderr) + sys.exit(code) + +def require_toolsmith_env(): + env = os.environ.get("ENV", "") + role = os.environ.get("ROLE", "") + if env != "tool/env" or role != "toolsmith": + hint = ( + "This script should be run from the toolsmith environment.\n" + "Try: source ./env_toolsmith (then re-run: set_project_permissions default)" + ) + die(f"bad environment: ENV='{env}' ROLE='{role}'.\n{hint}") + +def repo_home(): + rh = os.environ.get("REPO_HOME") + if not rh: + die("REPO_HOME is not set (did you source shared/authored/env?)") + return os.path.realpath(rh) + +def show_path(p, rh): + return p.replace(rh, "$REPO_HOME", 1) if p.startswith(rh) else p + +def is_git_dir(path): + return os.path.basename(path.rstrip(os.sep)) == ".git" + +def file_target_mode_077_preserve_exec(current_mode: int) -> int: + # Base 0600, add owner exec if currently set; drop all group/other. + target = 0o600 + if current_mode & stat.S_IXUSR: + target |= stat.S_IXUSR + return target + +def set_mode_if_needed(path, target, rh): + try: + st = os.lstat(path) + except FileNotFoundError: + return 0 + cur = stat.S_IMODE(st.st_mode) + if cur == target: + return 0 + os.chmod(path, target) + print(f"+ chmod {oct(target)[2:]} '{show_path(path, rh)}'") + return 1 + +def apply_policy(rh): + changed = 0 + release_root = os.path.join(rh, "release") + for dirpath, dirnames, filenames in os.walk(rh, topdown=True, followlinks=False): + # prune .git + dirnames[:] = [d for d in dirnames if d != ".git"] + + # directories: 0700 everywhere (incl. release/) + changed += set_mode_if_needed(dirpath, DIR_MODE_077, rh) + + # files: 0600 (+owner exec) everywhere, except release/kmod/*.ko → 0440 + rel_from_repo = os.path.relpath(dirpath, rh) + under_release = rel_from_repo == "release" or rel_from_repo.startswith("release"+os.sep) + top_under_release = "" + if under_release: + rel_from_release = os.path.relpath(dirpath, release_root) + top_under_release = (rel_from_release.split(os.sep, 1)[0] if rel_from_release != "." else "") + + for fn in filenames: + p = os.path.join(dirpath, fn) + if os.path.islink(p): + continue + try: + st = os.lstat(p) + except FileNotFoundError: + continue + + if under_release and top_under_release == "kmod" and fn.endswith(".ko"): + target = 0o440 + else: + target = file_target_mode_077_preserve_exec(stat.S_IMODE(st.st_mode)) + + changed += set_mode_if_needed(p, target, rh) + return changed + +def cmd_default(): + require_toolsmith_env() + rh = repo_home() + total = apply_policy(rh) + print(f"changes: {total}") + +def main(): + if len(sys.argv) == 1 or sys.argv[1] in ("default",): + return cmd_default() + if sys.argv[1] in ("help", "--help", "-h"): + print(__doc__.strip()); return 0 + # unknown command → help + print(__doc__.strip()); return 1 + +if __name__ == "__main__": + sys.exit(main()) diff --git a/administrator/tool/archive b/administrator/tool/archive new file mode 100755 index 0000000..a60a0a0 --- /dev/null +++ b/administrator/tool/archive @@ -0,0 +1,284 @@ +#!/usr/bin/env python3 +# -*- mode: python; coding: utf-8; python-indent-offset: 2; indent-tabs-mode: nil -*- + +""" +archive - Create an archive of the current Git repo's ref into ./scratchpad + +Commands (order-insensitive): + archive # default: zip (HEAD, ./scratchpad, Z-stamp if importable) + archive help # show help + archive version # show version + archive ref- # choose ref (tag/branch/commit), default HEAD + archive out- # choose output directory (default: /scratchpad) + archive no-stamp # force omit timestamp even if Z is importable + archive z-format- # override timestamp format used with Z (optional) + archive zip # write .zip + archive tgz # write .tgz (compressed tar) + archive tar # write .tar (uncompressed tar) + +Output names: + __[__].zip + __[__].tgz + __[__].tar +""" + +from __future__ import annotations +import gzip ,os ,pathlib ,subprocess ,sys +from typing import Optional +import importlib ,importlib.util +from importlib.machinery import SourceFileLoader + +VERSION = "2.0" + +# ---------------------------------------------------------------------- +# Editable timestamp format (used when calling Z) +# ---------------------------------------------------------------------- +Z_FORMAT = "%year-%month-%day_%hour%minute%secondZ" + +USAGE = f"""archive {VERSION} + +Usage: + archive [commands...] + +Commands (order-insensitive): + help + version + ref- + out- + no-stamp + z-format- + zip + tgz + tar + +Examples: + archive + archive tgz + archive ref-main out-/tmp + archive z-format-%year-%month-%dayT%hour:%minute:%second.%scintillaZ +""".rstrip() + +# ---------------------------------------------------------------------- +# git helpers +# ---------------------------------------------------------------------- +def _run(*args: str ,check: bool = True ,cwd: Optional[pathlib.Path] = None) -> subprocess.CompletedProcess[str]: + return subprocess.run( + args + ,check=check + ,cwd=(str(cwd) if cwd else None) + ,text=True + ,stdout=subprocess.PIPE + ,stderr=subprocess.PIPE + ) + +def _in_git_repo() -> bool: + try: + return _run("git" ,"rev-parse" ,"--is-inside-work-tree").stdout.strip().lower() == "true" + except subprocess.CalledProcessError: + return False + +def _git_top() -> pathlib.Path: + return pathlib.Path(_run("git" ,"rev-parse" ,"--show-toplevel").stdout.strip()) + +def _git_ref_label(repo_top: pathlib.Path ,ref: str) -> str: + try: + return _run("git" ,"-C" ,str(repo_top) ,"describe" ,"--tags" ,"--always" ,"--dirty" ,ref).stdout.strip() + except subprocess.CalledProcessError: + return _run("git" ,"-C" ,str(repo_top) ,"rev-parse" ,"--short" ,ref).stdout.strip() + +# ---------------------------------------------------------------------- +# Z module discovery (supports extension-less file named "Z") +# ---------------------------------------------------------------------- +def _import_Z_module(repo_top: pathlib.Path) -> Optional[object]: + try: + return importlib.import_module("Z") + except Exception: + pass + + candidates: list[pathlib.Path] = [] + here = pathlib.Path(__file__).resolve().parent + candidates += [here / "Z" ,here / "Z.py"] + candidates += [ + repo_top / "shared" / "third_party" / "RT-project-share" / "release" / "python" / "Z" + ,repo_top / "shared" / "third_party" / "RT-project-share" / "release" / "python" / "Z.py" + ,repo_top / "shared" / "third_party" / "RT-project-share" / "release" / "bash" / "Z" + ] + for d in (pathlib.Path(p) for p in (os.getenv("PATH") or "").split(os.pathsep) if p): + p = d / "Z" + if p.exists() and p.is_file(): + candidates.append(p) + + for path in candidates: + try: + if not path.exists() or not path.is_file(): continue + spec = importlib.util.spec_from_loader("Z" ,SourceFileLoader("Z" ,str(path))) + if not spec or not spec.loader: continue + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + if hasattr(mod ,"make_timestamp") or (hasattr(mod ,"get_utc_dict") and hasattr(mod ,"format_timestamp")): + return mod + except Exception: + continue + return None + +# ---------------------------------------------------------------------- +# Z stamp helper +# ---------------------------------------------------------------------- +def make_z_stamp(zmod: object ,z_format: str) -> Optional[str]: + try: + if hasattr(zmod ,"make_timestamp"): + s = zmod.make_timestamp(fmt=z_format) + return (str(s).strip().replace("\n" ,"") or None) + if hasattr(zmod ,"get_utc_dict") and hasattr(zmod ,"format_timestamp"): + td = zmod.get_utc_dict() + s = zmod.format_timestamp(td ,z_format) + return (str(s).strip().replace("\n" ,"") or None) + except Exception: + return None + return None + +# ---------------------------------------------------------------------- +# archiving +# ---------------------------------------------------------------------- +def _stream_git_archive_tar(repo_top: pathlib.Path ,prefix: str ,ref: str ,out_path: pathlib.Path ,compress: bool) -> None: + proc = subprocess.Popen( + ["git" ,"-C" ,str(repo_top) ,"archive" ,"--format=tar" ,f"--prefix={prefix}/" ,ref] + ,stdout=subprocess.PIPE + ) + try: + if compress: + with gzip.open(out_path ,"wb") as f: + while True: + chunk = proc.stdout.read(1024 * 1024) + if not chunk: break + f.write(chunk) + else: + with open(out_path ,"wb") as f: + while True: + chunk = proc.stdout.read(1024 * 1024) + if not chunk: break + f.write(chunk) + finally: + if proc.stdout: proc.stdout.close() + rc = proc.wait() + if rc != 0: + try: + out_path.unlink(missing_ok=True) + finally: + raise subprocess.CalledProcessError(rc ,proc.args) + +def _stream_git_archive_zip(repo_top: pathlib.Path ,prefix: str ,ref: str ,out_zip_path: pathlib.Path) -> None: + proc = subprocess.Popen( + ["git" ,"-C" ,str(repo_top) ,"archive" ,"--format=zip" ,f"--prefix={prefix}/" ,ref] + ,stdout=subprocess.PIPE + ) + try: + with open(out_zip_path ,"wb") as f: + while True: + chunk = proc.stdout.read(1024 * 1024) + if not chunk: break + f.write(chunk) + finally: + if proc.stdout: proc.stdout.close() + rc = proc.wait() + if rc != 0: + try: + out_zip_path.unlink(missing_ok=True) + finally: + raise subprocess.CalledProcessError(rc ,proc.args) + +# ---------------------------------------------------------------------- +# work function +# ---------------------------------------------------------------------- +def work( + ref: str = "HEAD" + ,outdir: Optional[pathlib.Path] = None + ,force_no_stamp: bool = False + ,z_format: Optional[str] = None + ,archive_kind: str = "zip" +) -> pathlib.Path: + + if archive_kind not in ("zip" ,"tgz" ,"tar"): + raise RuntimeError("archive_kind must be 'zip', 'tgz', or 'tar'") + + if not _in_git_repo(): + raise RuntimeError("not inside a git repository") + + repo_top = _git_top() + repo_name = repo_top.name + ref_label = _git_ref_label(repo_top ,ref) + + stamp: Optional[str] = None + if not force_no_stamp: + zmod = _import_Z_module(repo_top) + if zmod is not None: + stamp = make_z_stamp(zmod ,z_format or Z_FORMAT) + + target_dir = (outdir or (repo_top / "scratchpad")) + target_dir.mkdir(parents=True ,exist_ok=True) + + if archive_kind == "zip": + suffix = ".zip" + elif archive_kind == "tgz": + suffix = ".tgz" + else: + suffix = ".tar" + + out_name = f"{repo_name}__{ref_label}{('__' + stamp) if stamp else ''}{suffix}" + out_path = target_dir / out_name + + if archive_kind == "zip": + _stream_git_archive_zip(repo_top ,repo_name ,ref ,out_path) + else: + compress = (archive_kind == "tgz") + _stream_git_archive_tar(repo_top ,repo_name ,ref ,out_path ,compress) + + return out_path + +# ---------------------------------------------------------------------- +# CLI with command tokens +# ---------------------------------------------------------------------- +def CLI(argv: Optional[list[str]] = None) -> int: + if argv is None: argv = sys.argv[1:] + + ref = "HEAD" + outdir: Optional[pathlib.Path] = None + force_no_stamp = False + z_format: Optional[str] = None + archive_kind = "zip" + + if not argv: + try: + print(f"Wrote {work(ref=ref ,outdir=outdir ,force_no_stamp=force_no_stamp ,z_format=z_format ,archive_kind=archive_kind)}") + return 0 + except Exception as e: + print(f"archive: {e}" ,file=sys.stderr); return 1 + + for arg in argv: + if arg in ("help" ,"-h" ,"--help"): print(USAGE); return 0 + if arg == "version": print(f"archive {VERSION}"); return 0 + if arg == "no-stamp": force_no_stamp = True; continue + if arg == "zip": archive_kind = "zip"; continue + if arg == "tgz": archive_kind = "tgz"; continue + if arg == "tar": archive_kind = "tar"; continue + if arg.startswith("ref-"): ref = arg[4:] or ref; continue + if arg.startswith("out-"): + od = arg[4:] + outdir = pathlib.Path(od).resolve() if od else None + continue + if arg.startswith("z-format-"): + z_format = arg[len("z-format-"):] or None + continue + print(f"archive: unknown command '{arg}'" ,file=sys.stderr); return 1 + + try: + out_path = work(ref=ref ,outdir=outdir ,force_no_stamp=force_no_stamp ,z_format=z_format ,archive_kind=archive_kind) + except Exception as e: + print(f"archive: {e}" ,file=sys.stderr); return 1 + + print(f"Wrote {out_path}") + return 0 + +# ---------------------------------------------------------------------- +if __name__ == "__main__": + raise SystemExit(CLI()) diff --git a/administrator/tool/release b/administrator/tool/release new file mode 100755 index 0000000..d72bf60 --- /dev/null +++ b/administrator/tool/release @@ -0,0 +1,291 @@ +#!/usr/bin/env -S python3 -B +# -*- mode: python; coding: utf-8; python-indent-offset: 2; indent-tabs-mode: nil -*- + +import os, sys, shutil, stat, pwd, grp, glob, tempfile + +HELP = """usage: release {write|clean|ls|help|dry write} [DIR] + write [DIR] Writes released files into $REPO_HOME/release. If [DIR] is specified, only writes files found in scratchpad/DIR. + clean [DIR] Remove the contents of the release directories. If [DIR] is specified, clean only the contents of that release directory. + ls List release/ as an indented tree: PERMS OWNER NAME (root-level dotfiles printed first). + help Show this message. + dry write [DIR] + Preview what write would do without modifying the filesystem. +""" + +SETUP_MUST_BE = "developer/tool/setup" +DEFAULT_DIR_MODE = 0o700 # 077-congruent dirs + +def exit_with_status(msg, code=1): + print(f"release: {msg}", file=sys.stderr) + sys.exit(code) + +def assert_env(): + env = os.environ.get("ENV", "") + if env != ENV_MUST_BE: + hint = ( + "SETUP is not 'developer/tool/setup'.\n" + "Enter the project with: . setup developer\n" + "That script exports: ROLE=developer; SETUP=$ROLE/tool/setup" + ) + exit_with_status(f"bad environment: ENV='{env}'. {hint}") + +def repo_home(): + rh = os.environ.get("REPO_HOME") + if not rh: + exit_with_status("REPO_HOME not set (did you '. setup developer'?)") + return rh + +def dpath(*parts): + return os.path.join(repo_home(), "developer", *parts) + +def rpath(*parts): + return os.path.join(repo_home(), "release", *parts) + +def dev_root(): + return dpath() + +def rel_root(): + return rpath() + +def _display_src(p_abs: str) -> str: + try: + if os.path.commonpath([dev_root()]) == os.path.commonpath([dev_root(), p_abs]): + return os.path.relpath(p_abs, dev_root()) + except Exception: + pass + return p_abs + +def _display_dst(p_abs: str) -> str: + try: + rel = os.path.relpath(p_abs, rel_root()) + rel = "" if rel == "." else rel + return "$REPO_HOME/release" + ("/" + rel if rel else "") + except Exception: + return p_abs + +def ensure_mode(path, mode): + try: os.chmod(path, mode) + except Exception: pass + +def ensure_dir(path, mode=DEFAULT_DIR_MODE, dry=False): + if dry: + if not os.path.isdir(path): + shown = _display_dst(path) if path.startswith(rel_root()) else ( + os.path.relpath(path, dev_root()) if path.startswith(dev_root()) else path + ) + print(f"(dry) mkdir -m {oct(mode)[2:]} '{shown}'") + return + os.makedirs(path, exist_ok=True) + ensure_mode(path, mode) + +def filemode(m): + try: return stat.filemode(m) + except Exception: return oct(m & 0o777) + +def owner_group(st): + try: return f"{pwd.getpwuid(st.st_uid).pw_name}:{grp.getgrgid(st.st_gid).gr_name}" + except Exception: return f"{st.st_uid}:{st.st_gid}" + +# ---------- LS (two-pass owner:group width) ---------- +def list_tree(root): + if not os.path.isdir(root): + return + entries = [] + def gather(path: str, depth: int, is_root: bool): + try: + it = list(os.scandir(path)) + except FileNotFoundError: + return + dirs = [e for e in it if e.is_dir(follow_symlinks=False)] + files = [e for e in it if not e.is_dir(follow_symlinks=False)] + dirs.sort(key=lambda e: e.name); files.sort(key=lambda e: e.name) + + if is_root: + for f in (e for e in files if e.name.startswith(".")): + st = os.lstat(f.path); entries.append((False, depth, filemode(st.st_mode), owner_group(st), f.name)) + for d in dirs: + st = os.lstat(d.path); entries.append((True, depth, filemode(st.st_mode), owner_group(st), d.name + "/")) + gather(d.path, depth + 1, False) + for f in (e for e in files if not e.name.startswith(".")): + st = os.lstat(f.path); entries.append((False, depth, filemode(st.st_mode), owner_group(st), f.name)) + else: + for d in dirs: + st = os.lstat(d.path); entries.append((True, depth, filemode(st.st_mode), owner_group(st), d.name + "/")) + gather(d.path, depth + 1, False) + for f in files: + st = os.lstat(f.path); entries.append((False, depth, filemode(st.st_mode), owner_group(st), f.name)) + gather(root, depth=1, is_root=True) + + ogw = 0 + for (_isdir, _depth, _perms, ownergrp, _name) in entries: + if len(ownergrp) > ogw: ogw = len(ownergrp) + + print("release/") + for (_isdir, depth, perms, ownergrp, name) in entries: + indent = " " * depth + print(f"{perms} {ownergrp:<{ogw}} {indent}{name}") +# ---------- end LS ---------- + +def iter_src_files(topdir, src_root): + base = os.path.join(src_root, topdir) if topdir else src_root + if not os.path.isdir(base): + return + yield + if topdir == "kmod": + for p in sorted(glob.glob(os.path.join(base, "*.ko"))): + yield (p, os.path.basename(p)) + else: + for root, dirs, files in os.walk(base): + dirs.sort(); files.sort() + for fn in files: + src = os.path.join(root, fn) + rel = os.path.relpath(src, base) + yield (src, rel) + +def _target_mode_from_source(src_abs: str) -> int: + """077 policy: files 0600; if source has owner-exec, make 0700.""" + try: + sm = stat.S_IMODE(os.stat(src_abs).st_mode) + except FileNotFoundError: + return 0o600 + return 0o700 if (sm & stat.S_IXUSR) else 0o600 + +def copy_one(src_abs, dst_abs, dry=False): + src_show = _display_src(src_abs) + dst_show = _display_dst(dst_abs) + parent = os.path.dirname(dst_abs) + os.makedirs(parent, exist_ok=True) + target_mode = _target_mode_from_source(src_abs) + + def _is_writable_dir(p): return os.access(p, os.W_OK) + flip_needed = not _is_writable_dir(parent) + restore_mode = None + parent_show = _display_dst(parent) + + if dry: + if flip_needed: + print(f"(dry) chmod u+w '{parent_show}'") + if os.path.exists(dst_abs): + print(f"(dry) unlink '{dst_show}'") + # show final mode we will set + print(f"(dry) install -m {oct(target_mode)[2:]} -D '{src_show}' '{dst_show}'") + if flip_needed: + print(f"(dry) chmod u-w '{parent_show}'") + return + + try: + if flip_needed: + try: + st_parent = os.stat(parent) + restore_mode = stat.S_IMODE(st_parent.st_mode) + os.chmod(parent, restore_mode | stat.S_IWUSR) + except PermissionError: + exit_with_status(f"cannot write: parent dir not writable and chmod failed on {parent_show}") + + # Atomic replace with enforced 077-compliant mode + fd, tmp_path = tempfile.mkstemp(prefix='.tmp.', dir=parent) + try: + with os.fdopen(fd, "wb") as tmpf, open(src_abs, "rb") as sf: + shutil.copyfileobj(sf, tmpf) + tmpf.flush() + os.chmod(tmp_path, target_mode) + os.replace(tmp_path, dst_abs) + finally: + try: + if os.path.exists(tmp_path): + os.unlink(tmp_path) + except Exception: + pass + finally: + if restore_mode is not None: + try: os.chmod(parent, restore_mode) + except Exception: pass + + print(f"+ install -m {oct(target_mode)[2:]} '{src_show}' '{dst_show}'") + +def write_one_dir(topdir, dry): + rel_root_dir = rpath() + src_root = dpath("scratchpad") + src_dir = os.path.join(src_root, topdir) + dst_dir = os.path.join(rel_root_dir, topdir) + + if not os.path.isdir(src_dir): + exit_with_status( + f"cannot write: expected '{_display_src(src_dir)}' to exist. " + f"Create scratchpad/{topdir} (Makefiles may need to populate it)." + ) + + ensure_dir(dst_dir, DEFAULT_DIR_MODE, dry=dry) + + wrote = False + for src_abs, rel in iter_src_files(topdir, src_root): + dst_abs = os.path.join(dst_dir, rel) + copy_one(src_abs, dst_abs, dry=dry) + wrote = True + if not wrote: + msg = "no matching artifacts found" + if topdir == "kmod": msg += " (looking for *.ko)" + print(f"(info) {msg} in {_display_src(src_dir)}") + +def cmd_write(dir_arg, dry=False): + assert_env() + ensure_dir(rpath(), DEFAULT_DIR_MODE, dry=dry) + + src_root = dpath("scratchpad") + if not os.path.isdir(src_root): + exit_with_status(f"cannot find developer scratchpad at '{_display_src(src_root)}'") + + if dir_arg: + write_one_dir(dir_arg, dry=dry) + else: + subs = sorted([e.name for e in os.scandir(src_root) if e.is_dir(follow_symlinks=False)]) + if not subs: + print(f"(info) nothing to release; no subdirectories found under {_display_src(src_root)}") + return + for td in subs: + write_one_dir(td, dry=dry) + +def _clean_contents(dir_path): + if not os.path.isdir(dir_path): return + for name in os.listdir(dir_path): + p = os.path.join(dir_path, name) + if os.path.isdir(p) and not os.path.islink(p): + shutil.rmtree(p, ignore_errors=True) + else: + try: os.unlink(p) + except FileNotFoundError: pass + +def cmd_clean(dir_arg): + assert_env() + rel_root_dir = rpath() + if not os.path.isdir(rel_root_dir): + return + if dir_arg: + _clean_contents(os.path.join(rel_root_dir, dir_arg)) + else: + for e in os.scandir(rel_root_dir): + if e.is_dir(follow_symlinks=False): + _clean_contents(e.path) + +def CLI(): + if len(sys.argv) < 2: + print(HELP); return + cmd, *args = sys.argv[1:] + if cmd == "write": + cmd_write(args[0] if args else None, dry=False) + elif cmd == "clean": + cmd_clean(args[0] if args else None) + elif cmd == "ls": + list_tree(rpath()) + elif cmd == "help": + print(HELP) + elif cmd == "dry": + if args and args[0] == "write": + cmd_write(args[1] if len(args) >= 2 else None, dry=True) + else: + print(HELP) + else: + print(HELP) + +if __name__ == "__main__": + CLI() diff --git a/administrator/tool/setup b/administrator/tool/setup new file mode 100644 index 0000000..0b993ad --- /dev/null +++ b/administrator/tool/setup @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +script_afp=$(realpath "${BASH_SOURCE[0]}") + diff --git a/developer/authored/.gitkeep b/developer/authored/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/developer/authored/hello.cli.c b/developer/authored/hello.cli.c new file mode 100644 index 0000000..a626cac --- /dev/null +++ b/developer/authored/hello.cli.c @@ -0,0 +1,2 @@ +#include +int main(void){ puts("hello from Rabbit CLI"); return 0; } diff --git a/developer/document/.gitkeep b/developer/document/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/developer/document/00_RT_Code_Format.html b/developer/document/00_RT_Code_Format.html new file mode 100644 index 0000000..5813499 --- /dev/null +++ b/developer/document/00_RT_Code_Format.html @@ -0,0 +1,97 @@ + + + + + RT Prescriptive Code Format Guide + + + + + + + + + + + +

Object vs. Instance Nomenclature

+

+ We reserve the word 'object' for its general English meaning. When discussing data that is manipulated solely through a defined interface, use the term instance. +

+ +

Identifier Naming Conventions

+
    +
  • Types, modules: PascalCase
  • +
  • Functions, variables: snake_case
  • +
  • Globals: UPPER_SNAKE_CASE
  • +
+

+ Note for Lisp/elisp: Use a hyphen - as the primary identifier separator. Use an underscore _ to separate logically related portions of the identifier. +

+

+ Note for C: Use a center dot · for ad hoc namespaces within identifiers (e.g., TM·Arr). In Python, map this to an underscore (TM_Arr). +

+ +

Suffix Semantics

+

Add a container type suffix instead of making variables names plural. Never use plurals.

+
    +
  • *_dp : directory path
  • +
  • *_fp : file path
  • +
  • *_list : generic ordered items
  • +
  • *_count : number of elements
  • +
+ +

Comma Separated Lists

+

Horizontal Comma List

+

The comma is preceded by a space and abuts the item it follows.

+ +int x ,y ,z; + + +

Vertical Comma List

+

The comma is placed before the item on the new line, aligned with the item's indentation.

+ +result = some_function( + first_argument + ,second_argument + ,third_argument +); + + +

Enclosure Spacing

+

Single-Level Enclosures

+

No space padding inside the enclosure punctuation.

+ +if(condition){ + do_something(); +} + + +

Multi-Level Enclosures

+

One space of padding is applied only to the outermost enclosure punctuation.

+ +if( f(g(x)) ){ + do_something(); +} + + +

Short Stuff Rule

+

If a statement can fit on a single line and is short, keep it on a single line without braces.

+ +if(x == 0) return; + + +

Indentation

+
    +
  • Strictly two spaces per indentation level.
  • +
  • Never use tabs.
  • +
  • Nest lines under the syntactic element that opened them.
  • +
+ + +
+ + diff --git a/developer/document/02_RT_Code_Format.html b/developer/document/02_RT_Code_Format.html new file mode 100644 index 0000000..81e891d --- /dev/null +++ b/developer/document/02_RT_Code_Format.html @@ -0,0 +1,99 @@ + + + + + RT Prescriptive Code Format Guide + + + + + + + + + + + +

Object vs. Instance Nomenclature

+

+ We reserve the word 'object' for its general English meaning. When discussing data that is manipulated solely through a defined interface, use the term instance. +

+ +

Identifier Naming Conventions

+
    +
  • Types, modules: PascalCase
  • +
  • Functions, variables: snake-kebab_case (if - is supported) or snake_case (if not supported)
  • +
  • Globals: UPPER_SNAKE_CASE
  • +
+ +

Primary and Secondary Separators (snake-kebab_case)

+

+ If a language supports the hyphen (-) in identifiers (such as Common Lisp and Emacs Lisp), the identifier is written in snake-kebab_case. The hyphen is used as the primary word separator. The underscore (_) is then used as a secondary separator to denote logically related portions or namespace boundaries within the identifier. +

+

+ Otherwise, if the language does not support hyphens in identifiers (such as C, Python, and Java), the identifier falls back to standard snake_case and only the underscore (_) is used for all separation. In C specifically, a center dot (·) is used for ad hoc namespaces. +

+ +

Suffix Semantics

+

Add a container type suffix instead of making variable names plural. Never use plurals.

+
    +
  • *_dp : directory path
  • +
  • *_fp : file path
  • +
  • *_list : generic ordered items
  • +
  • *_count : number of elements
  • +
+ +

Comma Separated Lists

+

Horizontal Comma List

+

The comma is preceded by a space and abuts the item it follows.

+ +int x ,y ,z; + + +

Vertical Comma List

+

The comma is placed before the item on the new line, aligned with the item's indentation.

+ +result = some_function( + first_argument + ,second_argument + ,third_argument +); + + +

Enclosure Spacing

+

Single-Level Enclosures

+

No space padding inside the enclosure punctuation.

+ +if(condition){ + do_something(); +} + + +

Multi-Level Enclosures

+

One space of padding is applied only to the outermost enclosure punctuation.

+ +if( f(g(x)) ){ + do_something(); +} + + +

Short Stuff Rule

+

If a statement can fit on a single line and is short, keep it on a single line without braces.

+ +if(x == 0) return; + + +

Indentation

+
    +
  • Strictly two spaces per indentation level.
  • +
  • Never use tabs.
  • +
  • Nest lines under the syntactic element that opened them.
  • +
+ + +
+ + diff --git a/developer/document/03_Naming_and_Directory_Conventions.html b/developer/document/03_Naming_and_Directory_Conventions.html new file mode 100644 index 0000000..a490d83 --- /dev/null +++ b/developer/document/03_Naming_and_Directory_Conventions.html @@ -0,0 +1,49 @@ + + + + + Naming and Directory Conventions + + + + + + + + + +

+ A directory name is taken as a property for a set of files. Consequently, directory names are rarely plural. For example, suppose we have a number of test files in a directory. The directory would be named test, as each file in the directory has the property of being a test. +

+ +

+ It would be nice if we could attach multiple properties to a file as part of the file system framework, but conventional file systems do not support this. Consequently, when needed, people add a second property to a file using dot extensions to the file's name. Hence, we get something like sqrt.c in a directory called source. The first property is that the file is source code, and the second property is that it is C code. +

+ +

+ We could extend the dot suffix model of adding a property to a file by using multiple dot suffixes. Our C makefile structure makes use of this. +

+ +

So what is a reasonable primary property for a set of files? Perhaps:

+
    +
  • Who uses each file with this property. Home directories are named like this.
  • +
  • The role of the people using the file. This is a more generic version of the prior rule. The developer and tester directories were named in this manner.
  • +
  • What program are the files for. Thus we might name a directory of files for the C compiler cc.
  • +
  • The generic category of program said files are for. Thus we end up with directories called src or executable.
  • +
+ +

+ As for the names src and executable, those come from times when almost all programs were compiled. We prefer instead the names authored and made. authored files are those written by humans (or these days, perhaps AI), while made files are products of tools. For a Python program, we put packages in authored with a module called CLI.py for the command line interface. Then we link from made into authored so as to give the program a name. +

+ +

+ The RT C coding environment does not use separate source and header files. Instead, a variable is set that gates off the implementation if the source code is to be used as a header. Hence, all of our C source fits fine within an authored directory. +

+ + +
+ + diff --git a/developer/document/04_Language_Addenda.html b/developer/document/04_Language_Addenda.html new file mode 100644 index 0000000..4ab0352 --- /dev/null +++ b/developer/document/04_Language_Addenda.html @@ -0,0 +1,96 @@ + + + + + Language Addenda (C, Python, Bash, Lisp) + + + + + + + + + + + +

Purpose

+

+ The RT code format is language-agnostic, but actual languages differ in syntax and constraints. This document explains how the RT rules are applied in C, Python, Bash, and Lisp dialects. +

+ +

1. C Addendum

+

1.1 Control Structure and File Layout

+

+ Each module has an Interface section and an Implementation section in the same file. The sections are toggled using preprocessor macros (e.g., FACE). Interface declarations are processed even when included multiple times; the implementation is compiled only when used as an implementation. +

+ +

1.2 Indentation and Comma Lists

+

C code follows the RT two-space indentation and vertical comma lists:

+ +result = some_function( + first_argument + ,second_argument_with_longer_name + ,third_argument +); + + +

1.3 Error Handling and Ownership

+
    +
  • Functions should document ownership of pointers and lifetimes.
  • +
  • Prefer explicit *_count parameters over sentinel values when passing arrays.
  • +
+ +

2. Python Addendum

+

2.1 Indentation and Layout

+

Python enforces indentation syntactically, so the RT two-space rule becomes:

+
    +
  • Use two-space indentation for all Python code, even though four is common in the wider ecosystem.
  • +
  • Vertical comma lists still place the comma at the start of the line, after the indentation.
  • +
+ +

2.2 Modules and CLI Separation

+

Python scripts distinguish between:

+
    +
  1. Work functions (importable API).
  2. +
  3. CLI entry points (argument parsing, printing, exit codes).
  4. +
+

Put argument parsing and if __name__ == "__main__": in the CLI section. Keep side effects out of import time.

+ +

3. Bash Addendum

+

3.1 Shebang and Safety

+

Bash scripts should start with:

+ +#!/usr/bin/env bash +set -euo pipefail + + +

3.2 Functions vs. Top-Level Code

+

RT-style Bash separates a small top-level CLI harness (argument parsing, usage, dispatch) from a set of functions that implement the work. Parse arguments into variables, call a main function with explicit parameters, and avoid relying on global mutable state where possible.

+ +

4. Lisp / Emacs Lisp Addendum

+

4.1 Identifier Separators (snake-kebab_case)

+

+ Because Lisp dialects support the hyphen (-) in symbols, they utilize snake-kebab_case as the standard for functions and variables. The hyphen replaces the underscore as the primary word separator. +

+

+ The underscore (_) is reserved strictly as a secondary separator. It is used to group logically related portions of an identifier or to denote semantic boundaries, acting as a structural namespace within the symbol (e.g., city-scape_building-height). +

+ +

4.2 Enclosures and Indentation

+

+ Lisp relies entirely on parentheses for evaluation boundaries. The RT multi-level enclosure rule applies: one space of padding is applied to the outermost parentheses of an evaluated list, while inner lists receive no padding. Indentation remains strictly two spaces. +

+ +

5. Using the Addenda

+

+ When in doubt, start with 02_RT_Code_Format.html for the core rules, then apply the relevant language section here. If a language requires deviation from the generic rules, document that deviation in this file instead of ad-hoc decisions. +

+ + +
+ + diff --git a/developer/document/ontology.org b/developer/document/ontology.org new file mode 100644 index 0000000..a7a76a8 --- /dev/null +++ b/developer/document/ontology.org @@ -0,0 +1,45 @@ +#+TITLE: Project Ontology: Authored vs. Loadable +#+AUTHOR: Harmony Developer +#+DATE: 2025-11-21 +#+OPTIONS: toc:t num:nil + +* The Core Philosophy +This project distinguishes files based on fundamental **invariants** (properties) rather than arbitrary file types[cite: 889, 890]. This creates a clear semantic structure: +- **Provenance**: Who created this file? +- **Capability**: What is the file's primary function in the system? [cite: 890, 891] + +**The Golden Rule:** God and Artists (Developers) *create* things; Factories (Build Systems) *make* things[cite: 892]. + +* Directory Structure Overview + +#+BEGIN_SRC text +developer/ +├── authored/ # (The Logic) Human-written source code. +├── loadable/ # (Capability) Agnostic Entry Points. +├── scratchpad/ # (Transient) Intermediates, Objects. +└── tool/ # (The Factory) Build scripts. + +release/ +├── loadable/ # (Capability) Shared, Agnostic Release Entry Points. +├── local_build/ # (Action/Locality) Architecture-specific binaries. +#+END_SRC + +* Detailed Invariants + +** ~developer/authored/~ +- **Invariant:** Primary Logic Source (Code). Every file here is written by a human author[cite: 898, 899]. +- **Rule:** Scripts must treat this directory as read-only. This replaces the old `cc/` and `python3/` source directories. + +** ~developer/loadable/~ +- **Invariant:** Architecture-Agnostic Entry Points. Files here possess the property of being executable by the user[cite: 902]. +- **Contents:** Symlinks to interpreted code, shared scripts, and wrappers that are safe to commit[cite: 903]. + +** ~developer/scratchpad/loadable/~ +- **Invariant:** Machine-Generated Executables (Intermediate). This is the transient output location during development[cite: 904]. +- **Rule:** This directory is **ignored by Git** and houses compiled binaries and libraries derived by the build system[cite: 905, 906]. + +** ~release/local_build/~ +- **Invariant:** Local Action Required. +- **Rule:** This directory is added to the `.gitignore` in the release directory. Its presence signals to a new developer: **"You must perform a local build to populate this directory with machine-specific executables."** +- **Contents:** Final binaries are copied here by the release script from the `scratchpad/`[cite: 915]. + < diff --git a/developer/experiment/.gitkeep b/developer/experiment/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/developer/made/.gitkeep b/developer/made/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/developer/scratchpad/.gitignore b/developer/scratchpad/.gitignore new file mode 100644 index 0000000..120f485 --- /dev/null +++ b/developer/scratchpad/.gitignore @@ -0,0 +1,2 @@ +* +!/.gitignore diff --git a/developer/tool/.gitkeep b/developer/tool/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/developer/tool/do_all b/developer/tool/do_all new file mode 100755 index 0000000..2495705 --- /dev/null +++ b/developer/tool/do_all @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +script_afp=$(realpath "${BASH_SOURCE[0]}") + +# input guards + + setup_must_be="developer/tool/setup" + if [ "$ENV" != "$env_must_be" ]; then + echo "$(script_fp):: error: must be run in the $env_must_be environment" + exit 1 + fi + +set -e +set -x + + cd "$REPO_HOME"/developer || exit 1 + # /bin/make -f tool/makefile $@ + + scratchpad clear + make + release clean + release write + +set +x +echo "$(script_fn) done." diff --git a/developer/tool/make b/developer/tool/make new file mode 100755 index 0000000..58636de --- /dev/null +++ b/developer/tool/make @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +script_afp=$(realpath "${BASH_SOURCE[0]}") + +# input guards + + setup_must_be="developer/tool/setup" + if [ "$ENV" != "$env_must_be" ]; then + echo "$(script_fp):: error: must be run in the $env_must_be environment" + exit 1 + fi + +set -e +set -x + + cd "$REPO_HOME"/developer || exit 1 + # /bin/make -f tool/makefile $@ + + mkdir -p scratchpad/authored + cp authored/HTTP_server.js scratchpad/authored/ + cp authored/port_forwarder scratchpad/authored/ + cp authored/port_forwarder_CLI scratchpad/authored/ + cp authored/permission_RT scratchpad/authored/ + cp authored/permission_UPG scratchpad/authored/ + +set +x +echo "$(script_fn) done." diff --git a/developer/tool/makefile b/developer/tool/makefile new file mode 100644 index 0000000..65408ed --- /dev/null +++ b/developer/tool/makefile @@ -0,0 +1,54 @@ +# developer/tool/makefile — Orchestrator (Hybrid) +.SUFFIXES: +.EXPORT_ALL_VARIABLES: + +RT_INCOMMON := $(REPO_HOME)/shared/third_party/RT-project-share/release +include $(RT_INCOMMON)/make/environment_RT_1.mk + +.PHONY: usage +usage: + @printf "Usage: make [usage|information|all|lib|CLI|kmod|clean]\n" + +.PHONY: version +version: + @printf "local ----------------------------------------\n" + @echo tool/makefile version 2.0 + @printf "target_library_CLI.mk ----------------------------------------\n" + @$(MAKE) -f $(RT_INCOMMON)/make/target_kmod.mk version + @printf "target_kmod.mk ----------------------------------------\n" + @$(MAKE) -f $(RT_INCOMMON)/make/target_library_CLI.mk version + +.PHONY: information +information: + @printf "local ----------------------------------------\n" + -@echo CURDIR='$(CURDIR)' + @echo REPO_HOME="$(REPO_HOME)" + @echo KMOD_BUILD_DIR="/lib/modules/$(shell uname -r)/build" + @echo CURDIR="$(CURDIR)" + @printf "target_library_CLI.mk ----------------------------------------\n" + @$(MAKE) -f $(RT_INCOMMON)/make/target_library_CLI.mk information + @printf "target_kmod.mk ----------------------------------------\n" + @$(MAKE) -f $(RT_INCOMMON)/make/target_kmod.mk information + +.PHONY: all +all: library CLI kmod + +.PHONY: library lib +library lib: + @$(MAKE) -f $(RT_INCOMMON)/make/target_library_CLI.mk library + +.PHONY: CLI +CLI: + @$(MAKE) -f $(RT_INCOMMON)/make/target_library_CLI.mk CLI + +.PHONY: kmod +kmod: + @$(MAKE) -f $(RT_INCOMMON)/make/target_kmod.mk kmod + +.PHONY: clean +clean: + @printf "local ----------------------------------------\n" + @printf "target_library_CLI.mk ----------------------------------------\n" + @$(MAKE) -f $(RT_INCOMMON)/make/target_library_CLI.mk clean + @printf "target_kmod.mk ----------------------------------------\n" + @$(MAKE) -f $(RT_INCOMMON)/make/target_kmod.mk clean diff --git a/developer/tool/release b/developer/tool/release new file mode 100755 index 0000000..2b1027a --- /dev/null +++ b/developer/tool/release @@ -0,0 +1,289 @@ +#!/usr/bin/env -S python3 -B +# -*- mode: python; coding: utf-8; python-indent-offset: 2; indent-tabs-mode: nil -*- + +import os ,sys ,shutil ,stat ,pwd ,grp ,glob ,tempfile + +HELP = """usage: release {write|clean|ls|diff|help|dry write} + write Writes promoted files from scratchpad/stage into user/release. Only updates newer files. + clean Remove all contents of the user/release directory. + ls List user/release as an indented tree: PERMS OWNER NAME. + diff List files in user/release that are not in scratchpad/stage, or are newer. + help Show this message. + dry write Preview what write would do without modifying the filesystem. +""" + +SETUP_MUST_BE = "developer/tool/setup" +DEFAULT_DIR_MODE = 0o700 +DEFAULT_FILE_MODE = 0o400 + +def exit_with_status(msg ,code=1): + print(f"release: {msg}" ,file=sys.stderr) + sys.exit(code) + +def assert_env(): + env = os.environ.get("ENV" ,"") + if(env != ENV_MUST_BE): + hint = ( + "SETUP is not 'developer/tool/setup'.\n" + "Enter the project with: . setup developer\n" + "That script exports: ROLE=developer; SETUP=$ROLE/tool/setup" + ) + exit_with_status(f"bad environment: ENV='{env}'. {hint}") + +def repo_home(): + rh = os.environ.get("REPO_HOME") + if( not rh ): + exit_with_status("REPO_HOME not set") + return rh + +def dpath(*parts): + return os.path.join( + repo_home() + ,"developer" + ,*parts + ) + +def upath(*parts): + return os.path.join( + repo_home() + ,"user" + ,"release" + ,*parts + ) + +def dev_root(): + return dpath() + +def user_root(): + return upath() + +def _display_src(p_abs: str) -> str: + try: + if( os.path.commonpath([dev_root()]) == os.path.commonpath([dev_root() ,p_abs]) ): + return os.path.relpath(p_abs ,dev_root()) + except Exception: + pass + return p_abs + +def _display_dst(p_abs: str) -> str: + try: + rel = os.path.relpath( + p_abs + ,user_root() + ) + rel = "" if rel == "." else rel + return "$REPO_HOME/user/release" + ("/" + rel if rel else "") + except Exception: + return p_abs + +def ensure_mode(path_str ,mode): + try: os.chmod(path_str ,mode) + except Exception: pass + +def ensure_dir(path_str ,mode=DEFAULT_DIR_MODE ,dry=False): + if(dry): + if( not os.path.isdir(path_str) ): + shown = _display_dst(path_str) if path_str.startswith(user_root()) else ( + os.path.relpath(path_str ,dev_root()) if path_str.startswith(dev_root()) else path_str + ) + print(f"(dry) mkdir -m {oct(mode)[2:]} '{shown}'") + return + os.makedirs(path_str ,exist_ok=True) + ensure_mode(path_str ,mode) + +def filemode(m): + try: return stat.filemode(m) + except Exception: return oct(m & 0o777) + +def owner_group(st): + try: return f"{pwd.getpwuid(st.st_uid).pw_name}:{grp.getgrgid(st.st_gid).gr_name}" + except Exception: return f"{st.st_uid}:{st.st_gid}" + +def list_tree(root_dp): + if( not os.path.isdir(root_dp) ): + return + + entries = [] + def gather(path_str ,depth ,is_root): + try: + it = list(os.scandir(path_str)) + except FileNotFoundError: + return + dirs = [e for e in it if e.is_dir(follow_symlinks=False)] + files = [e for e in it if not e.is_dir(follow_symlinks=False)] + dirs.sort(key=lambda e: e.name) + files.sort(key=lambda e: e.name) + + if(is_root): + for f in ( e for e in files if e.name.startswith(".") ): + st = os.lstat(f.path) + entries.append((False ,depth ,filemode(st.st_mode) ,owner_group(st) ,f.name)) + for d in dirs: + st = os.lstat(d.path) + entries.append((True ,depth ,filemode(st.st_mode) ,owner_group(st) ,d.name + "/")) + gather(d.path ,depth + 1 ,False) + for f in ( e for e in files if not e.name.startswith(".") ): + st = os.lstat(f.path) + entries.append((False ,depth ,filemode(st.st_mode) ,owner_group(st) ,f.name)) + else: + for d in dirs: + st = os.lstat(d.path) + entries.append((True ,depth ,filemode(st.st_mode) ,owner_group(st) ,d.name + "/")) + gather(d.path ,depth + 1 ,False) + for f in files: + st = os.lstat(f.path) + entries.append((False ,depth ,filemode(st.st_mode) ,owner_group(st) ,f.name)) + + gather(root_dp ,1 ,True) + + ogw = 0 + for _isdir ,_depth ,_perms ,ownergrp ,_name in entries: + if( len(ownergrp) > ogw ): + ogw = len(ownergrp) + + print("user/release/") + for isdir ,depth ,perms ,ownergrp ,name in entries: + indent = " " * depth + print(f"{perms} {ownergrp:<{ogw}} {indent}{name}") + +def copy_one(src_abs ,dst_abs ,mode ,dry=False): + src_show = _display_src(src_abs) + dst_show = _display_dst(dst_abs) + parent = os.path.dirname(dst_abs) + os.makedirs(parent ,exist_ok=True) + + if(dry): + if( os.path.exists(dst_abs) ): + print(f"(dry) unlink '{dst_show}'") + print(f"(dry) install -m {oct(mode)[2:]} -D '{src_show}' '{dst_show}'") + return + + fd ,tmp_path = tempfile.mkstemp(prefix=".tmp." ,dir=parent) + try: + with os.fdopen(fd ,"wb") as tmpf, open(src_abs ,"rb") as sf: + shutil.copyfileobj(sf ,tmpf) + tmpf.flush() + os.chmod(tmp_path ,mode) + os.replace(tmp_path ,dst_abs) + finally: + try: + if( os.path.exists(tmp_path) ): + os.unlink(tmp_path) + except Exception: + pass + + print(f"+ install -m {oct(mode)[2:]} '{src_show}' '{dst_show}'") + +def cmd_write(dry=False): + assert_env() + ensure_dir(upath() ,DEFAULT_DIR_MODE ,dry=dry) + + src_root = dpath( + "scratchpad" + ,"stage" + ) + if( not os.path.isdir(src_root) ): + exit_with_status(f"cannot find developer scratchpad stage at '{_display_src(src_root)}'") + + wrote = False + for root ,dirs ,files in os.walk(src_root): + dirs.sort() + files.sort() + for fn in files: + src_abs = os.path.join(root ,fn) + rel = os.path.relpath(src_abs ,src_root) + dst_abs = os.path.join(upath() ,rel) + + if( os.path.exists(dst_abs) ): + src_mtime = os.stat(src_abs).st_mtime + dst_mtime = os.stat(dst_abs).st_mtime + if(dst_mtime >= src_mtime): + continue + + st = os.stat(src_abs) + is_exec = st.st_mode & stat.S_IXUSR + mode = 0o500 if is_exec else 0o400 + + copy_one( + src_abs + ,dst_abs + ,mode + ,dry=dry + ) + wrote = True + + if( not wrote ): + print(f"(info) nothing new to promote from {_display_src(src_root)}") + +def cmd_diff(): + assert_env() + dst_root = upath() + src_root = dpath( + "scratchpad" + ,"stage" + ) + + if( not os.path.isdir(dst_root) ): + print(f"Release directory {_display_dst(dst_root)} does not exist.") + return + + found_diff = False + for root ,dirs ,files in os.walk(dst_root): + dirs.sort() + files.sort() + for fn in files: + dst_abs = os.path.join(root ,fn) + rel = os.path.relpath(dst_abs ,dst_root) + src_abs = os.path.join(src_root ,rel) + + if( not os.path.exists(src_abs) ): + print(f"Orphaned in release: {rel}") + found_diff = True + else: + dst_mtime = os.stat(dst_abs).st_mtime + src_mtime = os.stat(src_abs).st_mtime + if(dst_mtime > src_mtime): + print(f"Newer in release: {rel}") + found_diff = True + + if( not found_diff ): + print("No differences found. Release matches stage.") + +def cmd_clean(): + assert_env() + user_root_dir = upath() + if( not os.path.isdir(user_root_dir) ): + return + for name in os.listdir(user_root_dir): + p = os.path.join(user_root_dir ,name) + if( os.path.isdir(p) and not os.path.islink(p) ): + shutil.rmtree(p ,ignore_errors=True) + else: + try: os.unlink(p) + except FileNotFoundError: pass + +def CLI(): + if( len(sys.argv) < 2 ): + print(HELP) + return + cmd ,*args = sys.argv[1:] + if(cmd == "write"): + cmd_write(dry=False) + elif(cmd == "clean"): + cmd_clean() + elif(cmd == "ls"): + list_tree(upath()) + elif(cmd == "diff"): + cmd_diff() + elif(cmd == "help"): + print(HELP) + elif(cmd == "dry"): + if( args and args[0] == "write" ): + cmd_write(dry=True) + else: + print(HELP) + else: + print(HELP) + +if __name__ == "__main__": + CLI() diff --git a/developer/tool/setup b/developer/tool/setup new file mode 100644 index 0000000..0b993ad --- /dev/null +++ b/developer/tool/setup @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +script_afp=$(realpath "${BASH_SOURCE[0]}") + diff --git a/document/.gitkeep b/document/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/document/style/rt_dark_doc.css b/document/style/rt_dark_doc.css new file mode 100644 index 0000000..bac4fbf --- /dev/null +++ b/document/style/rt_dark_doc.css @@ -0,0 +1,44 @@ + + body { + font-family: 'Noto Sans JP', Arial, sans-serif; + background-color: hsl(0, 0%, 0%); + color: hsl(42, 100%, 80%); + padding: 2rem; + } + .page { + padding: 3rem; + margin: 1.25rem auto; + max-width: 46.875rem; + background-color: hsl(0, 0%, 0%); + box-shadow: 0 0 0.625rem hsl(42, 100%, 50%); + } + h1 { + font-size: 1.5rem; + text-align: center; + color: hsl(42, 100%, 84%); + text-transform: uppercase; + margin-top: 1.5rem; + } + h2 { + font-size: 1.25rem; + color: hsl(42, 100%, 84%); + text-align: center; + margin-top: 2rem; + } + h3 { + font-size: 1.125rem; + color: hsl(42, 100%, 75%); + margin-top: 1.5rem; + } + p, li { + color: hsl(42, 100%, 90%); + text-align: justify; + margin-bottom: 1rem; + } + code { + font-family: 'Courier New', Courier, monospace; + background-color: hsl(0, 0%, 25%); + padding: 0.125rem 0.25rem; + color: hsl(42, 100%, 90%); + } + diff --git a/scratchpad/.gitignore b/scratchpad/.gitignore new file mode 100644 index 0000000..120f485 --- /dev/null +++ b/scratchpad/.gitignore @@ -0,0 +1,2 @@ +* +!/.gitignore diff --git a/setup b/setup new file mode 100644 index 0000000..8125877 --- /dev/null +++ b/setup @@ -0,0 +1,68 @@ +#!/usr/bin/env bash +# setup the project and role environment +# (must be sourced) + +script_afp=$(realpath "${BASH_SOURCE[0]}") +if [ "${BASH_SOURCE[0]}" == "${0}" ]; then + echo "${script_afp}:: This script must be sourced, not executed." + exit 1 +fi + +print_usage(){ + echo "usage: . setup " + echo "known roles: administrator, developer, tester, user" +} + +if [ -z "${1:-}" ] || [ "${1}" == "-h" ] || [ "${1}" == "--help" ]; then + print_usage + return 0 +fi + +role_is_valid=false +for r in administrator developer tester user; do + if [ "${1}" == "${r}" ]; then + role_is_valid=true + break + fi +done + +if [ "${role_is_valid}" == "false" ]; then + echo "setup: unrecognized role or option '${1}'" + print_usage + return 1 +fi + +# setup the project +# + source shared/authored/setup + +# setup tools +# + export PYTHON_HOME="${REPO_HOME}/shared/third_party/Python" + if [[ ":${PATH}:" != *":${PYTHON_HOME}/bin:"* ]]; then + export PATH="${PYTHON_HOME}/bin:${PATH}" + fi + + RT_gcc="${REPO_HOME}/shared/third_party/RT_gcc/release" + if [[ ":${PATH}:" != *":${RT_gcc}:"* ]]; then + export PATH="${RT_gcc}:${PATH}" + fi + +# setup the role +# + export ROLE="${1}" + + tool="${REPO_HOME}/${ROLE}/tool" + if [[ ":${PATH}:" != *":${tool}:"* ]]; then + export PATH="${tool}:${PATH}" + fi + + export SETUP="${ROLE}/tool/setup" + + cd "${ROLE}" || return 1 + if [ -f "tool/setup" ]; then + source "tool/setup" + echo "in environment: ${SETUP}" + else + echo "not found: ${SETUP}" + fi diff --git a/shared/authored/scratchpad b/shared/authored/scratchpad new file mode 100755 index 0000000..f14f140 --- /dev/null +++ b/shared/authored/scratchpad @@ -0,0 +1,225 @@ +#!/usr/bin/env -S python3 -B +# -*- mode: python; coding: utf-8; python-indent-offset: 2; indent-tabs-mode: nil -*- + +import os, sys, shutil, stat, pwd, grp, subprocess + +HELP = """usage: scratchpad {ls|clear|help|make|write|size|find|lock|unlock} [ARGS] + ls List scratchpad in an indented tree with perms and owner (quiet if missing). + clear Remove all contents of scratchpad/ except top-level .gitignore. + clear NAME Remove scratchpad/NAME only. + make [NAME] Ensure scratchpad/ exists with .gitignore; with NAME, mkdir scratchpad/NAME. + write SRC [DST] Copy file/dir SRC into scratchpad (to DST if given; parents created). + size Print 'empty' if only .gitignore; else total bytes and item count. + find [OPTS...] Run system 'find' rooted at scratchpad/ with OPTS (omit literal 'scratchpad'). + lock PATH... Attempt 'chattr +i' on given paths under scratchpad/ (no state kept). + unlock PATH... Attempt 'chattr -i' on given paths under scratchpad/. + +Examples: + scratchpad make + scratchpad write ~/Downloads/test.tar.gz + scratchpad find -type f -mtime +30 -print # files older than 30 days + scratchpad lock some/dir important.txt + scratchpad unlock some/dir important.txt +""" + +CWD = os.getcwd() +SP = os.path.join(CWD, "scratchpad") +GITIGNORE = os.path.join(SP, ".gitignore") + +def have_sp() -> bool: + return os.path.isdir(SP) + +def ensure_sp(): + os.makedirs(SP, exist_ok=True) + ensure_gitignore() + +def ensure_gitignore(): + os.makedirs(SP, exist_ok=True) + if not os.path.isfile(GITIGNORE): + with open(GITIGNORE, "w", encoding="utf-8") as f: + f.write("*\n!.gitignore\n") + +def filemode(mode: int) -> str: + try: + return stat.filemode(mode) + except Exception: + return oct(mode & 0o777) + +def owner_group(st) -> str: + try: + return f"{pwd.getpwuid(st.st_uid).pw_name}:{grp.getgrgid(st.st_gid).gr_name}" + except Exception: + return f"{st.st_uid}:{st.st_gid}" + +def rel_depth(base: str, root: str) -> int: + rel = os.path.relpath(base, root) + return 0 if rel == "." else rel.count(os.sep) + 1 + +def ls_tree(root: str) -> None: + if not have_sp(): + return + print("scratchpad/") + + def walk(path: str, indent: str, is_root: bool) -> None: + try: + it = list(os.scandir(path)) + except FileNotFoundError: + return + + dirs = [e for e in it if e.is_dir(follow_symlinks=False)] + files = [e for e in it if not e.is_dir(follow_symlinks=False)] + dirs.sort(key=lambda e: e.name) + files.sort(key=lambda e: e.name) + + if is_root: + # 1) root-level hidden files first + for f in (e for e in files if e.name.startswith(".")): + st = os.lstat(f.path) + print(f"{filemode(st.st_mode)} {owner_group(st)} {indent}{f.name}") + # 2) then directories (and recurse so children sit under the parent) + for d in dirs: + st = os.lstat(d.path) + print(f"{filemode(st.st_mode)} {owner_group(st)} {indent}{d.name}/") + walk(d.path, indent + ' ', False) + # 3) then non-hidden files + for f in (e for e in files if not e.name.startswith(".")): + st = os.lstat(f.path) + print(f"{filemode(st.st_mode)} {owner_group(st)} {indent}{f.name}") + else: + # subdirs: keep previous order (dirs first, then files; dotfiles naturally sort first) + for d in dirs: + st = os.lstat(d.path) + print(f"{filemode(st.st_mode)} {owner_group(st)} {indent}{d.name}/") + walk(d.path, indent + ' ', False) + for f in files: + st = os.lstat(f.path) + print(f"{filemode(st.st_mode)} {owner_group(st)} {indent}{f.name}") + + walk(root, " ", True) + + +def clear_all() -> None: + if not have_sp(): + return + for name in os.listdir(SP): + p = os.path.join(SP, name) + if name == ".gitignore" and os.path.isfile(p): + continue # preserve only top-level .gitignore + if os.path.isdir(p) and not os.path.islink(p): + shutil.rmtree(p, ignore_errors=True) + else: + try: os.unlink(p) + except FileNotFoundError: pass + +def clear_subdir(sub: str) -> None: + if not have_sp(): + return + target = os.path.normpath(os.path.join(SP, sub)) + try: + if os.path.commonpath([SP]) != os.path.commonpath([SP, target]): + return + except Exception: + return + if os.path.isdir(target) and not os.path.islink(target): + shutil.rmtree(target, ignore_errors=True) + +def cmd_make(args): + ensure_sp() + if args: + os.makedirs(os.path.join(SP, args[0]), exist_ok=True) + +def cmd_write(args): + if len(args) < 1: + print(HELP); return + if not have_sp(): + ensure_sp() + src = args[0] + dst = args[1] if len(args) >= 2 else (os.path.basename(src.rstrip(os.sep)) or "untitled") + dst_path = os.path.normpath(os.path.join(SP, dst)) + try: + if os.path.commonpath([SP]) != os.path.commonpath([SP, dst_path]): + print("refusing to write outside scratchpad", file=sys.stderr); return + except Exception: + print("invalid destination", file=sys.stderr); return + os.makedirs(os.path.dirname(dst_path), exist_ok=True) + if os.path.isdir(src): + if os.path.exists(dst_path): + shutil.rmtree(dst_path, ignore_errors=True) + shutil.copytree(src, dst_path, dirs_exist_ok=False) + else: + shutil.copy2(src, dst_path) + +def cmd_size(): + if not have_sp(): + return + names = os.listdir(SP) + if [n for n in names if n != ".gitignore"] == []: + print("empty"); return + total = 0; count = 0 + for base, dirs, files in os.walk(SP): + for fn in files: + if fn == ".gitignore": + continue + p = os.path.join(base, fn) + try: + total += os.path.getsize(p); count += 1 + except OSError: + pass + print(f"bytes={total} items={count}") + +def cmd_find(args): + if not have_sp(): + return + try: + subprocess.run(["find", SP] + args, check=False) + except FileNotFoundError: + print("find not available", file=sys.stderr) + +def cmd_chattr(flag: str, paths): + if not have_sp() or not paths: + return + try: + subprocess.run(["chattr", "-V"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False) + except FileNotFoundError: + print("chattr not available; lock/unlock skipped", file=sys.stderr); return + for rel in paths: + target = os.path.normpath(os.path.join(SP, rel)) + try: + if os.path.commonpath([SP]) != os.path.commonpath([SP, target]): + continue + except Exception: + continue + try: + subprocess.run(["chattr", flag, target], check=False) + except Exception: + pass + +def CLI(): + if len(sys.argv) < 2: + print(HELP); return + cmd, *args = sys.argv[1:] + if cmd == "ls": + if have_sp(): ls_tree(SP) + else: return + elif cmd == "clear": + if len(args) >= 1: clear_subdir(args[0]) + else: clear_all() + elif cmd == "help": + print(HELP) + elif cmd == "make": + cmd_make(args) + elif cmd == "write": + cmd_write(args) + elif cmd == "size": + cmd_size() + elif cmd == "find": + cmd_find(args) + elif cmd == "lock": + cmd_chattr("+i", args) + elif cmd == "unlock": + cmd_chattr("-i", args) + else: + print(HELP) + +if __name__ == "__main__": + CLI() diff --git a/shared/authored/setup b/shared/authored/setup new file mode 100644 index 0000000..2284ba2 --- /dev/null +++ b/shared/authored/setup @@ -0,0 +1,130 @@ +#!/usr/bin/env bash +script_afp=$(realpath "${BASH_SOURCE[0]}") +if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then + echo "$script_afp:: This script must be sourced, not executed." + exit 1 +fi + +# without this bash takes non-matching globs literally +shopt -s nullglob + +# does not presume sharing or world permissions +umask 0077 + +# -------------------------------------------------------------------------------- +# project definition + +# actual absolute director path for this script file + + script_adp(){ + dirname "$script_afp" + } + +# assume this script is located $REPO_HOME/tools_shared/authored and work backwards +# to get $REPO_HOME, etc. + + REPO_HOME=$(dirname "$(dirname "$(script_adp)")") + echo REPO_HOME "$REPO_HOME" + + PROJECT=$(basename "$REPO_HOME") + echo PROJECT "$PROJECT" + + # set the prompt decoration to the name of the project + PROMPT_DECOR=$PROJECT + + export REPO_HOME PROJECT PROMPT_DECOR + +# -------------------------------------------------------------------------------- +# Project wide Tool setup +# + +export VIRTUAL_ENV="$REPO_HOME/shared/third_party/Python" +export PYTHON_HOME="$VIRTUAL_ENV" +unset PYTHONHOME + + +# -------------------------------------------------------------------------------- +# PATH +# precedence: last defined, first discovered + + PATH="$REPO_HOME/shared/third_party/RT-project-share/release/bash:$PATH" + PATH="$REPO_HOME/shared/third_party/RT-project-share/release/amd64:$PATH" + PATH="$REPO_HOME/shared/third_party:$PATH" + PATH="$REPO_HOME/shared/authored:$PATH" + PATH="$REPO_HOME/shared/made:$PATH" + + # Remove duplicates + clean_path() { + PATH=$(echo ":$PATH" | awk -v RS=: -v ORS=: '!seen[$0]++' | sed 's/^://; s/:$//') + } + clean_path + export PATH + +# -------------------------------------------------------------------------------- +# the following functions are provided for other scripts to use. +# at the top of files that make use of these functions put the following line: +# script_afp=$(realpath "${BASH_SOURCE[0]}") +# + + ## script's filename + script_fn(){ + basename "$script_afp" + } + + ## script's dirpath relative to $REPO_HOME + script_fp(){ + realpath --relative-to="${REPO_HOME}" "$script_afp" + } + + ## script's dirpath relative to $REPO_HOME + script_dp(){ + dirname "$(script_fp)" + } + + export -f script_adp script_fn script_dp script_fp + +#-------------------------------------------------------------------------------- +# used by release scripts +# + + install_file() { + if [ "$#" -lt 3 ]; then + echo "env::install_file usage: install_file ... " + return 1 + fi + + perms="${@: -1}" # Last argument is permissions + target_dp="${@: -2:1}" # Second-to-last argument is the target directory + sources=("${@:1:$#-2}") # All other arguments are source files + + if [ ! -d "$target_dp" ]; then + echo "env::install_file no install done: target directory '$target_dp' does not exist." + return 1 + fi + + for source_fp in "${sources[@]}"; do + if [ ! -f "$source_fp" ]; then + echo "env::install_file: source file '$source_fp' does not exist." + return 1 + fi + + target_file="$target_dp/$(basename "$source_fp")" + + if ! install -m "$perms" "$source_fp" "$target_file"; then + echo "env::install_file: Failed to install $(basename "$source_fp") to $target_dp" + return 1 + else + echo "env::install_file: installed $(basename "$source_fp") to $target_dp with permissions $perms" + fi + done + } + + export -f install_file + +# -------------------------------------------------------------------------------- +# closing +# + if [[ -z "$ENV" ]]; then + export ENV=$(script_fp) + fi + diff --git a/shared/authored/version b/shared/authored/version new file mode 100755 index 0000000..7badeb9 --- /dev/null +++ b/shared/authored/version @@ -0,0 +1,4 @@ +echo "Harmony v2.0 2026-03-05" + + + diff --git a/shared/document/.gitkeep b/shared/document/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/shared/document/install_Python.org b/shared/document/install_Python.org new file mode 100644 index 0000000..14342f9 --- /dev/null +++ b/shared/document/install_Python.org @@ -0,0 +1,75 @@ +#+TITLE: Installing Python in Harmony +#+AUTHOR: Thomas Walker Lynch +#+OPTIONS: toc:2 num:nil + +* Overview + +This document describes how to install a project-local Python environment under: + +#+begin_src bash +shared/third_party/Python +#+end_src + +This environment is shared across the =developer= and =tester= roles and is automatically activated through their respective =env_= scripts. + +* Precondition + +Ensure the following: + +- You are in a POSIX shell with =python3= installed. +- The =python3-venv= package is available (on Debian: =sudo apt install python3-venv=). +- You have sourced the Harmony environment via =env_toolsmith= to initialize =REPO_HOME= and related variables. + +* Step-by-Step Installation + +1. Source the Harmony environment: + #+begin_src bash + source env_toolsmith + #+end_src + +2. Create the virtual environment: + #+begin_src bash + python3 -m venv "$REPO_HOME/shared/third_party/Python" + #+end_src + +3. Activate it temporarily to install required packages: + #+begin_src bash + source "$REPO_HOME/shared/third_party/Python/bin/activate" + pip install --upgrade pip + pip install pytest # Add any shared packages here + deactivate + #+end_src + +4. Rename Python's default activate and deactivate: + Harmony provides its own role-aware environment management. Using Python’s default activation scripts may interfere with prompt logic, PATH order, and role-specific behavior. + + Disable the default scripts by renaming them: + #+begin_src bash + mv "$REPO_HOME/shared/third_party/Python/bin/activate" \ + "$REPO_HOME/shared/third_party/Python/bin/activate_deprecated" + #+end_src + + This ensures that accidental sourcing of Python’s =activate= script won't override Harmony's environment setup. + +5. Verify installation: + #+begin_src bash + ls "$REPO_HOME/shared/third_party/Python/bin/python3" + #+end_src + + The binary should exist and report a working Python interpreter when run. + +* Notes + +- The virtual environment is deliberately named =Python=, not =venv=, to reflect its role as a shared system component. +- Harmony environment scripts define and control =VIRTUAL_ENV=, =PYTHON_HOME=, and =PATH=, making Python activation seamless and uniform. +- There is no need to use Python’s =bin/activate= directly — it is fully replaced by Harmony’s environment logic. + +* Related Files + +- =shared/authored/env= +- =shared/authored/env_source= +- =env_developer=, =env_tester=, =env_toolsmith= + +* Last Verified + +2025-05-19 :: Activate/deactivate renamed post-install. Requires Harmony environment sourcing prior to execution. diff --git a/shared/document/install_generic.org b/shared/document/install_generic.org new file mode 100644 index 0000000..90af13e --- /dev/null +++ b/shared/document/install_generic.org @@ -0,0 +1,81 @@ + +This is the generic install.org doc that comes with the skeleton. + +1. $REPO_HOME/shared/third_party/.gitignore: + + * + !/.gitignore + !/patch + + The only things from the third party directory that will be pushed to the repo origin is the .gitignore file and the patches. + + +2. downloaded tar files etc. go into the directory `upstream` + + $REPO_HOME/shared/upstream + + Typically the contents of upstream are deleted after the install. + +3. for the base install + + cd $REPO_HOME/shared/third_party + do whatever it takes to install tool, as examples: + git clone + tar -xzf ../upstream/tar + ... + + Be sure to add the path to the tool executable(s) in the $REPO_HOME/env_$ROLE files for the $ROLE who uses the tool. + + Assuming you are not also developing the tool, for safety + change each installed git project to a local branch: + + b=__local_$USER + git switch -c "$b" + + +4. Define some variables to simplify our discussion. Lowercase variable names + are not exported from the shell. + + # already set in the environment + # REPO_HOME + # PROJECT + # USER + + # example tool names: 'RT_gcc' 'RT-project share` etc. + tool= + tool_dpath="$REPO_HOME/shared/third_party/$tool" + patch_dpath="$REPO_HOME/shared/patch/" + + +5. create a patch series (from current vendor state → your local edits) + + # this can be repeated and will create an encompassing diff file + + # optionally crate a new branch after cloning the third party tool repo and work from there. You won't make any commits, but in case you plan to ever check the changes in, or have a the bad habit of doing ommits burned into your brain-stem, making a brnch will help. + + # make changes + + cd "$tool_dpath" + + # do your edits + + # Stage edits. Do not commit them!! Be sure you are in the third party + # tool directory when doing `git add -A` and `git diff` commands. + git add -A + + # diff the stage from the current repo to create the patch file + git diff --staged > "$patch_dpath/$tool" + + # the diff file can be added to the project and checked in at the project level. + + +6. how to apply an existing patch + + Get a fresh clone of the tool into $tool_dpath. + + cd "$tool_dpath" + git apply "$patch_dpath/$tool" + + You can see what `git apply` would do by running + + git apply --check /path/to/your/patch_dpath/$tool diff --git a/shared/made/walk b/shared/made/walk new file mode 120000 index 0000000..1325c19 --- /dev/null +++ b/shared/made/walk @@ -0,0 +1 @@ +../authored/gitignore_treewalk.py \ No newline at end of file diff --git a/shared/third_party/.gitignore b/shared/third_party/.gitignore new file mode 100644 index 0000000..0de97f0 --- /dev/null +++ b/shared/third_party/.gitignore @@ -0,0 +1,8 @@ +# Ignore all files +* + +# But don't ignore the .gitignore file itself +!/.gitignore + +# keep the upstream directory +!/upstream diff --git a/shared/third_party/upstream/.gitignore b/shared/third_party/upstream/.gitignore new file mode 100644 index 0000000..aa0e8eb --- /dev/null +++ b/shared/third_party/upstream/.gitignore @@ -0,0 +1,2 @@ +* +!/.gitignore \ No newline at end of file diff --git a/tester/.gitkeep b/tester/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/tester/RT_Format/RT_Format b/tester/RT_Format/RT_Format new file mode 100755 index 0000000..2b51ceb --- /dev/null +++ b/tester/RT_Format/RT_Format @@ -0,0 +1,415 @@ +#!/usr/bin/env -S python3 -B +# -*- mode: python; coding: utf-8; python-indent-offset: 2; indent-tabs-mode: nil -*- +""" +RT_Format — Reasoning Technology code formatter (commas + bracketed phrases per line) + +Commands: + RT_Format write Format files in place (rewrite originals) + RT_Format copy Save backups as ~ then format originals + RT_Format pipe Read from stdin, write to stdout + RT_Format self_test Run built-in tests + RT_Format version Show tool version + RT_Format help | --help Show usage + +Rules: + • Horizontal lists -> a ,b ,c (space BEFORE comma, none after) + • Tight (){}[] by default; add one space just inside borders only when an + OUTERMOST bracketed phrase on the line contains an INNER bracket. + • Multiple outermost phrases can exist on a line (e.g., `g() { ... }`); + apply the rule to EACH such phrase independently. + • Per-line, tolerant of unbalanced brackets: first unmatched opener OR last + unmatched closer is treated as “the” outermost for padding purposes. + • Strings and single-line comments (#, //) are not altered. +""" + +from typing import List ,Tuple ,Optional ,TextIO +import sys ,re ,io ,shutil ,os + +RTF_VERSION = "0.2.2" # pad all outermost-with-nesting phrases on a line + +BR_OPEN = "([{<" +BR_CLOSE = ")]}>" +PAIR = dict(zip(BR_OPEN ,BR_CLOSE)) +REV = dict(zip(BR_CLOSE ,BR_OPEN)) + +USAGE = """\ +Usage: + RT_Format write + RT_Format copy + RT_Format pipe + RT_Format self_test + RT_Format version + RT_Format help | --help +""" + +# --------------- Core token helpers ---------------- + +def split_code_comment(line: str): + """Return (code ,comment), keeping the comment marker if present; ignore markers inside strings.""" + in_s = None + esc = False + for i ,ch in enumerate(line): + if in_s: + if esc: + esc = False + elif ch == "\\": + esc = True + elif ch == in_s: + in_s = None + continue + else: + if ch in ("'" ,'"'): + in_s = ch + continue + if ch == "#": + return line[:i] ,line[i:] + if ch == "/" and i + 1 < len(line) and line[i + 1] == "/": + return line[:i] ,line[i:] + return line ,"" + +def format_commas(code: str) -> str: + """Space BEFORE comma, none after, outside strings.""" + out: List[str] = [] + in_s = None + esc = False + i = 0 + while i < len(code): + ch = code[i] + if in_s: + out.append(ch) + if esc: + esc = False + elif ch == "\\": + esc = True + elif ch == in_s: + in_s = None + i += 1 + else: + if ch in ("'" ,'"'): + in_s = ch + out.append(ch) + i += 1 + elif ch == ",": + while out and out[-1] == " ": + out.pop() + if out and out[-1] != " ": + out.append(" ") + out.append(",") + j = i + 1 + while j < len(code) and code[j] == " ": + j += 1 + i = j + else: + out.append(ch) + i += 1 + return "".join(out) + +# --------------- Bracket discovery ---------------- + +def top_level_spans(code: str) -> List[Tuple[int ,int]]: + """Return all balanced OUTERMOST bracketed spans (start,end) for this line, ignoring strings.""" + in_s = None + esc = False + stack: List[Tuple[str ,int]] = [] + spans: List[Tuple[int ,int]] = [] + for i ,ch in enumerate(code): + if in_s: + if esc: + esc = False + elif ch == "\\": + esc = True + elif ch == in_s: + in_s = None + continue + else: + if ch in ("'" ,'"'): + in_s = ch + continue + if ch in BR_OPEN: + stack.append((ch ,i)) + elif ch in BR_CLOSE: + if stack and REV[ch] == stack[-1][0]: + _ ,pos = stack.pop() + if not stack: + spans.append((pos ,i)) + else: + # unmatched closer ignored here; handled in unbalanced logic + pass + return spans + +def first_unmatched_opener(code: str) -> Optional[int]: + in_s = None + esc = False + stack: List[Tuple[str ,int]] = [] + for i ,ch in enumerate(code): + if in_s: + if esc: + esc = False + elif ch == "\\": + esc = True + elif ch == in_s: + in_s = None + continue + else: + if ch in ("'" ,'"'): + in_s = ch + continue + if ch in BR_OPEN: + stack.append((ch ,i)) + elif ch in BR_CLOSE: + if stack and REV[ch] == stack[-1][0]: + stack.pop() + else: + # unmatched closer: do nothing here + pass + return stack[0][1] if stack else None + +def last_unmatched_closer(code: str) -> Optional[int]: + in_s = None + esc = False + depth = 0 + last: Optional[int] = None + for i ,ch in enumerate(code): + if in_s: + if esc: + esc = False + elif ch == "\\": + esc = True + elif ch == in_s: + in_s = None + continue + else: + if ch in ("'" ,'"'): + in_s = ch + continue + if ch in BR_OPEN: + depth += 1 + elif ch in BR_CLOSE: + if depth > 0: + depth -= 1 + else: + last = i + return last + +def contains_inner_bracket(code: str ,start: Optional[int] ,end: Optional[int]) -> bool: + """Check for any bracket token inside the given bounds (respect strings).""" + if start is None and end is None: + return False + in_s = None + esc = False + lo = (start + 1) if start is not None else 0 + hi = (end - 1) if end is not None else len(code) - 1 + if hi < lo: + return False + for i ,ch in enumerate(code): + if i < lo or i > hi: + continue + if in_s: + if esc: + esc = False + elif ch == "\\": + esc = True + elif ch == in_s: + in_s = None + continue + else: + if ch in ("'" ,'"'): + in_s = ch + continue + if ch in BR_OPEN or ch in BR_CLOSE: + return True + return False + +# --------------- Spacing transforms ---------------- + +def tighten_all_brackets(code: str) -> str: + """Tight margins and remove immediate interior spaces next to borders.""" + out: List[str] = [] + in_s = None + esc = False + i = 0 + while i < len(code): + ch = code[i] + if in_s: + out.append(ch) + if esc: + esc = False + elif ch == "\\": + esc = True + elif ch == in_s: + in_s = None + i += 1 + else: + if ch in ("'" ,'"'): + in_s = ch + out.append(ch) + i += 1 + elif ch in BR_CLOSE: + if out and out[-1] == " ": + out.pop() + out.append(ch) + i += 1 + elif ch in BR_OPEN: + if out and out[-1] == " ": + out.pop() + out.append(ch) + i += 1 + while i < len(code) and code[i] == " ": + i += 1 + else: + out.append(ch) + i += 1 + return "".join(out) + +def apply_bracket_padding(code: str) -> str: + """ + 1) Tighten globally. + 2) For EACH balanced outermost span, if it contains an inner bracket, + ensure exactly one space just inside its borders — but only if missing. + 3) If there are no balanced spans, pad the first unmatched opener OR the last unmatched closer + only if that outer fragment contains an inner bracket, and only if padding is missing. + """ + s = tighten_all_brackets(code) + + def borders_have_space(text: str, start: int, end: int) -> Tuple[bool, bool]: + # Return (left_has_space, right_has_space) for just-inside borders. + left_has = (start + 1 < len(text)) and (text[start + 1] == " ") + right_has = (end - 1 >= 0) and (text[end - 1] == " ") + return left_has, right_has + + # Balanced top-level spans: may be multiple on one line (e.g., g() { ... }). + # Iterate while applying at most one mutation per pass; recompute spans after. + while True: + spans = top_level_spans(s) + changed = False + for (start, end) in spans: + if contains_inner_bracket(s, start, end): + left_has, right_has = borders_have_space(s, start, end) + if not left_has or not right_has: + # Insert exactly one space just inside each border that lacks it. + if not right_has: + # Right side first to avoid shifting the 'start' index computation + s = s[:end].rstrip(" ") + " " + s[end:].lstrip(" ") + if not left_has: + s = s[:start + 1].rstrip(" ") + " " + s[start + 1:].lstrip(" ") + changed = True + break # after a mutation, recompute spans fresh + if not changed: + break + + # If there are no balanced spans, consider unbalanced fragment once + if not top_level_spans(s): + o = first_unmatched_opener(s) + c = last_unmatched_closer(s) + if o is not None and contains_inner_bracket(s, o, None): + # add one space after opener only if missing + if not (o + 1 < len(s) and s[o + 1] == " "): + s = s[:o + 1].rstrip(" ") + " " + s[o + 1:] + elif c is not None and contains_inner_bracket(s, None, c): + # add one space before closer only if missing + if not (c - 1 >= 0 and s[c - 1] == " "): + s = s[:c].rstrip(" ") + " " + s[c:] + + return s + +# --------------- Public API ---------------- + +def rt_format_line(line: str) -> str: + code ,comment = split_code_comment(line.rstrip("\n")) + code = format_commas(code) + code = apply_bracket_padding(code) + return code + comment + +def rt_format_text(text: str) -> str: + return "\n".join(rt_format_line(ln) for ln in text.splitlines()) + +def rt_format_stream(inp: TextIO ,out: TextIO) -> None: + for line in inp: + out.write(rt_format_line(line) + "\n") + +# --------------- Self-test ---------------- + +def run_self_test() -> bool: + ok = True + def chk(src ,exp): + nonlocal ok + got = rt_format_line(src) + if got != exp: + print("FAIL:" ,src ,"=>" ,got ,"expected:" ,exp) + ok = False + + # Commas + chk("a,b,c" ,"a ,b ,c") + chk("a , b , c" ,"a ,b ,c") + + # Tight () by default + chk("f ( x )" ,"f(x)") + chk("f(x) + g(y)" ,"f(x) + g(y)") + + # Balanced: multiple outermost spans (g() and {...}) -> only pad {...} if it has inner bracket + src = "int g(){int a=0,b=1,c=2; return h(a,b,c);}" + exp = "int g(){ int a=0 ,b=1 ,c=2; return h(a ,b ,c); }" + chk(src ,exp) + + # Balanced: single outermost with nesting + chk("outer( inner(a,b) )" ,"outer( inner(a ,b) )") + + # Unbalanced open-right with nesting + chk("compute(x, f(y" ,"compute( x ,f(y)") + + # Unbalanced open-left without prior inner bracket => unchanged + chk("return z) + 1" ,"return z) + 1") + + print("SELFTEST OK" if ok else "SELFTEST FAILED") + return ok + +# --------------- CLI ---------------- + +def write_files(paths: List[str]) -> int: + for path in paths: + with open(path ,"r" ,encoding="utf-8") as f: + data = f.read() + formatted = rt_format_text(data) + with open(path ,"w" ,encoding="utf-8") as f: + f.write(formatted + ("\n" if not formatted.endswith("\n") else "")) + return 0 + +def copy_files(paths: List[str]) -> int: + for path in paths: + shutil.copy2(path ,path + "~") + return write_files(paths) + +def CLI(argv=None) -> int: + args = list(sys.argv[1:] if argv is None else argv) + if not args or args[0] in {"help" ,"--help" ,"-h"}: + print(USAGE) + return 0 + + cmd = args[0] + rest = args[1:] + + if cmd == "version": + print(RTF_VERSION) + return 0 + if cmd == "self_test": + ok = run_self_test() + return 0 if ok else 1 + if cmd == "pipe": + rt_format_stream(sys.stdin ,sys.stdout) + return 0 + if cmd == "write": + if not rest: + print("write: missing \n" + USAGE) + return 2 + return write_files(rest) + if cmd == "copy": + if not rest: + print("copy: missing \n" + USAGE) + return 2 + return copy_files(rest) + + print(f"Unknown command: {cmd}\n" + USAGE) + return 2 + +if __name__ == "__main__": + sys.exit(CLI()) diff --git a/tester/RT_Format/RT_Format.el b/tester/RT_Format/RT_Format.el new file mode 100644 index 0000000..a9f6a2d --- /dev/null +++ b/tester/RT_Format/RT_Format.el @@ -0,0 +1,4 @@ +(defun rt-format-buffer () + (interactive) + (shell-command-on-region (point-min) (point-max) + "RT_Format pipe" t t)) diff --git a/tester/RT_Format/test_0_data.c b/tester/RT_Format/test_0_data.c new file mode 100644 index 0000000..7b1e06d --- /dev/null +++ b/tester/RT_Format/test_0_data.c @@ -0,0 +1,15 @@ +// commas and simple tight brackets +int g(){int a=0,b=1,c=2; return h(a,b,c);} + +// balanced outermost-with-nesting -> pad inside outer () +int f(){return outer( inner(a,b) );} + +// strings and comments must be unchanged +int s(){ printf("x ,y ,z (still a string)"); /* a ,b ,c */ return 1; } + +// unbalanced open-right with nesting -> pad after first unmatched '(' +int u(){ if(doit(foo(1,2) // missing )) + return 0; } + +// arrays / subscripts stay tight; commas still RT-style +int a(int i,int j){ return M[i,j] + V[i] + W[j]; } diff --git a/tester/RT_Format/test_1_data.py b/tester/RT_Format/test_1_data.py new file mode 100644 index 0000000..9b2fa87 --- /dev/null +++ b/tester/RT_Format/test_1_data.py @@ -0,0 +1,16 @@ +# commas and spacing in defs / calls +def f ( x , y , z ): + return dict( a =1 , b= 2 ), [ 1, 2 ,3 ], ( (1,2) ) + +# outermost-with-nesting -> pad inside outer () +val = outer( inner( a,b ) ) + +# strings/comments untouched +s = "text, with , commas ( not to touch )" # a ,b ,c + +# unbalanced: open-left (closing without opener) -> no padding unless inner bracket before it +def g(): + return result) # likely unchanged + +# unbalanced: open-right (first unmatched opener) with inner bracket following +k = compute(x, f(y diff --git a/tester/authored/test_routine.sh b/tester/authored/test_routine.sh new file mode 100644 index 0000000..f22c3ba --- /dev/null +++ b/tester/authored/test_routine.sh @@ -0,0 +1,28 @@ +#!/usr/bin/env bash +set -euo pipefail + +# test_routing.sh +# Sends mock HTTP requests to the local unix socket to verify domain routing. + +SOCKET_FP="../user/release/scratchpad/network_interface/RT_server.sock" + +if [ ! -S "${SOCKET_FP}" ]; then + echo "Error: Socket not found at ${SOCKET_FP}" >&2 + echo "Make sure the HTTP_server.js process is running in the user workspace." >&2 + exit 1 +fi + +echo "=== Testing Reasoning Technology domain ===" +curl --unix-socket "${SOCKET_FP}" \ + -H "Host: x6.reasoningtechnology.com" \ + http://localhost/ + +echo -e "\n\n=== Testing Thomas Walker Lynch domain ===" +curl --unix-socket "${SOCKET_FP}" \ + -H "Host: x6.thomas-walker-lynch.com" \ + http://localhost/ + +echo -e "\n\n=== Testing Unknown domain ===" +curl --unix-socket "${SOCKET_FP}" \ + -H "Host: nonexistent-domain.com" \ + http://localhost/ diff --git a/tester/tool/setup b/tester/tool/setup new file mode 100644 index 0000000..0b993ad --- /dev/null +++ b/tester/tool/setup @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +script_afp=$(realpath "${BASH_SOURCE[0]}") + diff --git a/user/scratchpad/.gitignore b/user/scratchpad/.gitignore new file mode 100644 index 0000000..120f485 --- /dev/null +++ b/user/scratchpad/.gitignore @@ -0,0 +1,2 @@ +* +!/.gitignore diff --git a/user/tool/env b/user/tool/env new file mode 100644 index 0000000..d771749 --- /dev/null +++ b/user/tool/env @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +script_afp=$(realpath "${BASH_SOURCE[0]}") + +# -------------------------------------------------------------------------------- +# Network Interfaces +# + export RT_SERVER_SOCKET_FP="scratchpad/network_interface/RT_server.sock" -- 2.20.1